cph
cph

Reputation: 458

Why can't I access vars loaded via file in Ansible?

Why can't I access these Ansible file variables from within the Ansible task?

I've tried vars_files as well wit combinations of calling global.varname and global[varname]

- hosts: localhost
  gather_facts: True
  remote_user: root
  - include_vars: site_vars.yml
  tasks:
    - digital_ocean:
        state: present
        command: droplet
        unique_name: yes
        name: do_16_04_common
        api_token: "{{HOST_PROVIDER}}"

global_vars.yml:

global:
  WORKER_TAG_PREFIX:"dev"
  HOST_PROVIDER:"heroku-prod"

Error:

fatal: [localhost]: FAILED! => {"failed": true, "msg": "ERROR! 'ansible.parsing.yaml.objects.AnsibleUnicode object' has no attribute 'WORKER_TAG_PREFIX'"}

Upvotes: 1

Views: 2419

Answers (1)

techraf
techraf

Reputation: 68439

Firstly, your vars file is broken - it requires spaces between : and the values (and you don't need quotes for strings in this example):

global:
  WORKER_TAG_PREFIX: dev
  HOST_PROVIDER: heroku-prod

The above is the reason for the included error, but then the code has also syntax error which should be thrown first:

The correct syntax to include vars files at the play level is to define a vars_files key containing a list of files:

- hosts: localhost
  gather_facts: True
  remote_user: root
  vars_files:
    - site_vars.yml
  tasks:
    # ...

On the other hand, include_vars is a module (action) name for a task.

If you wanted to use it, you should add it to the tasks list:

- hosts: localhost
  gather_facts: True
  remote_user: root
  tasks:
    - include_vars: site_vars.yml

Upvotes: 2

Related Questions