Monthly Archives: September 2018

DigitalOcean – Create Ubuntu server using Terraform

Introduction

In this post, we are going to create a server on DigitalOcean running Ubuntu. There’s plenty of ways doing it but for this post I decided to give Terraform a try.

Pre-requisites
I’m assuming you have already a DigitalOcean account and have access to its webinterface. In order to create droplets via Terraform, you will need to get API access. On DigitalOcean’s webinterface, go to API and click “Generate Token”.

Then take a note for the token that got created.

Note: the above is just for education. In the below examples, I used another key myself (one I generated earlier). Should not matter of course as you will need to generate your own key anyway.

Next, you will also need the fingerprint of the SSH key you want to use to access the provisioned server. Therefore go to your Account page and then to Security. There is a section called “SSH keys”. You’ll want to copy/paste somewhere the fingerprint of the key you wish to use.

Creating the Terraform scripts

The below script will create a droplet called server 1 on DigitalOcean and will apply also a tag ‘webserver’ to the droplet.

Create a file called ‘provider.tf’.

variable "do_token" {}
variable "ssh_fingerprint" {}

provider "digitalocean"{
  token = "${var.do_token}"
}

Then, create a file called ‘create_server.tf’

resource "digitalocean_droplet" "Server1" {
    name = "Server1"
    image = "ubuntu-18-04-x64"
    size = "512mb"
    region = "ams3"
    ssh_keys = ["${var.ssh_fingerprint}"]
    tags = ["${digitalocean_tag.webserver.name}"]
}

resource "digitalocean_tag" "webserver" {
    name = "web"
}

Then execute the command ‘terraform init’. This will essentially download the DigitalOcean plugin and initilize it.

WAUTERW-M-T3ZT:DigitalOcean wim$ terraform init

Initializing provider plugins...
- Checking for available provider plugins on https://releases.hashicorp.com...
- Downloading plugin for provider "digitalocean" (1.0.2)...

The following providers do not have any version constraints in configuration,
so the latest version was installed.

To prevent automatic upgrades to new major versions that may contain breaking
changes, it is recommended to add version = "..." constraints to the
corresponding provider blocks in configuration, with the constraint strings
suggested below.

* provider.digitalocean: version = "~> 1.0"

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.

Next, perform a ‘terraform plan’ as follows. Note that it will prompt you for the two values in the provider.tf file.

WAUTERW-M-T3ZT:DigitalOcean wim$ terraform plan
var.do_token
  Enter a value: 0b231b8a4***f307da

var.ssh_fingerprint
  Enter a value: 5a:25:96:***:8d:03

Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.


------------------------------------------------------------------------

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  + digitalocean_droplet.Server1
      id:                   
      backups:              "false"
      disk:                 
      image:                "ubuntu-18-04-x64"
      ipv4_address:         
      ipv4_address_private: 
      ipv6:                 "false"
      ipv6_address:         
      ipv6_address_private: 
      locked:               
      memory:               
      monitoring:           "false"
      name:                 "Server1"
      price_hourly:         
      price_monthly:        
      private_networking:   "false"
      region:               "ams3"
      resize_disk:          "true"
      size:                 "512mb"
      ssh_keys.#:           "1"
      ssh_keys.1707954218:  "5a:25:96:***:8d:03"
      status:               
      tags.#:               "1"
      tags.365508689:       "web"
      vcpus:                
      volume_ids.#:         

  + digitalocean_tag.webserver
      id:                   
      name:                 "web"


Plan: 2 to add, 0 to change, 0 to destroy.

So we can see that the plan is to add two resources, essentially the droplet itself and then also the tags.

WAUTERW-M-T3ZT:DigitalOcean wim$ terraform apply
var.do_token
  Enter a value: 0b23***307da

var.ssh_fingerprint
  Enter a value: 5a:25:***:8d:03


An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  + digitalocean_droplet.Server1
      id:                   
      backups:              "false"
      disk:                 
      image:                "ubuntu-18-04-x64"
      ipv4_address:         
      ipv4_address_private: 
      ipv6:                 "false"
      ipv6_address:         
      ipv6_address_private: 
      locked:               
      memory:               
      monitoring:           "false"
      name:                 "Server1"
      price_hourly:         
      price_monthly:        
      private_networking:   "false"
      region:               "ams3"
      resize_disk:          "true"
      size:                 "512mb"
      ssh_keys.#:           "1"
      ssh_keys.1707954218:  "5a:25:***:8d:03"
      status:               
      tags.#:               "1"
      tags.365508689:       "web"
      vcpus:                
      volume_ids.#:         

  + digitalocean_tag.webserver
      id:                   
      name:                 "web"


Plan: 2 to add, 0 to change, 0 to destroy.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

digitalocean_tag.webserver: Creating...
  name: "" => "web"
digitalocean_tag.webserver: Creation complete after 2s (ID: web)
digitalocean_droplet.Server1: Creating...
  backups:              "" => "false"
  disk:                 "" => ""
  image:                "" => "ubuntu-18-04-x64"
  ipv4_address:         "" => ""
  ipv4_address_private: "" => ""
  ipv6:                 "" => "false"
  ipv6_address:         "" => ""
  ipv6_address_private: "" => ""
  locked:               "" => ""
  memory:               "" => ""
  monitoring:           "" => "false"
  name:                 "" => "Server1"
  price_hourly:         "" => ""
  price_monthly:        "" => ""
  private_networking:   "" => "false"
  region:               "" => "ams3"
  resize_disk:          "" => "true"
  size:                 "" => "512mb"
  ssh_keys.#:           "" => "1"
  ssh_keys.1707954218:  "" => "5a:25:***:8d:03"
  status:               "" => ""
  tags.#:               "" => "1"
  tags.365508689:       "" => "web"
  vcpus:                "" => ""
  volume_ids.#:         "" => ""
digitalocean_droplet.Server1: Still creating... (10s elapsed)
digitalocean_droplet.Server1: Still creating... (20s elapsed)
digitalocean_droplet.Server1: Still creating... (30s elapsed)
digitalocean_droplet.Server1: Creation complete after 35s (ID: 121467800)

Apply complete! Resources: 2 added, 0 changed, 0 destroyed.

As indicated in the output, the servers was created successfully and also the tag was applied properly.

SSH into the server
Let’s now try to ssh into the server by using our keypair. Go to the local folder on your PC/MAC and locate the public key that corresponds to the SSH key you uploaded to the DO webinterface,

WAUTERW-M-T3ZT:Keys_and_Certificates wim$ ssh -i keypair_digitalocean_146185179184 root@188.166.93.161
The authenticity of host '188.166.93.161 (188.166.93.161)' can't be established.
ECDSA key fingerprint is SHA256:3QEQKdgrfSHkNrgc85fj2MgPnLxKQ8+bshBI2gklP58.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '188.166.93.161' (ECDSA) to the list of known hosts.
Welcome to Ubuntu 18.04.1 LTS (GNU/Linux 4.15.0-38-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Sun Dec  2 15:39:47 UTC 2018

  System load:  0.02              Processes:           82
  Usage of /:   4.9% of 19.21GB   Users logged in:     0
  Memory usage: 24%               IP address for eth0: 188.166.93.161
  Swap usage:   0%

  Get cloud support with Ubuntu Advantage Cloud Guest:
    http://www.ubuntu.com/business/services/cloud

0 packages can be updated.
0 updates are security updates.



The programs included with the Ubuntu system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.

root@Server1:~#

Deleting the server
Deleting the server is very easy with Terraform. Just use the ‘Terraform destroy’ command will do the trick.

WAUTERW-M-T3ZT:DigitalOcean wim$ terraform destroy
var.do_token
  Enter a value: 0b2***307da

var.ssh_fingerprint
  Enter a value: 5a:25:***:8d:03

digitalocean_tag.webserver: Refreshing state... (ID: web)
digitalocean_droplet.Server1: Refreshing state... (ID: 121467800)

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  - destroy

Terraform will perform the following actions:

  - digitalocean_droplet.Server1

  - digitalocean_tag.webserver


Plan: 0 to add, 0 to change, 2 to destroy.

Do you really want to destroy all resources?
  Terraform will destroy all your managed infrastructure, as shown above.
  There is no undo. Only 'yes' will be accepted to confirm.

  Enter a value: yes

digitalocean_droplet.Server1: Destroying... (ID: 121467800)
digitalocean_droplet.Server1: Still destroying... (ID: 121467800, 10s elapsed)
digitalocean_droplet.Server1: Destruction complete after 12s
digitalocean_tag.webserver: Destroying... (ID: web)
digitalocean_tag.webserver: Destruction complete after 0s

Destroy complete! Resources: 2 destroyed.