Issue
We have a terraform script to create a lambda function in aws. This lambda function uses a custom bucket from S3.
The script below runs perfectly when I put "Resource": "*"
.
We need to specify a custom resource that aws lambda function can access on S3.
Our aws_iam_policy is configured this way:
resource "aws_iam_policy" "lambda_policy" {
name = "lambda-s3-policy"
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:*",
"ec2:CreateNetworkInterface",
"ec2:DescribeNetworkInterfaces",
"ec2:DeleteNetworkInterface",
"ec2:DescribeSecurityGroups",
"ec2:DescribeSubnets",
"ec2:DescribeVpcs"
],
"Resource": "arn:aws:s3:::my-mock-bucket/example-folder/*"
}
]
}
EOF
}
When the script runs, this error appears:
Error: Error applying plan:
1 error(s) occurred:
* aws_lambda_function.func_loader: 1 error(s) occurred:
* aws_lambda_function.func_loader: Error creating Lambda function: InvalidParameterValueException: The subnet subnet-xxxxxxxxxxxxxxxx is out of IP addresses.
{
RespMetadata: {
StatusCode: 400,
RequestID: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
},
Message_: "The subnet subnet-xxxxxxxxxxxxxxxx is out of IP addresses.",
Type: "User"
}
Terraform does not automatically rollback in the face of errors.
I already checked the permissions, the subnet ip range limits, but it is all good to go.
Solution
These permissions:
"ec2:CreateNetworkInterface",
"ec2:DescribeNetworkInterfaces",
"ec2:DeleteNetworkInterface",
"ec2:DescribeSecurityGroups",
"ec2:DescribeSubnets",
"ec2:DescribeVpcs"
Can't be restricted to this resource:
"Resource": "arn:aws:s3:::my-mock-bucket/example-folder/*"
What you have done is given your Lambda function permission to call those EC2 actions, as long as it is calling those actions on an S3 bucket, which obviously makes no sense. You probably need to split the IAM policy into multiple statements, like so:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:*",
],
"Resource": "arn:aws:s3:::my-mock-bucket/example-folder/*"
},
{
"Effect": "Allow",
"Action": [
"ec2:CreateNetworkInterface",
"ec2:DescribeNetworkInterfaces",
"ec2:DeleteNetworkInterface",
"ec2:DescribeSecurityGroups",
"ec2:DescribeSubnets",
"ec2:DescribeVpcs"
],
"Resource": "*"
}
]
}
Answered By - Mark B