Home:ALL Converter>Ansible - define settings based on host name prefix

Ansible - define settings based on host name prefix

Ask Time:2017-09-07T00:00:02         Author:lmills

Json Formatter

I would like to be able to set values in an ansible playbook based on the prefix of a hostname.

e.g. hosts that start LondonXXXX receive the IP 192.168.1.1 for DNS hosts that start NewYorkXXX receive the IP 192.168.2.1 for DNS etc

I have tried various methods but don't seem to be able to get it to work. I am referencing the variables .yml in the playbook by:

  vars_files:
    - dns.yml

An example of a couple of things I have tried in the DNS.yml file:

---
- include:
  - name: Check if located in London
    set_fact: 
      DNS: '192.168.1.1'
    when: ansible_hostname.find("London") != -1

  - set_fact:
      DNS: '192.168.2.1'
    when: '"NewYork" in ansible_hostname'

I am new to using ansible so apologies if this is a simple syntax issue.

Author:lmills,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/46079729/ansible-define-settings-based-on-host-name-prefix
larsks :

A vars file is just a collection of name: value pairs. It can't have tasks. There also appear to be some syntax errors in the example you've posted, and possibly you're using some variables that don't actually exist.\n\nIf you want to use tasks like set_fact, that needs to go in a playbook. For example, you could do something like this:\n\n- hosts: all\n gather_facts: false\n tasks:\n - name: Check if located in London\n set_fact:\n DNS: '192.168.1.1'\n when: >\n \"London\" in inventory_hostname\n\n - set_fact:\n DNS: '192.168.2.1'\n when: >\n \"NewYork\" in inventory_hostname\n\n - debug:\n msg: \"Variable DNS is: {{DNS}}\"\n\n\nGiven an inventory that looks like this:\n\nLondon1234 ansible_host=localhost ansible_connection=local\nNewYork1234 ansible_host=localhost ansible_connection=local\n\n\nI can run the above playbook like this:\n\nansible-playbook playbook.yml -i hosts\n\n\nAnd get:\n\nPLAY [all] *********************************************************************************\n\nTASK [Check if located in London] **********************************************************\nok: [London1234]\nskipping: [NewYork1234]\n\nTASK [set_fact] ****************************************************************************\nskipping: [London1234]\nok: [NewYork1234]\n\nTASK [debug] *******************************************************************************\nok: [London1234] => {\n \"msg\": \"Variable DNS is: 192.168.1.1\"\n}\nok: [NewYork1234] => {\n \"msg\": \"Variable DNS is: 192.168.2.1\"\n}\n\nPLAY RECAP *********************************************************************************\nLondon1234 : ok=2 changed=0 unreachable=0 failed=0 \nNewYork1234 : ok=2 changed=0 unreachable=0 failed=0 \n",
2017-09-06T16:06:28
yy