4 December 2018


by mo

Terraform makes it easy to describe your desired infrastructure as code. It will take care of invoking the appropriate API’s to turn your description of your infrastructure (the code) into actual running infrastructure.

To work with terraform you must specify a provider. There are multiple providers that terraform can work with. In the example below, I am using the AWS provider.

provider "aws" {
  access_key = "ACCESS KEY"
  secret_key = "SECRET"
  region     = "us-east-1"

Hardcoding your credentials sucks. terraform provides variables that can be fed into the runtime via environment variables or CLI flags.

variable "access_key" {}
variable "secret_key" {}
variable "region" {
  default = "us-east-1"
variable "amis" {
  type = "map"
  default = {
    "us-east-1" = "ami-b374d5a5"
    "us-east-2" = "ami-4b32be2b"
provider "aws" {
  access_key = "${var.access_key}"
  secret_key = "${var.secret_key}"
  region     = "${var.region}"

To provide the access_token and secret_key in the example above you can provide a terraform.tfvars file.


access_key = "my_access_key"
secret_key = "my_secret_key"

Or you can invoke terraform with the -var 'access_key=my_access_key' -var 'secret_key=my_secret_key' options.

With the basic configuration out of the way we can now start to describe our desired infrastructure.

In the example below, I have described the need for a S3 bucket named mokha-terraform, and a single EC2 instance that needs to be created after the S3 bucket, and an Elastic IP that will point to the single EC2 instance.

resource "aws_s3_bucket" "example" {
  bucket = "mokha-terraform"
  acl = "private"

resource "aws_instance" "example" {
  ami = "${lookup(var.amis, var.region)}"
  instance_type = "t2.micro"
  depends_on = ["aws_s3_bucket.example"]

resource "aws_eip" "ip" {
  instance = "${aws_instance.example.id}"

Run terraform apply to build the infrastructure.

To delete your infrastructure you can run terraform destroy.

Terraform uses a language called HCL as the DSL for the description of your infrastructure. The new GitHub Actions DSL is based on HCL.

To get started with Terraform try the Getting Started section of the docs.

Peace on 🌎