You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AWS EC2实例内部通过Bash获取实例名称标签

How to Retrieve Your AWS EC2 Instance's Name Tag via Bash

Got it, I’ve run into this exact issue before—hostname only spits out the private IP or a generic auto-generated hostname, which doesn’t help when you need the custom Name tag you assigned to your EC2 instance. Here’s a straightforward way to pull that value using Bash and the AWS CLI:


Prerequisites

  • AWS CLI installed: If it’s not on your instance yet, install it based on your OS:
    • Amazon Linux 2/Amazon Linux 2023:
      sudo yum install aws-cli -y
      
    • Ubuntu/Debian:
      sudo apt update && sudo apt install aws-cli -y
      
  • IAM Permissions: Your EC2 instance needs an attached IAM role with the ec2:DescribeTags permission. A minimal policy for this would be:
    {
        "Version": "2012-10-17",
        "Statement": [
            {
                "Effect": "Allow",
                "Action": "ec2:DescribeTags",
                "Resource": "*"
            }
        ]
    }
    
    Without this, the AWS CLI will throw a permission denied error when trying to fetch tags.

Step-by-Step Commands

  1. Get your instance ID from metadata:
    EC2 instances can access their own ID via the metadata service—no AWS CLI needed for this part:

    INSTANCE_ID=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
    
  2. Fetch the Name tag:
    Use the AWS CLI to filter tags for your instance ID and extract the Name tag value:

    INSTANCE_NAME=$(aws ec2 describe-tags \
        --filters "Name=resource-id,Values=$INSTANCE_ID" "Name=key,Values=Name" \
        --query 'Tags[0].Value' \
        --output text)
    
  3. Check the result:
    Just echo the variable to see your instance’s Name tag:

    echo $INSTANCE_NAME
    

Optional: Make the Name Tag Your Hostname

If you want hostname to return the Name tag instead of the IP, you can set it persistently:

sudo hostnamectl set-hostname $INSTANCE_NAME
echo $INSTANCE_NAME | sudo tee /etc/hostname

Note: On older systems, you might also need to update /etc/hosts to map the new hostname to your instance’s private IP.


Fallback for Unnamed Instances

If your instance doesn’t have a Name tag assigned, the above command will return a blank value. Add a fallback to handle this:

INSTANCE_NAME=$(aws ec2 describe-tags \
    --filters "Name=resource-id,Values=$INSTANCE_ID" "Name=key,Values=Name" \
    --query 'Tags[0].Value' \
    --output text || echo "No Name Tag Assigned")

内容的提问来源于stack exchange,提问作者Bogdan Dubyk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:46:36