when condition on a variable starting with a string value

Hello,

Actually I wrote my playbook this way to set values id the dual variable is the string value SRV:

  • set_fact:
    distrib: “{{ distribsrv }}”
    Directoryname: “{{ Directorysrv }}”
    when: dual == ‘SRV’

I would like to modify the when condition to run it when dual == ‘SRV1’, "SRV2’ … etc, is there a way to do a when condition : when : dual like ‘SRV*’ ?

I wrote this:

vars:
services:

  • SRV

  • SRV[1:99]

  • set_fact:
    distrib: “{{ distribsrv }}”
    when: dual in services

but dual is SRV2 and the set_fact module has been ignored

if I write this, i do not get a variable list:

  • set_fact:
    services: “{{ services + item }}”
    with_sequence: count=99
  • debug: msg=“sequence {{ services }}”

ok: [SRV1] => {
“msg”: “sequence SRV123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899”
}

the result expected is SRV1, SRV2, SRV3 …

My issue is: I would like to run a task when a variable start with ‘SRV’ (srv1, SRV2 …) ad I don’t know how to write the condition: when: dual like ‘SRV*’

I know this is weird, but can't think of something better:

   - set_fact:
      distrib: "{{ distribsrv }}"
      Directoryname: "{{ Directorysrv }}"
     when: dual | regex_replace( '^SRV.*', 'True') | bool

Cheers,
Marko
CONFIDENTIALITY NOTICE: This message is the property of International Game Technology PLC and/or its subsidiaries and may contain proprietary, confidential or trade secret information. This message is intended solely for the use of the addressee. If you are not the intended recipient and have received this message in error, please delete this message from your system. Any unauthorized reading, distribution, copying, or other use of this message or its attachments is strictly prohibited.

thank you I will have a look at your solution, I finally found this way to proceed otherwise:

  • set_fact:
    services: “{{ services }} + SRV{{item }}”

with_sequence: count=5

  • set_fact:
    distrib: “{{ distribsrv }}”
    when: dual in services

TASK [debug] *******************************************************************
ok: [SRV1] => {
“msg”: “sequence SRV + SRV1 + SRV2 + SRV3 + SRV4 + SRV5”
}

Thanks a lot Marko, I used your syntax:
dual>regex_replace(‘^SRV(.*)’, ‘True’)

Thanks a lot Marko, I used your syntax:
dual>regex_replace('^SRV(.*)', 'True')

Did you try the following?

No need to use regex for pattern searching. You can use search like
this:

when: name_prefix | search("stage-dbs")

from
https://stackoverflow.com/questions/34429842/how-to-evaluate-a-when-condition-for-ansible-task

In your case this should be:

when: dual | search("SRV")

Johannes