title: How do I correctly use the ansible hostname module?
body: <p>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. </p>
  
  <p>Here is the playbook I've written: </p>
  
  <pre><code>---
  - hosts: k8s_kvm_vms
    tasks:
    - name: "update hostnames"
      hostname:
        name: "{{ item }}"
      with_items:
        - centos01
        - centos02
        ...
  </code></pre>
  
  <p>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. </p>
  
  <p>I expect this behavior to essentially produce the same result as: </p>
  
  <pre><code>num=0
  for ip in ${list_of_ips[*]}; do 
      ssh $ip hostnamectl set-hostname centos${num}
      num=$((num+1))
  done
  </code></pre>
  
  <p>If I were to write it myself in bash</p>
  
  <p><a href="https://stackoverflow.com/questions/43144374/iterate-over-the-hostname-stored-in-var-files">The answer on this page</a> 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? </p>
  
  <p><a href="https://docs.ansible.com/ansible/latest/modules/hostname_module.html" rel="noreferrer">ansible hostname module</a></p>