V5 Loops in Terraform
For_Each
provider.tf file contents provider "aws" {
region = "us-west-2"
access_key = "xyz"
secret_key = "xyz"
}
Creating files using foreach block in terraform
main.tf file contents
main.tf file contents
variable "file_names" {
type = list
default = ["terraform.txt","ansible.txt","chef.txt","devops.txt"]
}
resource "local_file" "files" {
for_each = toset (var.file_names)
filename = each.key
content = "Hi "
}
Dynamic_Block
provider "aws" {
region = "us-west-2"
access_key = "xyz"
secret_key = "yzx"
}
variable "ports" {
type = list
default = ["80","443","8080","3128"]
}
resource "aws_security_group" "web-sg" {
name = "my-sg"
dynamic "ingress" {
for_each = var.ports
content {
from_port = ingress.value
to_port = ingress.value
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
}
Lab-Task
provider.tf file contents provider "aws" {
region = "us-west-2"
access_key = "xyz"
secret_key = "xyz"
}
main.tf file contents
resource "aws_instance" "web" {
ami = "ami-083ac7c7ecf9bb9b0"
instance_type = "t2.micro"
availability_zone = "us-west-2a"
tags = {
Name = "MyVM"
}
}
resource "aws_ebs_volume" "ebsvol1" {
availability_zone = "us-west-2a"
size = 40
tags = {
Name = "EBSVol1"
}
}
resource "aws_volume_attachment" "ebs_att" {
device_name = "/dev/sdh"
volume_id = aws_ebs_volume.ebsvol1.id
instance_id = aws_instance.web.id
}
output "Public-IP" {
value=aws_instance.web.public_ip
}
Presentation Link : Terraform_Loops
0 Comments