2

Ansible: Skip Parameter If Variable Not Defined

 1 year ago
source link: https://www.shellhacks.com/ansible-skip-parameter-if-variable-not-defined/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Ansible: Skip Parameter If Variable Not Defined

In Ansible, if you run a task that has some module’s parameter with a variable that is not set you will get “The task includes an option with an undefined variable” error.

If for some reason you can’t or don’t want to define this variable, you can make it optional.

In this case Ansible will ignore the parameter with the optional variable if it is not defined.

This note shows how to skip a module’s parameter in Ansible if a variable is not defined.

Cool Tip: How to set default values for variables in Ansible! Read more →

Skip Parameter If Variable Not Defined

Lets say we have a task with some variable that is not defined:

- name: "Count Files"
  shell: ls | wc -l
  args:
    chdir: "{{ directory }}" # undefined

If we run this task, it will throw the error as follows:

TASK [Count Files] ************************************************************
fatal: [127.0.0.1]: FAILED! => 
  msg: |-
    The task includes an option with an undefined variable.
    The error was: 'directory' is undefined
  
    The error appears to be in 'playbook.yml': line 5, column 7, but may
    be elsewhere in the file depending on the exact syntax problem.
  
    The offending line appears to be:
  
      tasks:
        - name: "Count Files"
          ^ here

If for some reason we don’t want or can’t set the default value for such variable, we can use the default(omit) filer that will make it optional:

- name: "Count Files"
  shell: ls | wc -l
  args:
    chdir: "{{ directory | default(omit) }}"

If the variable is not set but it is optional, Ansible simply skips the parameter with such kind of undefined variable:

TASK [Count Files] ************************************************************
changed: [127.0.0.1] => changed=true 
  cmd: ls | wc -l
  delta: '0:00:00.004890'
  end: '2022-08-03 09:48:39.285966'
  msg: ''
  rc: 0
  start: '2022-08-03 09:48:39.281076'
  stderr: ''
  stderr_lines: <omitted>
  stdout: '7'
  stdout_lines: <omitted>

Cool Tip: How to test a variable in Ansible: if it exists or not, if it is empty or not and if it is set to True or False! Read more →


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK