更新时间:2022-09-09 23:14:46
参考https://segmentfault.com/a/1190000008459574
group_vars
mkdir -p group_vars/dev group_vars/prod
touch group_vars/dev/nginx.yml group_vars/prod/nginx.yml
├── nginx.yml
├── named.conf.j1
├── named.conf.j2
└── nginx
└── tasks
└── main.yml
cat group_vars/dev/nginx.yml
nginx: 172.1.1.1
ip:
api: ['172.1.1.126:8080']
vim nginx.yml
- hosts: "` nginx `"
remote_user: root
gather_facts: no
vars_files:
- foo.yml
tasks:
- name: copy
template: dest=/tmp/`item`.`key`.conf src=/etc/ansible/test1/named.conf.j2 force=yes
with_dict: "` ip `"
- name: copy
template: dest=/tmp/`item`.`key`.conf src=/etc/ansible/test1/named.conf.j1 force=yes
with_dict: "` ip `"
├── named.conf.j1
├── named.conf.j2
(./set
upstream ` item`.`key ` {
{% for key in item.value %}
` key ` weight=1;
{% endfor %}
check interval=2000 rise=2 fall=2 timeout=1000 type=http;
check_http_send "GET / HTTP/1.0\r\n\r\n";
check_http_expect_alive http_2xx http_3xx;
}
---
./conf
server {
listen 80;
server_name `item`.`key`.com;
location / {
proxy_next_upstream http_500 http_502 http_503 http_504 error timeout invalid_header;
proxy_pass http://`item`.`key`;
}
}
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
cat / etc / ansible / test.py
import sys
try :
import json
except ImportError:
import simplejson as json
def grouplist():
inventory = {}
sfile = '/etc/ansible/books.txt'
with open (sfile, 'rb' ) as f:
for i in f.readlines():
group = i.strip().split()[ 0 ]
name = i.strip().split()[ 1 ]
if not group in inventory:
inventory[group] = {
'hosts' : []
}
inventory[group][ 'hosts' ].append(name)
print json.dumps(inventory, indent = 4 )
def hostinfo(name):
vars = {}
vars = {
'admin' : 'Jane Jolie' ,
'datacenter' : 1
}
print json.dumps( vars , indent = 4 )
if __name__ = = '__main__' :
if len (sys.argv) = = 2 and (sys.argv[ 1 ] = = '--list' ):
grouplist()
elif len (sys.argv) = = 3 and (sys.argv[ 1 ] = = '--host' ):
hostinfo(sys.argv[ 2 ])
else :
print "Usage: %s --list or --host <hostname>" % sys.argv[ 0 ]
sys.exit( 1 )
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
|
cat / etc / ansible / foo.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import ConfigParser
import string, os, sys,json
import yaml
''' vim books.txt api 172.1.1.126 dev 8005 8080 api bj5 pf 172.1.1.127 prod 8006 8081 pf bj02 ''' ''' 生成的foo.yml ip: api: ['172.1.1.126:8080']
''' def ynameconf():
sfile = 'books.txt'
stagedict = {}
with open (sfile, 'rb' ) as f:
for i in f.readlines():
inventory = {}
ip = i.strip().split()[ 1 ]
yname = i.strip().split()[ 5 ] # 域名
stage = i.strip().split()[ 2 ]
if stage not in stagedict:
if not yname in inventory:
inventory[yname] = []
port = i.strip().split()[ 4 ]
ipport = ip + ":" + port
inventory[yname].append(ipport)
stagedict[stage] = inventory
print stagedict
elif stage in stagedict:
dict1 = stagedict[stage]
if not yname in inventory:
inventory[yname] = []
port = i.strip().split()[ 4 ]
ipport = ip + ":" + port
inventory[yname].append(ipport)
dict2 = inventory
newdict = dict (dict1.items() + dict2.items())
stagedict[stage] = newdict
f.close()
return stagedict
def ynameParser(stage, file ):
# cf = ConfigParser.ConfigParser()
ynameyname = ynameconf()
# print ynameyname
# devstage = ynameyname[stage]
# jsObj = json.dumps(devstage)
# fileObject = open(file, 'w')
# fileObject.write(jsObj)
# fileObject.close()
print type (jsObj)
fileObject = open ( file , 'w' )
dataMap = { "ip" : jsObj}
yaml.dump(dataMap, fileObject)
'''
for k,v in ynameyname.iteritems():
general=k
cf.add_section(general)
cf.set(general, "pro_dir", k)
for i in range(len(v)):
ips="ip"+str(i+1)
cf.set(general,ips, v[i])
# cf.set(k, ','.join(v))
cf.write(open("vhost.fact", "w"))
'''
if __name__ = = '__main__' :
list2 = [ "foo.yml" , "foo2.yml" ]
list1 = [ "dev" , "prod" ]
for (stage, file ) in zip (list1, list2):
ynameParser(stage, file )
|
使用
python foo.py
ansible-playbook -i /etc/ansible/test.py nginx.yml
后者
- hosts: nginx
remote_user: root
gather_facts: no
vars:
ipall: {'api':['172.1.1.2'],'api3':['172.1.1.1']}
tasks:
- name: get
set_fact:
iplist: "{{ lookup('file', '/etc/ansible/foo.txt') }}"
- name: copy
template: dest=/usr/local/tengine/conf/SET/`item`.`key`.conf src=/etc/ansible/named.conf.j2 force=yes
with_dict: iplist
- name: copy
template: dest=/usr/local/tengine/conf/conf.d/`item`.`key`.conf src=/etc/ansible/named.conf.j1 force=yes
with_dict: iplist