How to use the c7n.actions.BaseAction 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 / vpc.py View on Github external
@resources.register('key-pair')
class KeyPair(query.QueryResourceManager):

    class resource_type(query.TypeInfo):
        service = 'ec2'
        arn_type = 'key-pair'
        enum_spec = ('describe_key_pairs', 'KeyPairs', None)
        name = id = 'KeyName'
        filter_name = 'KeyNames'
        taggable = False


@Vpc.action_registry.register('set-flow-log')
@Subnet.action_registry.register('set-flow-log')
@NetworkInterface.action_registry.register('set-flow-log')
class CreateFlowLogs(BaseAction):
    """Create flow logs for a network resource

    :example:

    .. code-block:: yaml

        policies:
          - name: vpc-enable-flow-logs
            resource: vpc
            filters:
              - type: flow-logs
                enabled: false
            actions:
              - type: set-flow-log
                DeliverLogsPermissionArn: arn:iam:role
                LogGroupName: /custodian/vpc/flowlogs/
github cloud-custodian / cloud-custodian / c7n / resources / iam.py View on Github external
continue
            elif state == 'detached' and policy_arn == "*":
                try:
                    self.detach_all_policies(client, r)
                except client.exceptions.NoSuchEntityException:
                    continue

    def detach_all_policies(self, client, resource):
        attached_policy = client.list_attached_role_policies(RoleName=resource['RoleName'])
        policy_arns = [p.get('PolicyArn') for p in attached_policy['AttachedPolicies']]
        for parn in policy_arns:
            client.detach_role_policy(RoleName=resource['RoleName'], PolicyArn=parn)


@Role.action_registry.register('delete')
class RoleDelete(BaseAction):
    """Delete an IAM Role.

    For example, if you want to automatically delete an unused IAM role.

    :example:

      .. code-block:: yaml

        - name: iam-delete-unused-role
          resource: iam-role
          filters:
            - type: usage
              match-operator: all
              LastAuthenticated: null
          actions:
            - type: delete
github cloud-custodian / cloud-custodian / c7n / resources / appelb.py View on Github external
policies:
              - name: appelb-targetgroups-default-vpc
                resource: app-elb-target-group
                filters:
                  - default-vpc
    """

    schema = type_schema('default-vpc')

    def __call__(self, target_group):
        return (target_group.get('VpcId') and
                self.match(target_group.get('VpcId')) or False)


@AppELBTargetGroup.action_registry.register('delete')
class AppELBTargetGroupDeleteAction(BaseAction):
    """Action to delete ELB target group

    It is recommended to apply a filter to the delete policy to avoid unwanted
    deletion of any app elb target groups.

    :example:

    .. code-block:: yaml

            policies:
              - name: appelb-targetgroups-delete-unused
                resource: app-elb-target-group
                filters:
                  - "tag:SomeTag": absent
                actions:
                  - delete
github cloud-custodian / cloud-custodian / c7n / resources / rdscluster.py View on Github external
"""

    schema = type_schema('stop')
    permissions = ('rds:StopDBCluster',)

    def process(self, clusters):
        client = local_session(self.manager.session_factory).client('rds')
        for c in clusters:
            _run_cluster_method(
                client.stop_db_cluster, dict(DBClusterIdentifier=c['DBClusterIdentifier']),
                (client.exceptions.DBClusterNotFoundFault, client.exceptions.ResourceNotFoundFault),
                client.exceptions.InvalidDBClusterStateFault)


@RDSCluster.action_registry.register('start')
class Start(BaseAction):
    """Start a stopped db cluster
    """

    schema = type_schema('start')
    permissions = ('rds:StartDBCluster',)

    def process(self, clusters):
        client = local_session(self.manager.session_factory).client('rds')
        for c in clusters:
            _run_cluster_method(
                client.start_db_cluster, dict(DBClusterIdentifier=c['DBClusterIdentifier']),
                (client.exceptions.DBClusterNotFoundFault, client.exceptions.ResourceNotFoundFault),
                client.exceptions.InvalidDBClusterStateFault)


def _run_cluster_method(method, params, ignore=(), warn=(), method_name=""):
github cloud-custodian / cloud-custodian / c7n / resources / apigw.py View on Github external
patch={'type': 'array', 'items': OP_SCHEMA},
        required=['patch'])

    def process(self, resources):
        client = utils.local_session(
            self.manager.session_factory).client('apigateway')
        for r in resources:
            self.manager.retry(
                client.update_stage,
                restApiId=r['restApiId'],
                stageName=r['stageName'],
                patchOperations=self.data['patch'])


@RestStage.action_registry.register('delete')
class DeleteStage(BaseAction):
    """Delete an api stage

    :example:

    .. code-block:: yaml

        policies:
          - name: delete-rest-stage
            resource: rest-stage
            filters:
              - methodSettings."*/*".cachingEnabled: true
            actions:
              - type: delete
    """
    permissions = ('apigateway:Delete',)
    schema = utils.type_schema('delete')
github davidclin / cloudcustodian-policies / custom-site-packages / iam.py View on Github external
s['Resource'] == "*" and
                    s['Effect'] == "Allow"):
                return True
        return False

    def process(self, resources, event=None):
        c = local_session(self.manager.session_factory).client('iam')
        results = [r for r in resources if self.has_allow_all_policy(c, r)]
        self.log.info(
            "%d of %d iam policies have allow all.",
            len(results), len(resources))
        return results


@Policy.action_registry.register('delete')
class PolicyDelete(BaseAction):
    """Delete an IAM Policy.

    For example, if you want to automatically delete all unused IAM policies.

    :example:

      .. code-block:: yaml

        - name: iam-delete-unused-policies
          resource: iam-policy
          filters:
            - type: unused
          actions:
            - delete

    """
github cloud-custodian / cloud-custodian / c7n / resources / ec2.py View on Github external
'c7n:matched-security-groups']
                if i.get('c7n:NetworkLocation'):
                    eni['c7n:NetworkLocation'] = i[
                        'c7n:NetworkLocation']
                interfaces.append(eni)

        groups = super(EC2ModifyVpcSecurityGroups, self).get_groups(interfaces)

        for idx, i in enumerate(interfaces):
            client.modify_network_interface_attribute(
                NetworkInterfaceId=i['NetworkInterfaceId'],
                Groups=groups[idx])


@actions.register('autorecover-alarm')
class AutorecoverAlarm(BaseAction, StateTransitionFilter):
    """Adds a cloudwatch metric alarm to recover an EC2 instance.

    This action takes effect on instances that are NOT part
    of an ASG.

    :Example:

    .. code-block:: yaml

        policies:
          - name: ec2-autorecover-alarm
            resource: ec2
            filters:
              - singleton
            actions:
              - autorecover-alarm
github cloud-custodian / cloud-custodian / c7n / resources / appelb.py View on Github external
arn_key = self.manager.resource_type.id

        # TODO implement force to reassociate.
        # TODO investigate limits on waf association.
        for r in resources:
            if state:
                client.associate_web_acl(
                    WebACLId=target_acl_id, ResourceArn=r[arn_key])
            else:
                client.disassociate_web_acl(
                    WebACLId=target_acl_id, ResourceArn=r[arn_key])


@AppELB.action_registry.register('set-s3-logging')
class SetS3Logging(BaseAction):
    """Action to enable/disable S3 logging for an application loadbalancer.

    :example:

    .. code-block:: yaml

            policies:
              - name: elbv2-test
                resource: app-elb
                filters:
                  - type: value
                    key: Attributes."access_logs.s3.enabled"
                    value: False
                actions:
                  - type: set-s3-logging
                    bucket: elbv2logtest
github cloud-custodian / cloud-custodian / c7n / resources / ec2.py View on Github external
raise


def extract_instance_id(state_error):
    "Extract an instance id from an error"
    instance_id = None
    match = RE_ERROR_INSTANCE_ID.search(str(state_error))
    if match:
        instance_id = match.groupdict().get('instance_id')
    if match is None or instance_id is None:
        raise ValueError("Could not extract instance id from error: %s" % state_error)
    return instance_id


@actions.register('resize')
class Resize(BaseAction, StateTransitionFilter):
    """Change an instance's size.

    An instance can only be resized when its stopped, this action
    can optionally restart an instance if needed to effect the instance
    type change. Instances are always left in the run state they were
    found in.

    There are a few caveats to be aware of, instance resizing
    needs to maintain compatibility for architecture, virtualization type
    hvm/pv, and ebs optimization at minimum.

    http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-resize.html
    """

    schema = type_schema(
        'resize',
github cloud-custodian / cloud-custodian / c7n / resources / rds.py View on Github external
permissions = ("rds:StopDBInstance",)

    def process(self, resources):
        client = local_session(self.manager.session_factory).client('rds')
        for r in filter(_eligible_start_stop, resources):
            try:
                client.stop_db_instance(
                    DBInstanceIdentifier=r['DBInstanceIdentifier'])
            except ClientError as e:
                log.exception(
                    "Error stopping db instance:%s err:%s",
                    r['DBInstanceIdentifier'], e)


@actions.register('start')
class Start(BaseAction):
    """Start an rds instance.
    """

    schema = type_schema('start')

    permissions = ("rds:StartDBInstance",)

    def process(self, resources):
        client = local_session(self.manager.session_factory).client('rds')
        start_filter = functools.partial(_eligible_start_stop, state='stopped')
        for r in filter(start_filter, resources):
            try:
                client.start_db_instance(
                    DBInstanceIdentifier=r['DBInstanceIdentifier'])
            except ClientError as e:
                log.exception(