【问题标题】:How to insert a yaml string into a yaml value as if it is yaml如何将 yaml 字符串插入到 yaml 值中,就好像它是 yaml
【发布时间】:2021-06-15 04:57:41
【问题描述】:

我需要一些关于 python 的帮助。
我有两个数组:param_keys 和 param_values。第一个包含字符串键,第二个包含 base64 编码的字符串。
我还有一个从文件中读取的现有 yaml 结构:

start:
  implementation: ansible.cloudify_ansible.tasks.run
  inputs:
    playbook_path: ansible/main-routers.yaml
    run_data:
      hostname: r1

我想将这些键值对添加到“run_data”键下的现有 yaml 中。问题是我的值不是简单的字符串,而是 base64 字符串形式的 yaml:
原始yaml

- index: 1
  address: { get_input: host_ip_int_nic_r1_1 }
  netmask: 30
- index: 2
  address: { get_input: host_ip_int_nic_r1_2 }
  netmask: 30

Base 64 编码字符串:

LSBpbmRleDogMQogIGFkZHJlc3M6IHsgZ2V0X2lucHV0OiBob3N0X2lwX2ludF9uaWNfcjFfMSB9CiAgbmV0bWFzazogMzAKLSBpbmRleDogMgogIGFkZHJlc3M6IHsgZ2V0X2lucHV0OiBob3N0X2lwX2ludF9uaWNfcjFfMiB9CiAgbmV0bWFzazogMzA=

这是我的代码:

with open(blueprintPath + "ansible_" + str(ansible_id) + ".yaml") as f:
    doc = yaml.safe_load(f)
    for key,value in zip(param_keys,param_values):
        decodedstring = base64.b64decode(value).decode('utf-8')
        doc["start"]["inputs"]["run_data"][key] = decodedstring
with open(blueprintPath + "ansible_" + str(ansible_id) + ".yaml",'w') as f:
    yaml.dump(doc, f)

这是我得到的:

start:
  implementation: ansible.cloudify_ansible.tasks.run
  inputs:
    playbook_path: ansible/main-routers.yaml
    run_data:
      hostname: r1
      ip_config: "- index: 1\n  address: { get_input: host_ip_int_nic_r1_1\
      \ }\n  netmask: 30\n- index: 2\n  address: { get_input: host_ip_int_nic_r1_2\
      \ }\n  netmask: 30"

我的愿望是得到这个:

start:
  implementation: ansible.cloudify_ansible.tasks.run
  inputs:
    playbook_path: ansible/main-routers.yaml
    run_data:
      hostname: r1
      ip_config:
      - index: 1
      address: { get_input: host_ip_int_nic_r1_1 }
      netmask: 30
      - index: 2
      address: { get_input: host_ip_int_nic_r1_2 }
      netmask: 30

其中“ip_config”是 param_keys 中键的示例。

【问题讨论】:

    标签: python yaml


    【解决方案1】:

    您在输出中得到一个字符串,因为您将值作为单个字符串放在那里。您要做的是将值解析为 YAML 并将结果值放在那里:

        doc["start"]["inputs"]["run_data"][key] = yaml.safe_load(decodedstring)
    

    【讨论】:

    • 很想你!这太简单了,也许我需要多睡觉! :D
    猜你喜欢
    • 2013-03-24
    • 1970-01-01
    • 2020-04-30
    • 1970-01-01
    • 2010-10-17
    • 1970-01-01
    • 2018-12-12
    • 2012-11-22
    • 2021-10-08
    相关资源
    最近更新 更多