Skip to content

Instantly share code, notes, and snippets.

@smoser
Created June 12, 2020 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smoser/280dbed3e9582c53c6035525f35814aa to your computer and use it in GitHub Desktop.
Save smoser/280dbed3e9582c53c6035525f35814aa to your computer and use it in GitHub Desktop.
demo of yaml anchors and yaml-dump script.

yaml anchors demo

yaml anchors are:

  • useful
  • confusing
  • hard to google for

yaml can be quite hard to read and see if it is valid.

I use 'yaml-dump' script here to just load a file and dump it as json to more easily see what it loads as.

example

yaml-dump outputs a copy of itself... so that if you paste its output to someone they can see what you did.

user@host$ yaml-dump my.yaml
$ python3 -c 'import json, sys, yaml; print(json.dumps(yaml.safe_load(open(sys.argv[1])), indent=1, sort_keys=True) + "\n")' /tmp/my.yaml
{
 "_myanchors_name_does_not_matter": [
  "this is the content of blob1\n"
 ],
 "key1": "this is the content of blob1\n"
}
_myanchors_name_does_not_matter:
- &blob1 |
this is the content of blob1
key1: *blob1
#!/usr/bin/python3
import sys
import yaml
import json
src = "-"
if len(sys.argv) > 1:
src = sys.argv[1]
fh = sys.stdin if src == "-" else open(src)
sys.stderr.write("$ python3 -c 'import json, sys, yaml; "
"print(json.dumps(yaml.safe_load(open(sys.argv[1])), "
"indent=1, sort_keys=True) + \"\\n\")' " + src + "\n")
print(json.dumps(yaml.safe_load(fh), indent=1, sort_keys=True) + "\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment