Home > Blockchain >  lambda function to start aws workspaces - overcome client.start_workspaces limitation
lambda function to start aws workspaces - overcome client.start_workspaces limitation

Time:12-05

i have a lambda function to start all the workspaces machines in my env

Lambda Function :

import boto3
client = boto3.client('workspaces')

def lambda_handler(event,context):
     workspaces = client.describe_workspaces()['Workspaces']
     for workspace in workspaces:
          if workspace['WorkspaceProperties']['RunningMode'] == 'AUTO_STOP':
               if workspace['State'] == 'STOPPED':
                   workspaces_id = (workspace['WorkspaceId'])
                   client.start_workspaces(
                       StartWorkspaceRequests=[
                           {
                               'WorkspaceId': workspaces_id
                           },
                        ]
                     )

The client.start_workspaces has a limitation of 25 workspaces per request , any idea how to overcome this ? im trying to build a robust solution for more then 25 workspaces .

https://docs.aws.amazon.com/workspaces/latest/api/API_StartWorkspaces.html#API_StartWorkspaces_RequestSyntax

Thanks in advance to the helpers

CodePudding user response:

You can use the paginate method to automatically paginate through the list of workspaces and call start_workspaces for each page of results. This would look something like this:

import boto3
client = boto3.client('workspaces')

def lambda_handler(event, context):
     workspaces_paginator = client.get_paginator('describe_workspaces')

     # Loop through all pages of workspaces
     for page in workspaces_paginator.paginate():
         workspaces = page['Workspaces']

         # Filter for workspaces that are in AUTO_STOP mode and are currently stopped
         stopped_workspaces = [workspace for workspace in workspaces if workspace['WorkspaceProperties']['RunningMode'] == 'AUTO_STOP' and workspace['State'] == 'STOPPED']

         # Call start_workspaces for the current page of workspaces
         if stopped_workspaces:
             client.start_workspaces(
                 StartWorkspaceRequests=[
                     {
                         'WorkspaceId': workspace['WorkspaceId']
                     } for workspace in stopped_workspaces
                 ]
             )
  • Related