AWS Builder Center

Automating Nested Virtualization enablement for Amazon Workspaces at Scale with AWS Lambda and Amazon S3

In the previous post we enabled nested virtualization on Amazon WorkSpaces using the Console, CLI, and PowerShell. Those work well for a handful of WorkSpaces but what if you need to enable multiple WorkSpaces, repeatably and auditable?

Solutions Architect - End User Computing
This post builds an event-driven automation: an administrator uploads a text file of WorkSpace IDs to an Amazon S3 bucket, and an AWS Lambda function automatically enables nested virtualization on every WorkSpace in the file — with validation, idempotency, rate limiting, and structured logging.
The best part: the entire Lambda is a single Python file with no external dependencies. You can paste it straight into the Lambda console.



Architecture Overview

Flow:
  1. Admin uploads  input/workspace_ids.txt  (one WorkSpace ID per line) to S3.
  1. S3  ObjectCreated  event triggers the Lambda.
  1. Lambda reads the file, validates each WorkSpace, and calls  ModifyWorkspaceProperties  to enable nested virtualization.
  1. Per-WorkSpace outcomes are written to CloudWatch Logs.



Prerequisites

  • An AWS account with Amazon WorkSpaces launched.
  • Permissions to deploy Lambda, IAM, and S3 (CloudFormation optional).
  • AWS CLI v2, configured for your target account and Region or CloudShell
  • A list of eligible WorkSpace IDs (Power+ bundle, supported OS see the limitations section in Post 1).



Step 1: The Lambda Function

The whole solution is one file  lambda_function.py  with a handler named  lambda_handler . It relies only on  boto3 , which the Lambda Python runtime already provides, so there are no dependencies to package.
It handles two trigger types (direct invocation and S3 upload) and, for each WorkSpace, it:
  • Validates the WorkSpace state (must be AVAILABLE or STOPPED) and bundle tier
  • Checks idempotency — skips WorkSpaces already in the desired state
  • Surfaces limitation warnings — including the AutoStop hibernation
  • Applies the change with exponential-backoff retry on throttling
  • Logs a per-WorkSpace outcome plus a summary with an exit code
Here is the complete  lambda_function.py :
"""Single-file AWS Lambda for enabling/disabling WorkSpaces nested virtualization.

This is a self-contained handler with NO external dependencies beyond boto3,
which the AWS Lambda Python runtime already provides. Deploy it by pasting the
contents directly into the Lambda console (or a 1-file zip) — no build step,
no packaged libraries.

Handler: lambda_function.lambda_handler

Supported event formats
-----------------------
1. Direct invocation:
{"action": "enable", "workspace_ids": ["ws-abc12345"]}
2. S3 trigger: an ObjectCreated event for a .txt file under input/ whose
contents are workspace IDs (one per line).

Exit-code semantics in the response body:
0 = all succeeded, 1 = partial failure, 2 = complete failure.
"""

from __future__ import annotations

import json
import logging
import os
import time
from typing import Any

import boto3 # provided by the Lambda runtime
from botocore.exceptions import ClientError

logger = logging.getLogger()
logger.setLevel(os.environ.get("LOG_LEVEL", "INFO"))

# --------------------------------------------------------------------------
# Configuration (via environment variables)
# --------------------------------------------------------------------------
REGION = os.environ.get("DEFAULT_REGION", "us-east-1")
DEFAULT_ACTION = os.environ.get("DEFAULT_ACTION", "enable")
MAX_BATCH_SIZE = int(os.environ.get("MAX_BATCH_SIZE", "5000"))
MAX_RETRIES = int(os.environ.get("MAX_RETRIES", "5"))
BASE_DELAY = float(os.environ.get("BASE_DELAY_SECONDS", "1.0"))

# --------------------------------------------------------------------------
# Eligibility rules
# --------------------------------------------------------------------------
HIGH_TIER_COMPUTE_TYPES = {
"POWER", "POWERPRO", "GRAPHICS", "GRAPHICSPRO", "GRAPHICS_G4DN",
"GRAPHICSPRO_G4DN", "GENERALPURPOSE_4XLARGE", "GENERALPURPOSE_8XLARGE",
}
ELIGIBLE_STATES = {"AVAILABLE", "STOPPED"}

HIGH_TIER_WARNING = (
"High-tier bundle: enabling nested virtualization may cause up to 30% "
"performance degradation. A restart is required."
)
LOW_TIER_WARNING = (
"Low-tier bundle: nested virtualization is recommended on 4 vCPU or higher "
"(Power and above). You can still enable it on this bundle."
)
AUTO_STOP_WARNING = (
"AutoStop running mode: on Windows Server 2025 or Windows 11 24H2/25H2, an "
"AutoStop WorkSpace with nested virtualization performs a full reboot "
"instead of hibernating on timeout, causing longer resume times and loss of "
"unsaved work. Use AlwaysOn for fast resume and session persistence."
)

# --------------------------------------------------------------------------
# Handler
# --------------------------------------------------------------------------
def lambda_handler(event: dict[str, Any], context: Any) -> dict[str, Any]:
logger.info("Event received: %s", json.dumps(event, default=str))

action = event.get("action", DEFAULT_ACTION)
workspaces_client = boto3.client("workspaces", region_name=REGION)

# --- Resolve the list of workspace IDs from the event source ---
if "workspace_ids" in event:
workspace_ids = event["workspace_ids"]
elif "Records" in event and event["Records"][0].get("eventSource") == "aws:s3":
workspace_ids = _read_ids_from_s3_event(event)
else:
return {"statusCode": 400, "body": "No workspace_ids provided."}

workspace_ids = [w.strip() for w in workspace_ids if w and w.strip()]
logger.info("Processing %d workspace IDs: %s", len(workspace_ids), workspace_ids)

if not workspace_ids:
return {"statusCode": 400, "body": "Empty workspace_ids list."}
if len(workspace_ids) > MAX_BATCH_SIZE:
return {
"statusCode": 400,
"body": f"Too many workspace IDs ({len(workspace_ids)}); "
f"max is {MAX_BATCH_SIZE}.",
}

if action not in ("enable", "disable", "status"):
return {"statusCode": 400, "body": f"Invalid action: '{action}'."}

# --- Look up all workspaces (batched by 25, the API max) ---
info_by_id = _describe_workspaces(workspaces_client, workspace_ids)

successful = failed = skipped = 0
results: list[dict[str, Any]] = []

for ws_id in workspace_ids:
outcome = _process_one(workspaces_client, ws_id, info_by_id.get(ws_id), action)
results.append(outcome)
if outcome["status"] == "success":
successful += 1
elif outcome["status"] == "skipped":
skipped += 1
else:
failed += 1

if outcome["status"] == "failed":
logger.error("FAILED workspace_id=%s error=%s",
ws_id, outcome.get("error"))
else:
for w in outcome.get("warnings", []):
logger.info("WARN workspace_id=%s: %s", ws_id, w)
logger.info("workspace_id=%s action=%s status=%s",
ws_id, action, outcome["status"])

exit_code = 0 if failed == 0 else (1 if successful > 0 else 2)
logger.info(
"Operation complete: action=%s total=%d successful=%d failed=%d "
"skipped=%d exit_code=%d",
action, len(workspace_ids), successful, failed, skipped, exit_code,
)

return {
"statusCode": 200 if exit_code == 0 else 207,
"body": {
"action": action,
"total": len(workspace_ids),
"successful": successful,
"failed": failed,
"skipped": skipped,
"exit_code": exit_code,
"results": results,
},
}

# --------------------------------------------------------------------------
# Core per-workspace logic
# --------------------------------------------------------------------------
def _process_one(client, ws_id, info, action) -> dict[str, Any]:
"""Validate, check idempotency, and apply the change for one workspace."""
if info is None:
return {"workspace_id": ws_id, "status": "failed",
"error": f"WorkSpace '{ws_id}' not found."}

state = info["state"]
compute_type = info["compute_type"]
running_mode = info["running_mode"]
currently_enabled = info["nested_virt_enabled"]

# Status action just reports current state.
if action == "status":
return {"workspace_id": ws_id, "status": "success",
"nested_virt_enabled": currently_enabled, "state": state}

# State eligibility.
if state not in ELIGIBLE_STATES:
return {"workspace_id": ws_id, "status": "failed",
"error": f"State '{state}' not eligible (must be AVAILABLE or STOPPED)."}

target = action == "enable"

# Idempotency: skip if already in the desired state.
if currently_enabled == target:
return {"workspace_id": ws_id, "status": "skipped",
"nested_virt_enabled": currently_enabled}

# Build warnings (tier + AutoStop).
warnings: list[str] = []
if target:
warnings.append(
HIGH_TIER_WARNING if compute_type.upper() in HIGH_TIER_COMPUTE_TYPES
else LOW_TIER_WARNING
)
if running_mode.upper() == "AUTO_STOP":
warnings.append(AUTO_STOP_WARNING)

# Apply the change with retry/backoff on throttling.
try:
_modify_with_retry(client, ws_id, target)
except ClientError as exc:
err = exc.response.get("Error", {})
return {"workspace_id": ws_id, "status": "failed",
"error": f"{err.get('Code')}: {err.get('Message')}",
"warnings": warnings}

return {"workspace_id": ws_id, "status": "success",
"nested_virt_enabled": target, "warnings": warnings,
"restart_required": target}

def _modify_with_retry(client, ws_id, enabled: bool) -> None:
"""Call ModifyWorkspaceProperties with exponential backoff on throttling."""
attempt = 0
while True:
try:
client.modify_workspace_properties(
WorkspaceId=ws_id,
WorkspaceProperties={"NestedVirtualizationEnabled": enabled},
)
return
except ClientError as exc:
code = exc.response.get("Error", {}).get("Code", "")
if code in ("ThrottlingException", "TooManyRequestsException") and attempt < MAX_RETRIES:
delay = BASE_DELAY * (2 ** attempt)
logger.warning("Throttled on %s; retrying in %.1fs", ws_id, delay)
time.sleep(delay)
attempt += 1
continue
raise

# --------------------------------------------------------------------------
# AWS helpers
# --------------------------------------------------------------------------
def _describe_workspaces(client, workspace_ids) -> dict[str, dict[str, Any]]:
"""Describe workspaces in batches of 25; return a dict keyed by workspace ID."""
info: dict[str, dict[str, Any]] = {}
for i in range(0, len(workspace_ids), 25):
batch = workspace_ids[i:i + 25]
token = None
while True:
kwargs = {"WorkspaceIds": batch}
if token:
kwargs["NextToken"] = token
resp = client.describe_workspaces(**kwargs)
for ws in resp.get("Workspaces", []):
props = ws.get("WorkspaceProperties", {})
info[ws.get("WorkspaceId", "")] = {
"state": ws.get("State", "UNKNOWN"),
"compute_type": props.get("ComputeTypeName", "UNKNOWN"),
"running_mode": props.get("RunningMode", ""),
"nested_virt_enabled": bool(
props.get("NestedVirtualizationEnabled", False)
),
}
token = resp.get("NextToken")
if not token:
break
return info

def _read_ids_from_s3_event(event) -> list[str]:
"""Read newline-separated workspace IDs from the S3 object in the event."""
record = event["Records"][0]
bucket = record["s3"]["bucket"]["name"]
key = record["s3"]["object"]["key"]
s3 = boto3.client("s3", region_name=REGION)
body = s3.get_object(Bucket=bucket, Key=key)["Body"].read().decode("utf-8")
return [line.strip() for line in body.splitlines() if line.strip()]



Step 2: Create and Deploy the Function

Because it's a single dependency-free file, you have two easy paths.

Option A — Paste into the Lambda Console (Fastest)

  1. Open the Lambda console → Create function → Author from scratch.
  1. Name it  workspace-nested-virt-automation , runtime Python 3.12.
  1. For execution role, choose the role from  Step 3  (or create the function first and attach it after).
  1. In the Code tab, replace the contents of  lambda_function.py  with the code above and choose Deploy.
  1. Confirm the handler is set to  lambda_function.lambda_handler  under Runtime settings.

Option B — Deploy from a One-File Zip (For CLI/IaC Workflows)

# A single-file zip — a few KB, not 17 MB
zip lambda.zip lambda_function.py

aws lambda update-function-code \
--function-name workspace-nested-virt-automation \
--zip-file fileb://lambda.zip \
--region us-east-1
Why no big package? AWS Lambda's Python runtime already includes  boto3  and  botocore . Since this function imports nothing else, there's nothing to bundle keeping the deployment tiny and reviewable.



Step 3: Create the IAM Role

The function needs permission to describe/modify WorkSpaces, write logs, and read the input file from S3.

Using CloudFormation

# iam-role.yaml (excerpt)
Resources:
AutomationRole:
Type: AWS::IAM::Role
Properties:
RoleName: WorkspaceNestedVirtAutomationRole
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: [lambda.amazonaws.com]
Action: sts:AssumeRole

WorkspacesPolicy:
Type: AWS::IAM::ManagedPolicy
Properties:
Roles: [!Ref AutomationRole]
PolicyDocument:
Version: '2012-10-17'
Statement:
- Sid: WorkspacesAccess
Effect: Allow
Action:
- workspaces:DescribeWorkspaces
- workspaces:ModifyWorkspaceProperties
Resource: '*'
- Sid: ReadInputFiles
Effect: Allow
Action: ['s3:GetObject']
Resource: 'arn:aws:s3:::YOUR-BUCKET/input/*'
- Sid: Logs
Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource: 'arn:aws:logs:*:*:log-group:/aws/lambda/workspace-nested-virt*'
aws cloudformation deploy \
--template-file cloudformation/iam-role.yaml \
--stack-name workspace-nested-virt-iam \
--capabilities CAPABILITY_NAMED_IAM \
--region us-east-1
The role bundles three permission sets: WorkSpaces (describe + modify), S3 (read the uploaded input file), and CloudWatch Logs. Attach this role to the function from Step 2.



Step 4: Configure Environment Variables

The function reads its configuration from environment variables — all optional with sensible defaults.
Variable
Default
Purpose
DEFAULT_REGION
us-east-1
Region for WorkSpaces API calls
DEFAULT_ACTION
enable
Action when none is supplied (enable/disable/status)
MAX_BATCH_SIZE
5000
Reject input files larger than this
MAX_RETRIES
5
Throttling retry attempts
BASE_DELAY_SECONDS
1.0
Base backoff delay
LOG_LEVEL
INFO
Log verbosity
Set the timeout to 900 seconds and memory to 256 MB for large batches.
aws lambda update-function-configuration \
--function-name workspace-nested-virt-automation \
--timeout 900 --memory-size 256 \
--environment "Variables={DEFAULT_REGION=us-east-1,DEFAULT_ACTION=enable,LOG_LEVEL=INFO}" \
--region us-east-1



Step 5: Configure the S3 Trigger

The input bucket fires the Lambda whenever a  .txt  file lands under the  input/  prefix.

Grant S3 Permission to Invoke the Lambda

aws lambda add-permission \
--function-name workspace-nested-virt-automation \
--statement-id S3TriggerPermission \
--action lambda:InvokeFunction \
--principal s3.amazonaws.com \
--source-arn arn:aws:s3:::YOUR-BUCKET \
--source-account YOUR-ACCOUNT-ID \
--region us-east-1

Add the Event Notification

{
"LambdaFunctionConfigurations": [
{
"Id": "TriggerNestedVirtLambda",
"LambdaFunctionArn": "arn:aws:lambda:us-east-1:ACCOUNT:function:workspace-nested-virt-automation",
"Events": ["s3:ObjectCreated:*"],
"Filter": {
"Key": {
"FilterRules": [
{ "Name": "prefix", "Value": "input/" },
{ "Name": "suffix", "Value": ".txt" }
]
}
}
}
]
}
aws s3api put-bucket-notification-configuration \
--bucket YOUR-BUCKET \
--notification-configuration file://notification.json \
--region us-east-1
Ordering matters. Add the Lambda invoke permission first. If you configure the notification before the permission exists, S3 returns  Unable to validate the following destination configurations .



Step 6: Test the End-to-End Flow

Create an input file and upload it:
echo "ws-xxxxxxxxx" > workspace_ids.txt

aws s3 cp workspace_ids.txt s3://YOUR-BUCKET/input/workspace_ids.txt --sse AES256
Watch the logs:
aws logs tail /aws/lambda/workspace-nested-virt-automation --follow --region us-east-1
A successful run looks like:
[INFO] Processing 1 workspace IDs: ['ws-xxxxxxxxx']
[INFO] workspace_id=ws-xxxxxxxxx action=enable status=success
[INFO] Operation complete: action=enable total=1 successful=1 failed=0 skipped=0 exit_code=0
Exit codes in the response body make results easy to consume in pipelines:
  •  0  — all succeeded
  •  1  — partial failure (some succeeded, some failed)
  •  2  — complete failure
You can also invoke it directly without S3, which is handy for a quick check:
aws lambda invoke \
--function-name workspace-nested-virt-automation \
--cli-binary-format raw-in-base64-out \
--payload '{"action":"status","workspace_ids":["ws-xxxxxxxxx"]}' \
--region us-east-1 /dev/stdout



Operational Considerations

  • Rate limiting — Throttled API calls are retried with exponential backoff ( MAX_RETRIES ,  BASE_DELAY_SECONDS ), so large batches don't trip WorkSpaces API limits.
  • Idempotency — WorkSpaces already in the desired state are reported as skipped with no redundant API call.
  • Fault isolation — A failure on one WorkSpace never stops processing of the rest; every outcome is captured in the summary.
  • Auditing — Every operation logs the WorkSpace ID, action, and result. Add an  input/  lifecycle policy on the bucket to retain an audit trail.
  • Batch size — Input larger than  MAX_BATCH_SIZE  is rejected; split very large populations across multiple uploads.
  • Eligibility & limitations — The function warns on AutoStop WorkSpaces and low-tier bundles. Review the full limitations list in Post 1 before rolling out fleet-wide.



Clean Up

# If deployed via CloudFormation
aws cloudformation delete-stack --stack-name workspace-nested-virt-iam --region us-east-1

# Delete the function and (optionally) the bucket
aws lambda delete-function --function-name workspace-nested-virt-automation --region us-east-1



Summary

With an S3-triggered Lambda you can enable nested virtualization across your entire WorkSpaces fleet by simply uploading a text file — no manual console clicks, no ad-hoc scripts, and no heavyweight deployment package. The function is a single dependency-free file that validates eligibility, respects API rate limits, is idempotent, and produces an auditable log of every change.
  •  Post 1  covered the manual methods (Console, CLI, PowerShell).
  • This post automated the process at scale with a single-file Lambda + S3.
Pair this with the AutoStop/OS limitation checks from Post 1, and you have a production-ready, safe, and repeatable way to roll out nested virtualization to your developer WorkSpaces.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article