# Use IP in hosts as variables in roles

**URL:** <https://forum.ansible.com/t/use-ip-in-hosts-as-variables-in-roles/18869>\
**Category:** Ansible Project\
**Created:** [July 27, 2015, 10:05pm UTC](https://forum.ansible.com/t/use-ip-in-hosts-as-variables-in-roles/18869 "2015-07-27T22:05:34Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Alexandre\_Grais](https://avatars.discourse-cdn.com/v4/letter/a/898d66/32.png) [@Alexandre\_Grais](https://forum.ansible.com/u/Alexandre_Grais)\
**Post date:** [July 27, 2015, 10:05pm UTC](https://forum.ansible.com/t/use-ip-in-hosts-as-variables-in-roles/18869/1 "2015-07-27T22:05:34Z")

</div>

Hi Ansible guys,

I am using ansible to provision my django application composed of:

- A Django Webserver on (Machine A IP : 1.1.1.1)
- A PostgreSQL Database (Machine B IP: 2.2.2.2)
- RabbitMQ Server (Machine C)
- Celery Woekers (Machine D)

`  
[database]  
2.2.2.2

[django]  
1.1.1.1  
`

The main question I have is the following:  
I’m using ansible to generate my settings.py for production. In this file, we need to define the database such as:

`

########## DATABASE CONFIGURATION

# See: [Settings | Django documentation | Django](https://docs.djangoproject.com/en/dev/ref/settings/#databases)

DATABASES = {  
‘default’: {  
‘ENGINE’: ‘django.db.backends.postgresql\_psycopg2’,  
‘NAME’: ‘toto’, # To be compliant with automatic exports from production  
‘USER’: ‘postgres’,  
‘PASSWORD’: ‘’,  
‘HOST’: ‘2.2.2.2’, # MACHINE B IP ADRESS  
‘PORT’: ‘5432’,  
}  
}  
########## END DATABASE CONFIGURATION

`

Right now, I am hard coding the IP of my database in the settings.py file. But I don’t feel confortable with this approach. What if I need to deploy an other environment ? I was wondering how I could get dynamically the IP of my database server and use it as a variable in my differents templates.

If you have any ideas about how to proceed, I would be really happy to hear from you.

Regards.

---

<div class="post-metadata">

**Author:** ![j.r.hawkesworth](https://avatars.discourse-cdn.com/v4/letter/j/a3d4f5/32.png) [@j.r.hawkesworth](https://forum.ansible.com/u/j.r.hawkesworth)\
**Post date:** [July 29, 2015, 5:25am UTC](https://forum.ansible.com/t/use-ip-in-hosts-as-variables-in-roles/18869/2 "2015-07-29T05:25:03Z")

</div>

Have a look at:

[http://docs.ansible.com/ansible/faq.html#how-do-i-loop-over-a-list-of-hosts-in-a-group-inside-of-a-template](http://docs.ansible.com/ansible/faq.html#how-do-i-loop-over-a-list-of-hosts-in-a-group-inside-of-a-template)  
and  
[http://docs.ansible.com/ansible/faq.html#how-do-i-access-a-variable-of-the-first-host-in-a-group](http://docs.ansible.com/ansible/faq.html#how-do-i-access-a-variable-of-the-first-host-in-a-group)  
I think this might get you pretty close to what you want.

Jon
