How to use the c7n.actions.Action function in c7n

To help you get started, we’ve selected a few c7n examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github cloud-custodian / cloud-custodian / c7n / resources / cloudtrail.py View on Github external
if self.annotation_key in r:
                continue
            client = local_session(self.manager.session_factory).client(
                'cloudtrail', region_name=region)
            status = client.get_trail_status(Name=r['Name'])
            status.pop('ResponseMetadata')
            r[self.annotation_key] = status

        return super(Status, self).process(resources)

    def __call__(self, r):
        return self.match(r['c7n:TrailStatus'])


@CloudTrail.action_registry.register('update-trail')
class UpdateTrail(Action):
    """Update trail attributes.

    :Example:

    .. code-block:: yaml

       policies:
         - name: cloudtrail-set-log
           resource: aws.cloudtrail
           filters:
            - or:
              - KmsKeyId: empty
              - LogFileValidationEnabled: false
           actions:
            - type: update-trail
              attributes:
github cloud-custodian / cloud-custodian / c7n / resources / asg.py View on Github external
schema = type_schema('unused')

    def get_permissions(self):
        return self.manager.get_resource_manager('asg').get_permissions()

    def process(self, configs, event=None):
        asgs = self.manager.get_resource_manager('asg').resources()
        used = set([
            a.get('LaunchConfigurationName', a['AutoScalingGroupName'])
            for a in asgs if not a.get('LaunchTemplate')])
        return [c for c in configs if c['LaunchConfigurationName'] not in used]


@LaunchConfig.action_registry.register('delete')
class LaunchConfigDelete(Action):
    """Filters all unused launch configurations

    :example:

    .. code-block:: yaml

            policies:
              - name: asg-unused-launch-config-delete
                resource: launch-config
                filters:
                  - unused
                actions:
                  - delete
    """

    schema = type_schema('delete')
github cloud-custodian / cloud-custodian / c7n / resources / mq.py View on Github external
class MQSGFilter(SecurityGroupFilter):

    RelatedIdsExpression = 'SecurityGroups[]'


@MessageBroker.filter_registry.register('metrics')
class MQMetrics(MetricsFilter):

    def get_dimensions(self, resource):
        # Fetching for Active broker instance only, https://amzn.to/2tLBhEB
        return [{'Name': self.model.dimension,
                 'Value': "{}-1".format(resource['BrokerName'])}]


@MessageBroker.action_registry.register('delete')
class Delete(Action):
    """Delete a set of message brokers
    """

    schema = type_schema('delete')
    permissions = ("mq:DeleteBroker",)

    def process(self, resources):
        client = local_session(self.manager.session_factory).client('mq')
        for r in resources:
            try:
                client.delete_broker(BrokerId=r['BrokerId'])
            except client.exceptions.NotFoundException:
                continue


@MessageBroker.action_registry.register('tag')
github cloud-custodian / cloud-custodian / c7n / resources / simpledb.py View on Github external
client = local_session(self.session_factory).client('sdb')
            results = []
            for r in resources:
                info = client.domain_metadata(DomainName=r)
                info.pop('ResponseMetadata')
                info['DomainName'] = r
                results.append(info)
            return results

        with self.executor_factory(max_workers=3) as w:
            return list(itertools.chain(
                *w.map(_augment, chunks(resources, 20))))


@SimpleDB.action_registry.register('delete')
class Delete(Action):

    schema = type_schema('delete')
    permissions = ('sdb:DeleteDomain',)

    def process(self, resources):
        client = local_session(self.manager.session_factory).client('sdb')
        for r in resources:
            client.delete_domain(DomainName=r['DomainName'])
github cloud-custodian / cloud-custodian / c7n / resources / asg.py View on Github external
if error:
            raise error

    def process_resource_set(self, client, asgs, tags):
        tag_set = []
        for a in asgs:
            for t in tags:
                tag_set.append(dict(
                    Key=t, ResourceType='auto-scaling-group',
                    ResourceId=a['AutoScalingGroupName']))
        self.manager.retry(client.delete_tags, Tags=tag_set)


@ASG.action_registry.register('tag')
@ASG.action_registry.register('mark')
class Tag(Action):
    """Action to add a tag to an ASG

    The *propagate* parameter can be used to specify that the tag being added
    will need to be propagated down to each ASG instance associated or simply
    to the ASG itself.

    :example:

    .. code-block:: yaml

            policies:
              - name: asg-add-owner-tag
                resource: asg
                filters:
                  - "tag:OwnerName": absent
                actions:
github cloud-custodian / cloud-custodian / c7n / resources / cloudtrail.py View on Github external
self.manager.resource_type.service)

    def process(self, resources):
        client = local_session(self.manager.session_factory).client('cloudtrail')
        shadow_check = IsShadow({'state': False}, self.manager)
        shadow_check.embedded = True
        resources = shadow_check.process(resources)

        for r in resources:
            client.update_trail(
                Name=r['Name'],
                **self.data['attributes'])


@CloudTrail.action_registry.register('set-logging')
class SetLogging(Action):
    """Set the logging state of a trail

    :Example:

    .. code-block:: yaml

      policies:
        - name: cloudtrail-set-active
          resource: aws.cloudtrail
          filters:
           - type: status
             key: IsLogging
             value: False
          actions:
           - type: set-logging
             enabled: True
github cloud-custodian / cloud-custodian / tools / c7n_gcp / c7n_gcp / actions / core.py View on Github external
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from googleapiclient.errors import HttpError

from c7n.actions import Action as BaseAction
from c7n.utils import local_session, chunks


class Action(BaseAction):
    pass


class MethodAction(Action):
    """Invoke an api call on each resource.

    Quite a number of procedural actions are simply invoking an api
    call on a filtered set of resources. The exact handling is mostly
    boilerplate at that point following an 80/20 rule. This class is
    an encapsulation of the 80%.
    """

    # method we'll be invoking
    method_spec = ()

    # batch size
github cloud-custodian / cloud-custodian / c7n / resources / ssm.py View on Github external
def resource_query(self):
        filters = []
        for q in self.data.get('query', ()):
            if (not isinstance(q, dict) or
                not set(q.keys()) == set(('Key', 'Values', 'Operator')) or
                q['Key'] not in self.QueryKeys or
                    q['Operator'] not in self.QueryOperators):
                raise PolicyValidationError(
                    "invalid ops-item query %s" % self.data['query'])
            filters.append(q)
        return {'OpsItemFilters': filters}


@OpsItem.action_registry.register('update')
class UpdateOpsItem(Action):
    """Update an ops item.

    : example :

    Close out open ops items older than 30 days for a given issue.

    .. code-block:: yaml

      policies:
       - name: issue-items
         resource: aws.ops-item
         filters:
          - Status: Open
          - Title: checking-lambdas
          - type: value
            key: CreatedTime
github cloud-custodian / cloud-custodian / c7n / resources / cloudsearch.py View on Github external
@resources.register('cloudsearch')
class CloudSearch(QueryResourceManager):

    class resource_type(TypeInfo):
        service = "cloudsearch"
        enum_spec = ("describe_domains", "DomainStatusList", None)
        name = id = "DomainName"
        dimension = "DomainName"
        filter_name = 'DomainNames'
        filter_type = 'list'
        arn_type = "domain"


@CloudSearch.action_registry.register('delete')
class Delete(Action):

    schema = type_schema('delete')
    permissions = ('cloudsearch:DeleteDomain',)

    def process(self, resources):
        client = local_session(
            self.manager.session_factory).client('cloudsearch')
        for r in resources:
            if r['Created'] is not True or r['Deleted'] is True:
                continue
            client.delete_domain(DomainName=r['DomainName'])
github cloud-custodian / cloud-custodian / c7n / resources / asg.py View on Github external
if not instance_ids:
            return
        retry = get_retry((
            'RequestLimitExceeded', 'Client.RequestLimitExceeded'))
        retry(ec2_client.start_instances, InstanceIds=instance_ids)

    def resume_asg(self, asg_client, asg):
        """Resume asg processes.
        """
        self.manager.retry(
            asg_client.resume_processes,
            AutoScalingGroupName=asg['AutoScalingGroupName'])


@ASG.action_registry.register('delete')
class Delete(Action):
    """Action to delete an ASG

    The 'force' parameter is needed when deleting an ASG that has instances
    attached to it.

    :example:

    .. code-block:: yaml

            policies:
              - name: asg-delete-bad-encryption
                resource: asg
                filters:
                  - type: not-encrypted
                    exclude_image: true
                actions: