[Terraform] Basic

Crash course: https://www.youtube.com/watch?v=SLB_c_ayRMo

Concepts

  • Provider: platforms the TF code will be based on. (AWS, Docker, etc)
  • Resources
1
2
3
4
5
6
7
8
9
10
provider "aws" {
region = "us-east-1"
access_key = "..."
secret_key = "..."
}

resource "<RESOURCE_TYPE> <RESOURCE_NAME>" {
ami = "AMI_ID"
instance_type = "t2.micro"
}
  • terraform init: initialize and download the api plugins.
  • terraform plan: prints out details on what will happen
  • terraform apply (--auto-approve): apply the plan
  • terraform destroy: destroy the entire infrastructure

Re-run terraform apply won’t create another resource. Terraform files are like infrastructure instructions on what the infrastructure should look like in the end.
The order of the code doesn’t matter

create aws vpc

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
resource "aws_vpc" "first-vpc" {
cidr_block = "10.0.1.0/16"
tags = {
Name = "production"
}
}

resource "aws_subnet" "subnet-1" {
vpc_id = aws_vpc.first-vpc.id # variable: reference
cidr_block = "10.0.1.0/24"

tags = {
Name = "prod-subnet"
}
}

terraform.tfstate file: do not mess around with it. It tracks the current state.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# 1. Create a VPC
resource "aws_vpc" "prod-vpc" {
cidr_block = "10.0.0.0/16"
tags = {
Name = "production"
}
}

# 2. Create an API Gateway
resource "aws_internet_gateway" "gw" {
vpc_id = aws_vpc.prod-vpc.id
}

# 3. Create custom route table
resource "aws_route_table" "prod-route-table" {
vpc_id = aws_vpc.prod-vpc.id

route {
cidr_block = "0.0.0.0/0" # route all traffic to gateway
gateway_id = aws_internet_gateway.gw.id
}

route {
ipv6_cidr_block = "::/0"
egress_only_gateway_id = aws_internet_gateway.gw.id
}

tags = {
Name = "prod"
}
}

# 4. Create a subnet
resource "aws_subnet" "subnet-1" {
vpc_id = aws_vpc.prod-vpc-vpc.id # variable: reference
cidr_block = "10.0.1.0/24"
availability_zone = "us-east-1a"

tags = {
Name = "prod-subnet"
}
}

# 5. Associate subnet with Route Table
resource "aws_route_table_association" "a" {

}