I am trying to load a YAML file in python, modify it and dump it back. The YAML looks like this:
data:
mapRoles: |
- username: system:node:{{EC2PrivateDNSName}}
groups:
- system:bootstrappers
- system:nodes
kind: ConfigMap
metadata:
name: aws-auth
namespace: kube-system
I would like to modify it so that the output file includes a new line rolearn: awsarn in mapRoles:
data:
mapRoles: |
- username: system:node:{{EC2PrivateDNSName}}
groups:
- system:bootstrappers
- system:nodes
rolearn: awsarn
kind: ConfigMap
metadata:
name: aws-auth
namespace: kube-system
But I am getting an output that where the mapRoles value get quoted like a string and includes the literal \n:
apiVersion: v1
data:
mapRoles: "- username: system:node:{{EC2PrivateDNSName}}\n groups:\n - system:bootstrappers\n\
\ - system:nodes\n rolearn: arnaws"
kind: ConfigMap
metadata:
name: aws-auth
namespace: kube-system
The code I am using:
with open ('/tmp/aws-auth-cm.yaml') as f:
content = yaml.safe_load(f)
content['data']['mapRoles'] = content['data']['mapRoles'] + ' rolearn: awsarn'
with open("/tmp/aws-auth-cm.yaml", "w") as f:
yaml.safe_dump(content, f, default_flow_style=False)
I also tried using yaml.safe_dump(content, f, default_flow_style=False, default_style='|') then all the values have |- and the keys get quoted with double quotes:
"apiVersion": |-
v1
"data":
"mapRoles": |-
- username: system:node:{{EC2PrivateDNSName}}
groups:
- system:bootstrappers
- system:nodes
rolearn: arnaws
"kind": |-
ConfigMap
"metadata":
"name": |
Is there a way that I could apply the style='|' just to the strings and also make sure the keys are not quoted?