16

After reading this question How to SSH and run commands in EC2 using boto3? I try to use SSM to automatically run the command on EC2 instance. However, when I write code like this

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)

It reminds me that

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 .

After I use SST to generate credentials for client and I got the code as below.

    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)

However, this time it reminds me that

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

Can anybody tell me how to solve this problem?

Coding_Rabbit
  • 1,287
  • 3
  • 22
  • 44

1 Answers1

7

You are missing permissions for the IAM user or the Role to access SSM.

You are also trying to use STS to get access which is over complicating what you need to do. The policy that STS needs to assume needs the same permissions. There are many good cases for using STS (the rule of least privilege), but I don't think you need STS here.

Amazon provides predefined policies for SSM that you can quickly add to a policy or role such as:

AmazonEC2RoleForSSM
AmazonSSMFullAccess
AmazonSSMReadOnlyAccess

This link will help you configure access to Systems Manager:

Configuring Access to Systems Manager

John Hanley
  • 74,467
  • 6
  • 95
  • 159