Home > database >  read key value from a json file for terraform variables
read key value from a json file for terraform variables

Time:10-27

I have the below sample json file: .json file

[
{
"ParameterKey": "key1",
"ParameterValue": "valueofthekey1" 
},
{
"ParameterKey": "key2",
"ParameterValue": "valueofthekey2"
}
]

resource tf file:


locals {
    local_data = jsondecode(file("./modules/path/file.json"))
}

resource "aws_ssm_parameter" "testing1" { 
type = "String" 
name = "test_name1" 
value = local.local_data.valueofthekey1
}

resource "aws_ssm_parameter" "testing2" { 
type = "String" 
name = "test_name2" 
value = local.local_data.valueofthekey2
}

Any leads how can I read the json file and pass the value for the key1 in first resource followed by key2 for 2nd resource ??

I tried using local, but they showed me the below error: 12: value = local.local_data.testing1 |---------------- | local.local_data is tuple with 2 elements

CodePudding user response:

If you want ParameterKey to be name of the parameter, you can do:

resource "aws_ssm_parameter" "testing" { 
  count = length(local.local_data)
  type = "String" 
  name = local.local_data[count.index].ParameterKey
  value = local.local_data[count.index].ParameterValue
}

But if you want the entire json element to be value, then you can do:

resource "aws_ssm_parameter" "testing" { 
  count = length(local.local_data)
  type = "String" 
  name = "test_name${count.index}" 
  value = jsonencode(local.local_data[count.index])
}
  • Related