ansible学习笔记-流程控制(综合案例)

案例介绍

批量创建用户,在根据不同系统安装软件,ubuntu安装nginx,centos安装httpd,再拷贝一个文件到指定文件夹中,检查nginx的配置文件是否正确,最后根据操作系统来启动nginx或者httpd。

- name: install nginx or httpd
  hosts: all
  remote_user: root
  vars:
    username:
      - user1
      - user2
      - user3
  tasks:
    - name: create user
      user:
        name: "{{ item }}"
        home: /home/{{ item }}
      loop: "{{ username }}"
    - name: install nginx ubuntu
      apt:
        name: nginx
        state: present
        update_cache: yes
      when:
        - ansible_pkg_mgr == 'apt'
      notify: ubuntu
    - name: install httpd centos
      yum:
        name: httpd
        state: present
      when:
        - ansible_pkg_mgr == 'yum'
      notify: centos
    - name: copy file
      copy:
        src: /root/alonzo.txt
        dest: /root/alonzo.txt
    - name: check nginx config
      shell: /usr/sbin/nginx -t
      register: nginx_check_config
      tags: restart_nginx
  handlers:
    - name: ubuntu
      service:
        name: nginx
        state: restarted
      when:
        - nginx_check_config.rc == 0
      tags: restart_nginx
    - name: centos
      service:
        name: httpd
        state: restarted

注意:

  • loop代表循环,使用前因提前定义变量, {{ item }}代表loop从每次循环中提取出来的变量,固定名称
  • when代表判断,可使用自己注册的变量也可以使用facts变量,使用facts变量记得开启gather_facts,when支持的判断如下
==
!=
> >=
< <=
is defined
is not defined
true
false
⽀持逻辑运算符: and or
  • handlers是另一种任务列表,与tasks平级,所以handlers中可以有多个任务,被tasks中不同的任务notify,执行完handlers后将继续执行playbook后续任务
  • tags是标签,在执行命令的时候加上-t 标签名,就可以执行只打标签的任务,在handlers中定义的tags是不生效的
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。