看完這個問題後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.
任何人能告訴我怎麼解決這個問題?
謝謝爲您的詳細答案!問題解決了! –