I have the following yaml snippet
I want to resolve the pointer to the anchor and also I don’t want to lose !flatten
and !ref
which are to be processed by another program.
Input:
_ip_context: &ip_context
ip_restriction: !flatten
- !ref 'constant::public_cidr_blocks'
policies:
- file: policies/somepolicy.json
context:
<<: *ip_context
Desired output:
policies:
- file: policies/somepolicy.json
context:
ip_restriction: !flatten
- !ref 'constant::public_cidr_blocks'
I tried this program which is produced by ChatGpt. But it didn’t get me what I wanted:
import sys
import yaml
yaml_content = """
_ip_context: &ip_context
ip_restriction: !flatten
- !ref 'constant::public_cidr_blocks'
policies:
- file: policies/somepolicy.json
context:
<<: *ip_context
"""
class FlattenConstructor(yaml.constructor.SafeConstructor):
def construct_flatten(self, node):
return self.construct_sequence(node)
class RefConstructor(yaml.constructor.SafeConstructor):
def construct_ref(self, node):
return self.construct_scalar(node)
yaml.add_constructor('!flatten', FlattenConstructor.construct_flatten, Loader=yaml.SafeLoader)
yaml.add_constructor('!ref', RefConstructor.construct_ref, Loader=yaml.SafeLoader)
data = yaml.load(yaml_content, Loader=yaml.SafeLoader)
class FlattenRepresenter(yaml.representer.SafeRepresenter):
def represent_flatten(self, data):
return self.represent_sequence('!flatten', data)
class RefRepresenter(yaml.representer.SafeRepresenter):
def represent_ref(self, data):
return self.represent_scalar('!ref', data)
yaml.add_representer(list, FlattenRepresenter.represent_flatten)
yaml.add_representer(str, RefRepresenter.represent_ref)
#with open('output.yaml', 'w') as outfile:
yaml.dump(data, sys.stdout, default_flow_style=False,Dumper=yaml.SafeDumper)
This is the output:
_ip_context:
ip_restriction: &id001
- constant::public_cidr_blocks
policies:
- context:
ip_restriction: *id001
file: policies/somepolicy.json
New contributor
Jeff Saremi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.