'Issue with python code in lambda function using boto3 using send_command
Issue with parsing string in python boto3 code
In my lambda function has following code
instance_id = "'" + str(instance[0]) + "'"
ssmresponse = ssm_client.send_command(InstanceIds=[ instance_id ],DocumentName='AWS-
RunShellScript',Parameters={'commands': ['ls -l']}, )
command_id = ssmresponse['Command']['CommandId']
if I specify the instance_id as
instance_id = str(instance[0])
send_command is erroring out with
"WARN: Exception occured An error occurred (ValidationException) when calling the SendCommand operation: 1 validation error detected: Value '[ec2.Instance(id='i-0xxxxxxxxxxxxxxx')]' at 'instanceIds' failed to satisfy constraint: Member must satisfy constraint: [Member must have length less than or equal to 20, Member must have length greater than or equal to 10, Member must satisfy regular expression pattern: (^i-(\w{8}|\w{17})$)|(^mi-\w{17}$)]."
if I specify instance_id as
instance_id = "'" + str(instance[0]) + "'"
send_command is erroring out with
"WARN: Exception occured An error occurred (ValidationException) when calling the SendCommand operation: 1 validation error detected: Value '['ec2.Instance(id='xxxxxxxxxxxxxxxxxx')']' at 'instanceIds' failed to satisfy constraint: Member must satisfy constraint: [Member must have length less than or equal to 20, Member must have length greater than or equal to 10, Member must satisfy regular expression pattern: (^i-(\w{8}|\w{17})$)|(^mi-\w{17}$)]."
When I hardcode the instance id within the send_command, there are no errors
ssmresponse = ssm_client.send_command(InstanceIds=[ 'i-xxxxxxxxxxxxxxxx' ],DocumentName='AWS-RunShellScript',Parameters={'commands': ['ls -l']}, )
there are no errors
I need to dynamically set the instance_id. What could possibly be wrong in this?
Any help is appreciated.
Thanks D
Solution 1:[1]
I am guessing you are first querying instances using Ec2 Service Resource and getting back a resource object, which would have instance[0].id as "i-123..." but when you specify it just as 'instance[0], it is simply returning the first instance "object"
For context, boto3 has clients and resources. When dealing with client, you get back text (mostly json) but resource returns pythonic 'objects'.
Service Resource: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#service-resource
vs Client: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#client
In case it is still not clear, use:
(InstanceIds=[ instance[0].id ]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Adil Hindistan |
