run_command_on_one_ec2#
This module allow you to run a Python script on EC2 via SSM run command.
- aws_ssm_run_command.patterns.run_command_on_one_ec2.parse_last_line_json_in_output(output: str) Union[dict, list, Any][source]#
Parse the last line of the Command invocation output as JSON.
Example:
>>> output = ( ... '{"id": 1}\n' ... '{"id": 2}\n' ... '{"id": 3}\n' ... ) >>> parse_last_line_json_in_output(output) {'id': 3}
- aws_ssm_run_command.patterns.run_command_on_one_ec2.run_python_script(ssm_client: SSMClient, s3_client: S3Client, instance_id: str, path_aws: str, path_python: str, code: str, s3uri: str, args: Optional[List[str]] = None, gap: int = 1, raises: bool = True, delays: int = 3, timeout: int = 60, verbose: bool = True) CommandInvocation[source]#
Run a Python script on EC2 via SSM run command. It will upload your Python script to S3, then download it to EC2, and finally run it. You can let the Python script to print data to stdout, and this function will capture the return code and stdout in the
CommandInvocationobject. Note that the return output data cannot exceed 24000 characters.Prerequisites:
your EC2 has aws cli installed, and it has S3 read permission.
- your EC2 has python installed, and it has the necessary packages to run
your Python script.
- Parameters:
ssm_client – boto3.client(“ssm”) object
s3_client – boto3.client(“s3”) object
instance_id – EC2 instance id
path_aws – the path to the AWS cli on EC2
path_python – the path to python interpreter on EC2, it is the one you want to use to run your script
code – the source code of your Python script (has to be single file)
s3uri – the S3 location you want to upload this Python script to.
args – the arguments you want to pass to your Python script, if the final command is ‘python /tmp/xxx.py arg1 arg2’, then args should be [“arg1”, “arg2”]
gap – the gap between each
send_commandapi and the firstget_command_invocationapi call. Because it takes some time to have the command invocation fired to SSM agent.raises – if True, then raises error if command failed, otherwise, just return the
CommandInvocationrepresents the failed invocation.delays – time interval in seconds to check the status of the command
timeout – the maximum time in seconds to wait for the command to finish
verbose – whether to print out the status of the command