user16442705
user16442705

Reputation:

How to add permissions to a Lambda function using the CDK?

I have a Lambda function that utilizes the AWS Python SDK to manage AWS CodeCommit repositories. I create the Lambda function using the CDK like so:

from aws_cdk import aws_lambda as _lambda
from aws_cdk.aws_lambda_python import PythonFunction

service = PythonFunction(
    self, 'Svc',
    entry='./path/to',
    index='file.py',
    runtime=_lambda.Runtime.PYTHON_3_8,
    handler='handler',
)

After deployment, I run the Lambda function, the following error occurs which is sent to CloudWatch logs:

An error occurred (AccessDeniedException) when calling the GetRepository operation: User: arn:aws:iam::XXXXXXXXXXXX:user/XXXX is not authorized to perform: codecommit:GetRepository on resource: arn:aws:codecommit:us-east-1:XXXXXXXXXXXX:XXXX

How can I allow the Lambda function to call codecommit:GetRepository on any repository in my account?

Upvotes: 5

Views: 11274

Answers (1)

user16442705
user16442705

Reputation:

Create an IAM Policy Statement and add it to your Function's role policy:

from aws_cdk import aws_iam as iam

service.add_to_role_policy(iam.PolicyStatement(
    effect=iam.Effect.ALLOW,
    actions=[
        'codecommit:*',
    ],
    resources=[
        'arn:aws:codecommit:us-east-1:XXXXXXXXXXXX:*',
    ],
))

Upvotes: 10

Related Questions