Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform: How can I read variables into Terraform from a YAML file? Or from a DB like Hiera?

Tags:

terraform

I wanted to read variables into my Terraform configuration file from an external YAML file or from a database like Hiera, how can I do that? For example:

provider "aws" {
    region = hiera('virginia')    # this should look up for virginia=us-east-1
}

resource "aws_instance" {
    ami = hiera('production') 
    ....
    ....
}

Basically its similar to how we can do a lookup for Puppet manifests/configs using hiera or a YAML file.

like image 441
dr_dino Avatar asked Oct 09 '17 19:10

dr_dino


2 Answers

yamldecode function can be use to read Yaml file as input for terraform and parse it to use.

Let's say test.yml file as below

a: 1
b: 2
c: 3

Then below code can be use to read the yaml file

output "log" {
  value = "${yamldecode(file("test.yml"))}"
}

In order to parse a specific value read from a yaml file

output "log" {
  value = "${yamldecode(file("test.yml"))["a"]}"
}

Important: this is available in 0.12 or later version of terraform, in case of using the old version of terraform and still want to use yaml file, then use terraform-provider-yaml

like image 160
Mahattam Avatar answered Nov 07 '22 20:11

Mahattam


You can include the yaml file as a local:

locals {
  config  = yamldecode(file("${path.module}/configfile.yml"))
}

Now you can call all variables from local.config, for example a variable project_name:

local.config.project_name 
like image 1
Joost Döbken Avatar answered Nov 07 '22 21:11

Joost Döbken