简体   繁体   中英

Terraform - Resource dependency on module

I have a Terraform module, which we'll call parent and a child module used inside of it that we'll refer to as child . The goal is to have the child module run the provisioner before the kubernetes_deployment resource is created. Basically, the child module builds and pushes a Docker image. If the image is not already present, the kubernetes_deployment will wait and eventually timeout because there's no image for the Deployment to use for creation of pods. I've tried everything I've been able to find online, output variables in the child module, using depends_on in the kubernetes_deployment resource, etc and have hit a wall. I would greatly appreciate any help!

parent.tf

module "child" {
  source       = ".\\child-module-path"
  ...
}


resource "kubernetes_deployment" "kub_deployment" {
  ...
}

child-module-path\child.tf

data "external" "hash_folder" {
  program = ["powershell.exe", "${path.module}\\bin\\hash_folder.ps1"]
}

resource "null_resource" "build" {
  triggers = {
    md5 = data.external.hash_folder.result.md5
  }

  provisioner "local-exec" {
    command     = "${path.module}\\bin\\build.ps1 ${var.argument_example}"
    interpreter = ["powershell.exe"]
  }
}

Example Terraform error output:

module.parent.kubernetes_deployment.kub_deployment: Still creating... [10m0s elapsed]
 Error output: 
 Error: Waiting for rollout to finish: 0 of 1 updated replicas are available...

In your child module, declare an output value that depends on the null resource that has the provisioner associated with it:

output "build_complete" {
  # The actual value here doesn't really matter,
  # as long as this output refers to the null_resource.
  value = null_resource.build.triggers.md5
}

Then in your "parent" module, you can either make use of module.child.build_complete in an expression (if including the MD5 string in the deployment somewhere is useful), or you can just declare that the resource depends on the output.

resource "kubernetes_deployment" "example" {
  depends_on = [module.child.build_complete]

  ...
}

Because the output depends on the null_resource and the kubernetes_deployment depends on the output, transitively the kubernetes_deployment now effectively depends on the null_resource , creating the ordering you wanted.

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