0

I'm trying to find a way to store Ansible inventory files on a location other than the server's local space (say for example Azure). Is this something that can be achieved by Ansible Dynamic Inventory? I have read the documentation about dynamic inventory but to me, it's a bit confusing. Probably because of a lack of knowledge on my side.

So simply speaking, my question is: Is there a way to store ansible inventory files on a remote location and ask ansible to read it from there when running the playbooks/roles? If so, what is it?

1 Answers1

0

Yes, this can only be done via a dynamic inventory. Write a python script like:

#!/usr/bin/env python

import os
import sys
import argparse
import json
import requests

class MyInventory(object):

  def __init__(self):
    self.inventory = {}
    self.read_cli_args()

    # Called with `--list`.
    if self.args.list:
      self.inventory = self.my_inventory()

    # Called with `--host [hostname]`.
    elif self.args.host:
      # Not implemented, since we return _meta info `--list`.
      self.inventory = self.host_inventory(self.args.host)

    # If no groups or vars are present, return an empty inventory.
    else:
      self.inventory = self.empty_inventory('no args')
        
    print(json.dumps(self.inventory, indent=2, sort_keys=True))

  def my_inventory(self):
    try:
      if "INVENTORY_ENDPOINT" in os.environ:
        url = os.environ.get('INVENTORY_ENDPOINT')
      else:
        url = 'https://myserver/inventory'

      if "INVENTORY_USERNAME" in os.environ:
        username = os.environ.get('INVENTORY_USERNAME')
      else:
        return self.empty_inventory('environment-variable INVENTORY_USERNAME not set')

      if "INVENTORY_PASSWORD" in os.environ:
        password = os.environ.get('INVENTORY_PASSWORD')
      else:
        return self.empty_inventory('environment-variable INVENTORY_PASSWORD not set')
      
      headers = {
        'Accept': 'application/json',
        'User-Agent': 'dynamic-inventory-script/v1.0',
        'Connection': 'close'
      }
      
      result = requests.get(url, timeout=5, auth=(username,password), headers=headers)
      result.encoding = 'utf-8'
      return json.loads(result.text)        
    except:
      return {}      

  # Host inventory for testing.
  def host_inventory(self, hostname):
    return {
      '_meta': {
        'hostvars': {}
      }
    }

  # Empty inventory for testing.
  def empty_inventory(self,message):
    return {
      '_meta': {
        'hostvars': {
          'mesage': message
        }
      }
    }

  # Read the command line args passed to the script.
  def read_cli_args(self):
    parser = argparse.ArgumentParser()
    parser.add_argument('--list', action = 'store_true')
    parser.add_argument('--host', action = 'store')
    self.args = parser.parse_args()

# Get the inventory.
MyInventory()

The URL that is either be hardcoded or a system environment variable should point to a JSON formatted inventory.

Be aware - dynamic inventories are always in JSON format and do have a different layout then INI or YAML files. See https://docs.ansible.com/ansible/latest/dev_guide/developing_inventory.html#developing-inventory-scripts

You can than call you ansible-playbook via

ansible-playbook -i inventory.py ...

Be aware - the inventory script must not be a python script. A bash script would work too. Only the JSON output is necessary.

#!/bin/sh

if [ -z "$INVENTORY_USERNAME" ]; then
    echo "{}"
    exit 0
fi

if [ -z "$INVENTORY_ENDPOINT" ]; then
    INVENTORY_ENDPOINT="https://myserver/inventory"
fi

curl -s GET "$INVENTORY_ENDPOINT" -H "accept: application/json" --user $INVENTORY_USERNAME:$INVENTORY_PASSWORD &> /dev/stdout

#eof
TRW
  • 488
  • 3
  • 16
  • Thanks for the answer. I'll try the way you explained and see how it goes. – ERH7777777 Jan 11 '21 at 23:07
  • ah, i forgot - the script must not be a python script - a bash script with a curl would be ok too, but the result must be a JSON - that is a fact. – TRW Jan 12 '21 at 07:17