Ansible-在用户模块内部使用for循环

时间:2018-11-22 12:04:36

标签: ansible

我最近发现在Ansible中使用for循环,对此感到非常兴奋。 试图在调试模块中使用它,并且效果很好,但是当我尝试在“用户”模块中使用相同的控件时,控制流无法识别用户模块的“名称”关键字。下面是我的诗,

- hosts: testservers
  tasks:
  - name: Setting user facts
    set_fact:
      username: "{{ lookup('ini', 'name section=userDetails file=details.ini') }}"
      userpass: "{{ lookup('ini', 'password section=userDetails file=details.ini') }}"

  - name: User creation
    become: true
   # debug:
   #    msg: |
   #     {% for x,y in item.1,item.2 %}
   #     {{ x }} is the username and its password is {{ y }}
   #     {% endfor %}
   # with_items: 
   #     - { 1: "{{ username.split(',') }}", 2: "{{ userpass.split(',') }}" }
    user: |
      {% for x,y in item.1,item.2 %}
      name: "{{ x }}"
      password: "{{ y }}"
      {% endfor %}
    with_items:
        - { 1: "{{ username.split(',') }}", 2: "{{ userpass.split(',') }}" }

Details.ini文件的内容如下

#User basic details
[userDetails]
name=vasanth,vasanthnagkv
password=vasanth12,pass2

上面的注释部分工作正常。但未注释的部分将引发以下错误

failed: [10.0.0.47] (item={1: [u'vasanth', u'vasanthnagkv'], 2: [u'vasanth12', u'pass2']}) => {
    "changed": false, 
    "invocation": {
        "module_args": {
            "append": false, 
            "create_home": true, 
            "force": false, 
            "move_home": false, 
            "non_unique": false, 
            "remove": false, 
            "ssh_key_bits": 0, 
            "ssh_key_comment": "ansible-generated on APUA-02", 
            "ssh_key_type": "rsa", 
            "state": "present", 
            "system": false, 
            "update_password": "always"
        }
    }, 
    "item": {
        "1": [
            "vasanth", 
            "vasanthnagkv"
        ], 
        "2": [
            "vasanth12", 
            "pass2"
        ]
    }, 
    "msg": "missing required arguments: name"
}
    to retry, use: --limit @/home/admin/ansiblePlaybooks/userCreation/userCreate.retry

PLAY RECAP ************************************************************************************************************************************************************************************
10.0.0.47                  : ok=2    changed=0    unreachable=0    failed=1 

在这里感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

此行user: |表示您使用块样式指示器:https://yaml-multiline.info/

将字符串传递给 user 模块

由于Ansible只会将其视为字符串,因此您没有将必需的name参数传递给user模块

尝试在第一个任务中查找后拆分名称,以便您可以看到名称和密码列表:

- name: Setting user facts
  set_fact:
    username: "{{ lookup('ini', 'name section=userDetails file=details.ini').split(',') }}"
    userpass: "{{ lookup('ini', 'password section=userDetails file=details.ini').split(',') }}"

一旦拥有用户名和密码列表,就可以通过以下方式使用这两个变量:

    - user:
        name: "{{ item }}"
        password: "{{ userpass[index] }}"
      loop: "{{ username }}"
      loop_control:
        index_var: index