如何从字典var中获取格式化行?

问题描述 投票:0回答:1

我对 Ansible 还很陌生,我不知道如何正确使用它。

首先,我以实现这个字典 var 为例。有 2 个值,但可以是更大的数字:

tf_ETCD:
  1:
    hostname: Etcd01
    ip: 192.168.1.141
  2:
    hostname: Etcd02
    ip: 192.168.1.142

我希望结果的格式如下:

{{ tf_ETCD1_Host }}=https://{{ tf_ETCD1_IP }}:2380,{{ tf_ETCD2_Host }}=https://{{ tf_ETCD2_IP }}:2380

所以我通过以下代码循环列表来得到它:

    - name: Format each value
      set_fact:
        etcd: "{{ item.value.hostname }}=https://{{ item.value.ip }}:2380,"
      loop: "{{ lookup('ansible.builtin.dict', tf_ETCD) }}"
      register: etcd_query

    - name: Examine the joined string
      debug:
        msg: "{{ etcd_query['results'][0]['ansible_facts']['etcd'] }}{{ etcd_query['results'][1]['ansible_facts']['etcd'] }}"

结果给了我:

TASK [Format each values] **********************************************************************************************
ok: [] => (item={'key': 1, 'value': {'hostname': 'Etcd01', 'ip': '192.168.1.141'}})
ok: [] => (item={'key': 2, 'value': {'hostname': 'Etcd02', 'ip': '192.168.1.142'}})

TASK [Examine the joined string] ***************************************************************************************
ok: [] => {
    "msg": "Etcd01=https://192.168.1.141:2380,Etcd02=https://192.168.1.142:2380,"
}

我无法弄清楚如何在“检查连接的字符串”游戏中执行“foreach 循环结果”。

如果您能给我一个提示或我正在寻找的概念,您将拯救我。

loops dictionary ansible jinja2 var
1个回答
0
投票

弄清楚如何在我的“检查连接的字符串”游戏中执行“foreach 循环结果”...

一个最小的示例手册

---
- hosts: localhost
  become: false
  gather_facts: false

  vars:

    tf_ETCD:
      1:
        hostname: Etcd01
        ip: 192.0.2.1
      2:
        hostname: Etcd02
        ip: 192.0.2.2

  tasks:

  - debug:
      msg: "{{ tf_ETCD[ansible_loop.index] }}"
    loop: "{{ range(0, tf_ETCD | length, 1) | list }}"
    loop_control:
      extended: true

  - set_fact:
      etcd: "{{ etcd | d('') + tf_ETCD[ansible_loop.index].hostname ~ '=https://' ~ tf_ETCD[ansible_loop.index].ip ~ ':2380,' }}"
    loop: "{{ range(0, tf_ETCD | length, 1) | list }}"
    loop_control:
      extended: true

  - debug:
      msg: "{{ etcd }}"

将产生

的输出
TASK [debug] ******************************************************
ok: [localhost] => (item=0) =>
  msg:
    hostname: Etcd01
    ip: 192.0.2.1
ok: [localhost] => (item=1) =>
  msg:
    hostname: Etcd02
    ip: 192.0.2.2

TASK [debug] ******************************************************
ok: [localhost] =>
  msg: Etcd01=https://192.0.2.1:2380,Etcd02=https://192.0.2.2:2380,

一些提示

© www.soinside.com 2019 - 2024. All rights reserved.