Jeff Terrell Ph.D.
Jeff Terrell Ph.D.

Reputation: 2711

How to list only the EC2 instances in a given CloudFormation stack?

What can I use for $QUERY in the command below that meets the following criteria:

aws ec2 describe-instances --query $QUERY
  1. Only prints instances with an aws:cloudformation:stack-name tag equal to test-stack.
  2. Only prints the InstanceId property for each instance.
  3. Doesn't resort to piping, for loops, or other shell fanciness.

Upvotes: 4

Views: 3321

Answers (1)

Bas Peeters
Bas Peeters

Reputation: 3354

There are a few parameters to use here:

Querying

--query (docs) for retrieving only the InstanceId

Filtering by stack-name tag

--filter (docs) for excluding the instances not tagged with the stack's name

  • tag-key - The key of a tag assigned to the resource. This filter is independent of the tag-value filter. For example, if you use both the filter "tag-key=Purpose" and the filter "tag-value=X", you get any resources assigned both the tag key Purpose (regardless of what the tag's value is), and the tag value X (regardless of what the tag's key is). If you want to list only resources where Purpose is X, see the tag :key =value filter.

  • tag-value - The value of a tag assigned to the resource. This filter is independent of the tag-key filter.

Formatting

--output (docs) for returning only the values you queried for (so no quotes or json/table fluff)

The text format organizes the AWS CLI's output into tab-delimited lines. It works well with traditional Unix text tools such as grep, sed, and awk, as well as Windows PowerShell.

Using those parameters like this:

aws ec2 describe-instances \                                                     
    --query "Reservations[*].Instances[*].InstanceId[]" \                        
    --filters "Name=tag-key,Values=aws:cloudformation:stack-name" "Name=tag-value,Values=test-stack" \
    --output=text

Returns:

i-sd64f52a  i-das5d64a  i-sad56d4

Upvotes: 6

Related Questions