Helm-Charts(yaml): Regex expression broken - yaml

I am working with https://github.com/prometheus-community/helm-charts and am running into some issues with a couple of regex queries are a part of our basic yaml deployments. The issue I'm having is specifically with the Node exporter part of the prometheus chart. I have configured this:
nodeExporter:
extraArgs: {
collector.filesystem.ignored-fs-types="^(devpts|devtmpfs|mqueue|proc|securityfs|binfmt_misc|debugfs|overlay|pstore|selinuxfs|tmpfs|hugetlbfs|nfsd|cgroup|configfs|rpc_pipefs|sysfs|autofs|rootfs)$",
collector.filesystem.ignored-mount-points="^/etc/.+$",
collector.netstat.fields="*",
collector.diskstats.ignored-devices="^(ram|loop|fd|(h|s|v|xv)d[a-z]|nvme\d+n\d+p|dm-)\d+$", # BROKEN
collector.netclass.ignored-devices=^(?:tun|kube|veth|dummy|docker).+$, # BROKEN
collector.nfs
}
tolerations:
- operator: Exists
As noted above, these two lines with regex are broken:
collector.diskstats.ignored-devices="^(ram|loop|fd|(h|s|v|xv)d[a-z]|nvme\d+n\d+p|dm-)\d+$", # BROKEN
collector.netclass.ignored-devices=^(?:tun|kube|veth|dummy|docker).+$, # BROKEN
There seems to be a problem with the | character right be fore "nvme" in the first one, and with the ?: in the second. I believe it's something to do with regex/yaml format, but I'm not sure how to correct this.

With {, you are beginning a YAML flow mapping. It typically contains comma-separated key-value pairs, though you can also, like in this example, give single values instead, which will make them a key with null value.
In YAML, as soon as you enter a flow-style collection, all special flow-indicators cannot be used in plain scalars anymore. Special flow indicators are {}[],. A plain scalar is a non-quoted textual value.
The first broken value is illegal because it contains [ and ]. The second broken value is actually legal according to the specification, but quite some YAML implementations choke on it because ? is also used as indicator for a mapping key.
You have several options:
Quote the scalars. since none of them contain single quotes, enclosing each with single quotes will do the trick. Generally you can also double-quote them, but then you need to escape all double-quote characters and all backslashes in there which does not help readability.
nodeExporter:
extraArgs: {
collector.filesystem.ignored-fs-types="^(devpts|devtmpfs|mqueue|proc|securityfs|binfmt_misc|debugfs|overlay|pstore|selinuxfs|tmpfs|hugetlbfs|nfsd|cgroup|configfs|rpc_pipefs|sysfs|autofs|rootfs)$",
collector.filesystem.ignored-mount-points="^/etc/.+$",
collector.netstat.fields="*",
'collector.diskstats.ignored-devices="^(ram|loop|fd|(h|s|v|xv)d[a-z]|nvme\d+n\d+p|dm-)\d+$"',
'collector.netclass.ignored-devices=^(?:tun|kube|veth|dummy|docker).+$',
collector.nfs
}
tolerations:
- operator: Exists
Use block scalars. Block scalars are generally the best way to enter scalars with lots of special characters because they are ended via indentation and therefore can contain any special character. Block scalars can only occur in other block structures, so you'd need to make extraArgs a block mapping:
nodeExporter:
extraArgs:
? collector.filesystem.ignored-fs-types="^(devpts|devtmpfs|mqueue|proc|securityfs|binfmt_misc|debugfs|overlay|pstore|selinuxfs|tmpfs|hugetlbfs|nfsd|cgroup|configfs|rpc_pipefs|sysfs|autofs|rootfs)$"
? collector.filesystem.ignored-mount-points="^/etc/.+$"
? collector.netstat.fields="*"
? |-
collector.diskstats.ignored-devices="^(ram|loop|fd|(h|s|v|xv)d[a-z]|nvme\d+n\d+p|dm-)\d+$"
? |-
collector.netclass.ignored-devices=^(?:tun|kube|veth|dummy|docker).+$
? collector.nfs
tolerations:
- operator: Exists
As you can see, this is now using the previously mentioned ? as key indicator.
Since it is a block sequence, you don't need the commas anymore.
|- starts a literal block scalar from which the final linebreak is stripped.

Related

Difference between with or without quotes for a value defined in an Ansible variable [duplicate]

I am trying to write a YAML dictionary for internationalisation of a Rails project. I am a little confused though, as in some files I see strings in double-quotes and in some without. A few points to consider:
example 1 - all strings use double quotes;
example 2 - no strings (except the last two) use quotes;
the YAML cookbook says: Enclosing strings in double quotes allows you to use escaping to represent ASCII and Unicode characters. Does this mean I need to use double quotes only when I want to escape some characters? If yes - why do they use double quotes everywhere in the first example - only for the sake of unity / stylistic reasons?
the last two lines of example 2 use ! - the non-specific tag, while the last two lines of the first example don't - and they both work.
My question is: what are the rules for using the different types of quotes in YAML?
Could it be said that:
in general, you don't need quotes;
if you want to escape characters use double quotes;
use ! with single quotes, when... ?!?
After a brief review of the YAML cookbook cited in the question and some testing, here's my interpretation:
In general, you don't need quotes.
Use quotes to force a string, e.g. if your key or value is 10 but you want it to return a String and not a Fixnum, write '10' or "10".
Use quotes if your value includes special characters, (e.g. :, {, }, [, ], ,, &, *, #, ?, |, -, <, >, =, !, %, #, \).
Single quotes let you put almost any character in your string, and won't try to parse escape codes. '\n' would be returned as the string \n.
Double quotes parse escape codes. "\n" would be returned as a line feed character.
The exclamation mark introduces a method, e.g. !ruby/sym to return a Ruby symbol.
Seems to me that the best approach would be to not use quotes unless you have to, and then to use single quotes unless you specifically want to process escape codes.
Update
"Yes" and "No" should be enclosed in quotes (single or double) or else they will be interpreted as TrueClass and FalseClass values:
en:
yesno:
'yes': 'Yes'
'no': 'No'
While Mark's answer nicely summarizes when the quotes are needed according to the YAML language rules, I think what many of the developers/administrators are asking themselves, when working with strings in YAML, is "what should be my rule of thumb for handling the strings?"
It may sound subjective, but the number of rules you have to remember, if you want to use the quotes only when they are really needed as per the language spec, is somewhat excessive for such a simple thing as specifying one of the most common datatypes. Don't get me wrong, you will eventually remember them when working with YAML regularly, but what if you use it occasionally, and you didn't develop automatism for writing YAML? Do you really want to spend time remembering all the rules just to specify the string correctly?
The whole point of the "rule of thumb" is to save the cognitive resource and to handle a common task without thinking about it. Our "CPU" time can arguably be used for something more useful than handling the strings correctly.
From this - pure practical - perspective, I think the best rule of thumb is to single quote the strings. The rationale behind it:
Single quoted strings work for all scenarios, except when you need to use escape sequences.
The only special character you have to handle within a single-quoted string is the single quote itself.
These are just 2 rules to remember for some occasional YAML user, minimizing the cognitive effort.
There have been some great answers to this question.
However, I would like to extend them and provide some context from the new official YAML v1.2.2 specification (released October 1st 2021) which is the "true source" to all things considering YAML.
There are three different styles that can be used to represent strings, each of them with their own (dis-)advantages:
YAML provides three flow scalar styles: double-quoted, single-quoted and plain (unquoted). Each provides a different trade-off between readability and expressive power.
Double-quoted style:
The double-quoted style is specified by surrounding " indicators. This is the only style capable of expressing arbitrary strings, by using \ escape sequences. This comes at the cost of having to escape the \ and " characters.
Single-quoted style:
The single-quoted style is specified by surrounding ' indicators. Therefore, within a single-quoted scalar, such characters need to be repeated. This is the only form of escaping performed in single-quoted scalars. In particular, the \ and " characters may be freely used. This restricts single-quoted scalars to printable characters. In addition, it is only possible to break a long single-quoted line where a space character is surrounded by non-spaces.
Plain (unquoted) style:
The plain (unquoted) style has no identifying indicators and provides no form of escaping. It is therefore the most readable, most limited and most context sensitive style. In addition to a restricted character set, a plain scalar must not be empty or contain leading or trailing white space characters. It is only possible to break a long plain line where a space character is surrounded by non-spaces.
Plain scalars must not begin with most indicators, as this would cause ambiguity with other YAML constructs. However, the :, ? and - indicators may be used as the first character if followed by a non-space “safe” character, as this causes no ambiguity.
TL;DR
With that being said, according to the official YAML specification one should:
Whenever applicable use the unquoted style since it is the most readable.
Use the single-quoted style (') if characters such as " and \ are being used inside the string to avoid escaping them and therefore improve readability.
Use the double-quoted style (") when the first two options aren't sufficient, i.e. in scenarios where more complex line breaks are required or non-printable characters are needed.
Strings in yaml only need quotation if (the beginning of) the value can be misinterpreted as a data type or the value contains a ":" (because it could get misinterpreted as key).
For example
foo: '{{ bar }}'
needs quotes, because it can be misinterpreted as datatype dict, but
foo: barbaz{{ bam }}
does not, since it does not begin with a critical char. Next,
foo: '123'
needs quotes, because it can be misinterpreted as datatype int, but
foo: bar1baz234
bar: 123baz
Does not, because it can not be misinterpreted as int
foo: 'yes'
needs quotes, because it can be misinterpreted as datatype bool
foo: "bar:baz:bam"
needs quotes, because the value can be misinterpreted as key.
These are just examples. Using yamllint helps avoiding to start values with a wrong token
foo#bar:/tmp$ yamllint test.yaml
test.yaml
3:4 error syntax error: found character '#' that cannot start any token (syntax)
and is a must, if working productively with yaml.
Quoting all strings as some suggest, is like using brackets in python. It is bad practice, harms readability and throws away the beautiful feature of not having to quote strings.
I had this concern when working on a Rails application with Docker.
My most preferred approach is to generally not use quotes. This includes not using quotes for:
variables like ${RAILS_ENV}
values separated by a colon (:) like postgres-log:/var/log/postgresql
other strings values
I, however, use double-quotes for integer values that need to be converted to strings like:
docker-compose version like version: "3.8"
port numbers like "8080:8080"
image "traefik:v2.2.1"
However, for special cases like booleans, floats, integers, and other cases, where using double-quotes for the entry values could be interpreted as strings, please do not use double-quotes.
Here's a sample docker-compose.yml file to explain this concept:
version: "3"
services:
traefik:
image: "traefik:v2.2.1"
command:
- --api.insecure=true # Don't do that in production
- --providers.docker=true
- --providers.docker.exposedbydefault=false
- --entrypoints.web.address=:80
ports:
- "80:80"
- "8080:8080"
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
That's all.
I hope this helps
If you are trying to escape a string in pytest tavern, !raw could be helpful to avoid parsing of strings to yaml:
some: !raw "{test: 123}"
Check for more info:
https://tavern.readthedocs.io/en/latest/basics.html#type-conversions
Here's a small function (not optimized for performance) that quotes your strings with single quotes if needed and tests if the result could be unmarshalled into the original value: https://go.dev/play/p/AKBzDpVz9hk.
Instead of testing for the rules it simply uses the marshaller itself and checks if the marshalled and unmmarshalled value matches the original version.
func yamlQuote(value string) string {
input := fmt.Sprintf("key: %s", value)
var res struct {
Value string `yaml:"key"`
}
if err := yaml.Unmarshal([]byte(input), &res); err != nil || value != res.Value {
quoted := strings.ReplaceAll(value, `'`, `''`)
return fmt.Sprintf("'%s'", quoted)
}
return value
}
version: "3.9"
services:
seunggabi:
image: seunggabi:v1.0.0
command:
api:
insecure: true
ports:
- 80:80
- 8080:8080
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
docker compoese up docker-compose.yaml
If you use docker compose v2, you don't need to use quotation for boolean.
Only the version needs quotations.

Reading and writing back yaml files with multi-line strings

I have to read a yaml file, modify it and write back using pyYAML. Every thing works fine except when there is multi-line string values in single quotes e.g. if input yaml file looks like
FOO:
- Bar: '{"HELLO":
"WORLD"}'
then reading it as data=yaml.load(open("foo.yaml")) and writing it yaml.dump(data, fref, default_flow_style=False) generates something like
FOO:
- Bar: '{"HELLO": "WORLD"}'
i.e. without the extra line for Bar value. Strange thing is that if input file has something like
FOO:
- Bar: '{"HELLO":
"WORLD"}'
i.e. one extra new line for Bar value then writing it back generates the correct number of new lines. Any idea what I am doing wrong?
You are not doing anything wrong, but you probably should have read more of the YAML specification.
According to the (outdated) 1.1 spec that PyYAML implements, within
single quoted scalars:
In a multi-line single-quoted scalar, line breaks are subject to (flow) line folding, and any trailing white space is excluded from the content.
And line-folding:
Line folding allows long lines to be broken for readability, while retaining the original semantics of a single long line. When folding is done, any line break ending an empty line is preserved. In addition, any specific line breaks are also preserved, even when ending a non-empty line.
This means that your first two examples are the same, as the
line-break is read as if there is a space.
The third example is different, because it actually contains a newline after loading, because "any line break ending an empty line is preserved".
In order to understand why that dumps back as it was loaded, you have to know that PyYAML doesn't
maintain any information about the quoting (nor about the single newline in the first example), it
just loads that scalar into a Python string. During dumping PyYAML evaluates how that string
can best be written and the options it considers (unless you try to force things using the default_style argument to dump()): plain style, single quoted style, double quoted style.
PyYAML will use plain style (without quotes) when possible, but since
the string starts with {, this leads to confusion (collision) with
that character's use as the start of a flow style mapping. So quoting
is necessary. Since there are also double quotes in the string, and
there are no characters that need backslash escaping the "cleanest"
representation that PyYAML can choose is single quoted style, and in
that style it needs to represent a line-break by including an emtpy
line withing the single quoted scalar.
I would personally prefer using a block style literal scalar to represent your last example:
FOO:
- Bar: |
{"HELLO":
"WORLD"}
but if you load, then dump that using PyYAML its readability would be lost.
Although worded differently in the YAML 1.2 specification (released almost 10 years ago) the line-folding works the same, so this would "work" in a similar way with a more up-to-date YAML loader/dumper. My package ruamel.yaml, for loading/dumping YAML 1.2 will properly maintain the block style if you set the attribute preserve_quotes = True on the YAML() instance, but it will still get rid of the newline in your first example. This could be implemented (as is shown by ruamel.yaml preserving appropriate newline positions in folded style block scalars), but nobody ever asked for that, probably because if people want that kind of control over wrapping they use a block style to start with.

Why does the YAML spec mandate a space after the colon?

The YAML spec clearly states:
Mappings use a colon and space (“: ”) to mark each key: value pair.
So this is legal:
foo: bar
But this, Ain't:
foo:bar
I see many people online that are ranting about the space. I think they have a point. I got burned by it several times myself.
Why is the space mandatory? What was the design consideration behind it?
It's easy to miss, because that specification uses the bizarre convention of only highlighting the last character of an internal link, but the “: ” in the section you quote is actually a link to another section of the specification which answers your question:
Normally, YAML insists the “:” mapping value indicator be separated from the value by white space. A benefit of this restriction is that the “:” character can be used inside plain scalars, as long as it is not followed by white space. This allows for unquoted URLs and timestamps. It is also a potential source for confusion as “a:1” is a plain scalar and not a key: value pair.
So the motivation is that you can write lists such as this without requiring any quoting:
useful_values:
- 2:30
- http://example.com
- localhost:8080
If the space was optional, this could end up being ambiguous, and interpreted as a set of key-value pairs.
Aside: Here's a snippet of JS to make the link formatting on that document less useless.
document.styleSheets[0].insertRule('a[href^="#"] { color: #00A !important; text-decoration: underline !important; background: none !important; }', 0);
Actually, space after column is not always mandatory. It is optional if two conditions are met:
Flow style syntax is used (aka JSON / one-liner / {} / []);
The key is quoted.
This syntax is valid (pyyaml=5.3.1):
{"x":abc}
Output: {'x': 'abc'}
But be careful:
{x:abc} # {'x:abc': None}
# Can't separate key from value if not quoted
---
{x:"abc"} # {'x:"abc"': None}
# Same problem
More edge cases with colon and space:
x:::abc # 'x:::abc'
# Scalar, not a key-value
---
x:: :abc # {'x:': ':abc'}
# Avoid this, use quotes to be safe if `:` is
# involved in either key or value.
---
{x:: :abc} # Error: while parsing a flow node expected the node
# content, but found ':'
# Parsing logic for flow syntax can be surprising.
---
{"x:":":abc"} # {'x:': ':abc'}
# Follow the "least surprise principle" - stick to JSON syntax.

YAML: Do I need quotes for strings in YAML?

I am trying to write a YAML dictionary for internationalisation of a Rails project. I am a little confused though, as in some files I see strings in double-quotes and in some without. A few points to consider:
example 1 - all strings use double quotes;
example 2 - no strings (except the last two) use quotes;
the YAML cookbook says: Enclosing strings in double quotes allows you to use escaping to represent ASCII and Unicode characters. Does this mean I need to use double quotes only when I want to escape some characters? If yes - why do they use double quotes everywhere in the first example - only for the sake of unity / stylistic reasons?
the last two lines of example 2 use ! - the non-specific tag, while the last two lines of the first example don't - and they both work.
My question is: what are the rules for using the different types of quotes in YAML?
Could it be said that:
in general, you don't need quotes;
if you want to escape characters use double quotes;
use ! with single quotes, when... ?!?
After a brief review of the YAML cookbook cited in the question and some testing, here's my interpretation:
In general, you don't need quotes.
Use quotes to force a string, e.g. if your key or value is 10 but you want it to return a String and not a Fixnum, write '10' or "10".
Use quotes if your value includes special characters, (e.g. :, {, }, [, ], ,, &, *, #, ?, |, -, <, >, =, !, %, #, \).
Single quotes let you put almost any character in your string, and won't try to parse escape codes. '\n' would be returned as the string \n.
Double quotes parse escape codes. "\n" would be returned as a line feed character.
The exclamation mark introduces a method, e.g. !ruby/sym to return a Ruby symbol.
Seems to me that the best approach would be to not use quotes unless you have to, and then to use single quotes unless you specifically want to process escape codes.
Update
"Yes" and "No" should be enclosed in quotes (single or double) or else they will be interpreted as TrueClass and FalseClass values:
en:
yesno:
'yes': 'Yes'
'no': 'No'
While Mark's answer nicely summarizes when the quotes are needed according to the YAML language rules, I think what many of the developers/administrators are asking themselves, when working with strings in YAML, is "what should be my rule of thumb for handling the strings?"
It may sound subjective, but the number of rules you have to remember, if you want to use the quotes only when they are really needed as per the language spec, is somewhat excessive for such a simple thing as specifying one of the most common datatypes. Don't get me wrong, you will eventually remember them when working with YAML regularly, but what if you use it occasionally, and you didn't develop automatism for writing YAML? Do you really want to spend time remembering all the rules just to specify the string correctly?
The whole point of the "rule of thumb" is to save the cognitive resource and to handle a common task without thinking about it. Our "CPU" time can arguably be used for something more useful than handling the strings correctly.
From this - pure practical - perspective, I think the best rule of thumb is to single quote the strings. The rationale behind it:
Single quoted strings work for all scenarios, except when you need to use escape sequences.
The only special character you have to handle within a single-quoted string is the single quote itself.
These are just 2 rules to remember for some occasional YAML user, minimizing the cognitive effort.
There have been some great answers to this question.
However, I would like to extend them and provide some context from the new official YAML v1.2.2 specification (released October 1st 2021) which is the "true source" to all things considering YAML.
There are three different styles that can be used to represent strings, each of them with their own (dis-)advantages:
YAML provides three flow scalar styles: double-quoted, single-quoted and plain (unquoted). Each provides a different trade-off between readability and expressive power.
Double-quoted style:
The double-quoted style is specified by surrounding " indicators. This is the only style capable of expressing arbitrary strings, by using \ escape sequences. This comes at the cost of having to escape the \ and " characters.
Single-quoted style:
The single-quoted style is specified by surrounding ' indicators. Therefore, within a single-quoted scalar, such characters need to be repeated. This is the only form of escaping performed in single-quoted scalars. In particular, the \ and " characters may be freely used. This restricts single-quoted scalars to printable characters. In addition, it is only possible to break a long single-quoted line where a space character is surrounded by non-spaces.
Plain (unquoted) style:
The plain (unquoted) style has no identifying indicators and provides no form of escaping. It is therefore the most readable, most limited and most context sensitive style. In addition to a restricted character set, a plain scalar must not be empty or contain leading or trailing white space characters. It is only possible to break a long plain line where a space character is surrounded by non-spaces.
Plain scalars must not begin with most indicators, as this would cause ambiguity with other YAML constructs. However, the :, ? and - indicators may be used as the first character if followed by a non-space “safe” character, as this causes no ambiguity.
TL;DR
With that being said, according to the official YAML specification one should:
Whenever applicable use the unquoted style since it is the most readable.
Use the single-quoted style (') if characters such as " and \ are being used inside the string to avoid escaping them and therefore improve readability.
Use the double-quoted style (") when the first two options aren't sufficient, i.e. in scenarios where more complex line breaks are required or non-printable characters are needed.
Strings in yaml only need quotation if (the beginning of) the value can be misinterpreted as a data type or the value contains a ":" (because it could get misinterpreted as key).
For example
foo: '{{ bar }}'
needs quotes, because it can be misinterpreted as datatype dict, but
foo: barbaz{{ bam }}
does not, since it does not begin with a critical char. Next,
foo: '123'
needs quotes, because it can be misinterpreted as datatype int, but
foo: bar1baz234
bar: 123baz
Does not, because it can not be misinterpreted as int
foo: 'yes'
needs quotes, because it can be misinterpreted as datatype bool
foo: "bar:baz:bam"
needs quotes, because the value can be misinterpreted as key.
These are just examples. Using yamllint helps avoiding to start values with a wrong token
foo#bar:/tmp$ yamllint test.yaml
test.yaml
3:4 error syntax error: found character '#' that cannot start any token (syntax)
and is a must, if working productively with yaml.
Quoting all strings as some suggest, is like using brackets in python. It is bad practice, harms readability and throws away the beautiful feature of not having to quote strings.
I had this concern when working on a Rails application with Docker.
My most preferred approach is to generally not use quotes. This includes not using quotes for:
variables like ${RAILS_ENV}
values separated by a colon (:) like postgres-log:/var/log/postgresql
other strings values
I, however, use double-quotes for integer values that need to be converted to strings like:
docker-compose version like version: "3.8"
port numbers like "8080:8080"
image "traefik:v2.2.1"
However, for special cases like booleans, floats, integers, and other cases, where using double-quotes for the entry values could be interpreted as strings, please do not use double-quotes.
Here's a sample docker-compose.yml file to explain this concept:
version: "3"
services:
traefik:
image: "traefik:v2.2.1"
command:
- --api.insecure=true # Don't do that in production
- --providers.docker=true
- --providers.docker.exposedbydefault=false
- --entrypoints.web.address=:80
ports:
- "80:80"
- "8080:8080"
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
That's all.
I hope this helps
If you are trying to escape a string in pytest tavern, !raw could be helpful to avoid parsing of strings to yaml:
some: !raw "{test: 123}"
Check for more info:
https://tavern.readthedocs.io/en/latest/basics.html#type-conversions
Here's a small function (not optimized for performance) that quotes your strings with single quotes if needed and tests if the result could be unmarshalled into the original value: https://go.dev/play/p/AKBzDpVz9hk.
Instead of testing for the rules it simply uses the marshaller itself and checks if the marshalled and unmmarshalled value matches the original version.
func yamlQuote(value string) string {
input := fmt.Sprintf("key: %s", value)
var res struct {
Value string `yaml:"key"`
}
if err := yaml.Unmarshal([]byte(input), &res); err != nil || value != res.Value {
quoted := strings.ReplaceAll(value, `'`, `''`)
return fmt.Sprintf("'%s'", quoted)
}
return value
}
version: "3.9"
services:
seunggabi:
image: seunggabi:v1.0.0
command:
api:
insecure: true
ports:
- 80:80
- 8080:8080
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
docker compoese up docker-compose.yaml
If you use docker compose v2, you don't need to use quotation for boolean.
Only the version needs quotations.

Allowed characters in map key identifier in YAML?

Which characters are and are not allowed in a key (i.e. example in example: "Value") in YAML?
According to the YAML 1.2 specification simply advises using printable characters with explicit control characters being excluded (see here):
In constructing key names, characters the YAML spec. uses to denote syntax or special meaning need to be avoided (e.g. # denotes comment, > denotes folding, - denotes list, etc.).
Essentially, you are left to the relative coding conventions (restrictions) by whatever code (parser/tool implementation) that needs to consume your YAML document. The more you stick with alphanumerics the better; it has simply been our experience that the underscore has worked with most tooling we have encountered.
It has been a shared practice with others we work with to convert the period character . to an underscore character _ when mapping namespace syntax that uses periods to YAML. Some people have similarly used hyphens successfully, but we have seen it misconstrued in some implementations.
Any character (if properly quoted by either single quotes 'example' or double quotes "example"). Please be aware that the key does not have to be a scalar ('example'). It can be a list or a map.

Resources