1. with_items
1.1 定义用户信息为列表模式
[root@clinet ansible_2]# cat vars_file/file1.yml
users:
- name: bob
shell: /sbin/nologin
home: /home/bob
state: present
- name: alice
home: /tmp/alice
state: present
- name: tom
shell: /bin/bash
state: present
[root@clinet ansible_2]#
1.2 编写playbook,使用with_items循环
[root@clinet ansible_2]# cat yum_file/with_x/with_x.yml
- hosts: mdb
gather_facts: no
vars_files:
- /root/ansible_test/ansible_2/vars_file/file1.yml
tasks:
- name: create user group
group:
name: "{{ item['name'] }}"
state: "{{ item['state'] }}"
with_items: "{{ users }}"
- name: create user with_items
user:
name: "{{ item['name'] }}"
shell: "{{ item['shell'] |default(omit) }}"
home: "{{ item['home'] |default(omit) }}"
state: "{{ item['state'] }}"
with_items: "{{ users }}"
[root@clinet ansible_2]#
1.3 也可以为loop循环
- hosts: mdb
gather_facts: no
vars_files:
- /root/ansible_test/ansible_2/vars_file/file1.yml
tasks:
- name: create user group
group:
name: "{{ item['name'] }}"
state: "{{ item['state'] }}"
loop: "{{ users }}"
- name: create user loop
user:
name: "{{ item['name'] }}"
shell: "{{ item['shell'] |default(omit)}}"
home: "{{ item['home'] |default(omit) }}"
state: "{{ item['state'] }}"
loop: "{{ users }}"
2. with_dict
2.1 定义用户信息为字典模式
[root@clinet ansible_2]# cat vars_file/file2.yml
users:
xhz:
shell: /sbin/nologin
home: /home/xhz
state: present
flf:
home: /tmp/flf
state: present
wsz:
shell: /bin/bash
state: present
[root@clinet ansible_2]#
2.2 编写playbook,使用with_dict循环
[root@clinet ansible_2]# cat yum_file/with_x/with_dict.yml
- hosts: mdb
gather_facts: no
vars_files:
- /root/ansible_test/ansible_2/vars_file/file2.yml
tasks:
- name: create user group
group:
name: "{{ item['key'] }}"
state: "{{ item['value']['state'] }}"
with_dict: "{{ users }}"
- name: create user with_dic
user:
name: "{{ item['key'] }}"
shell: "{{ item['value']['shell'] |default(omit)}}"
home: "{{ item['value']['home'] |default(omit) }}"
state: "{{ item['value']['state'] }}"
with_dict: "{{ users }}"
[root@clinet ansible_2]#
2.3 也可以为loop | dict2items
- hosts: mdb
gather_facts: no
vars_files:
- /root/ansible_test/ansible_2/vars_file/file2.yml
tasks:
- name: create user group
group:
name: "{{ item['key'] }}"
# state: "{{ item['value']['state'] }}"
with_dict: "{{ users |dict2items }}"
- name: create user with_x
user:
name: "{{ item['key'] }}"
shell: "{{ item['value']['shell'] |default(omit)}}"
home: "{{ item['value']['home'] |default(omit) }}"
state: "{{ item['value']['state'] }}"
loop: "{{ users |dict2items }}"
总结:
1. with_items主要是对列表,而with_dict主要是对字典;
2. "{{ item['value']['home'] |default(omit) }}"表示变量item['value']['home'] 不存在时,则使用默认变量;default(omit)表示系统中的默认值。也可以写为default(‘xhz123’),则表示变量item['value']['home'] 不存在时,将变量值设置为xhz123