Search code examples
bashamazon-ec2ec2-amiec2-api-tools

shell script to set amazon ec2 hostname from tags


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?


Solution

  • 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).