ansible任务控制

任务控制方式

   1.条件判断 when

- hosts: web
  tasks:

    -name: Install httpd server
     yum: name=httpd state=present
     when: ( ansible_distribution == "centos7" )

    -name: Install apache server
     yum: name=httpd2 state=present
     when: ( ansible_distribution == "ubuntu" )

- hosts: all
  tasks:
    -name: create yum repo
     yum_repository:
       name: ansible_nginx
       description: ansible_nginx
       baseurl: http://mirros.list.com
     when: ( ansible_fqdn is match("app*")) or ( ansible_fqdn is match("db*"))

    -name: check httpd server
     command: systemctl is-actived httpd
     ignore_errors: yes
     register: checkhttpd

    -name: httpd restart
     service: name=httpd state=present
     when: check_httpd.rc == 0
when控制
- name: "supervisor start es data node"
  shell: "supervisorctl update"
  ignore_errors: True
  tags: elastic

- name: "supervisor start es master node"
  shell: "supervisorctl restart elasticsearch"
  when: 
    - ansible_default_ipv4.address  == groups['elastic-master'][0]
  ignore_errors: True
  tags: elastic
when判断主机IP
when:
  - ansible_distribution in ['RedHat', 'CentOS', 'ScientificLinux']
  - ansible_distribution_version|version_compare('15.04', '>=')
when多条件判断

2.循环语句 with_items

- hosts: web
  tasks:
    -name: service {{ item }} server
     service: name={{ item }} state=restarted
     with_items:
       - nginx
       - mysql

- hosts: db
  tasks:
    - name: create user
      user: name={{ item.name }} group={{ item.group }} state=present
      with_items:
        - { name: 'www', group: 'bin' }
        - { name: 'test', group: 'root' }
循环

   3.触发器 handlers
      用来实现修改配置文件以后,自动触发服务的重启操作.  notify负责监控 > 通知 > handlers负责触发执行

      实现配置管理

#当所有正常的task全部执行结束后才会调用notify中的handlers,handlers是排在最后被执行的.跟它定义的位置无关
#所有的handlers只会在最后被调用一次 不管你在task中定义了多少次

- hosts: redis
  tasks:
    - name: copy redis config
      template: src=./etc/redis.conf dest=/etc/redis.conf
      notify: service restart redis
      notify:
        - service restart redis
        - service restart java

  handlers:
    - name: service restart redis
      service: name=redis state=restarted
    - name: service restart app
      service: name=java state=restarted
配置管理

     

   4.标签 tags
       用来在调试Playbook的时候根据tags执行指定的tasks,而不是一次执行playbook中的所有task

   5.包含 include
       多个项目直接可以包含同一个task 用来减少同样内容task的编写量

       

       

   6.错误忽略 ignore_errors

      强制触发handlers,默认handlers是要所有的task全部执行成功最后才执行handlers
      如果某个task执行失败 那么最后的handlers是不会触发的   force_handlers: yes

         

   7.错误处理 changed_when

         

         

         

原文地址:https://www.cnblogs.com/yxh168/p/14784969.html