0

Let's say I have a playbook that uses two roles like this.

---
- hosts: database
  become: yes
  roles:
    - role: foo_role_one
    - role: foo_role_two

And I have a file in /group_vars/database/vars.yml like this.

---
username: bar

The username variable is used by both foo_role_one and foo_role_two, but the values are not identical. I know I could include the variable directly as a child of - role: foo_role_one, but I am attempting to keep my playbooks clean with the variables for groups and and hosts in their own files. To accomplish this I'd like to do some like this.

---
- hosts: database
  become: yes
  roles:
    - role: foo_role_one
      '{{ foo_one }}'
    - role: foo_role_two
      '{{ foo_two }}'

And then in /group_vars/database/vars.yml have the following.

---
foo_one:
  username: bar
foo_two:
  username: baz

I cannot find a syntax with the yaml spec that will allow me to do this. I thought anchors and references would do it, but it appears that they do not span yaml files.

David Baucum
  • 2,162
  • 24
  • 25

1 Answers1

2

I think you'll find what you're looking for right in the roles documentation, which shows, for example in which two roles both want variables named dir and app_port, but the values for each role need to be different:

- hosts: webservers
  roles:
    - common
    - role: foo_app_instance
      vars:
        dir: '/opt/a'
        app_port: 5000
      tags: typeA
    - role: foo_app_instance
      vars:
        dir: '/opt/b'
        app_port: 5001
      tags: typeB

I believe that's the same situation you're asking about.

larsks
  • 277,717
  • 41
  • 399
  • 399
  • I was hoping to avoid a solution like this, but I think you are right. This is probably the best way to accomplish this. – David Baucum Mar 05 '21 at 04:12
  • I understand now what you're trying to do. I think you'll find the answers to [this question](https://stackoverflow.com/questions/50477012/how-to-use-a-dictionary-of-registered-ansible-variables-in-vars) to be of interest (but not of help). – larsks Mar 05 '21 at 13:38