Query EC2 tags from within instance

前端 未结 14 1776
暗喜
暗喜 2020-12-02 05:57

Amazon recently added the wonderful feature of tagging EC2 instances with key-value pairs to make management of large numbers of VMs a bit easier.

Is there some way

14条回答
  •  孤城傲影
    2020-12-02 06:41

    I have pieced together the following that is hopefully simpler and cleaner than some of the existing answers and uses only the AWS CLI and no additional tools.

    This code example shows how to get the value of tag 'myTag' for the current EC2 instance:

    Using describe-tags:

    export AWS_DEFAULT_REGION=us-east-1
    instance_id=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
    aws ec2 describe-tags \
      --filters "Name=resource-id,Values=$instance_id" 'Name=key,Values=myTag' \
      --query 'Tags[].Value' --output text
    

    Or, alternatively, using describe-instances:

    aws ec2 describe-instances --instance-id $instance_id \
      --query 'Reservations[].Instances[].Tags[?Key==`myTag`].Value' --output text
    

提交回复
热议问题