# Is it possible to export inventory to a file?

**URL:** <https://forum.ansible.com/t/is-it-possible-to-export-inventory-to-a-file/29454>\
**Category:** AWX Project\
**Created:** [January 17, 2019, 6:52am UTC](https://forum.ansible.com/t/is-it-possible-to-export-inventory-to-a-file/29454 "2019-01-17T06:52:32Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Ibrahim\_Ercan](https://avatars.discourse-cdn.com/v4/letter/i/96bed5/32.png) [@Ibrahim\_Ercan](https://forum.ansible.com/u/Ibrahim_Ercan)\
**Post date:** [January 17, 2019, 6:52am UTC](https://forum.ansible.com/t/is-it-possible-to-export-inventory-to-a-file/29454/1 "2019-01-17T06:52:32Z")

</div>

Hi.  
I need to import and export inventories. I can import inventory from a file but I couldn’t figure out if there is a way to export inventory to a file?  
I wonder if there is a easy way to do that? Any suggestion?

---

<div class="post-metadata">

**Author:** ![Ibrahim\_Ercan](https://avatars.discourse-cdn.com/v4/letter/i/96bed5/32.png) [@Ibrahim\_Ercan](https://forum.ansible.com/u/Ibrahim_Ercan)\
**Post date:** [January 17, 2019, 10:23am UTC](https://forum.ansible.com/t/is-it-possible-to-export-inventory-to-a-file/29454/2 "2019-01-17T10:23:54Z")

</div>

I wrote below script that run sql queries on awx database and print hosts as inventory format. Putting here in case someone needs it.

`

#!/bin/bash

PSQL=/usr/bin/psql

DB\_USER=awx  
DB\_NAME=awx

function run\_sql(){  
docker exec awx\_postgres\_1 $PSQL   
-X   
-U $DB\_USER   
-c “$1”   
–single-transaction   
–set AUTOCOMMIT=off   
–set ON\_ERROR\_STOP=on   
–no-align   
-t   
–field-separator ’ ’   
–quiet   
-d $DB\_NAME

}

function get\_host\_name(){  
echo `grep "^$1 " /tmp/awx_hosts | cut -d" " -f2`  
}

run\_sql “select id, name from main\_host” \> /tmp/awx\_hosts

run\_sql “select id, name from main\_group” | while read group\_id group\_name ; do  
echo “[$group\_name]”  
run\_sql “select host\_id from main\_group\_hosts where group\_id=‘$group\_id’” | while read host\_id; do

get\_host\_name $host\_id  
done  
echo  
done

rm -f /tmp/awx\_hosts

`

---

<div class="post-metadata">

**Author:** ![rpetrell](https://avatars.discourse-cdn.com/v4/letter/r/b4bc9f/32.png) [@rpetrell](https://forum.ansible.com/u/rpetrell)\
**Post date:** [January 17, 2019, 11:47am UTC](https://forum.ansible.com/t/is-it-possible-to-export-inventory-to-a-file/29454/3 "2019-01-17T11:47:38Z")

</div>

İbrahim,

AWX provides an API endpoint that will generate an inventory for you in JSON format:

curl -ks “[https://user:pass@awx.example.org/api/v2/inventories/1/script/](https://user:pass@awx.example.org/api/v2/inventories/1/script/)” | python -m json.tool

{  
“all”: {  
“hosts”: [  
“localhost”  
]  
}  
}
