大网数据广告活动
服务器运维问答

How should i write the yaml file for use in ansible variable?

· 52CE 我爱测

I started to deploying an ansible server, and i was trying to create 5 users in the client hosts, through a playbook (add5userslist.yaml), with a loop that uses variables in a list from another file (userslist.yaml), but isnt wor…

问题原文

原帖链接 · SergioDG · CC BY-SA 4.0

I started to deploying an ansible server, and i was trying to create 5 users in the client hosts, through a playbook (add5userslist.yaml), with a loop that uses variables in a list from another file (userslist.yaml), but isnt working.

And...this is what ansible retrieves when i try to use this playbook with that list:

Seems like the problem is the list used in fact ansible doesnt even sees that as a list, but well im new in ansible and dont know what should that file have.

the playbook code:

- hosts: GrupoPrincipal

  tasks:
    - include_vars:
        file: /etc/ansible/playbooks/userslist.yaml
        name: userslist
    - name: Add 5 users from a list
      ansible.builtin.user:
       name: "{{ item.name }}"
       password: "{{'abc123.' | password_hash('sha512')}}"
      loop: "{{ userslist }}"

the userlist.yaml code is only this, is the only thing that worked a little:

name: 'user1'
name: 'user2'
name: 'user3'
name: 'user4'
name: 'user5'

@Martin helped me with the problem above, but now im trying with more than 1 item type, doenst seems to work, here is how i have the new code

- hosts: GrupoPrincipal

  tasks:
    - include_vars:
        file: /etc/ansible/playbooks/userslist.yaml
        name: userslist

    - name: Add 5 users from a list and put them in groups
      ansible.builtin.user:
       name: "{{ item.names }}"
       groups: "{{ item.groups }}"
       password: "{{'abc123.' | password_hash('sha512')}}"
      loop:
      - { names: '{{ userslist.names }}', groups: '{{ userslist.groups }}' }

and the new list yaml:

names:
  - user1
  - user2
  - user3
  - user4
  - user5
groups:
  - users
  - users
  - users
  - users
  - users

已采纳解答

原帖链接 · Martin · CC BY-SA 4.0

You're telling to your task to loop over an object who's representing your files variables but loop require a list.

You have to define your var_files like :

users:
  - user1
  - user2

And then in your main playbook, removing "item.name" in order to just use the item, and precise inside your varfile what variable you use :

- hosts: GrupoPrincipal

  tasks:
    - include_vars:
        file: /etc/ansible/playbooks/userslist.yaml
        name: userslist

    - name: Add 5 users from a list
      ansible.builtin.user:
       name: "{{ item }}"
       password: "{{'abc123.' | password_hash('sha512')}}"
      loop: "{{ userslist.users }}"

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2021-11-22)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。