-
-
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 }}" |
ziamler, i hope this help you
- name: Configure slave's hostname
hosts: slaves
become: True
become_user: root
gather_facts: True
tasks:
- hostname:
name: "slave{{ play_hosts.index(inventory_hostname)|int+1 }}"
- debug: msg="{{ play_hosts.index(inventory_hostname) }}"
- debug: msg="{{ inventory_hostname }}"
With this: play_hosts.index(inventory_hostname) you obtain the current index
- 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 👍
hi,
i want to set hostname in multiple server with sequence for example i have 100 server and i want hostname starting web01 for first server second server hostname web02 and so on. can you please help me
[email protected] please mail m