How to use cloud-init with Terraform?
Solution 1
Cloud-init files are essentially bootstrap codes, that run before each startup, and can - among others - modify files, set up services, create users, etc.
Not all types of droplets support all functionalities of cloud-init, for example CoreOS uses it's own implementation, with a very limited subset of valid values.
To use this in terraform, simply provide the cloud-init file during droplet creation:
main.tf
:
resource "digitalocean_droplet" "web" {
image = "coreos-stable"
name = "web"
region = "lon1"
size = "2gb"
private_networking = true
ssh_keys = ["${digitalocean_ssh_key.dodemo.id}"]
user_data = "${file("web.conf")}"
}
web.conf
:
#cloud-config
coreos:
units:
- name: "etcd2.service"
command: "start"
- name: "fleet.service"
command: "start"
This will for example create a droplet, where CoreOS will run etcd2 and fleet during startup
You can find some more examples in this repository, where I show how one can use these configuration options to set up some simple docker based services on CoreOS
Solution 2
When you create an Auto Scaling group with Terraform, you can specify the user_data
to be used by instances created by this ASG. Documented here - https://www.terraform.io/docs/providers/aws/r/launch_configuration.html#user_data
You can also create a single EC2 instance, and provide user_data
to be used - https://www.terraform.io/docs/providers/aws/r/instance.html#user_data
The AWS EC2 documentation explains how user_data
is passed to the cloud-init
service which is running on most Linux distributions available as AMIs on AWS - http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html#user-data-cloud-init
Related videos on Youtube
Gepser Hoil
I'm an Engineering Manager with experience in Infrastructure and Backend! 🦾 I work at Homeday and my past jobs include Beek and PayPal 🗺 I like to travel ♟ I like to play Chess 🙌🏼 I've also worked as a CTO, Infrastructure and Software Engineer 🏯 Curious about what I am reading now? Check it out here. 💻 Mostly hacking in Ruby, Javascript, Golang, and Infra Tools.
Updated on September 18, 2022Comments
-
Gepser Hoil over 1 year
I am working with Digital Ocean and Terraform and I already can automate the domain, subdomain, network preferences and the host but there is a section called
User data
that looks like this:The description of that field says
Allows the use of Cloud-init to configure your droplet
. Looking around I found the documentation.How to take advantage of this while using Terraform?