Introduction#

Github this shows some basic concepts of terraform

  • Workspace
  • Backend such as S3
  • Provisioner

Different Workspace#

terraform workspace list

create a dev workspace

terraform workspace new prod

create a prod workspace

terraform workspace new dev

Pass Variables#

it is possible to access workspace in main.tf as

locals {
instance_name = "${terraform.workspace}-instance"
}

var.instance_type are different for dev and prod environments (workspace), and passed from dev.tfvars and prod.tfvars.

resource "aws_instance" "webserver" {
ami = "ami-0b0dcb5067f052a63"
instance_type = var.instance_type
subnet_id = aws_subnet.publicsubnet.id
tags = {
"Name" = local.instance_name
}
}

create variables.tf

variable "instance_type" {
type = string
}

create dev.tfvars

instance_type = 't2.medium'

create prod.tfvars

instance_type = 't3.medium'

then pass variables

terraform apply -var-file=def.tfvars

Deploy#

terraform init

and the apply

terraform apply -var-file dev.tfvars

and

terraform apply -var-file prod.tfvars

Backend S3#

create a bucket and configure in main.tf

terraform {
backend "s3" {
bucket = "terraform-backend-090688"
key = "terraform/"
region = "us-east-1"
}
required_providers {
aws = {
source = "hashicorp/aws"
version = "~>4.0.0"
}
}
}

then command, assume no state at this moment

terraform apply

wait for the statefile uploaded in the s3 bucket and there is not statefile stored in local.

Provisioner#

this is similar to EC2 UserData which means we can provide commands, data to EC2 or other compute resources. Here, echo command will run from the local machine, and the content will be upload to the EC2 in AWS.

resource "aws_instance" "webserver" {
ami = "ami-0b0dcb5067f052a63"
instance_type = "t2.medium"
subnet_id = aws_subnet.publicsubnet.id
tags = {
"Name" = "webserver"
}
provisioner "local-exec" {
command = "echo ${self.public_ip} > public_ip.txt"
}
provisioner "file" {
content = "hello haitran"
destination = "/home/ec2-user/"
}
}