This is a part of a Jinja template which creates a CSV file. This code snippet is supposed to perform a string replacement:
(... other variables here ...)
}},{% set ring = (myvars[h]['group_names'] | select('match', '^ring\\d+') | list | first) %}{{
(ring == 'ring0') | ternary('Ring 0 (Fast)',
(ring == 'ring1') | ternary('Ring 1 (Slow)',
(ring == 'ring2') | ternary('Ring 2 (Current)',
(ring == 'ring3') | ternary('Ring 3 (Manual)','No ring'))))
}},{{
(... other variables here ...)
However, it returns an error
"AnsibleUndefinedVariable: No first item, sequence was empty.
How to fix this code?
This alternate code returns the same error:
(... other variables here ...)
}},{% set ring = (myvars[h]['group_names'] | select('match', '^ring\\d+') | list | first) %}
{% set mapping = {
'ring0': 'Ring 0 (Fast)',
'ring1': 'Ring 1 (Slow)',
'ring2': 'Ring 2 (Current)',
'ring3': 'Ring 3 (Manual)'
} %}{{
mapping.get(ring, 'No ring')
}},{{
(... other variables here ...)
In reply to a comment from @Tsyvarev: The code should print "unknown" or whatever if the value in the sequence is not found.
Found the solution. I'm posting it here so it can be useful to other people.
(... other variables here ...)
}},{% set ring_raw = myvars[h]['group_names'] | select('match', '^ring\\d+') | list | first | default('No ring') %}
{% set ring_mapping = {
'ring0': 'Ring 0 (Fast)',
'ring1': 'Ring 1 (Slow)',
'ring2': 'Ring 2 (Current)',
'ring3': 'Ring 3 (Manual)'
} %}{{ ring_mapping[ring_raw] if ring_raw in ring_mapping else ring_raw }},{{
(... other variables here ...)