---
- name: Change Ubuntu hostnames from CSV
hosts: all
become: true
gather_facts: true
vars:
csv_file: "{{ playbook_dir }}/files/hqrs.csv"
tasks:
- name: Read CSV file
community.general.read_csv:
path: "{{ csv_file }}"
register: csv_data
delegate_to: localhost
run_once: true
- name: Match current host with CSV entry
set_fact:
matched_host: "{{ item }}"
loop: "{{ csv_data.list }}"
when: item.ip_address == ansible_host
- name: Stop play if no CSV match found
fail:
msg: "No matching entry found in CSV for {{ inventory_hostname }}"
when: matched_host is not defined
- name: Show hostname change
debug:
msg: "Changing hostname from {{ matched_host.old_hostname }} to {{ matched_host.new_hostname }}"
- name: Verify existing hostname
fail:
msg: "Hostname mismatch! Current hostname is {{ ansible_hostname }} but expected {{ matched_host.old_hostname }}"
when: ansible_hostname != matched_host.old_hostname
- name: Set new hostname
hostname:
name: "{{ matched_host.new_hostname }}"
- name: Update /etc/hosts
lineinfile:
path: /etc/hosts
regexp: '^127\.0\.1\.1'
line: "127.0.1.1 {{ matched_host.new_hostname }}"
state: present
- name: Restart systemd-hostnamed
service:
name: systemd-hostnamed
state: restarted
- name: Reboot machine
reboot:
reboot_timeout: 300⚠️Content was pasted as plain text and auto-formatted as a code block. Use the Code Block button in the editor for proper formatting.