day-05-Terraform
Day-05
Terraform For Loops, Lists and Count Meta-Argument
Step-00: Pre-requisite Note
- We are using
default vpc
inap-northeast-1
region
Step-01: Introduction
Terrafrom Meta-Argument:
count
Terraform Lists & Map
List(string)
map(string)
Terraform for loops
for loop with list
for loop with map
for loop with Map advanced
Splat Operators
Legacy splat operator .*.
Generalized Splat Operator (latest)
Understand terraform generic splat expression [*] when dealing with
count
Meta-Argument and multiple output values.
Step-02: c1-versions.tf
No changes
step-03: c2-variables.tf
- Lists and Maps
# AWS EC2 Instance type -List
variable "instance_type_list" {
description = "ec2 instance type declaring in the list"
type = list(string)
default = ["t3.micro", "t3.small"]
}
# AWS EC2 Instance type - Map
variable "instance_type_map" {
description = "ec2 instance type declaring it in the Map"
type = map(string)
default = {
"dev" = "t3.micro"
"qa" = "t3.small"
"prod" = "t3.large"
}
}
Step-04: c3-ec2securitygroups.tf
and c4-ami-datasource.tf
- No changes to both the files
Step-05: c5-ec2instance.tf
# How to reference List values ?
instance_type =var.instance_type_list[1]
# How to reference Map Values ?
instance_type = var.instance_type_map["prod"]
# Meta Argument count
count =2
# count.index
tags = {
"name" = "count-demo-${count.index}"
}
Step-06: c6-outpts.tf
for loop with list
for loop with Map
for loop with Map advanced
# Output - for loop with List
output "for_output_list" {
description = "Gor loop with List"
value = [for instance in aws_instance.myec2vm: instance.public_dns]
}
# Output - for loop with map
output "for_output_map" {
description = "for loop with map"
value = {for instance in aws_instance.myec2vm: instance.id=> instance.public_dns}
}
Step-07: Execute the terraform commands
terraform init
-> terraform validate
-> terraform plan
-> terraform apply
or terraform apply --auto-approve
Observations:
terraform plan
-> play with Lists and Maps for instance_type
terraform apply
-> two ec2 instances (count=2
) of a resource myec2vm will be created
-> count.index
will start from 0 and end with 1 for VM names
-> Review outputs in detail (for loop with list, maps)
Step-08: Clean-Up
#terraform destroy
terraform destroy --auto-approve
#Files
rm -rf .terraform*
rm -rf terraform.tfstate