Search code examples
amazon-web-servicesdevopsaws-glueaws-cdkcicd

Is there a way to attach ServiceRoles policies to a manually created role using AWS CDK?


I'm trying to attach AWSGlueServiceRole to a manually created role in AWS CDK app. It is easily attached through the AWS IAM console but I couldn't find a way to attach it through CDK.

The following is how I created the role in my CDK stack:

        self.glue_role = iam.Role(
            self,
            "GlueRole",
            role_name=f"glue-role",
            assumed_by=iam.ServicePrincipal("glue.amazonaws.com"),
            description="Allows Glue jobs to access AWS services and resources.",
        )

I can easily attach other policies to this role like below:

        self.glue_role.add_managed_policy(
            iam.ManagedPolicy.from_aws_managed_policy_name("AmazonS3FullAccess")
        )
        self.glue_role.add_managed_policy(
            iam.ManagedPolicy.from_aws_managed_policy_name("AmazonSSMFullAccess")
        )
        self.glue_role.add_managed_policy(
            iam.ManagedPolicy.from_aws_managed_policy_name("CloudWatchFullAccess")
        )
        self.glue_role.add_managed_policy(
            iam.ManagedPolicy.from_aws_managed_policy_name("SecretsManagerReadWrite")
        )

I wasn't able to attach AWSGlueServiceRole using the same add_managed_policy because it's not a managed policy receiving the following error:

Policy arn:aws:iam::aws:policy/AWSGlueServiceRole does not exist or is not attachable

I've tried a solution to create a manual policy with exact permissions as AWSGlueServiceRole and attached it to the role and it works, but I wonder if there's a direct way to attach such service role policies to manually created role.

I'm using CDK version 2.142.1


Solution

  • You have to add service-role/ as prefix to the policy name, when attaching service role policies:

    self.glue_role.add_managed_policy(
            iam.ManagedPolicy.from_aws_managed_policy_name("service-role/AWSGlueServiceRole")
        )
    

    If you look up the policy, you see it in its ARN also: arn:aws:iam::aws:policy/service-role/AWSGlueServiceRole