Manipulating part of a custom variable

14 views
Skip to first unread message

John Harmon

unread,
Nov 2, 2018, 4:49:30 PM11/2/18
to Ansible Project
I have a variable called 'oldid' set to a value of '0004fb0000060000b824b442d236a8b7'

I wish to manipulate it so that I do the following:
1.  strip off the last 12 characters (slicing?)
2.  Re-add 12 more characters that are a random numbers between 0-9

Here is what I have, but unsure if I can even do this (it is failing).  Syntax is wrong, but is hopefully descriptive in nature.  Wonder if my approach is wrong too?

  tasks:
   
- name: Set new_id
      set_fact
:
        new_id
: "{{ oldid[:-12]{{ 9 | random }}"

I need to repeat the {{ 9 | random }} a total of 12 times.... don't know if there is a shortcut way to do that other than retyping the command over and over.

Kai Stian Olstad

unread,
Nov 2, 2018, 5:24:34 PM11/2/18
to ansible...@googlegroups.com
Set random from a high number should do it

{{ oldid[:-12] ~ 1000000000000 | random(100000000000) }}"

this will only change from 100.000.000.000 to to 999.999.999.999 so your 12 last digit will never start with 0.


If you need to generate the same "random" number each time you need a predictable seed like inventory_hostname

{{ oldid[:-12] ~ 1000000000000 | random(100000000000,seed=inventory_hostname) }}"

--
Kai Stian Olstad


John Harmon

unread,
Nov 2, 2018, 5:35:01 PM11/2/18
to Ansible Project
Awesome, that works!  Using a large number for randomizing didn't even occur to me.  Just one follow-up question.  Can you explain to me what the tilde ~ is doing?  Having a hard time finding info on it.

Kai Stian Olstad

unread,
Nov 2, 2018, 5:43:16 PM11/2/18
to ansible...@googlegroups.com
It Jinja for concatenate strings[1].
Sometimes you see people using + and that will work if everything is stings, but if they are numbers Jinja will add them together, so the safest thing is to use ~ to concatenate.


[1] http://jinja.pocoo.org/docs/2.10/templates/#other-operators

--
Kai Stian Olstad


John Harmon

unread,
Nov 2, 2018, 5:43:58 PM11/2/18
to Ansible Project
Thank you

John Harmon

unread,
Nov 5, 2018, 12:53:55 PM11/5/18
to Ansible Project
How can I throw in a custom string?  Everything I try seems to fail:

Working:
newname: "{{ oldname.stdout ~ ansible_date_time.date }}"
Returns:
myserver2018-11-05

Desired:
myserver-COPY-2018-11-05

Kai Stian Olstad

unread,
Nov 5, 2018, 12:59:20 PM11/5/18
to ansible...@googlegroups.com
newname: "{{ oldname.stdout ~ '-COPY-' ~ ansible_date_time.date }}"


--
Kai Stian Olstad


John Harmon

unread,
Nov 5, 2018, 1:00:41 PM11/5/18
to Ansible Project
Ah, it was the single quotes that I was missing.  Thank you.
Reply all
Reply to author
Forward
0 new messages