【问题标题】:Ansible loop on URI/URLURI/URL 上的 Ansible 循环
【发布时间】:2023-01-10 02:00:53
【问题描述】:

我正在创建一个剧本,我在其中查询一些 NetBox 子前缀,然后使用每个子前缀的 ID 来查找每个子前缀中的可用 IP(这在 netbox.netbox 模块中不存在)。

为此,我使用 nb_lookup 返回每个子前缀的 ID,然后使用 ansible 自己的 URI 模块查询 NetBox API (api/ipam/prefixes//available-ips/) 并返回可用的 IP。

我的困难是一次查询所有 ID,因为我需要从查询的前缀中获取第一个可用的 IP。

我是 YAML 开发的新手,我真的不知道该怎么做。这是我的代码:

---
- name: NetBox
  hosts: localhost
  connection: local
  gather_facts: no
  collections:
    - netbox.netbox
  tasks:

    - name: "Get Prefixes"
      set_fact:
        prefixes: "{{ query('netbox.netbox.nb_lookup', 'prefixes',
                  api_endpoint='https://url-from-my-nb',
                  api_filter='role=valid status=active',
                  validate_certs=False,
                  token='myToken') }}"


    - name: Teste
      debug:
        msg: "{{ prefixes | json_query('[*].value.id') }}"

    - name: Teste 2
      uri:
        validate_certs: False
        url: "https://url-from-my-nb/api/ipam/prefixes/{{ prefixes | json_query('[*].value.id') }}/available-ips/"
        headers:
          Authorization: "Token myToken"
      register: prefix
      until: prefix

    - name: Teste
      debug:
        msg: "{{ prefix.json[0].address }}"

结果:

PLAY [NetBox] *********************************************************************************************************************************************************************************

TASK [Get Prefixes] *******************************************************************************************************************************************************************************************
/usr/local/lib/python3.9/site-packages/urllib3/connectionpool.py:1045: InsecureRequestWarning: Unverified HTTPS request is being made to host 'url-from-my-nb'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html#ssl-warnings
  warnings.warn(
ok: [localhost]

TASK [Teste] **************************************************************************************************************************************************************************************************
ok: [localhost] => {
    "msg": [
        2,
        4,
        5,
        6,
        11,
        7,
        8,
        10,
        12,
        13,
        14,
        15,
        16,
        17,
        18,
        19,
        20,
        21,
        22,
        23,
        24,
        25,
        26,
        27,
        29,
        51,
        52,
        28
    ]
}

TASK [Teste 2] ************************************************************************************************************************************************************************************************
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: http.client.InvalidURL: URL can't contain control characters. '/api/ipam/prefixes/[2, 4, 5, 6, 11, 7, 8, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 29, 51, 52, 28]/available-ips/' (found at least ' ')
fatal: [localhost]: FAILED! => {"attempts": 1, "changed": false, "elapsed": 0, "msg": "Status code was -1 and not [200]: An unknown error occurred: URL can't contain control characters. '/api/ipam/prefixes/[2, 4, 5, 6, 11, 7, 8, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 29, 51, 52, 28]/available-ips/' (found at least ' ')", "redirected": false, "status": -1, "url": "https://ipam.getcard.com.br/api/ipam/prefixes/[2, 4, 5, 6, 11, 7, 8, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 29, 51, 52, 28]/available-ips/"}

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

如何循环一次查询一个 ID 并检查是否有可用的 IP?

【问题讨论】:

    标签: ansible yaml netbox


    【解决方案1】:

    使用循环修改变量中的所有项目:

        - name: Teste 2
          ansible.builtin.uri:
            validate_certs: false
            url: "https://url-from-my-nb/api/ipam/prefixes/{{ item }}/available-ips/"
            headers:
              Authorization: "Token myToken"
          register: prefix
          with_items: "{{ prefixes | json_query('[*].value.id') }}"
    
    

    编辑:添加如何分组和处理每个结果的示例

    在这种情况下,需要对一些任务进行分组并将其应用于使用 IP 地址获得的每个结果,一种方法是在 include_tasks 任务中设置循环:

    1. 将需要分组的任务分开放在不同的YAML文件中,我们命名为assign_ip.yaml
      ---
      # Content of assign_ip.yaml
      - name: Set the variable with the value received
        ansible.builtin.set_fact:
          prefix_ip: "{{ item }}"
      
      - name: Teste 2
        ansible.builtin.uri:
          validate_certs: false
          url: "https://url-from-my-nb/api/ipam/prefixes/{{ prefix_ip }}/available-ips/"
          headers:
            Authorization: "Token myToken"
        register: prefix
      
      - name: Teste
        ansible.builtin.debug:
          msg: "{{ prefix.json[0].address }}"
      ...
      
      
      1. 在原始剧本中,执行那些任务
      - name: NetBox
        hosts: localhost
        connection: local
        gather_facts: false
        collections:
          - netbox.netbox
        tasks:
      
          - name: "Get Prefixes"
            ansible.builtin.set_fact:
              prefixes: "{{ query('netbox.netbox.nb_lookup', 'prefixes',
                        api_endpoint='https://url-from-my-nb',
                        api_filter='role=valid status=active',
                        validate_certs=False,
                        token='myToken') }}"
      
      
          - name: Teste
            ansible.builtin.debug:
              msg: "{{ prefixes | json_query('[*].value.id') }}"
      
          - name: Check IP
            ansible.builtin.include_tasks:
              file: "assign_ip.yaml"
            with_items: "{{ prefixes | json_query('[*].value.id') }}"
      

    【讨论】:

    • 谢谢,这太棒了,但是现在,我不知道如何捕获地址信息并在找到第一个地址后停止循环。 “{{ prefix.json[0].address }}” 不再有效,我遇到了这个问题:` fatal: [localhost]: FAILED! => {“msg”:“任务包含一个带有未定义变量的选项。错误是:‘prefix’未定义 该错误似乎在“/data/projects/vmware/prefix.yaml”中:第 32 行,第 7 列,但可能 根据确切的语法问题,在文件的其他地方。 违规行似乎是: - 姓名:特斯特 ^ 这里 “}`
    猜你喜欢
    • 2022-11-18
    • 2022-12-01
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-12
    相关资源
    最近更新 更多