3 * ============LICENSE_START=======================================================
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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.
25 from os import listdir
26 from os.path import isfile, join
30 def __init__(self, myhost, myuser, mypasswd, mydb):
35 self.db = pymysql.connect(host=myhost,
39 self.cur = self.db.cursor()
40 except Exception as e:
44 def Query (self, myquery, val = None):
48 self.cur.execute(myquery, val)
50 self.cur.execute(myquery)
52 results = self.cur.fetchall()
61 def loadPlaybook (sqlintf, value, version, ext = '.yml'):
66 # Test if primary key already defined
67 query = "SELECT name FROM playbook WHERE name='" + value +"'"
68 results = sqlintf.Query (query)
72 query = "INSERT INTO playbook (name) VALUES ('" + value + "')"
73 results = sqlintf.Query (query)
79 file = open(playbook_path + value + ext, 'r')
80 load_file = file.read()
83 sql = "UPDATE playbook SET value=%s, version=%s, type=%s WHERE name=%s"
85 results = sqlintf.Query(sql, (load_file, version, ext, value))
88 # Error loading playbook
92 return errorCode, diag
94 def loadCredentials (sqlintf, hostgroup, hostname, cred):
100 query = "SELECT hostname,hostgroup FROM inventory WHERE hostname='" + hostname +"'"
101 results = sqlintf.Query (query)
103 if hostname in str (results):
105 results_hostgroups = results[0][1]
107 if hostgroup in results_hostgroups.split(','):
108 query = "UPDATE inventory SET hostname='" + hostname + "',credentials='" +\
110 "' WHERE hostname='" + hostname + "'"
113 results_hostgroups = results_hostgroups + ',' + hostgroup
115 query = "UPDATE inventory SET hostname='" + hostname + "',credentials='" +\
116 cred + "',hostgroup='" + results_hostgroups + \
117 "' WHERE hostname='" + hostname + "'"
119 results = sqlintf.Query (query)
123 query = "INSERT INTO inventory (hostgroup, hostname, credentials) VALUES ('" + \
124 hostgroup + "','" + hostname + "','" + cred + "')"
125 results = sqlintf.Query (query)
127 if len (results) > 0:
128 # Error loading playbook
132 return errorCode, diag
135 def readPlaybook (sqlintf, value, version=None):
140 print "***> in AnsibleSql.readPlaybook"
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]
148 print " Provided playbook name:", value
149 print " Used version:", version
153 query = "SELECT value,type FROM playbook WHERE name='" + value + "@" + version + "'"
154 results = sqlintf.Query (query)
156 print "Query:", query
157 print "Results:", results
159 if len(results) == 0:
162 if len(results[0]) == 0:
168 return value, version, errorCode, diag
170 def readCredentials (sqlintf, tag):
174 print "***> in AnsibleSql.readCredential"
181 query = "SELECT hostgroup, hostname, credentials FROM inventory WHERE hostgroup LIKE '%" + \
183 query_results = sqlintf.Query (query)
186 for q in query_results:
187 if rec in q[0].split(','):
191 results = (q,) + results
193 if len(results) == 0:
195 query = "SELECT hostgroup, hostname, credentials FROM inventory WHERE hostname='" + \
197 results = sqlintf.Query (query)
199 print " Query:", query
200 print " Results:", len(results), results
202 if len(results) == 0:
206 credentials = 'ansible_connection=ssh ansible_ssh_user=na ansible_ssh_private_key_file=na\n'
207 diag.append([hostgroup, hostname, credentials])
210 for i in range(len (results)):
211 for h in results[i][0].split(','):
213 hostname = results[i][1]
214 credentials = results[i][2]
215 diag.append([hostgroup, hostname, credentials])
217 return errorCode, diag
220 if __name__ == '__main__':
222 ################################################################
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
230 playbook_path = "/home/ubuntu/RestServerOpenSource/"
231 inventory = "/home/ubuntu/RestServerOpenSource/Ansible_inventory"
232 ################################################################
234 onlyfiles = [f for f in listdir(playbook_path)
235 if isfile(join(playbook_path, f))]
237 sqlintf = mySql (host, user, passwd, db)
241 print "Loading playbooks"
242 for file in onlyfiles:
245 name = file.split (".yml")[0]
246 print " Loading:", name
247 version = name.split("@")[1]
248 errorCode, diag = loadPlaybook (sqlintf, name, version, '.yml')
250 print " Results: Failed - ", diag
252 print " Results: Success"
254 print "\nLoading inventory"
260 file = open(inventory, 'r')
264 if '[' in line and ']' in line:
265 hostgroup = line.strip().replace('[','').replace(']','')
267 elif hostgroup and len(line.strip())>0:
268 host = line.strip().split(" ")[0]
269 credentials = line.replace(host,"")
270 inv[hostgroup][host] = credentials
274 for hostgroup in inv:
275 print " Loading:", hostgroup
278 for hostname in inv[hostgroup]:
279 cred = inv[hostgroup][hostname]
280 errorCode, diag = loadCredentials (sqlintf, hostgroup, hostname, cred)
282 print " Results: Failed - ", diag
284 print " Results: Success"
286 print "\nReading playbook"
291 print "Cannot connect to MySql:", sqlintf.error
294 name = "ansible_sleep"
295 print "Reading playbook:", name
296 value, version, errorCode, diag = readPlaybook (sqlintf, name)
298 print "Results: Failed - ", diag
300 print "Results: Success"
305 print "\nReading inventory"
309 tag = ["your_inventory_test_group_name"]
310 print "Reading inventory tag:", tag
311 errorCode, diag = readCredentials (sqlintf, tag)
313 print "Results: Failed - ", diag
315 print "Results: Success"