-
-
Save phips/11233502 to your computer and use it in GitHub Desktop.
- name: Ensure hostname set | |
hostname: | |
name: {{ inventory_hostname }} | |
when: not inventory_hostname|trim is match('(\d{1,3}\.){3}\d{1,3}') | |
- name: Ensure hostname is in /etc/hosts | |
lineinfile: | |
dest: /etc/hosts | |
regexp: "^{{ ansible_default_ipv4.address }}.+$" | |
line: "{{ ansible_default_ipv4.address }} {{ ansible_fqdn }} {{ ansible_hostname }}" |
- name: Add Ansible inventory mappings to /etc/hosts
become: true
blockinfile:
path: /etc/hosts
block: |
{% for host in groups['all'] %}
{{ hostvars[host].ansible_host }} {{ host }}
{% endfor %}
In case this has stopped working for anyone else recently, with errors like
fatal: [mydomain.net]: FAILED! => {"msg": "The conditional check 'not inventory_hostname | match ('(\d{1,3}\.){3}\d{1,3}')' failed. The error was: template error while templating string: no filter named 'match'. String: {% if not inventory_hostname | match ('(\d{1,3}\.){3}\d{1,3}') %} True {% else %} False {% endif %}\n\nThe error appears to be in '/Users/config-hostname.yaml': line 5, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n tasks:\n - name: Ensure hostname set\n ^ here\n"}
changing line 3 to:
when: not inventory_hostname|trim is match('(\d{1,3}\.){3}\d{1,3}')
Should fix the issue.
---
- name: inventory name to hostname
hostname:
name: "{{ inventory_hostname }}"
- name: inventory name to hostname
hostname:
name: "{{ inventory_hostname }}"
Indeed @patsevanton — the original gist is in a really old format. You've correctly put the way things should be now 👍
ziamler, i hope this help you
With this: play_hosts.index(inventory_hostname) you obtain the current index