Centos – Hostname via Cloud-Init on CentOS running on EC2 do not work

amazon ec2centoscloud-init

I setup the cloud-config on the user-data for a CentOS 6.4's EC2 instance, and it looks like do not apply.

#cloud-config
manage_etc_hosts: true
preserve_hostname: false
hostname: myserver01.example.com

On the cloud-init logs I see:

cloud-init[DEBUG]: preserve_hostname is set. not managing hostname

How can I force to it set the hostname ?

Best Answer

I haven't tried this on the CentOS 6 AMI, but this works for CentOS 7:

NEWHOSTNAME="myserver01.example.com"

CLOUDTMP=`mktemp $TMPDIR/$(basename $0).XXXXXX 2>/dev/null` || exit 1

cat <<EOF > $CLOUDTMP 
#!/bin/bash
hostnamectl set-hostname $NEWHOSTNAME
echo "preserve_hostname: true" > /etc/cloud/cloud.cfg.d/99_hostname.cfg
EOF

aws ec2 run-instances --user-data file://$CLOUDTMP --cli-input-json file://path/to/file.json