https://www.tutorialspoint.com/yaml/index.htm
TOC
chapter |
---|
SCALAR |
COLLECTION |
COMMENT |
DOCUMENT |
REFERENCE |
DIRECTIVE |
PyYAML |
<br />
“YAML Ain’t Markup Language”
Le nom YAML veut dire “YAML Ain’t Markup Language”, soit “YAML n’est pas un langage de balises”. Si cela met d’emblée des distances avec XML, cela ne nous dit pas ce qu’est YAML. YAML est, d’après sa spécification, un langage de sérialisation de données conçu pour être lisible par des humains et travaillant bien avec les langage de programmation modernes pour les tâches de tous les jours
SCALAR
string
- Chaîne
- "3"
- Chaîne sur
une ligne
- "Guillemets doubles\t"
- 'Guillemets simples\t'
Le résultat de ce parsing nous amène aux commentaires suivants :
- Les caractères accentués sont gérés, en fait, l’Unicode est géré de manière plus générale
- Les retours à la ligne ne sont pas pris en compte dans les chaînes, ils sont gérés comme en HTML ou XML, à savoir qu’ils sont remplacés par des espaces
- Les guillemets doubles gèrent les caractères d’échappement, comme \t pour la tabulation par exemple
- Les guillemets simples ne gèrent pas les caractères d’échappement qui sont transcrits de manière littérale
- La liste des caractères d’échappement gérés par YAML comporte les valeurs classiques, mais aussi nombre d’autres que l’on pourra trouver dans la spécification YAML
UTF8 :
\xNN : pour écrire des caractères Unicode sur 8 bits, où NN est un nombre hexadécimal.
\uNNNN : pour des caractères Unicode sur 16 bits.
\UNNNNNNNN : pour des caractères Unicode sur 32 bits.
integer
canonique: 12345
decimal: +12_345
sexagesimal: 3:25:45
octal: 030071
hexadecimal: 0x3039
float
canonique: 1.23015e+3
exponentielle: 12.3015e+02
sexagesimal: 20:30.15
fixe: 1_230.15
infini negatif: -.inf
pas un nombre: .NaN
date
canonique: 2001-12-15T02:59:43.1Z
iso8601: 2001-12-14t21:59:43.10-05:00
espace: 2001-12-14 21:59:43.10 -5
date: 2002-12-14
others
nul: null
nul bis: ~
vrai: true
vrai bis: yes
vrai ter: on
faux: false
faux bis: no
faux ter: off
COLLECTION
List
- beans
- chocolat
- ham
[beans, chocolat, ham]
Associated Array
croissants: 2
chocolatines: 1
jambon: 0
{ croissants: 2, chocolatines: 1, jambon: 0}
COMMENT
# This is a comment
DOCUMENT
# this a first document stated by --- & ended by ...
---
first document
...
---
second document
...
REFERENCE
&ref : Defines the reference 'ref'
*ref : Link the reference 'ref'
# define the reference
monday: &p 'patatoes'
# uses the reference with pointeur
tuesday: *p
wednesday: *p
DIRECTIVE
Yaml
Give the version of YAML used
%YAML 1.1
---
Tag
Predefined Tag
tag is a data type
omap : is ordered map (list)
null: !!null
integer: !!int 3
float: !!float 1.2
string: !!str string
boolean: !!bool true
binary: !!binary dGVzdA==
map: !!map { key: value }
seq: !!seq [ element1, element2 ]
set: !!set { element1, element2 }
omap: !!omap [ key: value ]
Personnal Tag
Defines tag & use it
%TAG !person! tag:myfirst,2020:bar
---
- !person
nom: Simpson
prenom: Omer
PyYAML
http://sweetohm.net/article/introduction-yaml.html
Install yaml library like LibYaml
Read Yaml
Load file passed by argument & print the first document in file
#!/usr/bin/env python
# encoding: UTF-8
import sys
import yaml
print yaml.load(open(sys.argv[1]))
To load all documents (entire file) you can use the method 'yaml.load_all()'
for document in yaml.load_all(documents):
print document
Write Yaml
Uses method yaml.dump()
#!/usr/bin/env python
# encoding: UTF-8
import yaml
recette = {
'nom': 'sushi',
'ingredients': ['riz', 'vinaigre', 'sucre', 'sel', 'thon', 'saumon'],
'temps de cuisson': 10,
'difficulte': 'difficile'
}
print yaml.dump(recette)
Class Serialization
#!/usr/bin/env python
# encoding: UTF-8
import yaml
class Personne(object):
def __init__(self, nom, age):
self.nom = nom
self.age = age
def __repr__(self):
return "%s(nom=%r, age=%r)" % \
(self.__class__.__name__, self.nom, self.age)
print yaml.dump(Personne('Robert', 25), default_flow_style=False)
==>
!!python/object:__main__.Personne
age: 25
nom: Robert```
Class Unserialization
#!/usr/bin/env python
# encoding: UTF-8
import yaml
class Personne(object):
def __init__(self, nom, age):
self.nom = nom
self.age = age
def __repr__(self):
return "%s(nom=%r, age=%r)" % \
(self.__class__.__name__, self.nom, self.age)
print yaml.load("""
!!python/object:__main__.Personne
nom: Robert
age: 25
""")
==>
Personne(nom='Robert', age=25)
https://mikefarah.gitbook.io/yq/
yq is a lightweight and portable command-line YAML processor
It aims to be the jq or sed of yaml files
yq [flags]
yq [command]
SUBCOMMANDS
alias | subcommand | Designation |
---|---|---|
x | COMPARE | Deeply compares two yaml files |
d | DELETE | Deletes the nodes matching the given path expression from the YAML file |
h | HELP | Help provides help for any command in the application |
m | MERGE | Updates the yaml file by adding/updating the path(s) and value(s) from additional yaml file(s) |
n | NEW | Creates a new yaml w.r.t the given path and value |
p | PREFIX | Prefixes w.r.t to the yaml file at the given path |
r | READ | Outputs the value of the given path in the yaml file to STDOUT |
v | VALIDATE | test syntax of file |
w | WRITE | Updates the yaml file w.r.t the given path and value |
TRICKS |
Global options
-h, --help # help for yq
-C, --colors # print with colors
-I, --indent int # sets indent level for output (default 2)
-P, --prettyPrint # pretty print
-j, --tojson # output as json. By default it prints a json document in one line, use the prettyPrint flag to print a formatted doc.
-v, --verbose # verbose mode
-V, --version # Print version information and quit
COMPARE
Deeply compares two yaml files, prints the difference
Use with prettyPrint flag to ignore formatting differences
yq compare [yaml_file_a] [yaml_file_b] [flags]
-D, --defaultValue string # default value printed when there are no results
-d, --doc string # process document index number (0 based, * for all documents) (default "0")
-h, --help # help for compare
-p, --printMode string # print mode (v (values, default), p (paths), pv (path and value pairs) (default "v")
examples
yq x - data2.yml # reads from stdin
yq x -pp dataA.yaml dataB.yaml '**' # compare paths
yq x -d1 dataA.yaml dataB.yaml 'a.b.c'
DELETE
Deletes the nodes matching the given path expression from the YAML file
Outputs to STDOUT unless the inplace flag is used, in which case the file is updated instead
yq delete [yaml_file] [path_expression] [flags]
-d, --doc string # process document index number (0 based, * for all documents) (default "0")
-h, --help # help for delete
-i, --inplace # update the yaml file inplace
examples
yq delete things.yaml 'a.b.c'
yq delete things.yaml 'a.*.c'
yq delete things.yaml 'a.(child.subchild==co*).c'
yq delete things.yaml 'a.**'
yq delete --inplace things.yaml 'a.b.c'
yq delete --inplace -- things.yaml '--key-starting-with-dash' # need to use '--' to stop processing arguments as flags
yq d -i things.yaml 'a.b.c'
HELP
Help provides help for any command in the application
Simply type yq help [path to command] for full details
yq help [command] [flags]
-h, --help # help for help
MERGE
Updates the yaml file by adding/updating the path(s) and value(s) from additional yaml file(s)
Outputs to STDOUT unless the inplace flag is used, in which case the file is updated instead.
If overwrite flag is set then existing values will be overwritten using the values from each additional yaml file.
If append flag is set then existing arrays will be merged with the arrays from each additional yaml file.
yq merge [initial_yaml_file] [additional_yaml_file]... [flags]
-a, --append # update the yaml file by appending array values
-c, --autocreate # automatically create any missing entries (default true)
-d, --doc string # process document index number (0 based, * for all documents) (default "0")
-h, --help # help for merge
-i, --inplace # update the yaml file inplace
-x, --overwrite # update the yaml file by overwriting existing values
examples
yq merge things.yaml other.yaml
yq merge --inplace things.yaml other.yaml
yq m -i things.yaml other.yaml
yq m --overwrite things.yaml other.yaml
yq m -i -x things.yaml other.yaml
yq m -i -a things.yaml other.yaml
yq m -i --autocreate=false things.yaml other.yaml
NEW
Creates a new yaml w.r.t the given path and value
Outputs to STDOUT
Create Scripts:
Note that you can give a create script to perform more sophisticated yaml This follows the same format as the update script
yq new [path] [value] [flags]
-h, --help # help for new
-s, --script string # yaml script for creating yaml
-t, --tag string # set yaml tag (e.g. !!int)
examples
yq new 'a.b.c' cat
yq n 'a.b.c' --tag '!!str' true # force 'true' to be interpreted as a string instead of bool
yq n 'a.b[+]' cat
yq n -- '--key-starting-with-dash' cat # need to use '--' to stop processing arguments as flags
yq n --script create_script.yaml
PREFIX
Prefixes w.r.t to the yaml file at the given path
Outputs to STDOUT unless the inplace flag is used, in which case the file is updated instead
yq prefix [yaml_file] [path] [flags]
-d, --doc string # process document index number (0 based, * for all documents) (default "0")
-h, --help # help for prefix
-i, --inplace # update the yaml file inplace
examples
yq prefix things.yaml 'a.b.c'
yq prefix --inplace things.yaml 'a.b.c'
yq prefix --inplace -- things.yaml '--key-starting-with-dash' # need to use '--' to stop processing arguments as flags
yq p -i things.yaml 'a.b.c'
yq p --doc 2 things.yaml 'a.b.d'
yq p -d2 things.yaml 'a.b.d'
READ
Outputs the value of the given path in the yaml file to STDOUT
yq read [yaml_file] [path_expression] [flags]
-c, --collect # collect results into array
-D, --defaultValue string # default value printed when there are no results
-d, --doc string # process document index number (0 based, * for all documents) (default "0")
-X, --explodeAnchors # explode anchors
-h, --help # help for read
-l, --length # print length of results
-p, --printMode string # print mode (v (values, default), p (paths), pv (path and value pairs) (default "v")
examples
yq read things.yaml 'a.b.c'
yq r - 'a.b.c' # reads from stdin
yq r things.yaml 'a.*.c'
yq r things.yaml 'a.**.c' # deep splat
yq r things.yaml 'a.(child.subchild==co*).c'
yq r -d1 things.yaml 'a.array[0].blah'
yq r things.yaml 'a.array[*].blah'
yq r -- things.yaml '--key-starting-with-dashes.blah'
VALIDATE
test syntax of file
yq v sample.yaml
yq validate [yaml_file] [flags]
-d, --doc string # process document index number (0 based, * for all documents) (default "0")
-h, --help # help for validate
examples
yq v - # reads from stdin
WRITE
Updates the yaml file w.r.t the given path and value
Outputs to STDOUT unless the inplace flag is used, in which case the file is updated instead
Append value to array adds the value to the end of array
Update Scripts:
Note that you can give an update script to perform more sophisticated update. Update script format is list of update commands (update or delete) like so:
- command: update
path: b.c
value:
#great
things: frog # wow!
- command: delete
path: b.d
yq write [yaml_file] [path_expression] [value] [flags]
-d, --doc string # process document index number (0 based, * for all documents) (default "0")
-f, --from string # yaml file for updating yaml (as-is)
-h, --help # help for write
-i, --inplace # update the yaml file inplace
-s, --script string # yaml script for updating yaml
-t, --tag string # set yaml tag (e.g. !!int)
examples
yq write things.yaml 'a.b.c' true
yq write things.yaml 'a.*.c' true
yq write things.yaml 'a.**' true
yq write things.yaml 'a.(child.subchild==co*).c' true
yq write things.yaml 'a.b.c' --tag '!!str' true # force 'true' to be interpreted as a string instead of bool
yq write things.yaml 'a.b.c' --tag '!!float' 3
yq write --inplace -- things.yaml 'a.b.c' '--cat' # need to use '--' to stop processing arguments as flags
yq w -i things.yaml 'a.b.c' cat
yq w -i -s update_script.yaml things.yaml
yq w things.yaml 'a.b.d[+]' foo # appends a new node to the 'd' array
yq w --doc 2 things.yaml 'a.b.d[+]' foo # updates the 3rd document of the yaml file
TRICKS
LXC
pretty print
# pretty print
lxc list --format=yaml $ctname$ | yq r - -C
name
# print name
lxc list --format=yaml $ctname$ | yq r - '.name'
# print selected name for alpine.* in regexp format
lxc list --format=yaml | yq r - 'name==alpine*'
# display names of running containers
lxc list --format yaml | yq r - 'status==Running.name'
# display name of containers which have attached profile $profile
?