Ansible Playbook notifyを指定してタスクを実行するサンプル

環境
Ubuntu 24.04

概要
[notify] と [handlers] を利用することで、[notify] を指定したタスク実行後に [handlers] で
定義したタスクを実行することができます。

使用例
管理対象ホストの [sshd_config] を編集した後、[sshd] を再起動する
$ vi playbook_test.yml

追記内容

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
- hosts: target_servers
become: yes
become_method: sudo
handlers:
- name: restart sshd
service: name=ssh state=restarted
tasks:
- lineinfile:
path: /etc/ssh/sshd_config
regexp: '^PermitRootLogin'
line: 'PermitRootLogin no'
notify: restart sshd
tags: Edit_sshd_config
- hosts: target_servers become: yes become_method: sudo handlers: - name: restart sshd service: name=ssh state=restarted tasks: - lineinfile: path: /etc/ssh/sshd_config regexp: '^PermitRootLogin' line: 'PermitRootLogin no' notify: restart sshd tags: Edit_sshd_config
- hosts: target_servers
  become: yes
  become_method: sudo
  handlers:
  - name: restart sshd
    service: name=ssh state=restarted
  tasks:
  - lineinfile:
      path: /etc/ssh/sshd_config
      regexp: '^PermitRootLogin'
      line: 'PermitRootLogin no'
    notify: restart sshd
    tags: Edit_sshd_config

playbookを実行する

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$ ansible-playbook playbook_test.yml --ask-become-pass
$ ansible-playbook playbook_test.yml --ask-become-pass
$ ansible-playbook playbook_test.yml --ask-become-pass

結果確認

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$ ansible target_servers -m command -a "grep '^PermitRootLogin' /etc/ssh/sshd_config" -b --ask-become-pass
$ ansible target_servers -m command -a "grep '^PermitRootLogin' /etc/ssh/sshd_config" -b --ask-become-pass
$ ansible target_servers -m command -a "grep '^PermitRootLogin' /etc/ssh/sshd_config" -b --ask-become-pass

 

IT

Posted by arkgame