Example #1
0
    def put_configuration_recorder(self, config_recorder):
        # Validate the name:
        if not config_recorder.get("name"):
            raise InvalidConfigurationRecorderNameException(config_recorder.get("name"))
        if len(config_recorder.get("name")) > 256:
            raise NameTooLongException(
                config_recorder.get("name"), "configurationRecorder.name"
            )

        # We're going to assume that the passed in Role ARN is correct.

        # Config currently only allows 1 configuration recorder for an account:
        if len(self.recorders) == 1 and not self.recorders.get(config_recorder["name"]):
            raise MaxNumberOfConfigurationRecordersExceededException(
                config_recorder["name"]
            )

        # Is this updating an existing one?
        recorder_status = None
        if self.recorders.get(config_recorder["name"]):
            recorder_status = self.recorders[config_recorder["name"]].status

        # Validate the Recording Group:
        if config_recorder.get("recordingGroup") is None:
            recording_group = RecordingGroup()
        else:
            rg = config_recorder["recordingGroup"]

            # If an empty dict is passed in, then bad:
            if not rg:
                raise InvalidRecordingGroupException()

            # Can't have both the resource types specified and the other flags as True.
            if rg.get("resourceTypes") and (
                rg.get("allSupported", False)
                or rg.get("includeGlobalResourceTypes", False)
            ):
                raise InvalidRecordingGroupException()

            # Must supply resourceTypes if 'allSupported' is not supplied:
            if not rg.get("allSupported") and not rg.get("resourceTypes"):
                raise InvalidRecordingGroupException()

            # Validate that the list provided is correct:
            self._validate_resource_types(rg.get("resourceTypes", []))

            recording_group = RecordingGroup(
                all_supported=rg.get("allSupported", True),
                include_global_resource_types=rg.get(
                    "includeGlobalResourceTypes", False
                ),
                resource_types=rg.get("resourceTypes", []),
            )

        self.recorders[config_recorder["name"]] = ConfigRecorder(
            config_recorder["roleARN"],
            recording_group,
            name=config_recorder["name"],
            status=recorder_status,
        )
Example #2
0
    def put_delivery_channel(self, delivery_channel):
        # Must have a configuration recorder:
        if not self.recorders:
            raise NoAvailableConfigurationRecorderException()

        # Validate the name:
        if not delivery_channel.get("name"):
            raise InvalidDeliveryChannelNameException(delivery_channel.get("name"))
        if len(delivery_channel.get("name")) > 256:
            raise NameTooLongException(
                delivery_channel.get("name"), "deliveryChannel.name"
            )

        # We are going to assume that the bucket exists -- but will verify if the bucket provided is blank:
        if not delivery_channel.get("s3BucketName"):
            raise NoSuchBucketException()

        # We are going to assume that the bucket has the correct policy attached to it. We are only going to verify
        # if the prefix provided is not an empty string:
        if delivery_channel.get("s3KeyPrefix", None) == "":
            raise InvalidS3KeyPrefixException()

        # Ditto for SNS -- Only going to assume that the ARN provided is not an empty string:
        if delivery_channel.get("snsTopicARN", None) == "":
            raise InvalidSNSTopicARNException()

        # Config currently only allows 1 delivery channel for an account:
        if len(self.delivery_channels) == 1 and not self.delivery_channels.get(
            delivery_channel["name"]
        ):
            raise MaxNumberOfDeliveryChannelsExceededException(delivery_channel["name"])

        if not delivery_channel.get("configSnapshotDeliveryProperties"):
            dp = None

        else:
            # Validate the config snapshot delivery properties:
            self._validate_delivery_snapshot_properties(
                delivery_channel["configSnapshotDeliveryProperties"]
            )

            dp = ConfigDeliverySnapshotProperties(
                delivery_channel["configSnapshotDeliveryProperties"][
                    "deliveryFrequency"
                ]
            )

        self.delivery_channels[delivery_channel["name"]] = ConfigDeliveryChannel(
            delivery_channel["name"],
            delivery_channel["s3BucketName"],
            prefix=delivery_channel.get("s3KeyPrefix", None),
            sns_arn=delivery_channel.get("snsTopicARN", None),
            snapshot_properties=dp,
        )
Example #3
0
    def put_configuration_recorder(self, config_recorder):
        # Validate the name:
        if not config_recorder.get('name'):
            raise InvalidConfigurationRecorderNameException(
                config_recorder.get('name'))
        if len(config_recorder.get('name')) > 256:
            raise NameTooLongException(config_recorder.get('name'),
                                       'configurationRecorder.name')

        # We're going to assume that the passed in Role ARN is correct.

        # Config currently only allows 1 configuration recorder for an account:
        if len(self.recorders) == 1 and not self.recorders.get(
                config_recorder['name']):
            raise MaxNumberOfConfigurationRecordersExceededException(
                config_recorder['name'])

        # Is this updating an existing one?
        recorder_status = None
        if self.recorders.get(config_recorder['name']):
            recorder_status = self.recorders[config_recorder['name']].status

        # Validate the Recording Group:
        if not config_recorder.get('recordingGroup'):
            recording_group = RecordingGroup()
        else:
            rg = config_recorder['recordingGroup']

            # Can't have both the resource types specified and the other flags as True.
            if rg.get('resourceTypes') and (
                    rg.get('allSupported', True)
                    or rg.get('includeGlobalResourceTypes', False)):
                raise InvalidRecordingGroupException()

            # If an empty dict is provided, then bad:
            if not rg.get('resourceTypes', False) \
                    and not rg.get('resourceTypes') \
                    and not rg.get('includeGlobalResourceTypes', False):
                raise InvalidRecordingGroupException()

            # Validate that the list provided is correct:
            self._validate_resource_types(rg.get('resourceTypes', []))

            recording_group = RecordingGroup(
                all_supported=rg.get('allSupported', True),
                include_global_resource_types=rg.get(
                    'includeGlobalResourceTypes', False),
                resource_types=rg.get('resourceTypes', []))

        self.recorders[config_recorder['name']] = \
            ConfigRecorder(config_recorder['roleARN'], recording_group, name=config_recorder['name'],
                           status=recorder_status)
Example #4
0
    def put_configuration_aggregator(self, config_aggregator, region):
        # Validate the name:
        if len(config_aggregator['ConfigurationAggregatorName']) > 256:
            raise NameTooLongException(
                config_aggregator['ConfigurationAggregatorName'],
                'configurationAggregatorName')

        account_sources = None
        org_source = None

        # Tag validation:
        tags = validate_tags(config_aggregator.get('Tags', []))

        # Exception if both AccountAggregationSources and OrganizationAggregationSource are supplied:
        if config_aggregator.get(
                'AccountAggregationSources') and config_aggregator.get(
                    'OrganizationAggregationSource'):
            raise InvalidParameterValueException(
                'The configuration aggregator cannot be created because your request contains both the'
                ' AccountAggregationSource and the OrganizationAggregationSource. Include only '
                'one aggregation source and try again.')

        # If neither are supplied:
        if not config_aggregator.get(
                'AccountAggregationSources') and not config_aggregator.get(
                    'OrganizationAggregationSource'):
            raise InvalidParameterValueException(
                'The configuration aggregator cannot be created because your request is missing either '
                'the AccountAggregationSource or the OrganizationAggregationSource. Include the '
                'appropriate aggregation source and try again.')

        if config_aggregator.get('AccountAggregationSources'):
            # Currently, only 1 account aggregation source can be set:
            if len(config_aggregator['AccountAggregationSources']) > 1:
                raise TooManyAccountSources(
                    len(config_aggregator['AccountAggregationSources']))

            account_sources = []
            for a in config_aggregator['AccountAggregationSources']:
                account_sources.append(
                    AccountAggregatorSource(
                        a['AccountIds'],
                        aws_regions=a.get('AwsRegions'),
                        all_aws_regions=a.get('AllAwsRegions')))

        else:
            org_source = OrganizationAggregationSource(
                config_aggregator['OrganizationAggregationSource']['RoleArn'],
                aws_regions=config_aggregator['OrganizationAggregationSource'].
                get('AwsRegions'),
                all_aws_regions=config_aggregator[
                    'OrganizationAggregationSource'].get('AllAwsRegions'))

        # Grab the existing one if it exists and update it:
        if not self.config_aggregators.get(
                config_aggregator['ConfigurationAggregatorName']):
            aggregator = ConfigAggregator(
                config_aggregator['ConfigurationAggregatorName'],
                region,
                account_sources=account_sources,
                org_source=org_source,
                tags=tags)
            self.config_aggregators[
                config_aggregator['ConfigurationAggregatorName']] = aggregator

        else:
            aggregator = self.config_aggregators[
                config_aggregator['ConfigurationAggregatorName']]
            aggregator.tags = tags
            aggregator.account_aggregation_sources = account_sources
            aggregator.organization_aggregation_source = org_source
            aggregator.last_updated_time = datetime2int(datetime.utcnow())

        return aggregator.to_dict()
Example #5
0
    def put_configuration_aggregator(self, config_aggregator, region):
        # Validate the name:
        if len(config_aggregator["ConfigurationAggregatorName"]) > 256:
            raise NameTooLongException(
                config_aggregator["ConfigurationAggregatorName"],
                "configurationAggregatorName",
            )

        account_sources = None
        org_source = None

        # Tag validation:
        tags = validate_tags(config_aggregator.get("Tags", []))

        # Exception if both AccountAggregationSources and OrganizationAggregationSource are supplied:
        if config_aggregator.get(
                "AccountAggregationSources") and config_aggregator.get(
                    "OrganizationAggregationSource"):
            raise InvalidParameterValueException(
                "The configuration aggregator cannot be created because your request contains both the"
                " AccountAggregationSource and the OrganizationAggregationSource. Include only "
                "one aggregation source and try again.")

        # If neither are supplied:
        if not config_aggregator.get(
                "AccountAggregationSources") and not config_aggregator.get(
                    "OrganizationAggregationSource"):
            raise InvalidParameterValueException(
                "The configuration aggregator cannot be created because your request is missing either "
                "the AccountAggregationSource or the OrganizationAggregationSource. Include the "
                "appropriate aggregation source and try again.")

        if config_aggregator.get("AccountAggregationSources"):
            # Currently, only 1 account aggregation source can be set:
            if len(config_aggregator["AccountAggregationSources"]) > 1:
                raise TooManyAccountSources(
                    len(config_aggregator["AccountAggregationSources"]))

            account_sources = []
            for source in config_aggregator["AccountAggregationSources"]:
                account_sources.append(
                    AccountAggregatorSource(
                        source["AccountIds"],
                        aws_regions=source.get("AwsRegions"),
                        all_aws_regions=source.get("AllAwsRegions"),
                    ))

        else:
            org_source = OrganizationAggregationSource(
                config_aggregator["OrganizationAggregationSource"]["RoleArn"],
                aws_regions=config_aggregator["OrganizationAggregationSource"].
                get("AwsRegions"),
                all_aws_regions=config_aggregator[
                    "OrganizationAggregationSource"].get("AllAwsRegions"),
            )

        # Grab the existing one if it exists and update it:
        if not self.config_aggregators.get(
                config_aggregator["ConfigurationAggregatorName"]):
            aggregator = ConfigAggregator(
                config_aggregator["ConfigurationAggregatorName"],
                region,
                account_sources=account_sources,
                org_source=org_source,
                tags=tags,
            )
            self.config_aggregators[
                config_aggregator["ConfigurationAggregatorName"]] = aggregator

        else:
            aggregator = self.config_aggregators[
                config_aggregator["ConfigurationAggregatorName"]]
            aggregator.tags = tags
            aggregator.account_aggregation_sources = account_sources
            aggregator.organization_aggregation_source = org_source
            aggregator.last_updated_time = datetime2int(datetime.utcnow())

        return aggregator.to_dict()