3 * ============LICENSE_START=======================================================
5 * ================================================================================
6 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
7 * ================================================================================
8 * Copyright (C) 2017 Amdocs
9 * =============================================================================
10 * Licensed under the Apache License, Version 2.0 (the "License");
11 * you may not use this file except in compliance with the License.
12 * You may obtain a copy of the License at
14 * http://www.apache.org/licenses/LICENSE-2.0
16 * Unless required by applicable law or agreed to in writing, software
17 * distributed under the License is distributed on an "AS IS" BASIS,
18 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 * See the License for the specific language governing permissions and
20 * limitations under the License.
22 * ============LICENSE_END=========================================================
27 from os import listdir
28 from os.path import isfile, join
32 def __init__(self, myhost, myuser, mypasswd, mydb):
37 self.db = pymysql.connect(host=myhost,
41 self.cur = self.db.cursor()
42 except Exception as e:
46 def Query (self, myquery, val = None):
50 self.cur.execute(myquery, val)
52 self.cur.execute(myquery)
54 results = self.cur.fetchall()
55 except Exception as e:
63 def loadPlaybook (sqlintf, value, version, ext = '.yml'):
68 # Test if primary key already defined
69 query = "SELECT name FROM playbook WHERE name='" + value +"'"
70 results = sqlintf.Query (query)
74 query = "INSERT INTO playbook (name) VALUES ('" + value + "')"
75 results = sqlintf.Query (query)
81 file = open(playbook_path + value + ext, 'r')
82 load_file = file.read()
85 sql = "UPDATE playbook SET value=%s, version=%s, type=%s WHERE name=%s"
87 results = sqlintf.Query(sql, (load_file, version, ext, value))
90 # Error loading playbook
94 return errorCode, diag
96 def loadCredentials (sqlintf, hostgroup, hostname, cred):
102 query = "SELECT hostname,hostgroup FROM inventory WHERE hostname='" + hostname +"'"
103 results = sqlintf.Query (query)
105 if hostname in str (results):
107 results_hostgroups = results[0][1]
109 if hostgroup in results_hostgroups.split(','):
110 query = "UPDATE inventory SET hostname='" + hostname + "',credentials='" +\
112 "' WHERE hostname='" + hostname + "'"
115 results_hostgroups = results_hostgroups + ',' + hostgroup
117 query = "UPDATE inventory SET hostname='" + hostname + "',credentials='" +\
118 cred + "',hostgroup='" + results_hostgroups + \
119 "' WHERE hostname='" + hostname + "'"
121 results = sqlintf.Query (query)
125 query = "INSERT INTO inventory (hostgroup, hostname, credentials) VALUES ('" + \
126 hostgroup + "','" + hostname + "','" + cred + "')"
127 results = sqlintf.Query (query)
129 if len (results) > 0:
130 # Error loading playbook
134 return errorCode, diag
137 def readPlaybook (sqlintf, value, version=None):
142 print("***> in AnsibleSql.readPlaybook")
145 query = "SELECT MAX(version) FROM playbook WHERE name like'" + value + "%'"
146 print(" Query:", query)
147 results = sqlintf.Query (query)
148 version = results[0][0]
150 print(" Provided playbook name:", value)
151 print(" Used version:", version)
155 query = "SELECT value,type FROM playbook WHERE name='" + value + "@" + version + "'"
156 results = sqlintf.Query (query)
158 print("Query:", query)
159 print("Results:", results)
161 if len(results) == 0:
164 if len(results[0]) == 0:
170 return value, version, errorCode, diag
172 def readCredentials (sqlintf, tag):
176 print("***> in AnsibleSql.readCredential")
183 query = "SELECT hostgroup, hostname, credentials FROM inventory WHERE hostgroup LIKE '%" + \
185 query_results = sqlintf.Query (query)
188 for q in query_results:
189 if rec in q[0].split(','):
193 results = (q,) + results
195 if len(results) == 0:
197 query = "SELECT hostgroup, hostname, credentials FROM inventory WHERE hostname='" + \
199 results = sqlintf.Query (query)
201 print(" Query:", query)
202 print(" Results:", len(results), results)
204 if len(results) == 0:
208 credentials = 'ansible_connection=ssh ansible_ssh_user=na ansible_ssh_private_key_file=na\n'
209 diag.append([hostgroup, hostname, credentials])
212 for i in range(len (results)):
213 for h in results[i][0].split(','):
215 hostname = results[i][1]
216 credentials = results[i][2]
217 diag.append([hostgroup, hostname, credentials])
219 return errorCode, diag
222 if __name__ == '__main__':
224 ################################################################
226 ################################################################
227 host="localhost" # your host, usually localhost
228 user="mysql_user_id" # your username
229 passwd="password_4_mysql_user_id" # your password
230 db="ansible" # name of the data base
232 playbook_path = "/home/ubuntu/RestServerOpenSource/"
233 inventory = "/home/ubuntu/RestServerOpenSource/Ansible_inventory"
234 ################################################################
236 onlyfiles = [f for f in listdir(playbook_path)
237 if isfile(join(playbook_path, f))]
239 sqlintf = mySql (host, user, passwd, db)
243 print("Loading playbooks")
244 for file in onlyfiles:
247 name = file.split (".yml")[0]
248 print(" Loading:", name)
249 version = name.split("@")[1]
250 errorCode, diag = loadPlaybook (sqlintf, name, version, '.yml')
252 print(" Results: Failed - ", diag)
254 print(" Results: Success")
256 print("\nLoading inventory")
262 file = open(inventory, 'r')
266 if '[' in line and ']' in line:
267 hostgroup = line.strip().replace('[','').replace(']','')
269 elif hostgroup and len(line.strip())>0:
270 host = line.strip().split(" ")[0]
271 credentials = line.replace(host,"")
272 inv[hostgroup][host] = credentials
276 for hostgroup in inv:
277 print(" Loading:", hostgroup)
280 for hostname in inv[hostgroup]:
281 cred = inv[hostgroup][hostname]
282 errorCode, diag = loadCredentials (sqlintf, hostgroup, hostname, cred)
284 print(" Results: Failed - ", diag)
286 print(" Results: Success")
288 print("\nReading playbook")
293 print("Cannot connect to MySql:", sqlintf.error)
296 name = "ansible_sleep"
297 print("Reading playbook:", name)
298 value, version, errorCode, diag = readPlaybook (sqlintf, name)
300 print("Results: Failed - ", diag)
302 print("Results: Success")
307 print("\nReading inventory")
311 tag = ["your_inventory_test_group_name"]
312 print("Reading inventory tag:", tag)
313 errorCode, diag = readCredentials (sqlintf, tag)
315 print("Results: Failed - ", diag)
317 print("Results: Success")