Working with Loops
Learn how to perform repeated tasks using loops.
We'll cover the following...
Overview
When writing configuration, there might be a need to perform some repetitive tasks. We can get this done using the looping mechanisms available in Terraform. Let’s consider a situation when we need to move between different instance sizes.
variable "ami_id" {description = "AMI ID to use"type = stringdefault = "AMI_ID"}variable "instance_sizes" {description = "A list of instance sizes available"type = set(string)default = ["t2.micro", "t2.nano", "t2.small"]}resource "aws_instance" "demo_node" {for_each = var.instance_sizesami = var.ami_idinstance_type = each.valuetags = {Name = "demo-node-${each.value}"}}
In the example above, we create two variables ami_id
and instance_sizes
, and then loop through the list of sizes to create three unique EC2 instances. To make each instance unique, the value of the instance size is appended to the name attribute. We can use the playground below to create three instances of different sizes by following these steps:
-
Obtain your AMI
AMI_ID
by following the steps below:i. In the search bar of the AWS Management Console, search for “EC2” and select the “EC2” option from the results. This will take us to the EC2 dashboard.
ii. From the left panel, select “Instances” under “Instances” and click the “Launch instances” button.
iii. On the “Launch an instance” page, give a name to your instance.
iv. Under “Application and OS Images (Amazon Machine Image),” select “Quick Start,” and select “Linux” from the available OS. Under this section, there will be an AMI ID that we can use to replace the already given AMI in the following playground.
Note: We must ensure that we replace the
AMI_ID
placeholder with the actual AMI obtained from the AWS console. ...