How to Install and Configure Terraform on Ubuntu 18.04

Installing Terraform

 

Step 1: Downloading Terraform

First download the required packages in order to install Terraform on your system, To download the suitable package for your setup, visit, https://www.terraform.io/downloads.html

Step 2: Extracting Terraform Packages

Now extract the package which we downloaded from the previous step. 
In case, if the packages are downloaded in the ‘Downloads’ folder, use the below command. If it is not, replace it with your downloaded location.

mkdir -p ~/opt/terraform
unzip ~/Downloads/terraform_0.1.1_darwin_amd64.zip -d ~/opt/terraform

Step 3: Adding Path to Profile

Next, add your directory, ~/opt/terraform/bin to your path variable.
To add the path to your bash shell, open your profile.

sudo nano ~/.bash_profile

Now, add the following command at the end of the file.

export PATH=$PATH:~/opt/terraform/bin

Now that we have provided the exact path and made it as global, the Terraform command will be identified by all of your new bash sessions. To enable a new path, use the following command.

. .bash_profile
 

Testing Terraform:

To verify the terraform installation, run Terraform command in your terminal.

terraform

You should see an output like below.

Usage: terraform [-version] [-help] <command> [args]
The available commands for execution are listed below.
The most common, useful commands are shown first, followed by
less common or more advanced commands. If you're just getting
started with Terraform, stick with the common commands. For the
other commands, please read the help and docs before usage.
Common commands:
    apply              Builds or changes infrastructure
    console            Interactive console for Terraform interpolations
    destroy            Destroy Terraform-managed infrastructure
    env                Workspace management
    fmt                Rewrites config files to canonical format
    get                Download and install modules for the configuration
    graph              Create a visual graph of Terraform resources
    import             Import existing infrastructure into Terraform
    init               Initialize a Terraform working directory
    output             Read an output from a state file
    plan               Generate and show an execution plan
    providers          Prints a tree of the providers used in the configuration
    refresh            Update local state file against real resources
    show               Inspect Terraform state or plan
    taint              Manually mark a resource for recreation
    untaint            Manually unmark a resource as tainted
    validate           Validates the Terraform files
    version            Prints the Terraform version
    workspace          Workspace management
 All other commands:
    0.12upgrade        Rewrites pre-0.12 module source code for v0.12
    debug              Debug output management (experimental)
    force-unlock       Manually unlock the terraform state
    push               Obsolete command for Terraform Enterprise legacy (v1)
    state              Advanced state management

Next, it is time to describe the infrastructure. 

Let’s discuss the resources:

 

Variable Resources

There are different kinds of variables are used to define the server details, let us now look at some of the major variable resources.
do_token: DigitalOcean’s Personal Access Token which will be generated to your account. 
pub_key: Public key which we created in the previous section needs to be added in the Digital account. 
pvt_key: Private key which we created in the above step is used to establish a connection in the remote server.
ssh_fingerprint: The above-created fingerprint of the SSH key is the simplified form of the encrypted key. 

DigitalOcean Resources

Every cloud provider differs in its identification from one cloud provider to others. Below are widely used types of resources in DigitalOcean. 
digitalocean_domain: A human-friendly name that is more commonly used to associate with internet resources.
digitalocean_droplet: The droplets here simply refers to the servers you use, either standalone or part of a larger. 
digitalocean_record: DNS records that are used to map the resource with its name. 

 

Creating a Droplet

 

Step: 1

As known, terraform supports numerous providers and here we are going to make Terraform interact with the DigitalOcean cloud provider. 
Build a file called provider.tf to access the following variables:

sudo nano provider.tf

Include the following command into the file:

variable "do_token" {}
variable "pub_key" {}
variable "pvt_key" {}
variable "ssh_fingerprint" {}
provider "digitalocean" {
  token = "${var.do_token}"
}

Note: Here, you need to declare the variables which we are going to use in the following configurations.

 

Step: 2

Create the Terraform variables configuration file for storing the pre-existing values like a fingerprint, public key, token and so forth to use it directly at the time of executing the Terraform plan command.

sudo nano terraform.tfvars

Include the following command into the file:

do_token = "213af4c4652737ef1fa24bb11f4638517d729551ca284b12658bb28307b506a4"
ssh_fingerprint = "89:ff:cb:c1:20:97:f8:fe:68:77:72:ce:fe:2a:cf:b7"
pub_key = "~/.ssh/id_rsa.pub"
pvt_key = "~/.ssh/id_rsa"

Note: You can also use the same values for creating other droplets and services. (These values will be applicable only till you retain the same token). It is to be made sure that the values of the above-provided variables must not be shared with any other parties for security purpose.

Step: 3

Create a new Terraform-droplet configuration file called sample.tf:

sudo nano sample.tf

Insert the following command in order to define the droplet resource:

resource "digitalocean_droplet" "sample" {
    image = "ubuntu-18-04-x64"
    name = "sample"
    region = "nyc1"
    size = "1GB"
    private_networking = true
    ssh_keys = [
      "${var.ssh_fingerprint}"
    ]

Here is the breakdown of the above lines.
The first lines explain that the droplet has been created in DigitalOcean called ‘sample’. Following the second line, the Image refers to the operating system, Name refers to the name of the created droplet, Region is nothing but the location of the data centre, and size, the RAM size. These are the attributes that later will be accessed by DigitalOcean’s API. 
Add the following lines at the end of the file for the Terraform to establish a connection with the remote server via SSH:

 connection {
      user = "root"
      type = "ssh"
      private_key = "${file(var.pvt_key)}"
      timeout = "2m"
  }

As the connection has been established, it’s possible to install any services like Nginx, Apache, Varnish, etc. using the ‘remote-exec’ provisioner.
To know more about the droplet resources, refer to the official Terraform documentation: https://www.terraform.io/docs/providers/do/r/droplet.html

Running Terraform Script  to Create a Droplet

 

Step: 1

Initialize the terraform

terraform init

You shall see an output like below:

Output
Initializing the backend...
Initializing provider plugins...
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.12"
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.
 

Step: 2

For checking the syntax errors for all of your configuration files, use the below command.

terraform validate
Output
Success! The configuration is valid.
 

Step: 3

Next, run the terraform plan command to start the Terraform-droplet creation.

terraform plan
Output
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.testing will be created
  + resource "digitalocean_droplet" "sample" {
      + backups              = false
      + created_at           = (known after apply)
      + disk                 = (known after apply)
      + id                   = (known after apply)
      + image                = "ubuntu-18-04-x64"
      + ipv4_address         = (known after apply)
      + ipv4_address_private = (known after apply)
      + ipv6                 = false
      + ipv6_address         = (known after apply)
      + ipv6_address_private = (known after apply)
      + locked               = (known after apply)
      + memory               = (known after apply)
      + monitoring           = false
      + name                 = "testing"
      + price_hourly         = (known after apply)
      + price_monthly        = (known after apply)
      + private_networking   = true
      + region               = "nyc1"
      + resize_disk          = true
      + size                 = "1gb"
      + ssh_keys             = [
          + "89:ff:cb:c1:20:97:f8:fe:68:77:72:ce:fe:2a:cf:b7",
        ]
      + status               = (known after apply)
      + urn                  = (known after apply)
      + vcpus                = (known after apply)
      + volume_ids           = (known after apply)
    }
Plan: 1 to add, 0 to change, 0 to destroy.
-----------------------------------------------------------------------
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.
 

Step: 4

Now that we have executed the Terraform plan, let us now proceed with the final step.

terraform apply
Output
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.testing will be created
  + resource "digitalocean_droplet" "sample" {
      + backups              = false
      + created_at           = (known after apply)
      + disk                 = (known after apply)
      + id                   = (known after apply)
      + image                = "ubuntu-18-04-x64"
      + ipv4_address         = (known after apply)
      + ipv4_address_private = (known after apply)
      + ipv6                 = false
      + ipv6_address         = (known after apply)
      + ipv6_address_private = (known after apply)
      + locked               = (known after apply)
      + memory               = (known after apply)
      + monitoring           = false
      + name                 = "testing"
      + price_hourly         = (known after apply)
      + price_monthly        = (known after apply)
      + private_networking   = true
      + region               = "nyc1"
      + resize_disk          = true
      + size                 = "1gb"
      + ssh_keys             = [
          + "89:ff:cb:c1:20:97:f8:fe:68:77:72:ce:fe:2a:cf:b7",
        ]
      + status               = (known after apply)
      + urn                  = (known after apply)
      + vcpus                = (known after apply)
      + volume_ids           = (known after apply)
    }
Plan: 1 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_droplet.testing: Creating...
digitalocean_droplet.testing: Still creating... [10s elapsed]
digitalocean_droplet.testing: Still creating... [20s elapsed]
digitalocean_droplet.testing: Creation complete after 28s [id=173296706]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

By now, Terraform has created a new droplet called sample.
Hereby, we have discussed Terraform, it’s usage, features and basic commands. To know about the how-to process of installing Magento using Terraform, read our blog post, How to Install Magento using Terraform on Ubuntu system? We have also dealt with the end-to-end installation and droplet creation process of Terraform in the cloud provider, DigitalOcean. By using this procedure, you can create configuration files that best describes your infrastructure. It is also possible to create multiple droplets in your configuration provider (DigitalOcean).

 
 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top