diegus
diegus

Reputation: 1188

Ansible: Use variables in a playbook defined in different file (not the inventory file)

I would like to use variables defined in a file (hosts_vars) in my playbook. Here is the directory tree where the playbook is contained:

├── ansible.cfg
├── ansible.log
├── choco_deploy.yml
├── group_vars
│   └── win_clones.yml
├── hosts
├── hosts_vars

My host file:

[win_clones]
cl1 ansible_host='IP1'
cl3 ansible_host='IP2'

The hosts_vars file looks like this:

---
cl1:
  to_install:
   - soft1
   - soft2 46.0.1
  to_uninstall:
   - soft3 2.2.3
cl3:
  to_install:
  - soft4 2.2.3
  - soft5 6.9
  - sof6 6.9
  to_uninstall:
  - soft77

In my playbook I would like to refer for example to host_vars/cl1/to_install/soft1 or to loop through all the variables of host_vars/cl3/to_install/. Something like:

tasks:
- name: Installing the packages ...
  win_chocolatey:
    name: "{{ package_id }}" # here to pass variables defined in host_vars
    state: present

How can i do that? thanks

Upvotes: 1

Views: 6331

Answers (1)

Railslide
Railslide

Reputation: 5554

In your playbook you can add vars_files to specify external variables files, like this:

---

hosts: all
remote_user: root   
vars_files:
    - path/to/hosts_vars

tasks:
    - name: my awesome task
      command: /bin/echo {{ myvar }}

And in your hosts_vars:

---

myvar: "foo"
myothervar: "bar"

See: documentation for variable file separation

Upvotes: 3

Related Questions