2017-10-28 309 views
1

看完这个问题后How to SSH and run commands in EC2 using boto3? 我尝试使用SSM自动在EC2实例上运行该命令。然而,当我这样写代码AWS Boto3:请求中包含的安全令牌无效

def excute_command_on_instance(client, command, instance_id): 
    response = client.send_command(
     DocumentName="AWS-RunShellScript", # One of AWS' preconfigured documents 
     Parameters={'commands': command}, 
     InstanceIds=instance_id, 
    ) 
    return response 

# Using SSM in boto3 to send command to EC2 instances. 
ssm_client = boto3.client('ssm') 
commands = ['echo "hello world'] 
instance_id = running_instance[0:1] 
excute_command_on_instance(ssm_client, commands, instance_id) 

这让我想起

botocore.exceptions.ClientError: An error occurred (AccessDeniedException) when calling the SendCommand operation: User: arn:aws:iam::62771xxxx946:user/Python_CloudComputing is not authorized to perform: ssm:SendCommand on resource: arn:aws:ec2:eu-west-2:6277xxxx3946:instance/i-074f862c3xxxxfc07

当我使用SST来生成client的凭证后,我得到如下代码。

def excute_command_on_instance(client, command, instance_id): 
     response = client.send_command(
      DocumentName="AWS-RunShellScript", # One of AWS' preconfigured documents 
      Parameters={'commands': command}, 
      InstanceIds=instance_id, 
     ) 
     return response 

    # Using SSM in boto3 to send command to EC2 instances. 
    sts = boto3.client('sts') 
    sts_response = sts.get_session_token() 
    ACCESS_KEY = sts_response['Credentials']['AccessKeyId'] 
    SECRET_KEY = sts_response['Credentials']['SecretAccessKey'] 
    ssm_client = boto3.client(
     'ssm', 
     aws_access_key_id=ACCESS_KEY, 
     aws_secret_access_key=SECRET_KEY, 
    ) 
    commands = ['echo "hello world'] 
    instance_id = running_instance[0:1] 
    excute_command_on_instance(ssm_client, commands, instance_id) 

然而,这一次,它提醒我,

botocore.exceptions.ClientError: An error occurred (UnrecognizedClientException) when calling the SendCommand operation: The security token included in the request is invalid.

任何人能告诉我怎么解决这个问题?

回答

1

您缺少IAM用户或角色访问SSM的权限。

您也在尝试使用STS来获取访问权限,从而使您的操作复杂化。 STS需要承担的策略需要相同的权限。使用STS(最小特权规则)有很多好的例子,但我不认为你需要STS。

亚马逊提供SSM预定义的策略,你可以快速添加到一个政策或角色,例如:

AmazonEC2RoleForSSM 
AmazonSSMFullAccess 
AmazonSSMReadOnlyAccess 

此链接将帮助您配置对系统的访问管理器:

Configuring Access to Systems Manager

+0

谢谢为您的详细答案!问题解决了! –

相关问题