blob: 675000428efd64acb78b003f42ef0ac412c19c22 [file] [log] [blame]
ecnoelc8bb28a2017-07-06 09:02:01 -05001'''
2/*-
3* ============LICENSE_START=======================================================
4* APPC
5* ================================================================================
6* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
7* ================================================================================
8* Licensed under the Apache License, Version 2.0 (the "License");
9* you may not use this file except in compliance with the License.
10* You may obtain a copy of the License at
11*
12* http://www.apache.org/licenses/LICENSE-2.0
13*
14* Unless required by applicable law or agreed to in writing, software
15* distributed under the License is distributed on an "AS IS" BASIS,
16* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17* See the License for the specific language governing permissions and
18* limitations under the License.
19* ============LICENSE_END=========================================================
20* ECOMP is a trademark and service mark of AT&T Intellectual Property.
21*/
22'''
23
24import pymysql, sys
25from os import listdir
26from os.path import isfile, join
27
28class mySql():
29
30 def __init__(self, myhost, myuser, mypasswd, mydb):
31 self.con = True
32 self.error = ''
33 self.db = None
34 try:
35 self.db = pymysql.connect(host=myhost,
36 user=myuser,
37 passwd=mypasswd,
38 db=mydb)
39 self.cur = self.db.cursor()
40 except Exception as e:
41 self.error = e[1]
42 self.con = False
43
44 def Query (self, myquery, val = None):
45 results = None
46 try:
47 if val:
48 self.cur.execute(myquery, val)
49 else:
50 self.cur.execute(myquery)
51 self.db.commit()
52 results = self.cur.fetchall()
53 except Exception, e:
54 results = repr(e)
55 return results
56
57 def Close (self):
58 if self.db:
59 self.db.close()
60
61def loadPlaybook (sqlintf, value, version, ext = '.yml'):
62
63 errorCode = 0
64 diag = ''
65
66 # Test if primary key already defined
67 query = "SELECT name FROM playbook WHERE name='" + value +"'"
68 results = sqlintf.Query (query)
69 if len(results) > 0:
70 pass
71 else:
72 query = "INSERT INTO playbook (name) VALUES ('" + value + "')"
73 results = sqlintf.Query (query)
74 if len(results) > 0:
75 errorCode = 1
76 diag = results
77
78 # Load playbook
79 file = open(playbook_path + value + ext, 'r')
80 load_file = file.read()
81
82 if not errorCode:
83 sql = "UPDATE playbook SET value=%s, version=%s, type=%s WHERE name=%s"
84
85 results = sqlintf.Query(sql, (load_file, version, ext, value))
86
87 if len (results) > 0:
88 # Error loading playbook
89 errorCode = 1
90 diag = results
91
92 return errorCode, diag
93
94def loadCredentials (sqlintf, hostgroup, hostname, cred):
95 errorCode = 0
96 diag = ''
97
98 # Load credentials
99
100 query = "SELECT hostname,hostgroup FROM inventory WHERE hostname='" + hostname +"'"
101 results = sqlintf.Query (query)
102
103 if hostname in str (results):
104
105 results_hostgroups = results[0][1]
106
107 if hostgroup in results_hostgroups.split(','):
108 query = "UPDATE inventory SET hostname='" + hostname + "',credentials='" +\
109 cred +\
110 "' WHERE hostname='" + hostname + "'"
111 else:
112
113 results_hostgroups = results_hostgroups + ',' + hostgroup
114
115 query = "UPDATE inventory SET hostname='" + hostname + "',credentials='" +\
116 cred + "',hostgroup='" + results_hostgroups + \
117 "' WHERE hostname='" + hostname + "'"
118
119 results = sqlintf.Query (query)
120
121 else:
122
123 query = "INSERT INTO inventory (hostgroup, hostname, credentials) VALUES ('" + \
124 hostgroup + "','" + hostname + "','" + cred + "')"
125 results = sqlintf.Query (query)
126
127 if len (results) > 0:
128 # Error loading playbook
129 errorCode = 1
130 diag = results
131
132 return errorCode, diag
133
134
135def readPlaybook (sqlintf, value, version=None):
136
137 errorCode = 0
138 diag = ''
139
140 print "***> in AnsibleSql.readPlaybook"
141
142 if not version:
143 query = "SELECT MAX(version) FROM playbook WHERE name like'" + value + "%'"
144 print " Query:", query
145 results = sqlintf.Query (query)
146 version = results[0][0]
147
148 print " Provided playbook name:", value
149 print " Used version:", version
150
151 results = []
152 if version:
153 query = "SELECT value,type FROM playbook WHERE name='" + value + "@" + version + "'"
154 results = sqlintf.Query (query)
155
156 print "Query:", query
157 print "Results:", results
158
159 if len(results) == 0:
160 errorCode = 1
161 else:
162 if len(results[0]) == 0:
163 errorCode = 1
164 diag = results[0]
165 else:
166 diag = results[0]
167
168 return value, version, errorCode, diag
169
170def readCredentials (sqlintf, tag):
171 errorCode = []
172 diag = []
173
174 print "***> in AnsibleSql.readCredential"
175
176 # Load credentials
177
178 for rec in tag:
179
180 # Try hostgroup
181 query = "SELECT hostgroup, hostname, credentials FROM inventory WHERE hostgroup LIKE '%" + \
182 rec +"%'"
183 query_results = sqlintf.Query (query)
184
185 results = ()
186 for q in query_results:
187 if rec in q[0].split(','):
188 l = list(q)
189 l[0] = rec
190 q = tuple(l)
191 results = (q,) + results
192
193 if len(results) == 0:
194 # Try hostname
195 query = "SELECT hostgroup, hostname, credentials FROM inventory WHERE hostname='" + \
196 rec +"'"
197 results = sqlintf.Query (query)
198
199 print " Query:", query
200 print " Results:", len(results), results
201
202 if len(results) == 0:
203 errorCode = 1
204 hostgroup = rec
205 hostname = rec
206 credentials = 'ansible_connection=ssh ansible_ssh_user=na ansible_ssh_private_key_file=na\n'
207 diag.append([hostgroup, hostname, credentials])
208 else:
209 errorCode = 0
210 for i in range(len (results)):
211 for h in results[i][0].split(','):
212 hostgroup = h
213 hostname = results[i][1]
214 credentials = results[i][2]
215 diag.append([hostgroup, hostname, credentials])
216
217 return errorCode, diag
218
219
220if __name__ == '__main__':
221
222 ################################################################
223 # Change below
224 ################################################################
225 host="localhost" # your host, usually localhost
226 user="mysql_user_id" # your username
227 passwd="password_4_mysql_user_id" # your password
228 db="ansible" # name of the data base
229
230 playbook_path = "/home/ubuntu/RestServerOpenSource/"
231 inventory = "/home/ubuntu/RestServerOpenSource/Ansible_inventory"
232 ################################################################
233
234 onlyfiles = [f for f in listdir(playbook_path)
235 if isfile(join(playbook_path, f))]
236
237 sqlintf = mySql (host, user, passwd, db)
238
239 # Load playbooks
240
241 print "Loading playbooks"
242 for file in onlyfiles:
243 if "yml" in file:
244
245 name = file.split (".yml")[0]
246 print " Loading:", name
247 version = name.split("@")[1]
248 errorCode, diag = loadPlaybook (sqlintf, name, version, '.yml')
249 if errorCode:
250 print " Results: Failed - ", diag
251 else:
252 print " Results: Success"
253
254 print "\nLoading inventory"
255
256 # Load inventory
257
258 hostgroup = None
259 inv = {}
260 file = open(inventory, 'r')
261
262 for line in file:
263
264 if '[' in line and ']' in line:
265 hostgroup = line.strip().replace('[','').replace(']','')
266 inv[hostgroup] = {}
267 elif hostgroup and len(line.strip())>0:
268 host = line.strip().split(" ")[0]
269 credentials = line.replace(host,"")
270 inv[hostgroup][host] = credentials
271
272 file.close()
273
274 for hostgroup in inv:
275 print " Loading:", hostgroup
276 hostfqdn = ''
277 cred = ''
278 for hostname in inv[hostgroup]:
279 cred = inv[hostgroup][hostname]
280 errorCode, diag = loadCredentials (sqlintf, hostgroup, hostname, cred)
281 if errorCode:
282 print " Results: Failed - ", diag
283 else:
284 print " Results: Success"
285
286 print "\nReading playbook"
287
288 # Read playbook
289
290 if not sqlintf.con:
291 print "Cannot connect to MySql:", sqlintf.error
292 sys.exit()
293
294 name = "ansible_sleep"
295 print "Reading playbook:", name
296 value, version, errorCode, diag = readPlaybook (sqlintf, name)
297 if errorCode:
298 print "Results: Failed - ", diag
299 else:
300 print "Results: Success"
301 print value
302 print version
303 print diag
304
305 print "\nReading inventory"
306
307 # Read inventory
308
309 tag = ["your_inventory_test_group_name"]
310 print "Reading inventory tag:", tag
311 errorCode, diag = readCredentials (sqlintf, tag)
312 if errorCode:
313 print "Results: Failed - ", diag
314 else:
315 print "Results: Success"
316 print diag
317
318 sqlintf.Close()
319