0

I am Trying to change the AWS Tags for the Existing EC2 resources based on Key-Value pair. If Key-value pair matches, add/modify the tag. I am using AWS CLI for this operation

declare -a instance instance=$(aws ec2 describe-instances | jq ".Reservations[].Instances[].Tags[] | [.Key, .Value]")

This is generating the output as [ "Name", "TestCLI2" ] [ "Instance", "Trial2" ] [ "Instance", "Trial1" ] [ "Name", "TestCLI1" ]

Now I want to match for all those instances which has Key="Instance" and Value=["Trial1", "Trial2] should be modified to Trial3

I am trying to use loop but not able to proceed further as how to parse this JSON to check under if statements

for i in "${instance[@]}" # Looping through all the instances

0

You can use aws describe command to get all the ec2 instances that matches the tag with key="Instance" and value=["Trial1", "Trial2"].

$ aws ec2 describe-instances --region <yourRegion>   \
   --query Reservations[*].Instances[*].[InstanceId] \
   --filters "Name=tag:<tagKey>,Values=<tagValue>" --output text

The above command with provide you with instance id of instances matching the filter parameter. In next step you can pass the resource ids to below command.

$ aws ec2 create-tags --resources <id1> <id2> ... \
    --tags 'Key=<tagKey>,Value=<newValue>'

Create-tags command will create new tag if it doesn't exist. If it does then it will update the old tag value with new one.

Using xargs you can combine both commands to a single line.

$ aws ec2 describe-instances --region <yourRegion> \
 --query Reservations[*].Instances[*].[InstanceId] \
 --filters "Name=tag:<tagKey>,Values=<tagValue>"   \
 --output text| xargs -n1 -I@ aws ec2 create-tags  \
    --resources @ --tags 'Key=<tagKey>,Value=<newValue>'

For more info:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.