如何在AWS EC2实例内部通过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
- Amazon Linux 2/Amazon Linux 2023:
- IAM Permissions: Your EC2 instance needs an attached IAM role with the
ec2:DescribeTagspermission. A minimal policy for this would be:
Without this, the AWS CLI will throw a permission denied error when trying to fetch tags.{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "ec2:DescribeTags", "Resource": "*" } ] }
Step-by-Step Commands
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)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)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

