# Create variables based on  hostname

**URL:** <https://forum.ansible.com/t/create-variables-based-on-hostname/26402>\
**Category:** Ansible Project\
**Created:** [January 2, 2018, 5:53pm UTC](https://forum.ansible.com/t/create-variables-based-on-hostname/26402 "2018-01-02T17:53:03Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Yz\_Xyz](https://avatars.discourse-cdn.com/v4/letter/y/a698b9/32.png) [@Yz\_Xyz](https://forum.ansible.com/u/Yz_Xyz)\
**Post date:** [January 2, 2018, 5:53pm UTC](https://forum.ansible.com/t/create-variables-based-on-hostname/26402/1 "2018-01-02T17:53:03Z")

</div>

Hi - I want to create 3 variables based on hostname. These variables will be used inside other tasks.

Host Pattern: mabos

Ex: mabosqa1was01

what is the best way to create variables and use for subsequent task on host ?

should I write 3 different shell scripts to register appropriate variables ?

Thanks,

---

<div class="post-metadata">

**Author:** ![Mike\_Klebolt](https://avatars.discourse-cdn.com/v4/letter/m/58956e/32.png) [@Mike\_Klebolt](https://forum.ansible.com/u/Mike_Klebolt)\
**Post date:** [January 4, 2018, 9:09pm UTC](https://forum.ansible.com/t/create-variables-based-on-hostname/26402/2 "2018-01-04T21:09:22Z")

</div>

You can create your own filter. I’ve created this one that you should easily be able to modify to suit your needs.

`  
import math  
import collections  
from ansible import errors

def uppercase\_all(arg):  
return arg.upper()

def extract\_siteid(arg):  
if len(arg) \< 10:  
return FALSE  
site\_id = arg[:7]  
return site\_id

def extract\_datacenter(arg):  
if len(arg) \< 10:  
return FALSE  
datacenter = arg[7:10]  
return datacenter

class FilterModule(object):  
def filters(self):  
return {‘uppercase\_all’: uppercase\_all, ‘extract\_siteid’: extract\_siteid, ‘extract\_datacenter’: extract\_datacenter}

`

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/ansible/original/1X/1882d9a01da5d8996a862359b0913cc568a39b84.svg) [@system](https://forum.ansible.com/u/system)\
**Post date:** [June 15, 2018, 11:39pm UTC](https://forum.ansible.com/t/create-variables-based-on-hostname/26402/3 "2018-06-15T23:39:57Z")

</div>

just define vars based on inventory\_hostname:

group\_vars/all.yml

nodenum: '{{inventory\_hostname|regex\_replace("mabos.+?(\d+)$", "\1")}}'  
component: '{{inventory\_hostname|regex\_replace("mabos.+?\d+(\w+?)\d+$", "\1")}}'  
...
