c7n_azure package

Subpackages

Submodules

c7n_azure.actions module

Actions to perform on Azure resources

class c7n_azure.actions.AutoTagUser(data=None, manager=None, log_dir=None)[source]

Bases: c7n_azure.actions.AzureEventAction

Attempts to tag a resource with the first user who created/modified it.

policies:
  - name: azure-auto-tag-creator
    resource: azure.resourcegroup
    description: |
      Tag all existing resource groups with the 'CreatorEmail' tag
    actions:
     - type: auto-tag-user
       tag: CreatorEmail

This action searches from the earliest ‘write’ operation’s caller in the activity logs for a particular resource.

Note: activity logs are only held for the last 90 days.

default_user = 'Unknown'
static get_first_operation(logs, operation_name)[source]
max_query_days = 90
principal_role_jmes_path = {'type': 'subexpression', 'children': [{'type': 'field', 'children': [], 'value': 'data'}, {'type': 'field', 'children': [], 'value': 'authorization'}, {'type': 'field', 'children': [], 'value': 'evidence'}, {'type': 'field', 'children': [], 'value': 'role'}]}
principal_type_jmes_path = {'type': 'subexpression', 'children': [{'type': 'field', 'children': [], 'value': 'data'}, {'type': 'field', 'children': [], 'value': 'authorization'}, {'type': 'field', 'children': [], 'value': 'evidence'}, {'type': 'field', 'children': [], 'value': 'principalType'}]}
query_select = 'eventTimestamp, operationName, caller'
schema = {'additionalProperties': False, 'properties': {'days': {'type': 'integer'}, 'tag': {'type': 'string'}, 'type': {'enum': ['auto-tag-user']}, 'update': {'type': 'boolean'}}, 'required': ['tag', 'type'], 'type': 'object'}
service_admin_jmes_path = {'type': 'subexpression', 'children': [{'type': 'field', 'children': [], 'value': 'data'}, {'type': 'field', 'children': [], 'value': 'claims'}, {'type': 'field', 'children': [], 'value': 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress'}]}
sp_jmes_path = {'type': 'subexpression', 'children': [{'type': 'field', 'children': [], 'value': 'data'}, {'type': 'field', 'children': [], 'value': 'claims'}, {'type': 'field', 'children': [], 'value': 'appid'}]}
upn_jmes_path = {'type': 'subexpression', 'children': [{'type': 'field', 'children': [], 'value': 'data'}, {'type': 'field', 'children': [], 'value': 'claims'}, {'type': 'field', 'children': [], 'value': 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn'}]}
validate()[source]
class c7n_azure.actions.AzureBaseAction(data=None, manager=None, log_dir=None)[source]

Bases: c7n.actions.core.Action

chunk_size = 20
handle_exceptions(exceptions)[source]

raising one exception re-raises the last exception and maintains the stack trace

log = <Logger custodian.azure.AzureBaseAction (DEBUG)>
max_workers = 3
process(resources, event=None)[source]
process_in_parallel(resources, event)[source]
session = None
class c7n_azure.actions.AzureEventAction(data=None, manager=None, log_dir=None)[source]

Bases: c7n.actions.core.EventAction, c7n_azure.actions.AzureBaseAction

class c7n_azure.actions.DeleteAction(data=None, manager=None, log_dir=None)[source]

Bases: c7n_azure.actions.AzureBaseAction

schema = {'additionalProperties': False, 'properties': {'type': {'enum': ['delete']}}, 'required': ['type'], 'type': 'object'}
class c7n_azure.actions.Notify(data=None, manager=None, log_dir=None)[source]

Bases: c7n.actions.notify.BaseNotify

batch_size = 50
process(resources, event=None)[source]
schema = {'anyOf': [{'required': ['type', 'transport', 'to']}, {'required': ['type', 'transport', 'to_from']}], 'properties': {'cc': {'items': {'type': 'string'}, 'type': 'array'}, 'cc_from': {'additionalProperties': 'False', 'properties': {'expr': {'oneOf': [{'type': 'integer'}, {'type': 'string'}]}, 'format': {'enum': ['csv', 'json', 'txt', 'csv2dict']}, 'url': {'type': 'string'}}, 'required': ['url'], 'type': 'object'}, 'cc_manager': {'type': 'boolean'}, 'from': {'type': 'string'}, 'owner_absent_contact': {'items': {'type': 'string'}, 'type': 'array'}, 'subject': {'type': 'string'}, 'template': {'type': 'string'}, 'to': {'items': {'type': 'string'}, 'type': 'array'}, 'to_from': {'additionalProperties': 'False', 'properties': {'expr': {'oneOf': [{'type': 'integer'}, {'type': 'string'}]}, 'format': {'enum': ['csv', 'json', 'txt', 'csv2dict']}, 'url': {'type': 'string'}}, 'required': ['url'], 'type': 'object'}, 'transport': {'oneOf': [{'type': 'object', 'required': ['type', 'queue'], 'properties': {'queue': {'type': 'string'}, 'type': {'enum': ['asq']}}}]}, 'type': {'enum': ['notify']}}, 'type': 'object'}
send_data_message(message, session)[source]
send_to_azure_queue(queue_uri, message, session)[source]
class c7n_azure.actions.RemoveTag(data=None, manager=None, log_dir=None)[source]

Bases: c7n_azure.actions.AzureBaseAction

Removes tags from Azure resources

policies:
  - name: azure-remove-tag-resourcegroups
    resource: azure.resourcegroup
    description: |
      Remove tag for all existing resource groups with a key such as Environment
    actions:
     - type: untag
       tags: ['Environment']
schema = {'additionalProperties': False, 'properties': {'tags': {'items': {'type': 'string'}, 'type': 'array'}, 'type': {'enum': ['untag']}}, 'required': ['type'], 'type': 'object'}
validate()[source]
class c7n_azure.actions.Tag(data=None, manager=None, log_dir=None)[source]

Bases: c7n_azure.actions.AzureBaseAction

Adds tags to Azure resources

policies:
  - name: azure-tag-resourcegroups
    resource: azure.resourcegroup
    description: |
      Tag all existing resource groups with a value such as Environment
    actions:
     - type: tag
       tag: Environment
       value: Test
schema = {'additionalProperties': False, 'properties': {'tag': {'type': 'string'}, 'tags': {'type': 'object'}, 'type': {'enum': ['tag']}, 'value': {'type': 'string'}}, 'required': ['type'], 'type': 'object'}
validate()[source]
class c7n_azure.actions.TagDelayedAction(data=None, manager=None, log_dir=None)[source]

Bases: c7n_azure.actions.AzureBaseAction

Tag resources for future action.

The optional ‘tz’ parameter can be used to adjust the clock to align with a given timezone. The default value is ‘utc’.

If neither ‘days’ nor ‘hours’ is specified, Cloud Custodian will default to marking the resource for action 4 days in the future.

policies:
 - name: vm-mark-for-stop
   resource: azure.vm
   filters:
     - type: value
       key: Name
       value: instance-to-stop-in-four-days
   actions:
     - type: mark-for-op
       op: stop
default_template = 'Resource does not meet policy: {op}@{action_date}'
generate_timestamp(days, hours)[source]
schema = {'additionalProperties': False, 'properties': {'days': {'exclusiveMinimum': False, 'minimum': 0, 'type': 'integer'}, 'hours': {'exclusiveMinimum': False, 'minimum': 0, 'type': 'integer'}, 'msg': {'type': 'string'}, 'op': {'type': 'string'}, 'tag': {'type': 'string'}, 'type': {'enum': ['mark-for-op']}, 'tz': {'type': 'string'}}, 'required': ['type'], 'type': 'object'}
validate()[source]
class c7n_azure.actions.TagTrim(data=None, manager=None, log_dir=None)[source]

Bases: c7n_azure.actions.AzureBaseAction

Automatically remove tags from an azure resource. Azure Resources and Resource Groups have a limit of 15 tags. In order to make additional tag space on a set of resources, this action can be used to remove enough tags to make the desired amount of space while preserving a given set of tags. Setting the space value to 0 removes all tags but those listed to preserve.

policies:
  - name: azure-tag-trim
    comment: |
      Any instances with 14 or more tags get tags removed until
      they match the target tag count, in this case 13, so
      that we free up tag slots for another usage.
    resource: azure.resourcegroup
    filters:
        # Filter down to resources that do not have the space
        # to add additional required tags. For example, if an
        # additional 2 tags need to be added to a resource, with
        # 15 tags as the limit, then filter down to resources that
        # have 14 or more tags since they will need to have tags
        # removed for the 2 extra. This also ensures that metrics
        # reporting is correct for the policy.
       - type: value
         key: "length(Tags)"
         op: ge
         value: 14
    actions:
       - type: tag-trim
         space: 2
         preserve:
          - OwnerContact
          - Environment
          - downtime
          - custodian_status
max_tag_count = 15
schema = {'additionalProperties': False, 'properties': {'preserve': {'items': {'type': 'string'}, 'type': 'array'}, 'space': {'type': 'integer'}, 'type': {'enum': ['tag-trim']}}, 'required': ['type'], 'type': 'object'}
validate()[source]

c7n_azure.azure_events module

class c7n_azure.azure_events.AzureEventSubscription[source]

Bases: object

static create(destination, name, subscription_id, session=None, event_filter=None)[source]
class c7n_azure.azure_events.AzureEvents[source]

Bases: object

A mapping of resource types to events.

azure_events = {'AppServicePlanWrite': {'event': 'write', 'resource_provider': 'Microsoft.Web/serverFarms'}, 'BatchWrite': {'event': 'write', 'resource_provider': 'Microsoft.Batch/batchAccounts'}, 'CdnProfileWrite': {'event': 'write', 'resource_provider': 'Microsoft.Cdn/profiles'}, 'CognitiveServiceWrite': {'event': 'write', 'resource_provider': 'Microsoft.CognitiveServices/account'}, 'ContainerServiceWrite': {'event': 'write', 'resource_provider': 'Microsoft.ContainerService/managedClusters'}, 'CosmosDbWrite': {'event': 'write', 'resource_provider': 'Microsoft.DocumentDB/databaseAccounts'}, 'DataFactoryWrite': {'event': 'write', 'resource_provider': 'Microsoft.DataFactory/factories'}, 'DataLakeWrite': {'event': 'write', 'resource_provider': 'Microsoft.DataLakeStore/accounts'}, 'DiskWrite': {'event': 'write', 'resource_provider': 'Microsoft.Compute/disks'}, 'IotHubWrite': {'event': 'write', 'resource_provider': 'Microsoft.Devices/IotHubs'}, 'KeyVaultWrite': {'event': 'write', 'resource_provider': 'Microsoft.KeyVault/vaults'}, 'LoadBalancerWrite': {'event': 'write', 'resource_provider': 'Microsoft.Network/loadBalancers'}, 'NetworkInterfaceWrite': {'event': 'write', 'resource_provider': 'Microsoft.Network/networkInterfaces'}, 'NetworkSecurityGroupWrite': {'event': 'write', 'resource_provider': 'Microsoft.Network/networkSecurityGroups'}, 'PublicIpWrite': {'event': 'write', 'resource_provider': 'Microsoft.Network/publicIPAddresses'}, 'RedisWrite': {'event': 'write', 'resource_provider': 'Microsoft.Cache/Redis'}, 'ResourceGroupWrite': {'event': 'write', 'resource_provider': 'Microsoft.Resources/subscriptions/resourceGroups'}, 'RoleAssignmentWrite': {'event': 'write', 'resource_provider': 'Microsoft.Authorization/roleAssignments'}, 'RoleDefinitionW': {'event': 'write', 'resource_provider': 'Microsoft.Authorization/roleDefinitions'}, 'SqlServerWrite': {'event': 'write', 'resource_provider': 'Microsoft.Sql/servers'}, 'StorageWrite': {'event': 'write', 'resource_provider': 'Microsoft.Storage/storageAccounts'}, 'VmWrite': {'event': 'write', 'resource_provider': 'Microsoft.Compute/virtualMachines'}, 'VmssWrite': {'event': 'write', 'resource_provider': 'Microsoft.Compute/virtualMachineScaleSets'}, 'VnetWrite': {'event': 'write', 'resource_provider': 'Microsoft.Network/virtualNetworks'}, 'WebAppWrite': {'event': 'write', 'resource_provider': 'Microsoft.Web/sites'}}
classmethod get(event)[source]
classmethod get_event_operations(events)[source]

c7n_azure.constants module

Azure Functions

c7n_azure.constants.DEFAULT_CHUNK_SIZE = 20

Custom Retry Code Variables

c7n_azure.constants.DEFAULT_MAX_RETRY_AFTER = 30

KeyVault url templates

c7n_azure.constants.ENV_CUSTODIAN_DISABLE_SSL_CERT_VERIFICATION = 'CUSTODIAN_DISABLE_SSL_CERT_VERIFICATION'

Authentication Resource

c7n_azure.constants.EVENT_GRID_PRINCIPAL_ROLE_JMES_PATH = 'data.authorization.evidence.role'

Environment Variables

c7n_azure.constants.FUNCTION_PACKAGE_SAS_EXPIRY_DAYS = 3650

Event Grid Mode

c7n_azure.constants.RESOURCE_VAULT = 'https://vault.azure.net'

Threading Variable

c7n_azure.constants.TEMPLATE_KEYVAULT_URL = 'https://{0}.vault.azure.net'

Azure Functions Host Configuration

c7n_azure.dependency_manager module

class c7n_azure.dependency_manager.DependencyManager[source]

Bases: object

static check_cache(cache_metadata_file, cache_zip_file, packages)[source]
static create_cache_metadata(cache_metadata_file, cache_zip_file, packages)[source]
static download_wheels(packages, folder)[source]
static get_dependency_packages_list(packages, excluded_packages)[source]
static install_wheels(wheels_folder, install_folder)[source]
static prepare_non_binary_wheels(packages, folder)[source]

c7n_azure.entry module

c7n_azure.entry.initialize_azure()[source]

c7n_azure.filters module

class c7n_azure.filters.AzureOffHour(data, manager=None)[source]

Bases: c7n.filters.offhours.OffHour

get_tag_value(i)[source]

Get the resource’s tag value specifying its schedule.

class c7n_azure.filters.AzureOnHour(data, manager=None)[source]

Bases: c7n.filters.offhours.OnHour

get_tag_value(i)[source]

Get the resource’s tag value specifying its schedule.

class c7n_azure.filters.DiagnosticSettingsFilter(data, manager=None)[source]

Bases: c7n.filters.core.ValueFilter

process(resources, event=None)[source]

Bulk process resources and return filtered set.

process_resource_set(resources)[source]
schema = {'additionalProperties': False, 'properties': {'default': {'type': 'object'}, 'key': {'type': 'string'}, 'op': {'$ref': '#/definitions/filters_common/comparison_operators'}, 'type': {'enum': ['diagnostic-settings']}, 'value': {'$ref': '#/definitions/filters_common/value'}, 'value_from': {'$ref': '#/definitions/filters_common/value_from'}, 'value_type': {'$ref': '#/definitions/filters_common/value_types'}}, 'required': ['type'], 'type': 'object'}
class c7n_azure.filters.MetricFilter(data, manager=None)[source]

Bases: c7n.filters.core.Filter

Filters Azure resources based on live metrics from the Azure monitor

Example

Find all VMs with an average Percentage CPU greater than 75% over last 2 hours

policies:
  - name: vm-percentage-cpu
    resource: azure.vm
    filters:
      - type: metric
        metric: Percentage CPU
        aggregation: average
        op: gt
        threshold: 75
        timeframe: 2
DEFAULT_AGGREGATION = 'average'
DEFAULT_INTERVAL = 'P1D'
DEFAULT_TIMEFRAME = 24
aggregation_funcs = {'average': <function Math.mean>, 'total': <function Math.sum>}
get_metric_data(resource)[source]
passes_op_filter(resource)[source]
process(resources, event=None)[source]

Bulk process resources and return filtered set.

process_resource(resource)[source]
schema = {'properties': {'aggregation': {'enum': ['total', 'average']}, 'filter': {'type': 'string'}, 'interval': {'enum': ['PT1M', 'PT5M', 'PT15M', 'PT30M', 'PT1H', 'PT6H', 'PT12H', 'P1D']}, 'metric': {'type': 'string'}, 'no_data_action': {'enum': ['include', 'exclude']}, 'op': {'enum': ['eq', 'equal', 'ne', 'not-equal', 'gt', 'greater-than', 'ge', 'gte', 'le', 'lte', 'lt', 'less-than']}, 'threshold': {'type': 'number'}, 'timeframe': {'type': 'number'}}, 'required': ['type', 'metric', 'op', 'threshold'], 'type': 'object'}
class c7n_azure.filters.PolicyCompliantFilter(data, manager=None)[source]

Bases: c7n.filters.core.Filter

Filter resources based on Azure Policy compliance status

Filter resources by their current Azure Policy compliance status.

You can specify if you want to filter compliant or non-compliant resources.

You can provide a list of Azure Policy definitions display names or names to limit amount of non-compliant resources. By default it returns a list of all non-compliant resources.

policies:
 - name: vm-stop-marked
   resource: azure.vm
   filters:
     - type: policy-compliant
       compliant: false
       definitions:
         - "Definition display name 1"
         - "Definition display name 2"
process(resources, event=None)[source]

Bulk process resources and return filtered set.

schema = {'additionalProperties': False, 'properties': {'compliant': {'type': 'boolean'}, 'definitions': {'type': 'array'}, 'type': {'enum': ['policy-compliant']}}, 'required': ['type', 'compliant', 'type'], 'type': 'object'}
class c7n_azure.filters.TagActionFilter(data, manager=None)[source]

Bases: c7n.filters.core.Filter

Filter resources for tag specified future action

Filters resources by a ‘custodian_status’ tag which specifies a future date for an action.

The filter parses the tag values looking for an ‘op@date’ string. The date is parsed and compared to do today’s date, the filter succeeds if today’s date is gte to the target date.

The optional ‘skew’ parameter provides for incrementing today’s date a number of days into the future. An example use case might be sending a final notice email a few days before terminating an instance, or snapshotting a volume prior to deletion.

The optional ‘skew_hours’ parameter provides for incrementing the current time a number of hours into the future.

Optionally, the ‘tz’ parameter can get used to specify the timezone in which to interpret the clock (default value is ‘utc’)

policies:
 - name: vm-stop-marked
   resource: azure.vm
   filters:
     - type: marked-for-op
       # The default tag used is custodian_status
       # but that is configurable
       tag: custodian_status
       op: stop
       # Another optional tag is skew
       tz: utc
   actions:
     - type: stop
current_date = None
process(resources, event=None)[source]

Bulk process resources and return filtered set.

schema = {'additionalProperties': False, 'properties': {'op': {'type': 'string'}, 'skew': {'minimum': 0, 'type': 'number'}, 'skew_hours': {'minimum': 0, 'type': 'number'}, 'tag': {'type': 'string'}, 'type': {'enum': ['marked-for-op']}, 'tz': {'type': 'string'}}, 'required': ['type'], 'type': 'object'}
validate()[source]

validate filter config, return validation error or self

c7n_azure.function module

c7n_azure.function.main(input)[source]

c7n_azure.function_package module

class c7n_azure.function_package.FunctionPackage(name, function_path=None, target_subscription_ids=None)[source]

Bases: object

build(policy, modules, non_binary_packages, excluded_packages, queue_name=None)[source]
cache_folder
close()[source]
get_function_config(policy, queue_name=None)[source]
publish(deployment_creds)[source]
status(deployment_creds)[source]
wait_for_status(deployment_creds, retries=10, delay=15)[source]

c7n_azure.functionapp_utils module

class c7n_azure.functionapp_utils.FunctionAppUtilities[source]

Bases: object

class FunctionAppInfrastructureParameters(app_insights, service_plan, storage_account, function_app_resource_group_name, function_app_name)[source]

Bases: object

static deploy_function_app(parameters)[source]
static get_function_name(policy_name, suffix)[source]
static get_storage_account_connection_string(id)[source]
static is_consumption_plan(function_params)[source]
log = <Logger custodian.azure.function_app_utils (DEBUG)>
classmethod publish_functions_package(function_params, package)[source]
static validate_function_name(function_name)[source]

c7n_azure.handler module

c7n_azure.handler.get_tmp_output_dir()[source]
c7n_azure.handler.run(event, context, subscription_id=None)[source]

c7n_azure.output module

Provides output support for Azure Blob Storage using the ‘azure://’ prefix

class c7n_azure.output.AppInsightsLogHandler(instrumentation_key, policy_name, subscription_id, execution_id)[source]

Bases: applicationinsights.logging.LoggingHandler.LoggingHandler

emit(record)[source]

Emit a record.

If a formatter is specified, it is used to format the record. If exception information is present, an Exception telemetry object is sent instead of a Trace telemetry object.

Args:

record (logging.LogRecord). the record to format and send.

class c7n_azure.output.AppInsightsLogOutput(ctx, config=None)[source]

Bases: c7n.output.LogOutput

get_handler()[source]
log_format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s'
type = 'azure'
class c7n_azure.output.AzureStorageOutput(ctx, config=None)[source]

Bases: c7n.output.DirectoryOutput

Usage:

with AzureStorageOutput(session_factory, 'azure://bucket/prefix'):
    log.info('xyz')  # -> log messages sent to custodian-run.log.gz
DEFAULT_BLOB_FOLDER_PREFIX = '{policy_name}/{now:%Y/%m/%d/%H/}'
static get_blob_client_wrapper(output_path, ctx)[source]
get_output_path(output_url)[source]
static join(*parts)[source]
type = 'azure'
upload()[source]
class c7n_azure.output.MetricsOutput(ctx, config=None)[source]

Bases: c7n.output.Metrics

Send metrics data to app insights

type = 'azure'

c7n_azure.policy module

class c7n_azure.policy.AzureEventGridMode(policy)[source]

Bases: c7n_azure.policy.AzureFunctionMode

A policy that runs/executes in azure functions from an azure event.

get_logs(start, end)[source]

Retrieve logs for the policy

provision()[source]

Provision any resources needed for the policy.

run(event=None, lambda_context=None)[source]

Run the actual policy.

schema = {'additionalProperties': False, 'properties': {'events': {'items': {'oneOf': [{'type': 'string'}, {'type': 'object', 'required': ['resourceProvider', 'event'], 'properties': {'resourceProvider': {'type': 'string'}, 'event': {'type': 'string'}}}]}, 'type': 'array'}, 'execution-options': {'type': 'object'}, 'provision-options': {'appInsights': {'oneOf': [{'type': 'string'}, {'type': 'object', 'properties': {'name': 'string', 'location': 'string', 'resourceGroupName': 'string'}}], 'type': 'object'}, 'servicePlan': {'oneOf': [{'type': 'string'}, {'type': 'object', 'properties': {'name': 'string', 'location': 'string', 'resourceGroupName': 'string', 'skuTier': 'string', 'skuName': 'string'}}], 'type': 'object'}, 'storageAccount': {'oneOf': [{'type': 'string'}, {'type': 'object', 'properties': {'name': 'string', 'location': 'string', 'resourceGroupName': 'string'}}], 'type': 'object'}, 'type': 'object'}, 'type': {'enum': ['azure-event-grid']}}, 'required': ['events', 'type'], 'type': 'object'}
type = 'azure-event-grid'
class c7n_azure.policy.AzureFunctionMode(policy)[source]

Bases: c7n.policy.ServerlessExecutionMode

A policy that runs/executes in azure functions.

POLICY_METRICS = ('ResourceCount', 'ResourceTime', 'ActionTime')
build_functions_package(queue_name=None, target_subscription_ids=None)[source]
default_storage_name = 'custodian'
static extract_properties(options, name, properties)[source]
get_function_app_params()[source]
get_logs(start, end)[source]

Retrieve logs for the policy

provision()[source]

Provision any resources needed for the policy.

run(event=None, lambda_context=None)[source]

Run the actual policy.

schema = {'additionalProperties': False, 'properties': {'execution-options': {'type': 'object'}, 'provision-options': {'appInsights': {'oneOf': [{'type': 'string'}, {'type': 'object', 'properties': {'name': 'string', 'location': 'string', 'resourceGroupName': 'string'}}], 'type': 'object'}, 'servicePlan': {'oneOf': [{'type': 'string'}, {'type': 'object', 'properties': {'name': 'string', 'location': 'string', 'resourceGroupName': 'string', 'skuTier': 'string', 'skuName': 'string'}}], 'type': 'object'}, 'storageAccount': {'oneOf': [{'type': 'string'}, {'type': 'object', 'properties': {'name': 'string', 'location': 'string', 'resourceGroupName': 'string'}}], 'type': 'object'}, 'type': 'object'}}, 'type': 'object'}
class c7n_azure.policy.AzurePeriodicMode(policy)[source]

Bases: c7n_azure.policy.AzureFunctionMode, c7n.policy.PullMode

A policy that runs/execute s in azure functions at specified time intervals.

get_logs(start, end)[source]

Retrieve logs for the policy

provision()[source]

Provision any resources needed for the policy.

run(event=None, lambda_context=None)[source]

Run the actual policy.

schema = {'additionalProperties': False, 'properties': {'execution-options': {'type': 'object'}, 'provision-options': {'appInsights': {'oneOf': [{'type': 'string'}, {'type': 'object', 'properties': {'name': 'string', 'location': 'string', 'resourceGroupName': 'string'}}], 'type': 'object'}, 'servicePlan': {'oneOf': [{'type': 'string'}, {'type': 'object', 'properties': {'name': 'string', 'location': 'string', 'resourceGroupName': 'string', 'skuTier': 'string', 'skuName': 'string'}}], 'type': 'object'}, 'storageAccount': {'oneOf': [{'type': 'string'}, {'type': 'object', 'properties': {'name': 'string', 'location': 'string', 'resourceGroupName': 'string'}}], 'type': 'object'}, 'type': 'object'}, 'schedule': {'type': 'string'}, 'type': {'enum': ['azure-periodic']}}, 'required': ['type'], 'type': 'object'}
type = 'azure-periodic'

c7n_azure.provider module

class c7n_azure.provider.Azure[source]

Bases: c7n.provider.Provider

get_session_factory(options)[source]

Get a credential/session factory for api usage.

initialize(options)[source]

Perform any provider specific initialization

initialize_policies(policy_collection, options)[source]

Perform any initialization of policies.

Common usage is expanding policy collection for per region execution and filtering policies for applicable regions.

resource_prefix = 'azure'
resources = <c7n.registry.PluginRegistry object>
type = 'azure'

c7n_azure.query module

class c7n_azure.query.ChildDescribeSource(manager)[source]

Bases: c7n_azure.query.DescribeSource

get_query()[source]
resource_query_factory

alias of ChildResourceQuery

type = 'describe-child-azure'
class c7n_azure.query.ChildResourceManager(data, options)[source]

Bases: c7n_azure.query.QueryResourceManager

action_registry = <c7n.actions.core.ActionRegistry object>
child_source = 'describe-child-azure'
filter_registry = <c7n.filters.core.FilterRegistry object>
get_parent_manager()[source]
get_session()[source]
source_type
class c7n_azure.query.ChildResourceQuery(session_factory, manager)[source]

Bases: c7n_azure.query.ResourceQuery

A resource query for resources that must be queried with parent information. Several resource types can only be queried in the context of their parents identifiers. ie. SQL and Cosmos databases

filter(resource_manager, **params)[source]

Query a set of resources.

class c7n_azure.query.ChildTypeInfo[source]

Bases: c7n_azure.query.TypeInfo

annotate_parent = True
classmethod extra_args(parent_resource)[source]
parent_key = 'c7n:parent-id'
parent_manager_name = ''
raise_on_exception = True
class c7n_azure.query.DescribeSource(manager)[source]

Bases: object

augment(resources)[source]
get_permissions()[source]
get_resources(query)[source]
type = 'describe-azure'
class c7n_azure.query.QueryMeta[source]

Bases: type

metaclass to have consistent action/filter registry for new resources.

class c7n_azure.query.QueryResourceManager(data, options)[source]

Bases: c7n.manager.ResourceManager

action_registry = <c7n.actions.core.ActionRegistry object>
augment(resources)[source]
filter_registry = <c7n.filters.core.FilterRegistry object>
get_cache_key(query)[source]
get_client(service=None)[source]
classmethod get_model()[source]

Returns the resource meta-model.

get_permissions()[source]
get_resources(resource_ids, **params)[source]

Retrieve a set of resources by id.

get_session()[source]
get_source(source_type)[source]
static register_actions_and_filters(registry, _)[source]
resources(query=None)[source]
source_type
class c7n_azure.query.ResourceQuery(session_factory)[source]

Bases: object

filter(resource_manager, **params)[source]
static resolve(resource_type)[source]
class c7n_azure.query.TypeInfo[source]

Bases: object

client = ''
resource = 'https://management.core.windows.net/'
service = ''
class c7n_azure.query.TypeMeta[source]

Bases: type

c7n_azure.session module

class c7n_azure.session.Session(subscription_id=None, authorization_file=None, resource='https://management.core.windows.net/')[source]

Bases: object

client(client)[source]
get_bearer_token()[source]
get_credentials()[source]
get_function_target_subscription_ids()[source]
get_function_target_subscription_name()[source]
get_functions_auth_string(target_subscription_id)[source]

Build auth json string for deploying Azure Functions. Look for dedicated Functions environment variables or fall back to normal Service Principal variables.

get_session_for_resource(resource)[source]
get_subscription_id()[source]
get_tenant_id()[source]
load_auth_file(path)[source]
resource_api_version(resource_id)[source]

latest non-preview api version for resource

c7n_azure.storage_utils module

class c7n_azure.storage_utils.StorageUtilities[source]

Bases: object

static create_queue_from_storage_account(storage_account, name, session)[source]
static delete_queue_from_storage_account(storage_account, name, session)[source]
static delete_queue_message(queue_service, queue_name, message)[source]
static get_blob_client_by_uri(storage_uri, session)[source]
static get_blob_client_from_storage_account(resource_group, name, session, sas_generation=False)[source]
static get_queue_client_by_uri(queue_uri, session)[source]
static get_queue_messages(queue_service, queue_name, num_messages=None)[source]
get_storage_from_uri[source]
static get_storage_token(session)[source]
static put_queue_message(queue_service, queue_name, content)[source]

c7n_azure.tags module

class c7n_azure.tags.TagHelper[source]

Bases: object

static add_tags(tag_action, resource, tags_to_add)[source]
static get_tag_value(resource, tag, utf_8=False)[source]

Get the resource’s tag value.

log = <Logger custodian.azure.utils.TagHelper (DEBUG)>
static remove_tags(tag_action, resource, tags_to_delete)[source]
static update_resource_tags(tag_action, resource, tags)[source]

c7n_azure.utils module

class c7n_azure.utils.AppInsightsHelper[source]

Bases: object

static get_instrumentation_key(url)[source]
log = <Logger custodian.azure.utils.AppInsightsHelper (DEBUG)>
class c7n_azure.utils.GraphHelper[source]

Bases: object

static get_principal_dictionary(graph_client, object_ids, raise_on_graph_call_error=False)[source]

Retrieves Azure AD Objects for corresponding object ids passed. :param graph_client: A client for Microsoft Graph. :param object_ids: The object ids to retrieve Azure AD objects for. :param raise_on_graph_call_error: A boolean indicate whether an error should be raised if the underlying Microsoft Graph call fails. :return: A dictionary keyed by object id with the Azure AD object as the value. Note: empty Azure AD objects could be returned if not found in the graph.

static get_principal_name(graph_object)[source]

Attempts to resolve a principal name. :param graph_object: the Azure AD Graph Object :return: The resolved value or an empty string if unsuccessful.

log = <Logger custodian.azure.utils.GraphHelper (DEBUG)>
class c7n_azure.utils.IpRangeHelper[source]

Bases: object

static parse_ip_ranges(data, key)[source]

Parses IP range or CIDR mask. :param data: Dictionary where to look for the value. :param key: Key for the value to be parsed. :return: Set of IP ranges and networks.

class c7n_azure.utils.ManagedGroupHelper[source]

Bases: object

static get_subscriptions_list(managed_resource_group, credentials)[source]
class c7n_azure.utils.Math[source]

Bases: object

static mean(numbers)[source]
static sum(numbers)[source]
class c7n_azure.utils.PortsRangeHelper[source]

Bases: object

class PortsRange(start, end)

Bases: tuple

end

Alias for field number 1

start

Alias for field number 0

static build_ports_dict(nsg, direction_key, ip_protocol)[source]

Build entire ports array filled with True (Allow), False (Deny) and None(default - Deny) based on the provided Network Security Group object, direction and protocol.

static get_ports_set_from_rule(rule)[source]

Extract port ranges from NSG rule and convert it to the set of integers

static get_ports_set_from_string(ports)[source]

Convert ports range string to the set of integers Example: “10-12, 20” -> {10, 11, 12, 20}

static get_ports_strings_from_list(data)[source]

Transform a list of port numbers to the list of strings with port ranges Example: [10, 12, 13, 14, 15] -> [‘10’, ‘12-15’]

static validate_ports_string(ports)[source]

Validate that provided string has proper port numbers: 1. port number < 65535 2. range start < range end

class c7n_azure.utils.ResourceIdParser[source]

Bases: object

static get_namespace(resource_id)[source]
static get_resource_group(resource_id)[source]
static get_resource_name(resource_id)[source]
static get_resource_type(resource_id)[source]
static get_subscription_id(resource_id)[source]
class c7n_azure.utils.RetentionPeriod[source]

Bases: object

PATTERN = re.compile('^P([1-9][0-9]*)([DWMY])$')
class Units(str_value, iso8601_symbol)[source]

Bases: enum.Enum

An enumeration.

day = ('day', 'D')
days = ('days', 'D')
month = ('month', 'M')
months = ('months', 'M')
week = ('week', 'W')
weeks = ('weeks', 'W')
year = ('year', 'Y')
years = ('years', 'Y')
static duration_from_period_and_units(period, retention_period_unit)[source]
static parse_iso8601_retention_period(iso8601_retention_period)[source]

A simplified iso8601 duration parser that only accepts one duration designator.

class c7n_azure.utils.StringUtils[source]

Bases: object

static equal(a, b, case_insensitive=True)[source]
static naming_hash(val, length=8)[source]
static snake_to_camel(string)[source]
class c7n_azure.utils.ThreadHelper[source]

Bases: object

disable_multi_threading = False
static execute_in_parallel(resources, event, execution_method, executor_factory, log, max_workers=3, chunk_size=20)[source]
c7n_azure.utils.azure_name_value_pair(name, value)[source]
c7n_azure.utils.custodian_azure_send_override(self, request, headers=None, content=None, **kwargs)[source]

Overrides ServiceClient.send() function to implement retries & log headers

c7n_azure.utils.generate_key_vault_url(name)[source]
c7n_azure.utils.now(tz=None)[source]

The datetime object for the current time in UTC

c7n_azure.utils.utcnow()[source]

The datetime object for the current time in UTC

Module contents