terraform replace variable inside json
Asked Answered
B

2

6

i am creating rds server using terraform. I pass options group using list variable. The options groups variable in variable.tf like below

options = [
   {
    option_name = "SQLSERVER_BACKUP_RESTORE"

    option_settings=[
      {
      name  = "IAM_ROLE_ARN"
      value = "${role_arn}"
    },
  ]
},

i want replace the "${role_arn}" variable in main.tf . Can any one help with syntax ?

Bulahbulawayo answered 7/8, 2020 at 11:27 Comment(0)
A
13

I solve this kind of issue using terraform template files.

  1. Move your json to a separate file;
  2. update yout json to use Terraform template syntax;
  3. add a data resource to render and parse your template;
  4. reference your rendered template in your resource.

Let's say that you'll need something like:

resource "provider_resource" "name" {
  property = "value"
  options = [
    {
      option_name = "SQLSERVER_BACKUP_RESTORE"
      option_settings = [
        {
          name  = "IAM_ROLE_ARN"
          value = "${role_arn}"
        },
      ]
    }
  ]
}

after the change you will have something like:

data "template_file" "json_template" {
  template = file("path/to/file.json")
  vars = {
    role_arn = var.dynamic_value
  }
}

resource "provider_resource" "name" {
  property = "value"
  options = data.template_file.json_template.rendered
}
Adulteration answered 7/8, 2020 at 12:40 Comment(3)
Cheers .this is helping @gustavo... i passed this to resource options group code from github.com/terraform-aws-modules/terraform-aws-rds/tree/master/… .... It throws error Cannot use a string value in for_each. An iterable collection is required....... any variable conversion ??Bulahbulawayo
in your case the options is a list. If you will have only one value inside this list, you can change the options value to be an list with the rendered template as its single value. ex: remove the array from your json and change the resource to use options = [data.template_file.json_template.rendered]. If you'll need more than one value then you'll need to make more research.Adulteration
Appreciate your reposne @gustavo will try this... i was trying function tolist(data.template_file.json_template.rendered) to covert to list . doesn't workBulahbulawayo
S
0

Building on the template_file approach, the templatefile function allows to do this with minimal verbosity:

resource "provider_resource" "name" {
  property = "value"
  options  = templatefile("path/to/file.json", { role_arn = var.dynamic_value })
}
Sanderlin answered 29/8, 2023 at 16:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.