Day 69 - Meta-Arguments in Terraform
Meta-arguments in Terraform are special configuration settings that can be applied to resources and modules. They provide additional functionality and control over how resources are created and managed. Meta-arguments enable you to customize resource behavior, handle resource dependencies, and iterate over sets or maps to create multiple instances.
Here are some commonly used meta-arguments in Terraform:
count: Thecountmeta-argument allows you to create multiple instances of a resource based on a numeric value. It takes an integer value and generates a specified number of resource instances. It is useful when you need to create multiple similar resources, such as multiple EC2 instances or multiple subnets.
For example :
create a terraform file using below code :
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.16"
}
}
required_version = ">= 1.2.0"
}
provider "aws" {
region = "us-east-1"
}
resource "aws_instance" "server" {
count = 4
ami = "ami-053b0d53c279acc90"
instance_type = "t2.micro"
tags = {
Name = "Server ${count.index}"
}
}
In this code , the count meta-argument is used to create four instances of an AWS EC2 server. The count.index interpolation function is used within the tags block to assign a unique name to each instance based on the index.
Then run terraform init , terraform plan , terraform apply .



it will create 4 instances.

for_each: Thefor_eachmeta-argument allows you to create multiple instances of a resource based on a set or map of values. It iterates over each element in the set or map and creates a separate resource instance for each element. It is handy when you want to dynamically create resources based on a set of configurations or when you need to manage resources individually.terraform { required_providers { aws = { source = "hashicorp/aws" version = "~> 4.16" } } required_version = ">= 1.2.0" } provider "aws" { region = "us-east-1" } locals { ami_ids = toset([ "ami-053b0d53c279acc90", "ami-06b09bfacae1453cb", ]) } resource "aws_instance" "server" { for_each = local.ami_ids ami = each.key instance_type = "t2.micro" tags = { Name = "Server ${each.key}" } }In this code snippet, the
for_eachmeta-argument is used along with a local variableami_ids. Theami_idslocal variable is defined as a set of AMI IDs. Thefor_eachblock iterates over each AMI ID in the set and creates an AWS EC2 server instance for each AMI ID. Theeach.keyrepresents the current AMI ID being iterated.
Then run terraform init , terraform plan , terraform apply . It will create 2 instances.

That was all for today. if you have any queries/suggestions please write in comment. See you another day with another challenge.



