【发布时间】:2021-09-21 03:18:43
【问题描述】:
我目前正在使用以下代码加载单文档模板 YAML 文件,稍微更改它,并生成(即转储)不同的新部署文件。代码如下所示:
import yaml
import copy
import ruamel.yaml
from ruamel.yaml.scalarstring import (DoubleQuotedScalarString as dq,
SingleQuotedScalarString as sq)
#As requested, below a summary of the functionality of the function define_exp_parameters
def define_exp_parameters(experiment_template, deployments):
deployment_list = []
for duration in range(30, 71, 1):
for cpu_cores in range(1, 4):
exp_doc[0]['spec']['annotationCheck'] = 'true'
deployment_list.append(copy.deepcopy(exp_doc))
return deployment_list
testyaml = ruamel.yaml.YAML()
with open(template_dir, 'r') as read_file:
deployments = testyaml.load_all(read_file)
deployments = list(deployments)
# define_exp_parameters is used to generate different YAML deployments, each of which are added to a list, which is returned. The list basically consists of x YAML deployment definitions which are later dumped in seperate files.
deployments = define_exp_parameters(experiment_template, deployments)
i = 1
for deployment in deployments:
with open(save_dir) as created_file:
testyaml.default_flow_style = False
testyaml.dump(deployment, created_file)
i += 1
模板如下所示:
apiVersion: litmuschaos.io/v1alpha1
kind: ChaosEngine
metadata:
name: teastore-chaos
namespace: default
spec:
annotationCheck: 'false'
engineState: active
appinfo:
appns: default
applabel: app=teastore
appkind: deployment
chaosServiceAccount: litmus-admin
components:
runner:
runnerAnnotations:
sidecar.istio.io/inject: 'false'
jobCleanUpPolicy: delete
experiments:
- name: pod-cpu-hog
这会产生具有以下结构的文件:
- apiVersion: litmuschaos.io/v1alpha1
kind: ChaosEngine
metadata:
name: teastore-chaos
namespace: default
spec:
annotationCheck: 'false'
engineState: active
appinfo:
appns: default
applabel: app=teastore
appkind: deployment
chaosServiceAccount: litmus-admin
components:
runner:
runnerAnnotations:
sidecar.istio.io/inject: 'false'
jobCleanUpPolicy: delete
experiments:
- name: pod-cpu-hog
但是,我想要的结构如下(即与模板相同):
apiVersion: litmuschaos.io/v1alpha1
kind: ChaosEngine
metadata:
name: teastore-chaos
namespace: default
spec:
annotationCheck: 'false'
engineState: active
appinfo:
appns: default
applabel: app=teastore
appkind: deployment
chaosServiceAccount: litmus-admin
components:
runner:
runnerAnnotations:
sidecar.istio.io/inject: 'false'
jobCleanUpPolicy: delete
experiments:
- name: pod-cpu-hog
基本上,第一行不应该有破折号(由于某种原因,它是自动生成/添加的,因为它不在原始模板文件中)并且不应该有额外的第一个缩进整个结构(我认为与破折号一起出现)。我正在使用 ruamel.yaml 进行转储,因为它保留了字符串中的显式单引号(使用导入的包)。我曾尝试寻找类似的案例和ruamel.yaml 文档,但找不到原因/解决方案。
【问题讨论】:
-
缩进确实与破折号一起出现。
标签: python yaml ruamel.yaml