Score:0

Supplying hosts value to Ansible playbook via Jinja conditionals

cn flag

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
Score:1
th flag

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:
systrigger avatar
cn flag
thanks! the second one seems more ideal
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.