-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathPowervRNI.psm1
5706 lines (4807 loc) · 209 KB
/
PowervRNI.psm1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# VMware vRealize Network Insight PowerShell module
# Martijn Smit (@smitmartijn)
# Version 2.0
# Keep a list handy of all data source types and the different URIs that is supposed to be called for that datasource
$Script:DatasourceURLs = @{ }
$Script:DatasourceURLs.Add("vcenter", @("/data-sources/vcenters"))
$Script:DatasourceURLs.Add("nsxv", @("/data-sources/nsxv-managers"))
$Script:DatasourceURLs.Add("nsxt", @("/data-sources/nsxt-managers"))
$Script:DatasourceURLs.Add("nsxalb", @("/data-sources/nsxalb"))
$Script:DatasourceURLs.Add("ciscoswitch", @("/data-sources/cisco-switches"))
$Script:DatasourceURLs.Add("aristaswitch", @("/data-sources/arista-switches"))
$Script:DatasourceURLs.Add("dellswitch", @("/data-sources/dell-switches"))
$Script:DatasourceURLs.Add("dellos10switch", @("/data-sources/dell-os10-switches"))
$Script:DatasourceURLs.Add("brocadeswitch", @("/data-sources/brocade-switches"))
$Script:DatasourceURLs.Add("juniperswitch", @("/data-sources/juniper-switches"))
$Script:DatasourceURLs.Add("ciscoucs", @("/data-sources/ucs-managers"))
$Script:DatasourceURLs.Add("hpeswitch", @("/data-sources/hpe-switches"))
$Script:DatasourceURLs.Add("hponeview", @("/data-sources/hpov-managers"))
$Script:DatasourceURLs.Add("hpvcmanager", @("/data-sources/hpvc-managers"))
$Script:DatasourceURLs.Add("checkpointfirewall", @("/data-sources/checkpoint-firewalls"))
$Script:DatasourceURLs.Add("panfirewall", @("/data-sources/panorama-firewalls"))
$Script:DatasourceURLs.Add("infoblox", @("/data-sources/infoblox-managers"))
$Script:DatasourceURLs.Add("vmc-nsxmanager", @("/data-sources/vmc-nsxmanagers"))
$Script:DatasourceURLs.Add("f5-bigip", @("/data-sources/f5-bigip"))
$Script:DatasourceURLs.Add("huawei", @("/data-sources/huawei"))
$Script:DatasourceURLs.Add("ciscoaci", @("/data-sources/cisco-aci"))
$Script:DatasourceURLs.Add("pks", @("/data-sources/pks"))
$Script:DatasourceURLs.Add("kubernetes", @("/data-sources/kubernetes-clusters"))
$Script:DatasourceURLs.Add("openshift", @("/data-sources/openshift-clusters"))
$Script:DatasourceURLs.Add("servicenow", @("/data-sources/servicenow-instances"))
$Script:DatasourceURLs.Add("velocloud", @("/data-sources/velocloud"))
$Script:DatasourceURLs.Add("azure", @("/data-sources/azure-subscriptions"))
$Script:DatasourceURLs.Add("fortimanager", @("/data-sources/fortinet-firewalls"))
$Script:DatasourceURLs.Add("generic-device", @("/data-sources/generic-switches"))
$Script:DatasourceURLs.Add("mellanoxswitch", @("/data-sources/mellanox-switches"))
$Script:DatasourceURLs.Add("ciscoasrxrswitch", @("/data-sources/cisco-asrxr-switches"))
$Script:DatasourceURLs.Add("hcxconnector", @("/data-sources/hcx-connectors"))
$Script:DatasourceURLs.Add("aws", @("/data-sources/aws-accounts"))
# Collect a list of all data source URLs to be used to retrieve "all" data sources
$allURLs = New-Object System.Collections.Generic.List[System.Object]
foreach ($h in $Script:DatasourceURLs.GetEnumerator()) {
$allURLs += $h.Value
}
$Script:DatasourceURLs.Add("all", $allURLs)
# Keep another list handy which translates the internal vRNI Names for datasources to their relative URLs
$Script:DatasourceInternalURLs = @{ }
$Script:DatasourceInternalURLs.Add("VCenterDataSource", "/data-sources/vcenters")
$Script:DatasourceInternalURLs.Add("NSXVManagerDataSource", "/data-sources/nsxv-managers")
$Script:DatasourceInternalURLs.Add("NSXTManagerDataSource", "/data-sources/nsxt-managers")
$Script:DatasourceInternalURLs.Add("NSXALBDataSource", "/data-sources/nsxalb")
$Script:DatasourceInternalURLs.Add("CiscoSwitchDataSource", "/data-sources/cisco-switches")
$Script:DatasourceInternalURLs.Add("AristaSwitchDataSource", "/data-sources/arista-switches")
$Script:DatasourceInternalURLs.Add("DellSwitchDataSource", "/data-sources/dell-switches")
$Script:DatasourceInternalURLs.Add("BrocadeSwitchDataSource", "/data-sources/brocade-switches")
$Script:DatasourceInternalURLs.Add("JuniperSwitchDataSource", "/data-sources/juniper-switches")
$Script:DatasourceInternalURLs.Add("UCSManagerDataSource", "/data-sources/ucs-managers")
$Script:DatasourceInternalURLs.Add("HPESwitchDataSource", "/data-sources/hpe-switches")
$Script:DatasourceInternalURLs.Add("HPOneViewManagerDataSource", "/data-sources/hpov-managers")
$Script:DatasourceInternalURLs.Add("HPVCManagerDataSource", "/data-sources/hpvc-managers")
$Script:DatasourceInternalURLs.Add("CheckpointFirewallDataSource", "/data-sources/checkpoint-firewalls")
$Script:DatasourceInternalURLs.Add("PanFirewallDataSource", "/data-sources/panorama-firewalls")
$Script:DatasourceInternalURLs.Add("InfobloxManagerDataSource", "/data-sources/infoblox-managers")
$Script:DatasourceInternalURLs.Add("PolicyManagerDataSource", "/data-sources/vmc-nsxmanagers")
$Script:DatasourceInternalURLs.Add("F5BIGIPDataSource", "/data-sources/f5-bigip")
$Script:DatasourceInternalURLs.Add("HuaweiSwitchDataSource", "/data-sources/huawei")
$Script:DatasourceInternalURLs.Add("CiscoACIDataSource", "/data-sources/cisco-aci")
$Script:DatasourceInternalURLs.Add("PKSDataSource", "/data-sources/pks")
$Script:DatasourceInternalURLs.Add("KubernetesDataSource", "/data-sources/kubernetes-clusters")
$Script:DatasourceInternalURLs.Add("ServiceNowDataSource", "/data-sources/servicenow-instances")
$Script:DatasourceInternalURLs.Add("VeloCloudDataSource", "/data-sources/velocloud")
$Script:DatasourceInternalURLs.Add("AzureDataSource", "/data-sources/azure-subscriptions")
$Script:DatasourceInternalURLs.Add("FortinetFirewallDataSource", "/data-sources/fortinet-firewalls")
$Script:DatasourceInternalURLs.Add("GenericSwitchDataSource", "/data-sources/generic-switches")
$Script:DatasourceInternalURLs.Add("MellanoxSwitchDataSource", "/data-sources/mellanox-switches")
$Script:DatasourceInternalURLs.Add("CiscoASRXRSwitchDataSource", "/data-sources/cisco-asrxr-switches")
$Script:DatasourceInternalURLs.Add("HcxDataSource", "/data-sources/hcx-connectors")
$Script:DatasourceInternalURLs.Add("AWSDataSource", "/data-sources/aws-accounts")
# This list will be used in Get-vRNIEntity to map entity URLs to their IDs so we can use those IDs in /entities/fetch
$Script:EntityURLtoIdMapping = @{ }
$Script:EntityURLtoIdMapping.Add("problems", "ProblemEvent")
$Script:EntityURLtoIdMapping.Add("vms", "VirtualMachine")
$Script:EntityURLtoIdMapping.Add("vnics", "Vnic")
$Script:EntityURLtoIdMapping.Add("hosts", "Host")
$Script:EntityURLtoIdMapping.Add("clusters", "Cluster")
$Script:EntityURLtoIdMapping.Add("vc-datacenters", "VCDatacenter")
$Script:EntityURLtoIdMapping.Add("datastores", "Datastore")
$Script:EntityURLtoIdMapping.Add("vmknics", "Vmknic")
$Script:EntityURLtoIdMapping.Add("layer2-networks", "VxlanLayer2Network")
$Script:EntityURLtoIdMapping.Add("ip-sets", "NSXIPSet")
$Script:EntityURLtoIdMapping.Add("flows", "Flow")
$Script:EntityURLtoIdMapping.Add("security-groups", "NSXSecurityGroup")
$Script:EntityURLtoIdMapping.Add("security-tags", "SecurityTag")
$Script:EntityURLtoIdMapping.Add("firewall-rules", "NSXFirewallRule")
$Script:EntityURLtoIdMapping.Add("firewalls", "NSXDistributedFirewall")
$Script:EntityURLtoIdMapping.Add("services", "NSXService")
$Script:EntityURLtoIdMapping.Add("service-groups", "NSXServiceGroup")
$Script:EntityURLtoIdMapping.Add("vcenter-managers", "VCenterManager")
$Script:EntityURLtoIdMapping.Add("nsx-managers", "NSXVManager")
$Script:EntityURLtoIdMapping.Add("distributed-virtual-switches", "DistributedVirtualSwitch")
$Script:EntityURLtoIdMapping.Add("distributed-virtual-portgroups", "DistributedVirtualPortgroup")
$Script:EntityURLtoIdMapping.Add("firewall-managers", "CheckpointManager")
$Script:EntityURLtoIdMapping.Add("kubernetes-services", "KubernetesService")
$Script:EntityURLtoIdMapping.Add("direct-connect", "VmcAWSDxConnection")
$Script:EntityURLtoIdMapping.Add("dx-tunnels", "DirectConnectInterface")
$Script:EntityURLtoIdMapping.Add("logical-routers", "LogicalRouter")
$Script:EntityURLtoIdMapping.Add("vmware-transit-gateways", "VMWareTransitGateway")
$Script:EntityURLtoIdMapping.Add("ipsec-vpn-sessions", "PolicyManagerPolicyBasedIPSecVPNSession")
$Script:EntityURLtoIdMapping.Add("sddc-groups", "VMCSDDCGROUP")
$Script:EntityURLtoIdMapping.Add("vmc-sddc", "VMCSDDC")
$Script:EntityURLtoIdMapping.Add("switchports", "SwitchPort")
$Script:vRNICloudLocationUrlMapping = @{ }
$Script:vRNICloudLocationUrlMapping.Add("default", "api.mgmt.cloud.vmware.com")
$Script:vRNICloudLocationUrlMapping.Add("US", "api.mgmt.cloud.vmware.com")
$Script:vRNICloudLocationUrlMapping.Add("UK", "uk.api.mgmt.cloud.vmware.com")
$Script:vRNICloudLocationUrlMapping.Add("JP", "jp.api.mgmt.cloud.vmware.com")
$Script:vRNICloudLocationUrlMapping.Add("AU", "au.api.mgmt.cloud.vmware.com")
$Script:vRNICloudLocationUrlMapping.Add("CA", "ca.api.mgmt.cloud.vmware.com")
$Script:vRNICloudLocationUrlMapping.Add("DE", "de.api.mgmt.cloud.vmware.com")
# Thanks to PowerNSX (https://github.com/vmware/powernsx) for providing some of the base functions &
# principles on which this module is built on.
# Run at module load time to determine a few things about the platform this module is running on.
function _PvRNI_init {
# $PSVersionTable.PSEdition property does not exist pre v5. We need to do a few things in
# exported functions to workaround some limitations of core edition, so we export
# the global PNSXPSTarget var to reference if required.
if (($PSVersionTable.PSVersion.Major -ge 6) -or (($PSVersionTable.PSVersion.Major -eq 5) -And ($PSVersionTable.PSVersion.Minor -ge 1))) {
$script:PvRNI_PlatformType = $PSVersionTable.PSEdition
}
else {
$script:PvRNI_PlatformType = "Desktop"
}
# Define class required for certificate validation override. Version dependant.
# For whatever reason, this does not work when contained within a function?
$TrustAllCertsPolicy = @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem)
{
return true;
}
}
"@
if ($script:PvRNI_PlatformType -eq "Desktop") {
if (-not ("TrustAllCertsPolicy" -as [type])) {
Add-Type $TrustAllCertsPolicy
}
}
}
function Invoke-vRNIRestMethod {
<#
.SYNOPSIS
Forms and executes a REST API call to a vRealize Network Insight Platform VM.
.DESCRIPTION
Invoke-vRNIRestMethod uses either a specified connection object as returned
by Connect-vRNIServer, or the $defaultvRNIConnection global variable if
defined to construct a REST api call to the vRNI API.
Invoke-vRNIRestMethod constructs the appropriate request headers required by
the vRNI API, including the authentication token (built from the connection
object) and the content type, before making the rest call and returning the
appropriate JSON object to the caller cmdlet.
.EXAMPLE
PS C:\> Invoke-vRNIRestMethod -Method GET -Uri "/api/ni/data-sources/vcenters"
Performs a 'GET' against the URI /api/ni/data-sources/vcenters and returns
the JSON object which contains the vRNI response. This call requires the
$defaultvRNIConnection variable to exist and be populated with server and
authentiation details as created by Connect-vRNIServer, or it fails with a
message to first use Connect-vRNIServer
.EXAMPLE
PS C:\> $MyConnection = Connect-vRNIServer -Server vrni-platform.lab.local
PS C:\> Invoke-vRNIRestMethod -Method GET -Uri "/api/ni/data-sources/vcenters" -Connection $MyConnection
Connects to a vRNI Platform VM and stores the connection details in a
variable, which in turn is used for the following cmdlet to retrieve
all vCenter datasources. The JSON object containing the vRNI response
is returned.
#>
[CmdletBinding(DefaultParameterSetName = "ConnectionObj")]
param (
[Parameter (Mandatory = $true, ParameterSetName = "Parameter")]
# vRNI Platform server
[string]$Server,
[Parameter (Mandatory = $true, ParameterSetName = "Parameter")]
[Parameter (ParameterSetName = "ConnectionObj")]
# REST Method (GET, POST, DELETE, UPDATE)
[string]$Method,
[Parameter (Mandatory = $true, ParameterSetName = "Parameter")]
[Parameter (ParameterSetName = "ConnectionObj")]
# URI of API endpoint (/api/ni/endpoint)
[string]$URI,
[Parameter (Mandatory = $false, ParameterSetName = "Parameter")]
[Parameter (ParameterSetName = "ConnectionObj")]
# Content to be sent to server when method is PUT/POST/PATCH
[string]$Body = "",
[Parameter (Mandatory = $false, ParameterSetName = "Parameter")]
[Parameter (ParameterSetName = "ConnectionObj")]
# Save content to file
[string]$OutFile = "",
[Parameter (Mandatory = $false, ParameterSetName = "Parameter")]
[Parameter (ParameterSetName = "ConnectionObj")]
# Override Content-Type
[string]$ContentType = "application/json",
[Parameter (Mandatory = $false, ParameterSetName = "ConnectionObj")]
# Pre-populated connection object as returned by Connect-vRNIServer
[psObject]$Connection
)
if ($pscmdlet.ParameterSetName -eq "ConnectionObj") {
# Ensure we were either called with a connection or there is a defaultConnection (user has called Connect-vRNIServer)
if ($null -eq $connection) {
# Now we need to assume that defaultvRNIConnection does not exist...
if ( -not (test-path variable:global:defaultvRNIConnection) ) {
throw "Not connected. Connect to vRNI with Connect-vRNIServer first."
}
else {
Write-Host "$($MyInvocation.MyCommand.Name) : Using default connection"
$connection = $defaultvRNIConnection
}
}
$authtoken = $connection.AuthToken
$server = $connection.Server
# Check if the authentication token hasn't expired yet
if ((Get-Date) -gt $connection.AuthTokenExpiry) {
throw "The vRNI Authentication token has expired (expired at '$($connection.AuthTokenExpiry.DateTime)'). Please login again using Connect-vRNIServer."
}
}
# Sleep a tiny bit so we don't overload the vRNI API when using consecutive commands
Start-Sleep -m 100
# Create a header option dictionary, to be used for authentication (if we have an existing session) and other RESTy stuff
$headerDict = @{ }
$headerDict.add("Content-Type", $ContentType)
# Add the auth token to the headers, if the CSPToken is not filled out
if ($authtoken -ne "") {
$headerDict.add("Authorization", "NetworkInsight $authtoken")
}
# Add the Cloud Services Platform token if available (means we're using Network Insight as a Service)
if ($null -ne $connection) {
if ($null -ne $connection.CSPToken) {
$headerDict.remove("Authorization")
$headerDict.add("csp-auth-token", $connection.CSPToken)
}
}
# Form the URL to call and write in our journal about this call
$URL = "https://$($Server)$($URI)"
Write-Debug "$(Get-Date -format s) REST Call via Invoke-RestMethod: $Method $URL "
Write-Debug "Headers: $headerDict"
Write-Debug "Body: $Body"
# Build up Invoke-RestMethod parameters, can differ per platform
$invokeRestMethodParams = @{
"Method" = $Method;
"Headers" = $headerDict;
"ContentType" = $ContentType;
"Uri" = $URL;
}
# If a body for a POST request has been specified, add it to the parameters for Invoke-RestMethod
if ($Body -ne "") {
$invokeRestMethodParams.Add("Body", $body)
}
# If we want to save the output to a file (Get-vRNIRecommendedRulesNsxBundle uses this), specify -OutFile
if ($OutFile -ne "") {
$invokeRestMethodParams.Add("OutFile", $OutFile)
}
# Add a trigger to ignore SSL certificate checks, if we're not using Network Insight as a Service (self-hosted usually have self-signed certificates)
$SkipSSLCheck = $True
if ($null -ne $connection) {
if ($connection.CSPToken -eq "") {
$SkipSSLCheck = $False
}
}
if ($SkipSSLCheck -eq $True) {
if (($script:PvRNI_PlatformType -eq "Desktop")) {
# Allow untrusted certificate presented by the remote system to be accepted
if ([System.Net.ServicePointManager]::CertificatePolicy.tostring() -ne 'TrustAllCertsPolicy') {
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
}
}
# Core (for now) uses a different mechanism to manipulating [System.Net.ServicePointManager]::CertificatePolicy
if (($script:PvRNI_PlatformType -eq "Core")) {
$invokeRestMethodParams.Add("SkipCertificateCheck", $true)
}
}
# Only use TLS as SSL connection to vRNI
[Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls"
# Energize!
try {
$response = Invoke-RestMethod @invokeRestMethodParams
}
# If its a webexception, we may have got a response from the server with more information...
# Even if this happens on PoSH Core though, the ex is not a webexception and we cant get this info :(
catch [System.Net.WebException] {
#Check if there is a response populated in the response prop as we can return better detail.
$response = $_.exception.response
if ( $response ) {
$responseStream = $response.GetResponseStream()
$reader = New-Object system.io.streamreader($responseStream)
$responseBody = $reader.readtoend()
## include ErrorDetails content in case therein lies juicy info
$ErrorString = "$($MyInvocation.MyCommand.Name) : The API response received indicates a failure. $($response.StatusCode.value__) : $($response.StatusDescription) : Response Body: $($responseBody)`nErrorDetails: '$($_.ErrorDetails)'"
# Log the error with response detail.
Write-Warning -Message $ErrorString
## throw the actual error, so that the consumer can debug via the actuall ErrorRecord
Throw $_
}
else {
# No response, log and throw the underlying ex
$ErrorString = "$($MyInvocation.MyCommand.Name) : Exception occured calling invoke-restmethod. $($_.exception.tostring())"
Write-Warning -Message $_.exception.tostring()
## throw the actual error, so that the consumer can debug via the actuall ErrorRecord
Throw $_
}
}
catch {
# Not a webexception (may be on PoSH core), log and throw the underlying ex string
$ErrorString = "$($MyInvocation.MyCommand.Name) : Exception occured calling invoke-restmethod. $($_.exception.tostring())"
Write-Warning -Message $ErrorString
## throw the actual error, so that the consumer can debug via the actuall ErrorRecord
Throw $_
}
Write-Debug "$(Get-Date -format s) Invoke-RestMethod Result: $response"
Write-Debug "$(Get-Date -format s) Invoke-RestMethod Results: $($response.results)"
# Workaround for bug in invoke-restmethod where it doesnt complete the tcp session close to our server after certain calls.
# We end up with connectionlimit number of tcp sessions in close_wait and future calls die with a timeout failure.
# So, we are getting and killing active sessions after each call. Not sure of performance impact as yet - to test
# and probably rewrite over time to use invoke-webrequest for all calls... PiTA!!!! :|
#$ServicePoint = [System.Net.ServicePointManager]::FindServicePoint($FullURI)
#$ServicePoint.CloseConnectionGroup("") | out-null
# Return result
if ($response) { $response }
}
#####################################################################################################################
#####################################################################################################################
######################################## Connection Management #####################################################
#####################################################################################################################
#####################################################################################################################
function Connect-vRNIServer {
<#
.SYNOPSIS
Connects to the specified vRealize Network Insight Platform VM and
constructs a connection object.
.DESCRIPTION
The Connect-vRNIServer cmdlet returns a connection object that contains
an authentication token which the rest of the cmdlets in this module
use to perform authenticated REST API calls.
The connection object contains the authentication token, the expiry
datetime that the token expires and the vRNI server address.
.EXAMPLE
PS C:\> Connect-vRNIServer -Server vrni-platform.lab.local
Connect to vRNI Platform VM with the hostname vrni-platform.lab.local,
the cmdlet will prompt for credentials. Returns the connection object,
if successful.
.EXAMPLE
PS C:\> $mysecpassword = ConvertTo-SecureString secret -AsPlainText -Force
PS C:\> Connect-vRNIServer -Server vrni-platform.lab.local -Username admin@local -SecurePassword $mysecpassword
Connect to vRNI Platform VM with the hostname vrni-platform.lab.local
with the given local credentials. Returns the connection object, if successful.
.EXAMPLE
PS C:\> $mysecpassword = ConvertTo-SecureString secret -AsPlainText -Force
PS C:\> Connect-vRNIServer -Server vrni-platform.lab.local -Username [email protected] -SecurePassword $mysecpassword
Connect to vRNI Platform VM with the hostname vrni-platform.lab.local
with the given LDAP credentials. Returns the connection object, if successful.
.EXAMPLE
PS C:\> $mysecpassword = ConvertTo-SecureString secret -AsPlainText -Force
PS C:\> Connect-vRNIServer -Server vrni-platform.lab.local -Username [email protected] -SecurePassword $mysecpassword -UseLocalAuth
Connect to vRNI Platform VM with the hostname vrni-platform.lab.local
with the given LOCAL credentials. Returns the connection object, if successful.
.EXAMPLE
PS C:\> $mysecpassword = ConvertTo-SecureString secret -AsPlainText -Force
PS C:\> $MyConnection = Connect-vRNIServer -Server vrni-platform.lab.local -Username admin@local -SecurePassword $mysecpassword
PS C:\> Get-vRNIDataSource -Connection $MyConnection
Connects to vRNI with the given credentials and then uses the returned
connection object in the next cmdlet to retrieve all datasources from
that specific vRNI instance.
#>
param (
[Parameter (Mandatory = $true)]
# vRNI Platform hostname or IP address
[ValidateNotNullOrEmpty()]
[string]$Server,
[Parameter (Mandatory = $false)]
# Username to use to login to vRNI
[ValidateNotNullOrEmpty()]
[string]$Username,
[Parameter (Mandatory = $false)]
# Password to use to login to vRNI
[ValidateNotNullOrEmpty()]
[securestring]$Password,
[Parameter (Mandatory = $false)]
#PSCredential object containing NSX API authentication credentials
[PSCredential]$Credential,
[Parameter (Mandatory = $false)]
# Domain to use to login to vRNI - Deprecated, use the full username ([email protected]) for LDAP auth, and the UseLocalAuth parameter to force local user auth
[ValidateNotNullOrEmpty()]
[string]$Domain = "",
[Parameter (Mandatory = $false)]
# Are we doing local authentication?
[ValidateNotNullOrEmpty()]
[switch]$UseLocalAuth
)
# Make sure either -Credential is set, or both -Username and -Password
if (($PsBoundParameters.ContainsKey("Credential") -And $PsBoundParameters.ContainsKey("Username")) -Or
($PsBoundParameters.ContainsKey("Credential") -And $PsBoundParameters.ContainsKey("SecurePassword"))) {
throw "Specify either -Credential or -Username to authenticate (if using -Username and omitting -SecurePassword, a prompt will be given)"
}
# Build cred object for default auth if user specified username/pass
$connection_credentials = ""
if ($PsBoundParameters.ContainsKey("Username")) {
# Is the -Password omitted? Prompt securely
if (!($PsBoundParameters.ContainsKey("Password"))) {
$connection_credentials = Get-Credential -UserName $Username -Message "vRealize Network Insight Platform Authentication"
}
# If the password has been given in cleartext,
else {
$connection_credentials = New-Object System.Management.Automation.PSCredential($Username, $Password)
}
}
# If a credential object was given as a parameter, use that
elseif ($PSBoundParameters.ContainsKey("Credential")) {
$connection_credentials = $Credential
}
# If no -Username or -Credential was given, prompt for credentials
elseif (!$PSBoundParameters.ContainsKey("Credential")) {
$connection_credentials = Get-Credential -Message "vRealize Network Insight Platform Authentication"
}
# Start building the hash table containing the login call we need to do
$requestFormat = @{
"username" = $connection_credentials.Username
"password" = $connection_credentials.GetNetworkCredential().Password
}
# Figure out if the username is a local or remote username
$parts = $requestFormat.username.split("@")
# If no domain param is given, use the default LOCAL domain and populate the "domain" field
if ($parts[1] -eq "local" -Or $UseLocalAuth -eq $True -Or $Domain -eq "LOCAL") {
$requestFormat.domain = @{
"domain_type" = "LOCAL"
"value" = "local"
}
}
# Otherwise there a LDAP domain requested for credentials
else {
$requestFormat.domain = @{
"domain_type" = "LDAP"
"value" = $parts[1]
}
}
# Only use TLS as SSL connection to vRNI
[Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls"
# Convert the hash to JSON and send the request to vRNI
$requestBody = ConvertTo-Json $requestFormat
Write-Debug "Request: $($requestBody)"
$response = Invoke-vRNIRestMethod -Server $Server -Method POST -URI "/api/ni/auth/token" -Body $requestBody
Write-Debug "Response: $($response)"
if ($response) {
# Setup a custom object to contain the parameters of the connection
$connection = [pscustomObject] @{
"Server" = $Server
"AuthToken" = $response.token
## the expiration of the token; currently (vRNI API v1.0), tokens are valid for five (5) hours
"AuthTokenExpiry" = (Get-Date "01 Jan 1970").AddMilliseconds($response.expiry).ToLocalTime()
}
# Remember this as the default connection
Set-Variable -name defaultvRNIConnection -value $connection -scope Global
# Retrieve the API version so we can use that in determining if we can use newer API endpoints
$Script:vRNI_API_Version = [System.Version]((Get-vRNIAPIVersion).api_version)
# Return the connection
$connection
}
}
function Disconnect-vRNIServer {
<#
.SYNOPSIS
Destroys the Connection object if provided, otherwise this destroys the
$defaultvRNIConnection global variable if it exists.
.DESCRIPTION
Although REST is not connection-orientated, vRNI does remember the authentication
token which is used throughout the session. This cmdlet also invalidates the
authentication token from vRNI, so it can no longer be used.
.EXAMPLE
PS C:\> Disconnect-vRNIServer
Invalidates and removes the global default connection variable.
.EXAMPLE
PS C:\> Disconnect-vRNIServer -Connection $MyConnection
Invalidates the authentication token of a specific connection object
#>
param (
[Parameter (Mandatory = $False)]
# vRNI Connection object
[ValidateNotNullOrEmpty()]
[PSCustomObject]$Connection = $defaultvRNIConnection
)
# Invalidate auth token from vRNI
$result = Invoke-vRNIRestMethod -Connection $Connection -Method DELETE -URI "/api/ni/auth/token"
# Remove the global default connection variable, if the -Connection parameter is the same as the default
if ($Connection -eq $defaultvRNIConnection) {
if (Get-Variable -Name defaultvRNIConnection -scope global) {
Remove-Variable -name defaultvRNIConnection -scope global
}
}
$result
}
function Connect-NIServer {
<#
.SYNOPSIS
Connects to the Network Insight Service on the VMware Cloud Services
Platform and constructs a connection object.
.DESCRIPTION
The Connect-NIServer cmdlet returns a connection object that contains
an authentication token which the rest of the cmdlets in this module
use to perform authenticated REST API calls.
The connection object contains the Cloud Services Platform token, the expiry
datetime that the token expires and the NI server address.
The RefreshToken can be found in your profile, here: https://console.cloud.vmware.com/csp/gateway/portal/#/user/tokens
.EXAMPLE
PS C:\> Connect-NIServer -RefreshToken xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
Connect to the VMware Cloud Services Portal with your specified Refresh Token.
The cmdlet will connect to the CSP, validate the token and will return an
access token. Returns the connection object, if successful.
.EXAMPLE
PS C:\> Connect-NIServer -RefreshToken xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx -Location UK
Connect to the vRealize Network Insight Cloud service in the UK.
#>
param (
[Parameter (Mandatory = $true)]
# The Refresh Token from your VMware Cloud Services Portal
[ValidateNotNullOrEmpty()]
[string]$RefreshToken,
[Parameter (Mandatory = $false)]
# The Refresh Token from your VMware Cloud Services Portal
[ValidateNotNullOrEmpty()]
[ValidateSet ("default", "US", "UK", "JP", "AU", "CA", "DE")]
[string]$Location = "default"
)
# Only use TLS as SSL connection to vRNI
[Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls"
$vrni_cloud_url = $Script:vRNICloudLocationUrlMapping.$Location
$body = @{
api_token = $RefreshToken
}
$URL = "https://console.cloud.vmware.com/csp/gateway/am/api/auth/api-tokens/authorize"
# Energize!
try {
$response = Invoke-WebRequest -URI $URL -Body $body -ContentType "application/x-www-form-urlencoded" -Method POST -UseBasicParsing
Write-Debug "Response: $($response)"
}
# If its a webexception, we may have got a response from the server with more information...
# Even if this happens on PoSH Core though, the ex is not a webexception and we cant get this info :(
catch [System.Net.WebException] {
#Check if there is a response populated in the response prop as we can return better detail.
$response = $_.exception.response
if ( $response ) {
$responseStream = $response.GetResponseStream()
$reader = New-Object system.io.streamreader($responseStream)
$responseBody = $reader.readtoend()
## include ErrorDetails content in case therein lies juicy info
$ErrorString = "$($MyInvocation.MyCommand.Name) : The API response received indicates a failure. $($response.StatusCode.value__) : $($response.StatusDescription) : Response Body: $($responseBody)`nErrorDetails: '$($_.ErrorDetails)'"
# Log the error with response detail.
Write-Warning -Message $ErrorString
## throw the actual error, so that the consumer can debug via the actuall ErrorRecord
Throw $_
}
else {
# No response, log and throw the underlying ex
$ErrorString = "$($MyInvocation.MyCommand.Name) : Exception occured calling invoke-restmethod. $($_.exception.tostring())"
Write-Warning -Message $_.exception.tostring()
## throw the actual error, so that the consumer can debug via the actuall ErrorRecord
Throw $_
}
}
catch {
# Not a webexception (may be on PoSH core), log and throw the underlying ex string
$ErrorString = "$($MyInvocation.MyCommand.Name) : Exception occured calling invoke-restmethod. $($_.exception.tostring())"
Write-Warning -Message $ErrorString
## throw the actual error, so that the consumer can debug via the actuall ErrorRecord
Throw $_
}
if ($response) {
$response = ($response | ConvertFrom-Json)
# Setup a custom object to contain the parameters of the connection, including the URL to the CSP API & Access token
$connection = [pscustomObject] @{
"Server" = "$($vrni_cloud_url)/ni"
"CSPToken" = $response.access_token
## the expiration of the token; currently (vRNI API v1.0), tokens are valid for five (5) hours
"AuthTokenExpiry" = (Get-Date).AddSeconds($response.expires_in).ToLocalTime()
}
# Remember this as the default connection
Set-Variable -name defaultvRNIConnection -value $connection -scope Global
# Retrieve the API version so we can use that in determining if we can use newer API endpoints
$Script:vRNI_API_Version = [System.Version]((Get-vRNIAPIVersion).api_version)
# Return the connection
$connection
}
}
#####################################################################################################################
#####################################################################################################################
################################################ Search ###########################################################
#####################################################################################################################
#####################################################################################################################
function Invoke-vRNISearch {
<#
.SYNOPSIS
Run a search against vRNI. The syntax for these search query is the same as in the web interface.
.DESCRIPTION
There are 3 possible return fields, based on the type of search query you're doing:
- entity_list_response
- aggregation_response
- groupby_response
.EXAMPLE
PS C:\> Invoke-vRNISearch -Query "VMs where vCPU Count > 2"
Returns a list of all VMs with more than 2 vCPUs
#>
param (
[Parameter (Mandatory = $True)]
# Search query to run against vRNI
[ValidateNotNullOrEmpty()]
[String]$Query,
[Parameter (Mandatory = $False)]
# Limit the results with this number
[ValidateNotNullOrEmpty()]
[int]$Limit = 500,
[Parameter (Mandatory = $False)]
# vRNI Connection object
[ValidateNotNullOrEmpty()]
[PSCustomObject]$Connection = $defaultvRNIConnection
)
# Format request with all given data
$requestFormat = @{
"query" = $Query
"size" = $Limit
}
$requestBody = ConvertTo-Json $requestFormat
$results = Invoke-vRNIRestMethod -Connection $Connection -Method POST -URI "/api/ni/search/ql" -Body $requestBody
$results
}
#####################################################################################################################
#####################################################################################################################
####################################### Infrastructure Management ##################################################
#####################################################################################################################
#####################################################################################################################
function Get-vRNINodes {
<#
.SYNOPSIS
Retrieve details of the vRealize Network Insight nodes.
.DESCRIPTION
Nodes within a vRealize Network Insight typically consist of two
node types; collector VMs (or previously know as proxy VMs) and
platform VMs. You can have multiple of each type to support your
deployment and cluster them.
.EXAMPLE
PS C:\> Get-vRNINodes
Retrieves information about all available nodes.
.EXAMPLE
PS C:\> Get-vRNINodes | Where {$_.node_type -eq "PROXY_VM"}
Retrieves information about all available nodes, but filter on the collector VMs.
#>
param (
[Parameter (Mandatory = $False)]
# vRNI Connection object
[ValidateNotNullOrEmpty()]
[PSCustomObject]$Connection = $defaultvRNIConnection
)
# Get a list of available nodes first, this call returns a list of node IDs, which we can use
# to retrieve more details on the specific node
$nodes = Invoke-vRNIRestMethod -Connection $Connection -Method GET -URI "/api/ni/infra/nodes"
# Use this as a result container
$nodes_details = [System.Collections.ArrayList]@()
foreach ($node_record in $nodes.results) {
# Retrieve the node details and store those
$node_info = Invoke-vRNIRestMethod -Connection $Connection -Method GET -URI "/api/ni/infra/nodes/$($node_record.id)"
$nodes_details.Add($node_info) | Out-Null
}
$nodes_details
}
function Get-vRNIAPIVersion {
<#
.SYNOPSIS
Retrieve the version number of the vRealize Network Insight API.
.DESCRIPTION
The API of vRealize Network Insight is versioned and this retrieves
that version number.
.EXAMPLE
PS C:\> Get-vRNIAPIVersion
Returns the version number of the vRNI API.
#>
param (
[Parameter (Mandatory = $False)]
# vRNI Connection object
[ValidateNotNullOrEmpty()]
[PSCustomObject]$Connection = $defaultvRNIConnection
)
$version = Invoke-vRNIRestMethod -Connection $Connection -Method GET -URI "/api/ni/info/version"
$version
}
function Get-vRNILicensing {
<#
.SYNOPSIS
Retrieve the installed licenses and their usage of vRealize Network Insight.
.DESCRIPTION
vRealize Network Insight requires licensing to function. This will get the activated licenses and their usage
.EXAMPLE
PS C:\> Get-vRNILicensing
Returns the installed licenses and their usage.
#>
param (
[Parameter (Mandatory = $False)]
# vRNI Connection object
[ValidateNotNullOrEmpty()]
[PSCustomObject]$Connection = $defaultvRNIConnection
)
$licensing = Invoke-vRNIRestMethod -Connection $Connection -Method GET -URI "/api/ni/settings/licensing"
$licensing.result
}
function Test-vRNILicensing {
<#
.SYNOPSIS
Validates a given license against vRealize Network Insight.
.DESCRIPTION
vRealize Network Insight requires licensing to function. This will
validate whether a given license can be activated.
If successful, the result will be details of the license.
If not successful, the function will throw an exception
with the API error
.EXAMPLE
PS C:\> Test-vRNILicensing -License xxx-yyyy-dddd
Validates the given license
#>
param (
[Parameter (Mandatory = $true)]
# The license key we want to validate
[ValidateNotNullOrEmpty()]
[string]$License,
[Parameter (Mandatory = $False)]
# vRNI Connection object
[ValidateNotNullOrEmpty()]
[PSCustomObject]$Connection = $defaultvRNIConnection
)
# Format request with all given data
$requestFormat = @{
"licenseKey" = $License
}
# Convert the hash to JSON, form the URI and send the request to vRNI
$requestBody = ConvertTo-Json $requestFormat
$validate = Invoke-vRNIRestMethod -Connection $Connection -Method POST -URI "/api/ni/settings/licensing/validate" -Body $requestBody
$validate.result
}
function Install-vRNILicensing {
<#
.SYNOPSIS
Installs a given license on vRealize Network Insight.
.DESCRIPTION
vRealize Network Insight requires licensing to function. This will install
a given license. Use Test-vRNILicensing on the license first.
If successful, the result will be details of the license.
If not successful, the function will throw an exception
with the API error.
.EXAMPLE
PS C:\> Install-vRNILicensing -License xxx-yyyy-dddd
Installs the given license
#>
param (
[Parameter (Mandatory = $true)]
# The license key we want to validate
[ValidateNotNullOrEmpty()]
[string]$License,
[Parameter (Mandatory = $False)]
# vRNI Connection object
[ValidateNotNullOrEmpty()]
[PSCustomObject]$Connection = $defaultvRNIConnection
)
# Format request with all given data
$requestFormat = @{
"licenseKey" = $License
}
# Convert the hash to JSON, form the URI and send the request to vRNI
$requestBody = ConvertTo-Json $requestFormat
$validate = Invoke-vRNIRestMethod -Connection $Connection -Method POST -URI "/api/ni/settings/licensing/activate" -Body $requestBody
$validate.result
}
function Remove-vRNILicensing {
<#
.SYNOPSIS
Removes a given license from vRealize Network Insight.
.DESCRIPTION
vRealize Network Insight requires licensing to function. This will remove
a given license.
If successful, the result will empty.
If not successful, the function will throw an exception
with the API error.
.EXAMPLE
PS C:\> Remove-vRNILicensing -License xxx-yyyy-dddd
Removes the given license
#>
param (
[Parameter (Mandatory = $true)]
# The license key we want to validate
[ValidateNotNullOrEmpty()]
[string]$License,
[Parameter (Mandatory = $False)]
# vRNI Connection object
[ValidateNotNullOrEmpty()]
[PSCustomObject]$Connection = $defaultvRNIConnection
)
# Format request with all given data
$requestFormat = @{
"licenseKey" = $License
}
# Convert the hash to JSON, form the URI and send the request to vRNI
$requestBody = ConvertTo-Json $requestFormat
$validate = Invoke-vRNIRestMethod -Connection $Connection -Method DELETE -URI "/api/ni/settings/licensing/deactivate" -Body $requestBody
$validate.result
}
#####################################################################################################################
#####################################################################################################################
####################################### Backup Management ##################################################
#####################################################################################################################
#####################################################################################################################
function Get-vRNIBackup {
<#
.SYNOPSIS
Retrieve the settings of the backup of the vRealize Network Insight Platform configuration.
.DESCRIPTION
You can create scheduled backups of the vRealize Network Insight Platform configuration,
this cmdlet retrieves the settings of the backup.
If the invocation returns a 404 error; the backup is not configured.
.EXAMPLE
PS C:\> Get-vRNIBackup
Returns the current settings of the backup
#>
param (
[Parameter (Mandatory = $False)]
# vRNI Connection object
[ValidateNotNullOrEmpty()]
[PSCustomObject]$Connection = $defaultvRNIConnection
)
$conf = Invoke-vRNIRestMethod -Connection $Connection -Method GET -URI "/api/ni/settings/backup"
$conf
}
function Get-vRNIBackupStatus {
<#
.SYNOPSIS
Retrieve the status of the backup of the vRealize Network Insight Platform configuration.
.DESCRIPTION
You can create scheduled backups of the vRealize Network Insight Platform configuration,
this cmdlet retrieves the status of the backup.
.EXAMPLE
PS C:\> Get-vRNIBackupStatus
Returns the current status of the backup
#>
param (
[Parameter (Mandatory = $False)]
# vRNI Connection object
[ValidateNotNullOrEmpty()]
[PSCustomObject]$Connection = $defaultvRNIConnection
)
$status = Invoke-vRNIRestMethod -Connection $Connection -Method GET -URI "/api/ni/settings/backup/status"
$status
}