0
votes

I am using a bash script to dynamically create an EC2 CLI request. When the bash script is executed the AWS CLI returns Error parsing parameter '--launch-specification': Invalid JSON:, but if I copy the CLI string and submit it directly via the CLI, the CLI command works no problems.

Could / is the bash script generating some code characters that cause the CLI request to fail that are not present when I use copy/paste in the terminal?

BASH SCRIPT CODE

CMD01=("aws --profile ${myProf} --region ${myRegion} ec2 request-spot-instances --spot-price ${PRICE} --instance-count ${6} --type \"one-time\"  --launch-specification \"{\\\"ImageId\\\":\\\"${1}\\\",\\\"KeyName\\\":\\\"${2}\\\",\\\"InstanceType\\\":\\\"${!5}\\\",\\\"IamInstanceProfile\\\":{\\\"Arn\\\":\\\"${16}\\\"},\\\"Placement\\\":{\\\"AvailabilityZone\\\":\\\"${18}\\\",\\\"GroupName\\\":\\\"${11}\\\"},\\\"NetworkInterfaces\\\":[{\\\"DeviceIndex\\\":0,\\\"SubnetId\\\":\\\"${4}\\\",\\\"AssociatePublicIpAddress\\\":${17}}],\\\"UserData\\\":\\\"string\\\"}\" --dry-run")

echoed via

echo "$CMD01"

aws --profile myProfile --region eu-west-1 ec2 request-spot-instances --spot-price 0.004 --instance-count 1 --type "one-time" --launch-specification "{\"ImageId\":\"ami-9c7ad8eb\",\"KeyName\":\"myKey\",\"InstanceType\":\"t1.micro\",\"IamIns tanceProfile\":{\"Arn\":\"arn:aws:iam::000000000000:instance-profile/myprofile\"},\"Placement\":{\"AvailabilityZone\":\"eu-west-1c\",\"GroupName\":\"myGroup\"},\"NetworkInterfaces\":[{\"DeviceIndex\":0,\"SubnetId\":\"subnet-xxxyyy\",\"AssociatePublicIpAddress\":true}],\"UserData\":\"string\"}" --dry-run

executed via ${CMD01[@]} > $logFile

generates error

Error parsing parameter '--launch-specification': Invalid JSON: "{\"ImageId\":\"ami-9c7ad8eb\",\"KeyName\":\"myKey\",\"InstanceType\":\"t1.micro\",\"IamInstanceProfile\":{\"Arn\":\"arn:aws:iam::000000000000:instance-profile/myprofile\"},\"Placement\":{\"AvailabilityZone\":\"eu-west-1c\",\"GroupName\":\"myGroup\"},\"NetworkInterfaces\":[{\"DeviceIndex\":0,\"SubnetId\":\"subnet-xxxyyy\",\"AssociatePublicIpAddress\":true}],\"UserData\":\"string\"}"

now if I take the earlier echo echo "$CMD01" from the terminal and do a simple copy/paste, the CLI output

A client error (DryRunOperation) occurred when calling the RequestSpotInstances operation: Request would have succeeded, but DryRun flag is set.

So it seems the JSON is valid, but when executed from the bash scrip it is invalid. What am I doing wrong?

1

1 Answers

0
votes

I think you have a bash error.

Try with:

CMD01=$(aws commands commands...)