Exemple #1
0
    def test_get_resource_class(self):
        with self.assertRaises(KeyError) as ectx:
            get_resource_class('aws.xyz')
        self.assertIn("resource: xyz", str(ectx.exception))

        with self.assertRaises(KeyError) as ectx:
            get_resource_class('xyz.foo')
        self.assertIn("provider: xyz", str(ectx.exception))

        ec2 = get_resource_class('aws.ec2')
        self.assertEqual(ec2.type, 'ec2')
 def _get_resource_id(self, resource, policy):
     """
     Obtain the id for a given policy from a dict of resources.
     :param resource: the dict of resources
     :param policy: the name of the policy
     :return: the resource_id the policy affects
     :rtype: string
     """
     resource_type = resource.get(policy,
                                  {}).get(self.RESOURCE_TYPE_KEY,
                                          self.UNKNOWN_RESOURCE_TYPE)
     if resource_type == self.UNKNOWN_RESOURCE_TYPE:
         return
     load_available()
     _id = self.UNKNOWN_RESOURCE_ID
     try:
         _id = get_resource_class(resource_type) \
             .resource_type() \
             .id
     except Exception:
         logger.warning('unable to get resource_id for %s - id: %s', policy,
                        _id)
     return _id
Exemple #3
0
 def load_resource_manager(self):
     factory = get_resource_class(self.data.get('resource'))
     return factory(self.ctx, self.data)
Exemple #4
0
def report(config, output, use, output_dir, accounts,
           field, no_default_fields, tags, region, debug, verbose,
           policy, policy_tags, format, resource, cache_path):
    """report on a cross account policy execution."""
    accounts_config, custodian_config, executor = init(
        config, use, debug, verbose, accounts, tags, policy,
        resource=resource, policy_tags=policy_tags)

    resource_types = set()
    for p in custodian_config.get('policies'):
        resource_types.add(p['resource'])
    if len(resource_types) > 1:
        raise ValueError("can only report on one resource type at a time")
    elif not len(custodian_config['policies']) > 0:
        raise ValueError("no matching policies found")

    records = []
    with executor(max_workers=WORKER_COUNT) as w:
        futures = {}
        for a in accounts_config.get('accounts', ()):
            for r in resolve_regions(region or a.get('regions', ())):
                futures[w.submit(
                    report_account,
                    a, r,
                    custodian_config,
                    output_dir,
                    cache_path,
                    debug)] = (a, r)

        for f in as_completed(futures):
            a, r = futures[f]
            if f.exception():
                if debug:
                    raise
                log.warning(
                    "Error running policy in %s @ %s exception: %s",
                    a['name'], r, f.exception())
            records.extend(f.result())

    log.debug(
        "Found %d records across %d accounts and %d policies",
        len(records), len(accounts_config['accounts']),
        len(custodian_config['policies']))

    if format == 'json':
        dumps(records, output, indent=2)
        return

    prefix_fields = OrderedDict(
        (('Account', 'account'), ('Region', 'region'), ('Policy', 'policy')))
    config = Config.empty()

    factory = get_resource_class(list(resource_types)[0])
    formatter = Formatter(
        factory.resource_type,
        extra_fields=field,
        include_default_fields=not(no_default_fields),
        include_region=False,
        include_policy=False,
        fields=prefix_fields)

    rows = formatter.to_csv(records, unique=False)
    writer = UnicodeWriter(output, formatter.headers())
    writer.writerow(formatter.headers())
    writer.writerows(rows)