One idea that worked for me was use shell parameter expansion (I think that's the right term). I am still maintaining my own script, baked into my AMI, but I prefer the template-like approach versus my previous script that used sed to modify the /etc/hosts
file.
#!/bin/bash
# Get Name tag from AWS instance metadata
ec2id=$(curl http://169.254.169.254/latest/meta-data/instance-id)
hostname=$(aws ec2 describe-tags --filters "Name=resource-id,Values=$ec2id" "Name=key,Values=Name" --region us-east-1 | awk '/"Value":/ {print $2}' | tr -d '",')
fqdn="${hostname}.local"
# Write a new hosts file using variable expansion
cat >/etc/hosts <<EOF
# The following lines are desirable for IPv4 capable hosts
127.0.0.1 ${fqdn} ${hostname}
127.0.0.1 localhost.localdomain localhost
127.0.0.1 localhost4.localdomain4 localhost4
# The following lines are desirable for IPv6 capable hosts
::1 ${fqdn} ${hostname}
::1 localhost.localdomain localhost
::1 localhost6.localdomain6 localhost6
EOF
I run the script via cloud-init defined in user data:
#cloud-config
runcmd:
- bash /usr/local/bin/hostmod.sh
I also tried creating the entire script within user data via cloud-config. This works as well, but I split the file out to make it easier to manage separately in Ansible.
#cloud-config
write_files:
- path: /usr/local/bin/hostmod.sh
permissions: 0744
owner: root
content: |
#!/bin/bash
ec2id=$(curl http://169.254.169.254/latest/meta-data/instance-id)
hostname=$(aws ec2 describe-tags --filters "Name=resource-id,Values=$ec2id" "Name=key,Values=Name" --region us-east-1 | awk '/"Value":/ {print $2}' | tr -d '",')
fqdn="${hostname}.local"
cat >/etc/hosts <<EOF
# The following lines are desirable for IPv4 capable hosts
127.0.0.1 ${fqdn} ${hostname}
127.0.0.1 localhost.localdomain localhost
127.0.0.1 localhost4.localdomain4 localhost4
# The following lines are desirable for IPv6 capable hosts
::1 ${fqdn} ${hostname}
::1 localhost.localdomain localhost
::1 localhost6.localdomain6 localhost6
EOF
runcmd:
- bash /usr/local/bin/hostmod.sh
This obviously doesn't change the hostname, which is a bit more platform dependent. That is why I preferred to use cloud-init from the start. I may later add a similar template for updating the hostname.
/var/log/cloud-init.log
that the EC2 instance metadata is being read. I feel like I'm either close, or approaching this completely the wrong way?cloud-init[2412]: url_helper.py[DEBUG]: [0/6] open 'http://169.254.169.254/latest/meta-data/local-hostname' with {'url': 'http://169.254.169.254/latest/meta-data/local-hostname', 'headers': {'User-Agent': 'Cloud-Init/0.7.6'}, 'allow_redirects': True, 'method': 'GET', 'timeout': 5.0} configuration
– shawnjohnson