带条件的源

  • 本文关键字:条件 terraform
  • 更新时间 :
  • 英文 :


是否可以在地形模块中使用带有条件的源?

module user_creation {
source = local.region == "new_york" ? "./modules/new_york" : "./modules/default_regions"
--
---
}

Terraform中的模块依赖关系是静态的,由terraform init解析,因此不能根据只有在运行时才知道的数据而变化。

您没有说明动态选择不同模块的目的是什么,所以我猜您的想法是希望根据区域以不同的方式声明用户。如果是这样,有几个不同的选项可以实现:

  • 您可以设计代表用户的模块,使其具有自定义其行为的输入变量,然后根据所选区域更改传递给这些输入变量的值。

    variable "region" {
    type = string
    }
    locals {
    region_differences = {
    new_york = {
    something_configurable = 5
    }
    }
    selected_region_differences = local.region_differences[var.region]
    }
    module "users" {
    source = "./modules/users"
    something_configurable = try(
    local.selected_region_differences.something_configurable,
    2, // this is the default value if there is no override
    )
    }
    
  • 您可以设计您的模块,以便"纽约用户";模块是通用模块的扩展而不是替换,并使用条件count调用它,以便它表示仅在该区域声明的额外资源:

    variable "region" {
    type = string
    }
    module "users" {
    source = "./module/users"
    # ...
    }
    module "users_new_york" {
    source = "./module/users/new_york"
    count  = var.region == "new_york"
    # If the New York extension module requires
    # information from the base one, you can
    # declare an input variable of an object type
    # and then pass the module object into it to
    # concisely share the output values from
    # module.users with this module.
    base_users = module.users
    # ...
    }
    
  • 你可以写出两个模块块,并使用条件count和互斥条件来声明一次只应该实例化一个模块:

    variable "region" {
    type = string
    }
    module "users_other" {
    source = "./module/users/other_region"
    count  = var.region != "new_york"
    # ...
    }
    module "users_new_york" {
    source = "./module/users/new_york"
    count  = var.region == "new_york"
    # ...
    }
    locals {
    # OPTIONAL:
    # If both of the modules produce compatible output
    # values then it might be helpful to expose whichever
    # one was declared as local.users for use elsewhere
    # in the module without lots of conditional logic.
    # See the "one" and "concat" functions in the Terraform
    # docs to understand how this works.
    users = one(concat(
    module.users_other,
    module.users_new_york,
    ))
    }
    

你可能会发现阅读Terraform关于模块组成的文档对如何使用Terraform模块将问题分解成更小的部分很有用。

最新更新