Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run an Ansible task only when the variable contains a specific string

I have multiple tasks depend from the value of variable1. I want to check if the value is in {{variable1}} but i got an error:

- name: do something when the value in variable1   command: <command>   when: "'value' in {{variable1}}" 

I'm using ansible 2.0.2

like image 415
mndhr Avatar asked Apr 08 '16 10:04

mndhr


People also ask

Which keyword do you use to create a conditional task in Ansible?

To implement conditions in Ansible, we use the when keyword. The keyword takes Boolean expressions based on a value or a variable from previous tasks or facts gathered from the remote hosts. This guide will teach you how to implement conditions in Ansible playbooks using the when keyword.

What does Set_fact do in Ansible?

This module allows setting new variables. Variables are set on a host-by-host basis just like facts discovered by the setup module. These variables will be available to subsequent plays during an ansible-playbook run.

When Ansible variable is defined?

As per latest Ansible Version 2.5, to check if a variable is defined and depending upon this if you want to run any task, use undefined keyword. tasks: - shell: echo "I've got '{{ foo }}' and am not afraid to use it!" when: foo is defined - fail: msg="Bailing out. this play requires 'bar'" when: bar is undefined.


1 Answers

If variable1 is a string, and you are searching for a substring in it, this should work:

when: '"value" in variable1' 

if variable1 is an array or dict instead, in will search for the exact string as one of its items.

like image 123
guido Avatar answered Sep 19 '22 05:09

guido