How To Deploy Droplet on DigitalOcean With Terraform

Posted on

Hello good people. In today’s blog post we will be showing you how to create a Droplet in DigitalOcean using Terraform. Terraform is an IaC and automation software tool created to enable Developers and SysAdmins to define and provision data center infrastructure using a declarative configuration language known as HashiCorp Configuration Language.

DigitalOcean is a Cloud Platform created to help millions of developers to easily build, manage, and scale their applications of any size with speed. In this blog post we will demonstrate how you can use Terraform provider for DigitalOcean to provision, modify and delete Infrastructure resources.

Step 1: Install Terraform on Linux | macOS

Start with the installation of Terraform on your Linux or macOS system.

Install terraform on Linux:

TER_VER=`curl -s https://api.github.com/repos/hashicorp/terraform/releases/latest |  grep tag_name | cut -d: -f2 | tr -d ",v | awk '{$1=$1};1'`
wget https://releases.hashicorp.com/terraform/${TER_VER}/terraform_${TER_VER}_linux_amd64.zip

Extract the downloaded archive:

$ unzip terraform_${TER_VER}_linux_amd64.zip
Archive:  terraform_xxx_linux_amd64.zip
 inflating: terraform

Then move the binary file to directory in your PATH.

sudo mv terraform /usr/local/bin/

Install terraform on macOS:

On macOS you can install terraform using brew.

$ brew install terraform

If brew is not available use the following command to install it.

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

Confirm terraform version:

$ terraform version
Terraform v0.14.0

Step 2: Generate DigitalOcean Access Token

The DigitalOcean API allows you to manage Droplets and resources within the DigitalOcean cloud in a simple, programmatic way using conventional HTTP requests. The endpoints are intuitive and powerful, allowing you to easily make calls to retrieve information or to execute actions.

To generate the token login to DigitalOcean portal and head over to API > Applications & API > Tokens/Keys > Generate New Token.

Copy Token ID and save as environment variable in your ~/.bashrc or ~/.zshrc file.

$ vim ~/.bashrc
export DIGITALOCEAN_TOKEN="<paste-token>"

# OR
$ vim ~/.zshrc
export DIGITALOCEAN_TOKEN="<paste-token>"

Once the file is modified with the Token ID source the file to update the settings.

$ source ~/.bashrc
# OR for Zsh
$ source ~/.zshrc

Confirm the token can be accessed from the variable.

$ echo $DIGITALOCEAN_TOKEN

Step 3: Add your SSH Public Key to DigitalOcean

Add your SSH public key that will be copied to the instances for remote login. If you don’t have SSH keys generate with the command below.

$ ssh-keygen

SSH public key will be located in ~/.ssh/id_rsa.pub by default unless you specify custom path. You’ll copy the file contents to buffer and paste in the next section.

Navigate to Settings > Security > SSH keys > Add SSH Key

Save the key by clinking on “Add SSH Key”

Step 4: Create Terraform Code to create Droplet

Let’s create a directory where we’ll save our terraform code.

cd ~
mkdir digitalocean
cd digitalocean

Create deployment main.tf configuration file.

$ vim main.tf

Add provider definition.

terraform {
  required_providers {
    digitalocean = {
      source = "digitalocean/digitalocean"
    }
  }
}

Run the following command to initialize the project.

$ terraform init

Initializing the backend...

Initializing provider plugins...
- Reusing previous version of digitalocean/digitalocean from the dependency lock file
- Installing digitalocean/digitalocean v2.3.0...
- Installed digitalocean/digitalocean v2.3.0 (signed by a HashiCorp partner, key ID F82037E524B9C0E8)

Partner and community providers are signed by their developers.
If you'd like to know more about provider signing, you can read about it here:
https://www.terraform.io/docs/plugins/signing.html

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.

Add the extra sections to get SSH key fingerprint and create droplet.

# Get ssh key
data "digitalocean_ssh_key" "terraform" {
  name = "terraform"
}

# Create a droplet
resource "digitalocean_droplet" "ubuntu" {
    image = "ubuntu-20-04-x64"
    name = "ubuntu"
    region = "nyc1"
    size = "s-1vcpu-1gb" # https://developers.digitalocean.com/documentation/v2/#list-all-sizes
    private_networking = true
    ssh_keys = [
      data.digitalocean_ssh_key.terraform.id
    ]
}

Plan for the deployment.

$ terraform plan

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.ubuntu will be created
  + resource "digitalocean_droplet" "ubuntu" {
      + backups              = false
      + created_at           = (known after apply)
      + disk                 = (known after apply)
      + id                   = (known after apply)
      + image                = "ubuntu-20-04-x64"
      + ipv4_address         = (known after apply)
      + ipv4_address_private = (known after apply)
      + ipv6                 = false
      + ipv6_address         = (known after apply)
      + locked               = (known after apply)
      + memory               = (known after apply)
      + monitoring           = false
      + name                 = "ubuntu"
      + price_hourly         = (known after apply)
      + price_monthly        = (known after apply)
      + private_networking   = true
      + region               = "nyc1"
      + resize_disk          = true
      + size                 = "s-1vcpu-1gb"
      + ssh_keys             = [
          + "21266356",
        ]
      + status               = (known after apply)
      + urn                  = (known after apply)
      + vcpus                = (known after apply)
      + volume_ids           = (known after apply)
      + vpc_uuid             = (known after apply)
    }

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

Changes to Outputs:
  + serverip = (known after apply)

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

Note: You didn't specify an "-out" parameter to save this plan, so Terraform
can't guarantee that exactly these actions will be performed if
"terraform apply" is subsequently run.

Apply configuration to create droplet resource.

$ terraform apply -auto-approve
digitalocean_droplet.ubuntu: Creating...
digitalocean_droplet.ubuntu: Still creating... [10s elapsed]
digitalocean_droplet.ubuntu: Still creating... [20s elapsed]
digitalocean_droplet.ubuntu: Still creating... [30s elapsed]
digitalocean_droplet.ubuntu: Still creating... [40s elapsed]
digitalocean_droplet.ubuntu: Creation complete after 41s [id=219975305]

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

Outputs:

serverip = "161.35.62.31"

Confirm SSH access to the instance:

$ ssh [email protected]
Warning: Permanently added '161.35.62.31' (ECDSA) to the list of known hosts.
Enter passphrase for key '/Users/terraform/.ssh/id_rsa':
Welcome to Ubuntu 20.04.1 LTS (GNU/Linux 5.4.0-51-generic x86_64)

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

  System information as of Sat Dec  5 11:01:24 UTC 2020

  System load:  0.23              Users logged in:       0
  Usage of /:   5.1% of 24.06GB   IPv4 address for eth0: 161.35.62.31
  Memory usage: 18%               IPv4 address for eth0: 10.10.0.6
  Swap usage:   0%                IPv4 address for eth1: 10.116.0.3
  Processes:    103

1 update can be installed immediately.
0 of these updates are security updates.
To see these additional updates run: apt list --upgradable


The list of available updates is more than a week old.
To check for new updates run: sudo apt update


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.

[email protected]:~#

We can confirm the instance has been created and running on DigitalOcean Cloud Platform.

Destroying a resource with terraform

If you ever want to delete the droplet use the following command.

$ terraform destroy

Confirm resource deletion.

Terraform will perform the following actions:

  # digitalocean_droplet.ubuntu will be destroyed
  - resource "digitalocean_droplet" "ubuntu" {
      - backups              = false -> null
      - created_at           = "2020-12-08T12:58:32Z" -> null
      - disk                 = 25 -> null
      - id                   = "220446907" -> null
      - image                = "ubuntu-20-04-x64" -> null
      - ipv4_address         = "161.35.62.31" -> null
      - ipv4_address_private = "10.116.0.3" -> null
      - ipv6                 = false -> null
      - locked               = false -> null
      - memory               = 1024 -> null
      - monitoring           = false -> null
      - name                 = "ubuntu" -> null
      - price_hourly         = 0.00744 -> null
      - price_monthly        = 5 -> null
      - private_networking   = true -> null
      - region               = "nyc1" -> null
      - resize_disk          = true -> null
      - size                 = "s-1vcpu-1gb" -> null
      - ssh_keys             = [
          - "21266356",
        ] -> null
      - status               = "active" -> null
      - urn                  = "do:droplet:220446907" -> null
      - vcpus                = 1 -> null
      - volume_ids           = [] -> null
      - vpc_uuid             = "728b9b40-3c8b-41d0-8cb9-7fc62a860eb4" -> null
    }

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

Changes to Outputs:
  - serverip = "161.35.62.31" -> null

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

Resource deletion should complete in few seconds.

digitalocean_droplet.ubuntu: Destroying... [id=220446907]
digitalocean_droplet.ubuntu: Still destroying... [id=220446907, 10s elapsed]
digitalocean_droplet.ubuntu: Still destroying... [id=220446907, 20s elapsed]
digitalocean_droplet.ubuntu: Destruction complete after 26s

Destroy complete! Resources: 1 destroyed.

Check our terraform documentation on DigitalOcean provider use examples and explanations.

More guides:

How To Manage Docker Containers With Ansible

How To Run Rancher k3s Kubernetes in Docker Containers

How To Get Docker & Podman Container’s IP Address

Source link