Query EC2 tags from within instance

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

    Install AWS CLI:

    curl "https://s3.amazonaws.com/aws-cli/awscli-bundle.zip" -o "awscli-bundle.zip"
    sudo apt-get install unzip
    unzip awscli-bundle.zip
    sudo ./awscli-bundle/install -i /usr/local/aws -b /usr/local/bin/aws
    

    Get the tags for the current instance:

    aws ec2 describe-tags --filters "Name=resource-id,Values=`ec2metadata --instance-id`"
    

    Outputs:

    {
        "Tags": [
            {
                "ResourceType": "instance", 
                "ResourceId": "i-6a7e559d", 
                "Value": "Webserver", 
                "Key": "Name"
            }
        ]
    }
    

    Use a bit of perl to extract the tags:

    aws ec2 describe-tags --filters \
    "Name=resource-id,Values=`ec2metadata --instance-id`" | \
    perl -ne 'print "$1\n" if /\"Value\": \"(.*?)\"/'
    

    Returns:

    Webserver
    

提交回复
热议问题