简体   繁体   中英

terraform variable default value interpolation from locals

I have a use case where I need two AWS providers for different resources. The default aws provider is configured in the main module which uses another module that defines the additional aws provider.

By default, I'd like both providers to use the same AWS credentials unless explicitly overridden.

I figured I could do something like this. In the main module:

locals {
  foo_cloud_access_key = aws.access_key
  foo_cloud_secret_key = aws.secret_key
}

variable "foo_cloud_access_key" {
  type        = string
  default     = local.foo_cloud_access_key
}

variable "foo_cloud_secret_key" {
  type        = string
  default     = local.foo_cloud_secret_key
}

where variable s foo_cloud_secret_key and foo_cloud_access_key would then be passed down to the child module like this:

module foobar {
...
  foobar_access_key = var.foo_cloud_access_key
  foobar_secret_key = var.foo_cloud_secret_key
...
}

Where module foobar would then configure its additional was provide with these variables:

provider "aws" {
  alias      = "foobar_aws"
  access_key = var.foobar_access_key
  secret_key = var.foobar_secret_key
}

When I run the init terraform spits out this error (for both variables):

Error: Variables not allowed
  on variables.tf line 66, in variable "foo_cloud_access_key":
  66:   default     = local.foo_cloud_access_key

Variables may not be used here.

Is it possible to achieve something like this in terraform or is there any other way to go about this?

Having complex, computed default values of variables is possible, but only with a workaround:

  • define a dummy default value for the variable, eg null
  • define a local variable, its value is either the value of the variable or the actual default value
variable "something" {
    default = null
}

locals {
    some_computation = ... # based on whatever data you want
    something = var.something == null ? local.some_computation : var.something
}

And then only only use local.something instead of var.something in the rest of the terraform files.

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