Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@edthrn
Last active January 26, 2023 18:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edthrn/6f3139cd9bf3c678fb4a7467d2d019f2 to your computer and use it in GitHub Desktop.
Save edthrn/6f3139cd9bf3c678fb4a7467d2d019f2 to your computer and use it in GitHub Desktop.
Execute Shell command on EC2 Linux instance with Python and Boto3
# Following https://stackoverflow.com/questions/34028219/how-to-execute-commands-on-aws-instance-using-boto3
import boto3
ssm = boto3.client('ssm')
response = ssm.send_command(
InstanceIds=['i-abcde12345...'],
DocumentName='AWS-RunShellScript',
Parameters={'commands': ['echo "This command ran on $(date)"']
)
command_id = response['Command']['CommandId]
feedback = ssm.get_command_invocation(CommandId=command_id, InstanceId='i-abcde12345...')
print(feedback['StandardOutputContent'])
@tejeshreddy
Copy link

Encountered the following error while using this.

[ERROR] ParamValidationError: Parameter validation failed:
Invalid type for parameter InstanceIds, value: i-014...., type: <class 'str'>, valid types: <class 'list'>, <class 'tuple'>

@rogerdenisvieira
Copy link

rogerdenisvieira commented Jan 26, 2023

Encountered the following error while using this.

[ERROR] ParamValidationError: Parameter validation failed:
Invalid type for parameter InstanceIds, value: i-014...., type: <class 'str'>, valid types: <class 'list'>, <class 'tuple'>

The commands parameter must be an array of commands, otherwise you'll receive such error. E.g:

import boto3
commands = [' echo "hello world"']
ssm_client = boto3.client('ssm')

output = ssm_client.send_command(
InstanceIds=["i-your_instance_id"]],
DocumentName='AWS-RunShellScript',
Parameters={
    'commands': commands
    }
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment