How to use the c7n.utils.local_session 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 / tools / c7n_azure / tests_azure / tests_resources / test_storage.py View on Github external
def _get_storage_management_client_api_string(self):
        return local_session(Session)\
            .client('azure.mgmt.storage.StorageManagementClient')\
            .DEFAULT_API_VERSION.replace("-", "_")
github cloud-custodian / cloud-custodian / tools / c7n_azure / tests_azure / tests_resources / test_cosmos_db.py View on Github external
'actions': [
                {
                    'type': 'save-throughput-state',
                    'state-tag': 'test-store-throughput'
                }
            ]
        })

        collections = p.run()
        self.assertEqual(len(collections), 1)

        account_name = collections[0]['c7n:parent']['name']

        self.sleep_in_live_mode()

        client = local_session(Session).client(
            'azure.mgmt.cosmosdb.CosmosDBManagementClient')
        cosmos_account = client.database_accounts.get('test_cosmosdb', account_name)
        self.assertTrue('test-store-throughput' in cosmos_account.tags)

        tag_value = cosmos_account.tags['test-store-throughput']
        expected_throughput = collections[0]['c7n:offer']['content']['offerThroughput']
        expected_scaled_throughput = int(expected_throughput / THROUGHPUT_MULTIPLIER)
        expected_tag_value = '{}:{}'.format(collections[0]['_rid'], expected_scaled_throughput)
        self.assertEqual(expected_tag_value, tag_value)
github cloud-custodian / cloud-custodian / tests / test_cloudfront.py View on Github external
"filters": [
                    {"type": "value", "key": k, "value": "allow-all", "op": "contains"}
                ],
                "actions": [
                    {"type": "set-protocols", "ViewerProtocolPolicy": "https-only"}
                ],
            },
            session_factory=factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 1)
        expr = jmespath.compile(k)
        r = expr.search(resources[0])
        self.assertTrue("allow-all" in r)

        client = local_session(factory).client("cloudfront")
        resp = client.list_distributions()
        self.assertEqual(
            resp["DistributionList"]["Items"][0]["DefaultCacheBehavior"][
                "ViewerProtocolPolicy"
            ],
            "https-only",
        )
github cloud-custodian / cloud-custodian / c7n / policy.py View on Github external
def resolve_resources(self, event):
        session = utils.local_session(self.policy.resource_manager.session_factory)
        health = session.client('health', region_name='us-east-1')
        he_arn = event['detail']['eventArn']
        resource_arns = self.process_event_arns(health, [he_arn])

        m = self.policy.resource_manager.get_model()
        if 'arn' in m.id.lower():
            resource_ids = [r['entityValue'].rsplit('/', 1)[-1] for r in resource_arns]
        else:
            resource_ids = [r['entityValue'] for r in resource_arns]

        resources = self.policy.resource_manager.get_resources(resource_ids)
        for r in resources:
            r.setdefault('c7n:HealthEvent', []).append(he_arn)
        return resources
github cloud-custodian / cloud-custodian / tools / c7n_azure / c7n_azure / resources / subscription.py View on Github external
def _get_subscription(self, session_factory, config):
        session = local_session(session_factory)
        client = SubscriptionClient(session.get_credentials())
        details = client.subscriptions.get(subscription_id=session.get_subscription_id())
        return details.serialize(True)
github cloud-custodian / cloud-custodian / tools / c7n_azure / c7n_azure / functionapp_utils.py View on Github external
def publish_functions_package(cls, function_params, package):
        session = local_session(Session)
        web_client = session.client('azure.mgmt.web.WebSiteManagementClient')

        cls.log.info('Publishing Function application')

        # provision using Kudu Zip-Deploy
        if not cls.is_consumption_plan(function_params):
            publish_creds = web_client.web_apps.list_publishing_credentials(
                function_params.function_app_resource_group_name,
                function_params.function_app_name).result()

            if package.wait_for_status(publish_creds):
                package.publish(publish_creds)
            else:
                cls.log.error("Aborted deployment, ensure Application Service is healthy.")
        # provision using WEBSITE_RUN_FROM_PACKAGE
        else:
github cloud-custodian / cloud-custodian / c7n / resources / ecs.py View on Github external
def augment(self, resources):
        results = []
        client = local_session(self.session_factory).client('ecs')
        for task_def_set in resources:
            response = client.describe_task_definition(
                taskDefinition=task_def_set,
                include=['TAGS'])
            r = response['taskDefinition']
            r['tags'] = response.get('tags', [])
            results.append(r)
        ecs_tag_normalize(results)
        return results
github cloud-custodian / cloud-custodian / c7n / tags.py View on Github external
def process_transform(self, tag_value, resource_set):
        """
        Transform tag value

        - Collect value from tag
        - Transform Tag value
        - Assign new value for key
        """
        self.log.info("Transforming tag value on %s instances" % (
            len(resource_set)))
        key = self.data.get('key')

        c = utils.local_session(self.manager.session_factory).client('ec2')

        self.create_tag(
            c,
            [r[self.id_key] for r in resource_set if len(
                r.get('Tags', [])) < 50],
            key, tag_value)
github jtroberts83 / Cloud-Custodian / Other-Related-Scripts / random / s3.py View on Github external
def process(self, resources):
        enabled = self.data.get('enabled', True)

        for r in resources:
            client = bucket_client(local_session(self.manager.session_factory), r)
            if 'TargetBucket' in r['Logging']:
                r['Logging'] = {'Status': 'Enabled'}
            else:
                r['Logging'] = {'Status': 'Disabled'}
            if enabled and (r['Logging']['Status'] == 'Disabled'):
                # code to support expand_variables()
                session = local_session(self.manager.session_factory)
                iam_client = session.client('iam')
                aliases = iam_client.list_account_aliases().get('AccountAliases', ('',))
                account_name = aliases and aliases[0] or ""

                variables = {
                    'account_id': self.manager.config.account_id,
                    'account': account_name,
                    'region': self.manager.config.region,
                    'source_bucket_name': r['Name'],
                    'target_bucket_name': self.data.get('target_bucket'),
                    'target_prefix': self.data.get('target_prefix'),
                    'data': self.data.copy()
                }
                self.data = self.expand_variables(variables)
                # log.info("target_bucket=%s" % target_bucket)
github cloud-custodian / cloud-custodian / tools / c7n_gcp / c7n_gcp / query.py View on Github external
def get_client(self):
        return local_session(self.session_factory).client(
            self.resource_type.service,
            self.resource_type.version,
            self.resource_type.component)