Skip to content

Instantly share code, notes, and snippets.

@oskaralmlov
Last active October 28, 2022 14:57
Show Gist options
  • Save oskaralmlov/621b4a6c7b1d2c2877585552f8baadfe to your computer and use it in GitHub Desktop.
Save oskaralmlov/621b4a6c7b1d2c2877585552f8baadfe to your computer and use it in GitHub Desktop.
from ansible.cli import CLI
from ansible.template import Templar
from ansible.vars.manager import VariableManager
from ansible.parsing.dataloader import DataLoader
from ansible.inventory.manager import InventoryManager
import ansible.constants as C
def main():
# The DataLoader is responsible for loading yaml/json content
loader = DataLoader()
# Setup vault secrets
vault_secrets = CLI.setup_vault_secrets(
loader,
vault_ids=C.DEFAULT_VAULT_IDENTITY_LIST,
)
# Provide the loader with the vault secret
loader.set_vault_secrets(vault_secrets)
# If you have a layout where group_vars shared between different inventories are
# are stored adjacent to playbooks in a separate directory you need to update the
# loader basedir. This is similar to how you might need to provide the --playbook-dir
# flag to ansible-inventory.
# Example:
# ansible_directory/
# |- playbooks/
# |- playbook.yml
# |- group_vars/
# |- webservers/
# |- testing/
# |- group_vars/
# |- webservers/
# |- production/
# |- group_vars/
# |- webservers/
loader.set_basedir('playbooks')
# The InventoryManager creates and manages the inventory using the provided loader
inventory = InventoryManager(loader=loader, sources='testing')
# The VariableManager loads variables using the provided loader
variable_manager = VariableManager(loader=loader, inventory=inventory)
for host in inventory.get_hosts():
host_vars = variable_manager.get_vars(host=host)
# The templar helps us to expand/resolve variables
# variable_name: {{ inventory_hostname }} --> host.example.com
templar = Templar(loader=loader, variables=host_vars)
for var_name, var_value in host_vars.items():
# Expand variables that require it
print(var_name, templar.template(var_value))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment