I am trying to create a variable in ansible that is a verification of whether another variable contains a specific pattern or not.
The story is, I need to create a task in my playbook that will prevent images with the version tag dev from deploying on production. I'm new to ansible and not sure how to about this.
Previously, I'd worked this other way around, creating a variable that only deploys if a pattern is available.
vars:
archived_image_name: "{{ new_image.registry }}_{{ new_image.image | regex_replace('/', '_') }}_{{ new_image.version }}_image.tar"
archived_image_prod_name: "{{ archived_image_name | regex_search('.*-rev\\d.*')}}"
So this worked to only deploy images with -rev in their name. Can we reverse this?
You can use the search filter to identify if a string contains a substring. Then you can use the not operator to negate the result.
Check this example to see how to use them:
- hosts: localhost
gather_facts: no
vars:
tests:
- dev
- prod
- something:dev
- something:prod
- something/dev:latest
- something/prod:latest
tasks:
- debug:
msg: String "{{ item }}" doesn't have the substring "dev"
when: item is not search("dev")
loop: "{{ tests }}"
- debug:
msg: String "{{ item }}" does have the substring "dev"
when: item is search("dev")
loop: "{{ tests }}"
You should see this output:
PLAY [localhost] ***************************************************************
Saturday 29 May 2021 16:11:03 -0300 (0:00:00.020) 0:00:00.020 **********
TASK [debug] *******************************************************************
ok: [localhost] => (item=prod) =>
msg: String "prod" doesn't have the substring "dev"
ok: [localhost] => (item=something:prod) =>
msg: String "something:prod" doesn't have the substring "dev"
ok: [localhost] => (item=something/prod:latest) =>
msg: String "something/prod:latest" doesn't have the substring "dev"
Saturday 29 May 2021 16:11:03 -0300 (0:00:00.079) 0:00:00.100 **********
TASK [debug] *******************************************************************
ok: [localhost] => (item=dev) =>
msg: String "dev" does have the substring "dev"
ok: [localhost] => (item=something:dev) =>
msg: String "something:dev" does have the substring "dev"
ok: [localhost] => (item=something/dev:latest) =>
msg: String "something/dev:latest" does have the substring "dev"
PLAY RECAP *********************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
Please check the following link to learn more about the search filter:
https://docs.ansible.com/ansible/latest/user_guide/playbooks_tests.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With