Create and IAM_role, Define configuration in cluster.config :param iam_client: an IAM service client instance :return: True if IAM role created and policy applied successfully.
(iam_client)
| 18 | |
| 19 | |
| 20 | def create_IAM_role(iam_client): |
| 21 | """ |
| 22 | Create and IAM_role, Define configuration in cluster.config |
| 23 | :param iam_client: an IAM service client instance |
| 24 | :return: True if IAM role created and policy applied successfully. |
| 25 | """ |
| 26 | |
| 27 | role_name = config.get('IAM_ROLE', 'NAME') |
| 28 | role_description = config.get('IAM_ROLE', 'DESCRIPTION') |
| 29 | role_policy_arn = config.get('IAM_ROLE','POLICY_ARN') |
| 30 | |
| 31 | logging.info(f"Creating IAM role with name : {role_name}, description : {role_description} and policy : {role_policy_arn}") |
| 32 | |
| 33 | # Creating Role. |
| 34 | # Policy Documentation reference - https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html#aws-resource-iam-role--examples |
| 35 | role_policy_document = json.dumps( |
| 36 | { |
| 37 | "Version": "2012-10-17", |
| 38 | "Statement": [ |
| 39 | { |
| 40 | "Effect": "Allow", |
| 41 | "Principal": { "Service": [ "redshift.amazonaws.com" ] }, |
| 42 | "Action": [ "sts:AssumeRole" ] |
| 43 | } |
| 44 | ] |
| 45 | } |
| 46 | ) |
| 47 | |
| 48 | try: |
| 49 | create_response = iam_client.create_role( |
| 50 | Path='/', |
| 51 | RoleName=role_name, |
| 52 | Description=role_description, |
| 53 | AssumeRolePolicyDocument = role_policy_document |
| 54 | ) |
| 55 | logger.debug(f"Got response from IAM client for creating role : {create_response}") |
| 56 | logger.info(f"Role create response code : {create_response['ResponseMetadata']['HTTPStatusCode']}") |
| 57 | except Exception as e: |
| 58 | logger.error(f"Error occured while creating role : {e}") |
| 59 | return False |
| 60 | |
| 61 | |
| 62 | try: |
| 63 | # Attaching policy using ARN's( Amazon Resource Names ) |
| 64 | policy_response = iam_client.attach_role_policy( |
| 65 | RoleName=role_name, |
| 66 | PolicyArn=role_policy_arn |
| 67 | ) |
| 68 | logger.debug(f"Got response from IAM client for applying policy to role : {policy_response}") |
| 69 | logger.info(f"Attach policy response code : {policy_response['ResponseMetadata']['HTTPStatusCode']}") |
| 70 | except Exception as e: |
| 71 | logger.error(f"Error occured while applying policy : {e}") |
| 72 | return False |
| 73 | |
| 74 | return True if( (create_response['ResponseMetadata']['HTTPStatusCode'] == 200) and (policy_response['ResponseMetadata']['HTTPStatusCode'] == 200) ) else False |
| 75 | |
| 76 | |
| 77 | def delete_IAM_role(iam_client): |
no outgoing calls
no test coverage detected