ansibleansible-role

Ansible Skip Host For a Specific Role


I have a hosts file that looks a bit different for prod and test and here they are:

# Contains the host mappings

[master]
local-machine ansible_host=192.168.0.201 host_alias=local-machine

[node]
n1.com ansible_host=192.168.0.202 host_alias=n1
n2.com ansible_host=192.168.0.203 host_alias=n2
#n3.com ansible_host=192.168.0.204 host_alias=n3

[k3s_cluster:children]
master
node

[all:vars]
ansible_python_interpreter=/usr/bin/python3

The above is for the test environment and the below is for prod environment:

# Contains the host mappings

[master]
m1.com ansible_host=192.168.0.201 host_alias=m1

[node]
n1.com ansible_host=192.168.0.202 host_alias=n1
n2.com ansible_host=192.168.0.203 host_alias=n2
#n3.com ansible_host=192.168.0.104 host_alias=n3

[k3s_cluster:children]
master
node

[all:vars]
ansible_python_interpreter=/usr/bin/python3

In my playbook, I have the following:

---

# K3s installation and set up
- name: "K3S SETUP: K3s download, install and setup"
  hosts: k3s_cluster
  gather_facts: yes
  become: yes
  roles:
    - {role: prereq, tags: ['host', 'k3s']}
    - {role: download, tags: ['host', 'k3s']}
    - {role: raspberrypi, tags: ['host', 'k3s']}

- hosts: master
  become: yes
  roles:
    - {role: k3s/master, tags: ['k3s', 'master']}

- hosts: node
  become: yes
  roles:
    - {role: k3s/node, tags: ['k3s', 'node']}

I want to now apply that role: raspberrypi on my master node only for my prod environment and I would like to skip that role for the master node when I run Ansible against the test hosts file. Any suggestions on how I could do this?


Solution

  • You can add when conditions to your roles, so you could do something like this:

    - name: "K3S SETUP: K3s download, install and setup"
      hosts: k3s_cluster
      gather_facts: true
      become: true
      roles:
        - role: prereq
          tags: ['host', 'k3s']
        - role: download
          tags: ['host', 'k3s']
        - role: raspberrypi
          tags: ['host', 'k3s']
          when: not skip_raspberrypi|default(false)
    

    And then in your test inventory, set skip_raspberrypi=true for the master node:

    hosts:
      master_node:
        skip_raspberrypi: true
    

    If you're using an ini-style inventory:

    master_node skip_raspberrypi=true