How to check for undefined variable in Ansible. Getting error.

Incase a variable “outputmsg” has not been defined and assigned a value using set_fact in the playbook I wish to assign a string value to the variable.

Howver, if outputmsg is defined and is assigned some value which is the case, i expect the below ‘GET THE STATUS’ message to be skipped.

Below is what I do:

`

  • name: Set output message incase the process is already not RUNNING
    tags: stop_tomcat
    set_fact:
    outputmsg: “{{ ‘ALREADY in SHUTDOWN state’ if running_processes.stdout == ‘’ else ‘STOPPING NOW’ }}”

  • name: Status of Running process
    tags: always
    set_fact:
    outputmsg: “{{ ‘GET THE STATUS’ if outputmsg is undefined }}”
    `

I was expecting the above code to assign ‘GETTING THE STATUS’ incase

I’m getting the below error

TASK [Set output message incase the process is already not RUNNING] *****************************************************************************************
task path: /app/startstop.yml:127
ok: [10.9.9.111] => {“ansible_facts”: {“outputmsg”: “ALREADY in SHUTDOWN state”}, “changed”: false}

fatal: [10.9.9.111]: FAILED! => {“msg”: “The task includes an option with an undefined variable. The error was: the inline if-expression on line 1 evaluated to false and no else section was defined.\n\nThe error appears to be in ‘/app/startstop.yml’: line 177, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n - name: Status of Running process\n ^ here\n”}

Can you please suggest ?

Use *default*. For example

    - set_fact:
        outputmsg: "{{ outputmsg|default('GET THE STATUS') }}"

Cheers,

  -vlado

@vlado Thank you it helped :slight_smile:

You got a soulution from vlado, but the reason this doesn't work is because there is no test called undefined, you only have defined and can use "not" to get you desire behavior.

"{{ 'GET THE STATUS' if outputmsg is not defined }}"