ansible become method fallback

Let’s say you have the following hypothetical environment which contains two subsets of servers:

  • Internal servers: configured to use Centrify/AD for authentication (dzdo for your become method)
  • DMZ servers: configured with traditional sudoers files since access to internal AD is not available (sudo for your become method)

Assuming our inventory can’t be grouped by some trait like hostname, network segment, etc, what is the fastest (and laziest) way we can run our playbook against all these hosts?

Disclaimer: You should probably work on creating a stronger inventory. The following serves as a workaround only.

playbook.yml:

- hosts: all
  become: no
  become_method: dzdo
  gather_facts: no

  tasks:
    # fall back to sudo if centrify isn't configured
    - name: get hw info
      block:
        - name: try with dzdo
          gather_facts:
      rescue:
        - name: fallback to sudo
          vars:
            ansible_become_method: sudo
          gather_facts:
      become: yes

If our server isn’t configured with Centrify for AD authentication, the playbook will fallback and attempt to use sudo.