magi
magi

Reputation: 161

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? Below is my code. Below is the main.tf, where I have a module declared.

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. Is there a way I can use just one resource and pass arguments (ad) like a function to this resource?

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"]
}

Upvotes: 2

Views: 2371

Answers (1)

magi
magi

Reputation: 161

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

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]

Upvotes: 1

Related Questions