简体   繁体   中英

Terrafrom data source a localfile and retrieve some keys from the content as output

I Have a local file (named as x.json)contain some json content. like

{
    "client": {
      "apiKey": "xyzabcpqr!23",
      "permissions": {},
      "firebaseSubdomain": "my-project-1"
    }
}

I am doing data sources on this file like,

data "local_file" "myfile" {
    filename = "x.json" #localfile
}

Now I want to extract the apiKey as terraform out and pass the output to some other resource.

output "apiKey" {
   value = data.local_file.myfile.content
}

But I don't find any option to get that.

I tried this one also, but it is throwing the error as

Can't access attributes on a primitive-typed value (string).

output "apiKey" {
   value = data.local_file.myfile.content.client.apiKey
}

I hope it can help.

Instead of using local file then output, you can also pass your configuration as variable.

For each Terraform module, set the client configuration as variable, before to plan and apply:

export TF_VAR_client='{"apiKey": "xyzabcpqr!23","permissions": {},"firebaseSubdomain": "my-project-1"}'

or

terraform apply -var='apiKey={"apiKey": "xyzabcpqr!23","permissions": {},"firebaseSubdomain": "my-project-1"}'

Then in the Terraform code:

variables.tf file

variable "client" {
  description = "Client"
  type = "map"
}

main.tf file

resource "your_resource" "name" {
    apikey = var.client["apiKey"]

    ....

Assuming you have this:

data "local_file" "myfile" {
    filename = "x.json"
}

You can access the specific values by parsing as JSON (it's read as text).

output "apiKey" {
   value = jsondecode(data.local_file.myfile.content).apiKey
}

As a side note, given this is a sensitive file I'd recommend using local_sensitive_file instead. local_file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM