substring variables?

4,580 views
Skip to first unread message

Kyle

unread,
Apr 3, 2015, 10:22:58 AM4/3/15
to ansible...@googlegroups.com
I can't find anything in ansible nor jinja documentation regarding substring. I'm looking for something such as this:

# variable passed at command line
host
=prd01denutl01


{{ host | substring(0,5) }}
-> prd01



{{ host | substring(6,3) }}
-> den


{{ host | substring(9,3) }}
-> utl



Is there any functionality for this?

Brian Coca

unread,
Apr 3, 2015, 10:33:34 AM4/3/15
to ansible...@googlegroups.com
In python/jinja2 strings can be looked as lists, so host[0:5] will
give you the first 5 character substring of the string in host.


--
Brian Coca

Brian Coca

unread,
Apr 3, 2015, 10:39:12 AM4/3/15
to ansible...@googlegroups.com
small demo play, the numbers are a bit diff than in substring, but it
works the way you want.

- hosts: localhost
gather_facts: False
vars:
host: prd01denutl01
tasks:
- debug: msg={{ host[0:5] }}
- debug: msg={{ host[5:8] }}
- debug: msg={{ host[8:11] }}

ansible-playbook play.yml
__________________
< PLAY [localhost] >
------------------
________________________________
< TASK: debug msg={{ host0:5] }} >
--------------------------------
ok: [localhost] => {
"msg": "prd01"
}
________________________________
< TASK: debug msg={{ host5:8] }} >
--------------------------------
ok: [localhost] => {
"msg": "den"
}
_________________________________
< TASK: debug msg={{ host8:11] }} >
---------------------------------
ok: [localhost] => {
"msg": "utl"
}
____________
< PLAY RECAP >
------------
localhost : ok=3 changed=0 unreachable=0 failed=0


--
Brian Coca

Jan-Piet Mens

unread,
Apr 3, 2015, 10:42:43 AM4/3/15
to ansible...@googlegroups.com
> Is there any functionality for this?

The variable is a Jinja2 string, so you can split it like a Python
string:

{{ host }} -> prd01denutl01
{{ host[0:4] }} -> prd0
{{ host[5:7] }} -> de


-JP

Kyle

unread,
Apr 3, 2015, 10:53:50 AM4/3/15
to ansible...@googlegroups.com
Awesome, thanks guys
Reply all
Reply to author
Forward
0 new messages