Ansible way to stop a service only if it needs to

2020-04-08 12:57发布

In an ansible playbook I want to stop MariaDB if an upgrade is needed (restart from the RPM package does not always work in my situation). I'm quite new to ansible.

I came up with this:

- name: "Check if MariaDB needs to be upgraded"
  shell: "yum check-update MariaDB-server|grep MariaDB|wc -l"
  register: needs_update

- name: "Stop mysql service"
  service:
  name: mysql
  state: stopped
when: needs_update.stdout == "1"

Is there a better way to do this then by executing a shell command? When running it I get warnings:

TASK [mariadb_galera : Check if MariaDB needs to be upgraded]    ******************
changed: [139.162.220.42] => {"changed": true, "cmd": "yum check-update MariaDB-server|grep MariaDB|wc -l", "delta": "0:00:00.540862", "end": "2017-03-01 13:03:34.415272", "rc": 0, "start": "2017-03-01 13:03:33.874410", "stderr": "", "stdout": "0", "stdout_lines": ["0"], "warnings": ["Consider using yum module rather than running yum"]}
 [WARNING]: Consider using yum module rather than running yum

Thank you!

2条回答
Animai°情兽
2楼-- · 2020-04-08 13:22

The best way to handle this is use a "handler" eg something along the lines of

tasks:
  - name: Update db
    yum: name=MariaDB-server state=latest
    notify:
      - stop db

handlers:
  -  name: stop db  
     service: name=MariaDB-server state=stopped

You can specify multiple handlers if you need to do multiple things, but if you just want to restart the db, use restarted instead of stopped

http://docs.ansible.com/ansible/playbooks_best_practices.html

查看更多
劳资没心,怎么记你
3楼-- · 2020-04-08 13:45

You can hide warning with:

- name: "Check if MariaDB needs to be upgraded"
  shell: "yum check-update MariaDB-server|grep MariaDB|wc -l"
  args:
    warn: false
  register: needs_update

Or you can trick Ansible to execute yum task in check_mode:

- name: "Check if MariaDB needs to be upgraded (CHECK MODE!)"
  yum:
    name: MariaDB-server
    state: latest
  check_mode: yes
  register: needs_update_check

- name: "Stop mysql service"
  service:
    name: mysql
    state: stopped
  when: needs_update_check | changed

Please, test this code before use.

查看更多
登录 后发表回答