Ansible Python API - how to get variables defined in vars_files, host_vars, group_vars

Viewed 727

I am trying to pull variables from all possible locations using Python API

In my playbook test_play.yml I have..

---
hosts: abc.com
gather_facts: no

roles:
  - my_roles

vars_files:
  - var/var.yml    

tasks:   
  .....
  .....

file structure -

test_play.yml
roles
  - my_roles
    -- defaults
vars
  - var.yml
hosts
  - DEV
    -- hosts
    -- group_vars
       --- all.yml

My code --

host_file = path_to_host_file
play_path = path_to_playbook

inventory = InventoryManager(loader=DataLoader(), source=[host_file])
variable_manager = VariableManager(loader=DataLoader(), inventory=inventory)

pb = Playbook.load(play_path, variable_manager, DataLoader())
play = pb.get_plays()

# here I get one play, which is fine
all_vars = variable_manager.get_vars(play=plays[0])

in all_vars, I am getting variables defined in inventory file, rules only. But the variables defined in var.yml, group_vars/all.yml are missing. How to get them?

1 Answers

You just need to:

variable_manager.get_vars(host=inventory.get_host("hostname"))

It is sad that Ansible does not provide a better documentation for their API.

Related