动态配置文件

即从外部获取配置文件,在把ansible.cfg文件中inventory的定义值改成一个执行脚本
脚本必须支持两个参数:
  • --list或者-l,显示所有的主机以及主机组的信息(JSON格式)。
  • --host或者-H,这个参数后面需要指定一个host,运行结果会返回这台主机的所有信息(包括认证信息、主机变量等),也是JSON格式。

 

1、脚本

Ansible 动态配置文件
vim /tmp/p.py
#!/usr/bin/python
import sys
import json
import argparse
def lists():
  D = {}
  L=[ "10.240.1.13", "10.240.1.14","10.240.1.15" ]
  hosts={'hosts': L}
  D['docker'] = hosts
  return json.dumps(D,indent=4)
def hosts(name):
  r = {'ansible_ssh_pass': 'xxxx'}
  return json.dumps(r)
if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('-l', '--list', help='hosts list', action='store_true')
  parser.add_argument('-H', '--host', help='hosts vars')
  args = vars(parser.parse_args())
  if args['list']:
    print lists()
  elif args['host']:
    print hosts(args['host'])
  else:
    parser.print_help()
    
[root@han2 ~]# python /tmp/p.py --list
{
    "docker": {
        "hosts": [
            "10.240.1.103", 
            "10.240.1.104", 
            "10.240.1.105"
        ]
    }
}
Ansible 动态配置文件

 

2、修改配置文件

vim /etc/ansible/ansible.cfg 
inventory      = /tmp/p.py

 

3、使用动态配置

Ansible 动态配置文件
[root@han2 ~]# python /tmp/p.py --host 10.240.1.103
{"ansible_ssh_pass": "123.com"}
    
[root@han2 ~]# ansible all -m ping
10.240.1.103 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
10.240.1.104 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
10.240.1.105 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}    
Ansible 动态配置文件

 

相关文章:

  • 2022-01-12
  • 2022-12-23
  • 2021-05-26
  • 2022-12-23
  • 2021-06-09
  • 2021-07-10
  • 2021-04-08
  • 2022-01-24
猜你喜欢
  • 2021-07-07
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-30
相关资源
相似解决方案