8

I am trying to use ansible to modify the hostnames of a dozen newly created Virtual Machines, and I am failing to understand how to loop correctly.

Here is the playbook I've written:

---
- hosts: k8s_kvm_vms
  tasks:
  - name: "update hostnames"
    hostname:
      name: "{{ item }}"
    with_items:
      - centos01
      - centos02
      ...

The result is that it updates each host with each hostname. So if I have 12 machines, each hostname would be "centos12" at the end of the playbook.

I expect this behavior to essentially produce the same result as:

num=0
for ip in ${list_of_ips[*]}; do 
    ssh $ip hostnamectl set-hostname centos${num}
    num=$((num+1))
done

If I were to write it myself in bash

The answer on this page leads me to believe I would have to include all of the IP addresses in my playbook. In my opinion, the advantage of scripting would be that I could have the same hostnames even if their IP changes (I just have to copy the ip addresses into /etc/ansible/hosts) which I could reuse with other playbooks. I have read the ansible page on the hostname module, but their example leads me to believe I would, instead of using a loop, have to define a task for each individual IP address. If this is the case, why use ansible over a bash script?

ansible hostname module

goliath16
  • 101
  • 1
  • 1
  • 6
  • Can you please show your inventory ? Did you name the machines after the IPs ? – Zeitounator Nov 14 '19 at 14:46
  • It does work just like your bash script. IF you loop through by IP, or original hostname (in your inventory) and set a variable for the new hostname in your inventory. Like @Smily's answer. – Jeter-work Mar 28 '21 at 23:01

2 Answers2

11

You can create a new variable for each of the servers in the inventory like

[k8s_kvm_vms]
server1 new_hostname=centos1
server2 new_hostname=centos2

Playbook:

---
- hosts: k8s_kvm_vms
  tasks:
  - name: "update hostnames"
    hostname:
      name: "{{ new_hostname }}"
Smily
  • 2,308
  • 2
  • 17
  • 41
0

I think you need to sudo to change the hostname thus you should add "become: yes"

---
- hosts: k8s_kvm_vms
  become: yes
  tasks:
  - name: "update hostnames"
    hostname:
      name: "{{ new_hostname }}"
Cameron Little
  • 3,487
  • 23
  • 35
AMAR BESSALAH
  • 49
  • 1
  • 6