Variables

We can start to use variables to make our configuration more dynamic.

File cloudcasts.tf:

1variable infra_env {
2 type = string
3 description = "infrastructure environment"
4}
5 
6variable default_region {
7 type = string
8 description = "the region this infrastructure is in"
9 default = "us-east-2"
10}
11 
12variable instance_size {
13 type = string
14 description = "ec2 web server size"
15 default = "t3.small"
16}

Two of these variables have a default value, and we can let Terraform use the defaults. The third infra_env needs defining.

We can pass it in via cli:

1terraform plan -var 'infra_env=staging'

We can create a *.tfvars file:

1# file variables.tfvars
2infra_env="staging"

Then we can run terraform plan -var-file variables.tfvars.

We can create a file ending in *.auto.tfvars, it will be pulled in automatically:

1# file variables.auto.tfvars
2infra_env="staging"

Then we don't need any extra flags when running terraform commands, such as terraform plan!

Updating Resources

And of course, we should use those variables in our defined resources:

1  
2 # File cloudcasts.tf
3  
4 resource "aws_instance" "cloudcasts_web" {
5 ami = data.aws_ami.app.id
6- instance_type = "t3.small"
7+ instance_type = var.instance_size
8  
9 root_block_device {
10 volume_size = 8 # GB
11 volume_type = "gp3"
12 }
13  
14 tags = {
15- Name = "cloudcasts-staging-web"
16+ Name = "cloudcasts-${var.infra_env}-web"
17 Project = "cloudcasts.io"
18- Environment = "staging"
19+ Environment = var.infra_env
20 ManagedBy = "terraform"
21 }
22 }
23  
24 resource "aws_eip" "cloudcasts_addr" {
25 vpc = true
26  
27 tags = {
28- Name = "cloudcasts-staging-web-address"
29+ Name = "cloudcasts-${var.infra_env}-web-address"
30 Project = "cloudcasts.io"
31- Environment = "staging"
32+ Environment = var.infra_env
33 ManagedBy = "terraform"
34 }
35 }
36  
37 resource "aws_eip_association" "eip_assoc" {
38 instance_id = aws_instance.cloudcasts_web.id
39 allocation_id = aws_eip.cloudcasts_addr.id
40 }

Run it:

1terraform plan -var-file variables.tfvars
2terraform apply -var-file variables.tfvars

Don't miss out

Sign up to learn when new content is released! Courses are in production now.