Ansible uses dynamic inventory

Ansible can not only obtain host inventory through the default hosts file, but also dynamically manage and obtain host information through external script files. The external script file that stores the host information can be written in languages ​​such as python and PHP. The returned result of the operation must be a JSON string. Ansible will parse the string in JSON format and finally convert it into the inventory file format available to Ansible. . Therefore, the so-called dynamic inventory file script development is actually to write a script to express the host information and relationship (these data can be obtained by grabbing the database, calling an external API or directly reading the file) in JSON format according to the specific environment, and express it in JSON format. Pass to Ansible as script output. Here is a python script in the form of the following hosts list (where 192.168.13.5 is unreachable):

[group1]
127.0.0.1

[group2]
192.168.13.128
192.168.13.5

[group2: vars]
ansible_ssh_port=5555
ansible_connection=ssh
# hostlist.py

#!/usr/bin/python
#coding = utf-8

import json
group1 = 'group1'
group2 = 'group2'
hosts1 = ['127.0.0.1']
hosts2 = ['192.168.13.128', '192.168.13.5']
vars = {'ansible_ssh_port': 22, 'ansible_connection': 'ssh'}
hostdata = {group1:{"hosts": hosts1}, group2:{"hosts": hosts2, "vars": vars}}
print(json.dumps(hostdata, indent=4))

Execute the script:

[root@localhost /home/***/***_test/ansible_test]# python hostlist.py
{
    "group1": {
        "hosts": [
            "127.0.0.1"
        ]
    },
    "group2": {
        "hosts": [
            "192.168.13.128",
            "192.168.13.5"
        ],
        "vars": {
            "ansible_ssh_port": 5555,
            "ansible_connection": "ssh"
        }
    }
}

Test with Ansible:

[root@localhost /home/***/***_test/ansible_test]# ansible -i hostlist.py group1 -m ping
127.0.0.1 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}

[root@localhost /home/***/***_test/ansible_test]# ansible -i hostlist.py group2 -m ping
192.168.13.5 | UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh: ssh: connect to host 192.168.13.5 port 22: No route to host\r\n",
    "unreachable": true
}
192.168.13.128 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324884516&siteId=291194637