Reputation: 327
I have two variables:
name: "abc232323defg10"
cycle: "4"
I need to generate a list:
list:
- abc232323defg10
- abc232323defg9
- abc232323defg8
- abc232323defg7
where:
abc232323defg9 = abc232323defg(10-(cycle-3)),
abc232323defg8 = abc232323defg(10-(cycle-2)),
abc232323defg7 = abc232323defg(10-(cycle-1))
The variable "cycle" is the same as the number of items in the list, and I already have item where last 2 characters are the "largest number" (that is number 10 in the example). So other items should have last two characters subtracted from this "largest number" (with increments for each cycle). Cycle is never bigger then "largest number", but can be equal. Order in the list is not relevant.
PS last two characters can be any number or even combination of one letter (a-z,A-Z) and one number. So it can be t1, or e9, or 88... that is why I think I need regex.
Any idea?
Upvotes: 0
Views: 140
Reputation: 68074
Given the variables
_name: "abc232323defg10"
cycle: "4"
Declare the variables prefix and index by splitting _name
prefix: "{{ _name|regex_replace('^(.+?)(\\d+)$', '\\1') }}"
index: "{{ _name|regex_replace('^(.+?)(\\d+)$', '\\2') }}"
give
prefix: abc232323defg
index: 10
Declare the list indexes
indexes: "{{ query('sequence', params) }}"
params: "start={{ index|int }} end={{ index|int - cycle|int + 1 }} stride=-1"
give
indexes: ['10', '9', '8', '7']
Finally, create product of the prefix and indexes, and join them
names: "{{ [prefix]|product(indexes)|map('join')|list }}"
gives the expected result
names:
- abc232323defg10
- abc232323defg9
- abc232323defg8
- abc232323defg7
Example of a complete playbook for testing
- hosts: localhost
vars:
_name: "abc232323defg10"
cycle: "4"
prefix: "{{ _name|regex_replace('^(.+?)(\\d+)$', '\\1') }}"
index: "{{ _name|regex_replace('^(.+?)(\\d+)$', '\\2') }}"
indexes: "{{ query('sequence', params) }}"
params: "start={{ index|int }} end={{ index|int - cycle|int + 1 }} stride=-1"
names: "{{ [prefix]|product(indexes)|map('join')|list }}"
tasks:
- debug:
msg: |
prefix: {{ prefix }}
index: {{ index }}
indexes: {{ indexes }}
names:
{{ names|to_nice_yaml|indent(2) }}
Upvotes: 2