blob: 850c4b84a10d8bd1a877df8b16f7d53e17ef700f [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
24#!/usr/bin/python
25import pymysql
26from os import listdir
27from os.path import isfile, join
28
29class mySql():
30
31 def __init__(self, myhost, myuser, mypasswd, mydb):
32 self.db = pymysql.connect(host=myhost,
33 user=myuser,
34 passwd=mypasswd,
35 db=mydb)
36 self.cur = self.db.cursor()
37
38 def Query (self, myquery, val = None):
39 results = None
40 error = None
41 try:
42 if val:
43 self.cur.execute(myquery, val)
44 else:
45 self.cur.execute(myquery)
46 self.db.commit()
47 results = self.cur.fetchall()
48 except Exception, e:
49 error = str (e)
50 return results, error
51
52 def Close (self):
53 self.db.close()
54
55def loadPlaybook (value, version, ext = '.yml'):
56
57 errorCode = 0
58 diag = ''
59
60 # Test if primary key already defined
61 query = "SELECT name FROM playbook WHERE name='" + value +"'"
62 results, error = sqlintf.Query (query)
63 if results:
64 # print "Primary key already defined: Updating playbook"
65 pass
66 else:
67 # print "Primary key not defined: Insert new playbook"
68 query = "INSERT INTO playbook (name) VALUES ('" + value + "')"
69 results, error = sqlintf.Query (query)
70 if error:
71 errorCode = 1
72 diag = error
73
74 # Load playbook
75 file = open(playbook_path + value + ext, 'r')
76 load_file = file.read()
77
78 # Load playbook
79
80 if not errorCode:
81 sql = "UPDATE playbook SET value=%s, version=%s, type=%s WHERE name=%s"
82
83 results, error = sqlintf.Query(sql, (load_file, version, ext, value))
84
85 if error:
86 # Error loading playbook
87 errorCode = 1
88 diag = error
89
90 return errorCode, diag
91
92def loadCredentials (hostgroup, hostname, cred):
93 errorCode = 0
94 diag = ''
95
96 # Load credentials
97
98 query = "SELECT hostname,hostgroup FROM inventory WHERE hostname='" + hostname +"'"
99 results = sqlintf.Query (query)
100
101 print '==>', results
102
103 if hostname in str(results):
104
105 results_hostgroups = results[0][0][1]
106
107 # print "Record already defined: Updating inventory"
108 if hostgroup in results_hostgroups.split(','):
109 query = "UPDATE inventory SET hostname='" + hostname + "',credentials='" +\
110 cred +\
111 "' WHERE hostname='" + hostname + "'"
112 else:
113
114 results_hostgroups = results_hostgroups + ',' + hostgroup
115
116 query = "UPDATE inventory SET hostname='" + hostname + "',credentials='" +\
117 cred + "',hostgroup='" + results_hostgroups + \
118 "' WHERE hostname='" + hostname + "'"
119
120 results, error = sqlintf.Query (query)
121
122 else:
123
124 query = "INSERT INTO inventory (hostgroup, hostname, credentials) VALUES ('" + \
125 hostgroup + "','" + hostname + "','" + cred + "')"
126 results, error = sqlintf.Query (query)
127
128 if error:
129 # Error loading credentials
130 errorCode = 1
131 diag = results
132
133 return errorCode, diag
134
135
136if __name__ == '__main__':
137
138 ################################################################
139 # Change below
140 ################################################################
141 host="localhost" # your host, usually localhost
142 user="mysql_user_id" # your username
143 passwd="password_4_mysql_user_id" # your password
144 db="ansible" # name of the data base
145
146 playbook_path = "/home/ubuntu/RestServerOpenSource/"
147 inventory = "/home/ubuntu/RestServerOpenSource/Ansible_inventory"
148 ################################################################
149
150 onlyfiles = [f for f in listdir(playbook_path)
151 if isfile(join(playbook_path, f))]
152
153 sqlintf = mySql (host, user, passwd, db)
154
155 # Load playbooks
156 print "Loading playbooks"
157 for file in onlyfiles:
158 if "yml" in file:
159 name = file.split (".yml")[0]
160 print " Loading:", name
161 version = name.split("@")[1]
162 errorCode, diag = loadPlaybook (name, version)
163 if errorCode:
164 print " Results: Failed - ", diag
165 else:
166 print " Results: Success"
167 if "tar.gz" in file:
168 name = file.split (".tar.gz")[0]
169 print " Loading:", name
170 version = name.split("@")[1]
171 errorCode, diag = loadPlaybook (name, version, ".tar.gz")
172
173 print "\nLoading inventory"
174
175 # Load inventory
176 hostgroup = None
177 inv = {}
178 file = open(inventory, 'r')
179
180 for line in file:
181
182 if '[' in line and ']' in line:
183 hostgroup = line.strip().replace('[','').replace(']','')
184 inv[hostgroup] = {}
185 elif hostgroup and len(line.strip())>0:
186 host = line.strip().split(" ")[0]
187 credentials = line.replace(host,"")
188 inv[hostgroup][host] = credentials
189
190 file.close()
191
192 for hostgroup in inv:
193 print " Loading:", hostgroup
194 hostfqdn = ''
195 cred = ''
196 for hostname in inv[hostgroup]:
197 cred = inv[hostgroup][hostname]
198 errorCode, diag = loadCredentials (hostgroup, hostname, cred)
199 if errorCode:
200 print " Results: Failed - ", diag
201 else:
202 print " Results: Success"
203
204 sqlintf.Close()