ansible的loop循环
示例代码:
---
- name: test use var
hosts: webserver
vars_files: vars_playbook.yml
tasks:
- name: install pkg
yum:
name: "{{ item }}"
loop:
- "{{ web_pkg }}"
- "{{ firewall_pkg }}"
- "{{ python_pkg }}"
- name: service
service:
name: "{{ item }}"
enabled: true
state: started
loop:
- "{{ firewall_servcie }}"
- "{{ web_service }}"
在vars-file中定义变量文件,安装pkg
查看vars_file内容:cat vars_playbook.yml
web_pkg:
- httpd
- python3-PyMySQL
- mariadb-server
web_service:
- httpd
- mariadb
playbook内容:cat playbook.yml
---
- name: test use var
hosts: webserver
vars_files: vars_playbook.yml
tasks:
- name: install pkg
yum:
name: "{{ item }}"
loop: "{{ web_pkg }}"
- name: service
service:
name: "{{ item }}"
enabled: true
state: started
loop: "{{ web_service }}"
执行结果
[student@workstation data-variables]$ ansible-playbook playbook.yml
PLAY [test use var] ***********************************************************************
TASK [Gathering Facts] ********************************************************************
ok: [servera.lab.example.com]
TASK [install pkg] ************************************************************************
ok: [servera.lab.example.com] => (item=httpd)
ok: [servera.lab.example.com] => (item=python3-PyMySQL)
ok: [servera.lab.example.com] => (item=mariadb-server)
TASK [service] ****************************************************************************
ok: [servera.lab.example.com] => (item=httpd)
changed: [servera.lab.example.com] => (item=mariadb)
PLAY RECAP ********************************************************************************
servera.lab.example.com : ok=3 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
卸载pkg
变量文件不变cat remove_pkg.yml
web_pkg:
- httpd
- python3-PyMySQL
- mariadb-server
web_service:
- httpd
- mariadb
编写remove_pkg.yaml
---
- name: remove_pkg
hosts: webserver
vars_files:
- vars_playbook.yml
tasks:
- name: remove_pkg
yum:
name: "{{ item }}"
state: removed
loop: "{{ web_pkg }}"
执行playbookremove_pkg.yaml
[student@workstation data-variables]$ ansible-playbook remove_pkg.yml
PLAY [remove_pkg] *************************************************************************
TASK [Gathering Facts] ********************************************************************
ok: [servera.lab.example.com]
TASK [remove_pkg] *************************************************************************
changed: [servera.lab.example.com] => (item=httpd)
changed: [servera.lab.example.com] => (item=python3-PyMySQL)
changed: [servera.lab.example.com] => (item=mariadb-server)
PLAY RECAP ********************************************************************************
servera.lab.example.com : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
考试可能出现的内容
考试给的变量矩阵
解题方法