Ansible dynamic inventory format

Ansible can obtain dynamic Inventroy configuration from the server interface

The dynamic inventory format is as follows:

{
    
    
	"group1": {
    
    
		"hosts": ["host1", "host2"],
		"vars": {
    
    
			"env1": "aaa",
			"env2": "bbb"
		},
	},
	"group2": {
    
    },
	"group3": {
    
    }
}

Claim:

  • The interface must return a jsondictionary, as in the above format
  • InventoryThe script must support --listoptions (list all group information in the format above)
  • InventoryThe script must support --hostoptions (list hostinformation)

use:

ansible/ansible-playbook -i inventory.py group1 -m ping

example

Server interface:

from fastapi import FastAPI
import json

app1 = FastAPI()
ansible = FastAPI()

@app1.get("/")
def sayhi():
    return {
    
    "Hello World!"}

@ansible.get("/")
def getinfo():
    info = {
    
    
        # _meta可加速--host,详情见:https://ansible-tran.readthedocs.io/en/latest/docs/developing_inventory.html
        "_meta": {
    
    
            "hostvars": {
    
    
                "192.168.161.129": {
    
    "var1": 1111, "var2": "hhhh"},
                "192.168.161.128": {
    
    "var3": 2222, "var4": "xxxx"}
            }
        },
        "group1": {
    
    
            "hosts": ["192.168.161.129"],
            "vars": {
    
    
                "group1_user": "ec2-user",
                "dbport": "3306"
            },
            "children": ["group2", "group3"]
        },
        "group2": {
    
    
            "hosts": ["192.168.161.128"]
        },
        "group3": {
    
    
            "hosts": ["192.168.161.129"]
        },
        "vars": {
    
    
            "ansible_ssh_port": "22",
            "ansible_ssh_user": "root"
        }
    }

    return info

Inventoryscript:

import requests
import sys

if sys.argv[1] == "--list":
   response = requests.get("http://192.168.30.132:8000/")
   print(response.json())

Guess you like

Origin blog.csdn.net/Free_time_/article/details/107596364