简体   繁体   English

如何重用 terraform 资源?

[英]How to reuse a terraform resource?

I'm pretty much new to terraform. I wanted to know is there a way to reuse a resource?我是 terraform 的新手。我想知道有没有办法重用资源? Below is my code.下面是我的代码。 Below is the main.tf, where I have a module declared.下面是 main.tf,我在其中声明了一个模块。

module "deployments" {
  source = "./modules/odo_deployments"
  artifact_versions = local.artifact_versions
}

In the modules/odo_deployments folder, I have two resources which does exactly the same except for a different ad.在 modules/odo_deployments 文件夹中,我有两个资源,除了不同的广告外,它们的功能完全相同。 Is there a way I can use just one resource and pass arguments (ad) like a function to this resource?有没有一种方法可以只使用一个资源并将 arguments (ad) 像 function 一样传递给该资源?

variable "artifact_versions" {
  description = "What gets injected by terraform at the ET level"
}

resource "odo_deployment" "incident-management-service-dev" {
    count = var.artifact_versions["incident-management-service"].version == "skip" ? 0 : 1
    ad = "phx-ad-1"
    alias = "cloud-incident-management-application"
    artifact {
        url = var.artifact_versions["incident-management-service"].uri
        build_tag = var.artifact_versions["incident-management-service"].version
        type = var.artifact_versions["incident-management-service"].type
    }

    flags = ["SKIP_UP_TO_DATE_NODES"]
}

resource "odo_deployment" "incident-management-service-dev-ad3" {
    count = var.artifact_versions["incident-management-service"].version == "skip" ? 0 : 1
    ad = "phx-ad-3"
    alias = "cloud-incident-management-application"
    artifact {
        url = var.artifact_versions["incident-management-service"].uri
        build_tag = var.artifact_versions["incident-management-service"].version
        type = var.artifact_versions["incident-management-service"].type
    }

    flags = ["SKIP_UP_TO_DATE_NODES"]
}

What I did to solve this is,I added a locals in the main.tf and pass the local variable in the module like below我为解决这个问题所做的是,我在 main.tf 中添加了一个局部变量,并在模块中传递局部变量,如下所示

locals {
  ad = ["phx-ad-1", "phx-ad3"]
}
module "deployments" {
  source = "./modules/odo_deployments"
  artifact_versions = local.artifact_versions
  ad = local.ad

and in the resource instead of hard coding the ad value, I used it like below在资源中,我没有对广告价值进行硬编码,而是像下面这样使用它

count = length(var.ad)
ad    = var.ad[count.index]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM