nad87563
nad87563

Reputation: 4092

How to read bash variables into json

I need to tag my ec2 instances and i want to pass the key and value via bash variables.

#!/bin/bash
image=""
instancetype=t2.small
key1=name
value1=test

key2=cname
value2=test123

aws ec2 run-instances --image-id $image --count 1 --instance-type $instancetype --tag-specifications 'ResourceType=instance,Tags=[{Key="$key1",Value="$value1"},{Key="$key2",Value="$value2"}]'

Upvotes: 0

Views: 75

Answers (1)

chepner
chepner

Reputation: 531758

You need to double quote the argument, escaping any double quotes that are intended to be passed through as part of the tag-specification string.

aws ec2 run-instances \
        --image-id "$image" \
        --count 1 \
        --instance-type "$instancetype" \
        --tag-specifications "ResourceType=instance,Tags=[{Key="\$key1\",Value=\"$value1\"},{Key=\"$key2\",Value=\"$value2\"}]"

The same caveat I mentioned in my comment on the question applies: if any of your variables contain a value that could affect how the tag-spec is parsed, they need to be properly escaped before you use them. For example

value2='test" " 3'  # Wrong
value2='test\" \" 3'  # Right

Upvotes: 1

Related Questions