0

I have 4 environment variables on my laptop, ami_id, instance_type, key_name and security_group_ids. I am trying to create a launch template version using these variables but I do not know how to pass them into the JSON array properly

aws ec2 create-launch-template-version --launch-template-id lt-xxx --launch-template-data '{"ImageId":"$ami_id", "InstanceType": "$instance_type", "KeyName": "$key_name", "SecurityGroupIds": ["$security_group_ids"]}'

An error occurred (InvalidAMIID.Malformed) when calling the CreateLaunchTemplateVersion operation: The image ID '$ami_id' is not valid. The expected format is ami-xxxxxxxx or ami-xxxxxxxxxxxxxxxxx.

Ydrab
  • 21
  • 1
  • 5
  • Have a look at using a proper tool for generating your JSON (something like `jq`). https://stackoverflow.com/questions/48470049/build-a-json-string-with-bash-variables could be helpful – j_b Jun 08 '22 at 17:44

1 Answers1

0

Using a here-document allows you to feed some readable text into a variable while expanding the shell variables, like this:

#!/bin/sh

ami_id=ami1234
instance_type=t3.nano
key_name=key1
security_group_ids=sg123,sg456

template_data=$(cat <<EOF
{
  "ImageId":"$ami_id",
  "InstanceType": "$instance_type",
  "KeyName": "$key_name",
  "SecurityGroupIds": ["$security_group_ids"]
}
EOF
)

echo "$template_data"

You can then test the JSON syntax with jq:

./template.sh  | jq -c
{"ImageId":"ami1234","InstanceType":"t3.nano","KeyName":"key1","SecurityGroupIds":["sg123,sg456"]}
Erwin
  • 844
  • 4
  • 14