Programster's Blog

Tutorials focusing on Linux, programming, and open-source

Terraform Cheatsheet

Installation

The following chained commands will install the Hashicorp GPG key, add their PPA, and use that to install Terraform.

curl -fsSL https://apt.releases.hashicorp.com/gpg | sudo apt-key add - \
  && sudo apt-add-repository "deb [arch=amd64] https://apt.releases.hashicorp.com $(lsb_release -cs) main" \
  && sudo apt-get update && sudo apt-get install terraform -y

This will install Terraform version 1.0.0 at the time of updating this post.

Alternative Snap Installation

You can install the the terraform CLI tool con Ubuntu 20.04 by running:

sudo snap install terraform

... however, this will install Terraform v0.11.11 which will not work with some of the examples I provide, which need 0.12+.

File Extension and "Language"

Terraform files should have the .tf extension, and the "language" is called HCL (Hashicorp Configuration language).

One can use other tools like "Packer" to create custom AMIs.

Commands

Terraform Plan

The terraform plan command will tell you what changes are going to be made. Run this command before running terraform apply, which actually applies the changes.

Gitignore

Terraform will create the following files/folders that you may wish to add to your .gitignore file.

  • .terraform
  • .tfstate
  • .tfstate.backup

Terraform Apply

  • Run terraform apply to apply the changes that terraform plan says it would make.

Terraform Init

  • Sets up the area for terraform.
  • Can be run multiple times without issue.

Terraform Destroy

Run terraform destroy to completely remove anything that terraform set up.

Terraform Graph

  • Run the terraform graph command to map out the dependencies in your terraform setup. This will be output in DOT language which you can visualize by using GraphvizOnline.

Terraform Taint

  • Run the terraform taint command to mark a resource as "tainted". This allows you to force it to be replaced the next time you run terraform plan and terraform apply.
    • This is useful when you push an update to a docker image, which an EC2 image uses, but only fetches it when it is getting deployed etc.
    • Example usage: terraform taint aws_instance.my_compute_instance

AWS Authentication

To use terraform with AWS, you will need to provide it with your access key and secret. You can do this by running:

export AWS_ACCESS_KEY_ID=yourKeyId
export AWS_SECRET_ACCESS_KEY=yourKeySecret

Basic Example

The following terraform file will deploy a basic webserver (in London) that runs on port 8080 and will just respond with "Hello World". To "run" it, execute terraform apply.

provider "aws" {
  region = "eu-west-2"
}

# Create security group to allow port 8080
resource "aws_security_group" "instance" {
  name = "terraform-example-instance"

  ingress {
    from_port   = 8080
    to_port     = 8080
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

# Create the ubuntu 20.04 EC2 webserver resource 
# that uses the above security group
resource "aws_instance" "example" {
  ami                    = "ami-05c424d59413a2876"
  instance_type          = "t2.micro"
  vpc_security_group_ids = [aws_security_group.instance.id]


  user_data = <<-EOF
              #!/bin/bash
              /usr/bin/sleep 10
              /usr/bin/echo "Hello, World" > index.html
              /usr/bin/nohup /usr/bin/busybox httpd -f -p 8080 &
              EOF

  tags = {
    Name = "terraform-example"
  }
}

If you wish to change the region, you will also need to change the AMI ID as AMIs are tied to regions.

After executing that successfully, log into your amazon web console, find the instance to find its IP address and go to that in your browser with :8080 on the end.

You should see "Hello World" in your browser. If it doesn't appear, just wait a bit. It takes quite a while before its ready, especially after I had to put in a sleep to make the script work.

Variables

Variables can be defined like so:

variable "aws_region" {
    type = string
    description = "The region to deploy to. E.g. eu-west-2 for London."
    default = "eu-west-2"
}

You don't have to provide a default or description. They just help when it comes to someone specifying the values.

Supported Types

  • string
  • number
  • bool
  • list - a sequence of values, like ["us-west-1a", "us-west-1c"]. Elements in a list or tuple are identified by consecutive whole numbers, starting with zero.
  • tuple (alias of list)
  • map - a group of values identified by named labels. E.g. {name = "Mabel", age = 52}
  • object - alias of map

Outputs

After you create resources using Terraform, you will likely need to know their names/identifiers to then start using them. E.g. you need to know the IP address of the EC2 server you just deployed. You do this by declaring an output block. E.g.

output "my_ec2_ip" {
    value = aws_eip.my_elastic_ip.public_ip
}

This will cause them to be spat out at the end of performing a terraform apply operation.

Sensitive Outputs

You can mark some outputs as sensitive so that they will be hidden from the output. Some attributes, like AWS IAM credentials have to be marked as sensitive in order to have them as an output, otherwise terraform apply won't even run. In order to be able to retrieve these sensitive values, you have to execute:

terraform show -json

terraform show without the -json flag won't work and will just show you the outputs with the sensitive details hidden again

That will output a massive JSON dump from which you would have to find your sensitive values. Luckily, you can save yourself a lot of effort trying to find the needle with the help of jq like so:

terraform show -json | jq  '.values.outputs.name_of_my_output'

E.g. if the name of your output was my_super_secret_thing, then you would need:

terraform show -json | jq  '.values.outputs.my_super_secret_thing'

... or if you just want to see all of the outputs, you can use:

terraform show -json | jq  '.values.outputs'

String Substitution

This is best demonstrated with an example. Below, I am creating the value by using both a dynamic resource ID, and an input variable, with fixed/known string content

output "ecr_registry" {
    value = "${aws_ecr_repository.compute_engine_ecr.registry_id}.dkr.ecr.${var.aws_region}.amazonaws.com"
}

References

Last updated: 24th June 2021
First published: 24th September 2020