2

How to run a task conditionally when the user provides some input to vars_prompt. Problem is, my variable is treated as bool and yes and no are never matched.

- hosts: localhost
  gather_facts: no
  vars_prompt:
    - name: "myvar"
      prompt: "Do you want to proceed(yes/no)?"
      private: no

  tasks:

    - name: "Set variable"
      set_fact:
        myvar: "{{ myvar }}"

    - name: "Conditional task"
      shell: echo "conditional action"
      when: "'yes' in myvar"

I am getting following error message when I run above code:

fatal: [localhost]: FAILED! => {}

MSG:

The conditional check ''yes' in myvar' failed. The error was: Unexpected templating type error occurred on ({% if 'yes' in myvar %} True {% else %} False {% endif %}): argument of type 'bool' is not iterable

The error appears to have been in '/home/monk/samples/user.yml': line 14, column 7, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:


    - name: "Conditional task"
      ^ here
Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63
monk
  • 1,953
  • 3
  • 21
  • 41

2 Answers2

3

The conversion to Boolean is actually done when you re-affect your variable with set_fact which is not needed (unless you want to use it in a subsequent play). The following actually works as you expect:

---
- hosts: localhost
  gather_facts: false
  vars_prompt:
    - name: myvar
      prompt: "yes or no?"
      private: no
  tasks:
    - debug:
        msg: yes was entered
      when: "'yes' in myvar"

Meanwhile, this is probably not the best way to solve your problem. I would rather cast the answer to bool to test directly on it (and you could eventually use set_fact again if you need you prompt in the next play).

---
- hosts: localhost
  gather_facts: false
  vars_prompt:
    - name: myvar
      prompt: "yes or no?"
      private: no
  tasks:
    - debug:
        msg: yes was entered
      when: myvar | bool
Zeitounator
  • 38,476
  • 7
  • 53
  • 66
2

Q: Prevent conversion of variable to bool in ansible.

A: See How Exactly Does Ansible Parse Boolean Variables?. It's possible to simply evaluate the variable myvar in the condition

- name: "Set variable"
  set_fact:
    myvar: "{{ myvar }}"
- name: "Conditional task"
  shell: echo "conditional action"
  when: myvar

The condition when: "'yes' in myvar" does not work because myvar isn't a list. This the reason for the error:

argument of type 'bool' is not iterable


Notes

Prompts for individual vars_prompt variables will be skipped for any variable that is already defined through the command line --extra-vars option ...

Values passed in using the key=value syntax are interpreted as strings. Use the JSON format if you need to pass in anything that shouldn’t be a string (Booleans, integers, floats, lists etc).

Therefore, to be on the safe side, use explicit bool cast

when: myvar|bool
Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63