Search code examples
jsonvariablesterraformaws-step-functions

how can I insert variables into json file when using terraform


this is the module folder structure

the json definition file (machine_definition.json)

{
  "Comment": "A Hello World example of the Amazon States Language using Pass states",

  "StartAt": "Hello",
  "States": {
    "Hello": {
      "Type": "Pass",
      "Result": "Hello",
      "Next": "World"
    },
    "World": {
      "Type": "${var.test}",
      "Result": "World",
      "End": true
    }
  }
}

for example I'm trying to enter var.test in here. how to make the json file detect my variables?

here is the step function definition

module "step-functions" {
  source  = "terraform-aws-modules/step-functions/aws"
  name = "env-${var.environment}-state-machine"
  definition = file("${path.module}/machine_definition.json")
  tags = var.tags
  service_integrations = {
    xray = {
      xray = true 
    }
  }


  cloudwatch_log_group_name = "env-${var.environment}-state-machine-logGroup"
  attach_policies = true
  number_of_policies = 2
  policies = ["arn:aws:iam::aws:policy/AmazonS3FullAccess", "arn:aws:iam::aws:policy/AWSLambda_FullAccess"]
    
}

Solution

  • Variables cannot be added to a file that way. In order to achieve what you want, you need to use the templatefile [1] built-in fuction. To achieve this you need a bit of code change:

    definition = templatefile("${path.module}/machine_definition.json", {
      type = var.test
    })
    

    Then, in the JSON file, you need to reference the templated variable (type) like this:

    {
      "Comment": "A Hello World example of the Amazon States Language using Pass states",
    
      "StartAt": "Hello",
      "States": {
        "Hello": {
          "Type": "Pass",
          "Result": "Hello",
          "Next": "World"
        },
        "World": {
          "Type": "${type}",
          "Result": "World",
          "End": true
        }
      }
    }
    

    This should render the file properly.


    [1] https://developer.hashicorp.com/terraform/language/functions/templatefile