Query EC2 tags from within instance

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

    You can add this script to your cloud-init user data to download EC2 tags to a local file:

    #!/bin/sh
    INSTANCE_ID=`wget -qO- http://instance-data/latest/meta-data/instance-id`
    REGION=`wget -qO- http://instance-data/latest/meta-data/placement/availability-zone | sed 's/.$//'`
    aws ec2 describe-tags --region $REGION --filter "Name=resource-id,Values=$INSTANCE_ID" --output=text | sed -r 's/TAGS\t(.*)\t.*\t.*\t(.*)/\1="\2"/' > /etc/ec2-tags
    

    You need the AWS CLI tools installed on your system: you can either install them with a packages section in a cloud-config file before the script, use an AMI that already includes them, or add an apt or yum command at the beginning of the script.

    In order to access EC2 tags you need a policy like this one in your instance's IAM role:

    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Sid": "Stmt1409309287000",
          "Effect": "Allow",
          "Action": [
            "ec2:DescribeTags"
          ],
          "Resource": [
            "*"
          ]
        }
      ]
    }
    

    The instance's EC2 tags will available in /etc/ec2-tags in this format:

    FOO="Bar"
    Name="EC2 tags with cloud-init"
    

    You can include the file as-is in a shell script using . /etc/ec2-tags, for example:

    #!/bin/sh
    . /etc/ec2-tags
    echo $Name
    

    The tags are downloaded during instance initialization, so they will not reflect subsequent changes.


    The script and IAM policy are based on itaifrenkel's answer.

    0 讨论(0)
  • 2020-12-02 06:50

    Jq + ec2metadata makes it a little nicer. I'm using cf and have access to the region. Otherwise you can grab it in bash.

    aws ec2 describe-tags --region $REGION \
    --filters "Name=resource-id,Values=`ec2metadata --instance-id`" | jq --raw-output \
    '.Tags[] | select(.Key=="TAG_NAME") | .Value'
    

    No jq.

    aws ec2 describe-tags --region us-west-2 \
    --filters "Name=resource-id,Values=`ec2-metadata --instance-id | cut -d " " -f 2`" \
    --query 'Tags[?Key==`Name`].Value' \
    --output text
    
    0 讨论(0)
提交回复
热议问题