ansible笔记第三章(Ansible--tasks任务控制)
(1)when判断语句
实践案例一、根据不同操作系统,安装相同的软件包
[root@m01 project1]# cat tasks_1.yml
- hosts: oldboy
tasks:
- name: Installed {{ ansible_distribution }} Httpd Server
yum: name=httpd state=present
when: ( ansible_distribution == "CentOS" )
- name: Installed {{ ansible_distribution }} Httpd2 Server
yum: name=httpd2 state=present
when: ( ansible_distribution == "Ubuntu" )
实践案例二、为所有的web主机名添加nginx仓库,其余的都跳过添加
[root@m01 project1]# cat tasks_2.yml
- hosts: all
tasks:
- name: Create YUM Repo
yum_repository:
name: ansible_nginx
description: ansible_test
baseurl: https://mirrors.oldboy.com
gpgcheck: no
enabled: no
when: ( ansible_fqdn is match ("web*"))
#### 其中ansible_fqdn是fact系统变量里的参数,也可以not is match()。
-----------------------------其中的rc是注册变量check_httpd字典里的一个值,反映命令是否执行成功。
(2)循环语句 with_items
实践案例一、使用循环启动多个服务
[root@m01 project1]# cat tasks_4.yml
- hosts: webserver
tasks:
- name: Service Nginx Server
service: name={{ item }} state=restarted
with_items:
- nginx
- php-fpm
实践案例二、使用变量字典循环方式批量创建用户
[root@m01 project1]# cat tasks_6.yml
- hosts: webserver
tasks:
- name: Create User
user: name={{ item.name }} groups={{ item.groups }} state=present
with_items:
- { name: 'www', groups: 'bin'}
- { name: 'test', groups: 'root'}
(3) handlers 触发器
notify监控 --->通知 ---> Handlers触发
使用template模板,引用上面vars定义的变量至配置文件中
force_handlers: yes #强制调用触发器,即使有报错。
- name: Configure Httpd Server
template: src=./httpd.conf dest=/etc/httpd/conf/httpd.conf
notify: #调用名称为Restart Httpd Server的handlers(可以写多个)
- Restart Httpd Server
如果配置文件发生变化会调用该handlers下面的对应名称的task
handlers:
- name: Restart Httpd Server
service: name=httpd state=restarted
(4)tags标签
指定执行某个tags标签
[root@m01 docs1]# ansible-playbook -i hosts nginx_php.yml -t "test_user"
忽略执行某个tags标签
[root@m01 docs1]# ansible-playbook -i hosts nginx_php.yml --skip-tags "test_user"
(5)include包含
1)编写restart_httpd.yml文件
[root@ansible project1]# cat restart_httpd.yml #注意这是一个tasks所有没有play的任何信息
- name: Restart Httpd Server
service: name=httpd state=restarted
2)A Project的playbook如下
[root@ansible project1]# cat a_project.yml
- hosts: webserver
tasks:
- name: A Project command
command: echo "A"
- name: Restart httpd
include_tasks: restart_httpd.yml
(6)change_when语句
案例、使用changed_when检查tasks任务返回的结果
[root@m01 project1]# cat tasks_12.yml
- hosts: webserver
tasks:
- name: Installed Nginx Server
yum: name=nginx state=present
- name: Configure Nginx Server
copy: src=./nginx.conf.j2 dest=/etc/nginx/nginx.conf
notify: Restart Nginx Server
- name: Check Nginx Configure Status
command: /usr/sbin/nginx -t
register: check_nginx
changed_when:
- ( check_nginx.stdout.find('successful'))
- false
- name: Service Nginx Server
service: name=nginx state=started
handlers:
- name: Restart Nginx Server
service: name=nginx state=restarted