start_workspaces() 只接受关键字参数

问题描述

我正在尝试在 Lambda 函数中编写 Python 代码,该代码将在警报触发时启动已停止的工作区。响应类型为 dict。

但我收到错误消息。以下是我的代码错误

import json
import boto3

client = boto3.client('workspaces')
    
def lambda_handler(event,context):
    response = client.describe_workspaces(
        DirectoryId='d-966714f114'
    )
        
    #print(response)
    
    print("hello")

    for i in response['Workspaces']:
        if(i['State']== 'STOPPED'):
            print(i['WorkspaceId'])
            client.start_workspaces(i['WorkspaceId'])
{
    "errorMessage": "start_workspaces() only accepts keyword arguments.","errorType": "TypeError","stackTrace": [
    "  File \"/var/task/lambda_function.py\",line 21,in lambda_handler\n    client.start_workspaces(i)\n","  File \"/var/runtime/botocore/client.py\",line 354,in _api_call\n    raise TypeError(\n"
    ]
}

解决方法

如果您查看调用的 here,它说它需要关键字 StartWorkspaceRequests,它本身就是一个字典列表:

{
    'WorkspaceId': 'string'
},

调用不接受参数(只是传递一个没有相应关键字的值)。您需要调整您的调用以符合 boto3 预期的格式。

import json
import boto3

client = boto3.client('workspaces')
    
def lambda_handler(event,context):
    response = client.describe_workspaces(
        DirectoryId='d-966714f114'
    )
        
    workspaces_to_start = []
         
    for i in response['Workspaces']:
        if(i['State']== 'STOPPED'):
            workspaces_to_start.append({'WorkspaceId': i['WorkspaceId']})

    if workspaces_to_start:
        client.start_workspaces(StartWorkspaceRequests=workspaces_to_start)