Home > Blockchain >  AWS CDK : Unable to find IAM Role created using subprocess
AWS CDK : Unable to find IAM Role created using subprocess

Time:04-03

I created a role using iam.Role and then tried to find the role using subprocess library. I see the role getting created successfully, but not able to find the role in the output of the command executed using subprocess. Please find below for the code.

Can anyone point out what the issue is and also suggest whats the best way to get the Arn of any role based on the role name/Id in CDK

class CdkTestStack(Stack):

def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
    super().__init__(scope, construct_id, **kwargs)

    #Create role        
    role = iam.Role(self, role_name='cdk-test-role', 
              id='cdk-test-role',
              assumed_by=iam.CompositePrincipal(iam.ServicePrincipal('lambda.amazonaws.com')),
              max_session_duration=aws_cdk.Duration.seconds(10000),
              path='/test-cdk/')

    print('Created role with name: ' str(role.role_name))

    #Get list of all policies
    roles_output=subprocess.run(['aws', 'iam', 'list-roles', '--path-prefix', '/test-cdk/'], capture_output=True, text=True)
    roles = str(roles_output.stdout)
    roles_cli = json.loads(roles)

    for roles_cli_key in roles_cli:
        roles_arr = roles_cli[roles_cli_key]
        
        for rol in roles_arr:
            rol_nam = rol['RoleName']
            
            if(rol_nam == 'cdk-test-role'):
                role_id = rol['RoleId']
                role_arn = rol['Arn']
                imported_role = iam.Role.from_role_arn(id=role_id,scope=self,role_arn=role_arn)
                
                print('Found imported role: ' str(imported_role.role_name))

CodePudding user response:

CDK generates CloudFormation templates. So when the CLI runs your code, the result is a template. Your role will only be created when this template is uploaded to AWS and executed (cdk deploy does this).

Also, it's not a good idea to make network calls, especially SDK calls, from your CDK code. The best practice is to make your CDK code deterministic - i.e. synth to the same template every time and not be dependent on the network.

CodePudding user response:

You can use a CDK output to get the role arn from a Stack by name.

https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.CfnOutput.html

  • Related