0

I have an Ansible role that I want to execute on particular hosts based on a certain conditions.

I want to populate the hosts from Ansible Tower survey. Here's my playbook:

- name: HTTP Response Deploy Automation
  hosts: "{% if geo == 'LHR' %}'dblhr002' {% elif geo == 'SJC' %}'dbsjc003' {% endif %}"
  gather_facts: true
  roles:
    - http-response-deploy

I'm getting the following error when choosing LHR:

 [WARNING]: Could not match supplied host pattern, ignoring: 'dblhr002'

To note that, it doesn't work when I choose to omit the quotes around the hostnames.

TLDR; need to achieve the conditionals from Ansible as below:

if geo == "LHR": 
   hosts: dblhr002
if geo == "SJC":
   hosts: dbsjc003

1 Answer 1

1

What you have provided works fine, as long as dblhr002 is listed in inventory. Host patterns only match existing hosts, they do not add new hosts to the inventory.

ec2-user@pandora ~ $ cat test.yml 
- hosts: "{% if geo == 'LHR' %}'dblhr002' {% elif geo == 'SJC' %}'dbsjc003' {% endif %}"
  gather_facts: false
  tasks:
    - debug:
ec2-user@pandora ~ $ ANSIBLE_INVENTORY_ENABLED=host_list ansible-playbook ~/test.yml -e geo=LHR -i dblhr002,

PLAY [dblhr002] ****************************************************************

TASK [debug] *******************************************************************
ok: [dblhr002] => {
    "msg": "Hello world!"
}

PLAY RECAP *********************************************************************
dblhr002                   : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

If you need to dynamically add a host, use the add_host task in a separate play.

- hosts: localhost
  gather_facts: false
  tasks:
    - add_host:
        name: "{{ host_map[geo] }}"
        groups: target_host
      vars:
        host_map:
          LHR: dblhr002
          SJC: dbsjc003

- hosts: target_host
  gather_facts: false
  tasks:
    - debug:
1
  • thanks! the second one seems more ideal
    – systrigger
    Oct 8, 2021 at 14:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .