Home » DevOps » Terraform Count Example

About 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).

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.


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.


# 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" : [
        "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.

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

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions


Notify of

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

Inline Feedbacks
View all comments