Terraform

Terraform Count Example

Hello. In this tutorial, we will understand the count variable in Terraform.

1. Introduction

Terraform is an open-source tool developed by HashiCorp for building, changing, and versioning the infrastructure safely and efficiently. It is used to manage the infrastructure of the popular cloud service providers and custom in-house solutions. It helps manage both low-level (Compute, Storage, Networking, etc.) and high-level components (such as SaaS, DNS, etc.) Terraform deployment automation is divided into different sections i.e. –

  • IaaC – IaaC is popularly known as the Infrastructure as a Code wherein the infrastructure is described using a high-level configuration syntax. This allows a blueprint of the infrastructure which can be deployed, versioned, and shared for re-use
  • Execution Plans – Terraform has a planning step where it generates an execution plan. The execution plan tells the administrator what Terraform will do once applied and helps to avoid any surprises when it creates the infrastructure
  • Resource Graph – Terraform builds a graph of all the resources and parallelizes the creation and modification of non-dependent resources. This offers insights into learning the dependencies in their infrastructure
  • Change Automation – Terraform allows to apply of complex changesets to the infrastructure with minimal human intervention

1.1 Configuration language

Terraform has its configuration language designed to meet the infrastructure automation requirements. The main purpose of this language is to declare resources and a group of resources (gathered into a module) represents a larger unit of configuration. Language syntax consists of a few elements i.e. – Blocks, Arguments, and Expressions.

  • Blocks – Containers for other contents and represents the object configuration
  • Arguments – Assign a value to the name and appear within the blocks
  • Expressions – Represents a single value, referenced value, or combination of other values

1.2 Steps

To create the infrastructure via the Terraform scripts following commands need to be executed in a sequence. However, details and actions may differ between workflows.

  • terraform init – Initializing the new or existing terraform configuration
  • terraform plan – Generate the execution plan from the resources specified in the file
  • terraform apply – Create the infrastructure from the resources specified in the file
  • terraform destroy – Destroy the created infrastructure
terraform count - workflow
Fig. 1: Terraform workflow

2. Terraform Count Example

2.1 How to use count?

In terraform, we use the count variable but to use it we first need to declare the collections in the terraform file. Let us create a collection variable named usernames of type string.

variables.tf

variable "aws_access_key" {
  type        = string
  description = "cli user access key"
  default     = "YOUR_ACCESS_KEY"
}
variable "aws_secret_key" {
  type        = string
  description = "cli user secret key"
  default     = "YOUR_SECRET_KEY"
}
variable "region" {
  type        = string
  description = "iam region"
  default     = "ap-south-1"
}
variable "usernames" {
  type        = list(any)
  description = "list of users"
  default     = ["geek1", "geek2"]
}

2.2 How to iterate over the collection?

To use the usernames collection created in the above step let us create a resource. Here is the complete terraform file which will create an IAM policy, two IAM users, and attach the created policy to the users upon apply.

iam.tf

# policy creation
resource "aws_iam_policy" "terraform-ec2-read-access" {
  name        = "terraform-ec2-read-access"
  description = "ec2-read-access"
  /* jsonencode better than EOF. EOF breaks the new terraform code. */
  policy = jsonencode({
    "Version" : "2012-10-17",
    "Statement" : [
      {
        "Sid" : "VisualEditor0",
        "Effect" : "Allow",
        "Action" : [
          "ec2:GetDefaultCreditSpecification",
          "ec2:GetManagedPrefixListEntries",
          "ec2:DescribeTags",
          "ec2:GetCoipPoolUsage",
          "ec2:DescribeVpnConnections",
          "ec2:GetEbsEncryptionByDefault",
          "ec2:GetCapacityReservationUsage",
          "ec2:DescribeVolumesModifications",
          "ec2:GetHostReservationPurchasePreview",
          "ec2:DescribeFastSnapshotRestores",
          "ec2:GetConsoleScreenshot",
          "ec2:GetReservedInstancesExchangeQuote",
          "ec2:GetAssociatedEnclaveCertificateIamRoles",
          "ec2:GetConsoleOutput",
          "ec2:GetPasswordData",
          "ec2:GetLaunchTemplateData",
          "ec2:DescribeScheduledInstances",
          "ec2:GetSerialConsoleAccessStatus",
          "ec2:GetAssociatedIpv6PoolCidrs",
          "ec2:GetFlowLogsIntegrationTemplate",
          "ec2:DescribeScheduledInstanceAvailability",
          "ec2:GetManagedPrefixListAssociations",
          "ec2:GetEbsDefaultKmsKeyId",
          "ec2:DescribeElasticGpus"
        ],
        "Resource" : "*"
      }
    ]
  })
  tags = {
    "createdby" = "terraform"
  }
}

# user creation
resource "aws_iam_user" "newusers" {
  count = length(var.usernames)
  name  = element(var.usernames, count.index)
  tags = {
    "createdby" = "terraform"
  }
}

# attaching policy to the user
resource "aws_iam_user_policy_attachment" "terraform-user-policy-attachment" {
  count      = length(var.usernames)
  user       = element(aws_iam_user.newusers.*.name, count.index)
  policy_arn = aws_iam_policy.terraform-ec2-read-access.arn
}

3. Apply this terraform

Before apply remember to create the provider.tf responsible for interacting with the aws environment. Once you apply this terraform configuration using the terraform apply command, it will create the two IAM users on the aws environment named geek1 and geek2 as shown below and assign them with an ec2 read-access policy also created via terraform script.

terraform count - IAM users
Fig. 2: Creating IAM users

That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning, do not forget to share, and remember to clean up the environment after practice!

4. Summary

In this tutorial, we learned an introduction to Terraform, saw the usage of count variable in a collection of string datatype, and create a simple terraform script to practically understand the usage of the variable. You can download the source code from the Downloads section.

5. Download the Project

This was a tutorial on understanding the usage of count variable in terraform scripting.

Download
You can download the full source code of this example here: Terraform Count Example

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button