示例#1
0
    def create_and_attach_iam_role(self):
        logging.info("[begin] [create_and_attach_iam_role]")
        iam = Session(region_name=self.region).client('iam')
        iam_res = Session(region_name=self.region).resource('iam')
        gg_client = boto3.client('greengrass', region_name=self.region)
        role_name = '{0}_service_role'.format(self.type_name)
        aws_lambda_ro_access_arn = \
            "arn:aws:iam::aws:policy/AWSLambdaReadOnlyAccess"
        aws_iot_full_access_arn = "arn:aws:iam::aws:policy/AWSIoTFullAccess"

        assume_role_policy = {
            "Version":
            "2012-10-17",
            "Statement": [{
                "Effect": "Allow",
                "Principal": {
                    "Service": "greengrass.amazonaws.com"
                },
                "Action": "sts:AssumeRole"
            }]
        }
        gg_inline_policy = {
            "Version":
            "2012-10-17",
            "Statement": [{
                "Sid": "g3s20170630",
                "Effect": "Allow",
                "Action": ["greengrass:*"],
                "Resource": ["*"]
            }]
        }
        try:
            resp = iam.create_role(
                RoleName=role_name,
                AssumeRolePolicyDocument=json.dumps(assume_role_policy))
            logging.debug(
                "[create_and_attach_iam_role] create_role {0}".format(resp))
            resp = iam.attach_role_policy(RoleName=role_name,
                                          PolicyArn=aws_lambda_ro_access_arn)
            logging.debug(
                "[create_and_attach_iam_role] attach_policy 1 {0}".format(
                    resp))
            resp = iam.attach_role_policy(RoleName=role_name,
                                          PolicyArn=aws_iot_full_access_arn)
            logging.debug(
                "[create_and_attach_iam_role] attach_policy 2 {0}".format(
                    resp))
            resp = iam.put_role_policy(
                RoleName=role_name,
                PolicyName='g3s_inline_policy',
                PolicyDocument=json.dumps(gg_inline_policy))
            logging.debug(
                "[create_and_attach_iam_role] put_policy {0}".format(resp))
            role = iam_res.Role(role_name)
            gg_client.attach_service_role_to_account(RoleArn=role.arn)
            logging.info(
                "[end] [create_and_attach_iam_role] attached service role")

        except ClientError as ce:
            if ce.response['Error'][
                    'Code'] == 'ResourceAlreadyExistsException':
                logging.warning("[create_and_attach_iam_role] {0}".format(
                    ce.response['Error']['Message']))
            else:
                logging.error("[create_and_attach_iam_role] {0}".format(
                    ce.response['Error']['Message']))