Reputation: 23
I have this yaml_file in a variable in python using safe_load from yaml library:
domainInfo:
AdminUserName: '--FIX ME--'
AdminPassword: '--FIX ME--'
topology:
Name: 'wld-pil-10'
ConfigBackupEnabled: true
AdminServerName: 'wls-pil-10-sa-adm-n0'
DomainVersion: 12.2.1.4.0
ProductionModeEnabled: true
ArchiveConfigurationCount: 20
Cluster:
'test-bruno-jee-r01a-c01':
ClientCertProxyEnabled: true
WeblogicPluginEnabled: true
Server:
'wls-pil-10-sa-adm-n0':
ListenPort: 11030
WeblogicPluginEnabled: true
ClientCertProxyEnabled: true
Machine: 'wlm-pil-10-n0'
'test-bruno-jee-r01a-it-c01-m1-n1':
ListenPort: 10022
WeblogicPluginEnabled: true
ClientCertProxyEnabled: true
NMSocketCreateTimeoutInMillis: 30000
Machine: 'wlm-pil-10-n1'
'test-bruno-jee-r02a-it-c01-m1-n1':
ListenPort: 10025
WeblogicPluginEnabled: true
ClientCertProxyEnabled: true
NMSocketCreateTimeoutInMillis: 30000
Machine: 'wlm-pil-10-n2'
In order to split this yaml file I'm trying to put the keys and values in a new dictionary but without success. What am I missing? I know that I need to have a dictionary in some way, do I need to use another module like pyyaml or ruamel?
yaml_cluster = {}
yaml_cluster["topology"]["Name"] = yaml_file["topology"]["Name"]
yaml_cluster["topology"]["AdminServerName"] = yaml_file["topology"]["AdminServerName"]
Result:
fatal: [wls-pil-103-sa-adm-n0]: FAILED! => {"changed": true, "msg": "non-zero return code", "rc": 1, "stderr": "Traceback (most recent call last):\n File "/tmp/ansible-tmp-1611083722.9917288-55849-215378473850896/split_yaml.py", line 32, in \n yaml_cluster["topology"]["Name"] = yaml_file["topology"]["Name"]\nKeyError: 'topology'\n", "stderr_lines": ["Traceback (most recent call last):", " File "/tmp/ansible-tmp-1611083722.9917288-55849-215378473850896/split_yaml.py", line 32, in ", " yaml_cluster["topology"]["Name"] = yaml_file["topology"]["Name"]", "KeyError: 'topology'"], "stdout": "", "stdout_lines": []}
Upvotes: 0
Views: 500
Reputation: 128
The error you're getting is because yaml_cluster["topology"]["Name"]
is assigned a value without either of the keys existing. yaml_cluster["topology"]
does not exist and you can therefore not assign something to the key Name
.
Collections module from the standard library provides a class collections.defaultdict
that gives a key a default value if it doesn't exist. In your case a defaultdict
with a empty dictionary as default value sets the value of yaml_cluster["topology]
to {}
(an empty dict) and the key Name
can then be assigned with a value to the dictionary as normal.
from collections import defaultdict
yaml_cluster = defaultdict(dict) # Specifying dictionary as default value for missing keys
yaml_cluster["topology"]["Name"] = yaml_file["topology"]["Name"]
yaml_cluster["topology"]["AdminServerName"] = yaml_file["topology"]["AdminServerName"]
Upvotes: 1