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



我正试图通过terraform为gitlab repo中的文件创建一个lambda函数,但我在CICD管道中遇到了错误:

"/lambda_function.zip:没有这样的文件或目录">

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

我的Gitlab项目看起来像

项目名称

-src

  • lambda_function.py

-地形

  • lambda.tf

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文件

最新更新