如果json包含给定值,则用于处理json和寄存器变量的Ansible任务

ukqbszuj  于 2022-12-01  发布在  其他
关注(0)|答案(1)|浏览(94)

对于Ansible剧本,我需要从API调用中获取一些结果,以检查ID是否已经存在。
这应该是程序:

  • 如果ID存在,则任务应使用API放置请求更新配置
  • 如果ID不存在,则应使用API发布请求创建配置

我的解决方案是检查变量result中的JSON是否包含字段"ID:" "output-1"。如果包含,则将变量id_exists的值设置为true,然后将其用作以下任务中的条件。
不幸的是,我不知道使用哪个Ansible模块在JSON中搜索和注册变量。也许有人可以帮助我找到一个解决方案?
可行示例:

- name: "Call API to get JSON data"
  ansible.builtin.uri:
    url: https://example.com/api/outputs
    method: get
  register: result

- name: "Debug: Print all IDs"
  ansible.builtin.debug:
    msg: "{{ result.json | json_query(jmesquery) }}"
  vars:
    jmesquery: "items[*].{ID: id}"

## Task: Check if JSON result contains the ID output-1
## DON'T KNOW HOW :(

- name: "Create new config"
    url: https://example.com/api/outputs
    method: post
    headers:
      Content-Type: application/json
      Authorization: "ApiKey {{ api_key }}"
    body_format: json
    body: |
      {
         "id": "output-1",
         "name": "Name",
         "is_default": false,
         "type": "testtype",
         "config_yaml": "verification_mode: advanced"
      }
  when: id_exists == false

- name: "Update existing config"
  ansible.builtin.uri:
    url: https://example.com/api/outputs/output-1
    method: put
    headers:
      Content-Type: application/json
      Authorization: "ApiKey {{ api_key }}"
    body_format: json
    body: |
      {
         "name": "New Name",
         "is_default": false,
         "type": "testtype",
         "config_yaml": "verification_mode: advanced"
      }
  when: id_exists == true

JSON示例:

{
  "items": [
    {
      "id": "output-1",
      "name": "Output 1",
      "is_default": true,
      "type": "testtype",
      "config_yaml": "verification_mode: basic"
    },
    {
        "id": "output-2",
        "name": "Output 2",
        "is_default": false,
        "type": "testtype",
        "config_yaml": "verification_mode: basic"
      },
    {
      "id": "output-3",
      "name": "Output 3",
      "is_default": false,
      "type": "testtype",
      "config_yaml": "verification_mode: basic"
    }
  ]
}

非常感谢!

h4cxqtbf

h4cxqtbf1#

如果我没理解错的话,下面的内容应该能满足你的期望。我添加了几个例子作为调试任务,让你玩结果,并对如何调用你的API做出自己的决定(我自己不能运行一个例子)
以下行动手册

---
- hosts: localhost
  gather_facts: false

  vars:
    # Faking a return from you API based on example json (minified for legibility)
    result: {"items":[{"id":"output-1","name":"Output 1","is_default":true,"type":"testtype","config_yaml":"verification_mode: basic"},{"id":"output-2","name":"Output 2","is_default":false,"type":"testtype","config_yaml":"verification_mode: basic"},{"id":"output-3","name":"Output 3","is_default":false,"type":"testtype","config_yaml":"verification_mode: basic"}]}

    # What to find in haystack
    needle_id: output-1

    # Note: yes this will work with a register as well as long as it exists
    # at time you evaluate the var.
    # Note: having a key called `items` forces us to use the bracket notation
    # to disambiguate from the `items()` python function
    existing_id: "{{ result['items'] | selectattr('id', '==', needle_id) }}"

  tasks:
    - name: play a task if id exists
      debug:
        msg: id exists
      when: existing_id | length > 0

    - name: play a task if id does not exist
      debug:
        msg: id does not exist
      when: existing_id | length == 0

    - name: play single tasks which will be smart
      vars:
        debug_text: "{{ 'does not exist' if existing_id | length == 0 else 'exists' }}"
      debug:
        msg: "id {{ debug_text }}"

    - name: show the found entry (or empty if not)
      debug:
        var: existing_id | first | d({})

提供:

$ ansible-playbook uri.yml 

PLAY [localhost] ***********************************************************************************************************************************************************************************************************************

TASK [play a task if id exists] ********************************************************************************************************************************************************************************************************
ok: [localhost] => {
    "msg": "id exists"
}

TASK [play a task if id does not exist] ************************************************************************************************************************************************************************************************
skipping: [localhost]

TASK [play single tasks which will be smart] *******************************************************************************************************************************************************************************************
ok: [localhost] => {
    "msg": "id exists"
}

TASK [show the found entry (or empty if not)] ******************************************************************************************************************************************************************************************
ok: [localhost] => {
    "existing_id | first | d({})": {
        "config_yaml": "verification_mode: basic",
        "id": "output-1",
        "is_default": true,
        "name": "Output 1",
        "type": "testtype"
    }
}

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

相关问题