2017-10-28 124 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

謝謝爲您的詳細答案!問題解決了! –

相關問題