I want to create a CloudFront distribution that could invoke a lambda
(@edge). I was able to do that using AWS console. I am now trying to achieve the same using Terraform. My configurations are as follows.
First, I created a role for lambda.
resource "aws_iam_role" "my_edge_lambda_iam_role" {
name = "my_edge_lambda_iam_role"
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
EOF
}
Next, I created a the lambda.
resource "aws_lambda_function" "redirect_lambda" {
filename = "myscript.js.zip"
function_name = "my_js_script"
role = "arn:aws:iam::123456789:role/my_edge_lambda_iam_role"
handler = "index.handler"
runtime = "nodejs4.3-edge"
}
Finally, I (attempted to) created the CloudFront distribution using the ARN of the lambda function above. The definition is as follows.
resource "aws_cloudfront_distribution" "s3_distribution" {
origin {
domain_name = "my-bucket.s3.amazonaws.com"
origin_id = "<my S3 path>"
}
enabled = true
is_ipv6_enabled = true
default_cache_behavior {
allowed_methods = ["GET", "HEAD"]
cached_methods = ["GET", "HEAD"]
target_origin_id = "<my target origin>"
forwarded_values {
query_string = false
cookies {
forward = "none"
}
}
lambda_function_association {
event_type = "viewer-request"
lambda_arn = "<arn of the lambda function denerated above>"
}
viewer_protocol_policy = "allow-all"
min_ttl = 0
default_ttl = 86400
max_ttl = 31536000
}
price_class = "PriceClass_All"
viewer_certificate {
cloudfront_default_certificate = true
}
restrictions {
geo_restriction {
restriction_type = "none"
}
}
}
When trying to create the distribution, I get the following exception.
Error applying plan:
1 error(s) occurred:
* aws_cloudfront_distribution.s3_distribution: 1 error(s) occurred:
* aws_cloudfront_distribution.s3_distribution: InvalidLambdaFunctionAssociation: Failed to retrieve the function from Lambda. ErrorCode: AccessDeniedException Function: arn:aws:lambda:us-east-2:12345678:function:my_js_script
status code: 400, request id: 65579sd33-3f2d5-181e7-9140-79c1ff79fbdd
Could it be a problem with how I have defined the role?
As Michael mentioned in the comments, you need to add an aws_lambda_permission
resource to allow an AWS service to invoke a Lambda function.
resource "aws_lambda_permission" "allow_cloudfront" {
statement_id = "AllowExecutionFromCloudFront"
action = "lambda:GetFunction"
function_name = "${aws_lambda_function.redirect_lambda.function_name}"
principal = "edgelambda.amazonaws.com"
}
The AWS docs have a little more information about how to allow this outside of Terraform, using the CLI in this case:
aws lambda add-permission \
--function-name arn \
--statement-id statement-id \
--action lambda:GetFunction \
--principal edgelambda.amazonaws.com
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With