Meta-Arguments in Terraform

Day 69 of #90daysofdevops challenge

Meta-Arguments in Terraform

When you define a resource block in Terraform, by default, this specifies one resource that will be created. To manage several of the same resources, you can use either count or for_each, which removes the need to write a separate block of code for each one. Using these options reduces overhead and makes your code neater.

Count is what is known as a ‘meta-argument’ defined by the Terraform language. Meta-arguments help achieve certain requirements within the resource block.

Count

The count meta-argument accepts a whole number and creates the number of instances of the resource specified.

When each instance is created, it has its own distinct infrastructure object associated with it, so each can be managed separately. When the configuration is applied, each object can be created, destroyed, or updated as appropriate.

eg.

terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.16"
}
}
required_version = ">= 1.2.0"
}
provider "aws" {
region = "ap-south-1"
}
resource "aws_instance" "server" {
count = 4
ami = "ami-053b0d53c279acc90"
instance_type = "t2.micro"
tags = {
Name = "Server ${count.index}"
}
}

for_each

Like the count argument, the for_each meta-argument creates multiple instances of a module or resource block. However, instead of specifying the number of resources, the for_each meta-argument accepts a map or a set of strings. This is useful when multiple resources are required that have different values. Consider our Active Directory groups example, with each group requiring a different owner.

  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-0889a44b331db0194",
    "ami-007855ac798b5175e",
  ])
}

resource "aws_instance" "server" {
  for_each = local.ami_ids
  ami           = each.key
  instance_type = "t2.micro"
  tags = {
    Name = "Server ${each.key}"
  }
}

Task: Create the above Infrastructure as code and demonstrate the use of Count and for_each.

Count:

Copy the code written at the count block and paste it into the main.tf file.

Now, run terraform init, plan and apply.

Let’s check our output.

for_each:

Copy the code written at the for_each block and paste it into the main.tf file.

Now, run terraform init, plan and apply.

Let’s check our output.


Thank you for enjoying my DevOps blog! Your positive response fuels my passion to dive deeper into technology and innovation.

Stay tuned for more captivating DevOps articles, where we'll explore this dynamic field together. Follow me on Hashnode and connect on LinkedIn (https://www.linkedin.com/in/som-shanker-pandey/) for the latest updates and discussions.

Did you find this article valuable?

Support Som Pandey's blog by becoming a sponsor. Any amount is appreciated!