include_vars in folders

23 views
Skip to first unread message

Eric Chang

unread,
Feb 14, 2020, 10:00:06 PM2/14/20
to Ansible Project

this task should load all yaml files in /home/yaml/users and assign to var 'users'

- name: load yaml using include_vars with dir
  include_vars:
    name: 'users'
    dir: /home/yaml/users/
  delegate_to: localhost
  
- name: debug users
  debug:
    var: 'users'

but why debug message shows only the last yaml file content , not the all  ??



Vladimir Botka

unread,
Feb 14, 2020, 10:38:59 PM2/14/20
to Eric Chang, ansible...@googlegroups.com
On Fri, 14 Feb 2020 19:00:05 -0800 (PST)
Eric Chang <chan...@gmail.com> wrote:

> > - name: load yaml using include_vars with dir
> > include_vars:
> > name: 'users'
> > dir: /home/yaml/users/
> > delegate_to: localhost
> >
> > - name: debug users
> > debug:
> > var: 'users'
> >
>
> but why debug message shows only the last yaml file content , not the all
> ??

Works as expected for me. For example the files

$ cat yaml/users/user1.yml
user1: 'user1_var'
$ cat yaml/users/user2.yml
user2: 'user2_var'
$ cat yaml/users/user3.yml
user3: 'user3_var'

give

"users": {
"user1": "user1_var",
"user2": "user2_var",
"user3": "user3_var"
}

Probably, you might be interested in "DEFAULT_HASH_BEHAVIOUR"
https://docs.ansible.com/ansible/latest/reference_appendices/config.html#default-hash-behaviour

With the changed variables in the files

$ cat yaml/users/user1.yml
user: 'user1_var'
$ cat yaml/users/user2.yml
user: 'user2_var'
$ cat yaml/users/user3.yml
user: 'user3_var'

the variables overwrite each other, as expected

"users": {
"user": "user3_var"
}


HTH,

-vlado

Eric Chang

unread,
Feb 15, 2020, 3:16:02 AM2/15/20
to Ansible Project
so any suggesions to combine multiple yaml files with same attributes ?

Vladimir Botka

unread,
Feb 15, 2020, 4:42:57 AM2/15/20
to Eric Chang, ansible...@googlegroups.com
On Sat, 15 Feb 2020 00:16:02 -0800 (PST)
Eric Chang <chan...@gmail.com> wrote:

> so any suggesions to combine multiple yaml files with same attributes ?

Sure. For example

- set_fact:
users: "{{ users|
default({})|
combine({my_key: my_value}) }}"
vars:
my_key: "{{ (item|basename|splitext).0 }}"
my_value: "{{ lookup('file', item)|from_yaml }}"
with_fileglob: "yaml/users2/*.yml"
- debug:
var: users

give

"users": {
"user1": {
"user": "user1_var"
},
"user2": {
"user": "user2_var"
},
"user3": {
"user": "user3_var"
}
}

HTH,

-vlado
Reply all
Reply to author
Forward
0 new messages