Skip to content
Advertisement

How to attach a managed policy to a an IAM role using the CDK

I’m try to create a service role for AWS CodeBuild.

I can create a role like this:

from aws_cdk import aws_iam as iam

role = iam.Role(
    self, 'CodebuildServiceRole',
    assumed_by=iam.ServicePrincipal('codebuild.amazonaws.com'),
    max_session_duration=cdk.Duration.hours(1),
)

Now I need to attach the Amazon-provided AWSCodeBuildAdminAccess policy to the role. How can I do this using the CDK?

Advertisement

Answer

You can get access to the policy like this:

AWSCodeBuildAdminAccess = iam.ManagedPolicy.from_aws_managed_policy_name('AWSCodeBuildAdminAccess')

And attach it to your role like this:

role.add_managed_policy(AWSCodeBuildAdminAccess)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement