INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Returns a validator function that succeeds only for inputs of the provided valid_type.
def is_type(valid_type): """Returns a validator function that succeeds only for inputs of the provided valid_type. :param type valid_type: the type that should be considered valid for the validator :returns: a function which returns True its input is an instance of valid_type, and raises TypeError otherwis...
Returns a validator function that succeeds only if the input is a list and each item in the list passes as input to the provided validator validate_item.
def list_of(validate_item): """Returns a validator function that succeeds only if the input is a list, and each item in the list passes as input to the provided validator validate_item. :param callable validate_item: the validator function for items in the list :returns: a function which returns True i...
Returns a validator function that succeeds only if the input is a dict and each key and value in the dict passes as input to the provided validators validate_key and validate_item respectively.
def dict_of(validate_key, validate_item): """Returns a validator function that succeeds only if the input is a dict, and each key and value in the dict passes as input to the provided validators validate_key and validate_item, respectively. :param callable validate_key: the validator function for keys in t...
Returns a validator function that succeeds only if the input passes at least one of the provided validators.
def one_of(*validators): """Returns a validator function that succeeds only if the input passes at least one of the provided validators. :param callable validators: the validator functions :returns: a function which returns True its input passes at least one of the validators, and raises TypeError ...
With the given values for each parameter this method will return a policy statement that can be used directly with IAM.
def to_statement(self, parameter_values): """ With the given values for each parameter, this method will return a policy statement that can be used directly with IAM. :param dict parameter_values: Dict containing values for each parameter defined in the template :return dict: Di...
Checks if the given input contains values for all parameters used by this template
def missing_parameter_values(self, parameter_values): """ Checks if the given input contains values for all parameters used by this template :param dict parameter_values: Dictionary of values for each parameter used in the template :return list: List of names of parameters that are miss...
Parses the input and returns an instance of this class.
def from_dict(template_name, template_values_dict): """ Parses the input and returns an instance of this class. :param string template_name: Name of the template :param dict template_values_dict: Dictionary containing the value of the template. This dict must have passed the...
Register a plugin. New plugins are added to the end of the plugins list.
def register(self, plugin): """ Register a plugin. New plugins are added to the end of the plugins list. :param samtranslator.plugins.BasePlugin plugin: Instance/subclass of BasePlugin class that implements hooks :raises ValueError: If plugin is not an instance of samtranslator.plugins....
Retrieves the plugin with given name
def _get(self, plugin_name): """ Retrieves the plugin with given name :param plugin_name: Name of the plugin to retrieve :return samtranslator.plugins.BasePlugin: Returns the plugin object if found. None, otherwise """ for p in self._plugins: if p.name == pl...
Act on the specific life cycle event. The action here is to invoke the hook function on all registered plugins. * args and ** kwargs will be passed directly to the plugin s hook functions
def act(self, event, *args, **kwargs): """ Act on the specific life cycle event. The action here is to invoke the hook function on all registered plugins. *args and **kwargs will be passed directly to the plugin's hook functions :param samtranslator.plugins.LifeCycleEvents event: Event ...
: param logical_id: the logical_id of the resource that owns this deployment preference: param deployment_preference_dict: the dict object taken from the SAM template: return:
def from_dict(cls, logical_id, deployment_preference_dict): """ :param logical_id: the logical_id of the resource that owns this deployment preference :param deployment_preference_dict: the dict object taken from the SAM template :return: """ enabled = deployment_preferen...
decrypt leverages KMS decrypt and base64 - encode decrypted blob
def decrypt(message): '''decrypt leverages KMS decrypt and base64-encode decrypted blob More info on KMS decrypt API: https://docs.aws.amazon.com/kms/latest/APIReference/API_decrypt.html ''' try: ret = kms.decrypt( CiphertextBlob=base64.decodestring(message)) dec...
Demonstrates S3 trigger that uses Rekognition APIs to detect faces labels and index faces in S3 Object.
def lambda_handler(event, context): '''Demonstrates S3 trigger that uses Rekognition APIs to detect faces, labels and index faces in S3 Object. ''' #print("Received event: " + json.dumps(event, indent=2)) # Get the object from the event bucket = event['Records'][0]['s3']['bucket']['name'] k...
Prepends the first argument ( i. e. the exception message ) of the a BaseException with the provided message. Useful for reraising exceptions with additional information.
def prepend(exception, message, end=': '): """Prepends the first argument (i.e., the exception message) of the a BaseException with the provided message. Useful for reraising exceptions with additional information. :param BaseException exception: the exception to prepend :param str message: the message...
Validate the incoming token and produce the principal user identifier associated with the token. This can be accomplished in a number of ways:
def lambda_handler(event, context): # incoming token value token = event['authorizationToken'] print("Method ARN: " + event['methodArn']) ''' Validate the incoming token and produce the principal user identifier associated with the token. This can be accomplished in a number of ways: 1. Ca...
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
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.
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.
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
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
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.
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.
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.
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.
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 response to API eve...
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
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 internal pinned Lam...
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.
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.
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.
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
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.
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.
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
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
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
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
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.
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
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
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.
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
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
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.
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
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.
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.
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:
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.::
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.
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.
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.
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.
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
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
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
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.
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.
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.
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...
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 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...
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.
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.
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.
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.
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.
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
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.
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.
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
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.
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
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.
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.
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.
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.
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.
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.
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.
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
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.
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.
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.
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.
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.
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
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...