teat.yml
- hosts: all
become: true
vars:
config:
path: /etc/hosts
marker: "ANSIBLE MANAGED BLOCK"
content: |
192.168.10.10 web01
192.168.10.11 web02
tasks:
# 1. バックアップ取得
- name: バックアップ取得
copy:
src: "{{ config.path }}"
dest: "{{ config.path }}.{{ ansible_date_time.iso8601_basic }}"
remote_src: yes
# 2. 事前チェック(変更が必要か)
- name: 事前チェック(check_mode)
blockinfile:
path: "{{ config.path }}"
marker: "# {mark} {{ config.marker }}"
block: "{{ config.content }}"
check_mode: yes
register: precheck
# 3. 条件付きで反映
- name: 設定反映
blockinfile:
path: "{{ config.path }}"
marker: "# {mark} {{ config.marker }}"
block: "{{ config.content }}"
when: precheck.changed
# 4. 事後チェック(反映確認)
- name: 事後チェック(check_mode)
blockinfile:
path: "{{ config.path }}"
marker: "# {mark} {{ config.marker }}"
block: "{{ config.content }}"
check_mode: yes
register: postcheck
- name: 反映確認
assert:
that:
- postcheck.changed == false
fail_msg: "設定が正しく反映されていません: {{ config.path }}"
# 5. 管理ブロック表示
- name: 管理ブロック表示
command: >
sed -n '/BEGIN {{ config.marker }}/,/END {{ config.marker }}/p'
{{ config.path }}
changed_when: false