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._getEmptyStatement(effect) for curMethod in methods: if curMethod['conditions'] is None or len(curMethod['conditions']) == 0: statement['Resource'].append(curMethod['resourceArn']) else: conditionalStatement = self._getEmptyStatement(effect) conditionalStatement['Resource'].append(curMethod['resourceArn']) conditionalStatement['Condition'] = curMethod['conditions'] statements.append(conditionalStatement) if statement['Resource']: statements.append(statement) return statements
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 processed :param dict resource_properties: Properties of the resource :return: Nothing """ if not self._is_supported(resource_type): return function_policies = FunctionPolicies(resource_properties, self._policy_template_processor) if len(function_policies) == 0: # No policies to process return result = [] for policy_entry in function_policies.get(): if policy_entry.type is not PolicyTypes.POLICY_TEMPLATE: # If we don't know the type, skip processing and pass to result as is. result.append(policy_entry.data) continue # We are processing policy templates. We know they have a particular structure: # {"templateName": { parameter_values_dict }} template_data = policy_entry.data template_name = list(template_data.keys())[0] template_parameters = list(template_data.values())[0] try: # 'convert' will return a list of policy statements result.append(self._policy_template_processor.convert(template_name, template_parameters)) except InsufficientParameterValues as ex: # Exception's message will give lot of specific details raise InvalidResourceException(logical_id, str(ex)) except InvalidParameterValues: raise InvalidResourceException(logical_id, "Must specify valid parameter values for policy template '{}'" .format(template_name)) # Save the modified policies list to the input resource_properties[FunctionPolicies.POLICIES_PROPERTY_NAME] = result
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_count = sum(1 for record in output if record['result'] == 'Ok') failure_count = sum(1 for record in output if record['result'] == 'ProcessingFailed') print('Processing completed. Successful records: {0}, Failed records: {1}.'.format(success_count, failure_count)) return {'records': output}
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: the transformed CloudFormation template :rtype: dict """ sam_parser = Parser() translator = Translator(managed_policy_loader.load(), sam_parser) return translator.translate(input_fragment, parameter_values=parameter_values)
: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(None) and v is not None) return {'CodeDeployLambdaAliasUpdate': codedeploy_lambda_alias_update_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 :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 :return: Nothing """ template = SamTemplate(template_dict) # Temporarily add Serverless::Api resource corresponding to Implicit API to the template. # This will allow the processing code to work the same way for both Implicit & Explicit APIs # If there are no implicit APIs, we will remove from the template later. # If the customer has explicitly defined a resource with the id of "ServerlessRestApi", # capture it. If the template ends up not defining any implicit api's, instead of just # removing the "ServerlessRestApi" resource, we just restore what the author defined. self.existing_implicit_api_resource = copy.deepcopy(template.get(self.implicit_api_logical_id)) template.set(self.implicit_api_logical_id, ImplicitApiResource().to_dict()) errors = [] for logicalId, function in template.iterate(SamResourceType.Function.value): api_events = self._get_api_events(function) condition = function.condition if len(api_events) == 0: continue try: self._process_api_events(function, api_events, template, condition) except InvalidEventException as ex: errors.append(InvalidResourceException(logicalId, ex.message)) self._maybe_add_condition_to_implicit_api(template_dict) self._maybe_add_conditions_to_implicit_api_paths(template) self._maybe_remove_implicit_api(template) if len(errors) > 0: raise InvalidDocumentException(errors)
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, MethodSettings: {<something>}, Cors: {<something>}, Auth: {<something>}}, BarEvent: {Path: "/bar", Method: "any", MethodSettings: {<something>}, Cors: {<something>}, Auth: {<something>}}" }
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: { FooEvent: {Path: "/foo", Method: "post", RestApiId: blah, MethodSettings: {<something>}, Cors: {<something>}, Auth: {<something>}}, BarEvent: {Path: "/bar", Method: "any", MethodSettings: {<something>}, Cors: {<something>}, Auth: {<something>}}" } """ if not (function.valid() and isinstance(function.properties, dict) and isinstance(function.properties.get("Events"), dict) ): # Function resource structure is invalid. return {} api_events = {} for event_id, event in function.properties["Events"].items(): if event and isinstance(event, dict) and event.get("Type") == "Api": api_events[event_id] = event return api_events
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 events will be processed :param SamTemplate template: SAM Template where Serverless::Api resources can be found :param str condition: optional; this is the condition that is on the function with the API event
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 events to be processed :param dict api_events: API Events extracted from the function. These events will be processed :param SamTemplate template: SAM Template where Serverless::Api resources can be found :param str condition: optional; this is the condition that is on the function with the API event """ for logicalId, event in api_events.items(): event_properties = event.get("Properties", {}) if not event_properties: continue self._add_implicit_api_id_if_necessary(event_properties) api_id = self._get_api_id(event_properties) try: path = event_properties["Path"] method = event_properties["Method"] except KeyError as e: raise InvalidEventException(logicalId, "Event is missing key {}.".format(e)) if (not isinstance(path, six.string_types)): raise InvalidEventException(logicalId, "Api Event must have a String specified for 'Path'.") if (not isinstance(method, six.string_types)): raise InvalidEventException(logicalId, "Api Event must have a String specified for 'Method'.") api_dict = self.api_conditions.setdefault(api_id, {}) method_conditions = api_dict.setdefault(path, {}) method_conditions[method] = condition self._add_api_to_swagger(logicalId, event_properties, template) api_events[logicalId] = event # We could have made changes to the Events structure. Write it back to function function.properties["Events"].update(api_events)
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::Api resources
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 the event :param SamTemplate template: SAM Template to search for Serverless::Api resources """ # Need to grab the AWS::Serverless::Api resource for this API event and update its Swagger definition api_id = self._get_api_id(event_properties) # RestApiId is not pointing to a valid API resource if isinstance(api_id, dict) or not template.get(api_id): raise InvalidEventException(event_id, "RestApiId must be a valid reference to an 'AWS::Serverless::Api' resource " "in same template") # Make sure Swagger is valid resource = template.get(api_id) if not (resource and isinstance(resource.properties, dict) and SwaggerEditor.is_valid(resource.properties.get("DefinitionBody"))): # This does not have an inline Swagger. Nothing can be done about it. return if not resource.properties.get("__MANAGE_SWAGGER"): # Do not add the api to Swagger, if the resource is not actively managed by SAM. # ie. Implicit API resources are created & managed by SAM on behalf of customers. # But for explicit API resources, customers write their own Swagger and manage it. # If a path is present in Events section but *not* present in the Explicit API Swagger, then it is # customer's responsibility to add to Swagger. We will not modify the Swagger here. # # In the future, we will might expose a flag that will allow SAM to manage explicit API Swagger as well. # Until then, we will not modify explicit explicit APIs. return swagger = resource.properties.get("DefinitionBody") path = event_properties["Path"] method = event_properties["Method"] editor = SwaggerEditor(swagger) editor.add_path(path, method) resource.properties["DefinitionBody"] = editor.swagger template.set(api_id, resource)
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: api_id = api_id["Ref"] return 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 not self.api_conditions.get(self.implicit_api_logical_id, {}): return # Add a condition to the API resource IFF all of its resource+methods are associated with serverless functions # containing conditions. implicit_api_conditions = self.api_conditions[self.implicit_api_logical_id] all_resource_method_conditions = set([condition for path, method_conditions in implicit_api_conditions.items() for method, condition in method_conditions.items()]) at_least_one_resource_method = len(all_resource_method_conditions) > 0 all_resource_methods_contain_conditions = None not in all_resource_method_conditions if at_least_one_resource_method and all_resource_methods_contain_conditions: implicit_api_resource = template_dict.get('Resources').get(self.implicit_api_logical_id) if len(all_resource_method_conditions) == 1: condition = all_resource_method_conditions.pop() implicit_api_resource['Condition'] = condition else: # If multiple functions with multiple different conditions reference the Implicit Api, we need to # aggregate those conditions in order to conditionally create the Implicit Api. See RFC: # https://github.com/awslabs/serverless-application-model/issues/758 implicit_api_resource['Condition'] = self.implicit_api_condition self._add_combined_condition_to_template( template_dict, self.implicit_api_condition, all_resource_method_conditions)
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 form top-level condition.
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 template condition :param list conditions_to_combine: List of conditions that should be combined (via OR operator) to form top-level condition. """ # defensive precondition check if not conditions_to_combine or len(conditions_to_combine) < 2: raise ValueError('conditions_to_combine must have at least 2 conditions') template_conditions = template_dict.setdefault('Conditions', {}) new_template_conditions = make_combined_condition(sorted(list(conditions_to_combine)), condition_name) for name, definition in new_template_conditions.items(): template_conditions[name] = definition
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 path have conditions on them. If all of these conditions evaluate to false, the entire resource path should not be defined either. This method checks all resource paths' methods and if all methods under a given path contain a condition, a composite condition is added to the overall template Conditions section and that composite condition is added to the resource path.
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 conditions on them, it's possible to have a case where all methods under a resource path have conditions on them. If all of these conditions evaluate to false, the entire resource path should not be defined either. This method checks all resource paths' methods and if all methods under a given path contain a condition, a composite condition is added to the overall template Conditions section and that composite condition is added to the resource path. """ for api_id, api in template.iterate(SamResourceType.Api.value): if not api.properties.get('__MANAGE_SWAGGER'): continue swagger = api.properties.get("DefinitionBody") editor = SwaggerEditor(swagger) for path in editor.iter_on_path(): all_method_conditions = set( [condition for method, condition in self.api_conditions[api_id][path].items()] ) at_least_one_method = len(all_method_conditions) > 0 all_methods_contain_conditions = None not in all_method_conditions if at_least_one_method and all_methods_contain_conditions: if len(all_method_conditions) == 1: editor.make_path_conditional(path, all_method_conditions.pop()) else: path_condition_name = self._path_condition_name(api_id, path) self._add_combined_condition_to_template( template.template_dict, path_condition_name, all_method_conditions) editor.make_path_conditional(path, path_condition_name) api.properties["DefinitionBody"] = editor.swagger template.set(api_id, api)
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 templated params, e.g., /foo/{customerId}. So we'll replace # non-alphanumeric characters. path_logical_id = path.replace('/', 'SLASH').replace('{', 'OB').replace('}', 'CB') return '{}{}PathCondition'.format(api_id, path_logical_id)
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 events). :param SamTemplate template: SAM Template containing the Implicit API resource
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 Implicit API if it does not contain any Swagger paths (added in response to API events). :param SamTemplate template: SAM Template containing the Implicit API resource """ # Remove Implicit API resource if no paths got added implicit_api_resource = template.get(self.implicit_api_logical_id) if implicit_api_resource and len(implicit_api_resource.properties["DefinitionBody"]["paths"]) == 0: # If there's no implicit api and the author defined a "ServerlessRestApi" # resource, restore it if self.existing_implicit_api_resource: template.set(self.implicit_api_logical_id, self.existing_implicit_api_resource) else: template.delete(self.implicit_api_logical_id)
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 does NOT redeploy the API unless it has a new deployment resource # that points to latest RestApi resource. Append a hash of Swagger Body location to # redeploy only when the API data changes. First 10 characters of hash is good enough # to prevent redeployment when API has not changed # NOTE: `str(swagger)` is for backwards compatibility. Changing it to a JSON or something will break compat generator = logical_id_generator.LogicalIdGenerator(self.logical_id, str(swagger)) self.logical_id = generator.gen() hash = generator.get_hash(length=40) # Get the full hash self.Description = "RestApi deployment id: {}".format(hash) stage.update_deployment_ref(self.logical_id)
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 Lambdas.
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 having it built for them. This lets you include custom ExtensionMap_ values like subject which are needed for our internal pinned Lambdas. """ customer_logger.info('Invoking Lambda function "{}" with Greengrass Message "{}"'.format(function_arn, payload)) try: invocation_id = self.ipc.post_work(function_arn, payload, client_context, invocation_type) if invocation_type == "Event": # TODO: Properly return errors based on BOTO response # https://boto3.readthedocs.io/en/latest/reference/services/lambda.html#Lambda.Client.invoke return {'Payload': b'', 'FunctionError': ''} work_result_output = self.ipc.get_work_result(function_arn, invocation_id) if not work_result_output.func_err: output_payload = StreamingBody(work_result_output.payload) else: output_payload = work_result_output.payload invoke_output = { 'Payload': output_payload, 'FunctionError': work_result_output.func_err, } return invoke_output except IPCException as e: customer_logger.exception(e) raise InvocationException('Failed to invoke function due to ' + str(e))
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_context: The base64 encoded client context byte string that will be provided to the Lambda function being invoked. :type client_context: bytes :returns: Invocation ID for obtaining result of the work. :type returns: str
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 :param input_bytes: The data making up the work being posted. :type input_bytes: bytes :param client_context: The base64 encoded client context byte string that will be provided to the Lambda function being invoked. :type client_context: bytes :returns: Invocation ID for obtaining result of the work. :type returns: str """ url = self._get_url(function_arn) runtime_logger.info('Posting work for function [{}] to {}'.format(function_arn, url)) request = Request(url, input_bytes or b'') request.add_header(HEADER_CLIENT_CONTEXT, client_context) request.add_header(HEADER_AUTH_TOKEN, self.auth_token) request.add_header(HEADER_INVOCATION_TYPE, invocation_type) response = urlopen(request) invocation_id = response.info().get(HEADER_INVOCATION_ID) runtime_logger.info('Work posted with invocation id [{}]'.format(invocation_id)) return invocation_id
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. :type returns: WorkItem """ url = self._get_work_url(function_arn) runtime_logger.info('Getting work for function [{}] from {}'.format(function_arn, url)) request = Request(url) request.add_header(HEADER_AUTH_TOKEN, self.auth_token) response = urlopen(request) invocation_id = response.info().get(HEADER_INVOCATION_ID) client_context = response.info().get(HEADER_CLIENT_CONTEXT) runtime_logger.info('Got work item with invocation id [{}]'.format(invocation_id)) return WorkItem( invocation_id=invocation_id, payload=response.read(), client_context=client_context)
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: WorkItem :returns: None
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 holding the results of the work being posted. :type work_item: WorkItem :returns: None """ url = self._get_work_url(function_arn) runtime_logger.info('Posting work result for invocation id [{}] to {}'.format(work_item.invocation_id, url)) request = Request(url, work_item.payload or b'') request.add_header(HEADER_INVOCATION_ID, work_item.invocation_id) request.add_header(HEADER_AUTH_TOKEN, self.auth_token) urlopen(request) runtime_logger.info('Posted work result for invocation id [{}]'.format(work_item.invocation_id))
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 is being requested :type invocation_id: string :param handler_err: the error message caught from handler :type handler_err: string
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. :type function_arn: string :param invocation_id: Invocation ID of the work that is being requested :type invocation_id: string :param handler_err: the error message caught from handler :type handler_err: string """ url = self._get_work_url(function_arn) runtime_logger.info('Posting handler error for invocation id [{}] to {}'.format(invocation_id, url)) payload = json.dumps({ "errorMessage": handler_err, }).encode('utf-8') request = Request(url, payload) request.add_header(HEADER_INVOCATION_ID, invocation_id) request.add_header(HEADER_FUNCTION_ERR_TYPE, "Handled") request.add_header(HEADER_AUTH_TOKEN, self.auth_token) urlopen(request) runtime_logger.info('Posted handler error for invocation id [{}]'.format(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: string :param invocation_id: Invocation ID of the work that is being requested :type invocation_id: string :returns: The get work result output contains result payload and function error type if the invoking is failed. :type returns: GetWorkResultOutput
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: string :param invocation_id: Invocation ID of the work that is being requested :type invocation_id: string :returns: The get work result output contains result payload and function error type if the invoking is failed. :type returns: GetWorkResultOutput """ url = self._get_url(function_arn) runtime_logger.info('Getting work result for invocation id [{}] from {}'.format(invocation_id, url)) request = Request(url) request.add_header(HEADER_INVOCATION_ID, invocation_id) request.add_header(HEADER_AUTH_TOKEN, self.auth_token) response = urlopen(request) runtime_logger.info('Got result for invocation id [{}]'.format(invocation_id)) payload = response.read() func_err = response.info().get(HEADER_FUNCTION_ERR_TYPE) return GetWorkResultOutput( payload=payload, func_err=func_err)
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 has access to all specified applications. :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 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 has access to all specified applications. :param dict template_dict: Dictionary of the SAM template :return: Nothing """ template = SamTemplate(template_dict) intrinsic_resolvers = self._get_intrinsic_resolvers(template_dict.get('Mappings', {})) service_call = None if self._validate_only: service_call = self._handle_get_application_request else: service_call = self._handle_create_cfn_template_request for logical_id, app in template.iterate(SamResourceType.Application.value): if not self._can_process_application(app): # Handle these cases in the on_before_transform_resource event continue app_id = self._replace_value(app.properties[self.LOCATION_KEY], self.APPLICATION_ID_KEY, intrinsic_resolvers) semver = self._replace_value(app.properties[self.LOCATION_KEY], self.SEMANTIC_VERSION_KEY, intrinsic_resolvers) if isinstance(app_id, dict) or isinstance(semver, dict): key = (json.dumps(app_id), json.dumps(semver)) self._applications[key] = False continue key = (app_id, semver) if key not in self._applications: try: # Lazy initialization of the client- create it when it is needed if not self._sar_client: self._sar_client = boto3.client('serverlessrepo') service_call(app_id, semver, key, logical_id) except InvalidResourceException as e: # Catch all InvalidResourceExceptions, raise those in the before_resource_transform target. self._applications[key] = e
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.properties[self.LOCATION_KEY], dict) and self.APPLICATION_ID_KEY in app.properties[self.LOCATION_KEY] and self.SEMANTIC_VERSION_KEY in app.properties[self.LOCATION_KEY])
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 :param string key: The dictionary key consisting of (ApplicationId, SemanticVersion) :param string logical_id: the logical_id of this application resource
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. :param string app_id: ApplicationId :param string semver: SemanticVersion :param string key: The dictionary key consisting of (ApplicationId, SemanticVersion) :param string logical_id: the logical_id of this application resource """ get_application = (lambda app_id, semver: self._sar_client.get_application( ApplicationId=self._sanitize_sar_str_param(app_id), SemanticVersion=self._sanitize_sar_str_param(semver))) try: self._sar_service_call(get_application, logical_id, app_id, semver) self._applications[key] = {'Available'} except EndpointConnectionError as e: # No internet connection. Don't break verification, but do show a warning. warning_message = "{}. Unable to verify access to {}/{}.".format(e, app_id, semver) logging.warning(warning_message) self._applications[key] = {'Unable to verify'}
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: the logical_id of this application resource
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: The dictionary key consisting of (ApplicationId, SemanticVersion) :param string logical_id: the logical_id of this application resource """ create_cfn_template = (lambda app_id, semver: self._sar_client.create_cloud_formation_template( ApplicationId=self._sanitize_sar_str_param(app_id), SemanticVersion=self._sanitize_sar_str_param(semver) )) response = self._sar_service_call(create_cfn_template, logical_id, app_id, semver) self._applications[key] = response[self.TEMPLATE_URL_KEY] if response['Status'] != "ACTIVE": self._in_progress_templates.append((response[self.APPLICATION_ID_KEY], response['TemplateId']))
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 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 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 dict resource_properties: Properties of the resource :return: Nothing """ if not self._resource_is_supported(resource_type): return # Sanitize properties self._check_for_dictionary_key(logical_id, resource_properties, [self.LOCATION_KEY]) # If location isn't a dictionary, don't modify the resource. if not isinstance(resource_properties[self.LOCATION_KEY], dict): resource_properties[self.TEMPLATE_URL_KEY] = resource_properties[self.LOCATION_KEY] return # If it is a dictionary, check for other required parameters self._check_for_dictionary_key(logical_id, resource_properties[self.LOCATION_KEY], [self.APPLICATION_ID_KEY, self.SEMANTIC_VERSION_KEY]) app_id = resource_properties[self.LOCATION_KEY].get(self.APPLICATION_ID_KEY) if not app_id: raise InvalidResourceException(logical_id, "Property 'ApplicationId' cannot be blank.") if isinstance(app_id, dict): raise InvalidResourceException(logical_id, "Property 'ApplicationId' cannot be resolved. Only FindInMap " "and Ref intrinsic functions are supported.") semver = resource_properties[self.LOCATION_KEY].get(self.SEMANTIC_VERSION_KEY) if not semver: raise InvalidResourceException(logical_id, "Property 'SemanticVersion' cannot be blank.") if isinstance(semver, dict): raise InvalidResourceException(logical_id, "Property 'SemanticVersion' cannot be resolved. Only FindInMap " "and Ref intrinsic functions are supported.") key = (app_id, semver) # Throw any resource exceptions saved from the before_transform_template event if isinstance(self._applications[key], InvalidResourceException): raise self._applications[key] # validation does not resolve an actual template url if not self._validate_only: resource_properties[self.TEMPLATE_URL_KEY] = self._applications[key]
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 check :param list keys: list of keys that should exist in the dictionary """ for key in keys: if key not in dictionary: raise InvalidResourceException(logical_id, 'Resource is missing the required [{}] ' 'property.'.format(key))
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 """ if self._wait_for_template_active_status and not self._validate_only: start_time = time() while (time() - start_time) < self.TEMPLATE_WAIT_TIMEOUT_SECONDS: temp = self._in_progress_templates self._in_progress_templates = [] # Check each resource to make sure it's active for application_id, template_id in temp: get_cfn_template = (lambda application_id, template_id: self._sar_client.get_cloud_formation_template( ApplicationId=self._sanitize_sar_str_param(application_id), TemplateId=self._sanitize_sar_str_param(template_id))) response = self._sar_service_call(get_cfn_template, application_id, application_id, template_id) self._handle_get_cfn_template_response(response, application_id, template_id) # Don't sleep if there are no more templates with PREPARING status if len(self._in_progress_templates) == 0: break # Sleep a little so we don't spam service calls sleep(self.SLEEP_TIME_SECONDS) # Not all templates reached active status if len(self._in_progress_templates) != 0: application_ids = [items[0] for items in self._in_progress_templates] raise InvalidResourceException(application_ids, "Timed out waiting for nested stack templates " "to reach ACTIVE status.")
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 unique TemplateId for this application """ status = response['Status'] if status != "ACTIVE": # Other options are PREPARING and EXPIRED. if status == 'EXPIRED': message = ("Template for {} with id {} returned status: {}. Cannot access an expired " "template.".format(application_id, template_id, status)) raise InvalidResourceException(application_id, message) self._in_progress_templates.append((application_id, template_id))
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 for the service call lambda
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 logical_id: Logical ID of the resource being processed :param list *args: arguments for the service call lambda """ try: response = service_call_lambda(*args) logging.info(response) return response except ClientError as e: error_code = e.response['Error']['Code'] if error_code in ('AccessDeniedException', 'NotFoundException'): raise InvalidResourceException(logical_id, e.response['Error']['Message']) # 'ForbiddenException'- SAR rejects connection logging.exception(e) raise e
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 parameter_values is None: raise ValueError("`parameter_values` argument is required") if ("Resources" not in sam_template or not isinstance(sam_template["Resources"], dict) or not sam_template["Resources"]): raise InvalidDocumentException( [InvalidTemplateException("'Resources' section is required")]) if (not all(isinstance(sam_resource, dict) for sam_resource in sam_template["Resources"].values())): raise InvalidDocumentException( [InvalidTemplateException( "All 'Resources' must be Objects. If you're using YAML, this may be an " "indentation issue." )]) sam_template_instance = SamTemplate(sam_template) for resource_logical_id, sam_resource in sam_template_instance.iterate(): # NOTE: Properties isn't required for SimpleTable, so we can't check # `not isinstance(sam_resources.get("Properties"), dict)` as this would be a breaking change. # sam_resource.properties defaults to {} in SamTemplate init if (not isinstance(sam_resource.properties, dict)): raise InvalidDocumentException( [InvalidResourceException(resource_logical_id, "All 'Resources' must be Objects and have a 'Properties' Object. If " "you're using YAML, this may be an indentation issue." )]) SamTemplateValidator.validate(sam_template)
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 """ for logicalId, resource_dict in self.resources.items(): resource = SamResource(resource_dict) needs_filter = resource.valid() if resource_type: needs_filter = needs_filter and resource.type == resource_type if needs_filter: yield 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
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_dict = resource if isinstance(resource, SamResource): resource_dict = resource.to_dict() self.resources[logicalId] = resource_dict
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 return SamResource(self.resources.get(logicalId))
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 install :param parameters: Dictionary of parameter values :return samtranslator.plugins.SamPlugins: Instance of `SamPlugins`
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 samtranslator.plugins.BasePlugin plugins: List of plugins to install :param parameters: Dictionary of parameter values :return samtranslator.plugins.SamPlugins: Instance of `SamPlugins` """ required_plugins = [ DefaultDefinitionBodyPlugin(), make_implicit_api_plugin(), GlobalsPlugin(), make_policy_template_for_function_plugin(), ] plugins = [] if not plugins else plugins # If a ServerlessAppPlugin does not yet exist, create one and add to the beginning of the required plugins list. if not any(isinstance(plugin, ServerlessAppPlugin) for plugin in plugins): required_plugins.insert(0, ServerlessAppPlugin(parameters=parameters)) # Execute customer's plugins first before running SAM plugins. It is very important to retain this order because # other plugins will be dependent on this ordering. return SamPlugins(plugins + required_plugins)
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 \ CloudFormation transforms. :param dict parameter_values: Map of template parameter names to their values. It is a required parameter that should at least be an empty map. By providing an empty map, the caller explicitly opts-into the idea that some functionality that relies on resolving parameter references might not work as expected (ex: auto-creating new Lambda Version when CodeUri contains reference to template parameter). This is why this parameter is required :returns: a copy of the template with SAM resources replaced with the corresponding CloudFormation, which may \ be dumped into a valid CloudFormation JSON or YAML 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() or yaml.load(), or as provided by \ CloudFormation transforms. :param dict parameter_values: Map of template parameter names to their values. It is a required parameter that should at least be an empty map. By providing an empty map, the caller explicitly opts-into the idea that some functionality that relies on resolving parameter references might not work as expected (ex: auto-creating new Lambda Version when CodeUri contains reference to template parameter). This is why this parameter is required :returns: a copy of the template with SAM resources replaced with the corresponding CloudFormation, which may \ be dumped into a valid CloudFormation JSON or YAML template """ sam_parameter_values = SamParameterValues(parameter_values) sam_parameter_values.add_default_parameter_values(sam_template) sam_parameter_values.add_pseudo_parameter_values() parameter_values = sam_parameter_values.parameter_values # Create & Install plugins sam_plugins = prepare_plugins(self.plugins, parameter_values) self.sam_parser.parse( sam_template=sam_template, parameter_values=parameter_values, sam_plugins=sam_plugins ) template = copy.deepcopy(sam_template) macro_resolver = ResourceTypeResolver(sam_resources) intrinsics_resolver = IntrinsicsResolver(parameter_values) deployment_preference_collection = DeploymentPreferenceCollection() supported_resource_refs = SupportedResourceReferences() document_errors = [] changed_logical_ids = {} for logical_id, resource_dict in self._get_resources_to_iterate(sam_template, macro_resolver): try: macro = macro_resolver\ .resolve_resource_type(resource_dict)\ .from_dict(logical_id, resource_dict, sam_plugins=sam_plugins) kwargs = macro.resources_to_link(sam_template['Resources']) kwargs['managed_policy_map'] = self.managed_policy_map kwargs['intrinsics_resolver'] = intrinsics_resolver kwargs['deployment_preference_collection'] = deployment_preference_collection translated = macro.to_cloudformation(**kwargs) supported_resource_refs = macro.get_resource_references(translated, supported_resource_refs) # Some resources mutate their logical ids. Track those to change all references to them: if logical_id != macro.logical_id: changed_logical_ids[logical_id] = macro.logical_id del template['Resources'][logical_id] for resource in translated: if verify_unique_logical_id(resource, sam_template['Resources']): template['Resources'].update(resource.to_dict()) else: document_errors.append(DuplicateLogicalIdException( logical_id, resource.logical_id, resource.resource_type)) except (InvalidResourceException, InvalidEventException) as e: document_errors.append(e) if deployment_preference_collection.any_enabled(): template['Resources'].update(deployment_preference_collection.codedeploy_application.to_dict()) if not deployment_preference_collection.can_skip_service_role(): template['Resources'].update(deployment_preference_collection.codedeploy_iam_role.to_dict()) for logical_id in deployment_preference_collection.enabled_logical_ids(): template['Resources'].update(deployment_preference_collection.deployment_group(logical_id).to_dict()) # Run the after-transform plugin target try: sam_plugins.act(LifeCycleEvents.after_transform_template, template) except (InvalidDocumentException, InvalidResourceException) as e: document_errors.append(e) # Cleanup if 'Transform' in template: del template['Transform'] if len(document_errors) == 0: template = intrinsics_resolver.resolve_sam_resource_id_refs(template, changed_logical_ids) template = intrinsics_resolver.resolve_sam_resource_refs(template, supported_resource_refs) return template else: raise InvalidDocumentException(document_errors)
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 resource with API Events will modify the API resource's Swagger JSON. Therefore API resource needs to be parsed only after all the Swagger modifications are complete. :param dict sam_template: SAM template :param macro_resolver: Resolver that knows if a resource can be processed or not :return list: List containing tuple of (logicalId, resource_dict) in the order of processing
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::Api 3. Anything else This is necessary because a Function resource with API Events will modify the API resource's Swagger JSON. Therefore API resource needs to be parsed only after all the Swagger modifications are complete. :param dict sam_template: SAM template :param macro_resolver: Resolver that knows if a resource can be processed or not :return list: List containing tuple of (logicalId, resource_dict) in the order of processing """ functions = [] apis = [] others = [] resources = sam_template["Resources"] for logicalId, resource in resources.items(): data = (logicalId, resource) # Skip over the resource if it is not a SAM defined Resource if not macro_resolver.can_resolve(resource): continue elif resource["Type"] == "AWS::Serverless::Function": functions.append(data) elif resource["Type"] == "AWS::Serverless::Api": apis.append(data) else: others.append(data) return functions + apis + others
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>", "Properties": { <set of properties> } } :param str logical_id: The logical id of this Resource :param dict resource_dict: The value associated with this logical id in the CloudFormation template, a mapping \ containing the resource's Type and Properties. :param str relative_id: The logical id of this resource relative to the logical_id. This is useful to identify sub-resources. :param samtranslator.plugins.SamPlugins sam_plugins: Optional plugins object to help enhance functionality of translator :returns: a Resource object populated from the provided parameters :rtype: Resource :raises TypeError: if the provided parameters are invalid
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 following format. :: { "Type": "<resource type>", "Properties": { <set of properties> } } :param str logical_id: The logical id of this Resource :param dict resource_dict: The value associated with this logical id in the CloudFormation template, a mapping \ containing the resource's Type and Properties. :param str relative_id: The logical id of this resource relative to the logical_id. This is useful to identify sub-resources. :param samtranslator.plugins.SamPlugins sam_plugins: Optional plugins object to help enhance functionality of translator :returns: a Resource object populated from the provided parameters :rtype: Resource :raises TypeError: if the provided parameters are invalid """ resource = cls(logical_id, relative_id=relative_id) resource._validate_resource_dict(logical_id, resource_dict) # Default to empty properties dictionary. If customers skip the Properties section, an empty dictionary # accurately captures the intent. properties = resource_dict.get("Properties", {}) if sam_plugins: sam_plugins.act(LifeCycleEvents.before_transform_resource, logical_id, cls.resource_type, properties) for name, value in properties.items(): setattr(resource, name, value) if 'DependsOn' in resource_dict: resource.depends_on = resource_dict['DependsOn'] # Parse only well known properties. This is consistent with earlier behavior where we used to ignore resource # all resource attributes ie. all attributes were unsupported before for attr in resource._supported_resource_attributes: if attr in resource_dict: resource.set_resource_attribute(attr, resource_dict[attr]) resource.validate_properties() return resource
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 """ pattern = re.compile(r'^[A-Za-z0-9]+$') if logical_id is not None and pattern.match(logical_id): return True raise InvalidResourceException(logical_id, "Logical ids must be alphanumeric.")
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 resource dict has an invalid format
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 :rtype: bool :raises InvalidResourceException: if the resource dict has an invalid format """ if 'Type' not in resource_dict: raise InvalidResourceException(logical_id, "Resource dict missing key 'Type'.") if resource_dict['Type'] != cls.resource_type: raise InvalidResourceException(logical_id, "Resource has incorrect Type; expected '{expected}', " "got '{actual}'".format( expected=cls.resource_type, actual=resource_dict['Type'])) if 'Properties' in resource_dict and not isinstance(resource_dict['Properties'], dict): raise InvalidResourceException(logical_id, "Properties of a resource must be an object.")
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. :: { "<logical id>": { "Type": "<resource type>", "DependsOn": "<value specified by user>", "Properties": { <set of properties> } } } The resulting dict can then be serialized to JSON or YAML and included as part of a CloudFormation template. :returns: a dict corresponding to this Resource's entry in a CloudFormation template :rtype: dict :raises TypeError: if a required property is missing from this Resource
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 format. :: { "<logical id>": { "Type": "<resource type>", "DependsOn": "<value specified by user>", "Properties": { <set of properties> } } } The resulting dict can then be serialized to JSON or YAML and included as part of a CloudFormation template. :returns: a dict corresponding to this Resource's entry in a CloudFormation template :rtype: dict :raises TypeError: if a required property is missing from this Resource """ self.validate_properties() resource_dict = self._generate_resource_dict() return {self.logical_id: resource_dict}
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 = {} resource_dict['Type'] = self.resource_type if self.depends_on: resource_dict['DependsOn'] = self.depends_on resource_dict.update(self.resource_attributes) properties_dict = {} for name in self.property_types: value = getattr(self, name) if value is not None: properties_dict[name] = value resource_dict['Properties'] = properties_dict return resource_dict
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 """ for name, property_type in self.property_types.items(): value = getattr(self, name) # If the property value is an intrinsic function, any remaining validation has to be left to CloudFormation if property_type.supports_intrinsics and self._is_intrinsic_function(value): continue # If the property value has not been set, verify that the property is not required. if value is None: if property_type.required: raise InvalidResourceException( self.logical_id, "Missing required property '{property_name}'.".format(property_name=name)) # Otherwise, validate the value of the property. elif not property_type.validate(value, should_raise=False): raise InvalidResourceException( self.logical_id, "Type of property '{property_name}' is invalid.".format(property_name=name))
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 attribute list
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 :raises KeyError if `attr` is not in the supported attribute list """ if attr not in self._supported_resource_attributes: raise KeyError("Unsupported resource attribute specified: %s" % attr) self.resource_attributes[attr] = value
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 resource attributes" % attr) return self.resource_attributes[attr]
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 stack update is executed """ if attr_name in self.runtime_attrs: return self.runtime_attrs[attr_name](self) else: raise NotImplementedError(attr_name + " attribute is not implemented for resource " + self.resource_type)
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 Resource object generated_cfn_resources: List of CloudFormation resources generated by this SAM resource :param samtranslator.intrinsics.resource_refs.SupportedResourceReferences supported_resource_refs: Object holding the mapping between property names and LogicalId of the generated CFN resource it maps to :return: Updated supported_resource_refs
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 it supports and the type of CFN resource this property resolves to. :param list of Resource object generated_cfn_resources: List of CloudFormation resources generated by this SAM resource :param samtranslator.intrinsics.resource_refs.SupportedResourceReferences supported_resource_refs: Object holding the mapping between property names and LogicalId of the generated CFN resource it maps to :return: Updated supported_resource_refs """ if supported_resource_refs is None: raise ValueError("`supported_resource_refs` object is required") # Create a map of {ResourceType: LogicalId} for quick access resource_id_by_type = {resource.resource_type: resource.logical_id for resource in generated_cfn_resources} for property, cfn_type in self.referable_properties.items(): if cfn_type in resource_id_by_type: supported_resource_refs.add(self.logical_id, property, resource_id_by_type[cfn_type]) return supported_resource_refs
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_resolve(resource_dict): raise TypeError("Resource dict has missing or invalid value for key Type. Event Type is: {}.".format( resource_dict.get('Type'))) if resource_dict['Type'] not in self.resource_types: raise TypeError("Invalid resource type {resource_type}".format(resource_type=resource_dict['Type'])) return self.resource_types[resource_dict['Type']]
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.append(options[i]) return { 'contentType': 'application/vnd.amazonaws.card.generic', 'version': 1, 'genericAttachments': [{ 'title': title, 'subTitle': subtitle, 'buttons': buttons }] }
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 supported in this example, the function returns a mixture of fixed and randomized results. On Mondays, availability is randomized; otherwise there is no availability on Tuesday / Thursday and availability at 10:00 - 10:30 and 4:00 - 5:00 on Wednesday / Friday.
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 of all possible conversation paths supported in this example, the function returns a mixture of fixed and randomized results. On Mondays, availability is randomized; otherwise there is no availability on Tuesday / Thursday and availability at 10:00 - 10:30 and 4:00 - 5:00 on Wednesday / Friday. """ day_of_week = dateutil.parser.parse(date).weekday() availabilities = [] available_probability = 0.3 if day_of_week == 0: start_hour = 10 while start_hour <= 16: if random.random() < available_probability: # Add an availability window for the given hour, with duration determined by another random number. appointment_type = get_random_int(1, 4) if appointment_type == 1: availabilities.append('{}:00'.format(start_hour)) elif appointment_type == 2: availabilities.append('{}:30'.format(start_hour)) else: availabilities.append('{}:00'.format(start_hour)) availabilities.append('{}:30'.format(start_hour)) start_hour += 1 if day_of_week == 2 or day_of_week == 4: availabilities.append('10:00') availabilities.append('16:00') availabilities.append('16:30') return 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.
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 duration == 30: return time in availabilities elif duration == 60: second_half_hour_time = increment_time_by_thirty_mins(time) return time in availabilities and second_half_hour_time in availabilities # Invalid duration ; throw error. We should not have reached this branch due to earlier validation. raise Exception('Was not able to understand duration {}'.format(duration))
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_output_string(availabilities[0]) if len(availabilities) == 2: return '{} and {}'.format(prefix, build_time_output_string(availabilities[1])) return '{}, {} and {}'.format(prefix, build_time_output_string(availabilities[1]), build_time_output_string(availabilities[2]))
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 availabilities: if duration == 30: duration_availabilities.append(start_time) elif increment_time_by_thirty_mins(start_time) in availabilities: duration_availabilities.append(start_time) start_time = increment_time_by_thirty_mins(start_time) return duration_availabilities
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': 'cleaning (30 min)', 'value': 'cleaning'}, {'text': 'root canal (60 min)', 'value': 'root canal'}, {'text': 'whitening (30 min)', 'value': 'whitening'} ] elif slot == 'Date': # Return the next five weekdays. options = [] potential_date = datetime.datetime.today() while len(options) < 5: potential_date = potential_date + datetime.timedelta(days=1) if potential_date.weekday() < 5: options.append({'text': '{}-{} ({})'.format((potential_date.month), potential_date.day, day_strings[potential_date.weekday()]), 'value': potential_date.strftime('%A, %B %d, %Y')}) return options elif slot == 'Time': # Return the availabilities on the given date. if not appointment_type or not date: return None availabilities = try_ex(lambda: booking_map[date]) if not availabilities: return None availabilities = get_availabilities_for_duration(get_duration(appointment_type), availabilities) if len(availabilities) == 0: return None options = [] for i in range(min(len(availabilities), 5)): options.append({'text': build_time_output_string(availabilities[i]), 'value': build_time_output_string(availabilities[i])}) return options
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 confirmation is required on the bot model and the inferred slot values fully specify the intent.
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 confirmation of inferred slot values, when confirmation is required on the bot model and the inferred slot values fully specify the intent. """ appointment_type = intent_request['currentIntent']['slots']['AppointmentType'] date = intent_request['currentIntent']['slots']['Date'] time = intent_request['currentIntent']['slots']['Time'] source = intent_request['invocationSource'] output_session_attributes = intent_request['sessionAttributes'] booking_map = json.loads(try_ex(lambda: output_session_attributes['bookingMap']) or '{}') if source == 'DialogCodeHook': # Perform basic validation on the supplied input slots. slots = intent_request['currentIntent']['slots'] validation_result = validate_book_appointment(appointment_type, date, time) if not validation_result['isValid']: slots[validation_result['violatedSlot']] = None return elicit_slot( output_session_attributes, intent_request['currentIntent']['name'], slots, validation_result['violatedSlot'], validation_result['message'], build_response_card( 'Specify {}'.format(validation_result['violatedSlot']), validation_result['message']['content'], build_options(validation_result['violatedSlot'], appointment_type, date, booking_map) ) ) if not appointment_type: return elicit_slot( output_session_attributes, intent_request['currentIntent']['name'], intent_request['currentIntent']['slots'], 'AppointmentType', {'contentType': 'PlainText', 'content': 'What type of appointment would you like to schedule?'}, build_response_card( 'Specify Appointment Type', 'What type of appointment would you like to schedule?', build_options('AppointmentType', appointment_type, date, None) ) ) if appointment_type and not date: return elicit_slot( output_session_attributes, intent_request['currentIntent']['name'], intent_request['currentIntent']['slots'], 'Date', {'contentType': 'PlainText', 'content': 'When would you like to schedule your {}?'.format(appointment_type)}, build_response_card( 'Specify Date', 'When would you like to schedule your {}?'.format(appointment_type), build_options('Date', appointment_type, date, None) ) ) if appointment_type and date: # Fetch or generate the availabilities for the given date. booking_availabilities = try_ex(lambda: booking_map[date]) if booking_availabilities is None: booking_availabilities = get_availabilities(date) booking_map[date] = booking_availabilities output_session_attributes['bookingMap'] = json.dumps(booking_map) appointment_type_availabilities = get_availabilities_for_duration(get_duration(appointment_type), booking_availabilities) if len(appointment_type_availabilities) == 0: # No availability on this day at all; ask for a new date and time. slots['Date'] = None slots['Time'] = None return elicit_slot( output_session_attributes, intent_request['currentIntent']['name'], slots, 'Date', {'contentType': 'PlainText', 'content': 'We do not have any availability on that date, is there another day which works for you?'}, build_response_card( 'Specify Date', 'What day works best for you?', build_options('Date', appointment_type, date, booking_map) ) ) message_content = 'What time on {} works for you? '.format(date) if time: output_session_attributes['formattedTime'] = build_time_output_string(time) # Validate that proposed time for the appointment can be booked by first fetching the availabilities for the given day. To # give consistent behavior in the sample, this is stored in sessionAttributes after the first lookup. if is_available(time, get_duration(appointment_type), booking_availabilities): return delegate(output_session_attributes, slots) message_content = 'The time you requested is not available. ' if len(appointment_type_availabilities) == 1: # If there is only one availability on the given date, try to confirm it. slots['Time'] = appointment_type_availabilities[0] return confirm_intent( output_session_attributes, intent_request['currentIntent']['name'], slots, { 'contentType': 'PlainText', 'content': '{}{} is our only availability, does that work for you?'.format (message_content, build_time_output_string(appointment_type_availabilities[0])) }, build_response_card( 'Confirm Appointment', 'Is {} on {} okay?'.format(build_time_output_string(appointment_type_availabilities[0]), date), [{'text': 'yes', 'value': 'yes'}, {'text': 'no', 'value': 'no'}] ) ) available_time_string = build_available_time_string(appointment_type_availabilities) return elicit_slot( output_session_attributes, intent_request['currentIntent']['name'], slots, 'Time', {'contentType': 'PlainText', 'content': '{}{}'.format(message_content, available_time_string)}, build_response_card( 'Specify Time', 'What time works best for you?', build_options('Time', appointment_type, date, booking_map) ) ) return delegate(output_session_attributes, slots) # Book the appointment. In a real bot, this would likely involve a call to a backend service. duration = get_duration(appointment_type) booking_availabilities = booking_map[date] if booking_availabilities: # Remove the availability slot for the given date as it has now been booked. booking_availabilities.remove(time) if duration == 60: second_half_hour_time = increment_time_by_thirty_mins(time) booking_availabilities.remove(second_half_hour_time) booking_map[date] = booking_availabilities output_session_attributes['bookingMap'] = json.dumps(booking_map) else: # This is not treated as an error as this code sample supports functionality either as fulfillment or dialog code hook. logger.debug('Availabilities for {} were null at fulfillment time. ' 'This should have been initialized if this function was configured as the dialog code hook'.format(date)) return close( output_session_attributes, 'Fulfilled', { 'contentType': 'PlainText', 'content': 'Okay, I have booked your appointment. We will see you at {} on {}'.format(build_time_output_string(time), date) } )
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's intent handlers if intent_name == 'MakeAppointment': return make_appointment(intent_request) raise Exception('Intent with name ' + intent_name + ' not supported')
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, make a POST, PUT, or DELETE request respectively, passing in the payload to the DynamoDB API as a JSON body.
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 parameter. To put, update, or delete an item, make a POST, PUT, or DELETE request respectively, passing in the payload to the DynamoDB API as a JSON body. ''' print("Received event: " + json.dumps(event, indent=2)) operations = { 'DELETE': lambda dynamo, x: dynamo.delete_item(TableName=table_name, **x), 'GET': lambda dynamo, x: dynamo.scan(TableName=table_name, **x) if x else dynamo.scan(TableName=table_name), 'POST': lambda dynamo, x: dynamo.put_item(TableName=table_name, **x), 'PUT': lambda dynamo, x: dynamo.update_item(TableName=table_name, **x), } operation = event['httpMethod'] if operation in operations: payload = event['queryStringParameters'] if operation == 'GET' else json.loads(event['body']) return respond(None, operations[operation](dynamo, payload)) else: return respond(ValueError('Unsupported method "{}"'.format(operation)))
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 DELETE request respectively, passing in the payload to the DynamoDB API as a JSON body.
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 delete an item, make a POST, PUT, or DELETE request respectively, passing in the payload to the DynamoDB API as a JSON body. ''' #print("Received event: " + json.dumps(event, indent=2)) operations = { 'DELETE': lambda dynamo, x: dynamo.delete_item(**x), 'GET': lambda dynamo, x: dynamo.scan(**x), 'POST': lambda dynamo, x: dynamo.put_item(**x), 'PUT': lambda dynamo, x: dynamo.update_item(**x), } operation = event['httpMethod'] if operation in operations: payload = event['queryStringParameters'] if operation == 'GET' else json.loads(event['body']) return respond(None, operations[operation](dynamo, payload)) else: return respond(ValueError('Unsupported method "{}"'.format(operation)))
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 condition_name: base name desired for new condition :return: dictionary of condition_name: condition_value
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. :param list conditions_list: list of conditions :param string condition_name: base name desired for new condition :return: dictionary of condition_name: condition_value """ if len(conditions_list) < 2: # Can't make a condition if <2 conditions provided. return None # Total number of conditions allows in an Fn::Or statement. See docs: # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-conditions.html#intrinsic-function-reference-conditions-or max_conditions = 10 conditions = {} conditions_length = len(conditions_list) # Get number of conditions needed, then minus one to use them as 0-based indices zero_based_num_conditions = calculate_number_of_conditions(conditions_length, max_conditions) - 1 while len(conditions_list) > 1: new_condition_name = condition_name # If more than 1 new condition is needed, add a number to the end of the name if zero_based_num_conditions > 0: new_condition_name = '{}{}'.format(condition_name, zero_based_num_conditions) zero_based_num_conditions -= 1 new_condition_content = make_or_condition(conditions_list[:max_conditions]) conditions_list = conditions_list[max_conditions:] conditions_list.append(new_condition_name) conditions[new_condition_name] = new_condition_content return conditions
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 \ and isinstance(input, dict) \ and len(input) == 1: key = list(input.keys())[0] return key == "Ref" or key == "Condition" or key.startswith("Fn::") return False
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 """ return input_dict is not None \ and isinstance(input_dict, dict) \ and len(input_dict) == 1 \ and self.intrinsic_name in input_dict
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 input does not contain the structure, then both `logical_id` and property will be None
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 string, string: Returns two values - logical_id, property. If the input does not contain the structure, then both `logical_id` and property will be None """ no_result = (None, None) if not isinstance(ref_value, string_types): return no_result splits = ref_value.split(cls._resource_ref_separator, 1) # Either there is no 'dot' (or) one of the values is empty string (Ex: when you split "LogicalId.") if len(splits) != 2 or not all(splits): return no_result return splits[0], splits[1]
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"} :param parameters: Dictionary of parameter values for resolution :return:
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 contain only one key and it should be "Ref". Ex: {Ref: "foo"} :param parameters: Dictionary of parameter values for resolution :return: """ if not self.can_handle(input_dict): return input_dict param_name = input_dict[self.intrinsic_name] if not isinstance(param_name, string_types): return input_dict if param_name in parameters: return parameters[param_name] else: return input_dict
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"} => {"Ref": "SomeOtherLogicalId"} :param dict input_dict: Dictionary representing the Ref function to be resolved. :param samtranslator.intrinsics.resource_refs.SupportedResourceReferences supported_resource_refs: Instance of an `SupportedResourceReferences` object that contain value of the property. :return dict: Dictionary with resource references resolved.
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 executed via CloudFormation Example: {"Ref": "LogicalId.Property"} => {"Ref": "SomeOtherLogicalId"} :param dict input_dict: Dictionary representing the Ref function to be resolved. :param samtranslator.intrinsics.resource_refs.SupportedResourceReferences supported_resource_refs: Instance of an `SupportedResourceReferences` object that contain value of the property. :return dict: Dictionary with resource references resolved. """ if not self.can_handle(input_dict): return input_dict ref_value = input_dict[self.intrinsic_name] logical_id, property = self._parse_resource_reference(ref_value) # ref_value could not be parsed if not logical_id: return input_dict resolved_value = supported_resource_refs.get(logical_id, property) if not resolved_value: return input_dict return { self.intrinsic_name: resolved_value }
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 maps old logical ids to new ones. :return dict: Dictionary with resource references resolved.
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 the Ref function to be resolved. :param dict supported_resource_id_refs: Dictionary that maps old logical ids to new ones. :return dict: Dictionary with resource references resolved. """ if not self.can_handle(input_dict): return input_dict ref_value = input_dict[self.intrinsic_name] if not isinstance(ref_value, string_types) or self._resource_ref_separator in ref_value: return input_dict logical_id = ref_value resolved_value = supported_resource_id_refs.get(logical_id) if not resolved_value: return input_dict return { self.intrinsic_name: resolved_value }
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 :return: Resolved
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": ...} :param parameters: Dictionary of parameter values for substitution :return: Resolved """ def do_replacement(full_ref, prop_name): """ Replace parameter references with actual value. Return value of this method is directly replaces the reference structure :param full_ref: => ${logicalId.property} :param prop_name: => logicalId.property :return: Either the value it resolves to. If not the original reference """ return parameters.get(prop_name, full_ref) return self._handle_sub_action(input_dict, do_replacement)
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 that there can be only one property of resource referenced here. Everything else is an attribute reference. Example: Let's say `LogicalId.Property` will be resolved to `ResolvedValue` Ref usage: ${LogicalId.Property} => ${ResolvedValue} GetAtt usage: ${LogicalId.Property.Arn} => ${ResolvedValue.Arn} ${LogicalId.Property.Attr1.Attr2} => {ResolvedValue.Attr1.Attr2} :param input_dict: Dictionary to be resolved :param samtranslator.intrinsics.resource_refs.SupportedResourceReferences supported_resource_refs: Instance of an `SupportedResourceReferences` object that contain value of the property. :return: Resolved dictionary
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 converted to a Ref on the resolved value. GetAtt usages are split under the assumption that there can be only one property of resource referenced here. Everything else is an attribute reference. Example: Let's say `LogicalId.Property` will be resolved to `ResolvedValue` Ref usage: ${LogicalId.Property} => ${ResolvedValue} GetAtt usage: ${LogicalId.Property.Arn} => ${ResolvedValue.Arn} ${LogicalId.Property.Attr1.Attr2} => {ResolvedValue.Attr1.Attr2} :param input_dict: Dictionary to be resolved :param samtranslator.intrinsics.resource_refs.SupportedResourceReferences supported_resource_refs: Instance of an `SupportedResourceReferences` object that contain value of the property. :return: Resolved dictionary """ def do_replacement(full_ref, ref_value): """ Perform the appropriate replacement to handle ${LogicalId.Property} type references inside a Sub. This method is called to get the replacement string for each reference within Sub's value :param full_ref: Entire reference string such as "${LogicalId.Property}" :param ref_value: Just the value of the reference such as "LogicalId.Property" :return: Resolved reference of the structure "${SomeOtherLogicalId}". Result should always include the ${} structure since we are not resolving to final value, but just converting one reference to another """ # Split the value by separator, expecting to separate out LogicalId.Property splits = ref_value.split(self._resource_ref_separator) # If we don't find at least two parts, there is nothing to resolve if len(splits) < 2: return full_ref logical_id = splits[0] property = splits[1] resolved_value = supported_resource_refs.get(logical_id, property) if not resolved_value: # This ID/property combination is not in the supported references return full_ref # We found a LogicalId.Property combination that can be resolved. Construct the output by replacing # the part of the reference string and not constructing a new ref. This allows us to support GetAtt-like # syntax and retain other attributes. Ex: ${LogicalId.Property.Arn} => ${SomeOtherLogicalId.Arn} replacement = self._resource_ref_separator.join([logical_id, property]) return full_ref.replace(replacement, resolved_value) return self._handle_sub_action(input_dict, do_replacement)
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 that there can be only one property of resource referenced here. Everything else is an attribute reference. Example: Let's say `LogicalId` will be resolved to `NewLogicalId` Ref usage: ${LogicalId} => ${NewLogicalId} GetAtt usage: ${LogicalId.Arn} => ${NewLogicalId.Arn} ${LogicalId.Attr1.Attr2} => {NewLogicalId.Attr1.Attr2} :param input_dict: Dictionary to be resolved :param dict supported_resource_id_refs: Dictionary that maps old logical ids to new ones. :return: Resolved dictionary
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 directly converted to a Ref on the resolved value. GetAtt usages are split under the assumption that there can be only one property of resource referenced here. Everything else is an attribute reference. Example: Let's say `LogicalId` will be resolved to `NewLogicalId` Ref usage: ${LogicalId} => ${NewLogicalId} GetAtt usage: ${LogicalId.Arn} => ${NewLogicalId.Arn} ${LogicalId.Attr1.Attr2} => {NewLogicalId.Attr1.Attr2} :param input_dict: Dictionary to be resolved :param dict supported_resource_id_refs: Dictionary that maps old logical ids to new ones. :return: Resolved dictionary """ def do_replacement(full_ref, ref_value): """ Perform the appropriate replacement to handle ${LogicalId} type references inside a Sub. This method is called to get the replacement string for each reference within Sub's value :param full_ref: Entire reference string such as "${LogicalId.Property}" :param ref_value: Just the value of the reference such as "LogicalId.Property" :return: Resolved reference of the structure "${SomeOtherLogicalId}". Result should always include the ${} structure since we are not resolving to final value, but just converting one reference to another """ # Split the value by separator, expecting to separate out LogicalId splits = ref_value.split(self._resource_ref_separator) # If we don't find at least one part, there is nothing to resolve if len(splits) < 1: return full_ref logical_id = splits[0] resolved_value = supported_resource_id_refs.get(logical_id) if not resolved_value: # This ID/property combination is not in the supported references return full_ref # We found a LogicalId.Property combination that can be resolved. Construct the output by replacing # the part of the reference string and not constructing a new ref. This allows us to support GetAtt-like # syntax and retain other attributes. Ex: ${LogicalId.Property.Arn} => ${SomeOtherLogicalId.Arn} return full_ref.replace(logical_id, resolved_value) return self._handle_sub_action(input_dict, do_replacement)
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 specifics on these objects. :param handler: handler that is specific to each implementation. :return: Resolved value of the Sub dictionary
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 values that need to be changed. See each method above for specifics on these objects. :param handler: handler that is specific to each implementation. :return: Resolved value of the Sub dictionary """ if not self.can_handle(input_dict): return input_dict key = self.intrinsic_name sub_value = input_dict[key] input_dict[key] = self._handle_sub_value(sub_value, handler) return input_dict
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. Implementation could resolve and replace this structure with whatever they seem fit :return: Resolved value of the Sub dictionary
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 on every occurrence of `${LogicalId}` structure within the string. Implementation could resolve and replace this structure with whatever they seem fit :return: Resolved value of the Sub dictionary """ # Just handle known references within the string to be substituted and return the whole dictionary # because that's the best we can do here. if isinstance(sub_value, string_types): # Ex: {Fn::Sub: "some string"} sub_value = self._sub_all_refs(sub_value, handler_method) elif isinstance(sub_value, list) and len(sub_value) > 0 and isinstance(sub_value[0], string_types): # Ex: {Fn::Sub: ["some string", {a:b}] } sub_value[0] = self._sub_all_refs(sub_value[0], handler_method) return sub_value
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, ref_value): return "foo" _sub_all_refs(text, handler_method) will output "foo-hello-foo" :param string text: Input text :param handler_method: Method to be called to handle each occurrence of ${blah} reference structure. First parameter to this method is the full reference structure Ex: ${LogicalId.Property}. Second parameter is just the value of the reference such as "LogicalId.Property" :return string: Text with all reference structures replaced as necessary
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 = "${key1}-hello-${key2} def handler_method(full_ref, ref_value): return "foo" _sub_all_refs(text, handler_method) will output "foo-hello-foo" :param string text: Input text :param handler_method: Method to be called to handle each occurrence of ${blah} reference structure. First parameter to this method is the full reference structure Ex: ${LogicalId.Property}. Second parameter is just the value of the reference such as "LogicalId.Property" :return string: Text with all reference structures replaced as necessary """ # RegExp to find pattern "${logicalId.property}" and return the word inside bracket logical_id_regex = '[A-Za-z0-9\.]+|AWS::[A-Z][A-Za-z]*' ref_pattern = re.compile(r'\$\{(' + logical_id_regex + ')\}') # Find all the pattern, and call the handler to decide how to substitute them. # Do the substitution and return the final text return re.sub(ref_pattern, # Pass the handler entire string ${logicalId.property} as first parameter and "logicalId.property" # as second parameter. Return value will be substituted lambda match: handler_method(match.group(0), match.group(1)), 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 attribute (like Arn) of the resource. However tools like AWS CLI apply the assumption that first element of the array is a LogicalId and cannot contain a 'dot'. So they break at the first dot to convert YAML tag to JSON map like this: `!GetAtt LogicalId.Property.Arn` => {"Fn::GetAtt": [ "LogicalId", "Property.Arn" ] } Therefore to resolve the reference, we join the array into a string, break it back up to check if it contains a known reference, and resolve it if we can. :param input_dict: Dictionary to be resolved :param samtransaltor.intrinsics.resource_refs.SupportedResourceReferences supported_resource_refs: Instance of an `SupportedResourceReferences` object that contain value of the property. :return: Resolved dictionary
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 the array can contain reference to SAM resources. The second element is name of an attribute (like Arn) of the resource. However tools like AWS CLI apply the assumption that first element of the array is a LogicalId and cannot contain a 'dot'. So they break at the first dot to convert YAML tag to JSON map like this: `!GetAtt LogicalId.Property.Arn` => {"Fn::GetAtt": [ "LogicalId", "Property.Arn" ] } Therefore to resolve the reference, we join the array into a string, break it back up to check if it contains a known reference, and resolve it if we can. :param input_dict: Dictionary to be resolved :param samtransaltor.intrinsics.resource_refs.SupportedResourceReferences supported_resource_refs: Instance of an `SupportedResourceReferences` object that contain value of the property. :return: Resolved dictionary """ if not self.can_handle(input_dict): return input_dict key = self.intrinsic_name value = input_dict[key] # Value must be an array with *at least* two elements. If not, this is invalid GetAtt syntax. We just pass along # the input to CFN for it to do the "official" validation. if not isinstance(value, list) or len(value) < 2: return input_dict if (not all(isinstance(entry, string_types) for entry in value)): raise InvalidDocumentException( [InvalidTemplateException('Invalid GetAtt value {}. GetAtt expects an array with 2 strings.' .format(value))]) # Value of GetAtt is an array. It can contain any number of elements, with first being the LogicalId of # resource and rest being the attributes. In a SAM template, a reference to a resource can be used in the # first parameter. However tools like AWS CLI might break them down as well. So let's just concatenate # all elements, and break them into separate parts in a more standard way. # # Example: # { Fn::GetAtt: ["LogicalId.Property", "Arn"] } is equivalent to { Fn::GetAtt: ["LogicalId", "Property.Arn"] } # Former is the correct notation. However tools like AWS CLI can construct the later style. # Let's normalize the value into "LogicalId.Property.Arn" to handle both scenarios value_str = self._resource_ref_separator.join(value) splits = value_str.split(self._resource_ref_separator) logical_id = splits[0] property = splits[1] remaining = splits[2:] # if any resolved_value = supported_resource_refs.get(logical_id, property) return self._get_resolved_dictionary(input_dict, key, resolved_value, remaining)
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 attribute (like Arn) of the resource. However tools like AWS CLI apply the assumption that first element of the array is a LogicalId and cannot contain a 'dot'. So they break at the first dot to convert YAML tag to JSON map like this: `!GetAtt LogicalId.Arn` => {"Fn::GetAtt": [ "LogicalId", "Arn" ] } Therefore to resolve the reference, we join the array into a string, break it back up to check if it contains a known reference, and resolve it if we can. :param input_dict: Dictionary to be resolved :param dict supported_resource_id_refs: Dictionary that maps old logical ids to new ones. :return: Resolved dictionary
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 array can contain reference to SAM resources. The second element is name of an attribute (like Arn) of the resource. However tools like AWS CLI apply the assumption that first element of the array is a LogicalId and cannot contain a 'dot'. So they break at the first dot to convert YAML tag to JSON map like this: `!GetAtt LogicalId.Arn` => {"Fn::GetAtt": [ "LogicalId", "Arn" ] } Therefore to resolve the reference, we join the array into a string, break it back up to check if it contains a known reference, and resolve it if we can. :param input_dict: Dictionary to be resolved :param dict supported_resource_id_refs: Dictionary that maps old logical ids to new ones. :return: Resolved dictionary """ if not self.can_handle(input_dict): return input_dict key = self.intrinsic_name value = input_dict[key] # Value must be an array with *at least* two elements. If not, this is invalid GetAtt syntax. We just pass along # the input to CFN for it to do the "official" validation. if not isinstance(value, list) or len(value) < 2: return input_dict value_str = self._resource_ref_separator.join(value) splits = value_str.split(self._resource_ref_separator) logical_id = splits[0] remaining = splits[1:] # if any resolved_value = supported_resource_id_refs.get(logical_id) return self._get_resolved_dictionary(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 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 action. :param remaining: Remaining sections for the GetAtt action. """ if resolved_value: # We resolved to a new resource logicalId. Use this as the first element and keep remaining elements intact # This is the new value of Fn::GetAtt input_dict[key] = [resolved_value] + remaining return input_dict
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 should be "Fn::FindInMap". :param parameters: Dictionary of mappings from the SAM template
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 FindInMap function. Must contain only one key and it should be "Fn::FindInMap". :param parameters: Dictionary of mappings from the SAM template """ if not self.can_handle(input_dict): return input_dict value = input_dict[self.intrinsic_name] # FindInMap expects an array with 3 values if not isinstance(value, list) or len(value) != 3: raise InvalidDocumentException( [InvalidTemplateException('Invalid FindInMap value {}. FindInMap expects an array with 3 values.' .format(value))]) map_name = self.resolve_parameter_refs(value[0], parameters) top_level_key = self.resolve_parameter_refs(value[1], parameters) second_level_key = self.resolve_parameter_refs(value[2], parameters) if not isinstance(map_name, string_types) or \ not isinstance(top_level_key, string_types) or \ not isinstance(second_level_key, string_types): return input_dict if map_name not in parameters or \ top_level_key not in parameters[map_name] or \ second_level_key not in parameters[map_name][top_level_key]: return input_dict return parameters[map_name][top_level_key][second_level_key]
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['owner'] region = context.invoked_function_arn.split(':', 4)[3] log_events = event['logEvents'] for log_event in log_events: message = json.loads(log_event['message']) ts = log_event['timestamp'] / 1000 _process_rds_enhanced_monitoring_message(ts, message, account, region) stats.flush() return {'Status': 'OK'}
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.resource_attributes) rest_api.BinaryMediaTypes = self.binary_media rest_api.MinimumCompressionSize = self.minimum_compression_size if self.endpoint_configuration: self._set_endpoint_configuration(rest_api, self.endpoint_configuration) elif not RegionConfiguration.is_apigw_edge_configuration_supported(): # Since this region does not support EDGE configuration, we explicitly set the endpoint type # to Regional which is the only supported config. self._set_endpoint_configuration(rest_api, "REGIONAL") if self.definition_uri and self.definition_body: raise InvalidResourceException(self.logical_id, "Specify either 'DefinitionUri' or 'DefinitionBody' property and not both") self._add_cors() self._add_auth() self._add_gateway_responses() if self.definition_uri: rest_api.BodyS3Location = self._construct_body_s3_dict() elif self.definition_body: rest_api.Body = self.definition_body if self.name: rest_api.Name = self.name return rest_api
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.definition_uri, dict): if not self.definition_uri.get("Bucket", None) or not self.definition_uri.get("Key", None): # DefinitionUri is a dictionary but does not contain Bucket or Key property raise InvalidResourceException(self.logical_id, "'DefinitionUri' requires Bucket and Key properties to be specified") s3_pointer = self.definition_uri else: # DefinitionUri is a string s3_pointer = parse_s3_uri(self.definition_uri) if s3_pointer is None: raise InvalidResourceException(self.logical_id, '\'DefinitionUri\' is not a valid S3 Uri of the form ' '"s3://bucket/key" with optional versionId query parameter.') body_s3 = { 'Bucket': s3_pointer['Bucket'], 'Key': s3_pointer['Key'] } if 'Version' in s3_pointer: body_s3['Version'] = s3_pointer['Version'] return body_s3
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 """ deployment = ApiGatewayDeployment(self.logical_id + 'Deployment', attributes=self.passthrough_resource_attributes) deployment.RestApiId = rest_api.get_runtime_attr('rest_api_id') deployment.StageName = 'Stage' return deployment
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 """ # If StageName is some intrinsic function, then don't prefix the Stage's logical ID # This will NOT create duplicates because we allow only ONE stage per API resource stage_name_prefix = self.stage_name if isinstance(self.stage_name, string_types) else "" stage = ApiGatewayStage(self.logical_id + stage_name_prefix + 'Stage', attributes=self.passthrough_resource_attributes) stage.RestApiId = ref(self.logical_id) stage.update_deployment_ref(deployment.logical_id) stage.StageName = self.stage_name stage.CacheClusterEnabled = self.cache_cluster_enabled stage.CacheClusterSize = self.cache_cluster_size stage.Variables = self.variables stage.MethodSettings = self.method_settings stage.AccessLogSetting = self.access_log_setting stage.CanarySetting = self.canary_setting stage.TracingEnabled = self.tracing_enabled if swagger is not None: deployment.make_auto_deployable(stage, swagger) return stage
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(rest_api) swagger = None if rest_api.Body is not None: swagger = rest_api.Body elif rest_api.BodyS3Location is not None: swagger = rest_api.BodyS3Location stage = self._construct_stage(deployment, swagger) permissions = self._construct_authorizer_lambda_permission() return rest_api, deployment, stage, permissions
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.logical_id, "Cors works only with inline Swagger specified in " "'DefinitionBody' property") if isinstance(self.cors, string_types) or is_instrinsic(self.cors): # Just set Origin property. Others will be defaults properties = CorsProperties(AllowOrigin=self.cors) elif isinstance(self.cors, dict): # Make sure keys in the dict are recognized if not all(key in CorsProperties._fields for key in self.cors.keys()): raise InvalidResourceException(self.logical_id, INVALID_ERROR) properties = CorsProperties(**self.cors) else: raise InvalidResourceException(self.logical_id, INVALID_ERROR) if not SwaggerEditor.is_valid(self.definition_body): raise InvalidResourceException(self.logical_id, "Unable to add Cors configuration because " "'DefinitionBody' does not contain a valid Swagger") if properties.AllowCredentials is True and properties.AllowOrigin == _CORS_WILDCARD: raise InvalidResourceException(self.logical_id, "Unable to add Cors configuration because " "'AllowCredentials' can not be true when " "'AllowOrigin' is \"'*'\" or not set") editor = SwaggerEditor(self.definition_body) for path in editor.iter_on_path(): editor.add_cors(path, properties.AllowOrigin, properties.AllowHeaders, properties.AllowMethods, max_age=properties.MaxAge, allow_credentials=properties.AllowCredentials) # Assign the Swagger back to template self.definition_body = editor.swagger
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 works only with inline Swagger specified in " "'DefinitionBody' property") # Make sure keys in the dict are recognized if not all(key in AuthProperties._fields for key in self.auth.keys()): raise InvalidResourceException( self.logical_id, "Invalid value for 'Auth' property") if not SwaggerEditor.is_valid(self.definition_body): raise InvalidResourceException(self.logical_id, "Unable to add Auth configuration because " "'DefinitionBody' does not contain a valid Swagger") swagger_editor = SwaggerEditor(self.definition_body) auth_properties = AuthProperties(**self.auth) authorizers = self._get_authorizers(auth_properties.Authorizers, auth_properties.DefaultAuthorizer) if authorizers: swagger_editor.add_authorizers(authorizers) self._set_default_authorizer(swagger_editor, authorizers, auth_properties.DefaultAuthorizer) # Assign the Swagger back to template self.definition_body = swagger_editor.swagger
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( self.logical_id, "GatewayResponses works only with inline Swagger specified in " "'DefinitionBody' property") # Make sure keys in the dict are recognized for responses_key, responses_value in self.gateway_responses.items(): for response_key in responses_value.keys(): if response_key not in GatewayResponseProperties: raise InvalidResourceException( self.logical_id, "Invalid property '{}' in 'GatewayResponses' property '{}'".format(response_key, responses_key)) if not SwaggerEditor.is_valid(self.definition_body): raise InvalidResourceException( self.logical_id, "Unable to add Auth configuration because " "'DefinitionBody' does not contain a valid Swagger") swagger_editor = SwaggerEditor(self.definition_body) gateway_responses = {} for response_type, response in self.gateway_responses.items(): gateway_responses[response_type] = ApiGatewayResponse( api_logical_id=self.logical_id, response_parameters=response.get('ResponseParameters', {}), response_templates=response.get('ResponseTemplates', {}), status_code=response.get('StatusCode', None) ) if gateway_responses: swagger_editor.add_gateway_responses(gateway_responses) # Assign the Swagger back to template self.definition_body = swagger_editor.swagger
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 = ApiGatewayRestApi(self.logical_id, depends_on=self.depends_on, attributes=self.resource_attributes) api_id = rest_api.get_runtime_attr('rest_api_id') partition = ArnGenerator.get_partition_name() resource = '${__ApiId__}/authorizers/*' source_arn = fnSub(ArnGenerator.generate_arn(partition=partition, service='execute-api', resource=resource), {"__ApiId__": api_id}) lambda_permission = LambdaPermission(self.logical_id + authorizer_name + 'AuthorizerPermission', attributes=self.passthrough_resource_attributes) lambda_permission.Action = 'lambda:invokeFunction' lambda_permission.FunctionName = authorizer_lambda_function_arn lambda_permission.Principal = 'apigateway.amazonaws.com' lambda_permission.SourceArn = source_arn return lambda_permission
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]} rest_api.Parameters = {"endpointConfigurationTypes": 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 Beware that any exception raised by task_to_try won't get surfaced until (2) or (3) is satisfied. At step n, it sleeps for [0, delay), where delay is defined as the following: `delay = min(max_delay, multiplier * (backoff_coefficient ** (n - 1))) * time_unit` seconds Additionally, if you enable jitter, for each retry, the function will instead sleep for: random.random() * sleep, that is [0, sleep) seconds. :param time_unit: This field represents a fraction of a second, which is used as a multiplier to compute the amount of time to sleep. :type time_unit: float :param multiplier: The initial wait duration for the first retry. :type multiplier: float :param backoff_coefficient: the base value for exponential retry. :type backoff_coefficient: float :param max_delay: The maximum amount of time to wait per try. :type max_delay: float :param max_attempts: This method will retry up to this value. :type max_attempts: int :param expiration_duration: the maximum amount of time retry can wait. :type expiration_duration: float :param enable_jitter: Setting this to true will add jitter. :type enable_jitter: bool
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 retrying one more time will cause total wait time to go above: `expiration_duration`, then retry() raises an exception Beware that any exception raised by task_to_try won't get surfaced until (2) or (3) is satisfied. At step n, it sleeps for [0, delay), where delay is defined as the following: `delay = min(max_delay, multiplier * (backoff_coefficient ** (n - 1))) * time_unit` seconds Additionally, if you enable jitter, for each retry, the function will instead sleep for: random.random() * sleep, that is [0, sleep) seconds. :param time_unit: This field represents a fraction of a second, which is used as a multiplier to compute the amount of time to sleep. :type time_unit: float :param multiplier: The initial wait duration for the first retry. :type multiplier: float :param backoff_coefficient: the base value for exponential retry. :type backoff_coefficient: float :param max_delay: The maximum amount of time to wait per try. :type max_delay: float :param max_attempts: This method will retry up to this value. :type max_attempts: int :param expiration_duration: the maximum amount of time retry can wait. :type expiration_duration: float :param enable_jitter: Setting this to true will add jitter. :type enable_jitter: bool """ def deco_retry(task_to_try): @wraps(task_to_try) def retry_impl(*args, **kwargs): total_wait_time = 0 have_tried = 0 retry_errors = [] while have_tried < max_attempts: try: task_to_try(*args, **kwargs) return except Exception as e: retry_errors.append(e) going_to_sleep_for = min(max_delay, multiplier * (backoff_coefficient ** have_tried)) if enable_jitter: going_to_sleep_for = random.random() * going_to_sleep_for duration = going_to_sleep_for * time_unit if total_wait_time + duration > expiration_duration: raise RetryTimeoutException(task_to_try.__name__, have_tried, max_attempts, total_wait_time, multiplier, backoff_coefficient, enable_jitter, retry_errors) runtime_logger.warn('Retrying [{0}], going to sleep for {1} seconds, exception stacktrace:\n{2}' .format(task_to_try.__name__, duration, traceback.format_exc())) time.sleep(duration) total_wait_time += duration have_tried += 1 raise RetryTimeoutException(task_to_try.__name__, have_tried, max_attempts, total_wait_time, multiplier, backoff_coefficient, enable_jitter, retry_errors) return retry_impl return deco_retry
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 Function expands :rtype: list
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 vanilla CloudFormation Resources, to which this Function expands :rtype: list """ resources = [] intrinsics_resolver = kwargs["intrinsics_resolver"] if self.DeadLetterQueue: self._validate_dlq() lambda_function = self._construct_lambda_function() resources.append(lambda_function) lambda_alias = None if self.AutoPublishAlias: alias_name = self._get_resolved_alias_name("AutoPublishAlias", self.AutoPublishAlias, intrinsics_resolver) lambda_version = self._construct_version(lambda_function, intrinsics_resolver=intrinsics_resolver) lambda_alias = self._construct_alias(alias_name, lambda_function, lambda_version) resources.append(lambda_version) resources.append(lambda_alias) if self.DeploymentPreference: self._validate_deployment_preference_and_add_update_policy(kwargs.get('deployment_preference_collection', None), lambda_alias, intrinsics_resolver) managed_policy_map = kwargs.get('managed_policy_map', {}) if not managed_policy_map: raise Exception('Managed policy map is empty, but should not be.') execution_role = None if lambda_function.Role is None: execution_role = self._construct_role(managed_policy_map) lambda_function.Role = execution_role.get_runtime_attr('arn') resources.append(execution_role) try: resources += self._generate_event_resources(lambda_function, execution_role, kwargs['event_resources'], lambda_alias=lambda_alias) except InvalidEventException as e: raise InvalidResourceException(self.logical_id, e.message) return resources
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 :param dict or string original_alias_value: Value of Alias property as provided by the customer :param samtranslator.intrinsics.resolver.IntrinsicsResolver intrinsics_resolver: Instance of the resolver that knows how to resolve parameter references :return string: Alias name :raises InvalidResourceException: If the value is a complex intrinsic function that cannot be resolved
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 was used), then this method raises an exception. If alias name is just a plain string, it will return as is :param dict or string original_alias_value: Value of Alias property as provided by the customer :param samtranslator.intrinsics.resolver.IntrinsicsResolver intrinsics_resolver: Instance of the resolver that knows how to resolve parameter references :return string: Alias name :raises InvalidResourceException: If the value is a complex intrinsic function that cannot be resolved """ # Try to resolve. resolved_alias_name = intrinsics_resolver.resolve_parameter_refs(original_alias_value) if not isinstance(resolved_alias_name, string_types): # This is still a dictionary which means we are not able to completely resolve intrinsics raise InvalidResourceException(self.logical_id, "'{}' must be a string or a Ref to a template parameter" .format(property_name)) return resolved_alias_name
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, attributes=self.resource_attributes) if self.FunctionName: lambda_function.FunctionName = self.FunctionName lambda_function.Handler = self.Handler lambda_function.Runtime = self.Runtime lambda_function.Description = self.Description lambda_function.MemorySize = self.MemorySize lambda_function.Timeout = self.Timeout lambda_function.VpcConfig = self.VpcConfig lambda_function.Role = self.Role lambda_function.Environment = self.Environment lambda_function.Code = self._construct_code_dict() lambda_function.KmsKeyArn = self.KmsKeyArn lambda_function.ReservedConcurrentExecutions = self.ReservedConcurrentExecutions lambda_function.Tags = self._construct_tag_list(self.Tags) lambda_function.Layers = self.Layers if self.Tracing: lambda_function.TracingConfig = {"Mode": self.Tracing} if self.DeadLetterQueue: lambda_function.DeadLetterConfig = {"TargetArn": self.DeadLetterQueue['TargetArn']} return lambda_function
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_resource_attributes()) execution_role.AssumeRolePolicyDocument = IAMRolePolicies.lambda_assume_role_policy() managed_policy_arns = [ArnGenerator.generate_aws_managed_policy_arn('service-role/AWSLambdaBasicExecutionRole')] if self.Tracing: managed_policy_arns.append(ArnGenerator.generate_aws_managed_policy_arn('AWSXrayWriteOnlyAccess')) function_policies = FunctionPolicies({"Policies": self.Policies}, # No support for policy templates in the "core" policy_template_processor=None) policy_documents = [] if self.DeadLetterQueue: policy_documents.append(IAMRolePolicies.dead_letter_queue_policy( self.dead_letter_queue_policy_actions[self.DeadLetterQueue['Type']], self.DeadLetterQueue['TargetArn'])) for index, policy_entry in enumerate(function_policies.get()): if policy_entry.type is PolicyTypes.POLICY_STATEMENT: policy_documents.append({ 'PolicyName': execution_role.logical_id + 'Policy' + str(index), 'PolicyDocument': policy_entry.data }) elif policy_entry.type is PolicyTypes.MANAGED_POLICY: # There are three options: # Managed Policy Name (string): Try to convert to Managed Policy ARN # Managed Policy Arn (string): Insert it directly into the list # Intrinsic Function (dict): Insert it directly into the list # # When you insert into managed_policy_arns list, de-dupe to prevent same ARN from showing up twice # policy_arn = policy_entry.data if isinstance(policy_entry.data, string_types) and policy_entry.data in managed_policy_map: policy_arn = managed_policy_map[policy_entry.data] # De-Duplicate managed policy arns before inserting. Mainly useful # when customer specifies a managed policy which is already inserted # by SAM, such as AWSLambdaBasicExecutionRole if policy_arn not in managed_policy_arns: managed_policy_arns.append(policy_arn) else: # Policy Templates are not supported here in the "core" raise InvalidResourceException( self.logical_id, "Policy at index {} in the 'Policies' property is not valid".format(index)) execution_role.ManagedPolicyArns = list(managed_policy_arns) execution_role.Policies = policy_documents or None execution_role.PermissionsBoundary = self.PermissionsBoundary return execution_role
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') or not self.DeadLetterQueue.get('TargetArn'): raise InvalidResourceException(self.logical_id, "'DeadLetterQueue' requires Type and TargetArn properties to be specified" .format(valid_dlq_types)) # Validate required Types if not self.DeadLetterQueue['Type'] in self.dead_letter_queue_policy_actions: raise InvalidResourceException(self.logical_id, "'DeadLetterQueue' requires Type of {}".format(valid_dlq_types))
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 get attached to, if necessary :param implicit_api_stage: Global implicit API stage resource where implicit APIs get attached to, if necessary :param event_resources: All the event sources associated with this Lambda function :param model.lambda_.LambdaAlias lambda_alias: Optional Lambda Alias resource if we want to connect the event sources to this alias :returns: a list containing the function's event resources :rtype: list
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_role: generated Lambda execution role :param implicit_api: Global Implicit API resource where the implicit APIs get attached to, if necessary :param implicit_api_stage: Global implicit API stage resource where implicit APIs get attached to, if necessary :param event_resources: All the event sources associated with this Lambda function :param model.lambda_.LambdaAlias lambda_alias: Optional Lambda Alias resource if we want to connect the event sources to this alias :returns: a list containing the function's event resources :rtype: list """ resources = [] if self.Events: for logical_id, event_dict in self.Events.items(): try: eventsource = self.event_resolver.resolve_resource_type(event_dict).from_dict( lambda_function.logical_id + logical_id, event_dict, logical_id) except TypeError as e: raise InvalidEventException(logical_id, "{}".format(e)) kwargs = { # When Alias is provided, connect all event sources to the alias and *not* the function 'function': lambda_alias or lambda_function, 'role': execution_role, } for name, resource in event_resources[logical_id].items(): kwargs[name] = resource resources += eventsource.to_cloudformation(**kwargs) return resources
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 :param model.intrinsics.resolver.IntrinsicsResolver intrinsics_resolver: Class that can help resolve references to parameters present in CodeUri. It is a common usecase to set S3Key of Code to be a template parameter. Need to resolve the values otherwise we will never detect a change in Code dict :return: Lambda function Version resource
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_.LambdaFunction function: Lambda function object that is being connected to a version :param model.intrinsics.resolver.IntrinsicsResolver intrinsics_resolver: Class that can help resolve references to parameters present in CodeUri. It is a common usecase to set S3Key of Code to be a template parameter. Need to resolve the values otherwise we will never detect a change in Code dict :return: Lambda function Version resource """ code_dict = function.Code if not code_dict: raise ValueError("Lambda function code must be a valid non-empty dictionary") if not intrinsics_resolver: raise ValueError("intrinsics_resolver is required for versions creation") # Resolve references to template parameters before creating hash. This will *not* resolve all intrinsics # because we cannot resolve runtime values like Arn of a resource. For purposes of detecting changes, this # is good enough. Here is why: # # When using intrinsic functions there are two cases when has must change: # - Value of the template parameter changes # - (or) LogicalId of a referenced resource changes ie. !GetAtt NewResource.Arn # # Later case will already change the hash because some value in the Code dictionary changes. We handle the # first case by resolving references to template parameters. It is okay even if these references are # present inside another intrinsic such as !Join. The resolver will replace the reference with the parameter's # value and keep all other parts of !Join identical. This will still trigger a change in the hash. code_dict = intrinsics_resolver.resolve_parameter_refs(code_dict) # Construct the LogicalID of Lambda version by appending 10 characters of SHA of CodeUri. This is necessary # to trigger creation of a new version every time code location changes. Since logicalId changes, CloudFormation # will drop the old version and create a new one for us. We set a DeletionPolicy on the version resource to # prevent CloudFormation from actually deleting the underlying version resource # # SHA Collisions: For purposes of triggering a new update, we are concerned about just the difference previous # and next hashes. The chances that two subsequent hashes collide is fairly low. prefix = "{id}Version".format(id=self.logical_id) logical_id = logical_id_generator.LogicalIdGenerator(prefix, code_dict).gen() attributes = self.get_passthrough_resource_attributes() if attributes is None: attributes = {} attributes["DeletionPolicy"] = "Retain" lambda_version = LambdaVersion(logical_id=logical_id, attributes=attributes) lambda_version.FunctionName = function.get_runtime_attr('name') lambda_version.Description = self.VersionDescription return lambda_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.lambda_.LambdaVersion version: Lambda version object to associate the alias with :return: Lambda alias object :rtype model.lambda_.LambdaAlias
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.lambda_.LambdaVersion version: Lambda version object to associate the alias with :return: Lambda alias object :rtype model.lambda_.LambdaAlias """ if not name: raise InvalidResourceException(self.logical_id, "Alias name is required to create an alias") logical_id = "{id}Alias{suffix}".format(id=function.logical_id, suffix=name) alias = LambdaAlias(logical_id=logical_id, attributes=self.get_passthrough_resource_attributes()) alias.Name = name alias.FunctionName = function.get_runtime_attr('name') alias.FunctionVersion = version.get_runtime_attr("version") return alias
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 expands :rtype: list
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 vanilla CloudFormation Resources, to which this Function expands :rtype: list """ resources = [] api_generator = ApiGenerator(self.logical_id, self.CacheClusterEnabled, self.CacheClusterSize, self.Variables, self.depends_on, self.DefinitionBody, self.DefinitionUri, self.Name, self.StageName, endpoint_configuration=self.EndpointConfiguration, method_settings=self.MethodSettings, binary_media=self.BinaryMediaTypes, minimum_compression_size=self.MinimumCompressionSize, cors=self.Cors, auth=self.Auth, gateway_responses=self.GatewayResponses, access_log_setting=self.AccessLogSetting, canary_setting=self.CanarySetting, tracing_enabled=self.TracingEnabled, resource_attributes=self.resource_attributes, passthrough_resource_attributes=self.get_passthrough_resource_attributes()) rest_api, deployment, stage, permissions = api_generator.to_cloudformation() resources.extend([rest_api, deployment, stage]) resources.extend(permissions) return resources
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.Parameters nested_stack.NotificationArns = self.NotificationArns application_tags = self._get_application_tags() nested_stack.Tags = self._construct_tag_list(self.Tags, application_tags) nested_stack.TimeoutInMinutes = self.TimeoutInMinutes nested_stack.TemplateURL = self.TemplateUrl if self.TemplateUrl else "" return nested_stack