# How to set hostname with running number

**URL:** <https://forum.ansible.com/t/how-to-set-hostname-with-running-number/36020>\
**Category:** Ansible Project\
**Created:** [November 22, 2021, 8:00am UTC](https://forum.ansible.com/t/how-to-set-hostname-with-running-number/36020 "2021-11-22T08:00:34Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![dudu.c](https://avatars.discourse-cdn.com/v4/letter/d/278dde/32.png) [@dudu.c](https://forum.ansible.com/u/dudu.c)\
**Post date:** [November 22, 2021, 8:00am UTC](https://forum.ansible.com/t/how-to-set-hostname-with-running-number/36020/1 "2021-11-22T08:00:34Z")

</div>

Hi,  
In my inventory file i have 3 server, I need to set the hostname including prefix1-3

web1  
web2  
web3

**Inventory fie:**

[web]  
192.168.0.47  
192.168.0.48  
192.168.0.49

**Playbook**

- hosts:

- web  
become: true  
any\_errors\_fatal: true  
tasks:

- name: update hostname  
hostname:  
name : “web ???”

---

<div class="post-metadata">

**Author:** ![racke](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/racke/32/4767_2.png) [@racke](https://forum.ansible.com/u/racke)\
**Post date:** [November 22, 2021, 8:19am UTC](https://forum.ansible.com/t/how-to-set-hostname-with-running-number/36020/2 "2021-11-22T08:19:30Z")

</div>

> Hi,  
> In my inventory file i have 3 server, I need to set the hostname including prefix1-3
> 
> web1  
> web2  
> web3
> 
> \*Inventory fie:\*
> 
> [web]  
> 192.168.0.47  
> 192.168.0.48  
> 192.168.0.49

Add the hostname to the inventory file:

web1 ansible\_host=192.168.0.47

> \*Playbook\*
> 
> - hosts:  
> - web  
> become: true  
> any\_errors\_fatal: true  
> tasks:
> 
> ```
> \- name: update hostname
> hostname:
> name : &quot;web ????&quot;
> 
> ```

Now you can use the inventory\_hostname variable in your task:

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- name: update hostname  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;hostname:  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;name: "{{ inventory\_hostname }}"

Please note that might not survive reboots, e.g on Ubuntu I'm doing:

- name: Enable preserving hostname in Cloud configuration  
&nbsp;&nbsp;&nbsp;lineinfile:  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;path: /etc/cloud/cloud.cfg  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;line: 'preserve\_hostname: true'  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;regexp: '^preserve\_hostname:'  
&nbsp;&nbsp;&nbsp;tags: hostname

Regards  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Racke
