forked from lettdigital/aws-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathelastic-beanstalk-set-hostname-within-instance.sh
More file actions
executable file
·64 lines (50 loc) · 1.73 KB
/
elastic-beanstalk-set-hostname-within-instance.sh
File metadata and controls
executable file
·64 lines (50 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/env bash
# This script sets the hostname on Elastic Beanstalk servers from within the instance with their EB environment name and public IP address
# Requires "ec2:Describe*" IAM Policy
# Update boto
pip install --upgrade boto
# Remove any previous scripts
function cleanup(){
if [ -f /home/ec2-user/ebenvironmentname.py ]; then
rm -f /home/ec2-user/ebenvironmentname.py
fi
if [ -f /home/ec2-user/sethostname.sh ]; then
rm -f /home/ec2-user/sethostname.sh
fi
}
cleanup
# Create the Python script to detect EB Environment
cat > /home/ec2-user/ebenvironmentname.py <<- EOF
#!/usr/bin/env python
import boto.utils
import boto.ec2
iid_doc = boto.utils.get_instance_identity()['document']
region = iid_doc['region']
instance_id = iid_doc['instanceId']
ec2 = boto.ec2.connect_to_region(region)
instance = ec2.get_only_instances(instance_ids=[instance_id])[0]
env = instance.tags['elasticbeanstalk:environment-name']
print(env)
EOF
chmod +x /home/ec2-user/ebenvironmentname.py
# Set Hostname
{
echo '#!/usr/bin/env bash'
echo ebenvironmentname=\$\(/usr/bin/env python /home/ec2-user/ebenvironmentname.py\)
echo sudo hostname '"$ebenvironmentname"'-"$(curl -s http://169.254.169.254/latest/meta-data/local-ipv4)"
} >> /home/ec2-user/sethostname.sh
chmod +x /home/ec2-user/sethostname.sh
cd /home/ec2-user/ && ./sethostname.sh
# Make hostname resolvable
{
cat /etc/hosts
echo 127.0.0.1 $(hostname)
} > /tmp/hosts
sort /tmp/hosts | uniq > /etc/hosts
# Persist changes over reboot
if ! [ -f /home/ec2-user/crontab.bk ]; then
cp /etc/crontab /home/ec2-user/crontab.bk
fi
/bin/cp -f /home/ec2-user/crontab.bk /etc/crontab
echo '@reboot root bash /opt/elasticbeanstalk/hooks/appdeploy/post/98_set_hostname.sh' >> /etc/crontab
cleanup