def L4M_role()

in getting_started/utility.py [0:0]


def L4M_role(ARN_lambda):
    iam = boto3.client('iam')
    role_name_l4M= 'L4M_alert_lambda'
    assume_role_policy_document_L4M = {
        "Version": "2012-10-17",
        "Statement": [
            {
              "Effect": "Allow",
              "Principal": {
                "Service": "lookoutmetrics.amazonaws.com"
              },
              "Action": "sts:AssumeRole"
            }
        ]
    }
    try:
        create_role_response = iam.create_role(
            RoleName = role_name_l4M,
            AssumeRolePolicyDocument = json.dumps(assume_role_policy_document_L4M)
        );

    except iam.exceptions.EntityAlreadyExistsException as e:
        print('Warning: role already exists:', e)
        create_role_response = iam.get_role(
            RoleName = role_name_l4M
        );       
    role_arn = create_role_response["Role"]["Arn"]
    print('IAM Role: {}'.format(role_arn))

    policy_json={
        "Version": "2012-10-17",
        "Statement": [
            {
                "Effect": "Allow",
                "Action": [
                    "lambda:InvokeFunction"
                ],
                "Resource": [
                    ARN_lambda
                ]
            }
        ]
    }
    
    try:
        create_policy = iam.create_policy(
            PolicyName = 'L4M_alert_lambda',
            PolicyDocument = json.dumps(policy_json)
        );

    except iam.exceptions.EntityAlreadyExistsException as e:
        print('Warning: role already exists:', e)
        response = iam.list_policies()
        s= response['Policies']
        my_policy = next((item for item in s if item['PolicyName'] == 'L4M_alert_lambda'), None)
        create_policy = iam.get_policy(
            PolicyArn = my_policy['Arn']
        );

    policy_arn = create_policy["Policy"]["Arn"]
    print('IAM Policy: {}'.format(policy_arn))

    attach_response = iam.attach_role_policy(
        RoleName = role_name_l4M,
        PolicyArn = policy_arn
    );
    return (role_name_l4M, role_arn,policy_arn)