AWS:在Terraform中部署Lambda时描述ECR图像时出错



我正在尝试使用Terraform将lambda部署为容器。这是我的项目结构:

project
├── README.md
├── lambda_functions
│   ├── Dockerfile
│   └── index.py
├── terraform
└── lambda.tf

我正在terraform文件夹中运行terraform initterraform planterraform apply

variable "region" {
default = "eu-west-2"
}
data "aws_caller_identity" "current" {}
locals {
prefix              = "mycompany"
account_id          = data.aws_caller_identity.current.account_id
ecr_repository_name = "${local.prefix}-demo-lambda-container"
ecr_image_tag       = "latest"
}
resource "aws_ecr_repository" "repo" {
name = local.ecr_repository_name
}
resource "null_resource" "ecr_image" {
triggers = {
python_file = md5(file("${path.module}/lambda_functions/lambda_function.py"))
docker_file = md5(file("${path.module}/lambda_functions/Dockerfile"))
}
provisioner "local-exec" {
command = <<EOF
aws ecr get-login-password --region ${var.region} | docker login --username AWS --password-stdin ${local.account_id}.dkr.ecr.${var.region}.amazonaws.com
cd ${path.module}/lambda_functions
docker build -t ${aws_ecr_repository.repo.repository_url}:${local.ecr_image_tag} .
docker push ${aws_ecr_repository.repo.repository_url}:${local.ecr_image_tag}
EOF
}
}
data "aws_ecr_image" "lambda_image" {
depends_on = [
null_resource.ecr_image
]
repository_name = local.ecr_repository_name
image_tag       = local.ecr_image_tag
}

当我使用terraform apply时,我会收到以下错误:

Error: Error describing ECR images: ImageNotFoundException: The image with imageId {imageDigest:'null', imageTag:'latest'} does not exist within the repository with name 'capsphere-demo-lambda-container' in the registry with id 'XXXXXX'

我已经尝试过将${path.module}更改为..,或者也使用绝对路径来避免运气不佳。你知道问题可能是什么吗?

您可能需要显式指定解释器。如果您在Windows上,默认情况下将使用cmd,它将在ecr get-login-password之后停止执行。

此外,您可以为脚本指定workind目录,因此不需要更改目录。

resource "null_resource" "ecr_image" {
triggers = {
python_file = md5(file("../lambda_functions/lambda_function.py"))
docker_file = md5(file("../lambda_functions/Dockerfile"))
}
provisioner "local-exec" {
command = <<EOF
aws ecr get-login-password --region ${var.region} | docker login --username AWS --password-stdin ${local.account_id}.dkr.ecr.${var.region}.amazonaws.com
docker build -t ${aws_ecr_repository.repo.repository_url}:${local.ecr_image_tag} .
docker push ${aws_ecr_repository.repo.repository_url}:${local.ecr_image_tag}
EOF
# interpreter = ["pwsh", "-Command"] # For Windows 
interpreter = ["bash", "-c"] # For Linux/MacOS
working_dir = "../lambda_functions"
}
}

关于path.module,您在这里并不真正需要它,它将指向当前目录(.(。如果您从terraform文件夹运行terraform apply,则必须升级一级,这可以通过..实现。

相关内容

  • 没有找到相关文章

最新更新