Ravindra BagaleCourses & study guides मराठी

Chapter 11: Ansible Introduction

DevOps

11.9b Check mode and diff

Why: the problem

Suppose we are at HDFC Bank and a playbook must change the SSH config on 50 production servers. One mistake locks everyone out. You want to see exactly what would change before it changes. Check mode (--check) runs the playbook as a test and changes nothing. Diff mode (--diff) shows the before and after lines of each file. Together they are your preview button.

What we will build

You will preview an SSH hardening change with --check --diff, read the diff output, handle tasks that cannot run in check mode, and use check mode on a schedule to find drift on web servers.

What: every term in plain English

  • Check mode — A dry run: Ansible reports what would change but changes nothing.
  • Diff mode — Shows file changes as before (-) and after (+) lines.
  • check_mode: false — Forces one task to really run even in check mode, for safe read-only commands.
  • check_mode: true — Forces one task to always be a dry run.
  • ansible_check_mode — A variable that is true during a check run.
  • Drift report — A scheduled check run that lists servers that no longer match the code.
Write the hardening task Preview with check and diff Read the recap Try on one server first Check you can still log in Roll out to the rest Scheduled drift check
Check and diff: preview, then one host, then all

How: step by step

  1. Write the hardening task

    vim harden_ssh.yml
    

    What it does: Set PasswordAuthentication no.

    Output

    (file edit)
    
  2. Preview with check and diff

    ansible-playbook harden_ssh.yml --check --diff
    

    What it does: Nothing changes yet.

    Output

    --- before: /etc/ssh/sshd_config
    +++ after: /etc/ssh/sshd_config
    -PasswordAuthentication yes
    +PasswordAuthentication no
    
  3. Read the recap

    (look at the end)
    

    What it does: changed here means would change.

    Output

    web1 : ok=2 changed=1 unreachable=0 failed=0
    
  4. Try on one server first

    ansible-playbook harden_ssh.yml --limit web1
    

    What it does: Real run on one host.

    Output

    web1 : ok=3 changed=1
    
  5. Check you can still log in

    ssh ubuntu@10.0.1.11 echo still-in
    

    What it does: Key login must work.

    Output

    still-in
    
  6. Roll out to the rest

    ansible-playbook harden_ssh.yml
    

    What it does: Now all servers.

    Output

    web2 : ok=3 changed=1
    
  7. Scheduled drift check

    ansible-playbook site.yml --check --diff | tee drift-$(date +%F).log
    

    What it does: Run nightly; changed>0 means drift.

    Output

    web2 : ok=12 changed=1
    

Example 1: SSH hardening previewed with --check --diff, with validate

Stack. OpenSSH on Ubuntu

Goal. SSH hardening previewed with --check --diff, with validate.

harden_ssh.yml

- hosts: web
  become: true
  tasks:
    - name: No password logins
      ansible.builtin.lineinfile:
        path: /etc/ssh/sshd_config
        regexp: '^#?PasswordAuthentication'
        line: PasswordAuthentication no
        validate: /usr/sbin/sshd -t -f %s
      notify: Reload sshd
  handlers:
    - name: Reload sshd
      ansible.builtin.service: { name: ssh, state: reloaded }

What each line does

  • regexp — Find the old line, even if it is commented.
  • validate: sshd -t -f %s — Test the new file before saving it.
  • Reload sshd — Keep current sessions open.

Green output

$ ansible-playbook harden_ssh.yml --check --diff
TASK [No password logins] ******************************
--- before: /etc/ssh/sshd_config (content)
+++ after: /etc/ssh/sshd_config (content)
@@ -57 +57 @@
-#PasswordAuthentication yes
+PasswordAuthentication no
changed: [web1]
RUNNING HANDLER [Reload sshd] **************************
changed: [web1]
PLAY RECAP *********************************************
web1 : ok=3 changed=2 unreachable=0 failed=0

Expected result. You saw the exact line before touching prod.

Example 2: A read-only command that must run in check mode, and a task skipped in check mode

Stack. Node app, systemd

Goal. A read-only command that must run in check mode, and a task skipped in check mode.

release_check.yml

- hosts: web
  become: true
  tasks:
    - name: Read current app version (safe, always run)
      ansible.builtin.command: cat /opt/badge-api/VERSION
      register: ver
      check_mode: false
      changed_when: false
    - name: Show version
      ansible.builtin.debug: { msg: "running {{ ver.stdout }}" }
    - name: Restart app (skip in check mode)
      ansible.builtin.systemd: { name: badge-api, state: restarted }
      when: not ansible_check_mode

What each line does

  • check_mode: false — Run this read-only task for real.
  • when: not ansible_check_mode — Skip during a dry run.

Green output

$ ansible-playbook release_check.yml --check
ok: [web1] => { "msg": "running 1.4.2" }
TASK [Restart app (skip in check mode)] ****************
skipping: [web1]

Expected result. Later tasks get real data; dangerous tasks are skipped.

Example 3: Nightly drift report for a 3-tier app, saved and counted

Stack. Web, app and MySQL tiers, cron

Goal. Nightly drift report for a 3-tier app, saved and counted.

drift.sh

#!/usr/bin/env bash
# run from cron or a CI schedule on the control node
set -uo pipefail
cd /opt/shop-ansible
ansible-playbook site.yml --check --diff > /var/log/ansible/drift-$(date +%F).log 2>&1
grep -E "changed=[1-9]" /var/log/ansible/drift-$(date +%F).log || echo "no drift"

What each line does

  • --check --diff — Preview only.
  • grep changed=[1-9] — Lines for hosts that drifted.

Green output

web2 : ok=18 changed=1 unreachable=0 failed=0
db1  : ok=11 changed=2 unreachable=0 failed=0

Expected result. web2 and db1 were changed by hand; read the log to see which files.

Verify: did it work?

  1. Nothing changed after check

    ansible web -a "grep ^PasswordAuthentication /etc/ssh/sshd_config"
    

    What it does: After only --check, the old value stays.

    Output

    #PasswordAuthentication yes
    
  2. After real run

    ansible web -a "sshd -T" --become | grep passwordauthentication
    

    What it does: Effective setting.

    Output

    passwordauthentication no
    
  3. Diff is empty now

    ansible-playbook harden_ssh.yml --check --diff | grep -c "^+"
    

    What it does: No more changes.

    Output

    0
    

When it is red 1

fatal: [web1]: FAILED! => {"msg": "'dict object' has no attribute 'stdout'"} (in check mode)

Cause. A command was skipped in check mode, so register has no stdout.

Fix, step by step

  1. Add check_mode: false to that safe read-only task.
  2. Or use default: ver.stdout | default("unknown").

When it is red 2

fatal: [web1]: FAILED! => {"msg": "failed to validate", "stderr": "/etc/ssh/sshd_config line 57: Bad configuration option"}

Cause. validate caught a broken line.

Fix, step by step

  1. Good: the file was not saved.
  2. Fix the line and preview again.

When it is red 3

No diff shown for a template change

Cause. Diff mode was not turned on, or the task has diff: false.

Fix, step by step

  1. Add --diff.
  2. Remove diff: false unless the file has secrets.

Cleanup

  1. Delete old drift logs

    find /var/log/ansible -name "drift-*.log" -mtime +30 -delete
    

    What it does: Keep 30 days.

    Output

    (no output)
    

Ravindra Bagale's Tip

On prod never run anything without --check --diff. Look first, then do.

Practice tasks

Easy Preview a change

Why: Build the habit.

What to do: Run any playbook with --check --diff.

How:
  1. Read every + and - line.

Check: You can explain each change.

Medium Write a drift job

Why: Catch hand edits.

What to do: Schedule a nightly check run and save logs.

How:
  1. Use cron or CI schedule.

Check: A log appears each morning.

Easy Say check and diff mode in two lines

Why: If you can say it simply, you understand it. Interviewers and juniors both need the short version first.

What to do: Write two short lines about check and diff mode for a fresher who knows only Linux basics.

How:
  1. Write the problem it solves.
  2. Write the one command or file you use for it.
  3. Read it aloud to a friend.

Check: A fresher understands it without asking a question.

Easy Start a two-server Ansible lab

Why: Practice needs safe throwaway servers. If you break them, you delete them and start again in one minute.

What to do: Start two Ubuntu containers that accept SSH, and one control machine with Ansible.

How:
  1. python3 -m pip install --user ansible-core
  2. docker run -d --name web1 -p 2221:22 lscr.io/linuxserver/openssh-server
  3. docker run -d --name web2 -p 2222:22 lscr.io/linuxserver/openssh-server
  4. ansible --version

Check: ansible --version prints a core version, and ssh to both ports works.

Medium Do it on the second setup

Why: The idea must work on a VM, a container and a cloud server. Only the inventory should change, never the playbook.

What to do: Repeat this lesson on a different target than the one you used first.

How:
  1. If you used containers, use one EC2 or local VM now.
  2. Change only the inventory file.
  3. Run the same playbook.

Check: Same result, and you changed only the inventory.

Medium Break it on purpose

Why: You must know the red output by face. On a real outage there is no time to read slowly.

What to do: Cause one error from the "When it is red" part of this lesson and fix it.

How:
  1. Follow the error section.
  2. Copy the exact message into your notes.
  3. Write the fix in one line.

Check: You fixed it using the steps, without searching the web.

Medium Run it twice and read the recap

Why: Idempotence is the heart of Ansible.

What to do: Run your playbook or command two times and compare the PLAY RECAP lines.

How:
  1. Run once and note changed=.
  2. Run again with no edits.
  3. Explain any task that still says changed.

Check: The second run shows changed=0, or you can explain every change.

Medium Write a runbook page

Why: At 2 a.m. nobody remembers flags. A short written page saves the on-call person.

What to do: Write a one-page runbook for this lesson.

How:
  1. Title, when to use, exact commands, how to check, how to undo.

Check: A teammate can follow it alone.

Hard Explain it like an interview

Why: Interviewers want real stories, not definitions.

What to do: Record a 60 second answer about this lesson.

How:
  1. Say the problem, the playbook or command, and one error you hit.

Check: Your answer has a real command and a real error message.

Hard Draw the flow top to bottom

Why: A drawing shows the order of work.

What to do: Draw this lesson as boxes from top to bottom.

How:
  1. Start at your laptop, go through SSH, end at the check on the server.

Check: Each box matches a real step you ran.

Homework: try at home

Try at home

At home, change one config line with lineinfile. Preview it with --check --diff, read the diff, then run it on one host with --limit.

Recap

  • --check is a dry run; --diff shows line changes.
  • Always preview, then --limit one host, then all.
  • check_mode: false for safe read-only tasks.
  • Skip risky tasks with when: not ansible_check_mode.
  • Nightly check runs find drift.

FAQ

Is check mode 100% accurate?

Mostly. Tasks that depend on earlier real changes may guess wrong.

Does diff show secrets?

It can. Use diff: false or no_log on secret files.

Can I use check mode in CI on pull requests?

Yes, against staging, to show reviewers the changes.

Why use validate?

It tests the new file before saving it.

Does --check run handlers?

It shows them as changed but does not really run them.

What is the difference between --check and --syntax-check?

--syntax-check only reads the YAML; --check connects to servers and simulates every task.

Interview questions

  1. What is check mode in Ansible?

    A dry run that reports what would change without changing anything.

  2. How do you preview file changes?

    --check --diff

  3. How do you handle commands in check mode?

    check_mode: false for read-only commands, and when: not ansible_check_mode to skip risky ones.

  4. How would you detect configuration drift?

    Scheduled check and diff runs with alerts when changed is above zero.

  5. How do you avoid locking yourself out when changing SSH?

    validate with sshd -t, check mode first, one host first, and keep a session open.

  6. Why roll out to one host first?

    A bad change then hits one server, not fifty, and you can fix it quickly.

Quick quiz

Q1. Does --check change servers?

No.

Q2. What does --diff show?

Before and after lines of changed files.

Q3. How do you force a safe task to run in check mode?

check_mode: false

Q4. Which variable is true in check mode?

ansible_check_mode

Q5. How do you find drift?

Scheduled --check --diff runs.

Did you understand? Let us try it once more.

Ravi Sir's Cards for this lesson

मराठी cards