Zha*_* Yi 6 amazon-s3 aws-lambda terraform
我有以下 lambda 函数配置TerraForm:
resource "aws_lambda_function" "test_lambda" {
# filename = "crawler/dist/deploy.zip"
s3_bucket = "${var.s3-bucket}"
s3_key = "${aws_s3_bucket_object.file_upload.key}"
# source_code_hash = "${filebase64sha256("file.zip")}"
function_name = "quote-crawler"
role = "arn:aws:iam::773592622512:role/LambdaRole"
handler = "handler.handler"
source_code_hash = "${data.archive_file.zipit.output_base64sha256}"
runtime = "${var.runtime}"
timeout = 180
environment {
variables = {
foo = "bar"
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我运行 lambda"errorMessage": "An error occurred (AccessDenied) when calling the PutObject operation: Access Denied",时,当它尝试将文件上传到 s3 存储桶时出现错误。似乎 lambda 函数没有访问 s3 的权限。TerraFormdoc 不清楚如何配置它们。权限配置面板也不会出现lambda console。似乎由创建的 lambdaTerraForm具有有限的配置供我使用。那么如何向 lambda 授予 s3 权限呢?
小智 6
不允许与该函数关联的 IAM 角色上传到 S3。
解决方案是创建一个 IAM 策略,允许 S3 访问您的存储桶(例如读/写),该策略如下所示:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ListObjectsInBucket",
"Effect": "Allow",
"Action": ["s3:ListBucket"],
"Resource": ["arn:aws:s3:::bucket-name"]
},
{
"Sid": "AllObjectActions",
"Effect": "Allow",
"Action": "s3:*Object",
"Resource": ["arn:aws:s3:::bucket-name/*"]
}
]
}
Run Code Online (Sandbox Code Playgroud)
然后,您需要将此策略附加到 lambda 函数使用的角色。
更多信息请访问: https://www.terraform.io/docs/providers/aws/r/iam_role_policy.html
为方便起见,您可以分三步执行此操作,
创建角色。
resource "aws_iam_role" "role" {
name = "${var.env_prefix_name}-alb-logs-to-elk"
path = "/"
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
EOF
}
Run Code Online (Sandbox Code Playgroud)
创建具有指定访问 s3 权限的策略
#Created Policy for IAM Role
resource "aws_iam_policy" "policy" {
name = "${var.env_prefix_name}-test-policy"
description = "A test policy"
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:*"
],
"Resource": "arn:aws:logs:*:*:*"
},
{
"Effect": "Allow",
"Action": [
"s3:*"
],
"Resource": "arn:aws:s3:::*"
}
]
}
EOF
}
Run Code Online (Sandbox Code Playgroud)
附加的 IAM 角色和新创建的策略
resource "aws_iam_role_policy_attachment" "test-attach" {
role = "${aws_iam_role.role.name}"
policy_arn = "${aws_iam_policy.policy.arn}"
}
Run Code Online (Sandbox Code Playgroud)
现在将角色附加到 Lamba 源
resource "aws_lambda_function" "test_lambda" {
# filename = "crawler/dist/deploy.zip"
s3_bucket = "${var.s3-bucket}"
s3_key = "${aws_s3_bucket_object.file_upload.key}"
# source_code_hash = "${filebase64sha256("file.zip")}"
function_name = "quote-crawler"
role = "${aws_iam_role.role.arn}"
handler = "handler.handler"
source_code_hash = "${data.archive_file.zipit.output_base64sha256}"
runtime = "${var.runtime}"
timeout = 180
environment {
variables = {
foo = "bar"
}
}
}
Run Code Online (Sandbox Code Playgroud)