Search code examples
aws-cdkaws-codecommit

cdk: use aws_iam.ArnPrincipal to grant repository


I want to enable (cross-account) access to a repository. But my statement seems not to have any effect.

repository.grant_pull(aws_iam.ArnPrincipal('arn:aws:iam::123456789:role/technical-role'))

I even don't see any changes in the resulting template after synth, no matter if I add the line or comment it out. Do I have missed some point?


Solution

  • still don't know, why the obvious approach didn't work, but found a solution basing on this, that and this

    in the cdk with the repo (the account 999999999 where the source-code resides):

    def get_repository(self, kms_key, service_role):
        repository = aws_codecommit.Repository(
            self,
            "TechMainCdkAppRepository",
            repository_name="tech_main_cdk_app",
            description="Contains the Code to form the main stages",
            kms_key=kms_key,
        )
        proxy_role = self.get_stage_proxy_role()
        repository.grant_pull(proxy_role)
        kms_key.grant_encrypt_decrypt(proxy_role)
        repository.grant_pull(service_role)
        return repository
    
    
    def get_stage_proxy_role(self):
        role = aws_iam.Role(
            self,
            "StageAccountProxyRoleCodecommit",
            assumed_by=aws_iam.ArnPrincipal(
                "arn:aws:iam::123456789:role/codebuild-cdk_app-build_and_deploy_stage-run"
            ),
            role_name="codecommit-stage_account_proxy_role",
        )
        return role
    

    Take care: when using a custom kms-key the grant kms_key.grant_encrypt_decrypt(proxy_role) is crucial, as without that you always get a 403-error and (like me) will maybe search for the error in the wrong place.

    in the cdk with the "guest" (the account 123456789, you want to do your git pull/clone):

    service_role = aws_iam.Role(
        self,
        "MainStageDeployRole",
        assumed_by=aws_iam.ServicePrincipal("codebuild.amazonaws.com"),
        role_name="codebuild-cdk_app-build_and_deploy_stage-run",
    )
    
    service_role.add_to_policy(
        aws_iam.PolicyStatement(
            effect=aws_iam.Effect.ALLOW,
            actions=["sts:AssumeRole"],
            resources=[
                "arn:aws:iam::*:role/cdk-*",
                "arn:aws:iam::999999999:role/codecommit-stage_account_proxy_role",
            ],
        )
    )
    

    now start a CodeBuild-job with the service-role and inside your buildspec.yaml do the magic:

          - aws configure --profile proxyrole set role_arn arn:aws:iam::999999999:role/codecommit-stage_account_proxy_role
          - aws configure --profile proxyrole set credential_source EcsContainer
          - aws configure --profile proxyrole set account 999999999
          - git clone codecommit://proxyrole@tech_main_cdk_app