简体   繁体   中英

Excluding resource in Terraform module

I have a Terraform module which I built that deploys two instances of the module to a separate region. In this module there is a key vault. I only want the key vault to be present in one of the two regions.

Here is my module:

resource "azurerm_resource_group" "test" {
  name     = "test"
  location = "${var.location}"
}

resource "azurerm_key_vault" "keyvault" {
  name = "keyvault"
}

Here is my main.tf

module "test_uswest2" {
  source = "modules/test"

  location = "westus2"
  environment = "${var.environment}"
}

module "test_westcentralus" {
  source = "modules/test"

  location = "centralus"
  environment = "${var.environment}"
}

I want to exclude the key vault in the second region/location.

Terraform doesn't seem to support if/else so I'm not sure what my options are.

You can conditionally create resources by setting the count meta parameter to 0 and using the conditional ternary operator .

So you would have something like this:

variable "create_key_vault" {
  default = true
}

resource "azurerm_key_vault" "keyvault" {
  count = "${var.create_key_vault ? 0 : 1}"
  name  = "keyvault"
}

Then call your module with create_key_vault set to false to not create it:

module "test_westcentralus" {
  source = "modules/test"

  location         = "centralus"
  environment      = "${var.environment}"
  create_key_vault = false
}

ydaetskcoR's answer works fine, you can also do it the reverse way however with a default variable value, if that fits better the use case.

Set the count arg like:

count = "${var.create_key_vault}"

Define a variable in module's source with a false default value:

variable "create_key_vault" {
  default = false
}

and then define which modules need to ovverride that and set it to true:

module "test_westcentralus" {
  source = "modules/test"

  location         = "centralus"
  environment      = "${var.environment}"
  create_key_vault = true
}

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