我有一个具有以下结构的YAML:
- description: 'DUMMY_JOB'
sequence:
commands:
- description: Metadata
script: ASDF
- description: Login
jobref:
args: ASDF
group: ''
name: ASDF
nodeStep: 'true'
- description: Deployment
jobref:
args: ASDF
group: ''
name: ASDF
nodeStep: 'true'
- description: Logout
jobref:
group: ''
name: ASDF
nodeStep: 'true'
keepgoing: false
strategy: node-first
uuid: 'UNIQUE_ID'
这个YAML用作Rundeck中的工作描述,我要做的就是复制命令编辑数据(旧命令)和新命令以反映新参数。
我通过PyYaml加载它:
jobStream = open("example.yaml", 'r')
jobMap = yaml.safe_load(jobStream)
使用以下方式访问它:
jobMap[0]['sequence']['commands']
带回我需要的数据。但是,如果我只是通过合并来复制它,如:
commandsA = jobMap[0]['sequence']['commands']
commandsB = jobMap[0]['sequence']['commands']
jobMap[0]['sequence']['commands'] = commandsA + commandsB
如果我尝试执行yaml.dump(jobMap)
,它就不会重复命令,但会显示ID:
- *id001
- *id002
- *id003
- *id004
答案 0 :(得分:0)
列表commandsA
和commandsB
中的元素是字典,如果您复制那些元素,您将在结构中获得多个引用到相同的项目,从而导致锚点(&
)和别名(*
)
获得所需YAML的最快方法可能是使用deepcopy
:
from copy import deepcopy
jobMap[0]['sequence']['commands'] = deepcopy(commandsA) + deepcopy(commandsB)