如何在Terraform中的data.archive_file zips文件夹之前运行命令?

时间:2016-11-22 14:33:57

标签: terraform

我尝试使用terraform实现aws lambda函数。

我只有null_resource有本地配置工具,而resource.archive_file在完成所有准备工作后会压缩源代码。

resource "null_resource" "deps" {

  triggers = {
    package_json = "${base64sha256(file("${path.module}/src/package.json"))}"
  }

  provisioner "local-exec" {
    command = "cd ${path.module}/src && npm install"
  }
}

resource "archive_file" "function" {
    type = "zip"
    source_dir = "${path.module}/src"
    output_path = "${path.module}/function.zip"

    depends_on = [ "null_resource.deps" ]
}

最近对Terraform的更改已弃用resource.archive_file,因此应使用data.archive_file。不幸的是,data在资源之前执行,因此在创建zip之后会调用依赖资源的本地配置程序。因此,下面的代码不再产生警告,但根本不起作用。

resource "null_resource" "deps" {

  triggers = {
    package_json = "${base64sha256(file("${path.module}/src/package.json"))}"
  }

  provisioner "local-exec" {
    command = "cd ${path.module}/src && npm install"
  }
}

data "archive_file" "function" {
    type = "zip"
    source_dir = "${path.module}/src"
    output_path = "${path.module}/function.zip"

    depends_on = [ "null_resource.deps" ]
}

我错过了什么吗?使用最新版本执行此操作的正确方法是什么。

Terraform:v0.7.11 操作系统:Win10

2 个答案:

答案 0 :(得分:3)

Terraform 0.8中有一个新的数据源,external,允许您运行外部命令并提取输出。见data.external

数据源应用于检索某些依赖值,而不是npm install的执行,您仍应通过null_resource执行此操作。由于这是一个Terraform数据源,它不应该有任何副作用(虽然在这种情况下你可能需要一些,但不确定)。

基本上,null_resource执行依赖项,data.external获取一些您可以依赖的归档值(例如目录路径),然后data.archive_file执行归档。

这可能最适合伪随机目录名称,可能使脏检查工作更清洁。

答案 1 :(得分:3)

事实证明Terraform核心处理数据资源depends_on的方式存在问题。报告了几个问题,一个在archive provider中,另一个在the core中。

存档提供程序问题中列出了以下解决方法。请注意,它使用data.null_data_source放在null_resourcedata.archive_file之间,这使它成为显式依赖,而不是depends_on的隐式依赖。

resource "null_resource" "lambda_exporter" {
  # (some local-exec provisioner blocks, presumably...)

  triggers = {
    index = "${base64sha256(file("${path.module}/lambda-files/index.js"))}"
  }
}

data "null_data_source" "wait_for_lambda_exporter" {
  inputs = {
    # This ensures that this data resource will not be evaluated until
    # after the null_resource has been created.
    lambda_exporter_id = "${null_resource.lambda_exporter.id}"

    # This value gives us something to implicitly depend on
    # in the archive_file below.
    source_dir = "${path.module}/lambda-files/"
  }
}

data "archive_file" "lambda_exporter" {
  output_path = "${path.module}/lambda-files.zip"
  source_dir  = "${data.null_data_source.wait_for_lambda_exporter.outputs["source_dir"]}"
  type        = "zip"
}