INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
This function loops over an array of objects containing a resourceArn and conditions statement and generates the array of statements for the policy.
def _getStatementForEffect(self, effect, methods): '''This function loops over an array of objects containing a resourceArn and conditions statement and generates the array of statements for the policy.''' statements = [] if len(methods) > 0: statement = self._getEmptyStatem...
Hook method that gets called before "each" SAM resource gets processed :param string logical_id: Logical ID of the resource being processed :param string resource_type: Type of the resource being processed :param dict resource_properties: Properties of the resource :return: Nothing
def on_before_transform_resource(self, logical_id, resource_type, resource_properties): """ Hook method that gets called before "each" SAM resource gets processed :param string logical_id: Logical ID of the resource being processed :param string resource_type: Type of the resource being...
A Python AWS Lambda function to process aggregated records sent to KinesisAnalytics.
def lambda_handler(event, context): '''A Python AWS Lambda function to process aggregated records sent to KinesisAnalytics.''' raw_kpl_records = event['records'] output = [process_kpl_record(kpl_record) for kpl_record in raw_kpl_records] # Print number of successful and failed records. success_coun...
Translates the SAM manifest provided in the and returns the translation to CloudFormation. :param dict input_fragment: the SAM template to transform :param dict parameter_values: Parameter values provided by the user :returns: the transformed CloudFormation template :rtype: dict
def transform(input_fragment, parameter_values, managed_policy_loader): """Translates the SAM manifest provided in the and returns the translation to CloudFormation. :param dict input_fragment: the SAM template to transform :param dict parameter_values: Parameter values provided by the user :returns: t...
:return: a dict that can be used as part of a cloudformation template
def to_dict(self): """ :return: a dict that can be used as part of a cloudformation template """ dict_with_nones = self._asdict() codedeploy_lambda_alias_update_dict = dict((k, v) for k, v in dict_with_nones.items() if v != ref(N...
Hook method that gets called before the SAM template is processed. The template has pass the validation and is guaranteed to contain a non-empty "Resources" section. :param dict template_dict: Dictionary of the SAM template :return: Nothing
def on_before_transform_template(self, template_dict): """ Hook method that gets called before the SAM template is processed. The template has pass the validation and is guaranteed to contain a non-empty "Resources" section. :param dict template_dict: Dictionary of the SAM template ...
Method to return a dictionary of API Events on the function :param SamResource function: Function Resource object :return dict: Dictionary of API events along with any other configuration passed to it. Example: { FooEvent: {Path: "/foo", Method: "post", RestApiId: blah, Meth...
def _get_api_events(self, function): """ Method to return a dictionary of API Events on the function :param SamResource function: Function Resource object :return dict: Dictionary of API events along with any other configuration passed to it. Example: { FooEv...
Actually process given API events. Iteratively adds the APIs to Swagger JSON in the respective Serverless::Api resource from the template :param SamResource function: SAM Function containing the API events to be processed :param dict api_events: API Events extracted from the function. These eve...
def _process_api_events(self, function, api_events, template, condition=None): """ Actually process given API events. Iteratively adds the APIs to Swagger JSON in the respective Serverless::Api resource from the template :param SamResource function: SAM Function containing the API event...
Adds the API path/method from the given event to the Swagger JSON of Serverless::Api resource this event refers to. :param string event_id: LogicalId of the event :param dict event_properties: Properties of the event :param SamTemplate template: SAM Template to search for Serverless::Ap...
def _add_api_to_swagger(self, event_id, event_properties, template): """ Adds the API path/method from the given event to the Swagger JSON of Serverless::Api resource this event refers to. :param string event_id: LogicalId of the event :param dict event_properties: Properties of...
Get API logical id from API event properties. Handles case where API id is not specified or is a reference to a logical id.
def _get_api_id(self, event_properties): """ Get API logical id from API event properties. Handles case where API id is not specified or is a reference to a logical id. """ api_id = event_properties.get("RestApiId") if isinstance(api_id, dict) and "Ref" in api_id: ...
Decides whether to add a condition to the implicit api resource. :param dict template_dict: SAM template dictionary
def _maybe_add_condition_to_implicit_api(self, template_dict): """ Decides whether to add a condition to the implicit api resource. :param dict template_dict: SAM template dictionary """ # Short-circuit if template doesn't have any functions with implicit API events if no...
Add top-level template condition that combines the given list of conditions. :param dict template_dict: SAM template dictionary :param string condition_name: Name of top-level template condition :param list conditions_to_combine: List of conditions that should be combined (via OR operator) to f...
def _add_combined_condition_to_template(self, template_dict, condition_name, conditions_to_combine): """ Add top-level template condition that combines the given list of conditions. :param dict template_dict: SAM template dictionary :param string condition_name: Name of top-level templa...
Add conditions to implicit API paths if necessary. Implicit API resource methods are constructed from API events on individual serverless functions within the SAM template. Since serverless functions can have conditions on them, it's possible to have a case where all methods under a resource pa...
def _maybe_add_conditions_to_implicit_api_paths(self, template): """ Add conditions to implicit API paths if necessary. Implicit API resource methods are constructed from API events on individual serverless functions within the SAM template. Since serverless functions can have condition...
Generate valid condition logical id from the given API logical id and swagger resource path.
def _path_condition_name(self, api_id, path): """ Generate valid condition logical id from the given API logical id and swagger resource path. """ # only valid characters for CloudFormation logical id are [A-Za-z0-9], but swagger paths can contain # slashes and curly braces for t...
Implicit API resource are tentatively added to the template for uniform handling of both Implicit & Explicit APIs. They need to removed from the template, if there are *no* API events attached to this resource. This method removes the Implicit API if it does not contain any Swagger paths (added in respo...
def _maybe_remove_implicit_api(self, template): """ Implicit API resource are tentatively added to the template for uniform handling of both Implicit & Explicit APIs. They need to removed from the template, if there are *no* API events attached to this resource. This method removes the I...
Sets up the resource such that it will triggers a re-deployment when Swagger changes :param swagger: Dictionary containing the Swagger definition of the API
def make_auto_deployable(self, stage, swagger=None): """ Sets up the resource such that it will triggers a re-deployment when Swagger changes :param swagger: Dictionary containing the Swagger definition of the API """ if not swagger: return # CloudFormation ...
This private method is seperate from the main, public invoke method so that other code within this SDK can give this Lambda client a raw payload/client context to invoke with, rather than having it built for them. This lets you include custom ExtensionMap_ values like subject which are needed for our in...
def _invoke_internal(self, function_arn, payload, client_context, invocation_type="RequestResponse"): """ This private method is seperate from the main, public invoke method so that other code within this SDK can give this Lambda client a raw payload/client context to invoke with, rather than ha...
Read at most amt bytes from the stream. If the amt argument is omitted, read all data.
def read(self, amt=None): """Read at most amt bytes from the stream. If the amt argument is omitted, read all data. """ chunk = self._raw_stream.read(amt) self._amount_read += len(chunk) return chunk
Send work item to specified :code:`function_arn`. :param function_arn: Arn of the Lambda function intended to receive the work for processing. :type function_arn: string :param input_bytes: The data making up the work being posted. :type input_bytes: bytes :param client_contex...
def post_work(self, function_arn, input_bytes, client_context, invocation_type="RequestResponse"): """ Send work item to specified :code:`function_arn`. :param function_arn: Arn of the Lambda function intended to receive the work for processing. :type function_arn: string :para...
Retrieve the next work item for specified :code:`function_arn`. :param function_arn: Arn of the Lambda function intended to receive the work for processing. :type function_arn: string :returns: Next work item to be processed by the function. :type returns: WorkItem
def get_work(self, function_arn): """ Retrieve the next work item for specified :code:`function_arn`. :param function_arn: Arn of the Lambda function intended to receive the work for processing. :type function_arn: string :returns: Next work item to be processed by the function...
Post the result of processing work item by :code:`function_arn`. :param function_arn: Arn of the Lambda function intended to receive the work for processing. :type function_arn: string :param work_item: The WorkItem holding the results of the work being posted. :type work_item: WorkIte...
def post_work_result(self, function_arn, work_item): """ Post the result of processing work item by :code:`function_arn`. :param function_arn: Arn of the Lambda function intended to receive the work for processing. :type function_arn: string :param work_item: The WorkItem holdi...
Post the error message from executing the function handler for :code:`function_arn` with specifid :code:`invocation_id` :param function_arn: Arn of the Lambda function which has the handler error message. :type function_arn: string :param invocation_id: Invocation ID of the work that ...
def post_handler_err(self, function_arn, invocation_id, handler_err): """ Post the error message from executing the function handler for :code:`function_arn` with specifid :code:`invocation_id` :param function_arn: Arn of the Lambda function which has the handler error message. ...
Retrieve the result of the work processed by :code:`function_arn` with specified :code:`invocation_id`. :param function_arn: Arn of the Lambda function intended to receive the work for processing. :type function_arn: string :param invocation_id: Invocation ID of the work that is being ...
def get_work_result(self, function_arn, invocation_id): """ Retrieve the result of the work processed by :code:`function_arn` with specified :code:`invocation_id`. :param function_arn: Arn of the Lambda function intended to receive the work for processing. :type function_arn: st...
Hook method that gets called before the SAM template is processed. The template has passed the validation and is guaranteed to contain a non-empty "Resources" section. This plugin needs to run as soon as possible to allow some time for templates to become available. This verifies that the user ...
def on_before_transform_template(self, template_dict): """ Hook method that gets called before the SAM template is processed. The template has passed the validation and is guaranteed to contain a non-empty "Resources" section. This plugin needs to run as soon as possible to allow some t...
Determines whether or not the on_before_transform_template event can process this application :param dict app: the application and its properties
def _can_process_application(self, app): """ Determines whether or not the on_before_transform_template event can process this application :param dict app: the application and its properties """ return (self.LOCATION_KEY in app.properties and isinstance(app.prope...
Method that handles the get_application API call to the serverless application repo This method puts something in the `_applications` dictionary because the plugin expects something there in a later event. :param string app_id: ApplicationId :param string semver: SemanticVersion ...
def _handle_get_application_request(self, app_id, semver, key, logical_id): """ Method that handles the get_application API call to the serverless application repo This method puts something in the `_applications` dictionary because the plugin expects something there in a later event. ...
Method that handles the create_cloud_formation_template API call to the serverless application repo :param string app_id: ApplicationId :param string semver: SemanticVersion :param string key: The dictionary key consisting of (ApplicationId, SemanticVersion) :param string logical_id: th...
def _handle_create_cfn_template_request(self, app_id, semver, key, logical_id): """ Method that handles the create_cloud_formation_template API call to the serverless application repo :param string app_id: ApplicationId :param string semver: SemanticVersion :param string key: Th...
Hook method that gets called before "each" SAM resource gets processed Replaces the ApplicationId and Semantic Version pairs with a TemplateUrl. :param string logical_id: Logical ID of the resource being processed :param string resource_type: Type of the resource being processed :param...
def on_before_transform_resource(self, logical_id, resource_type, resource_properties): """ Hook method that gets called before "each" SAM resource gets processed Replaces the ApplicationId and Semantic Version pairs with a TemplateUrl. :param string logical_id: Logical ID of the resou...
Checks a dictionary to make sure it has a specific key. If it does not, an InvalidResourceException is thrown. :param string logical_id: logical id of this resource :param dict dictionary: the dictionary to check :param list keys: list of keys that should exist in the dictionary
def _check_for_dictionary_key(self, logical_id, dictionary, keys): """ Checks a dictionary to make sure it has a specific key. If it does not, an InvalidResourceException is thrown. :param string logical_id: logical id of this resource :param dict dictionary: the dictionary to c...
Hook method that gets called after the template is processed Go through all the stored applications and make sure they're all ACTIVE. :param dict template: Dictionary of the SAM template :return: Nothing
def on_after_transform_template(self, template): """ Hook method that gets called after the template is processed Go through all the stored applications and make sure they're all ACTIVE. :param dict template: Dictionary of the SAM template :return: Nothing """ i...
Handles the response from the SAR service call :param dict response: the response dictionary from the app repo :param string application_id: the ApplicationId :param string template_id: the unique TemplateId for this application
def _handle_get_cfn_template_response(self, response, application_id, template_id): """ Handles the response from the SAR service call :param dict response: the response dictionary from the app repo :param string application_id: the ApplicationId :param string template_id: the u...
Handles service calls and exception management for service calls to the Serverless Application Repository. :param lambda service_call_lambda: lambda function that contains the service call :param string logical_id: Logical ID of the resource being processed :param list *args: arguments ...
def _sar_service_call(self, service_call_lambda, logical_id, *args): """ Handles service calls and exception management for service calls to the Serverless Application Repository. :param lambda service_call_lambda: lambda function that contains the service call :param string log...
Validates the template and parameter values and raises exceptions if there's an issue :param dict sam_template: SAM template :param dict parameter_values: Dictionary of parameter values provided by the user
def _validate(self, sam_template, parameter_values): """ Validates the template and parameter values and raises exceptions if there's an issue :param dict sam_template: SAM template :param dict parameter_values: Dictionary of parameter values provided by the user """ if paramete...
Iterate over all resources within the SAM template, optionally filtering by type :param string resource_type: Optional type to filter the resources by :yields (string, SamResource): Tuple containing LogicalId and the resource
def iterate(self, resource_type=None): """ Iterate over all resources within the SAM template, optionally filtering by type :param string resource_type: Optional type to filter the resources by :yields (string, SamResource): Tuple containing LogicalId and the resource """ ...
Adds the resource to dictionary with given logical Id. It will overwrite, if the logicalId is already used. :param string logicalId: Logical Id to set to :param SamResource or dict resource: The actual resource data
def set(self, logicalId, resource): """ Adds the resource to dictionary with given logical Id. It will overwrite, if the logicalId is already used. :param string logicalId: Logical Id to set to :param SamResource or dict resource: The actual resource data """ resource_d...
Gets the resource at the given logicalId if present :param string logicalId: Id of the resource :return SamResource: Resource, if available at the Id. None, otherwise
def get(self, logicalId): """ Gets the resource at the given logicalId if present :param string logicalId: Id of the resource :return SamResource: Resource, if available at the Id. None, otherwise """ if logicalId not in self.resources: return None r...
Creates & returns a plugins object with the given list of plugins installed. In addition to the given plugins, we will also install a few "required" plugins that are necessary to provide complete support for SAM template spec. :param plugins: list of samtranslator.plugins.BasePlugin plugins: List of plugins to...
def prepare_plugins(plugins, parameters={}): """ Creates & returns a plugins object with the given list of plugins installed. In addition to the given plugins, we will also install a few "required" plugins that are necessary to provide complete support for SAM template spec. :param plugins: list of sam...
Loads the SAM resources from the given SAM manifest, replaces them with their corresponding CloudFormation resources, and returns the resulting CloudFormation template. :param dict sam_template: the SAM manifest, as loaded by json.load() or yaml.load(), or as provided by \ CloudFormatio...
def translate(self, sam_template, parameter_values): """Loads the SAM resources from the given SAM manifest, replaces them with their corresponding CloudFormation resources, and returns the resulting CloudFormation template. :param dict sam_template: the SAM manifest, as loaded by json.load() o...
Returns a list of resources to iterate, order them based on the following order: 1. AWS::Serverless::Function - because API Events need to modify the corresponding Serverless::Api resource. 2. AWS::Serverless::Api 3. Anything else This is necessary because a Function resour...
def _get_resources_to_iterate(self, sam_template, macro_resolver): """ Returns a list of resources to iterate, order them based on the following order: 1. AWS::Serverless::Function - because API Events need to modify the corresponding Serverless::Api resource. 2. AWS::Serverless...
Constructs a Resource object with the given logical id, based on the given resource dict. The resource dict is the value associated with the logical id in a CloudFormation template's Resources section, and takes the following format. :: { "Type": "<resource type>", ...
def from_dict(cls, logical_id, resource_dict, relative_id=None, sam_plugins=None): """Constructs a Resource object with the given logical id, based on the given resource dict. The resource dict is the value associated with the logical id in a CloudFormation template's Resources section, and takes the ...
Validates that the provided logical id is an alphanumeric string. :param str logical_id: the logical id to validate :returns: True if the logical id is valid :rtype: bool :raises TypeError: if the logical id is invalid
def _validate_logical_id(cls, logical_id): """Validates that the provided logical id is an alphanumeric string. :param str logical_id: the logical id to validate :returns: True if the logical id is valid :rtype: bool :raises TypeError: if the logical id is invalid """ ...
Validates that the provided resource dict contains the correct Type string, and the required Properties dict. :param dict resource_dict: the resource dict to validate :returns: True if the resource dict has the expected format :rtype: bool :raises InvalidResourceException: if the resour...
def _validate_resource_dict(cls, logical_id, resource_dict): """Validates that the provided resource dict contains the correct Type string, and the required Properties dict. :param dict resource_dict: the resource dict to validate :returns: True if the resource dict has the expected format ...
Validates that the required properties for this Resource have been provided, then returns a dict corresponding to the given Resource object. This dict will take the format of a single entry in the Resources section of a CloudFormation template, and will take the following format. :: { ...
def to_dict(self): """Validates that the required properties for this Resource have been provided, then returns a dict corresponding to the given Resource object. This dict will take the format of a single entry in the Resources section of a CloudFormation template, and will take the following f...
Generates the resource dict for this Resource, the value associated with the logical id in a CloudFormation template's Resources section. :returns: the resource dict for this Resource :rtype: dict
def _generate_resource_dict(self): """Generates the resource dict for this Resource, the value associated with the logical id in a CloudFormation template's Resources section. :returns: the resource dict for this Resource :rtype: dict """ resource_dict = {} reso...
Validates that the required properties for this Resource have been populated, and that all properties have valid values. :returns: True if all properties are valid :rtype: bool :raises TypeError: if any properties are invalid
def validate_properties(self): """Validates that the required properties for this Resource have been populated, and that all properties have valid values. :returns: True if all properties are valid :rtype: bool :raises TypeError: if any properties are invalid """ ...
Sets attributes on resource. Resource attributes are top-level entries of a CloudFormation resource that exist outside of the Properties dictionary :param attr: Attribute name :param value: Attribute value :return: None :raises KeyError if `attr` is not in the supported attribut...
def set_resource_attribute(self, attr, value): """Sets attributes on resource. Resource attributes are top-level entries of a CloudFormation resource that exist outside of the Properties dictionary :param attr: Attribute name :param value: Attribute value :return: None :...
Gets the resource attribute if available :param attr: Name of the attribute :return: Value of the attribute, if set in the resource. None otherwise
def get_resource_attribute(self, attr): """Gets the resource attribute if available :param attr: Name of the attribute :return: Value of the attribute, if set in the resource. None otherwise """ if attr not in self.resource_attributes: raise KeyError("%s is not in re...
Returns a CloudFormation construct that provides value for this attribute. If the resource does not provide this attribute, then this method raises an exception :return: Dictionary that will resolve to value of the attribute when CloudFormation stack update is executed
def get_runtime_attr(self, attr_name): """ Returns a CloudFormation construct that provides value for this attribute. If the resource does not provide this attribute, then this method raises an exception :return: Dictionary that will resolve to value of the attribute when CloudFormation...
Constructs the list of supported resource references by going through the list of CFN resources generated by to_cloudformation() on this SAM resource. Each SAM resource must provide a map of properties that it supports and the type of CFN resource this property resolves to. :param list of Resou...
def get_resource_references(self, generated_cfn_resources, supported_resource_refs): """ Constructs the list of supported resource references by going through the list of CFN resources generated by to_cloudformation() on this SAM resource. Each SAM resource must provide a map of properties that ...
Returns the Resource class corresponding to the 'Type' key in the given resource dict. :param dict resource_dict: the resource dict to resolve :returns: the resolved Resource class :rtype: class
def resolve_resource_type(self, resource_dict): """Returns the Resource class corresponding to the 'Type' key in the given resource dict. :param dict resource_dict: the resource dict to resolve :returns: the resolved Resource class :rtype: class """ if not self.can_resol...
Build a responseCard with a title, subtitle, and an optional set of options which should be displayed as buttons.
def build_response_card(title, subtitle, options): """ Build a responseCard with a title, subtitle, and an optional set of options which should be displayed as buttons. """ buttons = None if options is not None: buttons = [] for i in range(min(5, len(options))): buttons.a...
Returns a random integer between min (included) and max (excluded)
def get_random_int(minimum, maximum): """ Returns a random integer between min (included) and max (excluded) """ min_int = math.ceil(minimum) max_int = math.floor(maximum) return random.randint(min_int, max_int - 1)
Helper function which in a full implementation would feed into a backend API to provide query schedule availability. The output of this function is an array of 30 minute periods of availability, expressed in ISO-8601 time format. In order to enable quick demonstration of all possible conversation paths suppor...
def get_availabilities(date): """ Helper function which in a full implementation would feed into a backend API to provide query schedule availability. The output of this function is an array of 30 minute periods of availability, expressed in ISO-8601 time format. In order to enable quick demonstration...
Helper function to check if the given time and duration fits within a known set of availability windows. Duration is assumed to be one of 30, 60 (meaning minutes). Availabilities is expected to contain entries of the format HH:MM.
def is_available(time, duration, availabilities): """ Helper function to check if the given time and duration fits within a known set of availability windows. Duration is assumed to be one of 30, 60 (meaning minutes). Availabilities is expected to contain entries of the format HH:MM. """ if duratio...
Build a string eliciting for a possible time slot among at least two availabilities.
def build_available_time_string(availabilities): """ Build a string eliciting for a possible time slot among at least two availabilities. """ prefix = 'We have availabilities at ' if len(availabilities) > 3: prefix = 'We have plenty of availability, including ' prefix += build_time_outp...
Helper function to return the windows of availability of the given duration, when provided a set of 30 minute windows.
def get_availabilities_for_duration(duration, availabilities): """ Helper function to return the windows of availability of the given duration, when provided a set of 30 minute windows. """ duration_availabilities = [] start_time = '10:00' while start_time != '17:00': if start_time in av...
Build a list of potential options for a given slot, to be used in responseCard generation.
def build_options(slot, appointment_type, date, booking_map): """ Build a list of potential options for a given slot, to be used in responseCard generation. """ day_strings = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] if slot == 'AppointmentType': return [ {'text': 'cleani...
Performs dialog management and fulfillment for booking a dentists appointment. Beyond fulfillment, the implementation for this intent demonstrates the following: 1) Use of elicitSlot in slot validation and re-prompting 2) Use of confirmIntent to support the confirmation of inferred slot values, when confir...
def make_appointment(intent_request): """ Performs dialog management and fulfillment for booking a dentists appointment. Beyond fulfillment, the implementation for this intent demonstrates the following: 1) Use of elicitSlot in slot validation and re-prompting 2) Use of confirmIntent to support the...
Called when the user specifies an intent for this bot.
def dispatch(intent_request): """ Called when the user specifies an intent for this bot. """ logger.debug('dispatch userId={}, intentName={}'.format(intent_request['userId'], intent_request['currentIntent']['name'])) intent_name = intent_request['currentIntent']['name'] # Dispatch to your bot...
Demonstrates a simple HTTP endpoint using API Gateway. You have full access to the request and response payload, including headers and status code. TableName provided by template.yaml. To scan a DynamoDB table, make a GET request with optional query string parameter. To put, update, or delete an item, m...
def lambda_handler(event, context): '''Demonstrates a simple HTTP endpoint using API Gateway. You have full access to the request and response payload, including headers and status code. TableName provided by template.yaml. To scan a DynamoDB table, make a GET request with optional query string param...
Demonstrates a simple HTTP endpoint using API Gateway. You have full access to the request and response payload, including headers and status code. To scan a DynamoDB table, make a GET request with the TableName as a query string parameter. To put, update, or delete an item, make a POST, PUT, or DE...
def lambda_handler(event, context): '''Demonstrates a simple HTTP endpoint using API Gateway. You have full access to the request and response payload, including headers and status code. To scan a DynamoDB table, make a GET request with the TableName as a query string parameter. To put, update, or ...
Makes a combined condition using Fn::Or. Since Fn::Or only accepts up to 10 conditions, this method optionally creates multiple conditions. These conditions are named based on the condition_name parameter that is passed into the method. :param list conditions_list: list of conditions :param string cond...
def make_combined_condition(conditions_list, condition_name): """ Makes a combined condition using Fn::Or. Since Fn::Or only accepts up to 10 conditions, this method optionally creates multiple conditions. These conditions are named based on the condition_name parameter that is passed into the method. ...
Checks if the given input is an intrinsic function dictionary. Intrinsic function is a dictionary with single key that is the name of the intrinsics. :param input: Input value to check if it is an intrinsic :return: True, if yes
def is_instrinsic(input): """ Checks if the given input is an intrinsic function dictionary. Intrinsic function is a dictionary with single key that is the name of the intrinsics. :param input: Input value to check if it is an intrinsic :return: True, if yes """ if input is not None \ ...
Validates that the input dictionary contains only one key and is of the given intrinsic_name :param input_dict: Input dictionary representing the intrinsic function :return: True if it matches expected structure, False otherwise
def can_handle(self, input_dict): """ Validates that the input dictionary contains only one key and is of the given intrinsic_name :param input_dict: Input dictionary representing the intrinsic function :return: True if it matches expected structure, False otherwise """ ...
Splits a resource reference of structure "LogicalId.Property" and returns the "LogicalId" and "Property" separately. :param string ref_value: Input reference value which *may* contain the structure "LogicalId.Property" :return string, string: Returns two values - logical_id, property. If the in...
def _parse_resource_reference(cls, ref_value): """ Splits a resource reference of structure "LogicalId.Property" and returns the "LogicalId" and "Property" separately. :param string ref_value: Input reference value which *may* contain the structure "LogicalId.Property" :return s...
Resolves references that are present in the parameters and returns the value. If it is not in parameters, this method simply returns the input unchanged. :param input_dict: Dictionary representing the Ref function. Must contain only one key and it should be "Ref". Ex: {Ref: "foo"} ...
def resolve_parameter_refs(self, input_dict, parameters): """ Resolves references that are present in the parameters and returns the value. If it is not in parameters, this method simply returns the input unchanged. :param input_dict: Dictionary representing the Ref function. Must conta...
Resolves references to some property of a resource. These are runtime properties which can't be converted to a value here. Instead we output another reference that will more actually resolve to the value when executed via CloudFormation Example: {"Ref": "LogicalId.Property"} => {"Re...
def resolve_resource_refs(self, input_dict, supported_resource_refs): """ Resolves references to some property of a resource. These are runtime properties which can't be converted to a value here. Instead we output another reference that will more actually resolve to the value when execu...
Updates references to the old logical id of a resource to the new (generated) logical id. Example: {"Ref": "MyLayer"} => {"Ref": "MyLayerABC123"} :param dict input_dict: Dictionary representing the Ref function to be resolved. :param dict supported_resource_id_refs: Dictionary that...
def resolve_resource_id_refs(self, input_dict, supported_resource_id_refs): """ Updates references to the old logical id of a resource to the new (generated) logical id. Example: {"Ref": "MyLayer"} => {"Ref": "MyLayerABC123"} :param dict input_dict: Dictionary representing ...
Substitute references found within the string of `Fn::Sub` intrinsic function :param input_dict: Dictionary representing the Fn::Sub function. Must contain only one key and it should be `Fn::Sub`. Ex: {"Fn::Sub": ...} :param parameters: Dictionary of parameter values for substitution ...
def resolve_parameter_refs(self, input_dict, parameters): """ Substitute references found within the string of `Fn::Sub` intrinsic function :param input_dict: Dictionary representing the Fn::Sub function. Must contain only one key and it should be `Fn::Sub`. Ex: {"Fn::Sub": ...} ...
Resolves reference to some property of a resource. Inside string to be substituted, there could be either a "Ref" or a "GetAtt" usage of this property. They have to be handled differently. Ref usages are directly converted to a Ref on the resolved value. GetAtt usages are split under the assumption ...
def resolve_resource_refs(self, input_dict, supported_resource_refs): """ Resolves reference to some property of a resource. Inside string to be substituted, there could be either a "Ref" or a "GetAtt" usage of this property. They have to be handled differently. Ref usages are directly ...
Resolves reference to some property of a resource. Inside string to be substituted, there could be either a "Ref" or a "GetAtt" usage of this property. They have to be handled differently. Ref usages are directly converted to a Ref on the resolved value. GetAtt usages are split under the assumption ...
def resolve_resource_id_refs(self, input_dict, supported_resource_id_refs): """ Resolves reference to some property of a resource. Inside string to be substituted, there could be either a "Ref" or a "GetAtt" usage of this property. They have to be handled differently. Ref usages are dir...
Handles resolving replacements in the Sub action based on the handler that is passed as an input. :param input_dict: Dictionary to be resolved :param supported_values: One of several different objects that contain the supported values that need to be changed. See each method above for speci...
def _handle_sub_action(self, input_dict, handler): """ Handles resolving replacements in the Sub action based on the handler that is passed as an input. :param input_dict: Dictionary to be resolved :param supported_values: One of several different objects that contain the supported valu...
Generic method to handle value to Fn::Sub key. We are interested in parsing the ${} syntaxes inside the string portion of the value. :param sub_value: Value of the Sub function :param handler_method: Method to be called on every occurrence of `${LogicalId}` structure within the string. ...
def _handle_sub_value(self, sub_value, handler_method): """ Generic method to handle value to Fn::Sub key. We are interested in parsing the ${} syntaxes inside the string portion of the value. :param sub_value: Value of the Sub function :param handler_method: Method to be called...
Substitute references within a string that is using ${key} syntax by calling the `handler_method` on every occurrence of this structure. The value returned by this method directly replaces the reference structure. Ex: text = "${key1}-hello-${key2} def handler_method(full_ref, re...
def _sub_all_refs(self, text, handler_method): """ Substitute references within a string that is using ${key} syntax by calling the `handler_method` on every occurrence of this structure. The value returned by this method directly replaces the reference structure. Ex: text =...
Resolve resource references within a GetAtt dict. Example: { "Fn::GetAtt": ["LogicalId.Property", "Arn"] } => {"Fn::GetAtt": ["ResolvedLogicalId", "Arn"]} Theoretically, only the first element of the array can contain reference to SAM resources. The second element is name of an...
def resolve_resource_refs(self, input_dict, supported_resource_refs): """ Resolve resource references within a GetAtt dict. Example: { "Fn::GetAtt": ["LogicalId.Property", "Arn"] } => {"Fn::GetAtt": ["ResolvedLogicalId", "Arn"]} Theoretically, only the first element of ...
Resolve resource references within a GetAtt dict. Example: { "Fn::GetAtt": ["LogicalId", "Arn"] } => {"Fn::GetAtt": ["ResolvedLogicalId", "Arn"]} Theoretically, only the first element of the array can contain reference to SAM resources. The second element is name of an attribut...
def resolve_resource_id_refs(self, input_dict, supported_resource_id_refs): """ Resolve resource references within a GetAtt dict. Example: { "Fn::GetAtt": ["LogicalId", "Arn"] } => {"Fn::GetAtt": ["ResolvedLogicalId", "Arn"]} Theoretically, only the first element of the...
Resolves the function and returns the updated dictionary :param input_dict: Dictionary to be resolved :param key: Name of this intrinsic. :param resolved_value: Resolved or updated value for this action. :param remaining: Remaining sections for the GetAtt action.
def _get_resolved_dictionary(self, input_dict, key, resolved_value, remaining): """ Resolves the function and returns the updated dictionary :param input_dict: Dictionary to be resolved :param key: Name of this intrinsic. :param resolved_value: Resolved or updated value for this...
Recursively resolves "Fn::FindInMap"references that are present in the mappings and returns the value. If it is not in mappings, this method simply returns the input unchanged. :param input_dict: Dictionary representing the FindInMap function. Must contain only one key and it ...
def resolve_parameter_refs(self, input_dict, parameters): """ Recursively resolves "Fn::FindInMap"references that are present in the mappings and returns the value. If it is not in mappings, this method simply returns the input unchanged. :param input_dict: Dictionary representing the F...
Process a RDS enhenced monitoring DATA_MESSAGE, coming from CLOUDWATCH LOGS
def lambda_handler(event, context): ''' Process a RDS enhenced monitoring DATA_MESSAGE, coming from CLOUDWATCH LOGS ''' # event is a dict containing a base64 string gzipped event = json.loads(gzip.GzipFile(fileobj=StringIO(event['awslogs']['data'].decode('base64'))).read()) account = event[...
Constructs and returns the ApiGateway RestApi. :returns: the RestApi to which this SAM Api corresponds :rtype: model.apigateway.ApiGatewayRestApi
def _construct_rest_api(self): """Constructs and returns the ApiGateway RestApi. :returns: the RestApi to which this SAM Api corresponds :rtype: model.apigateway.ApiGatewayRestApi """ rest_api = ApiGatewayRestApi(self.logical_id, depends_on=self.depends_on, attributes=self.resou...
Constructs the RestApi's `BodyS3Location property`_, from the SAM Api's DefinitionUri property. :returns: a BodyS3Location dict, containing the S3 Bucket, Key, and Version of the Swagger definition :rtype: dict
def _construct_body_s3_dict(self): """Constructs the RestApi's `BodyS3Location property`_, from the SAM Api's DefinitionUri property. :returns: a BodyS3Location dict, containing the S3 Bucket, Key, and Version of the Swagger definition :rtype: dict """ if isinstance(self.definit...
Constructs and returns the ApiGateway Deployment. :param model.apigateway.ApiGatewayRestApi rest_api: the RestApi for this Deployment :returns: the Deployment to which this SAM Api corresponds :rtype: model.apigateway.ApiGatewayDeployment
def _construct_deployment(self, rest_api): """Constructs and returns the ApiGateway Deployment. :param model.apigateway.ApiGatewayRestApi rest_api: the RestApi for this Deployment :returns: the Deployment to which this SAM Api corresponds :rtype: model.apigateway.ApiGatewayDeployment ...
Constructs and returns the ApiGateway Stage. :param model.apigateway.ApiGatewayDeployment deployment: the Deployment for this Stage :returns: the Stage to which this SAM Api corresponds :rtype: model.apigateway.ApiGatewayStage
def _construct_stage(self, deployment, swagger): """Constructs and returns the ApiGateway Stage. :param model.apigateway.ApiGatewayDeployment deployment: the Deployment for this Stage :returns: the Stage to which this SAM Api corresponds :rtype: model.apigateway.ApiGatewayStage ...
Generates CloudFormation resources from a SAM API resource :returns: a tuple containing the RestApi, Deployment, and Stage for an empty Api. :rtype: tuple
def to_cloudformation(self): """Generates CloudFormation resources from a SAM API resource :returns: a tuple containing the RestApi, Deployment, and Stage for an empty Api. :rtype: tuple """ rest_api = self._construct_rest_api() deployment = self._construct_deployment(r...
Add CORS configuration to the Swagger file, if necessary
def _add_cors(self): """ Add CORS configuration to the Swagger file, if necessary """ INVALID_ERROR = "Invalid value for 'Cors' property" if not self.cors: return if self.cors and not self.definition_body: raise InvalidResourceException(self.log...
Add Auth configuration to the Swagger file, if necessary
def _add_auth(self): """ Add Auth configuration to the Swagger file, if necessary """ if not self.auth: return if self.auth and not self.definition_body: raise InvalidResourceException(self.logical_id, "Auth wor...
Add Gateway Response configuration to the Swagger file, if necessary
def _add_gateway_responses(self): """ Add Gateway Response configuration to the Swagger file, if necessary """ if not self.gateway_responses: return if self.gateway_responses and not self.definition_body: raise InvalidResourceException( s...
Constructs and returns the Lambda Permission resource allowing the Authorizer to invoke the function. :returns: the permission resource :rtype: model.lambda_.LambdaPermission
def _get_permission(self, authorizer_name, authorizer_lambda_function_arn): """Constructs and returns the Lambda Permission resource allowing the Authorizer to invoke the function. :returns: the permission resource :rtype: model.lambda_.LambdaPermission """ rest_api = ApiGateway...
Sets endpoint configuration property of AWS::ApiGateway::RestApi resource :param rest_api: RestApi resource :param string/dict value: Value to be set
def _set_endpoint_configuration(self, rest_api, value): """ Sets endpoint configuration property of AWS::ApiGateway::RestApi resource :param rest_api: RestApi resource :param string/dict value: Value to be set """ rest_api.EndpointConfiguration = {"Types": [value]} ...
The retry function will keep retrying `task_to_try` until either: (1) it returns None, then retry() finishes (2) `max_attempts` is reached, then retry() raises an exception. (3) if retrying one more time will cause total wait time to go above: `expiration_duration`, then retry() raises an exception ...
def retry(time_unit, multiplier, backoff_coefficient, max_delay, max_attempts, expiration_duration, enable_jitter): """ The retry function will keep retrying `task_to_try` until either: (1) it returns None, then retry() finishes (2) `max_attempts` is reached, then retry() raises an exception. (3) if...
Returns the Lambda function, role, and event resources to which this SAM Function corresponds. :param dict kwargs: already-converted resources that may need to be modified when converting this \ macro to pure CloudFormation :returns: a list of vanilla CloudFormation Resources, to which this Fun...
def to_cloudformation(self, **kwargs): """Returns the Lambda function, role, and event resources to which this SAM Function corresponds. :param dict kwargs: already-converted resources that may need to be modified when converting this \ macro to pure CloudFormation :returns: a list of v...
Alias names can be supplied as an intrinsic function. This method tries to extract alias name from a reference to a parameter. If it cannot completely resolve (ie. if a complex intrinsic function was used), then this method raises an exception. If alias name is just a plain string, it will return as is ...
def _get_resolved_alias_name(self, property_name, original_alias_value, intrinsics_resolver): """ Alias names can be supplied as an intrinsic function. This method tries to extract alias name from a reference to a parameter. If it cannot completely resolve (ie. if a complex intrinsic function wa...
Constructs and returns the Lambda function. :returns: a list containing the Lambda function and execution role resources :rtype: list
def _construct_lambda_function(self): """Constructs and returns the Lambda function. :returns: a list containing the Lambda function and execution role resources :rtype: list """ lambda_function = LambdaFunction(self.logical_id, depends_on=self.depends_on, ...
Constructs a Lambda execution role based on this SAM function's Policies property. :returns: the generated IAM Role :rtype: model.iam.IAMRole
def _construct_role(self, managed_policy_map): """Constructs a Lambda execution role based on this SAM function's Policies property. :returns: the generated IAM Role :rtype: model.iam.IAMRole """ execution_role = IAMRole(self.logical_id + 'Role', attributes=self.get_passthrough_...
Validates whether the DeadLetterQueue LogicalId is validation :raise: InvalidResourceException
def _validate_dlq(self): """Validates whether the DeadLetterQueue LogicalId is validation :raise: InvalidResourceException """ # Validate required logical ids valid_dlq_types = str(list(self.dead_letter_queue_policy_actions.keys())) if not self.DeadLetterQueue.get('Type')...
Generates and returns the resources associated with this function's events. :param model.lambda_.LambdaFunction lambda_function: generated Lambda function :param iam.IAMRole execution_role: generated Lambda execution role :param implicit_api: Global Implicit API resource where the implicit APIs...
def _generate_event_resources(self, lambda_function, execution_role, event_resources, lambda_alias=None): """Generates and returns the resources associated with this function's events. :param model.lambda_.LambdaFunction lambda_function: generated Lambda function :param iam.IAMRole execution_ro...
Constructs a Lambda Version resource that will be auto-published when CodeUri of the function changes. Old versions will not be deleted without a direct reference from the CloudFormation template. :param model.lambda_.LambdaFunction function: Lambda function object that is being connected to a version ...
def _construct_version(self, function, intrinsics_resolver): """Constructs a Lambda Version resource that will be auto-published when CodeUri of the function changes. Old versions will not be deleted without a direct reference from the CloudFormation template. :param model.lambda_.LambdaFunctio...
Constructs a Lambda Alias for the given function and pointing to the given version :param string name: Name of the alias :param model.lambda_.LambdaFunction function: Lambda function object to associate the alias with :param model.lambda_.LambdaVersion version: Lambda version object to associat...
def _construct_alias(self, name, function, version): """Constructs a Lambda Alias for the given function and pointing to the given version :param string name: Name of the alias :param model.lambda_.LambdaFunction function: Lambda function object to associate the alias with :param model....
Returns the API Gateway RestApi, Deployment, and Stage to which this SAM Api corresponds. :param dict kwargs: already-converted resources that may need to be modified when converting this \ macro to pure CloudFormation :returns: a list of vanilla CloudFormation Resources, to which this Function...
def to_cloudformation(self, **kwargs): """Returns the API Gateway RestApi, Deployment, and Stage to which this SAM Api corresponds. :param dict kwargs: already-converted resources that may need to be modified when converting this \ macro to pure CloudFormation :returns: a list of vanill...
Constructs a AWS::CloudFormation::Stack resource
def _construct_nested_stack(self): """Constructs a AWS::CloudFormation::Stack resource """ nested_stack = NestedStack(self.logical_id, depends_on=self.depends_on, attributes=self.get_passthrough_resource_attributes()) nested_stack.Parameters = self.Para...