ansibel的task控制语句

Playbook条件语句

判断在Ansible任务中的使用频率非常高。比如:

  1. web服务器角色都需要安装nginx仓库,但其他的服务器角色并不需要,此时就会用到when判断。
  2. Centos与Ubuntu系统都需要安装httpd服务,那么就需要使用when判断主机系统,然后调用不同的模块执行。

案例

# 1. 根据不同操作系统,安装不同软件包
cat 14.yml
- hosts: lb
  tasks:
    - name: CentOS install cowsay
      yum:
        name: cowsay
        state: present
      when: ( ansible_distribution == "CentOS" ) # 只有centos系统才安装 cowsay

    - name: Ubuntu install cmatrix
      apt:
        name: cmatrix
        state: present
      when: ( ansible_distribution == "Ubuntu" ) # 只有ubuntu系统 才安装 cmatrix

# 在when条件中,加上 小括号
# 在when中变量直接使用,不需要加上 {{}}

# 2. 所有主机名为web|lb的添加nginx仓库,其余的都跳过添加
cat 15.yml 
- hosts: lb
  tasks:
    - name: Add Nginx Yum Repository
      yum_repository:
        name: nginx
        description: Nginx Repository
        enabled: yes
        baseurl: http://nginx.org/packages/centos/7/$basearch/
        gpgcheck: no
      when: (ansible_hostname is match("web")) or (ansible_hostname is match("lb"))

# 3. 根据前者命令执行的结果进行判断,通过register将命令执行结果保存至变量,然后通过when语句进行判断
cat 16.yml 
- hosts: web
  tasks:
    - name: Check nginx Server
      command: systemctl is-active nginx
      ignore_errors: yes
      register: check_nginx

    - name: debug outprint
      debug: var=check_nginx # 通过debug的var输出该变量的所有内容

    - name: nginx Restart       # 如果check_httpd执行命令结果等于0,则执行重启httpd,否则跳过
      systemd: name=nginx state=restarted
      when: check_nginx.rc == 0

# Check Httpd Server 检查nginx是否正在运行 ,运行状态通过register 存放在 check_nginx变量中
# debug outprint 显示下运行信息check_nginx信息显示出来显示执行过程.
# Httpd Restart 重启apache,条件check_nginx.rc == 0

变量.rc通常指的是一个任务执行的返回码(Return Code),也就是任务执行的结果状态码。
这个返回码可以用来判断任务是否成功执行,以及根据不同的返回码执行不同的操作。
通常情况下,返回码为0表示任务执行成功,非0表示任务执行失败。
在Ansible中可以通过使用register关键字将任务的返回码保存到一个变量中,然后进行后续的处理。

Playbook循环语句

有时候我们写playbook的时候发现了很多task都要重复引用某个模块,比如一次启动10个服务,或者一次拷贝10个文件,如果按照传统的写法最少要写10次,这样会显得playbook很臃肿。如果使用循环的方式写playbook,这样可以减少重复使用某个模块。

案例

# 1. 使用循环安装多个服务
cat 18.yml
- hosts: web
  become: yes  # 使用root权限执行
  tasks:
    - name: Install required packages
      yum:
        name: "{{ item }}"     #item 是一个内置变量,用于表示当前循环迭代中的元素。
        state: latest
      loop:
        - openssh-server
        - nginx

# 2. 循环方式创建用户
cat 19.yml 
- hosts: web
  tasks:
    - name: Add Users
      user: name={{ item.name }} uid={{ item.uid }} state=present
      with_items:
        - { name: 'zqf', uid: '777' }
        - { name: 'zqf1' , uid: '888' }
        - { name: 'zqf2' , uid: '666' } 
ansible-playbook 19.yml 

# 3. 批量拷贝文件
cat 20.yml 
- hosts: all
  tasks:
    - name: Configure Rsync Server
      copy: src=/etc/{{ item.src }} dest=/tmp/{{ item.dest }} mode={{ item.mode }}
      with_items:
        - {src: "passwd", dest: "passwd", mode: "0644"}
        - {src: "hosts", dest: "hosts", mode: "0600"}

ansible-playbook 20.yml

Playbook Handlers

Handlers是一个触发器(notify) ,也是一个tasks,只不过是一个特殊的tasks,它是需要被tasks触发才会运行。

只要配置文件发生变更,则会触发handlers执行重启服务操作,如果配置文件不发生任何变化则不重启。

应用场景: notify监控配置文件变化, handlers 实现重启服务/重新挂载....

案例

cat 23.yml 
---
- hosts: web
  vars:
    http_port: 8080
  tasks:
    - name: Add Nginx Yum Repo
      yum_repository:
        name: nginx
        description: nginx repo
        baseurl: http://nginx.org/packages/centos/$releasever/$basearch/
        enabled: yes
        gpgcheck: yes
        gpgkey: https://nginx.org/keys/nginx_signing.key

    - name: Install Nginx
      yum:
        name: nginx
        state: installed

    - name: Index FIle
      copy:
        content: "This is ansible website ansible.oldboy.com"
        dest: /usr/share/nginx/html/index.html

    - name: Copy Nginx.d/conf File
      copy:
        src: ./www.conf
        dest: /etc/nginx/conf.d/default.conf
        backup: yes
      notify: Restart Nginx

    - name: Start Nginx
      systemd:
        name: nginx
        state: started
        enabled: yes

  handlers:
    - name: Restart Nginx
      systemd:
        name: nginx
        state: reloaded

cat www.conf
server {
    listen {{ http_port }};
    server_name ansible.zqf.com;
    location / {
        root /usr/share/nginx/html;
        index index.html;
    }
}

只有当我们修改配置文件才会触发handlers

handlers注意事项

  1. 无论多少个task通知了相同的handlers,handlers仅会在所有tasks结束后运行一次。
  2. 只有task发生改变了才会通知handlers,没有改变则不会触发handlers
  3. 不能使用handlers替代tasks
posted @ 2025-08-23 18:59  阿峰博客站  阅读(10)  评论(0)    收藏  举报