(Last Updated On: March 26, 2019)

This guide will help you install Terraform on Ubuntu 18.04 / CentOS 7. Terraform is an Infrastructure as code tool which allows you to easily manage cloud resources in a versioned manner. You use Terraform to build, change, and version infrastructure deployed on popular service providers. This tool is not cloud-agnostic and it supports custom in-house solutions.

With Terraform you can manage Cloud Compute, Networking, Load Balancers, DNS and so on using simple Declarative Programming Language. See the complete list of Terraform Providers. Complex changesets can be applied to your infrastructure with minimal human interaction

Install Terraform on Ubuntu 18.04 / CentOS 7

Terraform is distributed as a tarball on Github. Check the latest release on Terraform releases page before downloading below.

As of the writing of this article, the latest release is v0.11.13. Download it like below:

Ensure wget and unzip are installed

# Ubuntu
sudo apt-get install wget unzip

# CentOS
sudo yum install wget unzip

Then download the terraform archive.

export VER="0.11.13"
wget https://releases.hashicorp.com/terraform/${VER}/terraform_${VER}_linux_amd64.zip

Once downloaded, extract the archive:

$ unzip terraform_${VER}_linux_amd64.zip
Archive: terraform_0.11.13_linux_amd64.zip
inflating: terraform

This will create a terraform binary file on your working directory. Move this file to the directory/usr/local/bin.

sudo mv terraform /usr/local/bin/

This will make the tool accessible to all user accounts.

$ which terraform
/usr/local/bin/terraform

Confirm the version installed

$ terraform -v
Terraform v0.11.13

Verify that the tool works:

$ terraform
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
    push               Upload this Terraform module to Atlas to run
    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:
    debug              Debug output management (experimental)
    force-unlock       Manually unlock the terraform state
    state              Advanced state management

Using Terraform to Manage Infrastructure

Now that terraform is installed, let’s create a test project.

$ mkdir projects
$ cd projects

Create Terraform main configuration file.

touch main.tf

I’m doing a Test with AWS Provider but you can use other Providers for your projects. My terraform configuration provider section is as below.

$ vim main.tf

# Provider
 provider "aws" {
   access_key = ""
   secret_key = ""
   region = "us-west-1"
 }

Paste your AWS Access Key and Secret Key inside the access_key and secret_keysections respectively. You can also configure your AWS access credentials with AWS CLI tool.

When done, run terraform init to initialize a Terraform working directory.

$ terraform init
Initializing provider plugins…
Checking for available provider plugins on https://releases.hashicorp.com…
Downloading plugin for provider "aws" (2.1.0)…
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.aws: version = "~> 2.1"
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.

Terraform will automatically download provider configured to .terraform directory.

Let’s now add resource section to create AWS VPC and Subnet resources by editing the main.tf file.

# Provider
 provider "aws" {
   access_key = ""
   secret_key = ""
   region = ""
 }

# Retrieve the AZ where we want to create network resources
data "aws_availability_zones" "available" {}

# VPC Resource
resource "aws_vpc" "main" {
  cidr_block = "10.11.0.0/16"
  enable_dns_support = true
  enable_dns_hostnames = true
  tags {
    Name = "Test-VPC"
  }
  tags {
    Environment = "Test"
  }
}

# AWS subnet resource
resource "aws_subnet" "test" {
 vpc_id = "${aws_vpc.main.id}"
 cidr_block = "10.11.1.0/24"
 availability_zone = "${data.aws_availability_zones.available.names[0]}"
 map_public_ip_on_launch = "false"
 tags {
   Name = "Test_subnet1"
 }
}

Save the file after adding resource definitions and setting AWS variables then generate and show an execution plan.

$ terraform plan

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.

data.aws_availability_zones.available: Refreshing state...

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

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:

  + aws_subnet.test
      id:                               <computed>
      arn:                              <computed>
      assign_ipv6_address_on_creation:  "false"
      availability_zone:                "us-east-1a"
      availability_zone_id:             <computed>
      cidr_block:                       "10.11.1.0/24"
      ipv6_cidr_block:                  <computed>
      ipv6_cidr_block_association_id:   <computed>
      map_public_ip_on_launch:          "false"
      owner_id:                         <computed>
      tags.%:                           "1"
      tags.Name:                        "Test_subnet1"
      vpc_id:                           "${aws_vpc.main.id}"

  + aws_vpc.main
      id:                               <computed>
      arn:                              <computed>
      assign_generated_ipv6_cidr_block: "false"
      cidr_block:                       "10.11.0.0/16"
      default_network_acl_id:           <computed>
      default_route_table_id:           <computed>
      default_security_group_id:        <computed>
      dhcp_options_id:                  <computed>
      enable_classiclink:               <computed>
      enable_classiclink_dns_support:   <computed>
      enable_dns_hostnames:             "true"
      enable_dns_support:               "true"
      instance_tenancy:                 "default"
      ipv6_association_id:              <computed>
      ipv6_cidr_block:                  <computed>
      main_route_table_id:              <computed>
      owner_id:                         <computed>
      tags.%:                           "2"
      tags.Environment:                 "Test"
      tags.Name:                        "Test-VPC"


Plan: 2 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.

Finally build your Infrastructure with Terraform using terraform apply.

$ terraform apply

data.aws_availability_zones.available: Refreshing state...

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:

  + aws_subnet.test
      id:                               <computed>
      arn:                              <computed>
      assign_ipv6_address_on_creation:  "false"
      availability_zone:                "us-east-1a"
      availability_zone_id:             <computed>
      cidr_block:                       "10.11.1.0/24"
      ipv6_cidr_block:                  <computed>
      ipv6_cidr_block_association_id:   <computed>
      map_public_ip_on_launch:          "false"
      owner_id:                         <computed>
      tags.%:                           "1"
      tags.Name:                        "Test_subnet1"
      vpc_id:                           "${aws_vpc.main.id}"
...........................

Confirm changes to be made and type “yes” to initiate modifications.

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

A successful terraform run should print success message at the end.

Terraform state is saved to ./terraform.tfstate but the backend can be changed. You can confirm Infrastructure changes from AWS console.

Destroying Terraform Infrastructure

We have confirmed that our Terraform installation on CentOS 7 / Ubuntu 18.04 is working as expected. destroy Terraform-managed infrastructure by running terraform destroy command.

$ terraform destroy

aws_vpc.main: Refreshing state... (ID: vpc-0e94a7d72c02dab2b)
data.aws_availability_zones.available: Refreshing state...
aws_subnet.test: Refreshing state... (ID: subnet-0ad06c2e86542ddc1)

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:

  - aws_subnet.test

  - aws_vpc.main


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

If you don’t want confirmation prompt, use:

terraform destroy -auto-approve

Installing terraform on other systems:

How to Install Terraform on Fedora

Install and Use Terraform on Windows / Windows Server

Next Steps

Now that you have Terraform installed and tested, it is time to build infrastructure using a minimal Terraform configuration file. Terraform Use Cases is an interesting page to read for new users.

You may also be interested in:

How to Provision VMs on KVM with Terraform