def load_cfn_template(template_str): """ Loads a template from a string, detecting the format as JSON or YAML automatically. Returns a normal OrderedDict. """ # cfn_flip.load() raises a JSONDecodeError even when the content was YAML (but invalid). # So do our own loading here. try: template_data = cfn_flip.load_json(template_str) template_type = 'json' except ValueError as json_err: try: template_data = cfn_flip.load_yaml(template_str) template_type = 'yaml' except Exception as yaml_err: raise ValueError( f'Could not read template as JSON or YAML:\n\t{str(json_err)}\n\t{str(yaml_err)}' ) # cfn_flip.load() can return a cfn_tools.odict.ODict, which is almost # immutable because of the way it always returns new lists from items(), but # doesn't error. Return a copy that's a regular mutable OrderedDict so we can # avoid unpleasant surprises later. return copy_dict(template_data, impl=OrderedDict), template_type
def _format_yaml(filename): with open(filename, "r", encoding="utf-8") as f: try: unformatted_yaml = load_yaml(f) except Exception as e: print("ERROR: Invalid yaml document: {error}".format(error=e)) exit(1) return dump_yaml(unformatted_yaml, clean_up=True)
def test_compare_templates__templates_are_yaml_with_intrinsic_functions__returns_deepdiff_of_dicts(self): template = """ Resources: MyBucket: Type: AWS::S3::Bucket Properties: BucketName: !Ref MyParam """ comparison = self.differ.compare_templates(template, template) expected = cfn_flip.load_yaml(template) assert (comparison.t1, comparison.t2) == (expected, expected)
exit(1) auth_map = get_region_map() filters = template['Metadata']['AutoInstance'][parameter].get( 'InstanceFilters', []) ordered_instances, region_support_map = get_instances( filters, auth_map) if param.get('AllowedValues') is not None: print("adding values") start = param['AllowedValues'].start_mark.index end = param['AllowedValues'].end_mark.index template = template_rewriter((start, end), json.dumps(ordered_instances), template) if template.get('Rules'): rules = load_yaml( template.start_mark.buffer[template['Rules'].start_mark.index - 2:template['Rules'].end_mark.index]) for region_name, instances in region_support_map.items(): rule_name = f"{parameter}{region_name.replace('-', '').capitalize()}Instances" rules[rule_name] = { "RuleCondition": { "Fn::Equals": [{ "Ref": "AWS::Region" }, region_name] }, "Assertions": [{ "Assert": { "Fn::Contains": [instances, { "Ref": str(parameter) }]
def load_template(self, name): with open(name) as f: template = cfn_flip.load_yaml(f) template['Transform'] = os.getenv('MACRO_NAME') return cfn_flip.dump_yaml(template)