Eva
Eva

Reputation: 593

Ansible - Can't access value - Got error: 'dict object' has no attribute

---
- hosts: localhost
  gather_facts: no
  vars:
    var_folder_path: /home/play
  tasks:
    - name: Include all yaml files in directories
      include_vars:
        dir: "{{ var_folder_path }}/vars"
        extensions:
          - 'yaml'

    - name: "Print Variable Name"
      shell: echo "{{ item }}"
      loop:
        - "{{ global.globalname.property.Name }}"
        - "{{ S3.secret }}"

My var files under /home/play/vars

example_1.yaml

global:
  globalname:
    property:
      cipher: DEFAULT
      client:
        type: dynamic
      Name: test-run

example_2.yaml

gcp:
  keyname: sample-run
S3:
  secret: run
Resources: false
celery:
  resources:
    limits:
      cpu: 5

When I execute the playbook I get the below error. Not sure why the values are not loading

fatal: [localhost]: FAILED! => {"msg": "'dict object' has no attribute 'globalname'"}

Upvotes: 0

Views: 3341

Answers (2)

M I P
M I P

Reputation: 917

As mentioned in my comment above, there are no issues with the playbooks you shared, except for the "S3" variable definition in example_2.yaml, which should be "s3" (in lower case).

One possible cause for the error you reported is that there are more than one "global" var definition in the var files at /home/play/vars, and is overriding the global var definition in example_1.yaml.
Default Ansible merge is in ASCII order, i.e., the last group loaded overwrites the previous groups. See how-variables-are-merged from Ansible official documentation for more details on how variables are merged in Ansible and update your var files accordingly.

As mentioned by user @phanaz in the other answer, its a good practice to use "debug" module for printing the vars to validate, in such scenarios.

Upvotes: 1

phanaz
phanaz

Reputation: 1524

To debug a playbook when an error occurs, it is very often a good idea to insert a debug task.

In your case insert a debug task before the shell task and get the whole variable global output:

- debug:
    var: global

Upvotes: 2

Related Questions