Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@edthrn
Last active June 23, 2019 16:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edthrn/1d9d62412ebc35948952a81cf70cad7e to your computer and use it in GitHub Desktop.
Save edthrn/1d9d62412ebc35948952a81cf70cad7e to your computer and use it in GitHub Desktop.
Execute shell commands in EC2 with SSM
"""
https://aws.amazon.com/blogs/aws/manage-instances-at-scale-without-ssh-access-using-ec2-run-command/
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ssm.html
https://stackoverflow.com/questions/34028219/how-to-execute-commands-on-aws-instance-using-boto3
"""
import boto3
# Need AWS credentials in ~/.aws...
ssm = boto3.client('ssm')
response = ssm.send_command(
DocumentName='AWS-RunShellScript',
Parameters={
'commands': ['ls -al']
},
InstanceIds=['i-XXXXXXXXXXXXXXX']
)
output = ssm.get_command_invocation(
CommandId=response['Command']['CommandId'],
InstanceId='i-XXXXXXXXXXXXXXX'
)
stdout = output['StandardOutputContent']
lines = stdout.split('\n')
for line in lines:
print(line)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment