Reputation: 11
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.
Upvotes: 1
Views: 3716
Reputation: 6158
Seems to me it would be easier to have that variable in group_vars files. Your inventory would then put the London hosts into the London group, and the New York hosts into the New_York group.
Upvotes: 0
Reputation: 311238
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.
If you want to use tasks like set_fact
, that needs to go in a playbook. For example, you could do something like this:
- hosts: all
gather_facts: false
tasks:
- name: Check if located in London
set_fact:
DNS: '192.168.1.1'
when: >
"London" in inventory_hostname
- set_fact:
DNS: '192.168.2.1'
when: >
"NewYork" in inventory_hostname
- debug:
msg: "Variable DNS is: {{DNS}}"
Given an inventory that looks like this:
London1234 ansible_host=localhost ansible_connection=local
NewYork1234 ansible_host=localhost ansible_connection=local
I can run the above playbook like this:
ansible-playbook playbook.yml -i hosts
And get:
PLAY [all] *********************************************************************************
TASK [Check if located in London] **********************************************************
ok: [London1234]
skipping: [NewYork1234]
TASK [set_fact] ****************************************************************************
skipping: [London1234]
ok: [NewYork1234]
TASK [debug] *******************************************************************************
ok: [London1234] => {
"msg": "Variable DNS is: 192.168.1.1"
}
ok: [NewYork1234] => {
"msg": "Variable DNS is: 192.168.2.1"
}
PLAY RECAP *********************************************************************************
London1234 : ok=2 changed=0 unreachable=0 failed=0
NewYork1234 : ok=2 changed=0 unreachable=0 failed=0
Upvotes: 1