I have a variable called ‘oldid’ set to a value of ‘0004fb0000060000b824b442d236a8b7’
I wish to manipulate it so that I do the following:
- strip off the last 12 characters (slicing?)
- 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.
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) }}"
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.
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
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
newname: "{{ oldname.stdout ~ '-COPY-' ~ ansible_date_time.date }}"
Ah, it was the single quotes that I was missing. Thank you.