Reputation: 1638
I am trying to set amazon EC2 hostname from the tag "Name"
And found the answer to extract tags from instance data.
ec2-describe-tags \
--filter "resource-type=instance" \
--filter "resource-id=$(ec2-metadata -i | cut -d ' ' -f2)" \
--filter "key=Name" | cut -f5
the result is:
+------------+--------------+------+--------+
| resourceId | resourceType | key | value |
+------------+--------------+------+--------+
| i-1xxxxxxx | instance | Name | dev200 |
+------------+--------------+------+--------+
I can see that I am almost there, but how do I get the value(dev200) from the result above? Then I can use it in:
echo $HOSTNAME > /etc/hostname
p.s. I have BASH on the instance, but I am completely lost in the bash document. can someone point me to the correct paragraph?
Upvotes: 2
Views: 7083
Reputation: 1
Another way to get name tag is below.
hostname=$(aws ec2 describe-tags \
--filters "Name=resource-id,Values=$(curl http://169.254.169.254/latest/meta-data/instance-id)" \
--query 'Tags[?Key==`Name`].Value' \
--output text)
And then you can set the hostname using hostnamectl
.
hostnamectl set-hostname "$hostname"
Upvotes: 0
Reputation: 757
You could just use curl, since it is usually installed.
assigned_host_name=$(curl 'http://169.254.169.254/latest/meta-data/assigned_host_name') assigned_domain_name=$(curl 'http://169.254.169.254/latest/meta-data/assigned_domain_name')
Then just check that the values assigned don't contain a 404 HTML message like below.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>404 - Not Found</title> </head> <body> <h1>404 - Not Found</h1> </body> </html>
Thenn do whatever magic you want to assign hostname. I'll edit this later today to add how I did that.
Upvotes: 0
Reputation: 1638
After some error and trial, got the script working:
#!/bin/bash
hostname=`ec2-describe-tags --filter "resource-type=instance" \
--filter "resource-id=$(ec2-metadata -i | cut -d ' ' -f2)" \
--filter "key=Name" | grep Name`
IFS="|" read -ra NAME <<< "$hostname"
hostname=${NAME[4]}
echo $hostname
Used IFS to get the string parsed into arrays, and luckily I know the 4th element is always the hostname.
EDIT (20-DEC-2012): In the short time since this was posted, several of the relevant ec2 command line tools have been modified, and flags changed or deprecated (e.g., the -i flag from above no longer seems to work on the current version of ec2metadata). Bearing that in mind, here is the command line script I used to get the current machine's "Name" tag (can't speak to the rest of the script):
ec2-describe-tags --filter "resource-type=instance" --filter "resource-id=$(ec2metadata --instance-id)" | awk '{print $5}'
On Debian/Ubuntu, you need to apt-get install cloud-utils ec2-api-tools
to get these working (the later is only on Ubuntu Multiverse).
Upvotes: 4