I have the following YAML file. I need to update the YAML file with a new key-value pair using python.
I am doing the following but, it gives me error:
pod = mylib.load_yaml("net/pod.yaml")
pod['spec']['nodeSelector']['key']='val'
it gives error saying KeyError:'nodeSelector'
spec:
containers:
- image: ceridwen/networking:v1
imagePullPolicy: Always
name: networking
readinessProbe:
tcpSocket:
port: 5000
initialDelaySeconds: 5
periodSeconds: 1
restartPolicy: Always
I need to update it with a new key value
spec:
containers:
- image: ceridwen/networking:v1
imagePullPolicy: Always
name: networking
readinessProbe:
tcpSocket:
port: 5000
initialDelaySeconds: 5
periodSeconds: 1
restartPolicy: Always
nodeSelector:
key: value
Key-Value Pairs. The YAML above defines four keys - first_name , last_name , age_years , and home - with their four respective values. Values can be character strings, numeric (integer, floating point, or scientific representation), Boolean ( true or false ), or more complex nested types (see below).
YAML Example: Scalar TypesWords in keys can be separated by underscores, dashes, or spaces. At CircleCI, we use underscores. Note that the leading indentation for the multi-line string will be stripped.
Creating YAML config file in Python We can write data to the YAML file using yaml. dump() method which takes python object and file pointer as parameters. In the below example, we are writing the dictionary article_info to the YAML file tutswiki. yaml .
PyYAML is a YAML parser and emitter for Python. PyYAML features a complete YAML 1.1 parser, Unicode support, pickle support, capable extension API, and sensible error messages. PyYAML supports standard YAML tags and provides Python-specific tags that allow to represent an arbitrary Python object.
Once you load that YAML file, your pod
is a dict with a single key spec
. You can check the value for that key (print(pod['spec']
) and you'll see that that is dict, with a single key containers
. Since you want add an extra key nodeSelector
to that dict you should add to pod['spec']
:
pod['spec']['nodeSelector'] = dict(key='value')
Please note that the key:value
you had in your output (without a space after the :
and without quotes around key
and value
), is not a mapping but a single scalar string.
The "solution" given by @zwer in his comment:
pod["spec"] = {"nodeSelector": {"key": "val"}}
is incorrect, as it will dump as:
spec:
nodeSelector:
key: val
i.e. replacing the value for spec
and thereby deleting the existing dict/mapping with the key containers
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With