variablesansibleyamlundefineddefault

Ansible task includes undefined var, despite being defined in defaults/main.yml


I am trying to create a Galaxy role for our org's internal galaxy, which I am testing first locally. In our org we use a common list of defaults across all roles.

Ansible is throwing me a "The task includes an option with an undefined variable The error was: 'redis_download_url' is undefined" error when running my playbook, despite me having defined the variable in defaults/main.yml:

# Download
redis_version: "6.2.3"
redis_download_url: "https://download.redis.io/releases/redis-{{ redis_version }}.tar.gz"

When running my simple role/playbook.yml

---
- hosts: all
  become: true
  tasks:
    - include: tasks/main.yml

Linked to tasks/main.yml

---
- name: Check ansible version
  assert:
    that: "ansible_version.full is version_compare('2.4', '>=')"
    msg: "Please use Ansible 2.4 or later"

- include: download.yml
  tags:
    - download

- include: install.yml
  tags:
    - install

It should pull the tar file from tasks/download.yml as stated:

---
- name: Download Redis
  get_url:
    url: "{{ redis_download_url }}"
    dest: /usr/local/src/redis-{{ redis_version }}.tar.gz

- name: Extract Redis tarball
  unarchive:
    src: /usr/local/src/redis-{{ redis_version }}.tar.gz
    dest: /usr/local/src
    creates: /usr/local/src/redis-{{ redis_version }}/Makefile
    copy: no

The redis_download_url var is defined in defaults/main.yml which as I understand ansible should be able to locate there. I also have similar vars defined in defaults/task.yml eg.

redis_user: redis
redis_group: "{{ redis_user }}"
redis_port: "6379"
redis_root_dir: "/opt/redis"
redis_config_dir: "/etc/redis"
redis_conf_file: "{{ redis_config_dir }}/{{ redis_port }}.conf"
redis_password: "change-me"
redis_protected_mode: "yes"

and I assume they are also not able to be found/seen by ansible (but it does not get that far). I have also checked all file permissions and they seem to be fine.

Apologies in advance if the question is badly formatted.


Solution

  • As per documentation:

    If you include a task file from a role, it will NOT trigger role behavior, this only happens when running as a role, include_role will work.

    To get the role functionality of reading variables from defaults/main.yml, you'll need to use include_role or roles: [].

    - hosts: all
      become: true
    
      tasks:
        - include_role:
            name: myrole
    

    OR

    - hosts: all
      become: true
    
      roles:
        - myrole