Home > OS >  AWS Lambda, Terraform - Add Role to Lambda that References a Not-Yet-Created Lambda
AWS Lambda, Terraform - Add Role to Lambda that References a Not-Yet-Created Lambda

Time:09-21

TL;DR How do I create a role that a Lambda function can assume, that references the lambda, before the lambda has been created

Hello Folks,

I am using Terraform v1.0.5 along with AWS. I have a lambda that has the following code in it:

assumed_role = sts_client.assume_role(
        ...
        RoleSessionName="tms_rules_settings_lambda",
        ...
    )

To do this, I have to give my lambda a policy that it can assume such a role. Thus, I have the following Terraform.

locals {
  tms_rules_settings_lambda_role_name = "tms_rules_settings_lambda_role"
  tms_rules_settings_lambda_func_name = "tms_rules_settings_lambda"
}
...
** The Lambda Setup**
resource "aws_lambda_function" "tms_rules_settings_lambda" {
  ...
  function_name = local.tms_rules_settings_lambda_func_name
  role = aws_iam_role.tms_rules_settings_lambda_role.arn
  ...
}
...
** The Lambda Role Setup**
resource "aws_iam_role" "tms_rules_settings_lambda_role" {

  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Principal": {
        "AWS": "arn:aws:sts::${data.aws_caller_identity.current.account_id}:assumed-role/${local.tms_rules_settings_lambda_role_name}/${local.tms_rules_settings_lambda_func_name}",
        "Service": "lambda.amazonaws.com"
      },
      "Effect": "Allow",
      "Sid": ""
    }
  ]
}
EOF

}

This leads to the following error:

Error: Error creating IAM Role tms_rules_settings_lambda_role: 

MalformedPolicyDocument: Invalid principal in policy: 

"AWS":"arn:aws:sts::267601234567:assumed-role/tms_rules_settings_lambda_role/tms_rules_settings_lambda"

I believe this is being caused because the lambda and role reference one another, and when one doesn't exist it blows up.

How do I go about creating my role for the lambda when the principal (the lambda) doesn't exist.

Any help is greatly appreciated.

CodePudding user response:

Unfortunately, you can't do this. A valid principle must exist before you can use it in any IAM policy or role. So you either have to use a wildcard in the principle arn, or first create the function, and then update its roles or permissions, once the lambda exists.

CodePudding user response:

When you use a role as a principal in a policy statement, you use the role ARN, not the assumed role principal that STS gives you. You used the latter, and that's why you're getting the error.

However... it looks to me like you're trying to add a role to it's own assumeRole policy. Why would you do that? The role doesn't need to assume itself.

  • Related