Terraform – Install on Ubuntu Focal 20.04

This tutorial shows how to install Terraform on the Linux machine (Ubuntu Focal 20.04).

Check the Ubuntu release version

lsb_release -d

Update the apt package

sudo apt-get update

sudo apt-get install -y gnupg software-properties-common

Install the HashiCorp GPG key

wget -O- https://apt.releases.hashicorp.com/gpg | \
    gpg --dearmor | \
    sudo tee /usr/share/keyrings/hashicorp-archive-keyring.gpg

Verify the key’s fingerprint.

gpg --no-default-keyring \
    --keyring /usr/share/keyrings/hashicorp-archive-keyring.gpg \
    --fingerprint

Add Hashicorp Repository

echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] \
    https://apt.releases.hashicorp.com $(lsb_release -cs) main" | \
    sudo tee /etc/apt/sources.list.d/hashicorp.list

Install Terraform

sudo apt update

sudo apt-get install terraform

Verify the Installation

terraform -help

Enable Tab Completion

touch ~/.bashrc
terraform -install-autocomplete

Tutorial

Launch the nginx docker image using Terraform. You need to install Docker.

Write the Terraform script

mkdir terraform-test

cd terraform-test

vi main.tf
terraform {
  required_providers {
    docker = {
      source  = "kreuzwerker/docker"
      version = "~> 2.23.1"
    }
  }
}

provider "docker" {}

resource "docker_image" "nginx" {
  name         = "nginx:latest"
  keep_locally = false
}

resource "docker_container" "nginx" {
  image = docker_image.nginx.image_id
  name  = "test"
  ports {
    internal = 80
    external = 8080
  }
}

Initialize and Provision

terraform init

sudo terraform apply

docker container ls

Open the web browser and access http://{host-ip}:8080. You can see the nginx home page.

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s