json 如何在Ansible中添加字典中缺少的键

qojgxg4l  于 2023-05-30  发布在  其他
关注(0)|答案(1)|浏览(131)

我用这样的示例值进行变量测试:

- testing: 
  - failed: "yes"
    msg: "anothermessage"
  - results:
      - url: "ip:port"
        json:
          messages: 
            - message: "yepp"
              severity: "ok"
    failed: "yes"
    msg: "ikan"
  - failed: "no"
    msg: "anothermessageyeay"

测试的值可能不同,并且有时密钥导致结构丢失,如示例所示。如何添加一些字符串的结果的关键,所以我可以Map它?
我希望输出是这样的:

- testing: 
  - results: "not exist"
    failed: "yes"
    msg: "anothermessage"
  - results:
      - url: "ip:port"
        json:
          messages: 
            - message: "yepp"
              severity: "ok"
    failed: "yes"
    msg: "ikan"
  - results: "not exist"
   failed: "no"
    msg: "anothermessageyeay"
muk1a3rh

muk1a3rh1#

下面的表达式

results_default:
  results: not exist
testing2: "{{ [results_default]|
              product(testing)|
              map('combine')|
              list }}"

也可以使用下面的模板

testing2: |
  {% filter from_yaml %}
  {% for x,y in [results_default]|product(testing) %}
  - {{ x|combine(y) }}
  {% endfor %}
  {% endfilter %}

将默认属性 results 添加到字典

testing2:
  - failed: 'yes'
    msg: anothermessage
    results: not exist
  - failed: 'yes'
    msg: ikan
    results:
    - json:
        messages:
        - message: yepp
          severity: ok
      url: ip:port
  - failed: 'no'
    msg: anothermessageyeay
    results: not exist

完整的测试剧本示例

shell> cat pb.yml
- hosts: all

  vars:

    testing: 
      - failed: "yes"
        msg: "anothermessage"
      - results:
          - url: "ip:port"
            json:
              messages: 
                - message: "yepp"
                  severity: "ok"
        failed: "yes"
        msg: "ikan"
      - failed: "no"
        msg: "anothermessageyeay"

    results_default:
      results: not exist
    testing2: "{{ [results_default]|
                  product(testing)|
                  map('combine')|
                  list }}"

  tasks:

    - debug:
        var: testing2

给予

shell> ansible-playbook -i localhost, pb.yml

PLAY [all] ***********************************************************************************

TASK [debug] *********************************************************************************
ok: [localhost] => 
  testing2:
  - failed: 'yes'
    msg: anothermessage
    results: not exist
  - failed: 'yes'
    msg: ikan
    results:
    - json:
        messages:
        - message: yepp
          severity: ok
      url: ip:port
  - failed: 'no'
    msg: anothermessageyeay
    results: not exist

PLAY RECAP ***********************************************************************************
localhost: ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

相关问题