Create a Digital Ocean droplet with Terraform

Infrastructure as code

I’ve been meaning to try out terraform. It gives you the power to define your infrastructure with code. It plugs in with all major cloud providers. Here’s some links below:

https://www.terraform.io/
https://www.terraform.io/docs/providers/index.html

For simplicity sake I played around with terraform and digitalocean.
https://www.terraform.io/docs/providers/do/index.html

A couple things you have to just setup on digital ocean:

  • Add your ssh key to digital ocean – copy the name of your ssh key, paste it somewhere for reuse
  • Create a digital ocean api token – copy the token, paste it somewhere for reuse

Install terraform and make sure you can run the “terraform” command. (On mac, I had to move the install to /usr/local/bin/ ) https://www.terraform.io/intro/getting-started/install.html

Check terraform can be run correctly:

1
$ terraform -v

Setup main.tf file

I’ve put together this script, save it as main.tf in a new folder

Setup environment variables and run commands

You need to set up 2 environment variables. Use the two copied values from above:

1
2
export DOTOKEN="YOUR_DIGITAL_OCEAN_API_TOKEN_HERE"
export SSHKEYNAME="SSH_KEY_NAME_FROM_DIGITAL_OCEAN"

Test the values are correct:

1
2
echo $DOTOKEN
echo $SSHKEYNAME

Run the following commands:

1
2
3
4
$ terraform init
$ terraform plan -var="do_token=$DOTOKEN" -var="ssh_key_name=$SSHKEYNAME"
   - Output will end with: Plan: 1 to add, 0 to change, 0 to destroy.
$ terraform apply -var="do_token=$DOTOKEN" -var="ssh_key_name=$SSHKEYNAME"

If you get any authentication errors, make sure you have set up your ssh key with your computer’s public key.

After the “apply” command you’ll see an ip.

1
2
3
Outputs:

controller_ip_address = 127.0.0.1

(127.0.0.1 is just a placeholder ip value, you’ll get a different value which you can use)

ssh into the new server

Then, because we supplied the ssh key name, the new server will have our ssh key set up already.

You can ssh into the server using the ip displayed:

You now have an ubuntu droplet to play around with. When you’re done, just run the “destroy” command below:

1
$ terraform destroy -var="do_token=$DOTOKEN" -var="ssh_key_name=$SSHKEYNAME"

You can do some great things with terraform. You can spin up multiple servers to practice distributed systems. You can add chef into the mix and make sure the right software is setup on the servers in preparation for code.

You might then want to install a container orchestrator like kubernetes or swarm, then run yaml scripts. And automate it all via ansible, jenkins, gitlab etc. The possibilities are endless 🙂

Keep swimming…

Here’s a link for using chef with terraform:

https://www.terraform.io/docs/provisioners/chef.html