Kevin C
Kevin C

Reputation: 5750

Ansible - Check if var has been set twice

I've got 2 nodes with one variable:

Node1:

setup: master

Node2:

setup: slave

With a task, please set the vars in your host_vars:

---
- hosts: myhost
  tasks:
    - name: Copy file to master or slave
      copy:
        src: somesource
        dest: /tmp/"{{ setup }}"
        owner: root
        group: root
      mode: 0775
      # failed_when: setup is undefined or both_nodes_have_"master"

How can I fail the task if:

How can I only let the task continue if:

Upvotes: 2

Views: 515

Answers (1)

SztupY
SztupY

Reputation: 10546

Try counting them:

Inventory:

master ansible_connection=local
slave  ansible_connection=local

[master]
master

[slave]
slave

[myhost:children]
master
slave

[master:vars]
setup_type=master

[slave:vars]
setup_type=slave

Playbook:

---
- hosts: myhost
  gather_facts: yes
  vars:
    master_count: 0
    slave_count: 0
  tasks:
    - name: Count master fields
      set_fact:
        master_count: "{{master_count | int + 1}}"
      with_items:
        - "{{ groups.myhost }}"
      when: "hostvars[item]['setup_type'] is defined and hostvars[item]['setup_type'] == 'master'"

    - name: Count slave fields
      set_fact:
        slave_count: "{{slave_count | int + 1}}"
      with_items:
        - "{{ groups.myhost }}"
      when: "hostvars[item]['setup_type'] is defined and hostvars[item]['setup_type'] == 'slave'"

    - name: Fail if invalid master number
      debug:
        msg: "Master count: {{master_count}}"
      failed_when: "master_count | int != 1"

   - name: Fail if invalid slave number
     debug:
       msg: "Slave count: {{slave_count}}. Required: {{groups.myhost | length - master_count | int}}"
     failed_when: "slave_count | int + master_count | int != groups.myhost | length"

This will fail if there are zero or more than one master, and fail if there are not enough slaves (this will check how many hosts you have automatically and expect all non-master hosts to be slaves)

You'll need to modify these strings in case you need to paste this to your solution:

  • setup_type: is the variable in questions
  • master and slave are the variable values we are checking
  • myhost is the group where we are doing the search

Note that these appear in multiple places hence you should do a search and replace on all of them. Also Ithink all of them could be made dynamic as well meaning you could extract this as a role or separate play for easier reuse

Upvotes: 4

Related Questions