Skip to content

Instantly share code, notes, and snippets.

@gowatana
Last active May 7, 2023 06:19
Show Gist options
  • Save gowatana/6ccf3e814eecbe82ce7e425e18c2d6eb to your computer and use it in GitHub Desktop.
Save gowatana/6ccf3e814eecbe82ce7e425e18c2d6eb to your computer and use it in GitHub Desktop.
ansible dynamic inventory script for Nutanix Prism
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import json
import requests
# args = sys.argv
# conf_file = args[1]
conf_file = "/home/gowatana/prism-config.json"
def get_all_vm_inventory():
with open(conf_file, "r") as file:
conf = file.read()
conf = json.loads(conf)
prism_addr = conf["prism_address"]
prism_user = conf["user_name"]
prism_pass = conf["password"]
base_url = 'https://' + prism_addr + ':9440/PrismGateway/services/rest/v2.0/'
insecure_warn = requests.packages.urllib3.exceptions.InsecureRequestWarning
requests.packages.urllib3.disable_warnings(insecure_warn)
s = requests.Session()
s.auth = (prism_user, prism_pass)
s.headers.update({'Content-Type': 'application/json; charset=utf-8'})
# Get VM.
url = base_url + 'vms/?include_vm_nic_config=true'
vms = s.get(url, verify=False).json()
inventory = {
"all":{"hosts": []},
"poweron_vms":{"hosts": []},
"poweroff_vms":{"hosts": []},
"_meta": {
"hostvars": {}
}
}
vm_entities = []
hosts = {}
for vm in vms['entities']:
#print(json.dumps(vm, indent=2))
vm_name = vm['name']
power_state = vm['power_state']
if(vm['power_state'] == 'on'):
inventory["poweron_vms"]["hosts"].append(vm_name)
else:
inventory["poweroff_vms"]["hosts"].append(vm_name)
inventory["all"]["hosts"].append(vm_name)
if(vm['vm_nics']):
vm_nic = vm['vm_nics'][0]
ip_address = vm_nic.get('ip_address')
requested_ip_address = vm_nic.get('requested_ip_address')
if (ip_address == None):
ip_address = vm_nic.get('requested_ip_address')
if ip_address:
inventory["_meta"]["hostvars"][vm_name] = {"ansible_host": ip_address, "power_state": power_state}
else:
inventory["_meta"]["hostvars"][vm_name] = {}
return(inventory)
if __name__ == '__main__':
hostname = None
inventory = get_all_vm_inventory()
if len(sys.argv) > 1:
if sys.argv[1] == "--host":
hostname = sys.argv[2]
if hostname:
if inventory["_meta"]["hostvars"][hostname]:
print(json.dumps(inventory["_meta"]["hostvars"][hostname]))
else:
print(json.dumps(inventory))
@gowatana
Copy link
Author

ログイン情報のファイルを作成しておく。

$ cat /home/gowatana/prism-config.json
{
    "prism_address": "ntnx-n-01.go-lab.jp",
    "user_name": "admin",
    "password": "password strings"
}

@gowatana
Copy link
Author

何かエラーが出る。

$ ansible all -i ./ahv_inventory.py --list-hosts
 [ERROR]:

  hosts (3):
    vm03
    vm02
    vm01

@gowatana
Copy link
Author

設定の補足。下記も必要。

$ chmod +x ahv_inventory.py
$ pip install requests

@gowatana
Copy link
Author

@gowatana
Copy link
Author

下記の Python / Ansible では普通に使えた。

環境

$ python -V
Python 3.6.8
$ ansible --version
ansible 2.10.8
  config file = /home/gowatana/demo-nutanix-ansible/05_inventory/ansible.cfg
  configured module search path = ['/home/gowatana/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /home/gowatana/ansible/lib/python3.6/site-packages/ansible
  executable location = /home/gowatana/ansible/bin/ansible
  python version = 3.6.8 (default, Nov  5 2020, 18:03:20) [GCC 8.3.1 20191121 (Red Hat 8.3.1-5.0.1)]

実行した様子。

$ ansible all --list-hosts
  hosts (4):
    ol83-min-01
    vm01
    test-vm-clone-01
    demo-ansible-01
$ ansible-inventory --host test-vm-clone-01
{
    "ansible_host": "192.168.11.134"
}

@shklpshs
Copy link

shklpshs commented Nov 5, 2022

I am surprised to see from your output 2 things

  1. Red Hat 8.3.1-5.0.1
    2)ansible 2.10.8
    How was that possible do we have 2.10 for RHEL8 ?
    Could you please help me how to update ansible2.9 to 2.10 on EL8
    Much Appreciated

$ python -V
Python 3.6.8
$ ansible --version
ansible 2.10.8
config file = /home/gowatana/demo-nutanix-ansible/05_inventory/ansible.cfg
configured module search path = ['/home/gowatana/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /home/gowatana/ansible/lib/python3.6/site-packages/ansible
executable location = /home/gowatana/ansible/bin/ansible
python version = 3.6.8 (default, Nov 5 2020, 18:03:20) [GCC 8.3.1 20191121 (Red Hat 8.3.1-5.0.1)]

@shklpsh
Copy link

shklpsh commented Nov 5, 2022

Nutanix Dynamic Inventory Worked charm
Could you please help update this script so that i can only import VMs which are power-on only
i dont want to import power-off vms

@shklpsh
Copy link

shklpsh commented Nov 5, 2022

Much Appreciated

@HariKrishnaTulzapur
Copy link

The Script worked. Thank you.
Can you please help me to filter only power-on machines. How to apply the filters using ansible-playbook.
Using hosts as all is providing all the machines in nutanix environment. This is sample playbook example


  • name: Check whether realm installed or not
    hosts: all
    become: yes
    become_user: root
    tasks:
    • name: Run the command to check realm installed or not
      shell:
      "/usr/sbin/realm list|grep -i permitted"
      register: result

Command executed is
#ansible-playbook -i nutanix_inventory.py realminstalledORnot.yml

Please help on this.

Thank you. Appreciate your help.

@gowatana
Copy link
Author

gowatana commented May 5, 2023

PowerOn / PowerOff の VM をグループ化できるようにしてみた。

$ ansible-inventory -i ./ahv_inventory.py --graph
@all:
  |--@poweroff_vms:
  |  |--dev-vm-01
  |  |--lab-oracle-01
  |  |--ol87-base-01
  |--@poweron_vms:
  |  |--demo-ansible-01
  |  |--demo-ansible-02
  |  |--lab-ndb-01
  |  |--ndb-oracle-01
  |--@ungrouped:
$ ansible -i ./ahv_inventory.py --list-hosts poweron_vms
  hosts (4):
    lab-ndb-01
    demo-ansible-02
    ndb-oracle-01
    demo-ansible-01
$ansible-inventory -i ./ahv_inventory.py --host ndb-oracle-01
{
    "ansible_host": "192.168.11.125",
    "power_state": "on"
}
$ ansible-inventory -i ./ahv_inventory.py --host dev-vm-01
{
    "ansible_host": "192.168.11.146",
    "power_state": "off"
}

@gowatana
Copy link
Author

gowatana commented May 7, 2023

実行例はこちら。

Nutanix から仮想マシンを取得する Ansible Dynamic Inventory を作成してみる。(REST API v2)
https://blog.ntnx.jp/entry/2023/05/07/150924

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment