Terraform

AWS provider

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = ">= 3.22.0"
    }
  }
}

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

State configuration

terraform {
  backend "s3" {
    region         = "<REGION>"
    bucket         = "<BUCKET NAME>"
    key            = "<FILENAME>.tfstate"
    dynamodb_table = "<TABLE NAME>"
    encrypt        = true
  }
}

Get AZs

data "aws_availability_zones" "available" {
}

Latest AMI

data "aws_ami" "latest-ubuntu" {
most_recent = true
owners = ["099720109477"] # Canonical

  filter {
      name   = "name"
      values = ["ubuntu/images/hvm-ssd/ubuntu-xenial-18.04-amd64-server-*"]
  }

  filter {
      name   = "virtualization-type"
      values = ["hvm"]
  }
}

Random string

resource "random_string" "suffix" {
  length  = 8
  special = false
}

Datasources

data "aws_vpc" "selected" {
  tags = {
    environment = var.environment
  }
}

data "aws_subnet_ids" "private" {
  vpc_id = data.aws_vpc.selected.id

  tags = {
    Name = "*private*"
  }
}

data "aws_subnet_ids" "public" {
  vpc_id = data.aws_vpc.selected.id

  tags = {
    Name = "*public*"
  }
}

vpc_zone_identifier = var.public == "true" ? data.aws_subnet_ids.public.ids : data.aws_subnet_ids.private.ids