Query EC2 tags from within instance

前端 未结 14 1737
暗喜
暗喜 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:30

    If you are not in the default availability zone the results from overthink would return empty.

    ec2-describe-tags \
       --region \
         $(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone  | sed -e "s/.$//") \
       --filter \
         resource-id=$(curl --silent http://169.254.169.254/latest/meta-data/instance-id)
    

    If you want to add a filter to get a specific tag (elasticbeanstalk:environment-name in my case) then you can do this.

    ec2-describe-tags \
       --region \
         $(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone  | sed -e "s/.$//") \
       --filter \
         resource-id=$(curl --silent http://169.254.169.254/latest/meta-data/instance-id) \
       --filter \
         key=elasticbeanstalk:environment-name | cut -f5
    

    And to get only the value for the tag that I filtered on, we pipe to cut and get the fifth field.

    ec2-describe-tags \
      --region \
        $(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone  | sed -e "s/.$//") \
      --filter \
        resource-id=$(curl --silent http://169.254.169.254/latest/meta-data/instance-id) \
      --filter \
        key=elasticbeanstalk:environment-name | cut -f5
    

提交回复
热议问题