Terraform - 从子模块访问根模块脚本 [英] Terraform - access root module script from child module

查看:16
本文介绍了Terraform - 从子模块访问根模块脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 main.tfROOT_MODULE:

I have a ROOT_MODULE with main.tf:

#Root Module - Just run the script
resource "null_resource" "example" {
  provisioner "local_exec" {
    command = "./script.sh"
}

script.sh:

echo "Hello world

现在我在其他地方有另一个目录,我在其中创建了一个 CHILD_MODULE 和另一个 main.tf:

now I have another directory elsewhere where I've created a CHILD_MODULE with another main.tf:

#Child Module
module "ROOT_MODULE" {
  source = "gitlabURL/ROOT_MODULE"
}

我已经导出了我的计划文件:terraform plan -out="planfile"但是,当我对计划文件执行 terraform apply 时,我当前所在的目录不再知道 script.sh 的位置.我需要将脚本保存在与根模块相同的目录中.该脚本也在 gitlab 存储库中,因此我没有本地路径来调用它.关于如何将此脚本放入我的子模块/从我的计划文件中执行它的任何想法?

I've exported my planfile: terraform plan -out="planfile" however, when I do terraform apply against the planfile, the directory I am currently in no longer has any idea where the script.sh is. I need to keep the script in the same directory as the root module. This script is also inside a gitlab repository so I don't have a local path to call it. Any idea as to how I can get this script into my child module / execute it from my planfile?

Error running command './script.sh': exit status 1. Output: cannot access 'script.sh': No such file or directory

推荐答案

您可以访问根模块配置的路径以保留具有 path.root 内在文件的路径:

You can access the path to the root module config to preserve pathing for files with the path.root intrinsic:

provisioner "local_exec" {
  command = "${path.root}/script.sh"
}

但是,根据您的问题,您似乎已经交换了根模块和子模块的术语.因此,该模块似乎真的是您的子模块而不是根模块,您需要使用 path.module 内在访问路径:

However, based on your question, it appears you have swapped the terminology for root module and child module. Therefore, that module appears to really be your child module and not root, and you need to access the path with the path.module intrinsic:

provisioner "local_exec" {
  command = "${path.module}/script.sh"
}

然后无论您当前的工作目录如何,都会保留脚本的路径.

and then the pathing to the script will be preserved regardless of your current working directory.

这些内在表达式记录在这里.

These intrinsic expressions are documented here.

这篇关于Terraform - 从子模块访问根模块脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆