Posted at

How to change Linux host name in EC2 user data

This article is an automatic translation of the article[ead862e002c543070b49] below.

https://qiita.com/speaktech/items/ead862e002c543070b49


User data

Use fqdn key in cloud-init directive of user data.

This is all you need to do is change the host name.


user-data.yaml

#cloud-config

fqdn: example.co.jp


** The hostname key also has a hostname key.

However, the hostname key is ignored if the fqdn key is used.

Since the AWS default host name is defined by the fqdn key, you need to use the fqdn key to overwrite it. **


How to enter user data 1: GUI

Paste it in [User data] of [Create instance]> [Step 3: Detailed setting of instance]

Just create an instance.

image.png


How to enter user data 2: AWS CLI

Pass the raw text file with the --user-data option. As yaml, but the extension is OK.

aws ec2 run-instances --region $Region \

--image-id $AmiId --count 1 \
--instance-type $InstanceType --key-name $KeyName \
--subnet-id $SubnetId --private-ip-address $PrivateIpAddress \
--associate-public-ip-address \
--security-group-ids $SecurityGroupIds \
--tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=$NameTag}]" \
--credit-specification CpuCredits=standard \
--user-data file://userdata.yml

※ Please set the value of variable appropriately. Please change the line feed character from"\"to"`"when executing with Powershell.


NOTE: The host name is initialized when launching from the created AMI

The default behavior is to initialize the hostname, locale and default user in cloud-init.

If you simply want to prevent this, set the preserve_hostname key to true in the user data.


user-data.yaml

#cloud-config

fqdn: example.co.jp

runcmd:
- echo "preserve_hostname: true" >> /etc/cloud/cloud.cfg



  • If the preserve_hostname key is set to true, the hostname key and fqdn key will not function.

that's all.