import json


def attach_iam_role_policy(config, iam):
    """Creates & attaches S3 & EC2 policy to the newly created IAM role

    Attaches a policy to an AWS IAM role for read-only access to
    S3 buckets and Redshift service-role access to EC2.

    Args:
        config: a ConfigParser object
        iam: a boto3 client object for the AWS IAM service

    Returns:
        A dict with AWS API response metadata on the attach_role_policy call
    """
    managed_policy_name = config['IAM_ROLE']['POLICY_NAME']
    print("Creating managed policy: ", managed_policy_name)

    response = iam.create_policy(
        PolicyName=managed_policy_name,
        PolicyDocument=json.dumps(config['IAM_ROLE']['MANAGED_POLICY'])
    )

    print(
        "Attaching policy: {} to IAM Role {}".format(
            managed_policy_name,
            config['IAM_ROLE']['NAME']
        )
    )
    return iam.attach_role_policy(
        PolicyArn=response['Policy']['Arn'],
        RoleName=config['IAM_ROLE']['NAME']
    )