text
stringlengths
81
112k
Checks (recursively) if the directory contains .py or .pyc files def contains_python_files_or_subdirs(folder): """ Checks (recursively) if the directory contains .py or .pyc files """ for root, dirs, files in os.walk(folder): if [filename for filename in files if filename.endswith('.py') or fil...
Checks if a directory lies in the same directory as a .py file with the same name. def conflicts_with_a_neighbouring_module(directory_path): """ Checks if a directory lies in the same directory as a .py file with the same name. """ parent_dir_path, current_dir_name = os.path.split(os.path.normpath(dire...
Checks if an S3 bucket name is valid according to https://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html#bucketnamingrules def is_valid_bucket_name(name): """ Checks if an S3 bucket name is valid according to https://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html#bucketnamingr...
Merge the values of headers and multiValueHeaders into a single dict. Opens up support for multivalue headers via API Gateway and ALB. See: https://github.com/Miserlou/Zappa/pull/1756 def merge_headers(event): """ Merge the values of headers and multiValueHeaders into a single dict. Opens up suppor...
Given some event_info via API Gateway, create and return a valid WSGI request environ. def create_wsgi_request(event_info, server_name='zappa', script_name=None, trailing_slash=True, binary_support=False, ...
Given the WSGI environ and the response, log this event in Common Log Format. def common_log(environ, response, response_time=None): """ Given the WSGI environ and the response, log this event in Common Log Format. """ logger = logging.getLogger() if response_time: formatter = Ap...
Puts the project files from S3 in /tmp and adds to path def load_remote_project_archive(self, project_zip_path): """ Puts the project files from S3 in /tmp and adds to path """ project_folder = '/tmp/{0!s}'.format(self.settings.PROJECT_NAME) if not os.path.isdir(project_folder):...
Attempt to read a file from s3 containing a flat json object. Adds each key->value pair as environment variables. Helpful for keeping sensitiZve or stage-specific configuration variables in s3 instead of version control. def load_remote_settings(self, remote_bucket, remote_file): """ ...
Given a modular path to a function, import that module and return the function. def import_module_and_get_function(whole_function): """ Given a modular path to a function, import that module and return the function. """ module, function = whole_function.rsplit('.', 1) ...
Given a function and event context, detect signature and execute, returning any result. def run_function(app_function, event, context): """ Given a function and event context, detect signature and execute, returning any result. """ # getargspec does not support python 3 ...
Get the associated function to execute for a triggered AWS event Support S3, SNS, DynamoDB, kinesis and SQS events def get_function_for_aws_event(self, record): """ Get the associated function to execute for a triggered AWS event Support S3, SNS, DynamoDB, kinesis and SQS events ...
For the given event build ARN and return the configured function def get_function_from_bot_intent_trigger(self, event): """ For the given event build ARN and return the configured function """ intent = event.get('currentIntent') if intent: intent = intent.get('name')...
Get the associated function to execute for a cognito trigger def get_function_for_cognito_trigger(self, trigger): """ Get the associated function to execute for a cognito trigger """ print("get_function_for_cognito_trigger", self.settings.COGNITO_TRIGGER_MAPPING, trigger, self.settings....
An AWS Lambda function which parses specific API Gateway input into a WSGI request, feeds it to our WSGI app, procceses the response, and returns that back to the API Gateway. def handler(self, event, context): """ An AWS Lambda function which parses specific API Gateway input into a ...
validate the incoming token def lambda_handler(event, context): print("Client token: " + event['authorizationToken']) print("Method ARN: " + event['methodArn']) """validate the incoming token""" """and produce the principal user identifier associated with the token""" """this could be accomplished...
Adds a method to the internal lists of allowed or denied methods. Each object in the internal list contains a resource ARN and a condition statement. The condition statement can be null. def _addMethod(self, effect, verb, resource, conditions): """Adds a method to the internal lists of allowed ...
Adds an API Gateway method (Http verb + Resource path) to the list of allowed methods and includes a condition for the policy statement. More on AWS policy conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition def allowMethodWithConditions(self, ver...
Adds an API Gateway method (Http verb + Resource path) to the list of denied methods and includes a condition for the policy statement. More on AWS policy conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition def denyMethodWithConditions(self, verb,...
Generates the policy document based on the internal lists of allowed and denied conditions. This will generate a policy with two main statements for the effect: one statement for Allow and one statement for Deny. Methods that includes conditions will have their own statement in the policy. def ...
Allow for custom endpoint urls for non-AWS (testing and bootleg cloud) deployments def configure_boto_session_method_kwargs(self, service, kw): """Allow for custom endpoint urls for non-AWS (testing and bootleg cloud) deployments""" if service in self.endpoint_urls and not 'endpoint_url' in kw: ...
A wrapper to apply configuration options to boto clients def boto_client(self, service, *args, **kwargs): """A wrapper to apply configuration options to boto clients""" return self.boto_session.client(service, *args, **self.configure_boto_session_method_kwargs(service, kwargs))
A wrapper to apply configuration options to boto resources def boto_resource(self, service, *args, **kwargs): """A wrapper to apply configuration options to boto resources""" return self.boto_session.resource(service, *args, **self.configure_boto_session_method_kwargs(service, kwargs))
Returns a troposphere Ref to a value cached as a parameter. def cache_param(self, value): '''Returns a troposphere Ref to a value cached as a parameter.''' if value not in self.cf_parameters: keyname = chr(ord('A') + len(self.cf_parameters)) param = self.cf_template.add_paramet...
For a given package, returns a list of required packages. Recursive. def get_deps_list(self, pkg_name, installed_distros=None): """ For a given package, returns a list of required packages. Recursive. """ # https://github.com/Miserlou/Zappa/issues/1478. Using `pkg_resources` # ...
Takes the installed zappa and brings it into a fresh virtualenv-like folder. All dependencies are then downloaded. def create_handler_venv(self): """ Takes the installed zappa and brings it into a fresh virtualenv-like folder. All dependencies are then downloaded. """ import subprocess ...
Returns the path to the current virtualenv def get_current_venv(): """ Returns the path to the current virtualenv """ if 'VIRTUAL_ENV' in os.environ: venv = os.environ['VIRTUAL_ENV'] elif os.path.exists('.python-version'): # pragma: no cover try: ...
Create a Lambda-ready zip file of the current virtualenvironment and working directory. Returns path to that file. def create_lambda_zip( self, prefix='lambda_package', handler_file=None, slim_handler=False, ...
Extracts the lambda package into a given path. Assumes the package exists in lambda packages. def extract_lambda_package(self, package_name, path): """ Extracts the lambda package into a given path. Assumes the package exists in lambda packages. """ lambda_package = lambda_packages[pack...
Returns a dict of installed packages that Zappa cares about. def get_installed_packages(site_packages, site_packages_64): """ Returns a dict of installed packages that Zappa cares about. """ import pkg_resources package_to_keep = [] if os.path.isdir(site_packages): ...
Checks if a given package version binary should be copied over from lambda packages. package_name should be lower-cased version of package name. def have_correct_lambda_package_version(self, package_name, package_version): """ Checks if a given package version binary should be copied over from ...
Downloads a given url in chunks and writes to the provided stream (can be any io stream). Displays the progress bar for the download. def download_url_with_progress(url, stream, disable_progress): """ Downloads a given url in chunks and writes to the provided stream (can be any io stream). ...
Gets the locally stored version of a manylinux wheel. If one does not exist, the function downloads it. def get_cached_manylinux_wheel(self, package_name, package_version, disable_progress=False): """ Gets the locally stored version of a manylinux wheel. If one does not exist, the function downloads it...
For a given package name, returns a link to the download URL, else returns None. Related: https://github.com/Miserlou/Zappa/issues/398 Examples here: https://gist.github.com/perrygeo/9545f94eaddec18a65fd7b56880adbae This function downloads metadata JSON of `package_name` from Pypi ...
r""" Given a file, upload it to S3. Credentials should be stored in environment variables or ~/.aws/credentials (%USERPROFILE%\.aws\credentials on Windows). Returns True on success, false on failure. def upload_to_s3(self, source_path, bucket_name, disable_progress=False): r""" ...
Copies src file to destination within a bucket. def copy_on_s3(self, src_file_name, dst_file_name, bucket_name): """ Copies src file to destination within a bucket. """ try: self.s3_client.head_bucket(Bucket=bucket_name) except botocore.exceptions.ClientError as e: ...
Given a file name and a bucket, remove it from S3. There's no reason to keep the file hosted on S3 once its been made into a Lambda function, so we can delete it from S3. Returns True on success, False on failure. def remove_from_s3(self, file_name, bucket_name): """ Given a file name...
Given a bucket and key (or a local path) of a valid Lambda-zip, a function name and a handler, register that Lambda function. def create_lambda_function( self, bucket=None, function_name=None, handler=None, ...
Given a bucket and key (or a local path) of a valid Lambda-zip, a function name and a handler, update that Lambda function's code. Optionally, delete previous versions if they exceed the optional limit. def update_lambda_function(self, bucket, function_name, s3_key=None, publish=True, local_zip=None, num_revis...
Given an existing function ARN, update the configuration variables. def update_lambda_configuration( self, lambda_arn, function_name, handler, description='...
Directly invoke a named Lambda function with a payload. Returns the response. def invoke_lambda_function( self, function_name, payload, invocation_type='Event', log_type='Tail', ...
Rollback the lambda function code 'versions_back' number of revisions. Returns the Function ARN. def rollback_lambda_function_version(self, function_name, versions_back=1, publish=True): """ Rollback the lambda function code 'versions_back' number of revisions. Returns the Function AR...
Returns the lambda function ARN, given a name This requires the "lambda:GetFunction" role. def get_lambda_function(self, function_name): """ Returns the lambda function ARN, given a name This requires the "lambda:GetFunction" role. """ response = self.lambda_client.get...
Simply returns the versions available for a Lambda function, given a function name. def get_lambda_function_versions(self, function_name): """ Simply returns the versions available for a Lambda function, given a function name. """ try: response = self.lambda_client.list_ver...
The `zappa deploy` functionality for ALB infrastructure. def deploy_lambda_alb( self, lambda_arn, lambda_name, alb_vpc_config, timeout ): """ The `zappa deploy` func...
The `zappa undeploy` functionality for ALB infrastructure. def undeploy_lambda_alb(self, lambda_name): """ The `zappa undeploy` functionality for ALB infrastructure. """ print("Undeploying ALB infrastructure...") # Locate and delete alb/lambda permissions try: ...
Create the API Gateway for this Zappa deployment. Returns the new RestAPI CF resource. def create_api_gateway_routes( self, lambda_arn, api_name=None, api_key_required=False, ...
Create Authorizer for API gateway def create_authorizer(self, restapi, uri, authorizer): """ Create Authorizer for API gateway """ authorizer_type = authorizer.get("type", "TOKEN").upper() identity_validation_expression = authorizer.get('validation_expression', None) au...
Set up the methods, integration responses and method responses for a given API Gateway resource. def create_and_setup_methods( self, restapi, resource, api_key_required, ...
Set up the methods, integration responses and method responses for a given API Gateway resource. def create_and_setup_cors(self, restapi, resource, uri, depth, config): """ Set up the methods, integration responses and method responses for a given API Gateway resource. """ if config is ...
Deploy the API Gateway! Return the deployed API URL. def deploy_api_gateway( self, api_id, stage_name, stage_description="", description="", cache_cluster_enabled=False, ...
Remove binary support def remove_binary_support(self, api_id, cors=False): """ Remove binary support """ response = self.apigateway_client.get_rest_api( restApiId=api_id ) if "binaryMediaTypes" in response and "*/*" in response["binaryMediaTypes"]: ...
Add Rest API compression def add_api_compression(self, api_id, min_compression_size): """ Add Rest API compression """ self.apigateway_client.update_rest_api( restApiId=api_id, patchOperations=[ { 'op': 'replace', ...
Generator that allows to iterate per API keys associated to an api_id and a stage_name. def get_api_keys(self, api_id, stage_name): """ Generator that allows to iterate per API keys associated to an api_id and a stage_name. """ response = self.apigateway_client.get_api_keys(limit=500) ...
Create new API key and link it with an api_id and a stage_name def create_api_key(self, api_id, stage_name): """ Create new API key and link it with an api_id and a stage_name """ response = self.apigateway_client.create_api_key( name='{}_{}'.format(stage_name, api_id), ...
Remove a generated API key for api_id and stage_name def remove_api_key(self, api_id, stage_name): """ Remove a generated API key for api_id and stage_name """ response = self.apigateway_client.get_api_keys( limit=1, nameQuery='{}_{}'.format(stage_name, api_id) ...
Add api stage to Api key def add_api_stage_to_api_key(self, api_key, api_id, stage_name): """ Add api stage to Api key """ self.apigateway_client.update_api_key( apiKey=api_key, patchOperations=[ { 'op': 'add', ...
Return an object that describes a change of configuration on the given staging. Setting will be applied on all available HTTP methods. def get_patch_op(self, keypath, value, op='replace'): """ Return an object that describes a change of configuration on the given staging. Setting will b...
Generator that allows to iterate per every available apis. def get_rest_apis(self, project_name): """ Generator that allows to iterate per every available apis. """ all_apis = self.apigateway_client.get_rest_apis( limit=500 ) for api in all_apis['items']: ...
Delete a deployed REST API Gateway. def undeploy_api_gateway(self, lambda_name, domain_name=None, base_path=None): """ Delete a deployed REST API Gateway. """ print("Deleting API Gateway..") api_id = self.get_api_id(lambda_name) if domain_name: # XXX - Rem...
Update CloudWatch metrics configuration. def update_stage_config( self, project_name, stage_name, cloudwatch_log_level, cloudwatch_data_trace, cloudwatch_me...
Delete the CF stack managed by Zappa. def delete_stack(self, name, wait=False): """ Delete the CF stack managed by Zappa. """ try: stack = self.cf_client.describe_stacks(StackName=name)['Stacks'][0] except: # pragma: no cover print('No Zappa stack named {...
Build the entire CF stack. Just used for the API Gateway, but could be expanded in the future. def create_stack_template( self, lambda_arn, lambda_name, api_key_required, iam_authori...
Update or create the CF stack managed by Zappa. def update_stack(self, name, working_bucket, wait=False, update_only=False, disable_progress=False): """ Update or create the CF stack managed by Zappa. """ capabilities = [] template = name + '-template-' + str(int(time.time())) ...
Given a name, describes CloudFront stacks and returns dict of the stack Outputs , else returns an empty dict. def stack_outputs(self, name): """ Given a name, describes CloudFront stacks and returns dict of the stack Outputs , else returns an empty dict. """ try: ...
Given a lambda_name and stage_name, return a valid API URL. def get_api_url(self, lambda_name, stage_name): """ Given a lambda_name and stage_name, return a valid API URL. """ api_id = self.get_api_id(lambda_name) if api_id: return "https://{}.execute-api.{}.amazonaw...
Given a lambda_name, return the API id. def get_api_id(self, lambda_name): """ Given a lambda_name, return the API id. """ try: response = self.cf_client.describe_stack_resource(StackName=lambda_name, LogicalResou...
Creates the API GW domain and returns the resulting DNS name. def create_domain_name(self, domain_name, certificate_name, certificate_body=None, certificate_private_key=None, certifica...
Updates Route53 Records following GW domain creation def update_route53_records(self, domain_name, dns_name): """ Updates Route53 Records following GW domain creation """ zone_id = self.get_hosted_zone_id_for_domain(domain_name) is_apex = self.route53.get_hosted_zone(Id=zone_id...
This updates your certificate information for an existing domain, with similar arguments to boto's update_domain_name API Gateway api. It returns the resulting new domain information including the new certificate's ARN if created during this process. Previously, this method involved do...
Update domain base path mapping on API Gateway if it was changed def update_domain_base_path_mapping(self, domain_name, lambda_name, stage, base_path): """ Update domain base path mapping on API Gateway if it was changed """ api_id = self.get_api_id(lambda_name) if not api_id: ...
Same behaviour of list_host_zones, but transparently handling pagination. def get_all_zones(self): """Same behaviour of list_host_zones, but transparently handling pagination.""" zones = {'HostedZones': []} new_zones = self.route53.list_hosted_zones(MaxItems='100') while new_zones['IsT...
Scan our hosted zones for the record of a given name. Returns the record entry, else None. def get_domain_name(self, domain_name, route53=True): """ Scan our hosted zones for the record of a given name. Returns the record entry, else None. """ # Make sure api gateway ...
Given our role name, get and set the credentials_arn. def get_credentials_arn(self): """ Given our role name, get and set the credentials_arn. """ role = self.iam.Role(self.role_name) self.credentials_arn = role.arn return role, self.credentials_arn
Create and defines the IAM roles and policies necessary for Zappa. If the IAM role already exists, it will be updated if necessary. def create_iam_roles(self): """ Create and defines the IAM roles and policies necessary for Zappa. If the IAM role already exists, it will be updated if ...
Remove obsolete policy statements to prevent policy from bloating over the limit after repeated updates. def _clear_policy(self, lambda_name): """ Remove obsolete policy statements to prevent policy from bloating over the limit after repeated updates. """ try: policy_respons...
Create permissions to link to an event. Related: http://docs.aws.amazon.com/lambda/latest/dg/with-s3-example-configure-event-source.html def create_event_permission(self, lambda_name, principal, source_arn): """ Create permissions to link to an event. Related: http://docs.aws.amazon.c...
Given a Lambda ARN, name and a list of events, schedule this as CloudWatch Events. 'events' is a list of dictionaries, where the dict must contains the string of a 'function' and the string of the event 'expression', and an optional 'name' and 'description'. Expressions can be in rate or cron ...
Returns an AWS-valid Lambda event name. def get_event_name(lambda_name, name): """ Returns an AWS-valid Lambda event name. """ return '{prefix:.{width}}-{postfix}'.format(prefix=lambda_name, width=max(0, 63 - len(name)), postfix=name)[:64]
Returns an AWS-valid CloudWatch rule name using a digest of the event name, lambda name, and function. This allows support for rule names that may be longer than the 64 char limit. def get_hashed_rule_name(event, function, lambda_name): """ Returns an AWS-valid CloudWatch rule name using a dige...
Delete a CWE rule. This deletes them, but they will still show up in the AWS console. Annoying. def delete_rule(self, rule_name): """ Delete a CWE rule. This deletes them, but they will still show up in the AWS console. Annoying. """ logger.debug('De...
Get all of the rule names associated with a lambda function. def get_event_rule_names_for_lambda(self, lambda_arn): """ Get all of the rule names associated with a lambda function. """ response = self.events_client.list_rule_names_by_target(TargetArn=lambda_arn) rule_names = res...
Get all of the rule details associated with this function. def get_event_rules_for_lambda(self, lambda_arn): """ Get all of the rule details associated with this function. """ rule_names = self.get_event_rule_names_for_lambda(lambda_arn=lambda_arn) return [self.events_client.des...
Given a list of events, unschedule these CloudWatch Events. 'events' is a list of dictionaries, where the dict must contains the string of a 'function' and the string of the event 'expression', and an optional 'name' and 'description'. def unschedule_events(self, events, lambda_arn=None, lambda_name=N...
Create the SNS-based async topic. def create_async_sns_topic(self, lambda_name, lambda_arn): """ Create the SNS-based async topic. """ topic_name = get_topic_name(lambda_name) # Create SNS topic topic_arn = self.sns_client.create_topic( Name=topic_name)['Topi...
Remove the async SNS topic. def remove_async_sns_topic(self, lambda_name): """ Remove the async SNS topic. """ topic_name = get_topic_name(lambda_name) removed_arns = [] for sub in self.sns_client.list_subscriptions()['Subscriptions']: if topic_name in sub['T...
Create the DynamoDB table for async task return values def create_async_dynamodb_table(self, table_name, read_capacity, write_capacity): """ Create the DynamoDB table for async task return values """ try: dynamodb_table = self.dynamodb_client.describe_table(TableName=table_n...
Fetch the CloudWatch logs for a given Lambda name. def fetch_logs(self, lambda_name, filter_pattern='', limit=10000, start_time=0): """ Fetch the CloudWatch logs for a given Lambda name. """ log_name = '/aws/lambda/' + lambda_name streams = self.logs_client.describe_log_streams(...
Filter all log groups that match the name given in log_filter. def remove_log_group(self, group_name): """ Filter all log groups that match the name given in log_filter. """ print("Removing log group: {}".format(group_name)) try: self.logs_client.delete_log_group(log...
Removed all logs that are assigned to a given rest api id. def remove_api_gateway_logs(self, project_name): """ Removed all logs that are assigned to a given rest api id. """ for rest_api in self.get_rest_apis(project_name): for stage in self.apigateway_client.get_stages(res...
Get the Hosted Zone ID for a given domain. def get_hosted_zone_id_for_domain(self, domain): """ Get the Hosted Zone ID for a given domain. """ all_zones = self.get_all_zones() return self.get_best_match_zone(all_zones, domain)
Return zone id which name is closer matched with domain name. def get_best_match_zone(all_zones, domain): """Return zone id which name is closer matched with domain name.""" # Related: https://github.com/Miserlou/Zappa/issues/459 public_zones = [zone for zone in all_zones['HostedZones'] if not...
Remove DNS challenge TXT. def remove_dns_challenge_txt(self, zone_id, domain, txt_challenge): """ Remove DNS challenge TXT. """ print("Deleting DNS challenge..") resp = self.route53.change_resource_record_sets( HostedZoneId=zone_id, ChangeBatch=self.get_d...
Load AWS credentials. An optional boto_session can be provided, but that's usually for testing. An optional profile_name can be provided for config files that have multiple sets of credentials. def load_credentials(self, boto_session=None, profile_name=None): """ Load AWS cred...
Main cert installer path. def get_cert_and_update_domain( zappa_instance, lambda_name, api_stage, domain=None, manual=False, ): ...
Parse account key to get public key def parse_account_key(): """Parse account key to get public key""" LOGGER.info("Parsing account key...") cmd = [ 'openssl', 'rsa', '-in', os.path.join(gettempdir(), 'account.key'), '-noout', '-text' ] devnull = open(os.devnull, 'wb...
Parse certificate signing request for domains def parse_csr(): """ Parse certificate signing request for domains """ LOGGER.info("Parsing CSR...") cmd = [ 'openssl', 'req', '-in', os.path.join(gettempdir(), 'domain.csr'), '-noout', '-text' ] devnull = open(os...
Use regular expressions to find crypto values from parsed account key, and return a header we can send to our Boulder instance. def get_boulder_header(key_bytes): """ Use regular expressions to find crypto values from parsed account key, and return a header we can send to our Boulder instance. """ ...
Agree to LE TOS def register_account(): """ Agree to LE TOS """ LOGGER.info("Registering account...") code, result = _send_signed_request(DEFAULT_CA + "/acme/new-reg", { "resource": "new-reg", "agreement": "https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf", }) ...
Call LE to get a new signed CA. def get_cert(zappa_instance, log=LOGGER, CA=DEFAULT_CA): """ Call LE to get a new signed CA. """ out = parse_account_key() header = get_boulder_header(out) accountkey_json = json.dumps(header['jwk'], sort_keys=True, separators=(',', ':')) thumbprint = _b64(ha...
Loop until our challenge is verified, else fail. def verify_challenge(uri): """ Loop until our challenge is verified, else fail. """ while True: try: resp = urlopen(uri) challenge_status = json.loads(resp.read().decode('utf8')) except IOError as e: ra...