【发布时间】:2022-10-23 15:51:13
【问题描述】:
我正在尝试编写一个创建多个用户的剧本,但是当我将变量放在列表形式中时它不起作用。
不工作的剧本
[root@ansible-master playbooks]# cat users_list_new.yml
---
users:
- username:
- amba
- ruchita
[root@ansible-master playbooks]# cat multi_users_new.yml
---
- name: Creating the multi users with a new approach
hosts: california
become: true
vars_files:
- users_list_new.yml
tasks:
- name: Create the user
user:
name: "{{ item.username[0] }}"
loop: "{{ users }}"
它只创建第一个用户,因为我已将下标 0 放在用户模块中。我的问题是我们如何在 username 上创建一个循环。例如,我修改了我的剧本,但它没有用
---
- name: Creating the multi users with a new approach
hosts: california
become: true
vars_files:
- users_list_new.yml
tasks:
- name: Create the user
user:
name: "{{ item }}"
loop: "{{ users.username }}"
当我运行剧本时它抛出了错误
PLAY [Creating the multi users with a new approach] ********************************************************************************************************************
TASK [Gathering Facts] *************************************************************************************************************************************************
ok: [10.128.0.5]
TASK [Create the user] *************************************************************************************************************************************************
fatal: [10.128.0.5]: FAILED! => {"msg": "'list object' has no attribute 'username'"}
PLAY RECAP *************************************************************************************************************************************************************
10.128.0.5 : ok=1 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0
[root@ansible-master playbooks]#
请帮我找出解决方案
【问题讨论】:
-
我思考(无法验证 atm,不在工作中)您只需要展平外部列表:去掉用户名前面的连字符。