How to pass a string from python to AWS Run Powershell script commands section using boto3

870 views Asked by At

Is there anyway to pass the variable (var) defined in python idle to AWS-RunPowerShellScript commands section ?

Here is my code:

import boto3

ssm = boto3.client("ssm")
var = "test"

res = ssm.send_command(
     DocumentName="AWS-RunPowerShellScript",
     Targets=[
         {
             'Key': 'tag:test',
             'Values': ['testing']
         }
     ] 
     Comment="Test",
     Parameters={'commands':[
          'hostname',
          '$var'
       ]
}
)

In the above code, I am defining variable var in python and the same I want to refer in the commands section of the send_command as $var but it seems like it is not working due to the remote execution. Is there any possibility to pass the variable from python to the commands section ?

1

There are 1 answers

0
ma77c On BEST ANSWER

You can build the command string before calling send_command with the ssm_client. Then reference the variable in the parameters.

This can be done with any type of send_command including AWS-RunShellScript or AWS-RunPowershellScript

In your example above, note that you have used '$var' which is a actually a string since it is wrapped in ''. Also note that in Python, the $ char is not used to reference variables. That is a PHP thing.

import boto3

ssm_client = boto3.client('ssm')
# build your command string here
command = "echo 'hello world' > testfile.txt"
# send command
response = ssm_client.send_command(
        DocumentName="AWS-RunShellScript",
        Targets=[
            {
                'Key': 'tag:test',
                'Values': ['testing']
            }
        ],
        # the command var is just a string after all
        Parameters={'commands': [command]}
    )
print(response)