DevOps Blog - Nicolas Paris

Loop in Terraform with For Each from Json File

Terraform

I'll loop a Terraform object based on values in a json file. Let's make the example simple with a list of DNS zone from Cloudflare. Terraform is a growing part of DevOps and Infrastructure as Code, well known in DevOps tech.

The following show two subjects,

Files structure looks like this:

- records.auto.tfvars.json
- declare_vars.tf
- main.tf
- zone.tf

The json file look like this in records.auto.tfvars.json

{
"records": {
"www": {
"value" : "127.0.0.1",
"proxied": false
},
"api": {
"value" : "127.0.0.1",
"proxied": true
}
}
}

A declare_vars.tf with the following.

variable "records" {
description = "records"
type = map
}

a main.tf with cloudflare provider and credential.

terraform {
required_providers {
cloudflare = {
source = "cloudflare/cloudflare"
version = "~> 3.0"
}
}
}

provider "cloudflare" {
email = "myemail@example.com"
api_key = "aaabbbcccdddeee123456789"
}

Here is the for each in Terraform, in zone.tf

variable "cloudflare_zone_id" {
default = "123456789abcde"
}

resource "cloudflare_record" "records" {
for_each = var.records
zone_id = var.cloudflare_zone_id
name = each.key
value = each.value.value
type = "A"
ttl = 3600
proxied = each.value.proxied
}