Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using variables from one yml file in another playbook

I am new to ansible and am trying to use variables from a vars.yml file in a playbook.yml file.

vars.yml

---
- firstvar:
    id: 1
    name: One
- secondvar:
    id: 2
    name: two

playbook.yml

---
- hosts: localhost

  tasks:
  - name: Import vars
    include_vars:
      file: ./vars.yml
      name: vardata

  - name: Use FirstVar
    iso_vlan:
      vlan_id: "{{ vardata.firstvar.id }}"
      name: "{{ vardata.firstvar.name }}"
      state: present

  - name: Use Secondvar
    iso_vlan:
      vlan_id: "{{ vardata.secondvar.id }}"
      name: "{{ vardata.secondvar.name }}"
      state: present

So you can see here I am treating the imported variable data, which is stored in vardata, as object and trying to call each of them in other tasks. I am pretty sure these imported vars at the first task are only available in that very task. How can I use that in other tasks? It would output as variables undefined for each tasks. Any input is appreciated.

like image 975
robinhoodjr Avatar asked Aug 21 '18 03:08

robinhoodjr


People also ask

How do you pass a variable from one YAML to another?

To pass params between yml files in Azure DevOps you have to specify a path to the template (the file you want to pass the param across to) and give the parameter a value. Then in the second file also declare the parameter.

How do you pass variables in ansible playbook?

To pass a value to nodes, use the --extra-vars or -e option while running the Ansible playbook, as seen below. This ensures you avoid accidental running of the playbook against hardcoded hosts.

How do you use variables in playbook?

Save and close the file when you're done editing. The vars section of the playbook defines a list of variables that will be injected in the scope of that play. All tasks, as well as any file or template that might be included in the playbook, will have access to these variables.

Can YAML use variables?

YAML does not natively support variable placeholders. Anchors and Aliases almost provide the desired functionality, but these do not work as variable placeholders that can be inserted into arbitrary regions throughout the YAML text. They must be placed as separate YAML nodes.


1 Answers

Your vars.yml file isn't formatted correctly.

Try this:

---

firstvar:
  id: 1
  name: One
secondvar:
  id: 2
  name: two

I used this to test it:

---
- hosts: localhost

  tasks:
    - name: Import vars
      include_vars:
        file: ./vars.yml
        name: vardata

    - name: debug
      debug:
        msg: "{{ vardata.firstvar.name }}"

    - name: more debug
      debug:
        msg: "{{ vardata.secondvar.id }}"
like image 130
kenlukas Avatar answered Oct 20 '22 07:10

kenlukas