How to Start AWS instance if it has Tag exists

I would like to run AWS CLI command to start the instance if it has relevant Tags exist for Eg "MigratedBy". If Tag doesnt exists, it shouldnt start the instance at all

I tried running below command but it didnt work out

aws ec2 start-instances --instance-ids `aws ec2 describe-instances --filters "Name=tag:MigratedBy,Values=my-super-tag" --query 'Reservations[].Instances[].InstanceId' --outpu t text` 

It seems this command would run all the instance with the tag "MigratedBy" but this is wrong in my case. I would like to just start the particular instance if tag exists otherwise not


Solution 1:

If you want to filter based only on the existence of the tag you can include it in the query and then pipe to show only the InstanceId:

aws ec2 describe-instances --query 'Reservations[].Instances[].[Tags[?Key=='MigratedBy'],InstanceId] | [*][1]' --output text

Finally, to start those instances the whole command will be:

aws ec2 start-instances --instance-ids `aws ec2 describe-instances --query 'Reservations[].Instances[].[Tags[?Key=='MigratedBy'],InstanceId] | [*][1]' --output text` 

Reference:

Filtering AWS CLI output