无法通过 Terraform 在 Gitlab 中为 AWS Lambda Fx 创建 Zip 文件

Not able to create Zip file for AWS Lambda Fx in Gitlab through Terraform

我正在尝试通过 terraform 为 gitlab 存储库中存在的文件创建 lambda 函数,但是我在 CICD 管道中遇到错误:

"./lambda_function.zip: 没有那个文件或目录"

包含 lambda 函数 python 文件的文件夹(src 文件夹)与包含 terraform 文件的文件夹(terraform)不同。

我的 Gitlab 项目看起来像

项目名称

-src

-地形

lambda.tf 中的地形代码是:

data "archive_file" "lambda" {
type = "zip"
source_file = "../src/lambda_function.py"
output_path = "lambda_function.zip"

}

    resource "aws_lambda_function" "automation-lambda" 
{filename=data.archive_file.lambda.output_path
  description       = "Creating lambda"
  function_name     = "lambda_fx"
  role              = "xxxxxxxxxxxxx"  
  handler           = "lambda_function.lambda_handler"
  memory_size       =  128
  timeout           =  300
  source_code_hash  = data.archive_file.lambda.output_base64sha256
  runtime = "python3.7"
}

请建议如何解决该问题。

谢谢

问题简述:

问题归结为:terraform plan 创建 data.archive_file 资源,稍后由 terraform apply 使用。如果您在单独的 gitlab 管道阶段执行这两个 terraform 命令。在 plan 阶段生成的 zip 文件将无法用于 apply 阶段。除非您将输出目录添加为工件

较长版本的答案

如果您正在使用 gitlab 管道的多个阶段,一个用于计划,然后一个用于应用。这是你的问题。

“dist”zip 文件是在计划阶段创建的,因此您需要将 $PWD/dist 作为工件添加到您的管道中。然后在您的应用阶段,告诉管道它需要计划阶段,使工件可用于应用命令。

所以在我们的管道中,我有这样的东西:

plan_lambda:
  stage: plan
  needs:
    - init_lambda
    - validate_lambda
  script:
    - terraform -chdir=${PROJECT} plan -out=planfile ${args[@]}
  artifacts:
    paths:
      - ${PROJECT}/planfile
      # This is important, data.archive_file's are generated during plan stage, not apply, so these artifacts need to be stored
      # https://github.com/hashicorp/terraform-provider-archive/issues/39#issuecomment-1013680518
      - ${PWD}/dist

然后在申请阶段

apply_lambda:
  stage: apply
  when: manual
  needs:
    - init_lambda
    - plan_lambda
    - apply_execution_role
  variables:
    PROJECT: lambda
  script:
    - terraform -chdir=${PROJECT} apply -auto-approve planfile

在这里,计划阶段生成的 dist zip 文件将可用于应用阶段,您的问题应该得到解决。

有关其他信息和引导我找到此解决方案的整个对话,这是 terraform github 存储库中的票证:

https://github.com/hashicorp/terraform-provider-archive/issues/39#issuecomment-1013680518

“dist”或“dist zip”文件是什么意思?

这是一些 terraform 代码,它运行 yarn 来安装 node_modules,然后将源代码打包成一个 zip 文件,以便您可以在 AWS Lambda 上部署

resource "null_resource" "run_yarn" {
  triggers  =  {
    always_run = timestamp()
  }

  provisioner "local-exec" {
    command = "yarn --cwd ${local.root_path}/app/src install"
  }
}

data "archive_file" "app_src" {
  depends_on    = [null_resource.run_yarn]
  type          = "zip"
  source_dir    = "${local.root_path}/app/src"
  output_path   = "${local.root_path}/dist/app.zip"
}

所以“dist”文件是生成并上传到 AWS Lambda 的分布式 zip 文件