List of Topics:
Location Research Breakthrough Possible @S-Logix pro@slogix.in

Office Address

Social List

How to Terraform Dynamically Generate a JSON Configuration File using Map Variables and the jsonencode() Function?

Terraform

Condition for Terraform Dynamically Generate a JSON Configuration File using Map Variables and the jsonencode() Function

  • Description:
    Terraform is not only for cloud provisioning—it can also generate configuration files.Using the jsonencode() function, Terraform can convert maps, lists, or any structured data into a valid JSON file.
  •  Requirements
     This method is commonly used for generating:
     App config files
     Microservice environment configs
     JSON-based settings for containers
     This exercise demonstrates dynamic file generation controlled by variables.

STEPS

  •  STEP 1 — Create project directory
     Create directory and navigate into it:
    mkdir terraform-json-generator
    cd terraform-json-generator
        
  •  STEP 2 — Create variables.tf
     Create the variables file:
    nano variables.tf
        
     Add the following content:
    variable "config" {
      type = map(string)
      default = {
        app  = "terraform-demo"
        port = "9090"
        mode = "local"
      }
    }
        
  •  STEP 3 — Create main.tf
     Create the main configuration file:
    nano main.tf
        
     Paste the following content:
    terraform {
      required_providers {
        local = {
          source  = "hashicorp/local"
          version = "~> 2.4"
        }
      }
    }
    
    provider "local" {}
    
    resource "local_file" "json_config" {
      filename = "${path.module}/config.json"
      content  = jsonencode(var.config)
    }
        
     This converts the map into a JSON structure.
  •  STEP 4 — Initialize Terraform
     Initialize the project:
    terraform init
        
     Expected:
    Terraform has been successfully initialized!
        
  •  STEP 5 — Apply Terraform
     Apply the configuration:
    terraform apply -auto-approve
        
     Terraform creates:
    config.json
        
     Expected Terminal Output:
    Apply complete!
        
  •  STEP 6 — Verify JSON File
     Show the file:
    cat config.json
        
     Expected output:
    {"app":"terraform-demo","port":"9090","mode":"local"}
        
Screenshots
  • 543
  • 544
  • 545
  • 546
  • 547
  • 548
  • 549
  • 550
  • 551