【问题标题】:ansible : how to iterate over a listansible :如何遍历列表
【发布时间】:2022-06-22 02:15:18
【问题描述】:

我在迭代列表时遇到了麻烦。欢迎任何帮助。

我有两台主机:一台在 Prod 中,另一台在 Test 中。 “test”和“prod”在目标主机(节点)上可用的事实文件中定义。


[node]
type= prod 

or 
[node]
type= test

我定义了以下变量:

users:
  - username: A
    password: password_A
    update_password: always
    home: /home/A
    state: present
    nodes: ['test', 'prod']


  - username: B 
    password: passwd_B
    update_password: always
    home: /home/B
    state: present
    nodes: ['test']

我的“A”用户应安装在生产和测试主机上。
“B”用户仅在测试主机上。

此后,如果我使用单个值进行节点定义,则该角色可以正常工作。 节点:在线或节点离线

 

- name: create users
  ansible.builtin.user:
    name: "{{ item.username }}"
    password: "{{ item.password }}"
    uid: "{{ item.uid }}"
    home: "{{ item.home }}"
    create_home: yes
    group : "{{ item.group }}"
    shell: /bin/bash
    state: present
    expires: -1
  with_items:
      - "{{ users }}"
  when:  item.nodes  ==  ansible_local['myfact']['node"']['type']
 

我不知道如何循环节点列表的每个值并将它们与本地事实值进行比较。节点[0] ,节点[1] ...(我可以有其他类型的主机,不仅是生产和测试) 我尝试了子元素但没有成功。

我不确定是不是很清楚?! BR。

【问题讨论】:

    标签: ansible


    【解决方案1】:

    你可以像这样循环使用产品:

    - hosts: localhost
      gather_facts: false
      vars:
        type: test
        users:
          - username: A
            password: password_A
            update_password: always
            home: /home/A
            state: present
            nodes: ['test', 'prod']
    
          - username: B 
            password: passwd_B
            update_password: always
            home: /home/B
            state: present
            nodes: ['test']
    
      tasks:
        - name: display
          debug:
            msg: "{{ item.0.username }} created in {{ _node }} --> belongs to {{ _nodes }}"
          loop: "{{ users | product([type]) }}"
          vars:
            _nodes: "{{ item.0.nodes }}"
            _node: "{{ item.1 }}"
          when: _node in _nodes
    

    结果:

    "msg": "A created in test --> belongs to ['test', 'prod']"
    "msg": "B created in test --> belongs to ['test']"
    

    在你的情况下,你这样做:

    loop: "{{ users | product([ansible_local['myfact']['node"']['type']]) }}"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-14
      • 1970-01-01
      • 2013-01-26
      • 1970-01-01
      相关资源
      最近更新 更多