Molly Guard for Ansible

· 294 words · 2 minute read

The Jargon File defines Molly Guard as:

A shield to prevent tripping of some Big Red Switch by clumsy or ignorant hands. Originally used of the plexiglass covers improvised for the BRS on an IBM 4341 after a programmer’s toddler daughter (named Molly) frobbed it twice in one day. Later generalized to covers over stop/reset switches on disk drives and networking equipment. In hardware catalogues, you’ll see the much less interesting description “guarded button”.

Before Ansible and wide-spread infrastructure automation in general, I used the Debian package molly-guard to prevent mistakenly rebooting the wrong server. Ansible and automation made it possible to make the same sort of mistake on multiple hosts at once!

To prevent this, some extra check from the user is needed. I believe a simple confirmation prompt isn’t that useful, because people just learn to press enter, type in ‘yes’ or use a switch to skip the check. The brilliant idea in molly-guard was to ask for the hostname. GitHub/GitLab ask for the name of the repository to confirm removal. So my idea is to make Ansible ask for the number of affected hosts:

# vim: set ft=yaml:
---
- hosts: all
  gather_facts: false
  tasks:
    - local_action:
        module: ansible.builtin.debug
        msg: 'Run affects {{ansible_play_hosts|length}} hosts'
      run_once: true

    - local_action:
        module: ansible.builtin.pause
        prompt: Confirm number of hosts affected
      register: prompt
      when: not ansible_check_mode

    - name: Verify number of affected hosts
      local_action:
        module: ansible.builtin.assert
        that:
          - '{{prompt.user_input|int}} == {{ansible_play_hosts|length}}'
        quiet: true
      run_once: true
      when: not ansible_check_mode

Put that at the start of your Ansible playbooks and hopefully you’ll stay safe.

This is mostly useful for running Ansible playbooks by hand on the command line. When Ansible is run completely automated, e.g. in CI/CD, you cannot have a human confirming as part of the process.