miq_utilities 0.2.1

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: b2238911c5afe3bc64b77cf5678044f81a15b3bab44da036c3b6efda38fe7b50
4
+ data.tar.gz: 615876043211d98d49c2e0898284cbd900b13929155862a9d25c8ec20402737c
5
+ SHA512:
6
+ metadata.gz: b48663b05141985b94313a9996a33562048fb7b0b20ab655ce7e418b63a4848f5f5d032d8673f70c0946d7952a145996c49322889a8efc3bad8271ee6438ad83
7
+ data.tar.gz: 4bab43cdb2338c9ef1abeab52dd429ab762542627c1f0f65599387c7f04dd6a215609b8efccdd5c07d84473ab9cd472556b6946a0d2b7809cea18c3d2f23c347
data/.gitignore ADDED
@@ -0,0 +1,10 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+ *.iml
10
+ .idea
data/Gemfile ADDED
@@ -0,0 +1,14 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in miq_utilities.gemspec
6
+ gemspec
7
+ gem 'slack-ruby-client'
8
+ gem 'eventmachine'
9
+ gem 'faye-websocket'
10
+ gem 'rbvmomi'
11
+ gem 'tiny_tds'
12
+ gem 'winrm'
13
+ gem 'rest-client'
14
+ gem 'json'
data/Gemfile.lock ADDED
@@ -0,0 +1,112 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ miq_utilities (0.2.1)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ activesupport (5.2.0)
10
+ concurrent-ruby (~> 1.0, >= 1.0.2)
11
+ i18n (>= 0.7, < 2)
12
+ minitest (~> 5.1)
13
+ tzinfo (~> 1.1)
14
+ builder (3.2.3)
15
+ concurrent-ruby (1.0.5)
16
+ domain_name (0.5.20180417)
17
+ unf (>= 0.0.5, < 1.0.0)
18
+ erubis (2.7.0)
19
+ eventmachine (1.2.6-x64-mingw32)
20
+ faraday (0.15.0)
21
+ multipart-post (>= 1.2, < 3)
22
+ faraday_middleware (0.12.2)
23
+ faraday (>= 0.7.4, < 1.0)
24
+ faye-websocket (0.10.7)
25
+ eventmachine (>= 0.12.0)
26
+ websocket-driver (>= 0.5.1)
27
+ ffi (1.9.23-x64-mingw32)
28
+ gli (2.17.1)
29
+ gssapi (1.2.0)
30
+ ffi (>= 1.0.1)
31
+ gyoku (1.3.1)
32
+ builder (>= 2.1.2)
33
+ hashie (3.5.7)
34
+ http-cookie (1.0.3)
35
+ domain_name (~> 0.5)
36
+ httpclient (2.8.3)
37
+ i18n (1.0.1)
38
+ concurrent-ruby (~> 1.0)
39
+ json (2.1.0)
40
+ little-plugger (1.1.4)
41
+ logging (2.2.2)
42
+ little-plugger (~> 1.1)
43
+ multi_json (~> 1.10)
44
+ mime-types (3.1)
45
+ mime-types-data (~> 3.2015)
46
+ mime-types-data (3.2016.0521)
47
+ mini_portile2 (2.3.0)
48
+ minitest (5.11.3)
49
+ multi_json (1.13.1)
50
+ multipart-post (2.0.0)
51
+ netrc (0.11.0)
52
+ nokogiri (1.8.2-x64-mingw32)
53
+ mini_portile2 (~> 2.3.0)
54
+ nori (2.6.0)
55
+ rake (10.5.0)
56
+ rbvmomi (1.12.0)
57
+ builder (~> 3.0)
58
+ json (>= 1.8)
59
+ nokogiri (~> 1.5)
60
+ trollop (~> 2.1)
61
+ rest-client (2.0.2-x64-mingw32)
62
+ ffi (~> 1.9)
63
+ http-cookie (>= 1.0.2, < 2.0)
64
+ mime-types (>= 1.16, < 4.0)
65
+ netrc (~> 0.8)
66
+ rubyntlm (0.6.2)
67
+ slack-ruby-client (0.11.1)
68
+ activesupport
69
+ faraday (>= 0.9)
70
+ faraday_middleware
71
+ gli
72
+ hashie
73
+ websocket-driver
74
+ thread_safe (0.3.6)
75
+ tiny_tds (2.1.1-x64-mingw32)
76
+ trollop (2.1.2)
77
+ tzinfo (1.2.5)
78
+ thread_safe (~> 0.1)
79
+ unf (0.1.4)
80
+ unf_ext
81
+ unf_ext (0.0.7.5-x64-mingw32)
82
+ websocket-driver (0.7.0)
83
+ websocket-extensions (>= 0.1.0)
84
+ websocket-extensions (0.1.3)
85
+ winrm (2.2.3)
86
+ builder (>= 2.1.2)
87
+ erubis (~> 2.7)
88
+ gssapi (~> 1.2)
89
+ gyoku (~> 1.0)
90
+ httpclient (~> 2.2, >= 2.2.0.2)
91
+ logging (>= 1.6.1, < 3.0)
92
+ nori (~> 2.0)
93
+ rubyntlm (~> 0.6.0, >= 0.6.1)
94
+
95
+ PLATFORMS
96
+ x64-mingw32
97
+
98
+ DEPENDENCIES
99
+ bundler (~> 1.16)
100
+ eventmachine
101
+ faye-websocket
102
+ json
103
+ miq_utilities!
104
+ rake (~> 10.0)
105
+ rbvmomi
106
+ rest-client
107
+ slack-ruby-client
108
+ tiny_tds
109
+ winrm
110
+
111
+ BUNDLED WITH
112
+ 1.16.1
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017 Aaron.Mccatty
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,277 @@
1
+ # MiqUtilities
2
+
3
+ ## Installation
4
+
5
+ $ gem install miq_utilities
6
+
7
+ ## Usage
8
+
9
+ require 'miq_utilities'
10
+
11
+ ## Dependencies
12
+
13
+ 1. bundler ~> 1.16
14
+ 2. rake ~> 10.0
15
+ 3. rbvmomi ~> 1.11.3
16
+ 4. tiny_tds ~> 2.1.0
17
+ 5. winrm ~> 2.2.3
18
+ 6. slack-ruby-client ~> 0.11.1
19
+ 7. rest-client ~> 1.8.0 x64-mingw32
20
+ 8. json ~> 2.0.4
21
+
22
+ # Class Summary
23
+ ## Sql Server (SqlClass)
24
+
25
+ Used to manage Sql Server queries. This Class utilises the `tiny_tds` Ruby Gem (version => 2.1.0).
26
+
27
+ ### Class Method Summary
28
+
29
+ #### **initialize**
30
+
31
+ _Create a connection to the client_
32
+ Name | Type | Description
33
+ ---- | ---- | ----
34
+ user | String | Username
35
+ password | String | Password
36
+ host | String | The host name to connect to
37
+ port | String | The port to use, default 1433
38
+ database | String | The database name to connect to
39
+ azure | Boolean | Set to true when connecting to Azure
40
+
41
+ ##### Method usage
42
+ ```
43
+ require 'miq_utilities'
44
+ sql = SqlClass.new(user, pwrd, host, 1433, db, azure)
45
+ ```
46
+
47
+ #### **get_client**
48
+
49
+ _Returns the client to utilise the `tiny_tds` functionality_
50
+
51
+ ##### Method usage
52
+ ```
53
+ client = sql.get_client()
54
+ ```
55
+
56
+ #### **run_sql_query**
57
+
58
+ _Runs the specified SQL query against the client the class was instantiated for._
59
+ Name | Type | Description
60
+ ---- | ---- | ----
61
+ sql | String | Sql query to be run
62
+
63
+ ##### Method usage
64
+ ```
65
+ query = 'SELECT * FROM tbl_users'
66
+ out = sql.run_sql_query(query)
67
+ out.each {|user| puts "User Details: #{user}"}
68
+ ```
69
+
70
+ #### **close_connection**
71
+
72
+ _closes the connection to the client._
73
+
74
+ ##### Method usage
75
+ ```
76
+ sql.close_connection()
77
+ ```
78
+
79
+ ## Logging (LoggingClass)
80
+
81
+ This Class is used to handle the logging for ManageIQ and an IDE.
82
+
83
+ ### Class Method Summary
84
+
85
+ #### **initialize**
86
+
87
+ _Instantiate the class using the name of the class/method/instantiator._
88
+ Name | Type | Description
89
+ ---- | ---- | ----
90
+ name | String | The name of the class/method/instantiator
91
+
92
+ ##### Method usage
93
+ ```
94
+ require 'miq_utilities'
95
+ logger = LoggingClass.new('example_method_name')
96
+ ```
97
+
98
+ #### **log**
99
+
100
+ _Log to the `$evm` object i.e. automation.log._
101
+ Name | Type | Description
102
+ ---- | ---- | ----
103
+ level | String | The level of info/warning/error (no action is taken regardless of level)
104
+ message | String | The message to write
105
+ logtoscreenonly | Boolean | Only log to screen
106
+ notify | Boolean | Process message through the notify process
107
+
108
+ ##### Method usage
109
+ ```
110
+ logger.log('info','This is a test message!')
111
+ ```
112
+ or to process through the Notify class we would use the follwoing:
113
+ ```
114
+ logger.log('warn', 'This is a warning message', false, true)
115
+ ```
116
+ NOTE: When "NOTE" is passed as the level, the notify class turns this into an INFO on-screen message.
117
+
118
+ ## VmWare (VmwareClass)
119
+
120
+ This Class is used to handle some of the heavily used VMWare utilities. This Class utilises the `rbvmomi` Ruby Gem (version => 1.11.3).
121
+
122
+ ### Class Method Summary
123
+
124
+ #### **initialize**
125
+
126
+ _Assign the host name._
127
+ Name | Type | Description
128
+ ---- | ---- | ----
129
+ hostName | String | The name of the host to be used
130
+
131
+ ##### Method usage
132
+ ```
133
+ vmware = VmwareClass.new('MyHostName')
134
+ ```
135
+
136
+ #### **get_vsphere_connection**
137
+
138
+ _Returns the client connection._
139
+ Name | Type | Description
140
+ ---- | ---- | ----
141
+ user | String | The user to connect with
142
+ password | String | The users password
143
+
144
+ ##### Method usage
145
+ ```
146
+ vsphereconn = vmware.get_vsphere_connection(user,pwd)
147
+ ```
148
+
149
+ #### **retrieve_data_centre**
150
+
151
+ _Returns the datacentre based on the connection and datacentre name._
152
+ Name | Type | Description
153
+ ---- | ---- | ----
154
+ vsphereconn | object | The return of "get_vsphere_connection"
155
+ dcname | String | The name of the datacentre
156
+
157
+ ##### Method usage
158
+ ```
159
+ vmdc = vmware.retrieve_data_centre(vsphereconn,'MyDatacentre')
160
+ ```
161
+
162
+ ## Run Powershell (WinrmClass)
163
+
164
+ This Class is used to run PowerShell scripts. This Class utilises the `winrm` Ruby Gem (version => 2.2.3).
165
+
166
+ ### Class Method Summary
167
+
168
+ #### **initialize**
169
+
170
+ _Run a specified PowerShell script._
171
+ Name | Type | Description
172
+ ---- | ---- | ----
173
+ ps_script | String | The name of the script to run (including path to the file)
174
+ host | String | The name of the host to connect to
175
+ user | String | The user to connect with
176
+ password | String | The users password
177
+
178
+ ##### Method usage
179
+ ```
180
+ Name = 'Aaron'
181
+ ps1 = "C:\\Powershell\\RunHelloWorld.ps1 -name #{Name}"
182
+ winrm_run(ps1,host,user,pwrd)
183
+ ```
184
+
185
+ ## Notification (NotificationClass)
186
+
187
+ This Class is used to notify users and log messages accordingly. This Class utilises the `slack-ruby-client` Ruby Gem (version => 0.11.1).
188
+
189
+ ### Class Method Summary
190
+
191
+ #### **notify**
192
+
193
+ _Initiate the process._
194
+ Name | Type | Description
195
+ ---- | ---- | ----
196
+ event_level | String | info, warn, error
197
+ event_message | String | The message to be used
198
+ email_to | String | Who to send an email to
199
+ email_from | String | Sent from which email address
200
+ from | String | From who
201
+ slack_channel | Boolean | The slcak channel to send the message to
202
+
203
+
204
+ ##### Method usage
205
+ ```
206
+ require 'miq_utilities'
207
+ logger = LoggingClass.new('Test NotificationCLass')
208
+ logger.log('error', 'An error occured!', false, true)
209
+ ```
210
+
211
+ #### Levels
212
+ Level | Action
213
+ ---- | ---- | ----
214
+ INFO | Logs to the $evm log
215
+ WARN | Logs to the $evm log, sends an Email and a Slack message
216
+ ERROR | Logs to the $evm log, sends an Email, a Slack message and an on-screen notification
217
+ NOTE | Sends and on-screen notification (As an info message)
218
+
219
+
220
+ #### **send_email**
221
+ _Sends an email to the specified user using the **$evm.execute** MIQ method_
222
+ Name | Type | Description
223
+ ---- | ---- | ----
224
+ message | String | The message to be used
225
+ subject | String | The Subject to be used
226
+ to_email | String | Recipient email
227
+ from_email | String | Sender email
228
+ from | String | Sent from
229
+
230
+ ##### Method usage
231
+
232
+ ```$xslt
233
+ require 'miq_utilities'
234
+ notify = NotificationCLass.new
235
+ notify.send_email('This is an Email.', 'Test', 'aaron@mycompany.com', 'miq@mycompany.com', 'DevOps')
236
+ ```
237
+
238
+ #### **send_slack_message**
239
+
240
+ _Sends a Slcak message_
241
+ Name | Type | Description
242
+ ---- | ---- | ----
243
+ message | String | The message to be used
244
+ channel | String | The channel in which to post the message
245
+ token | String | The API token used to authenticate
246
+
247
+ ##### Method usage
248
+
249
+ ```$xslt
250
+ require 'miq_utilities'
251
+ notify = NotificationCLass.new
252
+ notify.send_slack_message('This a Slack post!', '#MIQ-CHANNEL', 'token-to-use')
253
+ ```
254
+
255
+ #### **on_screen_message**
256
+ _on_screen_message - Sends an on-screen notification_
257
+ Name | Type | Description
258
+ ---- | ---- | ----
259
+ level | String | info, warn, error
260
+ message | String | The message to be used
261
+ subject | String | The Subject to be used
262
+
263
+ ##### Method usage
264
+
265
+ ```$xslt
266
+ require 'miq_utilities'
267
+ notify = NotificationCLass.new
268
+ notify.on_screen_message('info', 'This is an on-screen notification', 'Test')
269
+ ```
270
+
271
+ ## Contributing
272
+
273
+ Currently not in a public repo, but you have the source to change at your will.
274
+
275
+ ## License
276
+
277
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,2 @@
1
+ require "bundler/gem_tasks"
2
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "miq_utilities"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,136 @@
1
+ # frozen_string_literal: true
2
+
3
+ # .SYNOPSIS
4
+ # This Class utilises the rest-client (version => 1.8.0 x64-mingw32) & json (version => 2.0.4) Ruby Gems
5
+ #
6
+ # Methods Summary:
7
+ # > Name > Description/Params
8
+ # process_args - Process Arguments
9
+ # inargs - Hash : Hash Table of key value pairs of arguments to process i.e. { 'name' => some_fdqn }
10
+ # inurl - String : The url to append to
11
+ #
12
+ # process_extattrs - Process extra attributes
13
+ # inargextattrs - Hash : Hash table of key value pairs of the extra attributes to process i.e. { 'Country' => 'UK' }
14
+ # inurl - String : The url to append to
15
+ # args - Boolean : Identifies if arguments were processed, if so an ampersand needs to be appended
16
+ #
17
+ # process_returnfields - Process return fields
18
+ # inurl - String : The url to append to
19
+ # returnfields - String : A string listing the return fields, delimited by commas (CSV)
20
+ # args - Boolean (Default:Flase): Identifies if arguments were processed, if so an ampersand needs to be appended
21
+ #
22
+ # call_infoblox - Process the inputs and make the API call to infoblox
23
+ # action - String : The Action being preformed i.e. GET, DELETE
24
+ # resource - String : The resource being used i.e. record:host
25
+ # ibobj - Object : Custom object created to hold the extra attributes, arguments and return fields.
26
+ # Examples: * vars are suffixed with @ *
27
+ # infobloxobj = { 'args' => nil, 'returnfields' => nil, 'argextattrs' => { 'Country' => @ib_cmdb_country, '*VLAN Number' => @ib_cmdb_vlan, '*Site' => @ib_site } } or;
28
+ # infobloxobj = { 'args' => { 'name' => @ib_fdqn }, 'returnfields' => nil, 'argextattrs' => nil } or;
29
+ # infobloxobj = { 'args' => { 'name' => @ib_fdqn }, 'returnfields' => 'ipv4addrs', 'argextattrs' => nil }......
30
+ #
31
+ # body_type - String (Default json) : The body type
32
+ # body - String : The body to use in the call, if there is one
33
+ # servername - String : The server name to connect to
34
+ # username - String : The username to connect with
35
+ # password - String : The password for the user
36
+ # baseurl - String (Default: https://[SERVERNAME]/wapi/v2.3.1/): the base URL to use
37
+ #
38
+ #
39
+ require 'rest-client'
40
+ require 'json'
41
+ require_relative 'logging.rb'
42
+
43
+ # Class to interact with Infoblox
44
+ class InfobloxClass
45
+ private def process_args(inargs, inurl)
46
+ loops = 1
47
+ outurl = inurl
48
+ inargs.each do |key, value|
49
+ outurl = "#{outurl}#{key}~=#{value}" if loops == inargs.count
50
+ outurl = "#{outurl}#{key}~=#{value}&" if loops != inargs.count
51
+ loops += 1
52
+ end
53
+ outurl.to_s
54
+ end
55
+
56
+ private def process_extattrs(inargextattrs, inurl, args)
57
+ loops = 1
58
+ outurl = if args
59
+ "#{inurl}&_return_fields%2B=extattrs&*"
60
+ else
61
+ "#{inurl}_return_fields%2B=extattrs&*"
62
+ end
63
+ inargextattrs.each do |key, value|
64
+ outurl = "#{outurl}#{key}%3A=#{value}" if loops == inargextattrs.count
65
+ outurl = "#{outurl}#{key}%3A=#{value}&" if loops != inargextattrs.count
66
+ loops += 1
67
+ end
68
+ outurl.to_s
69
+ end
70
+
71
+ private def process_returnfields(inurl, returnfields, inargs = false)
72
+ inurl = if inargs
73
+ "#{inurl}&_return_fields%2B=#{returnfields}"
74
+ else
75
+ "#{inurl}_return_fields%2B=#{returnfields}"
76
+ end
77
+ inurl
78
+ end
79
+
80
+ def call_infoblox(action, resource, ibobj, body_type = :json, body = nil, servername = nil, username = nil, password = nil, baseurl = 'https://[SERVERNAME]/wapi/v2.3.1/')
81
+ @logger = LoggingClass.new('Infoblox')
82
+
83
+ servername ||= $evm.object['InfobloxServername']
84
+ username ||= $evm.object['InfobloxUsername']
85
+ password ||= $evm.object.decrypt('InfobloxPassword')
86
+ baseurl ||= $evm.object['baseURL'].to_s
87
+ url = baseurl.sub('[SERVERNAME]', servername.to_s) + resource.to_s
88
+ refend = '&_return_as_object=1'
89
+ argsfound = false
90
+
91
+ unless ibobj['args'].nil?
92
+ args = ibobj['args']
93
+ argsfound = true
94
+ end
95
+
96
+ argextattrs = ibobj['argextattrs'] unless ibobj['argextattrs'].nil?
97
+ returnfields = ibobj['returnfields'] unless ibobj['returnfields'].nil?
98
+
99
+ url = process_args(args, url) if args
100
+ url = process_returnfields(url, returnfields, argsfound) if returnfields
101
+ url = process_extattrs(argextattrs, url, argsfound) if argextattrs
102
+
103
+ url = if argextattrs || returnfields
104
+ "#{url}#{refend}"
105
+ else
106
+ url
107
+ end
108
+
109
+ @logger.log('info', "URL: \"#{url}\"")
110
+
111
+ params = {
112
+ method: action,
113
+ url: url,
114
+ user: username,
115
+ password: password,
116
+ verify_ssl: false,
117
+ headers: { content_type: body_type, accept: :json }
118
+ }
119
+
120
+ if body_type == :json
121
+ params[:payload] = JSON.generate(body) if body
122
+ @logger.log('info', "Calling -> Infoblox:<#{url}> action:<#{action}> payload:<#{params[:payload]}>") if body
123
+ elsif body
124
+ params[:payload] = body
125
+ end
126
+
127
+ response = RestClient::Request.new(params).execute
128
+ if response.code == 200 || response.code == 201
129
+ @logger.log('info', "Success <- Infoblox Response:<#{response.code}>")
130
+ else
131
+ err_msg = "Error calling infoblox. <#{response.inspect}>"
132
+ @logger.log('error', err_msg, false, true)
133
+ end
134
+ response
135
+ end
136
+ end
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ #
4
+ # This Class is used to handle the logging for ManageIQ and an IDE
5
+ #
6
+ # Methods Summary:
7
+ # > Name > Description/Params
8
+ # initialize - Create the connection to the client
9
+ # name - String : The name of the class/method/instantiator
10
+ #
11
+ # log - Logs detail in the relevant manner
12
+ # level - String : info, warn, error
13
+ # message - String : The message
14
+ # logtoscreenonly - Boolean : Log it to screen only
15
+ # notify - Boolean : process through the notify class
16
+ #
17
+ require_relative 'notification.rb'
18
+
19
+ # logging class
20
+ class LoggingClass
21
+ # initialize class
22
+ def initialize(name)
23
+ @initializer = name
24
+ @notification = NotificationClass.new
25
+ end
26
+
27
+ def log(level, message, logtoscreenonly = false, notify = false)
28
+ levelvalid = %w[info warn error].any? { |msglevel| level.upcase.include? msglevel.to_s.upcase }
29
+
30
+ if $evm.nil? || logtoscreenonly
31
+ puts "#{level}: #{@initializer} - #{message}"
32
+ elsif levelvalid
33
+ $evm.log(level, "#{@initializer} - #{message}")
34
+ else
35
+ $evm.log('info', "#{@initializer} - #{message}")
36
+ end
37
+
38
+ # Notify - Only if flag (notify) is set to TRUE
39
+ @notification.notify(level, message) if notify
40
+ end
41
+ end
@@ -0,0 +1,143 @@
1
+ # frozen_string_literal: true
2
+
3
+ # .SYNOPSIS
4
+ # This Class utilises the slack-ruby-client Ruby Gem (version => 0.11.1).
5
+ #
6
+ # Methods Summary:
7
+ # > Name > Description/Params
8
+ # notify - based on the params passed, process through and notify in the appropriate ways
9
+ # event_level - String : info, warn, error
10
+ # event_message - String : The message to be used
11
+ # email_to - String : Who to send an email to
12
+ # email_from - String : Sent from which email address
13
+ # from - String : From who
14
+ # slack_channel - Boolean : The slcak channel to send the message to
15
+ #
16
+ # send_email - Sends an email to the specified user
17
+ # message - String : The message to be used
18
+ # subject - String : The Subject to be used
19
+ # to_email - String : Recipient email
20
+ # from_email - String : Sender email
21
+ # from - String : Sent from
22
+ #
23
+ # send_slack_message - Sends a Slcak message
24
+ # message - String : The message to be used
25
+ # channel - String : The channel in which to post the message
26
+ # token - String : The API token used to authenticate
27
+ #
28
+ # on_screen_message - Sends an on-screen notification
29
+ # level - String : info, warn, error
30
+ # message - String : The message to be used
31
+ # subject - String : The Subject to be used
32
+ # WIP
33
+ require 'slack-ruby-client'
34
+
35
+ # notification class
36
+ class NotificationClass
37
+
38
+ def notify(event_level, event_message, email_to = nil, email_from = nil, from = nil, slack_channel = nil)
39
+ case event_level.upcase
40
+ when %w[WARN WARNING]
41
+ send_email(event_message, 'Warning Identified', email_to, email_from, from)
42
+ send_slack_message(event_message, slack_channel)
43
+ when %w[ERR ERROR]
44
+ send_email(event_message, 'Error Identified', email_to, email_from, from)
45
+ send_slack_message(event_message, slack_channel)
46
+ on_screen_message(event_level, event_message)
47
+ when 'NOTE'
48
+ on_screen_message(event_level, event_message)
49
+ end
50
+ rescue => err
51
+ raise("Oopps! Something went wrong trying to notify. Error:<#{err}>")
52
+ end
53
+
54
+ def send_email(message, subject, to_email = nil, from_email, from)
55
+ # Look in the current object for a VM
56
+ vm = $evm.object['vm']
57
+ if vm.nil?
58
+ vm_id = $evm.object['vm_id'].to_i
59
+ vm = $evm.vmdb('vm', vm_id) unless vm_id.zero?
60
+ end
61
+
62
+ # Look in the Root Object for a VM
63
+ if vm.nil?
64
+ vm = $evm.root['vm']
65
+ if vm.nil?
66
+ vm_id = $evm.root['vm_id'].to_i
67
+ vm = $evm.vmdb('vm', vm_id) unless vm_id.zero?
68
+ end
69
+ end
70
+
71
+ # Look in the Root Object for a Provision/Request
72
+ prov = $evm.root['miq_provision_request'] || $evm.root['miq_provision']
73
+ vm = prov.vm if prov && vm.nil?
74
+
75
+ raise 'VM details not found!' if vm.nil?
76
+
77
+ # Look at the Event Type in the Current Object or in the Root Object
78
+ event_type = $evm.object['event'] || $evm.root['event_type']
79
+
80
+ # Get VM Owner Name and Email
81
+ evm_owner_id = vm.attributes['evm_owner_id']
82
+ owner = nil
83
+ owner = $evm.vmdb('user', evm_owner_id) unless evm_owner_id.nil?
84
+
85
+ # to_email_address from owner.email then from model if nil
86
+ to = if owner
87
+ owner.email.to_s.strip
88
+ else
89
+ $evm.object['to_email_address'].to_s.strip
90
+ end
91
+
92
+ to ||= to_email unless to_email.nil?
93
+
94
+ subject += " - #{event_type}"
95
+ body = 'Hello, '
96
+ body += message
97
+ body += 'Thank you,'
98
+ body += from
99
+
100
+ $evm.execute(:send_email, to, from_email, subject, body)
101
+ rescue => err
102
+ raise("Oopps! Something went wrong trying to send an email to:<#{to}>. Error:<#{err}>")
103
+ end
104
+
105
+ # TBD - awaiting webhook setup
106
+ def send_slack_message(message, channel, token = nil)
107
+ # https://github.com/slack-ruby/slack-ruby-client - install required
108
+ if token.nil?
109
+ Slack.configure do |config|
110
+ config.token = ENV['SLACK_API_TOKEN']
111
+ raise 'Missing ENV[SLACK_API_TOKEN]!' unless config.token
112
+ end
113
+ else
114
+ config.token = token
115
+ end
116
+
117
+ begin
118
+ client = Slack::Web::Client.new
119
+ client.auth_test
120
+ client.chat_postMessage(channel: channel, text: message, as_user: true)
121
+ rescue => err
122
+ raise("Oopps! Something went wrong trying to send a Slack notification. Error:<#{err}>")
123
+ end
124
+ end
125
+
126
+ def on_screen_message(level, message, subject = nil)
127
+ if subject.nil?
128
+ vm = $evm.root['vm']
129
+ prov = $evm.root['miq_provision']
130
+ subject ||= vm unless vm.nil?
131
+ subject ||= prov.miq_request unless prov.miq_request.nil?
132
+ end
133
+
134
+ levelvalid = %w[info warn error].any? { |msglevel| level.upcase.include? msglevel.to_s.upcase }
135
+ level = 'info' unless levelvalid
136
+
137
+ begin
138
+ $evm.create_notification(level: level, subject: subject, message: message)
139
+ rescue => err
140
+ raise("Oopps! Something went wrong trying to display on-screen notification. Error:<#{err}>")
141
+ end
142
+ end
143
+ end
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+
3
+ # .SYNOPSIS
4
+ # This Class utilises the tiny_tds Ruby Gem (version => 2.1.0).
5
+ #
6
+ # Methods Summary:
7
+ # > Name > Description/Params
8
+ # initialize - Create the connection to the client
9
+ # user - String : Username
10
+ # password - String : Password
11
+ # host - String : The host name to connect to
12
+ # port - String : The port to use, default (nil) 1433
13
+ # database - String : The database name to connect to
14
+ # azure - Boolean : Set to true when connecting to Azure
15
+ #
16
+ # get_client - returns the client to utilise the tiny_tds functionality
17
+ #
18
+ # run_sql_query - runs the specified sql query against the client when the class was instantiated
19
+ # sql - String : Sql query to be run
20
+ #
21
+ # close_connection - closes the connection to the client
22
+ #
23
+ require 'tiny_tds'
24
+
25
+ # Sql class
26
+ class SqlClass
27
+ # Initialize Class
28
+ def initialize(user, password, host, port = nil, database, azure)
29
+ # Logging
30
+ @logger = LoggingClass.new('SQL')
31
+
32
+ # Default port
33
+ unless port.nil? || port.empty?
34
+ @logger.log('info', 'Using default port 1433')
35
+ port = '1433'
36
+ end
37
+
38
+ # Get connection to client
39
+ client = TinyTds::Client.new(username: user,
40
+ password: password,
41
+ host: host,
42
+ port: port,
43
+ database: database,
44
+ azure: azure)
45
+ @client = client
46
+ end
47
+
48
+ # Return Client object
49
+ def return_client
50
+ @client
51
+ end
52
+
53
+ # Run Sql query
54
+ def run_sql_query(sql)
55
+ if @client.nil?
56
+ @logger.log('warn', 'SQL Server Connection Not Established! Query hasn\'t been run!')
57
+ else
58
+ @client.execute(sql)
59
+ end
60
+ end
61
+
62
+ # Close the connection to the sql client
63
+ def close_connection
64
+ @client.close unless @client.closed?
65
+ @logger.log('info', 'Connection to SQL Client Closed Successfully.') if @client.closed?
66
+ end
67
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MiqUtilities
4
+ VERSION = '0.2.1'
5
+ end
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ #
4
+ # This Class is used to handle some of the heavily used VMWare utilities
5
+ #
6
+ # Methods Summary:
7
+ # > Name > Description/Params
8
+ # initialize - Assign the host name
9
+ # host_name - String : The name of the host being utilised
10
+ #
11
+ # get_vsphere_connection - returns the client connection
12
+ # user - String : The user to connect with
13
+ # password - String : The users password
14
+ #
15
+ # get_data_center - returns the datacenter based on the connection and datacenter
16
+ # vsphereconn - connection : The return of "get_vsphere_connection"
17
+ # dcname - String : The name of the datacenter
18
+ #
19
+ require 'rbvmomi'
20
+
21
+ # vmware wrapper class
22
+ class VmwareClass
23
+ def initialize(host_name)
24
+ @host_name = host_name
25
+ end
26
+
27
+ def get_vsphere_connection(user, password)
28
+ @connection = RbVmomi::VIM.connect(host: @host_name, user: user, password: password, insecure: true)
29
+ @connection
30
+ end
31
+
32
+ def retrieve_data_center
33
+ @connection.serviceInstance.find_datacenter || raise('Datacenter not found!') unless @connection.nil?
34
+ raise("No connection established!\nUse the \"get_vsphere_connection\" method to connect.") if @connection.nil?
35
+ end
36
+
37
+ def find_vm(dc, name)
38
+ vm = {}
39
+ dc.datastoreFolder.childEntity.collect do |datastore|
40
+ vm[:instance] = datastore.vm.find { |x| x.name == name }
41
+ if vm[:instance]
42
+ vm[:datastore] = datastore.name
43
+ break
44
+ end
45
+ end
46
+ vm
47
+ end
48
+
49
+ def upg_tools(vm)
50
+ instopts = if vm[:instance][:guest][:guestFamily] == 'windowsGuest'
51
+ '/s /v "/qn REBOOT=ReallySuppress"'
52
+ end
53
+ vm[:instance].UpgradeTools_Task(installerOptions: instopts).wait_for_completion
54
+ end
55
+ end
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ # .SYNOPSIS
4
+ # This Class utilises the winrm Ruby Gem (version => 2.2.3) and is used to handle the running of powershell scripts using winrm
5
+ #
6
+ # Methods Summary:
7
+ # > Name > Description/Params
8
+ # winrm_run - Run a specified PowerShell script
9
+ # ps_script - String : The name of the script to run (including path to the file)
10
+ # host - String : The name of the host to connect to
11
+ # user - String : The user to connect with
12
+ # password - String : The users password
13
+ #
14
+ require 'winrm'
15
+ require 'logging.rb'
16
+
17
+ # WinRM class
18
+ class WinrmClass
19
+ def winrm_run(ps_script, host, user, password)
20
+ @logger = LoggingClass.new('WinRM')
21
+ value = ''
22
+ ps1 = <<~PS_SCRIPT
23
+ #{ps_script}
24
+ PS_SCRIPT
25
+
26
+ opts = {
27
+ endpoint: "http://#{host}:5985/wsman",
28
+ user: user.to_s,
29
+ password: password.to_s
30
+ }
31
+
32
+ conn = WinRM::Connection.new(opts)
33
+
34
+ @logger.log('info', "WinRM is connecting to #{opts[:endpoint]}")
35
+ msg = ps1.to_s.gsub(password.to_s, '****')
36
+ @logger.log('info', "Running PowerShell script: #{msg}")
37
+
38
+ conn.shell(:powershell) do |shell|
39
+ err = ''
40
+ output = shell.run(ps1) do |stdout, stderr|
41
+ value = stdout
42
+ err = stderr
43
+ end
44
+ if output.exitcode.zero?
45
+ @logger.log('info', "PS script finished with exit code #{output.exitcode} - Output: <#{value.to_s.strip}>")
46
+ else
47
+ @logger.log('error', "PS script failed with exit code #{output.exitcode} and error message #{err}. STDOUT: #{value.to_s.strip}")
48
+ end
49
+ end
50
+ value.to_s.strip
51
+ end
52
+ end
@@ -0,0 +1,10 @@
1
+
2
+ module MiqUtilities
3
+ require_relative 'miq_utilities/version'
4
+ require_relative 'miq_utilities/infoblox.rb'
5
+ require_relative 'miq_utilities/logging.rb'
6
+ require_relative 'miq_utilities/notification.rb'
7
+ require_relative 'miq_utilities/sql.rb'
8
+ require_relative 'miq_utilities/winrm.rb'
9
+ require_relative 'miq_utilities/vmware.rb'
10
+ end
@@ -0,0 +1,31 @@
1
+
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "miq_utilities/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "miq_utilities"
8
+ spec.version = MiqUtilities::VERSION
9
+ spec.authors = ["Aaron McCatty"]
10
+ spec.email = ["aaronmccatty@hotmail.co.uk"]
11
+
12
+ spec.summary = %q{Commonly used utilities in ManageIQ/Cloudforms }
13
+ spec.description = %q{ This Gem was written to hold utilities commonly used within ManageIQ/Cloudforms. }
14
+ spec.license = "MIT"
15
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
16
+ f.match(%r{^(test|spec|features)/})
17
+ end
18
+ spec.bindir = "exe"
19
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
20
+ spec.require_paths = ["lib"]
21
+
22
+ spec.homepage = 'http://www.rubydoc.info/gems/miq_utilities'
23
+
24
+ spec.add_development_dependency "bundler", "~> 1.16"
25
+ spec.add_development_dependency "rake", "~> 10.0"
26
+ spec.add_development_dependency "tiny_tds", "~> 2.1"
27
+ spec.add_development_dependency "rbvmomi", "~> 1.11"
28
+ spec.add_development_dependency "winrm", "~> 2.2"
29
+ spec.add_development_dependency "rest-client", "~>1.8"
30
+ spec.add_development_dependency "json", "~> 2.0"
31
+ end
metadata ADDED
@@ -0,0 +1,159 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: miq_utilities
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.2.1
5
+ platform: ruby
6
+ authors:
7
+ - Aaron McCatty
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2018-05-09 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.16'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.16'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: tiny_tds
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '2.1'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '2.1'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rbvmomi
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '1.11'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '1.11'
69
+ - !ruby/object:Gem::Dependency
70
+ name: winrm
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '2.2'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '2.2'
83
+ - !ruby/object:Gem::Dependency
84
+ name: rest-client
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '1.8'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '1.8'
97
+ - !ruby/object:Gem::Dependency
98
+ name: json
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - "~>"
102
+ - !ruby/object:Gem::Version
103
+ version: '2.0'
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - "~>"
109
+ - !ruby/object:Gem::Version
110
+ version: '2.0'
111
+ description: " This Gem was written to hold utilities commonly used within ManageIQ/Cloudforms. "
112
+ email:
113
+ - aaronmccatty@hotmail.co.uk
114
+ executables: []
115
+ extensions: []
116
+ extra_rdoc_files: []
117
+ files:
118
+ - ".gitignore"
119
+ - Gemfile
120
+ - Gemfile.lock
121
+ - LICENSE.txt
122
+ - README.md
123
+ - Rakefile
124
+ - bin/console
125
+ - bin/setup
126
+ - lib/miq_utilities.rb
127
+ - lib/miq_utilities/infoblox.rb
128
+ - lib/miq_utilities/logging.rb
129
+ - lib/miq_utilities/notification.rb
130
+ - lib/miq_utilities/sql.rb
131
+ - lib/miq_utilities/version.rb
132
+ - lib/miq_utilities/vmware.rb
133
+ - lib/miq_utilities/winrm.rb
134
+ - miq_utilities.gemspec
135
+ homepage: http://www.rubydoc.info/gems/miq_utilities
136
+ licenses:
137
+ - MIT
138
+ metadata: {}
139
+ post_install_message:
140
+ rdoc_options: []
141
+ require_paths:
142
+ - lib
143
+ required_ruby_version: !ruby/object:Gem::Requirement
144
+ requirements:
145
+ - - ">="
146
+ - !ruby/object:Gem::Version
147
+ version: '0'
148
+ required_rubygems_version: !ruby/object:Gem::Requirement
149
+ requirements:
150
+ - - ">="
151
+ - !ruby/object:Gem::Version
152
+ version: '0'
153
+ requirements: []
154
+ rubyforge_project:
155
+ rubygems_version: 2.7.6
156
+ signing_key:
157
+ specification_version: 4
158
+ summary: Commonly used utilities in ManageIQ/Cloudforms
159
+ test_files: []