Cloud-init is a multi-distribution package that handles early initialization of cloud instances. Some of the things cloud-init can do are
- set up the hostname.
- setting up a local user.
- Updating and installing the packages on Linux.
- Disk setup and mounting the additional volumes.
More information can be found at Cloud-Init
Today most of the distribution support cloud-init and using cloud-init can run all cloud providers(AWS, Azure, GCP). In this article, I want to show some of the code-snippets I have tried in AWS with different distributions mainly Ubuntu and Amazon Linux.
#To create hostname :
#cloud-config
#set the hostmachine name
fqdn: myhostname.com
This will set the hostname of the deployed instance to myhostname.com. But the default AMI from Amazon Linux does not support changing the hostname. You need to launch the instance and change the preserve_hostname to false in etc/cloud/cloud.cfg.Then you need to build an image from that instance and launch a new instance from the build image with the above cloud-config script to change the hostname.
#To add additional users to the instance
#cloud-config
users:
- name: bob
sudo: ALL=(ALL) NOPASSWD: ALL
groups: admin, root
This will add user bob to the instance along with the default user created by distro’s like for Amazon Linux default user ec2-user and for Ubuntu default user is ubuntu.
#To update packages and install new ones:
#cloud-config
package_update:true
packages:
- pwgen
- nginx
The above will update the distro package system and install the pwgen and nginx packages.
#Disk Setup and mount the additional EBS volumes.
#cloud-config
# - /dev can ommited for device names starting with xvd, sd, hd, vd
# if device does not exist at the time, an entry will still be written to /etc/fstab
mounts:
- [xvdb, /data,"auto","defaults,nofail", "0", "0"]
#setup the file system on the device
fs_setup:
- label: data
filesystem: 'ext4'
device: '/dev/xvdb'
partition: auto
runcmd:
- mkdir /data
This will basically set up the disk to filesystem ext4 and add the mounting device to /etc/fstab in Linux.
Thanks for viewing.
Best Regards
Naveen