Terraform: Quick Start

This post explains how to run “hashicorp/terraform docker” using docker-compose.

You will be able to create an instance on AWS.

pre-requisite

IAM user with programmatic access is needed.

1. Dockerfile

Create a directory to mount the local files (Reference: Terraform With Docker).

FROM hashicorp/terraform:0.12.29

RUN mkdir /workspace
WORKDIR /workspace

2. docker-compose.yml

Pass the IAM info as environment variables, and mount the current directory.

version: '3'
services:
  terraform:
    build: .
    environment:
      AWS_ACCESS_KEY_ID: YOUR_ACCESS_ID
      AWS_SECRET_ACCESS_KEY: YOUR_SECRET_KEY
      AWS_DEFAULT_REGION: us-east-1
    volumes:
      - .:/workspace

3. main.tf

resource "aws_instance" "example" {
  ami = "ami-08f3d892de259504d"
  instance_type = "t1.micro"
}

The AMI ID refers to Amazon Linux 2 AMI (HVM), SSD Volume Type - ami-08f3d892de259504d (64-bit x86)

4. create & destroy instance

Probably, it is a good idea to setup an alias.

alias tf='docker-compose run terraform'
tf --version

Initialize terraform, confirm plan, then create the instance.

tf init
tf plan
tf apply

Delete the instance if you no longer need it.

tf destroy

Comments