【问题标题】:AWS Boto3: The security token included in the request is invalidAWS Boto3:请求中包含的安全令牌无效
【发布时间】:2018-04-09 23:24:49
【问题描述】:

阅读此问题How to SSH and run commands in EC2 using boto3? 后,我尝试使用SSM 在EC2 实例上自动运行命令。但是,当我编写这样的代码时

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 .

在我使用SSTclient 生成凭据后,我得到了如下代码。

    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.

谁能告诉我如何解决这个问题?

【问题讨论】:

    标签: amazon-web-services amazon-ec2 ssh boto3


    【解决方案1】:

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

    您还尝试使用 STS 获取访问权限,这使您需要做的事情过于复杂。 STS 需要承担的策略需要相同的权限。使用 STS(最小权限规则)有很多好的案例,但我认为您在这里不需要 STS。

    Amazon 为 SSM 提供预定义策略,您可以快速将其添加到策略或角色中,例如:

    AmazonEC2RoleForSSM
    AmazonSSMFullAccess
    AmazonSSMReadOnlyAccess
    

    此链接将帮助您配置对 Systems Manager 的访问:

    Configuring Access to Systems Manager

    【讨论】:

    • 感谢您的详细解答!问题解决了!
    猜你喜欢
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-24
    • 2021-09-07
    • 1970-01-01
    • 2016-12-12
    相关资源
    最近更新 更多