def main(): parser = setup_parser() options = parser.parse_args() config = Config.empty() resources.load_resources() collection = policy_load( config, options.config_file).filter(options.policy_filter) sam = { 'AWSTemplateFormatVersion': '2010-09-09', 'Transform': 'AWS::Serverless-2016-10-31', 'Resources': {}} for p in collection: if p.provider_name != 'aws': continue exec_mode_type = p.data.get('mode', {'type': 'pull'}).get('type') if exec_mode_type == 'pull': continue sam_func = render(p) if sam_func: sam['Resources'][resource_name(p.name)] = sam_func sam_func['Properties']['CodeUri'] = './%s.zip' % p.name else: print("unable to render sam for policy:%s" % p.name) continue archive = mu.PolicyLambda(p).get_archive() with open(os.path.join(options.output_dir, "%s.zip" % p.name), 'wb') as fh: fh.write(archive.get_bytes()) with open(os.path.join(options.output_dir, 'deploy.yml'), 'w') as fh: fh.write(yaml.safe_dump(sam, default_flow_style=False))
def get_logs(self, start, end): manager = mu.LambdaManager(self.policy.session_factory) log_gen = manager.logs(mu.PolicyLambda(self.policy), start, end) return log_entries_in_range( log_gen, start, end, )
def render(p): policy_lambda = mu.PolicyLambda(p) properties = policy_lambda.get_config() # Translate api call params to sam env = properties.pop('Environment', None) if env and 'Variables' in env: properties['Environment'] = env.get('Variables') trace = properties.pop('TracingConfig', None) if trace: properties['Tracing'] = trace.get('Mode', 'PassThrough') dlq = properties.pop('DeadLetterConfig', None) if dlq: properties['DeadLetterQueue'] = { 'Type': ':sns:' in dlq['TargetArn'] and 'SNS' or 'SQS', 'TargetArn': dlq['TargetArn']} key_arn = properties.pop('KMSKeyArn') if key_arn: properties['KmsKeyArn'] if p.execution_mode == 'periodic': # Event render revents = {} revents = { 'PolicySchedule': { 'Type': 'Schedule', 'Properties': { 'Schedule': p.data.get('mode', {}).get('schedule')}} } properties['Events'] = revents elif p.execution_mode == 'cloudtrail': events = [e for e in policy_lambda.get_events(None) if isinstance(e, mu.CloudWatchEventSource)] if not events: return revents = {} for idx, e in enumerate(events): revents[ 'PolicyTrigger%s' % string.ascii_uppercase[idx]] = { 'Type': 'CloudWatchEvent', 'Properties': { 'Pattern': json.loads(e.render_event_pattern())} } properties['Events'] = revents elif p.execution_mode == 'config-rule': properties.pop('Delay', None) return { 'Type': 'AWS::Serverless::Function', 'Properties': properties}
def provision(self): with self.policy.ctx: self.policy.log.info( "Provisioning policy lambda %s", self.policy.name) try: manager = mu.LambdaManager(self.policy.session_factory) except ClientError: # For cli usage by normal users, don't assume the role just use # it for the lambda manager = mu.LambdaManager( lambda assume=False: self.policy.session_factory(assume)) return manager.publish( mu.PolicyLambda(self.policy), 'current', role=self.policy.options.assume_role)
def dispatch_render(p, sam): if p.execution_mode not in SAM_RENDER_FUNCS: raise ValueError("Unsupported sam deploy mode (%s) on policy: %s" % (p.execution_mode, p.name)) render_func = SAM_RENDER_FUNCS[p.execution_mode] if render_func is None: return None policy_lambda = mu.PolicyLambda(p) properties = render_func(p, policy_lambda, sam) properties['CodeUri'] = "./%s.zip" % p.name sam['Resources'][resource_name(p.name)] = { 'Type': 'AWS::Serverless::Function', 'Properties': properties } return policy_lambda
def logs(options, policies): assert len(policies) == 1, "Only one policy log at a time" policy = policies.pop() if not policy.is_lambda: log.debug('lambda only atm') return session_factory = SessionFactory(options.region, options.profile, options.assume_role) manager = mu.LambdaManager(session_factory) for e in manager.logs(mu.PolicyLambda(policy)): print "%s: %s" % (time.strftime( "%Y-%m-%d %H:%M:%S", time.localtime( e['timestamp'] / 1000)), e['message'])
def render_config_rule(p): policy_lambda = mu.PolicyLambda(p) policy_lambda.arn = get_lambda_arn(policy_lambda.name) config_rule = policy_lambda.get_events(Session) properties = config_rule[0].get_rule_params(policy_lambda) exec_mode_type = p.data.get('mode', {'type': 'pull'}).get('type') if exec_mode_type == 'config-poll-rule': properties.pop('Scope', None) attributes = {} attributes['Type'] = 'AWS::Config::ConfigRule' attributes['DependsOn'] = resource_name(p.name) + "Invoke" attributes['Properties'] = properties return attributes
def provision(self): # auto tag lambda policies with mode and version, we use the # version in mugc to effect cleanups. tags = self.policy.data['mode'].setdefault('tags', {}) tags['custodian-info'] = "mode=%s:version=%s" % ( self.policy.data['mode']['type'], version) from c7n import mu with self.policy.ctx: self.policy.log.info("Provisioning policy lambda %s", self.policy.name) try: manager = mu.LambdaManager(self.policy.session_factory) except ClientError: # For cli usage by normal users, don't assume the role just use # it for the lambda manager = mu.LambdaManager( lambda assume=False: self.policy.session_factory(assume)) return manager.publish(mu.PolicyLambda(self.policy), role=self.policy.options.assume_role)