Nirav
Nirav

Reputation: 662

How to pass down file path to module?

I am learning terraform modules.

I've created module for Google Provider.

provider "google" {
  credentials = "${var.credentials}"
  project     = "${var.project_id}"
  region      = "${var.region}"
  zone        = "${var.zone}"
}

I want to pass credential file path form the module consuming above.

Here is the consumer module.

main.tf

module "google" {
  source      = "../modules/google-provider"
  project_id = "${var.project_id}"
  credentials = "${var.credentials}"
}

variables.tf

variable "credentials" {
    default = "${file("cred.json")}"
}

This is the error I am getting:

Error: variable "credentials": default may not contain interpolations

I read this stackoverflow comment but did not understand how it will work.

Thank you for the help in advance.

Upvotes: 2

Views: 11903

Answers (1)

laxman
laxman

Reputation: 2110

from the docs,

When you declare variables in the root module of your configuration, you can set their values using CLI options and environment variables. When you declare them in child modules, the calling module should pass values in the module block.

In your case,

#This is your calling module, hence you need to pass variables to child module from here
module "google" {
  source      = "../modules/google-provider"
  passed_project_id_to_child = "${var.project_id}"
  passed_credentials_to_child = "${var.credentials}"
}

UPDATE: for some reasons, terraform is not allowing you to read file with interpolation syntax create a data source of type local_file docs

data "local_file" "credJSON" {
    filename = "./cred.json"
}

then you will need to do something like this in your module's configuration file or you can also create a seperate file for that too,

variable passed_project_id_to_child{
  default = "${jsonencode(data.credJSON.content).projectId}"
}
variable passed_credentials_to_child{}

provider "google" {
      credentials = "${var.passed_project_id_to_child}"
      project     = "${var.passed_project_id_to_child}"
      region      = "${var.region}"
      zone        = "${var.zone}"
    }

Hopefully this works. Read more here

Upvotes: 3

Related Questions