diff --git a/CHANGELOG.md b/CHANGELOG.md index 500b2dae..84500aad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,44 @@ # Release History +## v1.5.0 (2022-29-03) +- Enhanced `Add-SsoPermission` cmdlet to verify that the SSO Group exists in vCenter Single Sign-On. +- Enhanced `Enable-SupervisorCluster` cmdlet additional enhancements around pre-validation of inputs. +- Enhanced `Add-vRLIAgentGroup` cmdlet to support adding multiple Agent Groups of the same type. +- Enhanced `Add-vROPSAdapterNsxt` cmdlet to support defaulting to Default collector group rather than using custom remote collector group. +- Enhanced `Add-vROPSAdapterPing` cmdlet to support defaulting to Default collector group rather than using custom remote collector group. +- Enhanced `Set-WorkspaceOneNtpConfig` cmdlet to support updating NTP configuration for Clustered Workspace ONE Access +- Added `Undo-WorkspaceOneNsxtIntegration` cmdlet to disable the integration between NSX Manager and Workspace ONE Access. +- Added `Undo-SsoPermission` cmdlet to remove a user or group's access from vCenter Single Sign-On. +- Added `Undo-NsxtVidmRole` cmdlet to remove user or group's access from NSX-T Data Center. +- Added `Undo-ClusterGroup` cmdlet to remove a vSphere DRS Cluster Group. +- Added `Undo-vCenterGlobalPermission` cmdlet to remove vSphere Global Permissions from vCenter Server. +- Added `Undo-vSphereRole` cmdlet to remove a custom vSphere Role from vCenter Server. +- Added `Undo-AntiAffinityRule` cmdlet to remove an Anti-Affinity Rule from vCenter Server. +- Added `Undo-VmStartupRule` cmdlet to remove a VM to VM vSphere DRS Rule from vCenter Server. +- Added `Undo-WorkspaceOneDirectoryGroup` cmdlet to remove Active Directory Groups from Workspace ONE Access Directory sync. +- Added `Add-SupervisorClusterLicense` cmdlet to install and assign a license to a Tanzu Kubernetes Cluster. +- Added `Request-SignedCertificate` cmdlet to request a signed certificate from a Microsoft Certificate Authority. +- Added `Set-vRSLCMDnsConfig` cmdlet to update the DNS configuration of vRealize Suite Lifecycle Manager. +- Added `Undo-vRSLCMDnsConfig` cmdlet to revert the DNS configuration of vRealize Suite Lifecycle Manager to match SDDC Manager. +- Added `Add-vRSLCMNtpServer` cmdlet to add NTP Servers to vRealize Suite Lifecycle Manager. +- Added `Undo-vRSLCMNtpServer` cmdlet to revert the NTP configuration of vRealize Suite Lifecycle Manager to match SDDC Manager. +- Added `Set-WorkspaceOneDnsConfig` cmdlet to update the DNS configuration of Workspace ONE Access. +- Added `Undo-WorkspaceOneDnsConfig` cmdlet to revert the DNS configuration of Workspace ONE Access to match SDDC Manager. +- Added `Set-vROPSDnsConfig` cmdlet to update the DNS configuration of vRealize Operations Manager. +- Added `Undo-vROPSDnsConfig` cmdlet to revert the DNS configuration of vRealize Operations Manager to match SDDC Manager. +- Added `Add-vROPSNtpServer` cmdlet to add NTP Servers to vRealize Operations Manager. +- Added `Undo-vROPSNtpServer` cmdlet to revert the NTP configuration of vRealize Operations Manager to match SDDC Manager. +- Added Sample Scripts in the SampleScripts\iam folder, each script uses the Planning and Preparation Workbook as the input source: + - `iamUndoDeployment.ps1` automates the removal of the Identity and Access Management for VMware Cloud Foundation validated solution. +- Updated Sample Scripts in the SampleScripts\iam folder, each script uses the Planning and Preparation Workbook as the input source: + - `iamConfigureWorkspaceOne.ps1` updated input values to use latest VCF 4.4.x Planning and Prep Workbook. + Added Sample Scripts in the SampleScripts\dri folder, each script uses the Planning and Preparation Workbook as the input source: + - `driConfigureSupervisorCluster.ps1` automates the configuration of vSphere, NSX and enables the Supervisor Cluster. + - `driDeployTanzuCluster.ps1` automates the the deployment of a Tanzu Kubernetes Cluster. + - `driUndoDeployment.ps1` automates the removal of the Developer Ready Infrastructure for VMware Cloud Foundation validated solution. +Added Sample Scripts in the SampleScripts\ila folder, each script uses the Planning and Preparation Workbook as the input source: + - `ilaUndoVrealizeLogInsight.ps1` automates the removal of Intelligent Logging and Analytics for VMware Cloud Foundation validated solution. + ## v1.4.0 (2022-22-02) - Enhanced all Developer Ready Infrastructure Solution cmdlets for better error handling and message output. - Added `Undo-NetworkSegment` cmdlet to remove an NSX segment from an NSX Management Cluster. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b524d1e4..11b2350c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -19,7 +19,7 @@ This is a rough outline of what a contributor's workflow looks like: Example: ``` shell -git remote add upstream https://github.com/vmware/power-validated-solutions-for-cloud-foundation.git +git remote add upstream https://github.com/vmware-samples/power-validated-solutions-for-cloud-foundation.git git checkout -b my-new-feature main git commit -a git push origin my-new-feature diff --git a/LICENSE b/LICENSE index fa436274..774944bf 100644 --- a/LICENSE +++ b/LICENSE @@ -1,5 +1,5 @@ Power Validated Solutions for Cloud Foundation -Copyright 2021 VMware, Inc. +Copyright 2021-2022 VMware, Inc. The BSD-2 license (the "License") set forth below applies to all parts of the Power Validated Solutions for Cloud Foundation project. You may not use this file except in compliance with the License. diff --git a/NOTICE b/NOTICE index 692ca83b..c69e85c7 100644 --- a/NOTICE +++ b/NOTICE @@ -1,5 +1,5 @@ Power Validated Solutions for Cloud Foundation -Copyright 2021 VMware, Inc. +Copyright 2021-2022 VMware, Inc. This product is licensed to you under the BSD-2 license (the "License"). You may not use this product except in compliance with the BSD-2 License. diff --git a/PowerValidatedSolutions.psd1 b/PowerValidatedSolutions.psd1 index 3b7c9f02..b1ad2b0a 100644 --- a/PowerValidatedSolutions.psd1 +++ b/PowerValidatedSolutions.psd1 @@ -1,9 +1,9 @@ -# + # Module manifest for module 'PowerValidatedSolutions' # # Generated by: Gary Blake, Cloud Infrastructure Business Group (CIBG) # -# Generated on: 2/22/2022 +# Generated on: 3/29/2022 # @{ @@ -12,13 +12,13 @@ RootModule = 'PowerValidatedSolutions.psm1' # Version number of this module. - ModuleVersion = '1.4.0' + ModuleVersion = '1.5.0' # Supported PSEditions # CompatiblePSEditions = @() # ID used to uniquely identify this module - GUID = '082b7143-0d52-40f6-b148-a0a6bc9743fa' + GUID = 'b72bc9fc-482a-4c8b-9506-e20e4168d3bc' # Author of this module Author = 'Gary Blake, Cloud Infrastructure Business Group (CIBG)' diff --git a/PowerValidatedSolutions.psm1 b/PowerValidatedSolutions.psm1 index b638ee97..db95fa9f 100644 --- a/PowerValidatedSolutions.psm1 +++ b/PowerValidatedSolutions.psm1 @@ -1,6 +1,5 @@ -# PowerShell module for VMware Cloud Foundation Validated Solutions -# Contributions, Improvements &/or Complete Re-writes Welcome! -# https://github.com/? +# PowerShell Module for VMware Validated Solutions for VMware Cloud Foundation +# Contributions are welcome. https://github.com/vmware-samples/power-validated-solutions-for-cloud-foundation/blob/main/CONTRIBUTING.md # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR @@ -8,11 +7,11 @@ # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ### Note -# This powershell module should be considered entirely experimental. It is still in development & not tested beyond lab -# scenarios. It is recommended you dont use it for any production environment without testing extensively! +# This PowerShell module should be considered entirely experimental. It is still in development & not tested beyond lab +# scenarios. It is recommended you don't use it for any production environment without testing extensively! # Enable communication with self signed certs when using Powershell Core. If you require all communications to be secure -# and do not wish to allow communication with self signed certs remove lines 17-38 before importing the module. +# and do not wish to allow communication with self-signed certificates remove lines 17-38 before importing the module. if ($PSEdition -eq 'Core') { $PSDefaultParameterValues.Add("Invoke-RestMethod:SkipCertificateCheck", $true) @@ -56,7 +55,7 @@ Function Resolve-PSModule { Informing user only if the module needs importing/installing. If the module is already present nothing will be displayed. .EXAMPLE - PS C:\> $poshSSH = Resolve-PSModule -moduleName "Posh-SSH" + $poshSSH = Resolve-PSModule -moduleName "Posh-SSH" This example will check if the current PS module session has Posh-SSH installed, if not will try to install it #> @@ -117,9 +116,8 @@ Function Add-IdentitySource { The Add-IdentitySource cmdlets adds Active Directory over LDAP/LDAPS as an Identity Provider to the vCenter Server and configures is as the default provider. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible - - Connects to the Management Domain vCenter Server instance + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to Management Domain vCenter Server - Verifies a connection to the Active Directory Domain Controller using the -domain and -dcMachineName values - Adds the Active Directory Domain as an Identity Provider if not already present - Configures the new LDAP/LDAPs Identity Provider as the default @@ -223,9 +221,8 @@ Function Undo-IdentitySource { .DESCRIPTION The Undo-IdentitySource cmdlets removes Active Directory over LDAP/LDAPS as an Identity Provider from the vCenter Server. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible - - Connects to the Management Domain vCenter Server instance + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to Management Domain vCenter Server - Removes the Active Directory Domain as an Identity Provider if its present .EXAMPLE @@ -279,10 +276,9 @@ Function Add-SddcManagerRole { .DESCRIPTION The Add-SddcManagerRole cmdlet assigns an SDDC Manager role to the user or group provided. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible - Verifies that the bind credetials are valid - - Connects to the Management Domain vCenter Server instance + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to Management Domain vCenter Server - Verifies that the domain is present in vCenter Server as an Identity Provider - Verifies the user or group exists in Active Directory - Assigns the user or group to the SDDC Manager role @@ -386,10 +382,8 @@ Function Undo-SddcManagerRole { .DESCRIPTION The Undo-SddcManagerRole cmdlet removes access for a user or group in SDDC Manager. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible - - Verifies the user or group is assigned access - - Removes the user or group from SDDC Manager + - Validates that network connectivity and authentication is possible to SDDC Manager + - Removes the user or group from SDDC Manager if present .EXAMPLE Undo-SddcManagerRole -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -principal gg-vcf-admins -type GROUP @@ -436,10 +430,8 @@ Function Set-vCenterPasswordExpiration { .DESCRIPTION The Set-vCenterPasswordExpiration cmdlet configures password expiration settings for the vCenter Server root account. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible - - Validates that network connectivity is available to the vCenter Server instance - - Makes a connection to the vCenter Server instance and validates that authentication possible + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to vCenter Server - Configures the password expiration either to never expire or to expire in given number of days - Sets the email for warning notification to given value @@ -507,12 +499,9 @@ Function Set-EsxiPasswordPolicy { .DESCRIPTION The Set-EsxiPasswordPolicy cmdlet configures the password and lockout policies on ESXi. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible - - Gathers the vCenter Server details for the workload domain - - Validates that network connectivity is available to the vCenter Server instance - - Makes a connection to the vCenter Server instance and validates that authentication possible + - Validates that network connectivity and authentication is possible to SDDC Manager - Validates that the workload domain exists in the SDDC Manager inventory + - Validates that network connectivity and authentication is possible to vCenter Server - Gathers the ESXi hosts for the cluster specificed - Configured all ESXi hosts in he provided cluster @@ -588,11 +577,8 @@ Function Install-WorkspaceOne { .DESCRIPTION The Install-WorkspaceOne cmdlet deploys the Workspace ONE Access Virtual Appliance OVA. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible - - Gathers vSphere configuration from Management Domain vCenter Server - - Validates that network connectivity is available to the vCenter Server instance - - Makes a connection to the vCenter Server instance and validates that authentication possible + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to Management Domain vCenter Server - Gathers DNS and NTP configuration from SDDC Manager - Deploys the Workspace ONE Access Virtual Appliance to the Management Domain vCenter Server @@ -716,6 +702,68 @@ Function Install-WorkspaceOne { } Export-ModuleMember -Function Install-WorkspaceOne +Function Undo-WorkspaceOne { + <# + .SYNOPSIS + Remove Workspace ONE Access Virtual Appliance + + .DESCRIPTION + The Undo-WorkspaceOne cmdlet removes the Workspace ONE Access Virtual Appliance. The cmdlet connects + to SDDC Manager using the -server, -user, and -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to Management Domain vCenter Server + - Removes the Workspace ONE Access Virtual Appliance from the Management Domain vCenter Server + + .EXAMPLE + Undo-WorkspaceOne -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -wsaHostname sfo-wsa01 + This example removes the Workspace ONE Access Virtual Appliance named sfo-wsa01 from the Management Domain + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaHostname + ) + + Try { + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) { + if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + if (Get-VM -Name $wsaHostname -ErrorAction Ignore) { + if ((Get-VM -Name $wsaHostname).PowerState -ne "PoweredOff") { + Stop-VM -VM $wsaHostname -Kill -Confirm:$false | Out-Null + if ((Get-VM -Name $wsaHostname).PowerState -ne "PoweredOff") { + Write-Error "Unable to Power Off virtual machine: PRE_VALIDATION_FAILED" + Break + } + } + Remove-VM $wsaHostname -DeletePermanently -Confirm:$false | Out-null + if (!(Get-VM -Name $wsaHostname -ErrorAction Ignore)) { + Write-Output "Removing virtual machine from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($wsaHostname): SUCCESSFUL" + } + else { + Write-Error "Removing virtual machine from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($wsaHostname): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Removing virtual machine from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($wsaHostname), already removed: SKIPPED" + } + Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue + } + } + } + } + } + } + Catch { + Debug-ExceptionWriter -object $_ + } +} +Export-ModuleMember -Function Undo-WorkspaceOne + Function Initialize-WorkspaceOne { <# .SYNOPSIS @@ -723,7 +771,7 @@ Function Initialize-WorkspaceOne { .DESCRIPTION The Initialize-WorkspaceOne cmdlet performs the initial configuration of Workspace ONE Access Virtual Appliance. - - Validates that network connectivity is available to the Workspace ONE Access instance + - Validates that network connectivity is possible to Workspace ONE Access - Sets the default password for the admin, root and SSH Users - Initializes the internal PostgrsSQL database - Activates the default connector @@ -790,59 +838,83 @@ Function Set-WorkspaceOneNtpConfig { The Set-WorkspaceOneNtpConfig cmdlet configures the NTP Server details of the Workspace ONE Access Appliance using the same NTP Server configuration as SDDC Manager. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible - - Gathers Management Domain vCenter Server details - - Validates that network connectivity is available to the vCenter Server instance - - Makes a connection to the vCenter Server instance and validates that authentication possible + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to Management Domain vCenter Server - Gathers the NTP configuration details from SDDC Manager - Configures Workspace ONE Access NTP configuration .EXAMPLE Set-WorkspaceOneNtpConfig -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -wsaFqdn sfo-wsa01.sfo.rainpole.io -rootPass VMw@re1! - This example configures the Workspace ONE Access Virtual Appliance sfo-wsa01.sfo.rainpole.io with the same NTP Servers defined in SDDC Manager + This example configures the Workspace ONE Access Virtual Appliance sfo-wsa01.sfo.rainpole.io with the same NTP servers defined in SDDC Manager + + .EXAMPLE + Set-WorkspaceOneNtpConfig -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -wsaFqdn sfo-wsa01.sfo.rainpole.io -rootPass VMw@re1! -ntpServer ntp.lax.rainpole.io + This example adds the NTP server ntp.lax.rainpole.io to the Workspace ONE Access Virtual Appliance sfo-wsa01.sfo.rainpole.io in addition to the NTP servers defined in SDDC Manager #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaFqdn, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$rootPass + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$wsaFqdn, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$rootPass, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$ntpServer, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [switch]$vrslcmIntegrated ) - + Try { if (Test-VCFConnection -server $server) { if (Test-VCFAuthentication -server $server -user $user -pass $pass) { if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) { if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { - if (Test-WSAConnection -server $wsaFqdn) { + if (!$ntpServer) { $ntpServer = (Get-VCFConfigurationNTP).ipAddress - $vmName = $wsaFqdn.Split(".")[0] - if ((Get-VM -Name $vmName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue )) { - $scriptCommand = '/usr/local/horizon/scripts/ntpServer.hzn --get' - $output = Invoke-VMScript -VM $vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $rootPass -Server $vcfVcenterDetails.fqdn - if (($output.ScriptOutput).Contains($ntpServer)) { - Write-Warning "Configuring NTP on Workspace ONE Access Instance ($vmName) to NTP Server ($ntpServer), already performed: SKIPPED" + } + else { + $testNtp = Test-NtpServer -Server $ntpServer + if ($testNtp -eq $false) { + Write-Error "Unable to confirm NTP server $ntpServer is valid: PRE_VALIDATION_FAILED" + break + } + $existingNtpServer = (Get-VCFConfigurationNTP).ipAddress + $ntpServer = $existingNtpServer + "," + $ntpServer + } + if ($vrslcmIntegrated) { + if (($vcfVrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-vRSLCMAuthentication -server $vcfVrslcmDetails.fqdn -user $vcfVrslcmDetails.adminUser -pass $vcfVrslcmDetails.adminPass) { + $wsaVms = Get-vRSLCMProductNode -environmentName globalenvironment -product vidm + foreach ($wsaVm in $wsaVms) { + if (Test-WSAConnection -server $wsaVm.hostname) { + if ((Get-VM -Name $wsaVm.vmName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue )) { + Set-WorkspaceOneApplianceNtpConfig -vmName $wsaVm.vmName -rootPass $rootPass -ntpServer $ntpServer + } + else { + Write-Error "Unable to locate a virtual machine named ($($wsaVm.vmName)) in vCenter Server ($($vcfVcenterDetails.fqdn)) inventory: PRE_VALIDATION_FAILED" + } + } + } } else { - $scriptCommand = '/usr/local/horizon/scripts/ntpServer.hzn --set ' + $ntpServer - $output = Invoke-VMScript -VM $vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $rootPass -Server $vcfVcenterDetails.fqdn - $scriptCommand = '/usr/local/horizon/scripts/ntpServer.hzn --get' - $output = Invoke-VMScript -VM $vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $rootPass -Server $vcfVcenterDetails.fqdn - if (($output.ScriptOutput).Contains($ntpServer)) { - Write-Output "Configuring NTP on Workspace ONE Access Instance ($vmName) to NTP Server ($ntpServer): SUCCESSFUL" - } - else { - Write-Error "Configuring NTP on Workspace ONE Access Instance ($vmName) to NTP Server ($ntpServer): POST_VALIDATION_FAILED" - } + Write-Error "Unable to connect to vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn) to gather Workspace ONE Access appliance inventory: PRE_VALIDATION_FAILED" } + Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue } - else { - Write-Error "Unable to local a virtual machine named ($vmName) in vCenter Server ($($vcfVcenterDetails.fqdn)) inventory: PRE_VALIDATION_FAILED" + } + else { + if (!$wsaFqdn) { + Write-Error "The FQDN parameter (-wsaFqdn) is required for a standalone Workspace ONE Access instance: PRE_VALIDATION_FAILED" + } + $vmName = $wsaFqdn.Split(".")[0] + if (Test-WSAConnection -server $wsaFqdn) { + if ((Get-VM -Name $vmName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue )) { + Set-WorkspaceOneApplianceNtpConfig -vmName $vmName -rootPass $rootPass -ntpServer $ntpServer + } + else { + Write-Error "Unable to locate a virtual machine named ($vmName) in vCenter Server ($($vcfVcenterDetails.fqdn)) inventory: PRE_VALIDATION_FAILED" + } + Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue } - Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue } } } @@ -854,7 +926,8 @@ Function Set-WorkspaceOneNtpConfig { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Set-WorkspaceOneNtpConfig +New-Alias -Name Undo-WorkspaceOneNtpConfig -Value Set-WorkspaceOneNtpConfig +Export-ModuleMember -Alias Undo-WorkspaceOneNtpConfig -Function Set-WorkspaceOneNtpConfig Function Install-WorkspaceOneCertificate { <# @@ -864,11 +937,8 @@ Function Install-WorkspaceOneCertificate { .DESCRIPTION The Install-WorkspaceOneCertificate cmdlet replaces the certificate on the Workspace ONE Access. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible - - Gathers Management Domain vCenter Server details - - Validates that network connectivity is available to the vCenter Server instance - - Makes a connection to the vCenter Server instance and validates that authentication possible + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to Management Domain vCenter Server - Copies over the certificate files to the Workspace ONE Access appliance and installs the certificate .EXAMPLE @@ -955,8 +1025,7 @@ Function Set-WorkspaceOneSmtpConfig { .DESCRIPTION The Set-WorkspaceOneSmtpConfig cmdlet configures the SMTP Server details of the Workspace ONE Access Appliance. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the Workspace ONE Access instance - - Makes a connection to the Workspace ONE Access instance instance and validates that authentication possible + - Validates that network connectivity and authentication is possible to Workspace ONE Access - Configures the SMTP Server settings .EXAMPLE @@ -1011,8 +1080,7 @@ Function Add-WorkspaceOneDirectory { .DESCRIPTION The Add-WorkspaceOneDirectory cmdlet configures Active Directory LDAP Directory in Workspace ONE Access Appliance. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the Workspace ONE Access instance - - Makes a connection to the Workspace ONE Access instance and validates that authentication possible + - Validates that network connectivity and authentication is possible to Workspace ONE Access - Validates that the bind user can authenticate to the domain - Creates an identity provider within Workspace ONE Access @@ -1126,14 +1194,10 @@ Function Set-WorkspaceOneNsxtIntegration { .DESCRIPTION The Set-WorkspaceOneNsxtIntegration cmdlet configures integration between NSX Manager and Workspace ONE Access. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible - - Gathers details for the NSX Management Cluster for the Workload Domain - - Validates that network connectivity is available to the NSX Management Cluster instance - - Makes a connection to the NSX Management Cluster instance and validates that authentication possible - - Validates that network connectivity is available to the Workspace ONE Access instance - - Makes a connection to the Workspace ONE Access instance and validates that authentication possible - - Creates a service client within Workspace ONE Access instance + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to NSX Management Cluster + - Validates that network connectivity and authentication is possible to Workspace ONE Access + - Creates a service client within Workspace ONE Access - Enables the integration between NSX Manager and Workspace ONE Access .EXAMPLE @@ -1208,6 +1272,82 @@ Function Set-WorkspaceOneNsxtIntegration { } Export-ModuleMember -Function Set-WorkspaceOneNsxtIntegration +Function Undo-WorkspaceOneNsxtIntegration { + <# + .SYNOPSIS + Disables the integrate between NSX Manager with Workspace ONE Access + + .DESCRIPTION + The Undo-WorkspaceOneNsxtIntegration cmdlet disables integration between NSX Manager and Workspace ONE Access. + The cmdlet connects to SDDC Manager using the -server, -user, and -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to NSX Management Cluster + - Disables the integration between NSX Manager and Workspace ONE Access + + .EXAMPLE + Undo-WorkspaceOneNsxtIntegration -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -wsaFqdn sfo-wsa01.sfo.rainpole.io -wsaUser admin -wsaPass VMw@re1! + This example disables the integration between NSX Manager with Workspace ONE Access + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaFqdn, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaUser, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaPass + ) + + Try { + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}) { + if (($vcfNsxDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain)) { + if (Test-NSXTConnection -server $vcfNsxDetails.fqdn) { + if (Test-NSXTAuthentication -server $vcfNsxDetails.fqdn -user $vcfNsxDetails.adminUser -pass $vcfNsxDetails.adminPass) { + if (Test-WSAConnection -server $wsaFqdn) { + if (Test-WSAAuthentication -server $wsaFqdn -user $wsaUser -pass $wsaPass) { + if ((Get-NsxtVidm).vidm_enable -match "True") { + $clientId = $vcfNsxDetails.fqdn.Split(".")[0] + "-oauth" + $command = 'openssl s_client -connect ' + $wsaFqdn + ':443 2>&1 | openssl x509 -sha256 -fingerprint -noout' + $wsaThumbprint = (Invoke-Expression "& $command").Split("=")[1] + if (!$wsaThumbprint) { + Write-Error "Obtaining SSL Thumbprint for Workspace ONE Access Instance ($wsaFqdn): FAILED" + Break + } + #$sharedSecret = (Get-WSAOAuthToken).message + #if ((Get-NsxtVidm).vidm_enable -match "True") { + $clientIdSecret = (Get-WSAClient -clientId $clientId).secret + Set-NsxtVidm -wsaHostname $wsaFqdn -thumbprint $wsaThumbprint -clientId $clientId -sharedSecret $clientIdSecret -nsxHostname $vcfNsxDetails.fqdn -disable | Out-Null + if ((Get-NsxtVidm).vidm_enable -match "False") { + Write-Output "Disabling integration between NSX Manager ($($vcfNsxDetails.fqdn)) and Workspace ONE Acccess Instance ($wsaFqdn): SUCCESSFUL" + } + else { + Write-Error "Disabling integration between NSX Manager ($($vcfNsxDetails.fqdn)) and Workspace ONE Acccess Instance ($wsaFqdn): POST_VALIDATION_FAILEDg" + } + } + else { + Write-Warning "Disabling integration between NSX Manager ($($vcfNsxDetails.fqdn)) and Workspace ONE Acccess Instance ($wsaFqdn), already disabled: SKIPPED" + } + } + } + } + } + } + } + else { + Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" + } + } + } + } + Catch { + Debug-ExceptionWriter -object $_ + } +} +Export-ModuleMember -Function Undo-WorkspaceOneNsxtIntegration + Function Add-NsxtVidmRole { <# .SYNOPSIS @@ -1216,11 +1356,8 @@ Function Add-NsxtVidmRole { .DESCRIPTION The Add-NsxtVidmRole cmdlet configures role assignments in NSX Manager. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible - - Gathers details for the NSX Management Cluster for the Workload Domain - - Validates that network connectivity is available to the NSX Management Cluster instance - - Makes a connection to the NSX Management Cluster instance and validates that authentication possible + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to NSX Management Cluster - Assigns Active Directory users or groups to NSX Manager roles based on the -type, -principal, and -role values. .EXAMPLE @@ -1231,6 +1368,7 @@ Function Add-NsxtVidmRole { Add-NsxtVidmRole -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -type user -principal "svc-vra-nsx@rainpole.io" -role enterprise_admin This example assigns the user svc-vra-nsx@rainpole.io with the enterprise_admin role in NSX Manager #> + Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, @@ -1280,6 +1418,65 @@ Function Add-NsxtVidmRole { } Export-ModuleMember -Function Add-NsxtVidmRole +Function Undo-NsxtVidmRole { + <# + .SYNOPSIS + Remove Role-Based Access Control from NSX Manager + + .DESCRIPTION + The Undo-NsxtVidmRole cmdlet removes role assignments in NSX Manager. The cmdlet connects to SDDC Manager + using the -server, -user, and -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to NSX Management Cluster + - Removes user or group's from NSX Manager roles based on the -principal + + .EXAMPLE + Undo-NsxtVidmRole -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -principal "gg-nsx-enterprise-admins@sfo.rainpole.io" + This example removes the group gg-nsx-enterprise-admins@sfo.rainpole.io from NSX Manager + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$principal + ) + Try { + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}) { + if (($vcfNsxDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain)) { + if (Test-NSXTConnection -server $vcfNsxDetails.fqdn) { + if (Test-NSXTAuthentication -server $vcfNsxDetails.fqdn -user $vcfNsxDetails.adminUser -pass $vcfNsxDetails.adminPass) { + if (Get-NsxtUser | Where-Object { $_.name -eq $principal }) { + Remove-NsxtRole -id (Get-NsxtUser | Where-Object { $_.name -eq $principal }).id + if (!(Get-NsxtUser | Where-Object { $_.name -eq $principal })) { + Write-Output "Removing access for ($principal) from NSX-T Data Center for Workload Domain ($domain): SUCCESSFUL" + } + else { + Write-Error "Removing access for ($principal) from NSX-T Data Center for Workload Domain ($domain): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Removing access for ($principal) from NSX-T Data Center for Workload Domain ($domain), already removed: SKIPPED" + } + } + } + } + } + else { + Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" + } + } + } + } + Catch { + Debug-ExceptionWriter -object $_ + } +} +Export-ModuleMember -Function Undo-NsxtVidmRole + Function Add-WorkspaceOneRole { <# .SYNOPSIS @@ -1289,8 +1486,7 @@ Function Add-WorkspaceOneRole { The Add-WorkspaceOneRole cmdlet assigns roles to Active Directory groups provided to manage administrative access to the Workspace ONE Access instance. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the Workspace ONE Access instance - - Makes a connection to the Workspace ONE Access instance and validates that authentication possible + - Validates that network connectivity and authentication is possible to Workspace ONE Access - Validates the role exists in Workspace ONE Access - Validates the group exists in Workspace ONE Access - Assign the role to the group @@ -1367,7 +1563,9 @@ Function Get-NsxtManagerAuthenticationPolicy { .DESCRIPTION The Get-NsxtManagerAuthenticationPolicy cmdlet retrieves the current Authentication policy from each NSX manager nodes for a workload domain. The cmdlet connects to SDDC Manager using the -server, -user, and - -password values to retrive the NSX-T Data Center details from its inventory and then: + -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to NSX Manager - Output the following Authentication policy on each NSX manager node. a) api_failed_auth_lockout_period (in sec) b) api_failed_auth_reset_period (in sec) @@ -1420,11 +1618,8 @@ Function Set-NsxtManagerAuthenticationPolicy { .DESCRIPTION The Set-NsxtManagerAuthenticationPolicy cmdlet configures Authentication policy within NSX manager nodes within a workload domain. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible - - Gathers details for the NSX Management Cluster for the Workload Domain - - Validates that network connectivity is available to the NSX Management Cluster instance - - Makes a connection to the NSX Management Cluster instance and validates that authentication possible + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to NSX Management Cluster - Configure the following Authentication password policy on each NSX manager. a) api_failed_auth_lockout_period (in sec) b) api_failed_auth_reset_period (in sec) @@ -1513,8 +1708,10 @@ Function Get-NsxtEdgeNodeAuthenticationPolicy { .DESCRIPTION The Get-NsxtEdgeNodeAuthenticationPolicy cmdlet retrieves the current Authentication policy from NSX Edge nodes within a workload domain. The cmdlet connects to SDDC Manager using the -server, -user, and -password - values to retrive the NSX-T Data Center details from its inventory and then: - -Output the following Authentication policy on each NSX Edge Nodes. + values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to NSX Management Cluster + - Output the following Authentication policy on each NSX Edge Nodes. a) cli_failed_auth_lockout_period (in sec) b) cli_max_auth_failures (in attempt) c) minimum_password_length (in characters) @@ -1564,11 +1761,8 @@ Function Set-NsxtEdgeNodeAuthenticationPolicy { .DESCRIPTION The Set-NsxtEdgeNodeAuthenticationPolicy cmdlet configures the Authentication policy within NSX Edge nodes. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible - - Gathers details for the NSX Management Cluster for the Workload Domain - - Validates that network connectivity is available to the NSX Management Cluster instance - - Makes a connection to the NSX Management Cluster instance and validates that authentication possible + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to NSX Management Cluster - Configure the following Authentication policy on each NSX Edge Node. a) cli_failed_auth_lockout_period (in sec) b) cli_max_auth_failures (in attempt) @@ -1642,20 +1836,20 @@ Export-ModuleMember -Function Set-NsxtEdgeNodeAuthenticationPolicy Function Install-SiteRecoveryManager { <# .SYNOPSIS - Deploy Site Recovery Manager Virtual Appliance + Deploy Site Recovery Manager Virtual Appliance - .DESCRIPTION - The Install-SiteRecoveryManager cmdlet deploys the Site Recovery Manager Virtual Appliance OVA. - The cmdlet connects to SDDC Manager using the -server, -user, and -password values to retrive the management domain + .DESCRIPTION + The Install-SiteRecoveryManager cmdlet deploys the Site Recovery Manager Virtual Appliance OVA. The cmdlet + connects to SDDC Manager using the -server, -user, and -password values to retrive the management domain vCenter Server details from its inventory and then: - Gathers vSphere configuration from vCenter Server - Gathers DNS and NTP configuration from SDDC Manager - Deploys the Site Recovery Manage Virtual Appliance - .EXAMPLE - Install-SiteRecoveryManager -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -srmFqdn sfo-wsa01.sfo.rainpole.io -srmIpAddress 192.168.31.60 -srmGateway 192.168.31.1 -srmSubnetMask 255.255.255.0 -srmOvfPath F:\identity-manager.ova -srmFolder sfo-m01-fd-srm + .EXAMPLE + Install-SiteRecoveryManager -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -srmFqdn sfo-wsa01.sfo.rainpole.io -srmIpAddress 192.168.31.60 -srmGateway 192.168.31.1 -srmSubnetMask 255.255.255.0 -srmOvfPath F:\identity-manager.ova -srmFolder sfo-m01-fd-srm This example deploys the Site Recovery Manager Virtual Appliance into the sfo-m01-fd-srm folder of the management domain - #> + #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, @@ -1741,20 +1935,20 @@ Export-ModuleMember -Function Install-SiteRecoveryManager Function Install-vSphereReplicationManager { <# .SYNOPSIS - Deploy vSphere Replication Manager Virtual Appliance + Deploy vSphere Replication Manager Virtual Appliance - .DESCRIPTION - The Install-vSphereReplicationManager cmdlet deploys the vSphere Replication Manager Virtual Appliance OVA. + .DESCRIPTION + The Install-vSphereReplicationManager cmdlet deploys the vSphere Replication Manager Virtual Appliance OVA. The cmdlet connects to SDDC Manager using the -server, -user, and -password values to retrive the management domain vCenter Server details from its inventory and then: - Gathers vSphere configuration from vCenter Server - Gathers DNS and NTP configuration from SDDC Manager - Deploys the vSphere Replication Manager Virtual Appliance - .EXAMPLE - Install-vSphereReplicationManager -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -vrmsFqdn sfo-m01-vrms01.sfo.rainpole.io -vrmsIpAddress 192.168.31.60 -vrmsGateway 192.168.31.1 -vrmsSubnetMask 255.255.255.0 -vrmsOvfPath F:\vrms.ova -vrmsFolder sfo-m01-fd-vrms + .EXAMPLE + Install-vSphereReplicationManager -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -vrmsFqdn sfo-m01-vrms01.sfo.rainpole.io -vrmsIpAddress 192.168.31.60 -vrmsGateway 192.168.31.1 -vrmsSubnetMask 255.255.255.0 -vrmsOvfPath F:\vrms.ova -vrmsFolder sfo-m01-fd-vrms This example deploys the vSphere Replication Manager Virtual Appliance into the sfo-m01-fd-vrms folder of the management domain - #> + #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, @@ -1838,20 +2032,20 @@ Export-ModuleMember -Function Install-vSphereReplicationManager Function Connect-DRSolutionTovCenter { <# .SYNOPSIS - Register SRM & vRMS with vCenter + Register Site Recovery Manager & vSphere Replciation with vCenter Server - .DESCRIPTION - The Connect-DRSolutionTovCenter cmdlet deploys the Site Recovery Manage Virtual Appliance OVA. + .DESCRIPTION + The Connect-DRSolutionTovCenter cmdlet deploys the Site Recovery Manage Virtual Appliance OVA. The cmdlet connects to SDDC Manager using the -server, -user, and -password values to retrive the management domain vCenter Server details from its inventory and then: - Gathers vSphere configuration from vCenter Server - Gathers DNS and NTP configuration from SDDC Manager - Deploys the Site Recovery Manage Virtual Appliance - .EXAMPLE - Connect-DRSolutionTovCenter -solution SRM -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -applianceFqdn sfo-m01-srm01.sfo.rainpole.io -vamiAdminPassword 'VMw@re1!' -domainType MANAGEMENT -siteName SFO01 -ssoAdminUser administrator@vsphere.local -ssoAdminPassword 'VMw@re1!' -adminEmail 'admin@rainpole.io' + .EXAMPLE + Connect-DRSolutionTovCenter -solution SRM -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -applianceFqdn sfo-m01-srm01.sfo.rainpole.io -vamiAdminPassword 'VMw@re1!' -domainType MANAGEMENT -siteName SFO01 -ssoAdminUser administrator@vsphere.local -ssoAdminPassword 'VMw@re1!' -adminEmail 'admin@rainpole.io' This example registers Site Recovery Manager with the vCenter Server of the management domain - #> + #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, @@ -1955,15 +2149,15 @@ Export-ModuleMember -Function Install-VAMICertificate Function Get-DRSolutionSummary { <# .SYNOPSIS - Retrieves the Site Recovery Manager summary + Retrieves the Site Recovery Manager summary - .DESCRIPTION - The Get-DRSolutionSummary cmdlet retrieves the Site Recovery Manager summary + .DESCRIPTION + The Get-DRSolutionSummary cmdlet retrieves the Site Recovery Manager summary - .EXAMPLE - Get-DRSolutionSummary -fqdn sfo-m01-srm01.sfo.rainpole.io -username admin -password VMw@re1! + .EXAMPLE + Get-DRSolutionSummary -fqdn sfo-m01-srm01.sfo.rainpole.io -username admin -password VMw@re1! This example retrieves the Site Recovery Manager summary - #> + #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$fqdn, @@ -1987,15 +2181,15 @@ Export-ModuleMember -Function Get-DRSolutionSummary Function Register-DRSolutionTovCenter { <# .SYNOPSIS - Registers SRM & vRMS with a given vCenter Server + Registers SRM & vRMS with a given vCenter Server - .DESCRIPTION - The Register-DRSolutionTovCenter cmdlet registers SRM & vRMS with a given vCenter Server + .DESCRIPTION + The Register-DRSolutionTovCenter cmdlet registers SRM & vRMS with a given vCenter Server - .EXAMPLE - Register-DRSolutionTovCenter -applianceFqdn sfo-m01-srm01.sfo.rainpole.io -vamiAdminPassword VMw@re1! -pscHost sfo-m01-vc01.sfo.rainpole.io -thumbprint EA:0F:24:7E:B4:4C:5E:ED:38:AE:79:A6:9E:A2:E8:8F:EE:54:D8:AF:18:6A:A2:57:DC:87:09:68:D4:76:36:DD -vcInstanceId 53cad28c-4160-4956-b7c1-c7bbc5185a39 -ssoAdminUser administrator@vsphere.local -ssoAdminPassword VMw@re1! -siteName SFO01 -adminEmail admin@rainpole.io -hostName sfo-m01-srm01.sfo.rainpole.io + .EXAMPLE + Register-DRSolutionTovCenter -applianceFqdn sfo-m01-srm01.sfo.rainpole.io -vamiAdminPassword VMw@re1! -pscHost sfo-m01-vc01.sfo.rainpole.io -thumbprint EA:0F:24:7E:B4:4C:5E:ED:38:AE:79:A6:9E:A2:E8:8F:EE:54:D8:AF:18:6A:A2:57:DC:87:09:68:D4:76:36:DD -vcInstanceId 53cad28c-4160-4956-b7c1-c7bbc5185a39 -ssoAdminUser administrator@vsphere.local -ssoAdminPassword VMw@re1! -siteName SFO01 -adminEmail admin@rainpole.io -hostName sfo-m01-srm01.sfo.rainpole.io This example registers the Site Recovery Manager Virtual Appliance with vCenter - #> + #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$applianceFqdn, @@ -2044,17 +2238,17 @@ Export-ModuleMember -Function Register-DRSolutionTovCenter Function Backup-VMOvfProperties { <# .SYNOPSIS - Backup-VMOvfProperties + Backup-VMOvfProperties - .DESCRIPTION - The Backup-VMOvfProperties cmdlet creates a backup of the OVF properties for each supplied VM. + .DESCRIPTION + The Backup-VMOvfProperties cmdlet creates a backup of the OVF properties for each supplied VM. The cmdlet connects to SDDC Manager using the -server, -user, and -password values to retrive the DR protected VMs from its inventory and then: - Creates a backup of the VM OVF environment - .EXAMPLE - Backup-VMOvfProperties -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! + .EXAMPLE + Backup-VMOvfProperties -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! This example creates a backup of the OVF properties for each supplied VM. - #> + #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, @@ -2143,17 +2337,17 @@ Export-ModuleMember -Function Backup-VMOvfProperties Function Restore-VMOvfProperties { <# .SYNOPSIS - Restore-VMOvfProperties + Restore-VMOvfProperties - .DESCRIPTION - The Restore-VMOvfProperties cmdlet creates a backup of the OVF properties for each supplied VM. + .DESCRIPTION + The Restore-VMOvfProperties cmdlet creates a backup of the OVF properties for each supplied VM. The cmdlet connects to SDDC Manager using the -server, -user, and -password values to retrive the DR protected VMs from its inventory and then: - Creates a restore of the VM OVF environment - .EXAMPLE - Restore-VMOvfProperties -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! + .EXAMPLE + Restore-VMOvfProperties -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! This example creates a backup of the OVF properties for each supplied VM. - #> + #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, @@ -2161,7 +2355,7 @@ Function Restore-VMOvfProperties { [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$fileDir ) - + Try { if (!$PsBoundParameters.ContainsKey("fileDir")) { $fileDir = Get-ExternalDirectoryPath @@ -2254,7 +2448,7 @@ Export-ModuleMember -Function Get-VMvAppConfig Function New-VMOvfProperty { <# - .SYNOPSIS + .SYNOPSIS Create a single OVF Property on a standard VM. .DESCRIPTION @@ -2346,7 +2540,6 @@ Function Set-VMOvfEnvTransport { .EXAMPLE Set-VMOvfEnvTransport -vm $vm -transport $transportObject - #> Param ( @@ -2447,26 +2640,103 @@ Function Set-VMOvfEULA { } Export-ModuleMember -Function Set-VMOvfEULA +Function Get-VMOvfProperty { + <# + .SYNOPSIS + Get OVF properties of a virtual appliance + + .DESCRIPTION + Returns OVF properties of a virtual appliance + + .EXAMPLE + Get-VMOvfProperty -vm (Get-VM -Name xreg-wsa01a) + This example returns an object that contains a full list of OVF properties for xreg-wsa01a + #> + + Param ( + [Parameter (Mandatory=$true)] [psObject]$vm + ) + + $vappProperties = $VM.ExtensionData.Config.VAppConfig.Property + + $results = @() + foreach ($vappProperty in $vappProperties | Sort-Object -Property Id) { + $tmp = [pscustomobject] @{ + Id = $vappProperty.Id; + Value = $vappProperty.Value + } + $results+=$tmp + } + $results +} +Export-ModuleMember -Function Get-VMOvfProperty + +Function Set-VMOvfProperty { + <# + .SYNOPSIS + Sets OVF properties on a virtual appliance + + .DESCRIPTION + Accepts a hash table with property ID and value and sets the defined OVF property and value for a virtual + appliance. + + .EXAMPLE + Set-VMOvfProperty -vm (Get-VM -Name xreg-wsa01a) -Properties @{"DNS"="172.16.11.4,172.16.11.5"} + This example sets the DNS servers to 172.16.11.4 and 172.16.11.5 in the OVF properties for xreg-wsa01a + #> + Param ( + [Parameter (Mandatory=$true)] [PSObject]$vm, + [Parameter (Mandatory=$true)] [hashtable]$properties + ) + + $vappProperties = $VM.ExtensionData.Config.VAppConfig.Property + + #define spec + $spec = New-Object VMware.Vim.VirtualMachineConfigSpec + $spec.vAppConfig = New-Object VMware.Vim.VmConfigSpec + $propertySpec = New-Object VMware.Vim.VAppPropertySpec[]($properties.count) + + #populate spec + foreach ($vappProperty in $vappProperties) { + if($properties.ContainsKey($vappProperty.Id)) { + $tmp = New-Object VMware.Vim.VAppPropertySpec + $tmp.Operation = "edit" + $tmp.Info = New-Object VMware.Vim.VAppPropertyInfo + $tmp.Info.Key = $vappProperty.Key + $tmp.Info.value = $properties[$vappProperty.Id] + $propertySpec+=($tmp) + } + } + $spec.VAppConfig.Property = $propertySpec + + #write spec + Write-Output "Setting vApp properties on $($vm.name)" + $task = $vm.ExtensionData.ReconfigVM_Task($spec) + $task1 = Get-Task -Id ("Task-$($task.value)") + $waitask = $task1 | Wait-Task +} +Export-ModuleMember -Function Set-VMOvfProperty + Function Get-NSXLBDetails { <# .SYNOPSIS - Get-NSXLBDetails + Get-NSXLBDetails - .DESCRIPTION - The Get-NSXLBDetails cmdlet gets the IP addresses of the VIPs & pool members for the NSX-T Load Balancer for vRealize. + .DESCRIPTION + The Get-NSXLBDetails cmdlet gets the IP addresses of the VIPs & pool members for the NSX-T Load Balancer for vRealize. The cmdlet connects to SDDC Manager using the -server, -user, and -password values to retrive the NSX load balancer configurationn - .EXAMPLE - Get-NSXLBDetails -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! + .EXAMPLE + Get-NSXLBDetails -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! This example gets the IP addresses of the VIPs & pool members for the NSX-T Load Balancer for vRealize. - #> + #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass ) - + Try { # Retrieve WSA VIP $wsaDetails = Get-WSAServerDetail -fqdn $server -username $user -password $pass @@ -2507,74 +2777,85 @@ Function Get-NSXLBDetails { } Export-ModuleMember -Function Get-NSXLBDetails -####################################################################################################################### -################## D E V E L O P E R R E A D Y I N F R A S T R U C T U R E F U N C T I O N S ################# - -Function Add-NetworkSegment { +Function Add-vRSLCMNtpServer { <# - .SYNOPSIS - The Add-NetworkSegment cmdlet creates an NSX segment. The cmdlet connects to SDDC Manager using the -server, - -user, and -password values: - - Validates that network connectivity and authentication is possible to SDDC Manager - - Validates that network connectivity and authentication is possible to NSX Manager - - Create the NSX segment if not already created in NSX Manager + .SYNOPSIS + Add an NTP Server for the vRealize Suite Lifecycle Manager appliance .DESCRIPTION - The Add-NetworkSegment cmdlet creates an NSX Segment - + The Add-vRSLCMNtpServer cmdlet configures the NTP Server details of the vRealize Suite Lifecycle Manager + appliance using one or more NTP servers passed as a parameter. The cmdlet connects to SDDC Manager using + the -server, -user, and -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to Management Domain vCenter Server + - Configures the vRealize Suite Lifecycle Manager appliance NTP configuration + .EXAMPLE - Add-NetworkSegment -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -segmentName sfo-w01-kub-seg01 -gatewayType Tier1 -connectedGateway sfo-w01-ec01-t1-gw01 -cidr 192.168.31.1/24 -transportZone overlay-tz-sfo-w01-nsx01.sfo.rainpole.io -segmentType Overlay - This example creates an overlay-backed NSX segment in the workload domain sfo-w01 + Add-vRSLCMNtpServer -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -ntpServer ntp.lax.rainpole.io -ntpServerDesc "VCF NTP Server 2" + This example configures the vRealize Suite Lifecycle Manager appliance managed by SDDC Manager sfo-vcf01.sfo.rainpole.io to add ntp.lax.rainpole.io to its list of NTP servers #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$segmentName, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$connectedGateway, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cidr, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$transportZone, - [Parameter (Mandatory = $true)] [ValidateSet("Tier0", "Tier1")] [String]$gatewayType, - [Parameter (Mandatory = $true)] [ValidateSet("Overlay", "VLAN")] [String]$segmentType + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ntpServer, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ntpServerDesc ) + $testNtp = Test-NtpServer -Server $ntpServer + if ($testNtp -eq $false) { + Write-Error "Unable to confirm NTP server $ntpServer is valid: PRE_VALIDATION_FAILED" + break + } + Try { if (Test-VCFConnection -server $server) { if (Test-VCFAuthentication -server $server -user $user -pass $pass) { - if (($vcfNsxtDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain)) { - if (Test-NSXTConnection -server $vcfNsxtDetails.fqdn) { - if (Test-NSXTAuthentication -server $vcfNsxtDetails.fqdn -user $vcfNsxtDetails.adminUser -pass $vcfNsxtDetails.adminPass) { - if (!(Get-NsxtSegment -name $segmentName)) { - if ($gatewayType -eq "Tier0") { $tierGatewayExists = Get-NsxtTier0Gateway -name $connectedGateway } - if ($gatewayType -eq "Tier1") { $tierGatewayExists = Get-NsxtTier1Gateway -name $connectedGateway } - if ($tierGatewayExists) { - $validateTransportZone = Get-NsxtTransportZone -Name $transportZone -ErrorAction SilentlyContinue - if ($validateTransportZone.display_name -eq $transportZone) { - if ($validateTransportZone.transport_type -ne $segmentType.ToUpper()){ - Write-Error "NSX Transport Zone $transportZone does not match the defined segment Type $segmentType in NSX Manager ($($vcfNsxtDetails.fqdn)): PRE_VALIDATION_FAILED" - Break - } + if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) { + if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + $vrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass + if (Test-vRSLCMConnection -server $vrslcmDetails.fqdn) { + $vmName = $vrslcmDetails.fqdn.Split(".")[0] + if (Test-vRSLCMAuthentication -server $vrslcmDetails.fqdn -user $vrslcmDetails.adminUser -pass $vrslcmDetails.adminPass) { + $vrslcmProductNtpServers = Get-vRSLCMProductNtpServer + if ($vrslcmProductNtpServers -match $ntpServer) { + Write-Warning "Adding NTP server ($ntpServer) to vRealize Suite Lifecycle Manager ($vmName) product NTP server list, already performed: SKIPPED" } else { - Write-Error "Unable to find NSX Transport Zone ($transportZone) in NSX Manager ($($vcfNsxtDetails.fqdn)): PRE_VALIDATION_FAILED" - Break + $addvRSLCMProductNtp = Add-vRSLCMProductNtpServer -ntpServer $ntpServer -ntpServerDesc $ntpServerDesc -ErrorAction SilentlyContinue + if ($addvRSLCMProductNtp -match $ntpServer) { + Write-Output "Adding NTP server ($ntpServer) to vRealize Suite Lifecycle Manager ($vmName) product NTP server list: SUCCESSFUL" + } + else { + Write-Error "Adding NTP server ($ntpServer) to vRealize Suite Lifecycle Manager ($vmName) product NTP server list: POST_VALIDATION_FAILED" + } } - New-NsxtSegment -name $segmentName -connectedGateway $connectedGateway -cidr $cidr -transportZone $transportZone -gatewayType $gatewayType -segmentType $segmentType | Out-Null - if (Get-NsxtSegment -name $segmentName) { - Write-Output "Creating $segmentType-backed NSX segment in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($segmentName): SUCCESSFUL" + $vRSLCMAppliancePreCheck = Get-vRSLCMProductNtpServer + if ($vRSLCMAppliancePreCheck -match $ntpServer) { + $vrslcmApplianceNtpConfig = Get-vRSLCMApplianceNtpConfig + if ($vrslcmApplianceNtpConfig.ntpServers -match $ntpServer) { + Write-Warning "Adding NTP server ($ntpServer) to vRealize Suite Lifecycle Manager ($vmName) appliance NTP configuration, already performed: SKIPPED" + } + else { + $addvRSLCMApplianceNtp = Add-vRSLCMApplianceNtpConfig -ntpServer $ntpServer -ErrorAction SilentlyContinue + if ($addvRSLCMApplianceNtp.ntpServers -match $ntpServer) { + Write-Output "Adding NTP server ($ntpServer) to vRealize Suite Lifecycle Manager ($vmName) appliance NTP configuration: SUCCESSFUL" + } + else { + Write-Error "Adding NTP server ($ntpServer) to vRealize Suite Lifecycle Manager ($vmName) appliance NTP configuration: POST_VALIDATION_FAILED" + } + } } else { - Write-Error "Creating $segmentType-backed NSX segment in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($segmentName): POST_VALIDATION_FAILED" + Write-Error "Adding NTP server ($ntpServer) to vRealize Suite Lifecycle Manager ($vmName) appliance NTP configuration: PRE_VALIDATION_FAILED" } } else { - Write-Error "Unable to find NSX $gatewayType Gateway $connectedGateway in NSX Manager ($($vcfNsxtDetails.fqdn)): PRE_VALIDATION_FAILED" + Write-Error "Unable to authenticate with vRealize Suite Lifecycle Manager ($vmName) appliance: PRE_VALIDATION_FAILED" } - } - else { - Write-Warning "Creating $segmentType-backed NSX segment in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($segmentName), already exists: SKIPPED" + Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue } } } @@ -2586,50 +2867,83 @@ Function Add-NetworkSegment { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-NetworkSegment +Export-ModuleMember -Function Add-vRSLCMNtpServer -Function Undo-NetworkSegment { +Function Set-vRSLCMDnsConfig { <# - .SYNOPSIS - The Undo-NetworkSegment cmdlet removes an NSX segment. The cmdlet connects to SDDC Manager using the -server, - -user, and -password values: - - Validates that network connectivity and authentication is possible to SDDC Manager - - Validates that network connectivity and authentication is possible to NSX Manager - - Removes the NSX segment if not already removed from NSX Manager + .SYNOPSIS + Configure DNS Server and/or DNS search domains on vRealize Suite Lifecycle Manager appliance .DESCRIPTION - The Undo-NetworkSegment cmdlet removes an NSX Segment from NSX Manager + The Set-vRSLCMDnsConfig cmdlet configures the DNS server and search domain details of the vRealize Suite + Lifecycle Manager appliance using one or more DNS servers and/or DNS search domains passed as a parameter. + The cmdlet connects to SDDC Manager using the -server, -user, and -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to Management Domain vCenter Server + - Configures the vRealize Suite Lifecycle Manager appliance DNS configuration .EXAMPLE - Undo-NetworkSegment -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -segmentName sfo-w01-kub-seg01 - This example removes an NSX segment from the NSX Manager of Workload Domain sfo-w01 + Set-vRSLCMDnsConfig -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -rootPass VMw@re1! -dnsServers "172.16.11.4 172.16.11.5" -dnsSearchDomains rainpole.io + This example configures the vRealize Suite Lifecycle Manager appliance managed by SDDC Manager sfo-vcf01.sfo.rainpole.io to use 172.16.11.4 and 172.16.11.5 as its DNS servers and rainpole.io as its search domain + + .EXAMPLE + Set-vRSLCMDnsConfig -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -rootPass VMw@re1! -dnsServers "172.16.11.4 172.16.11.5 172.17.11.4 172.17.11.5" -dnsSearchDomains "rainpole.io sfo.rainpole.io lax.rainpole.io" + This example configures the vRealize Suite Lifecycle Manager appliance managed by SDDC Manager sfo-vcf01.sfo.rainpole.io to use 172.16.11.4, 172.16.11.5, 172.17.11.4, and 172.17.11.5 as its DNS servers and rainpole.io, sfo.rainpole.io, and lax.rainpole.io as its DNS search domains #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$segmentName + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$dnsServers, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$dnsSearchDomains ) Try { if (Test-VCFConnection -server $server) { if (Test-VCFAuthentication -server $server -user $user -pass $pass) { - if (($vcfNsxtDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain)) { - if (Test-NSXTConnection -server $vcfNsxtDetails.fqdn) { - if (Test-NSXTAuthentication -server $vcfNsxtDetails.fqdn -user $vcfNsxtDetails.adminUser -pass $vcfNsxtDetails.adminPass) { - if (Get-NsxtSegment -name $segmentName) { - Remove-NsxtSegment -name $segmentName | Out-Null - if (!(Get-NsxtSegment -name $segmentName)) { - Write-Output "Removing NSX segment in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($segmentName): SUCCESSFUL" + if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) { + if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + $vrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass + if (Test-vRSLCMConnection -server $vrslcmDetails.fqdn) { + $vmName = $vrslcmDetails.fqdn.Split(".")[0] + if ((Get-VM -Name $vmName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue )) { + if ($dnsServers) { + $scriptCommand = "sed -i '/#DNS=/d' /etc/systemd/resolved.conf" + $output = Invoke-VMScript -VM $vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vrslcmDetails.rootPassword -Server $vcfVcenterDetails.fqdn + $scriptCommand = "sed -i '/^DNS=/c\DNS=$dnsServers' /etc/systemd/resolved.conf | systemctl restart systemd-resolved" + $output = Invoke-VMScript -VM $vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vrslcmDetails.rootPassword -Server $vcfVcenterDetails.fqdn + $scriptCommand = "cat /etc/systemd/resolved.conf" + $output = Invoke-VMScript -VM $vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vrslcmDetails.rootPassword -Server $vcfVcenterDetails.fqdn + if (($output.ScriptOutput).Contains("DNS=$dnsServers")) { + Write-Output "Configuring vRealize Suite Lifecycle Manager ($vmName) to use DNS Server(s) ($dnsServers): SUCCESSFUL" + } + else { + Write-Error "Configuring vRealize Suite Lifecycle Manager ($vmName) to use DNS Server(s) ($dnsServers): POST_VALIDATION_FAILED" + } + } + if ($dnsSearchDomains) { + if (($output.ScriptOutput).Contains("#Domains")) { + $scriptCommand = "sed -i '/#Domains=/c\Domains=$dnsSearchDomains' /etc/systemd/resolved.conf | systemctl restart systemd-resolved" + } else { + $scriptCommand = "sed -i '/^Domains=/c\Domains=$dnsSearchDomains' /etc/systemd/resolved.conf | systemctl restart systemd-resolved" + } + $output = Invoke-VMScript -VM $vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vrslcmDetails.rootPassword -Server $vcfVcenterDetails.fqdn + $scriptCommand = "cat /etc/systemd/resolved.conf" + $output = Invoke-VMScript -VM $vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vrslcmDetails.rootPassword -Server $vcfVcenterDetails.fqdn + if (($output.ScriptOutput).Contains("Domains=$dnsSearchDomains")) { + Write-Output "Configuring vRealize Suite Lifecycle Manager ($vmName) to use DNS search domain(s) ($dnsSearchDomains): SUCCESSFUL" + } + else { + Write-Error "Configuring vRealize Suite Lifecycle Manager ($vmName) to use DNS search domain(s) ($dnsSearchDomains): POST_VALIDATION_FAILED" + } + } } else { - Write-Error "Removing NSX segment in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($segmentName): POST_VALIDATION_FAILED" + Write-Error "Unable to locate a virtual machine named ($vmName) in vCenter Server ($($vcfVcenterDetails.fqdn)) inventory: PRE_VALIDATION_FAILED" } - } - else { - Write-Warning "Removing NSX segment in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($segmentName), does not exist: SKIPPED" + Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue } } } @@ -2641,64 +2955,91 @@ Function Undo-NetworkSegment { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Undo-NetworkSegment +Export-ModuleMember -Function Set-vRSLCMDnsConfig -Function Add-PrefixList { +Function Undo-vRSLCMNtpServer { <# - .SYNOPSIS - The Add-PrefixList cmdlet creates NSX Prefix List in the NSX Management Cluster. The cmdlet connects to SDDC - Manager using the -server, -user, and -password values: - - Validates that network connectivity and authentication is possible to SDDC Manager - - Validates that network connectivity and authentication is possible to NSX Manager - - Create an NSX Prefix List if not already created in NSX Manager + .SYNOPSIS + Set the NTP Server configuration of vRealize Suite Lifecycle Manager to match SDDC Manager .DESCRIPTION - The Add-PrefixList cmdlet creates an NSX Prefix List - + The Undo-vRSLCMNtpServer cmdlet sets the NTP Server details of the vRealize Suite Lifecycle Manager appliance + back to what is stored in SDDC Manager. The cmdlet connects to SDDC Manager using the -server, -user, and + -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to Management Domain vCenter Server + - Retrieves NTP server configuration from SDDC Manager + - Configures the vRealize Suite Lifecycle Manager to use only the values stored in SDDC Manager + .EXAMPLE - Add-PrefixList -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -tier0Gateway sfo-w01-ec01-t0-gw01 -prefixListName sfo-w01-ec01-t0-gw01-mgmt-prefixlist -subnetCIDR 192.168.20.0/24 -ingressSubnetCidr "192.168.21.0/24" -egressSubnetCidr "192.168.22.0/24" -GE "28" -LE "32" -action PERMIT - This example creates an NSX Prefix List in the workload domain NSX Management Cluster + Undo-vRSLCMNtpServer -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! + This example configures the vRealize Suite Lifecycle Manager appliance managed by SDDC Manager sfo-vcf01.sfo.rainpole.io to use only the NTP servers found in SDDC Manager #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tier0Gateway, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$prefixListName, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$subnetCidr, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ingressSubnetCidr, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$egressSubnetCidr, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$GE, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$LE, - [Parameter (Mandatory = $true)] [ValidateSet("PERMIT", "DENY")] [String]$action + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass ) Try { if (Test-VCFConnection -server $server) { if (Test-VCFAuthentication -server $server -user $user -pass $pass) { - if (($vcfNsxtDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain)) { - if (Test-NSXTConnection -server $vcfNsxtDetails.fqdn) { - if (Test-NSXTAuthentication -server $vcfNsxtDetails.fqdn -user $vcfNsxtDetails.adminUser -pass $vcfNsxtDetails.adminPass) { - if (Get-NsxtTier0Gateway -name $tier0Gateway) { - if (!(Get-NsxtTier0Gateway -name $tier0Gateway | Get-NsxtPrefixList -name $prefixListName -ErrorAction SilentlyContinue)) { - Get-NsxtTier0Gateway -name $tier0Gateway | New-NsxtPrefixList -name $prefixListName -subnetCidr $subnetCidr -action $action | Out-Null - if (Get-NsxtTier0Gateway -name $tier0Gateway | Get-NsxtPrefixList -name $prefixListName -ErrorAction SilentlyContinue) { - Get-NsxtTier0Gateway -name $tier0Gateway | Get-NsxtPrefixList -name $prefixListName | Add-NsxtPrefix -subnetCidr $ingressSubnetCidr -GE $GE -LE $LE -action $action | Out-Null - Get-NsxtTier0Gateway -name $tier0Gateway | Get-NsxtPrefixList -name $prefixListName | Add-NsxtPrefix -subnetCidr $egressSubnetCidr -GE $GE -LE $LE -action $action | Out-Null - Write-Output "Adding NSX IP Prefix List in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($prefixListName): SUCCESSFUL" + if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) { + $sddcManagerNtpServers = Get-VCFConfigurationNTP | Select-Object -ExpandProperty ipAddress + if ($sddcManagerNtpServers.count -gt 1) { + $sddcManagerNtpServers = $sddcManagerNtpServers -join "," + } + if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + $vrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass + if (Test-vRSLCMConnection -server $vrslcmDetails.fqdn) { + $vmName = $vrslcmDetails.fqdn.Split(".")[0] + if (Test-vRSLCMAuthentication -server $vrslcmDetails.fqdn -user $vrslcmDetails.adminUser -pass $vrslcmDetails.adminPass) { + $evaluatevRSLCMApplianceNtpConfig = Get-vRSLCMApplianceNtpConfig | Select-Object -ExpandProperty ntpServers + if ($evaluatevRSLCMApplianceNtpConfig -ne $sddcManagerNtpServers) { + Set-vRSLCMApplianceNtpConfig -ntpServer $sddcManagerNtpServers -ErrorAction SilentlyContinue | Out-Null + $validateApplianceNtpConfig = Get-vRSLCMApplianceNtpConfig | Select-Object -ExpandProperty ntpServers + if ($validateApplianceNtpConfig -eq $sddcManagerNtpServers) { + Write-Output "Restoring vRealize Suite Lifecycle Manager ($vmName) appliance NTP servers to SDDC Manager defaults: SUCCESSFUL" + } + else { + Write-Error "Restoring vRealize Suite Lifecycle Manager ($vmName) appliance NTP servers to SDDC Manager defaults: POST_VALIDATION_FAILED" + } } else { - Write-Error "Adding NSX IP Prefix List in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($prefixListName): POST_VALIDATION_FAILED" + Write-Warning "Restoring vRealize Suite Lifecycle Manager ($vmName) appliance NTP servers to SDDC Manager defaults: SKIPPED" + } + $sddcManagerNtpServers = $null + $currentProductNtpServers = Get-vRSLCMProductNtpServer | Select-Object -ExpandProperty hostName + $sddcManagerNtpServers = Get-VCFConfigurationNTP | Select-Object -ExpandProperty ipAddress + foreach ($currentProductNtpServer in $currentProductNtpServers) { + if ($sddcManagerNtpServers -notContains $currentProductNtpServer) { + Remove-vRSLCMProductNtpServer -ntpServer $currentProductNtpServer -ErrorAction SilentlyContinue | Out-Null + $removedvRSLCMProductNtpServer = 1 + } + } + if ($removedvRSLCMProductNtpServer -eq 1) { + $validateProductNtpServers = Get-vRSLCMProductNtpServer | Select-Object -ExpandProperty hostName + $validateProductNtpServerSuccess = 1 + foreach ($validateProductNtpServer in $validateProductNtpServers) { + if ($sddcManagerNtpServers -notContains $validateProductNtpServer) { + $validateProductNtpServerSuccess = 0 + Write-Error "Restoring vRealize Suite Lifecycle Manager ($vmName) product NTP servers to SDDC Manager defaults: POST_VALIDATION_FAILED" + } + } + if ($validateProductNtpServerSuccess -eq 1) { + Write-Output "Restoring vRealize Suite Lifecycle Manager ($vmName) product NTP servers to SDDC Manager defaults: SUCCESSFUL" + } + } + else { + Write-Warning "Restoring vRealize Suite Lifecycle Manager ($vmName) product NTP servers to SDDC Manager defaults: SKIPPED" } } else { - Write-Warning "Adding NSX IP Prefix List in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($prefixListName), already exists: SKIPPED" + Write-Error "Unable to authenticate with vRealize Suite Lifecycle Manager ($vmName) appliance: PRE_VALIDATION_FAILED" } - } - else { - Write-Error "Unable to find NSX Tier0 Gateway ($tier0Gateway) in NSX Manager ($($vcfNsxtDetails.fqdn)): PRE_VALIDATION_FAILED" + Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue } } } @@ -2710,57 +3051,68 @@ Function Add-PrefixList { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-PrefixList +Export-ModuleMember -Function Undo-vRSLCMNtpServer -Function Undo-PrefixList { +Function Undo-vRSLCMDnsConfig { <# - .SYNOPSIS - The Undo-PrefixList cmdlet removes the NSX Prefix List from NSX Manager. The cmdlet connects to SDDC Manager - using the -server, -user, and -password values: - - Validates that network connectivity and authentication is possible to SDDC Manager - - Validates that network connectivity and authentication is possible to NSX Manager - - Removes an NSX Prefix List if not already removed from NSX Manager + .SYNOPSIS + Sets the DNS Server and/or DNS search domains on vRealize Suite Lifecycle Manager to match SDDC Manager .DESCRIPTION - The Undo-PrefixList cmdlet removes an NSX Prefix List + The Undo-vRSLCMDnsConfig cmdlet configures the DNS server and search domain details of the vRealize Suite + Lifecycle Manager appliance to the values stored in SDDC Manager. The cmdlet connects to SDDC Manager using + the -server, -user, and -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to Management Domain vCenter Server + - Retrieves the DNS server and search domain values from SDDC Manager + - Configures the vRealize Suite Lifecycle Manager appliance DNS configuration to match the values retrieved from SDDC Manager .EXAMPLE - Undo-PrefixList -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -tier0Gateway sfo-w01-ec01-t0-gw01 -prefixListName sfo-w01-ec01-t0-gw01-mgmt-prefixlist - This example removes an NSX Prefix List in the Workload Domain NSX Management Cluster + Undo-vRSLCMDnsConfig -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! + This example configures the vRealize Suite Lifecycle Manager appliance managed by SDDC Manager sfo-vcf01.sfo.rainpole.io to use values for DNS servers and search domains to the values stored in SDDC Manager. #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tier0Gateway, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$prefixListName + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerRootPass ) Try { if (Test-VCFConnection -server $server) { if (Test-VCFAuthentication -server $server -user $user -pass $pass) { - if (($vcfNsxtDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain)) { - if (Test-NSXTConnection -server $vcfNsxtDetails.fqdn) { - if (Test-NSXTAuthentication -server $vcfNsxtDetails.fqdn -user $vcfNsxtDetails.adminUser -pass $vcfNsxtDetails.adminPass) { - if (Get-NsxtTier0Gateway -name $tier0Gateway) { - if (Get-NsxtTier0Gateway -name $tier0Gateway | Get-NsxtPrefixList -name $prefixListName -ErrorAction SilentlyContinue) { - Remove-NsxtPrefixList -name $prefixListName -tier0Gateway $tier0Gateway | Out-Null - if (!(Get-NsxtTier0Gateway -name $tier0Gateway | Get-NsxtPrefixList -name $prefixListName -ErrorAction SilentlyContinue)) { - Write-Output "Removing NSX IP Prefix List in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($prefixListName): SUCCESSFUL" + $sddcManagerInstance = Get-VCFManager + $sddcManagerVmName = $sddcManagerInstance.fqdn.Split(".")[0] + $sddcManagerDnsServers = Get-VCFConfigurationDNS | Select-Object -ExpandProperty ipAddress + if ($sddcManagerDnsServers.Count -gt 1) { + $sddcManagerDnsServers = $sddcManagerDnsServers -Join " " + } + if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) { + if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + $vrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass + if (Test-vRSLCMConnection -server $vrslcmDetails.fqdn) { + $vmName = $vrslcmDetails.fqdn.Split(".")[0] + if (Test-vRSLCMAuthentication -server $vrslcmDetails.fqdn -user $vrslcmDetails.adminUser -pass $vrslcmDetails.adminPass) { + $sddcManagerSearchDomains = Get-VCFDnsSearchDomain -sddcManagerVmName $sddcManagerVmName -sddcManagerRootPass $sddcManagerRootPass + if (!$sddcManagerDnsServers -or !$sddcManagerSearchDomains) { + Write-Error "Unable to undo DNS configuration on vRealize Suite Lifecycle Manager ($vmName) appliance: PRE_VALIDATION_FAILED" } else { - Write-Error "Removing NSX IP Prefix List in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($prefixListName): POST_VALIDATION_FAILED" + try { + Set-vRSLCMDnsConfig -server $server -user $user -pass $pass -dnsServers $sddcManagerDnsServers -dnsSearchDomains $sddcManagerSearchDomains + } + catch { + Write-Error "Unable to undo DNS configuration on vRealize Suite Lifecycle Manager ($vmName) appliance: POST_VALIDATION_FAILED" + } } } - else { - Write-Warning "Removing NSX IP Prefix List in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($prefixListName), does not exist: SKIPPED" - } } else { - Write-Error "Unable to find NSX Tier0 Gateway ($tier0Gateway) in NSX Manager ($($vcfNsxtDetails.fqdn)): PRE_VALIDATION_FAILED" + Write-Error "Unable to locate a virtual machine named ($sddcManagerVmName) in vCenter Server ($($vcfVcenterDetails.fqdn)) inventory: PRE_VALIDATION_FAILED" } + Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue } } } @@ -2771,67 +3123,107 @@ Function Undo-PrefixList { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Undo-PrefixList +Export-ModuleMember -Function Undo-vRSLCMDnsConfig -Function Add-RouteMap { +Function Set-WorkspaceOneDnsConfig { <# - .SYNOPSIS - The Add-RouteMap cmdlet creates NSX Prefix List in the NSX Management Cluster. The cmdlet connects to SDDC - Manager using the -server, -user, and -password values: - - Validates that network connectivity and authentication is possible to SDDC Manager - - Validates that network connectivity and authentication is possible to NSX Manager - - Create an NSX Route Map if not already created in NSX Manager + .SYNOPSIS + Sets the DNS server and/or DNS search domains for all Workspace ONE Access appliances .DESCRIPTION - The Add-RouteMap cmdlet creates an NSX Route Map + The Set-WorkspaceOneDnsConfig cmdlet configures the DNS server and search domain details of all Workspace ONE + Access appliances to the values stored in SDDC Manager. The cmdlet connects to SDDC Manager using the -server, + -user, and -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to Management Domain vCenter Server + - Configures the DNS configuration for all Workspace ONE Access appliances .EXAMPLE - Add-RouteMap -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -tier0Gateway sfo-w01-ec01-t0-gw01 -routeMapName sfo-w01-ec01-t0-gw01-routemap -prefixListName sfo-w01-ec01-t0-gw01-mgmt-prefixlist -action PERMIT -applyPolicy:$true - This example creates an NSX Route Map in workload domain sfo-w01 + Set-WorkspaceOneDnsConfig -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -dnsServers "172.16.11.4 172.16.11.5" -dnsSearchDomains "rainpole.io sfo.rainpole.io lax.rainpole.io" + This example configures all Workspace ONE Access appliances managed by SDDC Manager sfo-vcf01.sfo.rainpole.io to use 172.16.11.4 amd 172.16.11.5 as its DNS servers and rainpole.io, sfo.rainpole.io, and lax.rainpole.io as its DNS search domains #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tier0Gateway, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$routeMapName, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$prefixListName, - [Parameter (Mandatory = $true)] [ValidateSet("PERMIT", "DENY")][String]$action, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Bool]$applyPolicy + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$dnsServers, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$dnsSearchDomains ) Try { if (Test-VCFConnection -server $server) { if (Test-VCFAuthentication -server $server -user $user -pass $pass) { - if (($vcfNsxtDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain)) { - if (Test-NSXTConnection -server $vcfNsxtDetails.fqdn) { - if (Test-NSXTAuthentication -server $vcfNsxtDetails.fqdn -user $vcfNsxtDetails.adminUser -pass $vcfNsxtDetails.adminPass) { - if (Get-NsxtTier0Gateway -name $tier0Gateway) { - if (!(Get-NsxtRouteMap -tier0Gateway $tier0Gateway -name $routeMapName -ErrorAction SilentlyContinue)) { - if (Get-NsxtTier0Gateway -name $tier0Gateway | Get-NsxtPrefixList -name $prefixListName -ErrorAction SilentlyContinue) { - Get-NsxtTier0Gateway -name $tier0Gateway | New-NsxtRouteMap -name $routeMapName -prefixList $prefixListName -action $Action | Out-Null - if (Get-NsxtRouteMap -tier0Gateway $tier0Gateway -name $routeMapName -ErrorAction SilentlyContinue) { - if ($applyPolicy -eq $true) { - Get-NsxtRouteRedistributionPolicy -tier0Gateway $tier0Gateway | Set-NsxtRouteRedistributionPolicy -routeMap $routeMapName | Out-Null + if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) { + if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + $vcfVrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass + if (Test-vRSLCMAuthentication -server $vcfVrslcmDetails.fqdn -user $vcfVrslcmDetails.adminUser -pass $vcfVrslcmDetails.adminPass) { + try { + $newRequest = Stop-vRSLCMProductNode -environment globalenvironment -product vidm -ErrorAction Stop + } + catch { + Write-Error $_.Exception.Message + break + } + if ($newRequest) { + Write-Output "Powering off Workspace ONE Access appliances. This may take quite a while." + Start-Sleep 10 + Watch-vRSLCMRequest -vmid $($newRequest.requestId) | Out-Null + } + else { + Write-Error "Power off request of Workspace ONE Access failed, check the vRealize Suite Lifecycle Manager UI: POST_VALIDATION_FAILED" + } + $productVMs = Get-vRSLCMProductNode -environmentName globalenvironment -product vidm + foreach ($productVM in $productVMs) { + if ((Get-VM -Name $productVM.vmName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue )) { + if ($dnsServers) { + $existingDNS = Get-VMOvfProperty -vm (Get-VM -Name $productVM.vmName) | Where-Object {$_.Id -eq "DNS"} | Select-Object -ExpandProperty Value + if ($existingDNS -eq $dnsServers) { + Write-Warning "Configuring Workspace ONE Access appliance $($productVM.vmName) to use DNS Server(s) ($dnsServers) already done: SKIPPED" + } + else { + Set-VMOvfProperty -vm (Get-VM -Name $productVM.vmName) -properties @{"DNS"="$dnsServers"} | Out-Null + } + $validateDNS = Get-VMOvfProperty -vm (Get-VM -Name $productVM.vmName) | Where-Object {$_.Id -eq "DNS"} | Select-Object -ExpandProperty Value + if ($validateDNS -eq $dnsServers) { + Write-Output "Configuring Workspace ONE Access appliance $($productVM.vmName) to use DNS server(s) ($dnsServers): SUCCESSFUL" + } + else { + Write-Error "Configuring Workspace ONE Access appliance $($ProductVM.vmName) to use DNS server(s) ($dnsServers): POST_VALIDATION_FAILED" } - Write-Output "Adding NSX Route Map in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($routeMapName): SUCCESSFUL" } - else { - Write-Error "Adding NSX Route Map in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($routeMapName): POST_VALIDATION_FAILED" + if ($dnsSearchDomains) { + $existingSearchDomains = Get-VMOvfProperty -vm (Get-VM -Name $productVM.vmName) | Where-Object {$_.Id -eq "searchpath"} | Select-Object -ExpandProperty Value + if ($existingSearchDomains -eq $dnsSearchDomains) { + Write-Warning "Configuring Workspace ONE Access appliance $($productVM.vmName) to use DNS search domain(s) ($dnsSearchDomains) already done: SKIPPED" + } + else { + Set-VMOvfProperty -vm (Get-VM -Name $productVM.vmName) -properties @{"searchpath"="$dnsSearchDomains"} | Out-Null + } + $validateSearchDomains = Get-VMOvfProperty -vm (Get-VM -Name $productVM.vmName) | Where-Object {$_.Id -eq "searchpath"} | Select-Object -ExpandProperty Value + if ($validateSearchDomains -eq $dnsSearchDomains) { + Write-Output "Configuring Workspace ONE Access appliance $($productVM.vmName) to use DNS search domain(s) ($dnsSearchDomains): SUCCESSFUL" + } + else { + Write-Error "Configuring Workspace ONE Access appliance $($ProductVM.vmName) to use DNS search domain(s) ($dnsSearchDomains): POST_VALIDATION_FAILED" + } } } else { - Write-Error "Unable to find NSX Prefix List in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($prefixListName): PRE_VALIDATION_FAILED" + Write-Error "Unable to locate a virtual machine named $($productVM.vmName) in vCenter Server ($($vcfVcenterDetails.fqdn)) inventory: PRE_VALIDATION_FAILED" } } + $newRequest = Start-vRSLCMProductNode -environment globalenvironment -product vidm + if ($newRequest) { + Write-Output "Powering on Workspace ONE Access appliances and bringing up services. This may take quite a while." + Start-Sleep 10 + Watch-vRSLCMRequest -vmid $($newRequest.requestId) | Out-Null + } else { - Write-Warning "Adding NSX Route Map in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($routeMapName), already exists: SKIPPED" + Write-Error "Power on request of Workspace ONE Access appliance(s) failed, check the vRealize Suite Lifecycle Manager UI: POST_VALIDATION_FAILED" } - } - else { - Write-Error "Unable to find NSX Tier0 Gateway ($tier0Gateway) in NSX Manager ($($vcfNsxtDetails.fqdn)): PRE_VALIDATION_FAILED" + Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue } } } @@ -2843,57 +3235,67 @@ Function Add-RouteMap { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-RouteMap +Export-ModuleMember -Function Set-WorkspaceOneDnsConfig -Function Undo-RouteMap { +Function Undo-WorkspaceOneDnsConfig { <# - .SYNOPSIS - The Undo-RouteMap cmdlet removes NSX Route Map from the NSX Management Cluster. The cmdlet connects to SDDC - Manager using the -server, -user, and -password values: - - Validates that network connectivity and authentication is possible to SDDC Manager - - Validates that network connectivity and authentication is possible to NSX Manager - - Removes an NSX Route Map from NSX Manager + .SYNOPSIS + Sets the DNS Server and/or DNS search domains on Workspace ONE Access to match SDDC Manager .DESCRIPTION - The Undo-RouteMap cmdlet removes an NSX Route Map + The Undo-WorkspaceOneDnsConfig cmdlet configures the DNS server and search domain details of all Workspace + ONE Access appliances to the values stored in SDDC Manager. The cmdlet connects to SDDC Manager using the + -server, -user, and -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to Management Domain vCenter Server + - Retrieves the DNS server and search domain values from SDDC Manager + - Configures all Workspace ONE appliance DNS configuration to match the values retrieved from SDDC Manager .EXAMPLE - Undo-RouteMap -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -tier0Gateway sfo-w01-ec01-t0-gw01 -routeMapName sfo-w01-ec01-t0-gw01-routemap - This example removes an NSX Route Map in the workload domain sfo-w01 + Undo-WorkspaceOneDnsConfig -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -sddcManagerRootPass VMw@re1! + This example configures all Workspace ONE Access appliances managed by SDDC Manager sfo-vcf01.sfo.rainpole.io to use values for DNS servers and search domains to the values stored in SDDC Manager. #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tier0Gateway, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$routeMapName + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerRootPass ) Try { if (Test-VCFConnection -server $server) { if (Test-VCFAuthentication -server $server -user $user -pass $pass) { - if (($vcfNsxtDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain)) { - if (Test-NSXTConnection -server $vcfNsxtDetails.fqdn) { - if (Test-NSXTAuthentication -server $vcfNsxtDetails.fqdn -user $vcfNsxtDetails.adminUser -pass $vcfNsxtDetails.adminPass) { - if (Get-NsxtTier0Gateway -name $tier0Gateway) { - if (Get-NsxtRouteMap -tier0Gateway $tier0Gateway -name $routeMapName -ErrorAction SilentlyContinue) { - Remove-NsxtRouteMap -name $routeMapName -tier0Gateway $tier0Gateway | Out-Null - if (!(Get-NsxtRouteMap -tier0Gateway $tier0Gateway -name $routeMapName -ErrorAction SilentlyContinue)) { - Write-Output "Removing NSX Route Map in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($routeMapName): SUCCESSFUL" + $sddcManagerInstance = Get-VCFManager + $sddcManagerVmName = $sddcManagerInstance.fqdn.Split(".")[0] + $sddcManagerDnsServers = Get-VCFConfigurationDNS | Select-Object -ExpandProperty ipAddress + if ($sddcManagerDnsServers.Count -gt 1) { + $sddcManagerDnsServers = $sddcManagerDnsServers -Join "," + } + if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) { + if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + $vrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass + if (Test-vRSLCMConnection -server $vrslcmDetails.fqdn) { + if (Test-vRSLCMAuthentication -server $vrslcmDetails.fqdn -user $vrslcmDetails.adminUser -pass $vrslcmDetails.adminPass) { + $sddcManagerSearchDomains = Get-VCFDnsSearchDomain -sddcManagerVmName $sddcManagerVmName -sddcManagerRootPass $sddcManagerRootPass + if (!$sddcManagerDnsServers -or !$sddcManagerSearchDomains) { + Write-Error "Unable to undo DNS configuration on Workspace ONE Access ($vmName) appliance: PRE_VALIDATION_FAILED" } else { - Write-Error "Removing NSX Route Map in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($routeMapName): POST_VALIDATION_FAILED" + Try { + Set-WorkspaceOneDnsConfig -server $server -user $user -pass $pass -dnsServers $sddcManagerDnsServers -dnsSearchDomains $sddcManagerSearchDomains -ErrorAction Stop -WarningAction SilentlyContinue + } + Catch { + Write-Error $_.Exception.Message + } } } - else { - Write-Warning "Removing NSX Route Map in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($routeMapName), does not exist: SKIPPED" - } } else { - Write-Error "Unable to find NSX Tier0 Gateway ($tier0Gateway) in NSX Manager ($($vcfNsxtDetails.fqdn)): PRE_VALIDATION_FAILED" + Write-Error "Unable to locate a virtual machine named ($sddcManagerVmName) in vCenter Server ($($vcfVcenterDetails.fqdn)) inventory: PRE_VALIDATION_FAILED" } + Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue } } } @@ -2904,73 +3306,103 @@ Function Undo-RouteMap { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Undo-RouteMap +Export-ModuleMember -Function Undo-WorkspaceOneDnsConfig -Function Set-DatastoreTag { +Function Set-vROPSDnsConfig { <# - .SYNOPSIS - The Function Set-DatastoreTag cmdlet creates and applies a vSphere Tag to the primary datastore. The cmdlet - connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity and authentication is possible to SDDC Manager - - Validates that network connectivity and authentication is possible to vCenter Server - - Creates and applies a vSphere Tag to the primary datastore + .SYNOPSIS + Configure DNS Server and/or DNS search domains on vRealize Operations Manager appliance .DESCRIPTION - The Set-DatastoreTag cmdlet creates and applies a vSphere Tag to the primary datastore + The Set-vROPSDnsConfig cmdlet configures the DNS server and search domain details of all vRealize Operations + Manager analytics cluster appliances to the values passed as parameters. The cmdlet connects to SDDC Manager + using the -server, -user, and -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to Management Domain vCenter Server + - Configures all vRealize Operations Manager analytics cluster appliance DNS configuration to the values + passed to the function using -dnsServers and -dnsSearchDomains. .EXAMPLE - Set-DatastoreTag -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -tagName vsphere-with-tanzu-tag -tagCategoryName vsphere-with-tanzu-category - This example creates a new tag and assigns it to the primary datastore of Workload Domain sfo-w01 + Set-vROPSDnsConfig -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -environmentName xint-env -dnsServers "172.16.11.4 172.16.11.5" -dnsSearchDomains rainpole.io + This example configures the vRealize Operations Manager analytics cluster appliances managed by SDDC Manager sfo-vcf01.sfo.rainpole.io to use 172.16.11.4 and 172.16.11.5 as its DNS servers and rainpole.io as its search domain #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tagName, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tagCategoryName + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$environmentName, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$dnsServers, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$dnsSearchDomains ) Try { if (Test-VCFConnection -server $server) { if (Test-VCFAuthentication -server $server -user $user -pass $pass) { - if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) { - if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) { - if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { - if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { - $datastore = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }).clusters.id) }).primaryDatastoreName - if ($datastoreExist = Get-Datastore -Name $datastore -ErrorAction SilentlyContinue | Where-Object {$_.Name -eq $datastore}) { - if (!(Get-TagAssignment -Entity $datastoreExist.Name -Category $tagCategoryName -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue)) { - if (!(Get-TagCategory -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue | Where-Object { $_.Name -eq $tagCategoryName })) { - New-TagCategory -Name $tagCategoryName -EntityType Datastore -Server $vcfVcenterDetails.fqdn -Confirm:$false | Out-Null - } - if (!(Get-Tag -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue | Where-Object { $_.Name -eq $tagName })) { - New-Tag -Name $tagName -Category $tagCategoryName -Server $vcfVcenterDetails.fqdn -Confirm:$false | Out-Null - } - Get-Datastore -Name $Datastore -Server $vcfVcenterDetails.fqdn | New-TagAssignment -Tag $tagName -Server $vcfVcenterDetails.fqdn -Confirm:$false | Out-Null - if ((Get-TagAssignment -Entity $datastoreExist.Name -Category $tagCategoryName -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue)) { - Write-Output "Creating vSphere Tag ($tagName) and applying to datastore ($datastore) in vCenter Server ($($vcfVcenterDetails.fqdn)): SUCCESSFUL" + if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) { + if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + $vrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass + if (Test-vRSLCMAuthentication -server $vrslcmDetails.fqdn -user $vrslcmDetails.adminUser -pass $vrslcmDetails.adminPass) { + $vropsVMs = (Get-VCFvROPs).nodes.fqdn + $productVMs = (Get-vRSLCMProductNode -environmentName $environmentName -product vrops) + $vropsXregVMs = @() + foreach ($productVM in $productVMs) { + if ($vropsVMs -contains $productVM.hostName) { + $vropsXregVMs += $productVM + } + } + foreach ($vropsXregVM in $vropsXregVMs){ + $vropsRootPass = (Get-VCFCredential | Where-Object {$_.credentialType -eq "SSH" -and $_.resource.resourceType -eq "VROPS" -and $_.resource.resourceName -eq $vropsXregVM.hostName}).password + if ((Get-VM -Name $vropsXregVM.vmName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue )) { + if ($dnsServers) { + $scriptCommand = "sed -i '/#DNS=/d' /etc/systemd/resolved.conf" + $output = Invoke-VMScript -VM $vropsXregVM.vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vropsRootPass -Server $vcfVcenterDetails.fqdn + $scriptCommand = "sed -i '/^DNS=/c\DNS=$dnsServers' /etc/systemd/resolved.conf | systemctl restart systemd-resolved" + $output = Invoke-VMScript -VM $vropsXregVM.vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vropsRootPass -Server $vcfVcenterDetails.fqdn + $scriptCommand = "cat /etc/systemd/resolved.conf" + $output = Invoke-VMScript -VM $vropsXregVM.vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vropsRootPass -Server $vcfVcenterDetails.fqdn + if (($output.ScriptOutput).Contains("DNS=$dnsServers")) { + Write-Output "Configuring vRealize Operations Manager appliance ($($vropsXregVM.vmName)) to use DNS Server(s) ($dnsServers): SUCCESSFUL" + } + else { + Write-Error "Configuring vRealize Operations Manager appliance ($($vropsXregVM.vmName)) to use DNS Server(s) ($dnsServers): POST_VALIDATION_FAILED" + } } - else { - Write-Error "Creating vSphere Tag ($tagName) and applying to datastore ($datastore) in vCenter Server ($($vcfVcenterDetails.fqdn)): POST_VALIDATION_FAILED" + if ($dnsSearchDomains) { + $scriptCommand = "cat /etc/systemd/network/10-eth0.network" + $output = Invoke-VMScript -VM $vropsXregVM.vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vropsRootPass -Server $vcfVcenterDetails.fqdn + if (($output.ScriptOutput).Contains("Domains=")) { + $scriptCommand = "sed -i '/^Domains=/d' /etc/systemd/network/10-eth0.network | systemctl restart systemd-networkd" + $output = Invoke-VMScript -VM $vropsXregVM.vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vropsRootPass -Server $vcfVcenterDetails.fqdn + } + $scriptCommand = "cat /etc/systemd/resolved.conf" + $output = Invoke-VMScript -VM $vropsXregVM.vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vropsRootPass -Server $vcfVcenterDetails.fqdn + if (($output.ScriptOutput).Contains("#Domains")) { + $scriptCommand = "sed -i '/#Domains=/c\Domains=$dnsSearchDomains' /etc/systemd/resolved.conf | systemctl restart systemd-resolved" + } else { + $scriptCommand = "sed -i '/^Domains=/c\Domains=$dnsSearchDomains' /etc/systemd/resolved.conf | systemctl restart systemd-resolved" + } + $output = Invoke-VMScript -VM $vropsXregVM.vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vropsRootPass -Server $vcfVcenterDetails.fqdn + $scriptCommand = "cat /etc/systemd/resolved.conf" + $output = Invoke-VMScript -VM $vropsXregVM.vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vropsRootPass -Server $vcfVcenterDetails.fqdn + if (($output.ScriptOutput).Contains("Domains=$dnsSearchDomains")) { + Write-Output "Configuring vRealize Operations Manager appliance ($($vropsXregVM.vmName)) to use DNS search domain(s) ($dnsSearchDomains): SUCCESSFUL" + } + else { + Write-Error "Configuring vRealize Operations Manager appliance ($($vropsXregVM.vmName)) to use DNS search domain(s) ($dnsSearchDomains): POST_VALIDATION_FAILED" + } } } else { - Write-Warning "Creating vSphere Tag ($tagName) and applying to datastore ($datastore) in vCenter Server ($($vcfVcenterDetails.fqdn)), already exists: SKIPPED" + Write-Error "Unable to locate a virtual machine named ($($vropsXregVM.vmName)) in vCenter Server ($($vcfVcenterDetails.fqdn)) inventory: PRE_VALIDATION_FAILED" } - } - else { - Write-Error "Unable to find datastore ($datastore) in vCenter Server ($($vcfVcenterDetails.fqdn)): PRE_VALIDATION_FAILED" - } - } - Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue + } + Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue + } } } } - else { - Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" - } } } } @@ -2978,62 +3410,84 @@ Function Set-DatastoreTag { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Set-DatastoreTag +Export-ModuleMember -Function Set-vROPSDnsConfig -Function Undo-DatastoreTag { +Function Undo-vROPSDnsConfig { <# - .SYNOPSIS - The Function Undo-DatastoreTag cmdlet removes a vSphere Category and Tag. The cmdlet connects to SDDC Manager using the - -server, -user, and -password values: - - Validates that network connectivity and authentication is possible to SDDC Manager - - Validates that network connectivity and authentication is possible to vCenter Server - - Removes the vSphere Tag + .SYNOPSIS + Sets the DNS Server and/or DNS search domains on vRealize Operations Manager appliances to match SDDC Manager .DESCRIPTION - The Undo-DatastoreTag cmdlet removes the vSphere Tag + The Undo-vROPSDnsConfig cmdlet configures the DNS server and search domain details of vRealize Operations + Manager analytics cluster appliances to the values stored in SDDC Manager. The cmdlet connects to SDDC Manager + using the -server, -user, and -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to Management Domain vCenter Server + - Retrieves the DNS server and search domain values from SDDC Manager + - Configures vRealize Operations Manager analytics cluster appliance DNS configuration to match the values + retrieved from SDDC Manager .EXAMPLE - Undo-DatastoreTag -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -tagName vsphere-with-tanzu-tag -tagCategoryName vsphere-with-tanzu-category - This example removes the vSphere tag from the Workload Domain sfo-w01 vCenter Server + Undo-vROPSDnsConfig -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -sddcManagerRootPass VMw@re1! -environmentName xint-env + This example configures all vRealize Operations Manager analytics cluster appliances managed by SDDC Manager sfo-vcf01.sfo.rainpole.io to use values for DNS servers and search domains to the values stored in SDDC Manager. #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tagName, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tagCategoryName + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerRootPass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$environmentName ) Try { if (Test-VCFConnection -server $server) { if (Test-VCFAuthentication -server $server -user $user -pass $pass) { - if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) { - if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) { - if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { - if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { - if (Get-Tag -Server $vcfVcenterDetails.fqdn -ErrorAction Ignore | Where-Object { $_.Name -eq $tagName }) { - Remove-Tag -Tag $tagName -Server $vcfVcenterDetails.fqdn -Confirm:$false | Out-Null - Remove-TagCategory -Category $tagCategoryName -Server $vcfVcenterDetails.fqdn -Confirm:$false | Out-Null - if (!(Get-Tag -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue | Where-Object { $_.Name -eq $tagName })) { - Write-Output "Removing vSphere Tag ($tagName) and vSphere Category ($tagCategoryName) from vCenter Server ($($vcfVcenterDetails.fqdn)): SUCCESSFUL" + $sddcManagerInstance = Get-VCFManager + $sddcManagerVmName = $sddcManagerInstance.fqdn.Split(".")[0] + $sddcManagerDnsServers = Get-VCFConfigurationDNS | Select-Object -ExpandProperty ipAddress + if ($sddcManagerDnsServers.Count -gt 1) { + $sddcManagerDnsServers = $sddcManagerDnsServers -Join " " + } + if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) { + if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + $vrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass + if (Test-vRSLCMConnection -server $vrslcmDetails.fqdn) { + if (Test-vRSLCMAuthentication -server $vrslcmDetails.fqdn -user $vrslcmDetails.adminUser -pass $vrslcmDetails.adminPass) { + $vcfvROPSDetails = Get-VCFvROPS + if (Test-vROPSConnection -server $vcfVROPSDetails.loadBalancerFqdn) { + $sddcManagerSearchDomains = Get-VCFDnsSearchDomain -sddcManagerVmName $sddcManagerVmName -sddcManagerRootPass $sddcManagerRootPass + if (!$sddcManagerDnsServers -or !$sddcManagerSearchDomains) { + Write-Error "Unable to undo DNS configuration for vRealize Operations Manager analytics cluster appliances: PRE_VALIDATION_FAILED" + } + else { + try { + Set-vROPSDnsConfig -server $server -user $user -pass $pass -environmentName $environmentName -dnsServers $sddcManagerDnsServers -dnsSearchDomains $sddcManagerSearchDomains -ErrorAction Stop -WarningAction SilentlyContinue + } + catch { + Write-Error $_.Exception.Message + } + } } else { - Write-Error "Removing vSphere Tag ($tagName) and vSphere Category ($tagCategoryName) from vCenter Server ($($vcfVcenterDetails.fqdn)): POST_VALIDATION_FAILED" + Write-Error "Unable connect to vRealize Operations Manager: PRE_VALIDATION_FAILED" } } else { - Write-Warning "Removing vSphere Tag ($tagName) and Category ($tagCategoryName) from vCenter Server ($($vcfVcenterDetails.fqdn)), does not exist: SKIPPED" + Write-Error "Unable to authenticate with vRealize Suite Lifecycle Manager to retrieve vRealize Operations Manager analytics cluster appliances: PRE_VALIDATION_FAILED" } } - Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue + else { + Write-Error "Unable to connect to vRealize Suite Lifecycle Manager ($($vrslcmDetails.fqdn.Split(".")[0])): PRE_VALIDATION_FAILED" + } + Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue + } + else { + Write-Error "Unable to locate a virtual machine named ($sddcManagerVmName) in vCenter Server ($($vcfVcenterDetails.fqdn)) inventory: PRE_VALIDATION_FAILED" } } } - else { - Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" - } } } } @@ -3041,66 +3495,86 @@ Function Undo-DatastoreTag { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Undo-DatastoreTag +Export-ModuleMember -Function Undo-vROPSDnsConfig -Function Add-StoragePolicy { +Function Add-vROPSNtpServer { <# - .SYNOPSIS - The Add-StoragePolicy cmdlet creates a vSphere Storage Policy. The cmdlet connects to SDDC Manager using the - -server, -user, and -password values: - - Validates that network connectivity and authentication is possible to SDDC Manager - - Validates that network connectivity and authentication is possible to vCenter Server - - Creates a VM vSphere Storage Policy + .SYNOPSIS + Adds an NTP server to all vRealize Operations Manager appliances .DESCRIPTION - The Add-StoragePolicy cmdlet creates a VM vSphere Storage Policy + The Add-vROPSNtpServer cmdlet adds an NTP server to all vRealize Operations Manager appliances. The cmdlet + connects to SDDC Manager using the -server, -user, and -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to Management Domain vCenter Server + - Configures all vRealize Operations Manager appliances to use an additional NTP server defined using the value + passed to the function using -ntpServer. .EXAMPLE - Add-StoragePolicy -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -policyName vsphere-with-tanzu-storage-policy -tagName vsphere-with-tanzu-tag - This example creates a VM Storage Policy named vsphere-with-tanzu-policy in the Wrkload Domain vCenter Server + Add-vROPSNtpServer -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -environmentName xint-env -ntpServer ntp.lax.rainpole.io + This example configures the vRealize Operations Manager appliances managed by SDDC Manager sfo-vcf01.sfo.rainpole.io to add the NTP server ntp.lax.rainpole.io. #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$policyName, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tagName + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$environmentName, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ntpServer ) + $testNtp = Test-NtpServer -Server $ntpServer + if ($testNtp -eq $false) { + Write-Error "Unable to confirm NTP server $ntpServer is valid: PRE_VALIDATION_FAILED" + break + } + Try { if (Test-VCFConnection -server $server) { if (Test-VCFAuthentication -server $server -user $user -pass $pass) { - if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) { - if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) { - if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { - if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { - if (!(Get-SpbmStoragePolicy -Name $policyName -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue)) { - if (Get-Tag -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue | Where-Object { $_.Name -eq $tagName }) { - New-SpbmStoragePolicy -Name $policyName -AnyOfRuleSets (New-SpbmRuleSet -AllOfRules (New-SpbmRule -AnyOfTags $tagName -Server $vcfVcenterDetails.fqdn)) -Server $vcfVcenterDetails.fqdn | Out-Null - if (Get-SpbmStoragePolicy -Name $policyName -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue) { - Write-Output "Creating Storage Policy in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($policyName): SUCCESSFUL" - } - else { - Write-Error "Creating Storage Policy in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($policyName): POST_VALIDATION_FAILED" - } + if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) { + if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + $vrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass + if (Test-vRSLCMAuthentication -server $vrslcmDetails.fqdn -user $vrslcmDetails.adminUser -pass $vrslcmDetails.adminPass) { + $productVM = (Get-vRSLCMProductNode -environmentName $environmentName -product vrops)[0] + $vropsRootPass = (Get-VCFCredential | Where-Object {$_.credentialType -eq "SSH" -and $_.resource.resourceType -eq "VROPS" -and $_.resource.resourceName -eq $productVM.hostName}).password + if ((Get-VM -Name $productVM.vmName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue )) { + $scriptCommand = "python /usr/lib/vmware-casa/bin/ntp_list.py" + $output = Invoke-VMScript -VM $productVM.vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vropsRootPass -Server $vcfVcenterDetails.fqdn + $existingNtpServers = ($output.ScriptOutput | ConvertFrom-JSON).time_servers + $ntpServers = @() + foreach ($existingNtpServer in $existingNtpServers) { + $ntpServers += $existingNtpServer.address } - else { - Write-Error "Unable to find vSphere Tag ($tagName) in vCenter Server ($($vcfVcenterDetails.fqdn)): PRE_VALIDATION_FAILED" + $ntpServers += $ntpServer + $ntpServersJson = $ntpServers | ConvertTo-JSON + $ntpServersJson = $ntpServersJson -replace "`r`n","" -replace " ","" + $scriptCommand = "echo '$ntpServersJson' | python /usr/lib/vmware-casa/bin/ntp_update.py > /dev/null 2>&1" + $output = Invoke-VMScript -VM $productVM.vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vropsRootPass -Server $vcfVcenterDetails.fqdn + $scriptCommand = "python /usr/lib/vmware-casa/bin/ntp_list.py" + $output = Invoke-VMScript -VM $productVM.vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vropsRootPass -Server $vcfVcenterDetails.fqdn + $vropsNtpServers = ($output.ScriptOutput | ConvertFrom-JSON).time_servers + $vropsNtpServerArray = @() + foreach ($vropsNtpServer in $vropsNtpServers) { + $vropsNtpServerArray += $vropsNtpServer.address + } + $compareArrays = Compare-Object -ReferenceObject $ntpServers -DifferenceObject $vropsNtpServerArray + if (!$compareArrays) { + Write-Output "Configuring vRealize Operations Manager appliances to use NTP servers ($($ntpServers -Join ", ")): SUCCESSFUL" + } + else { + Write-Output "Unable to validate vRealize Operations Manager appliances were configured to use NTP servers ($($ntpServers -Join ", ")): POST_VALIDATION_FAILED" } } else { - Write-Warning "Creating Storage Policy in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($policyName), already exists: SKIPPED" - } - } - Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue + Write-Error "Unable to locate a virtual machine named ($($productVM.vmName)) in vCenter Server ($($vcfVcenterDetails.fqdn)) inventory: PRE_VALIDATION_FAILED" + } + Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue + } } } } - else { - Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" - } } } } @@ -3108,60 +3582,78 @@ Function Add-StoragePolicy { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-StoragePolicy +Export-ModuleMember -Function Add-vROPSNtpServer -Function Undo-StoragePolicy { +Function Undo-vROPSNtpServer { <# - .SYNOPSIS - The Undo-StoragePolicy cmdlet removes a vSphere Storage Policy. The cmdlet connects to SDDC Manager using the - -server, -user, and -password values: - - Validates that network connectivity and authentication is possible to SDDC Manager - - Validates that network connectivity and authentication is possible to vCenter Server - - Removes a VM vSphere Storage Policy + .SYNOPSIS + Configure NTP settings for all vRealize Operations Manager appliances to match SDDC Manager .DESCRIPTION - The Undo-StoragePolicy cmdlet removes a VM vSphere Storage Policy + The Undo-vROPSNtpServer cmdlet removes any added NTP server(s) to all vRealize Operations Manager appliances by + returning their configuration to match that of SDDC Manager. The cmdlet connects to SDDC Manager using the + -server, -user, and -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to Management Domain vCenter Server + - Configures all vRealize Operations Manager appliances to the use NTP server(s) defined in SDDC Manager. .EXAMPLE - Undo-StoragePolicy -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -policyName vsphere-with-tanzu-storage-policy - This example removes a VM Storage Policy named vsphere-with-tanzu-storage-policy from the Wrkload Domain vCenter Server + Undo-vROPSNtpServer -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -environmentName xint-env + This example configures the vRealize Operations Manager appliances managed by SDDC Manager sfo-vcf01.sfo.rainpole.io to use the NTP server(s) defined in SDDC Manager. #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$policyName + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$environmentName ) Try { if (Test-VCFConnection -server $server) { if (Test-VCFAuthentication -server $server -user $user -pass $pass) { - if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) { - if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) { - if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { - if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { - if (Get-SpbmStoragePolicy -Name $policyName -Server $vcfVcenterDetails.fqdn -ErrorAction Ignore) { - Remove-SpbmStoragePolicy -StoragePolicy $policyName -Server $vcfVcenterDetails.fqdn -Confirm:$false | Out-Null - if (!(Get-SpbmStoragePolicy -Name $policyName -Server $vcfVcenterDetails.fqdn -ErrorAction Ignore)) { - Write-Output "Removing Storage Policy in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($policyName): SUCCESSFUL" + if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) { + if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + $vrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass + if (Test-vRSLCMAuthentication -server $vrslcmDetails.fqdn -user $vrslcmDetails.adminUser -pass $vrslcmDetails.adminPass) { + $productVM = (Get-vRSLCMProductNode -environmentName $environmentName -product vrops)[0] + $vropsRootPass = (Get-VCFCredential | Where-Object {$_.credentialType -eq "SSH" -and $_.resource.resourceType -eq "VROPS" -and $_.resource.resourceName -eq $productVM.hostName}).password + if ((Get-VM -Name $productVM.vmName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue )) { + $ntpServers = (Get-VCFConfigurationNTP).ipAddress + if ($ntpServers.count -eq 1) { + $ntpServersJson = $ntpServers | ConvertTo-JSON + $ntpServersJson = "[$ntpServersJson]" } else { - Write-Error "Removing Storage Policy in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($policyName): POST_VALIDATION_FAILED" + $ntpServersJson = $ntpServers | ConvertTo-JSON + $ntpServersJson = $ntpServersJson -replace "`r`n","" -replace " ","" + } + $scriptCommand = "echo '$ntpServersJson' | python /usr/lib/vmware-casa/bin/ntp_update.py > /dev/null 2>&1" + $output = Invoke-VMScript -VM $productVM.vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vropsRootPass -Server $vcfVcenterDetails.fqdn + $scriptCommand = "python /usr/lib/vmware-casa/bin/ntp_list.py" + $output = Invoke-VMScript -VM $productVM.vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vropsRootPass -Server $vcfVcenterDetails.fqdn + $vropsNtpServers = ($output.ScriptOutput | ConvertFrom-JSON).time_servers + $vropsNtpServerArray = @() + foreach ($vropsNtpServer in $vropsNtpServers) { + $vropsNtpServerArray += $vropsNtpServer.address + } + $compareArrays = Compare-Object -ReferenceObject $ntpServers -DifferenceObject $vropsNtpServerArray + if (!$compareArrays) { + Write-Output "Configuring vRealize Operations Manager appliances to use NTP servers ($($ntpServers -Join ", ")): SUCCESSFUL" + } + else { + Write-Output "Unable to validate vRealize Operations Manager appliances were configured to use NTP servers ($($ntpServers -Join ", ")): POST_VALIDATION_FAILED" } } else { - Write-Warning "Removing Storage Policy in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($policyName), does not exist: SKIPPED" - } - } - Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue + Write-Error "Unable to locate a virtual machine named ($($productVM.vmName)) in vCenter Server ($($vcfVcenterDetails.fqdn)) inventory: PRE_VALIDATION_FAILED" + } + Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue + } } } } - else { - Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" - } } } } @@ -3169,27 +3661,26 @@ Function Undo-StoragePolicy { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Undo-StoragePolicy +Export-ModuleMember -Function Undo-vROPSNtpServer -Function Add-ContentLibrary { +####################################################################################################################### +################## D E V E L O P E R R E A D Y I N F R A S T R U C T U R E F U N C T I O N S ################# + +Function Add-NetworkSegment { <# .SYNOPSIS - Creates a subscribed content library - + The Add-NetworkSegment cmdlet creates an NSX segment. The cmdlet connects to SDDC Manager using the -server, + -user, and -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to NSX Manager + - Create the NSX segment if not already created in NSX Manager + .DESCRIPTION - The Add-ContentLibrary cmdlet creates a subscribed content library - - .EXAMPLE - Add-ContentLibrary -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -contentLibraryName sfo-w01-lib01 -published - This example creates published content library named sfo-w01-lib01 on the primary datastore in workload domain sfo-w01 - - .EXAMPLE - Add-ContentLibrary -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -contentLibraryName sfo-w01-lib01 -datastore sfo-w01-ds-nfs01 -published - This example creates published content library named sfo-w01-lib01 on a specific datastore in workload domain sfo-w01 - + The Add-NetworkSegment cmdlet creates an NSX Segment + .EXAMPLE - Add-ContentLibrary -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -contentLibraryName Kubernetes -subscriptionUrl "https://wp-content.vmware.com/v2/latest/lib.json" - This example creates subscribed content library named Kubernetes on the primary datastore in workload domain sfo-w01 + Add-NetworkSegment -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -segmentName sfo-w01-kub-seg01 -gatewayType Tier1 -connectedGateway sfo-w01-ec01-t1-gw01 -cidr 192.168.31.1/24 -transportZone overlay-tz-sfo-w01-nsx01.sfo.rainpole.io -segmentType Overlay + This example creates an overlay-backed NSX segment in the workload domain sfo-w01 #> Param ( @@ -3197,67 +3688,53 @@ Function Add-ContentLibrary { [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$contentLibraryName, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$datastore, - [Parameter (ParameterSetName = 'Subscription', Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$subscriptionUrl, - [Parameter (ParameterSetName = 'Local', Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$published + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$segmentName, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$connectedGateway, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cidr, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$transportZone, + [Parameter (Mandatory = $true)] [ValidateSet("Tier0", "Tier1")] [String]$gatewayType, + [Parameter (Mandatory = $true)] [ValidateSet("Overlay", "VLAN")] [String]$segmentType ) Try { if (Test-VCFConnection -server $server) { if (Test-VCFAuthentication -server $server -user $user -pass $pass) { - if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) { - if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) { - if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { - if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { - if (!(Get-ContentLibrary -Name $contentLibraryName -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue)) { - if (!$PsBoundParameters.ContainsKey('datastore')) { - $datastore = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }).clusters.id) }).primaryDatastoreName - } - if (Get-Datastore -Name $datastore -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue | Where-Object {$_.Name -eq $datastore}) { - if ($subscriptionUrl) { - #attribution to William Lam (https://gist.github.com/lamw/988e4599c0f88d9fc25c9f2af8b72c92) for this snippet - Invoke-RestMethod -Uri $subscriptionUrl -Method Get | Out-Null - - $endpointRequest = [System.Net.Webrequest]::Create("$subscriptionUrl") - $sslThumbprint = $endpointRequest.ServicePoint.Certificate.GetCertHashString() - $sslThumbprint = $sslThumbprint -replace '(..(?!$))', '$1:' - - $contentLibraryInput = @{ - Name = $contentLibraryName - Datastore = $datastore - AutomaticSync = $true - SubscriptionUrl = $subscriptionUrl - SslThumbprint = $sslThumbprint - } - - New-ContentLibrary @contentLibraryInput -Server $vcfVcenterDetails.fqdn | Out-Null - } - elseif ($published) { - New-ContentLibrary -Name $contentLibraryName -Published -Datastore $datastore -Server $vcfVcenterDetails.fqdn | Out-Null - } - if (Get-ContentLibrary -Name $contentLibraryName -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue) { - Write-Output "Creating Content Library in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($contentLibraryName): SUCCESSFUL" - } - else { - Write-Error "Creating Content Library in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($contentLibraryName): POST_VALIDATION_FAILED" + if (($vcfNsxtDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain)) { + if (Test-NSXTConnection -server $vcfNsxtDetails.fqdn) { + if (Test-NSXTAuthentication -server $vcfNsxtDetails.fqdn -user $vcfNsxtDetails.adminUser -pass $vcfNsxtDetails.adminPass) { + if (!(Get-NsxtSegment -name $segmentName)) { + if ($gatewayType -eq "Tier0") { $tierGatewayExists = Get-NsxtTier0Gateway -name $connectedGateway } + if ($gatewayType -eq "Tier1") { $tierGatewayExists = Get-NsxtTier1Gateway -name $connectedGateway } + if ($tierGatewayExists) { + $validateTransportZone = Get-NsxtTransportZone -Name $transportZone -ErrorAction SilentlyContinue + if ($validateTransportZone.display_name -eq $transportZone) { + if ($validateTransportZone.transport_type -ne $segmentType.ToUpper()){ + Write-Error "NSX Transport Zone $transportZone does not match the defined segment Type $segmentType in NSX Manager ($($vcfNsxtDetails.fqdn)): PRE_VALIDATION_FAILED" + Break } } else { - Write-Error "Unable to find Datastore named ($datastore) in vCenter Server ($($vcfVcenterDetails.fqdn)): PRE_VALIDATION_FAILED" + Write-Error "Unable to find NSX Transport Zone ($transportZone) in NSX Manager ($($vcfNsxtDetails.fqdn)): PRE_VALIDATION_FAILED" + Break + } + New-NsxtSegment -name $segmentName -connectedGateway $connectedGateway -cidr $cidr -transportZone $transportZone -gatewayType $gatewayType -segmentType $segmentType | Out-Null + if (Get-NsxtSegment -name $segmentName) { + Write-Output "Creating $segmentType-backed NSX segment in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($segmentName): SUCCESSFUL" + } + else { + Write-Error "Creating $segmentType-backed NSX segment in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($segmentName): POST_VALIDATION_FAILED" } } else { - Write-Warning "Creating Content Library in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($contentLibraryName), already exists: SKIPPED" + Write-Error "Unable to find NSX $gatewayType Gateway $connectedGateway in NSX Manager ($($vcfNsxtDetails.fqdn)): PRE_VALIDATION_FAILED" } } - Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue + else { + Write-Warning "Creating $segmentType-backed NSX segment in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($segmentName), already exists: SKIPPED" + } } } } - else { - Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" - } } } } @@ -3265,19 +3742,23 @@ Function Add-ContentLibrary { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-ContentLibrary +Export-ModuleMember -Function Add-NetworkSegment -Function Undo-ContentLibrary { +Function Undo-NetworkSegment { <# .SYNOPSIS - Remove Content Library + The Undo-NetworkSegment cmdlet removes an NSX segment. The cmdlet connects to SDDC Manager using the -server, + -user, and -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to NSX Manager + - Removes the NSX segment if not already removed from NSX Manager .DESCRIPTION - The Undo-ContentLibrary cmdlet removes a content library + The Undo-NetworkSegment cmdlet removes an NSX Segment from NSX Manager .EXAMPLE - Undo-ContentLibrary -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -contentLibraryName sfo-w01-lib01 - This example removes the content library from the Workload Domain vCenter Server + Undo-NetworkSegment -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -segmentName sfo-w01-kub-seg01 + This example removes an NSX segment from the NSX Manager of Workload Domain sfo-w01 #> Param ( @@ -3285,36 +3766,30 @@ Function Undo-ContentLibrary { [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$contentLibraryName + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$segmentName ) Try { if (Test-VCFConnection -server $server) { if (Test-VCFAuthentication -server $server -user $user -pass $pass) { - if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) { - if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) { - if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { - if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { - if (Get-ContentLibrary -Name $contentLibraryName -ErrorAction Ignore) { - Remove-ContentLibrary -ContentLibrary $contentLibraryName -Server $vcfVcenterDetails.fqdn -Confirm:$false | Out-Null - if (!(Get-ContentLibrary -Name $contentLibraryName -ErrorAction Ignore)) { - Write-Output "Removing Content Library from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($contentLibraryName): SUCCESSFUL" - } - else { - Write-Error "Removing Content Library from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($contentLibraryName): POST_VALIDATION_FAILED" - } + if (($vcfNsxtDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain)) { + if (Test-NSXTConnection -server $vcfNsxtDetails.fqdn) { + if (Test-NSXTAuthentication -server $vcfNsxtDetails.fqdn -user $vcfNsxtDetails.adminUser -pass $vcfNsxtDetails.adminPass) { + if (Get-NsxtSegment -name $segmentName) { + Remove-NsxtSegment -name $segmentName | Out-Null + if (!(Get-NsxtSegment -name $segmentName)) { + Write-Output "Removing NSX segment in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($segmentName): SUCCESSFUL" } else { - Write-Warning "Removing Content Library from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($contentLibraryName), does not exist: SKIPPED" + Write-Error "Removing NSX segment in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($segmentName): POST_VALIDATION_FAILED" } } - Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue + else { + Write-Warning "Removing NSX segment in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($segmentName), does not exist: SKIPPED" + } } } } - else { - Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" - } } } } @@ -3322,53 +3797,23 @@ Function Undo-ContentLibrary { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Undo-ContentLibrary +Export-ModuleMember -Function Undo-NetworkSegment -Function Enable-SupervisorCluster { +Function Add-PrefixList { <# .SYNOPSIS - Enables Workload Management on a VCF cluster + The Add-PrefixList cmdlet creates NSX Prefix List in the NSX Management Cluster. The cmdlet connects to SDDC + Manager using the -server, -user, and -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to NSX Manager + - Create an NSX Prefix List if not already created in NSX Manager .DESCRIPTION - The Enable-SupervisorCluster cmdlet enables Workload Management on a VCF cluster - - .EXAMPLE - $wmClusterInput = @{ - server = "sfo-vcf01.sfo.rainpole.io" - user = "administrator@vsphere.local" - pass = 'VMw@re1!' - domain = "sfo-w01" - cluster = "sfo-w01-cl01" - sizeHint = "Tiny" - managementVirtualNetwork = "sfo-w01-kub-seg01" - managementNetworkMode = "StaticRange" - managementNetworkStartIpAddress = "192.168.20.10" - managementNetworkAddressRangeSize = 5 - managementNetworkGateway = "192.168.20.1" - managementNetworkSubnetMask = "255.255.255.0" - masterDnsName = "sfo-w01-cl01.sfo.rainpole.io" - masterDnsServers = @("172.16.11.4", "172.16.11.5") - masterNtpServers = @("172.16.11.253", "172.16.12.253") - contentLibrary = "Kubernetes" - ephemeralStoragePolicy = "vsphere-with-tanzu-policy" - imageStoragePolicy = "vsphere-with-tanzu-policy" - masterStoragePolicy = "vsphere-with-tanzu-policy" - nsxEdgeCluster = "sfo-w01-ec01" - distributedSwitch = "sfo-w01-cl01-vds01" - podCIDRs = "100.100.0.0/20" - serviceCIDR = "100.200.0.0/22" - externalIngressCIDRs = "192.168.21.0/24" - externalEgressCIDRs = "192.168.22.0/24" - workerDnsServers = @("172.16.11.4", "172.16.11.5") - masterDnsSearchDomain = "sfo.rainpole.io" - } + The Add-PrefixList cmdlet creates an NSX Prefix List - Enable-SupervisorCluster @wmClusterInput -RunAsync - This example enables Workload Management on a vSphere Cluster in workload domain sfo-w01 in async mode - .EXAMPLE - Enable-SupervisorCluster -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -sizeHint Tiny -managementVirtualNetwork sfo-w01-kub-seg01 -managementNetworkMode StaticRange -managementNetworkStartIpAddress 192.168.20.10 -managementNetworkAddressRangeSize 5 -managementNetworkGateway 192.168.20.1 -managementNetworkSubnetMask 255.255.255.0 -cluster sfo-w01-cl01 -contentLibrary Kubernetes -ephemeralStoragePolicy vsphere-with-tanzu-storage-policy -imageStoragePolicy vsphere-with-tanzu-storage-policy -masterStoragePolicy vsphere-with-tanzu-storage-policy -nsxEdgeCluster sfo-w01-ec01 -distributedSwitch sfo-w01-sfo-w01-vc01-sfo-w01-cl01-vds01 -podCIDRs "100.100.0.0/20" -serviceCIDR "100.200.0.0/22" -externalIngressCIDRs "192.168.21.0/24" -externalEgressCIDRs "192.168.22.0/24" -masterNtpServers @("172.16.11.253", "172.16.12.253") -masterDnsServers @("172.16.11.4", "172.16.11.5") -masterDnsName sfo-w01-cl01.sfo.rainpole.io -masterDnsSearchDomain sfo.rainpole.io -workerDnsServers @("172.16.11.4", "172.16.11.5") - This example enables Workload Management on a vSphere Cluster in workload domain sfo-w01 + Add-PrefixList -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -tier0Gateway sfo-w01-ec01-t0-gw01 -prefixListName sfo-w01-ec01-t0-gw01-mgmt-prefixlist -subnetCIDR 192.168.20.0/24 -ingressSubnetCidr "192.168.21.0/24" -egressSubnetCidr "192.168.22.0/24" -GE "28" -LE "32" -action PERMIT + This example creates an NSX Prefix List in the workload domain NSX Management Cluster #> Param ( @@ -3376,523 +3821,40 @@ Function Enable-SupervisorCluster { [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster, - [Parameter (Mandatory = $true)] [ValidateSet("Tiny", "Small", "Medium", "Large")] [String]$sizeHint, - [Parameter (Mandatory = $true)] [ValidateSet("DHCP", "StaticRange")][String]$managementNetworkMode, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$managementVirtualNetwork, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$managementNetworkStartIpAddress, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$managementNetworkAddressRangeSize, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$managementNetworkGateway, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$managementNetworkSubnetMask, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [string]$masterDnsName, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Array]$masterNtpServers, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Array]$masterDnsServers, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$contentLibrary, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ephemeralStoragePolicy, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$imageStoragePolicy, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$masterStoragePolicy, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$nsxEdgeCluster, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$distributedSwitch, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$podCIDRs, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$serviceCIDR, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$externalIngressCIDRs, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$externalEgressCIDRs, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$masterDnsSearchDomain, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Array]$workerDnsServers, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$RunAsync, - [Parameter (Mandatory = $false)] [ValidateSet("true", "false")] [Bool]$SkipValidation, - [Parameter (Mandatory = $false)] [ValidateSet("true", "false")] [Bool]$ValidateOnly + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tier0Gateway, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$prefixListName, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$subnetCidr, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ingressSubnetCidr, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$egressSubnetCidr, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$GE, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$LE, + [Parameter (Mandatory = $true)] [ValidateSet("PERMIT", "DENY")] [String]$action ) Try { if (Test-VCFConnection -server $server) { if (Test-VCFAuthentication -server $server -user $user -pass $pass) { - if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) { - if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { - if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { - Request-vSphereApiToken -Fqdn $vcfVcenterDetails.fqdn -Username $vcfVcenterDetails.ssoadmin -Password $vcfVcenterDetails.ssoAdminPass | Out-Null - if (($vcfNsxtDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain)) { - if (Test-NSXTConnection -server $vcfNsxtDetails.fqdn) { - if (Test-NSXTAuthentication -server $vcfNsxtDetails.fqdn -user $vcfNsxtDetails.adminUser -pass $vcfNsxtDetails.adminPass) { - if (!(Get-WMCluster -cluster $cluster -ErrorAction SilentlyContinue)) { - if ($SkipValidation -eq $false -or !$SkipValidation) { - # Valid Starting IP Address is an actual IPv4 address - Do { - $checkManagementNetworkStartIpAddress = [IPAddress]$managementNetworkStartIpAddress - if ($checkManagementNetworkStartIpAddress.IPAddressToString -ne $managementNetworkStartIpAddress -or !$checkManagementNetworkStartIpAddress) { - Do { - $managementNetworkStartIpAddress = Read-Host "Invalid Management Network Start IP Address ($managementNetworkStartIpAddress). Please enter the correct IPv4 address (e.g., 192.168.20.10) and press Enter" - } Until ($managementNetworkStartIpAddress -ne [String]::Empty) - } - } Until ($checkManagementNetworkStartIpAddress.IPAddressToString -eq $managementNetworkStartIpAddress) - - # At least 5 in the range - Do { - if ($managementNetworkAddressRangeSize -lt 5) { - Do { - $managementNetworkAddressRangeSize = Read-Host "Invalid setting for Management Network Address Range Size. Type a new value (at least 5) and press Enter" - } Until ($managementNetworkAddressRangeSize -ne [string]::Empty -and $managementNetworkAddressRangeSize -match '^\d+$') - } - } Until ($managementNetworkAddressRangeSize -ge 5) - - # Valid Subnet Mask - Do { - $checkManagementNetworkSubnetMask = $null - if ($managementNetworkSubnetMask) { - Do { - if ($isWindows -or $PSEdition -eq "Desktop") { - $managementNetworkSubnetMaskSplit = $managementNetworkSubnetMask.Split('\.') - } - elseif ($isMacOS -or $isLinux) { - $managementNetworkSubnetMaskSplit = $managementNetworkSubnetMask.Split(".") - } - if ($managementNetworkSubnetMaskSplit.Length -ne 4) { - Do { - $managementNetworkSubnetMask = Read-Host "Management Network Subnet Mask ($managementNetworkSubnetMask) validation failed. Please enter a valid subnet mask (e.g., 255.255.255.0) and press Enter" - } Until ($managementNetworkSubnetMask -ne [String]::Empty) - } - } Until ($managementNetworkSubnetMaskSplit.Length -eq 4) - } - - $checkManagementNetworkSubnetMask = [IPAddress] $managementNetworkSubnetMask - if ($checkManagementNetworkSubnetMask) { - $getManagementNetworkCidr = New-Object -TypeName Text.StringBuilder - $lastOctet = 255 - $subnetFormatValidated = $null - $validSubnetMaskRegex = '^(0|128|192|224|240|248|252|254|255)$' - $getSubnetMaskInBytes = $checkManagementNetworkSubnetMask.GetAddressBytes() - - for ($i = 0;$i -lt $getSubnetMaskInBytes.length; $i++) { - if ($getSubnetMaskInBytes[$i] -notmatch $validSubnetMaskRegex) { - $subnetFormatValidated = $false - } - [void]$getManagementNetworkCidr.Append([Convert]::ToString($getSubnetMaskInBytes[$i],2)) - $lastOctet=$getSubnetMaskInBytes[$i] - } - $managementNetworkCidr = ($getManagementNetworkCidr.ToString().TrimEnd('0')).Length - } - - if ($subnetFormatValidated -eq $false -or !$checkManagementNetworkSubnetMask) { - Do { - $managementNetworkSubnetMask = Read-Host "Management Network Subnet Mask validation failed. Please enter a valid subnet mask (e.g., 255.255.255.0) and press Enter" - } Until ($managementNetworkSubnetMask -ne [String]::Empty) - } - } Until ($checkManagementNetworkSubnetMask.IPAddressToString -eq $managementNetworkSubnetMask -and $subnetFormatValidated -ne $false) - - # Validate Gateway IP Address is an actual IPv4 address and exists in the same subnet as the management starting address - Do { - $checkManagementNetworkGateway = [IPAddress]$managementNetworkGateway - if ($checkManagementNetworkGateway.IPAddressToString -ne $managementNetworkGateway -or !$checkManagementNetworkGateway) { - $managementNetworkGateway = Read-Host "Invalid Management Network Gateway Address ($managementNetworkGateway). Please enter the correct IPv4 address (e.g., 192.168.20.1) and press Enter" - } - - # Validate the Gateway IP address and the starting IP address are in the same subnet - $checkManagementNetworkGatewayInSubnet = $null - $checkManagementNetworkGatewayInSubnet = Test-IpAddress -IpAddress $managementNetworkGateway -Subnet "$managementNetworkStartIpAddress/$managementNetworkCidr" - if ($checkManagementNetworkGatewayInSubnet.Validated -eq $false) { - Do { - $managementNetworkGateway = Read-Host "Cannot validate the gateway IP address for the Management Network ($managementNetworkGateway) is from the same subnet as the Management Network Starting IP Address ($managementNetworkStartIpAddress/$managementNetworkCidr). Please enter a valid IPv4 address (e.g., 192.168.20.1) and press Enter" - $checkAlteredManagementNetworkGatewayFormat = [IPAddress]$managementNetworkGateway - } Until ($managementNetworkGateway -ne [String]::Empty -and $checkAlteredManagementNetworkGatewayFormat.IpAddressToString -eq $managementNetworkGateway) - } - } Until ($checkManagementNetworkGatewayInSubnet.Validated -eq $True) - - # Validate Management Virtual Network (dvPortGroup) exists - Do { - $checkManagementVirtualNetwork = Get-VirtualNetwork -Name $ManagementVirtualNetwork -ErrorAction SilentlyContinue - if (!$checkManagementVirtualNetwork -or !$managementVirtualNetwork) { - $managementVirtualNetwork = Read-Host "Invalid Management Virtual Network ($ManagementVirtualNetwork). Please enter the correct name and press Enter" - } - } Until ($checkManagementVirtualNetwork.Name -eq $managementVirtualNetwork) - - # Validate Ephemeral Storage Policy exists - Do { - $checkEphemeralStoragePolicy = $null - $checkEphemeralStoragePolicy = Get-SpbmStoragePolicy -Name $EphemeralStoragePolicy -ErrorAction SilentlyContinue - if (!$checkEphemeralStoragePolicy -or !$ephemeralStoragePolicy) { - $EphemeralStoragePolicy = Read-Host "Invalid Ephemeral Storage Policy ($EphemeralStoragePolicy). Please enter the correct value and press Enter" - } - } Until ($checkEphemeralStoragePolicy.Name -eq $ephemeralStoragePolicy) - - # Validate Image Storage Policy exists - Do { - $checkImageStoragePolicy = $null - $checkImageStoragePolicy = Get-SpbmStoragePolicy -Name $ImageStoragePolicy -ErrorAction SilentlyContinue - if (!$checkImageStoragePolicy -or !$imageStoragePolicy) { - $ImageStoragePolicy = Read-Host "Invalid Image Storage Policy ($ImageStoragePolicy). Please enter the correct value and press Enter" - } - } Until ($checkImageStoragePolicy.Name -eq $imageStoragePolicy) - - # Validate Master Storage Policy exists - Do { - $checkMasterStoragePolicy = $null - $checkMasterStoragePolicy = Get-SpbmStoragePolicy -Name $MasterStoragePolicy -ErrorAction SilentlyContinue - if (!$checkMasterStoragePolicy -or !$masterStoragePolicy) { - $MasterStoragePolicy = Read-Host "Invalid Master Storage Policy ($MasterStoragePolicy). Please enter the correct value and press Enter" - } - } Until ($checkMasterStoragePolicy.Name -eq $masterStoragePolicy) - - # Validate NSX Edge Cluster exists and lookup ID - Do { - $nsxEdgeClusterId = $null - $checkNsxEdgeCluster = $null - $checkNsxEdgeCluster = Get-NsxEdgeCluster -Name $nsxEdgeCluster -ErrorAction SilentlyContinue - $nsxEdgeClusterId = $checkNsxEdgeCluster.Id - if (!$nsxEdgeClusterId -or !$nsxEdgeCluster) { - $NsxEdgeCluster = Read-Host "Invalid NSX Edge Cluster ($NsxEdgeCluster). Please enter the correct value and press Enter" - } - } Until ($checkNsxEdgeCluster.display_name -eq $nsxEdgeCluster) - - # Validate control plane NTP servers exist and are functional - if ($masterNtpServers) { - for ($i = 0;$i -lt $masterNtpServers.length; $i++) { - $count = 0 - Do { - $checkNtpServer = $null - $masterNtpServerPrompt = $null - if ($masterNtpServers[$i]) { - $checkNtpServer = Get-NtpServer -server $masterNtpServers[$i] - } - if ($checkNtpServer.Results -eq "Not Working" -or !$masterNtpServers[$i]) { - Do { - $masterNtpServerPrompt = Read-Host "Invalid NTP server ("$masterNtpServers[$i]"). Please enter the correct value and press Enter" - $masterNtpServers[$i] = $masterNtpServerPrompt - $checkAlteredMasterNtpServer = Get-NtpServer -server $masterNtpServers[$i] - } Until ($checkAlteredMasterNtpServer.Results -eq "Working") - } - } Until ($checkNtpServer.Results -eq "Working") - } - } - - # Validate control plane DNS servers exist and are functional - if ($masterDnsServers -or $workerDnsServers) { - if ($masterDnsServers){ - for ($i = 0;$i -lt $masterDnsServers.length; $i++) { - $checkMasterDnsServer = $null - $checkMasterDnsServerFormat = $null - - if ($masterDnsServers[$i]) { - $checkMasterDnsServerFormat = [IPAddress]$masterDnsServers[$i] - if ($checkMasterDnsServerFormat.IPAddressToString -ne $masterDnsServers[$i] -or !$checkMasterDnsServerFormat) { - Do { - $masterDnsServerFormatPrompt = $null - $checkAlteredMasterDnsServerFormat = $null - $masterDnsServerFormatPrompt = Read-Host "Invalid control plane DNS server ("$masterDnsServers[$i]"). Please enter a properly formatted IPv4 address (e.g., 172.16.11.4) and press Enter" - $masterDnsServers[$i] = $masterDnsServerFormatPrompt - $checkAlteredMasterDnsServerFormat = [IPAddress]$masterDnsServerFormatPrompt - } Until ($checkAlteredMasterDnsServerFormat.IPAddressToString -eq $masterDnsServerFormatPrompt -and $masterDnsServerFormatPrompt.Length -ne [string]::Empty) - } - - if ($isWindows -eq $true -or $PSVersionTable.PSEdition -eq "Desktop") { - $masterDnsServerPrompt = $null - Do { - Try { - $checkMasterDnsServer = Resolve-DnsName -Name vmware.com -Type A -Server $masterDnsServers[$i] -QuickTimeout -ErrorAction Stop - } Catch [System.ComponentModel.Win32Exception] { - $masterDnsServerPrompt = Read-Host "Invalid control plane DNS server ("$masterDnsServers[$i]"). Please enter a properly formatted IPv4 address (e.g., 172.16.11.4) and press Enter" - $masterDnsServers[$i] = $masterDnsServerPrompt - } - } Until ($checkMasterDnsServer) - } elseif ($isLinux -or $isMacOS) { - do { - Try { - $checkMasterDnsServer = Invoke-Expression 'nslookup -type=A vmware.com ""$masterDnsServers[$i]""' - } Catch {} - if ($checkMasterDnsServer -match "connection timed out"){ - Do { - $checkAlteredMasterDnsServer = $null - $masterDnsServerPrompt = Read-Host "Invalid control plane DNS server ("$masterDnsServers[$i]"). Please enter a properly formatted IPv4 address (e.g., 172.16.11.4) and press Enter" - $checkAlteredMasterDnsServer = [IPAddress]$masterDnsServerPrompt - $masterDnsServers[$i] = $masterDnsServerPrompt - } Until ($checkAlteredMasterDnsServer.IpAddressToString -eq $masterDnsServerPrompt -and $masterDnsServerPrompt.Length -ne [string]::Empty) - } - } Until ($checkMasterDnsServer[0] -match $masterDnsServers[$i] -and $checkMasterDnsServer[4] -match "vmware.com") - } - } - } - } - - if ($workerDnsServers){ - for ($i = 0;$i -lt $workerDnsServers.length; $i++) { - $checkWorkerDnsServer = $null - $checkWorkerDnsServerFormat = $null - if ($workerDnsServers[$i]) { - $checkWorkerDnsServerFormat = [IPAddress]$workerDnsServers[$i] - if ($checkWorkerDnsServerFormat.IPAddressToString -ne $workerDnsServers[$i] -or !$checkWorkerDnsServerFormat) { - Do { - $workerDnsServerFormatPrompt = $null - $checkAlteredWorkerDnsServerFormat = $null - $workerDnsServerFormatPrompt = Read-Host "Invalid worker DNS server ("$workerDnsServers[$i]"). Please enter a properly formatted IPv4 address (e.g., 172.16.11.4) and press Enter" - $workerDnsServers[$i] = $workerDnsServerFormatPrompt - $checkAlteredWorkerDnsServerFormat = [IPAddress]$workerDnsServerFormatPrompt - } Until ($checkAlteredWorkerDnsServerFormat.IPAddressToString -eq $workerDnsServerFormatPrompt -and $workerDnsServerFormatPrompt.Length -ne [string]::Empty) - } - if ($isWindows -eq $true -or $PSVersionTable.PSEdition -eq "Desktop") { - $workerDnsServerPrompt = $null - Do { - Try { - $checkWorkerDnsServer = Resolve-DnsName -Name vmware.com -Type A -Server $workerDnsServers[$i] -QuickTimeout -ErrorAction Stop - } Catch [System.ComponentModel.Win32Exception] { - $workerDnsServerPrompt = Read-Host "Invalid worker DNS server ("$workerDnsServers[$i]"). Please enter a properly formatted IPv4 address (e.g., 172.16.11.4) and press Enter" - $workerDnsServers[$i] = $workerDnsServerPrompt - } - } Until ($checkWorkerDnsServer) - } elseif ($isLinux -or $isMacOS) { - Do { - $checkWorkerDnsServer = Invoke-Expression 'nslookup -type=A vmware.com ""$workerDnsServers[$i]""' - if ($checkWorkerDnsServer -match "connection timed out"){ - Do { - $checkAlteredWorkerDnsServer = $null - $workerDnsServerPrompt = Read-Host "Invalid worker DNS server ("$workerDnsServers[$i]"). Please enter a properly formatted IPv4 address (e.g., 172.16.11.4) and press Enter" - $checkAlteredWorkerDnsServer = [IPAddress]$workerDnsServerPrompt - $workerDnsServers[$i] = $workerDnsServerPrompt - } Until ($checkAlteredWorkerDnsServer.IpAddressToString -eq $workerDnsServerPrompt -and $workerDnsServerPrompt.Length -ne [string]::Empty) - } - } Until ($checkWorkerDnsServer[0] -match $workerDnsServers[$i] -and $checkWorkerDnsServer[4] -match "vmware.com") - } - } - } - } - } - - # Validate ContentLibrary exists - Do { - $checkContentLibrary = $null - if ($contentLibrary){ - Try { - $checkContentLibrary = Get-SubscribedLibrary -Name $contentLibrary -ErrorAction SilentlyContinue - } - Catch { - Debug-ExceptionWriter -object $_ - } - } - if ($checkContentLibrary.Name -ne $contentLibrary -or !$contentLibrary) { - $contentLibrary = Read-Host "Invalid Content Library ($contentLibrary). Please enter the correct name and press Enter" - } - } Until ($checkContentLibrary.Name -eq $contentLibrary) - - # Validate Distributed Virtual Switch exists - if ($distributedSwitch) { - Do { - $checkDistributedSwitch = $null - if ($distributedSwitch){ - Try { - $checkDistributedSwitch = Get-VDSwitch -Name $distributedSwitch -ErrorAction SilentlyContinue - } - Catch { - Debug-ExceptionWriter -object $_ - } - } - if ($checkDistributedSwitch.Name -ne $distributedSwitch -or !$distributedSwitch) { - $distributedSwitch = Read-Host "Invalid Virtual Distributed Switch ($distributedSwitch). Please enter the correct name and press Enter" - } - } Until ($checkDistributedSwitch.Name -eq $distributedSwitch) - } - - # Validates subnet inputs are formatted correctly and sized to meet minimum requirements - $checkPodCidr = Test-SubnetInput -Subnet $podCIDRs -SubnetType "Pod" - if ($checkPodCidr.Altered -eq $true) { - $podCIDRs = $checkPodCidr.subnet - } - $checkServiceCidr = Test-SubnetInput -Subnet $serviceCIDR -SubnetType "Service" - if ($checkServiceCidr.Altered -eq $true) { - $serviceCIDR = $checkServiceCidr.subnet - } - $checkIngressCidr = Test-SubnetInput -Subnet $externalIngressCIDRs -SubnetType "Ingress" - if ($checkIngressCidr.Altered -eq $true) { - $externalIngressCIDRs = $checkIngressCidr.subnet - } - $checkEgressCidr = Test-SubnetInput -Subnet $externalEgressCIDRs -SubnetType "Egress" - if ($checkEgressCidr.Altered -eq $true) { - $externalEgressCIDRs = $checkEgressCidr.subnet - } - - # Validate control plane Kubernetes API endpoint is valid and in DNS - if ($masterDnsName) { - $checkMasterDnsName = $null - if ($isWindows -eq $true -or $PSVersionTable.PSEdition -eq "Desktop") { - $masterDnsSearchDomainPrompt = $null - Do { - Try { - $checkMasterDnsName = Resolve-DnsName -Name $masterDnsName -Type A -QuickTimeout -ErrorAction Stop - } - Catch [System.ComponentModel.Win32Exception] { - Do { - $masterDnsName = Read-Host "Invalid control plane DNS name ("$masterDnsName "). Please enter a fully-qualified domain name (e.g., sfo-w01-cl01.sfo.rainpole.io) and press Enter" - } Until ($masterDnsName.Length -ne [string]::Empty) - } - } Until ($checkMasterDnsName) - } elseif ($isLinux -or $isMacOS) { - Do { - $checkMasterDnsName = Invoke-Expression "nslookup -type=A $masterDnsName" - if ($checkMasterDnsName) { - if ($checkMasterDnsName[3] -match "NXDOMAIN" -or $checkMasterDnsName[4] -match "SERVFAIL" -or $checkMasterDnsName[3] -match "in-addr.arpa"){ - Do { - $masterDnsNamePrompt = Read-Host "Invalid control plane DNS name ("$masterDnsName "). Please enter a fully-qualified domain name (e.g., sfo-w01-cl01.sfo.rainpole.io) and press Enter" - } Until ($masterDnsNamePrompt.Length -ne [string]::Empty -and $masterDnsNamePrompt -notcontains " ") - - $masterDnsName = $masterDnsNamePrompt - } - } elseif (!$checkMasterDnsName) { - Do { - $masterDnsNamePrompt = Read-Host "Invalid control plane DNS name ("$masterDnsName "). Please enter a fully-qualified domain name (e.g., sfo-w01-cl01.sfo.rainpole.io) and press Enter" - } Until ($masterDnsNamePrompt.Length -ne [string]::Empty -and $masterDnsNamePrompt -notcontains " ") - $checkMasterDnsName = 1...4 - $masterDnsName = $masterDnsNamePrompt - } - } Until ($checkMasterDnsName[3] -match $masterDnsName) - } - - Try { - $checkMasterIpAddress = Test-IpAddress -IpAddress $checkMasterDnsName.Answers[0].Address.IPAddressToString -Subnet $externalIngressCIDRs - } Catch { - $checkMasterIpAddress - } - - if ($checkMasterIpAddress.Validated -eq $false) { - $masterDnsNameIpAddress = $checkMasterDnsName.Answers[0].Address.IPAddressToString - Write-Error -Message "Cannot validate the IP address for $masterDnsName ($masterDnsNameIpAddress) is from the external ingress CIDR ($externalIngressCIDRs). Please resolve this and try again." - Break - } - } - - # Validate master DNS search domain is formatted correctly and exists in DNS - if ($masterDnsSearchDomain) { - $checkMasterDnsSearchDomain = $null - if ($isWindows -eq $true -or $PSVersionTable.PSEdition -eq "Desktop") { - $masterDnsSearchDomainPrompt = $null - Do { - Try { - $checkMasterDnsSearchDomain = Resolve-DnsName -Name $masterDnsSearchDomain -Type A -QuickTimeout -ErrorAction Stop - } - Catch [System.ComponentModel.Win32Exception] { - Do { - $masterDnsSearchDomain = Read-Host "Invalid control plane DNS search domain ("$masterDnsSearchDomain "). Please enter a search domain (e.g., sfo.rainpole.io) and press Enter" - } Until ($masterDnsSearchDomain.Length -ne [string]::Empty) - } - } Until ($checkMasterDnsSearchDomain) - } elseif ($isLinux -or $isMacOS) { - Do { - $checkMasterDnsSearchDomain = Invoke-Expression "nslookup -type=A $masterDnsSearchDomain" - if ($checkMasterDnsSearchDomain) { - if ($checkMasterDnsSearchDomain[3] -match "NXDOMAIN" -or $checkMasterDnsSearchDomain[4] -match "SERVFAIL" -or $checkMasterDnsSearchDomain[3] -match "in-addr.arpa"){ - Do { - $masterDnsSearchDomainPrompt = Read-Host "Invalid control plane DNS search domain ("$masterDnsSearchDomain" ). Please enter a search domain (e.g., sfo.rainpole.io) and press Enter" - } Until ($masterDnsSearchDomainPrompt.Length -ne [string]::Empty -and $masterDnsSearchDomainPrompt -notcontains " ") - - $masterDnsSearchDomain = $masterDnsSearchDomainPrompt - } - } elseif (!$checkMasterDnsSearchDomain) { - Do { - $masterDnsSearchDomainPrompt = Read-Host "Invalid control plane DNS search domain ("$masterDnsSearchDomain" ). Please enter a search domain (e.g., sfo.rainpole.io) and press Enter" - } Until ($masterDnsSearchDomainPrompt.Length -ne [string]::Empty -and $masterDnsSearchDomainPrompt -notcontains " ") - $checkMasterDnsSearchDomain = 1...4 - $masterDnsSearchDomain = $masterDnsSearchDomainPrompt - } - } Until ($checkMasterDnsSearchDomain[3] -match $masterDnsSearchDomain) - } - } - - # Validate vSphere license is in place - Try { - $checkLicense = Get-WMLicenseStatus -server $server -domain $domain -ErrorAction SilentlyContinue - if ($checkLicense.namespaces_licensed -eq $false) { - Write-Error -Message "The vSphere license applied to cluster $cluster does not support Workload Management or is expired. Please resolve this and try again." - Break - } elseif ($checklicense.namespaces_supported -eq $false) { - Write-Error -Message "The cluster $cluster does not support Workload Management. Please resolve this and try again." - } - } - Catch { - Debug-ExceptionWriter -object $_ - } - - # Validate the cluster is present - Do { - $checkCluster = Get-Cluster -Name $cluster -ErrorAction SilentlyContinue - if (!$checkCluster -or !$cluster) { - $cluster = Read-Host -Prompt "Invalid vSphere cluster ($cluster). Please enter the correct value and press Enter" - } - } Until ($checkCluster.Name -eq $cluster) - } - - if ($SkipValidation -eq $true) { - $internalWMClusterInput = @{ - SizeHint = $SizeHint - ManagementVirtualNetwork = (Get-VirtualNetwork -Name $managementVirtualNetwork) - ManagementNetworkMode = $managementNetworkMode - ManagementNetworkStartIpAddress = $managementNetworkStartIpAddress - ManagementNetworkAddressRangeSize = $managementNetworkAddressRangeSize - ManagementNetworkGateway = $managementNetworkGateway - ManagementNetworkSubnetMask = $managementNetworkSubnetMask - MasterDnsNames = $masterDnsName - MasterNtpServer = $masterNtpServers - Cluster = (Get-Cluster -Name $cluster) - ContentLibrary = $contentLibrary - EphemeralStoragePolicy = (Get-SpbmStoragePolicy -Name $ephemeralStoragePolicy) - ImageStoragePolicy = (Get-SpbmStoragePolicy -Name $imageStoragePolicy) - MasterStoragePolicy = (Get-SpbmStoragePolicy -Name $masterStoragePolicy) - NsxEdgeClusterId = ((Get-NsxEdgeCluster -Name $nsxEdgeCluster).id) - DistributedSwitch = (Get-VDSwitch -Name $distributedSwitch) - PodCIDRs = $podCIDRs - ServiceCIDR = $serviceCIDR - ExternalIngressCIDRs = $externalIngressCIDRs - ExternalEgressCIDRs = $externalEgressCIDRs - WorkerDnsServer = $workerDnsServers - MasterDnsServerIpAddress = $masterDnsServers - MasterDnsSearchDomain = $masterDnsSearchDomain - } - } else { - $internalWMClusterInput = @{ - SizeHint = $SizeHint - ManagementVirtualNetwork = $checkManagementVirtualNetwork - ManagementNetworkMode = $managementNetworkMode - ManagementNetworkStartIpAddress = $managementNetworkStartIpAddress - ManagementNetworkAddressRangeSize = $managementNetworkAddressRangeSize - ManagementNetworkGateway = $managementNetworkGateway - ManagementNetworkSubnetMask = $managementNetworkSubnetMask - MasterDnsNames = $masterDnsName - MasterNtpServer = $masterNtpServers - Cluster = $checkCluster - ContentLibrary = $contentLibrary - EphemeralStoragePolicy = $checkEphemeralStoragePolicy - ImageStoragePolicy = $checkImageStoragePolicy - MasterStoragePolicy = $checkMasterStoragePolicy - NsxEdgeClusterId = $NsxEdgeClusterId - DistributedSwitch = $checkDistributedSwitch - PodCIDRs = $podCIDRs - ServiceCIDR = $serviceCIDR - ExternalIngressCIDRs = $externalIngressCIDRs - ExternalEgressCIDRs = $externalEgressCIDRs - WorkerDnsServer = $workerDnsServers - MasterDnsServerIpAddress = $masterDnsServers - MasterDnsSearchDomain = $masterDnsSearchDomain - } - } - - if ($ValidateOnly -eq $true) { - Write-Output "Validating all Supervisor Cluster Inputs: SUCCESSFUL" - } elseif (!$ValidateOnly -or $ValidateOnly -eq $false) { - if (!$PsBoundParameters.ContainsKey("RunAsync")) { - Enable-WMCluster @internalWMClusterInput -RunAsync -Server $vcfVcenterDetails.fqdn | Out-Null - Write-Output "Enabling Supervisor Cluster in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($cluster): SUCCESSFUL" - } - else { - Enable-WMCluster @internalWMClusterInput -Server $vcfVcenterDetails.fqdn | Out-Null - if (Get-WMCluster -cluster $cluster -ErrorAction SilentlyContinue) { - Write-Output "Enabling Supervisor Cluster in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($cluster): SUCCESSFUL" - } - else { - Write-Error "Enabling Supervisor Cluster in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($cluster): POST_VALIDATION_FAILED" - } - } - } - } - else { - Write-Warning "Enabling Supervisor Cluster in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($cluster), already enabled: SKIPPED" - } + if (($vcfNsxtDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain)) { + if (Test-NSXTConnection -server $vcfNsxtDetails.fqdn) { + if (Test-NSXTAuthentication -server $vcfNsxtDetails.fqdn -user $vcfNsxtDetails.adminUser -pass $vcfNsxtDetails.adminPass) { + if (Get-NsxtTier0Gateway -name $tier0Gateway) { + if (!(Get-NsxtTier0Gateway -name $tier0Gateway | Get-NsxtPrefixList -name $prefixListName -ErrorAction SilentlyContinue)) { + Get-NsxtTier0Gateway -name $tier0Gateway | New-NsxtPrefixList -name $prefixListName -subnetCidr $subnetCidr -action $action | Out-Null + if (Get-NsxtTier0Gateway -name $tier0Gateway | Get-NsxtPrefixList -name $prefixListName -ErrorAction SilentlyContinue) { + Get-NsxtTier0Gateway -name $tier0Gateway | Get-NsxtPrefixList -name $prefixListName | Add-NsxtPrefix -subnetCidr $ingressSubnetCidr -GE $GE -LE $LE -action $action | Out-Null + Get-NsxtTier0Gateway -name $tier0Gateway | Get-NsxtPrefixList -name $prefixListName | Add-NsxtPrefix -subnetCidr $egressSubnetCidr -GE $GE -LE $LE -action $action | Out-Null + Write-Output "Adding NSX IP Prefix List in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($prefixListName): SUCCESSFUL" + } + else { + Write-Error "Adding NSX IP Prefix List in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($prefixListName): POST_VALIDATION_FAILED" } } + else { + Write-Warning "Adding NSX IP Prefix List in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($prefixListName), already exists: SKIPPED" + } + } + else { + Write-Error "Unable to find NSX Tier0 Gateway ($tier0Gateway) in NSX Manager ($($vcfNsxtDetails.fqdn)): PRE_VALIDATION_FAILED" } } } @@ -3904,19 +3866,23 @@ Function Enable-SupervisorCluster { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Enable-SupervisorCluster +Export-ModuleMember -Function Add-PrefixList -Function Undo-SupervisorCluster { +Function Undo-PrefixList { <# .SYNOPSIS - Remove Supervisor Cluster + The Undo-PrefixList cmdlet removes the NSX Prefix List from NSX Manager. The cmdlet connects to SDDC Manager + using the -server, -user, and -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to NSX Manager + - Removes an NSX Prefix List if not already removed from NSX Manager .DESCRIPTION - The Undo-SupervisorCluster cmdlet removes the Supervisor Cluster from a Workload Domain + The Undo-PrefixList cmdlet removes an NSX Prefix List .EXAMPLE - Undo-SupervisorCluster -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -cluster sfo-w01-cl01 - This example enables Workload Management on a vSphere Cluster in workload domain sfo-w01 + Undo-PrefixList -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -tier0Gateway sfo-w01-ec01-t0-gw01 -prefixListName sfo-w01-ec01-t0-gw01-mgmt-prefixlist + This example removes an NSX Prefix List in the Workload Domain NSX Management Cluster #> Param ( @@ -3924,46 +3890,36 @@ Function Undo-SupervisorCluster { [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$RunAsync + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tier0Gateway, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$prefixListName ) Try { if (Test-VCFConnection -server $server) { if (Test-VCFAuthentication -server $server -user $user -pass $pass) { - if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) { - if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) { - if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { - if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { - if (Test-vSphereApiConnection -server $($vcfVcenterDetails.fqdn)) { - if (Test-vSphereApiAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { - if (Get-WMCluster -cluster $cluster -ErrorAction Ignore) { - if (!$PsBoundParameters.ContainsKey("RunAsync")) { - Disable-WMCluster -WMCluster $cluster -RunAsync -Server $vcfVcenterDetails.fqdn -Confirm:$false | Out-Null - } - else { - Disable-WMCluster -WMCluster $cluster -Server $vcfVcenterDetails.fqdn -Confirm:$false | Out-Null - } - if (!(Get-WMCluster -cluster $cluster -ErrorAction Ignore)) { - Write-Output "Removing Supervisor Cluster ($cluster) from vCenter Server ($($vcfVcenterDetails.fqdn)): SUCCESSFUL" - } - else { - Write-Error "Removing Supervisor Cluster ($cluster) from vCenter Server ($($vcfVcenterDetails.fqdn)): POST_VALIDATION_FAILED" - } - } - else { - Write-Warning "Removing Supervisor Cluster ($cluster) from vCenter Server ($($vcfVcenterDetails.fqdn)), does not exist: SKIPPED" - } + if (($vcfNsxtDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain)) { + if (Test-NSXTConnection -server $vcfNsxtDetails.fqdn) { + if (Test-NSXTAuthentication -server $vcfNsxtDetails.fqdn -user $vcfNsxtDetails.adminUser -pass $vcfNsxtDetails.adminPass) { + if (Get-NsxtTier0Gateway -name $tier0Gateway) { + if (Get-NsxtTier0Gateway -name $tier0Gateway | Get-NsxtPrefixList -name $prefixListName -ErrorAction SilentlyContinue) { + Remove-NsxtPrefixList -name $prefixListName -tier0Gateway $tier0Gateway | Out-Null + if (!(Get-NsxtTier0Gateway -name $tier0Gateway | Get-NsxtPrefixList -name $prefixListName -ErrorAction SilentlyContinue)) { + Write-Output "Removing NSX IP Prefix List in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($prefixListName): SUCCESSFUL" } + else { + Write-Error "Removing NSX IP Prefix List in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($prefixListName): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Removing NSX IP Prefix List in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($prefixListName), does not exist: SKIPPED" } } - Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue + else { + Write-Error "Unable to find NSX Tier0 Gateway ($tier0Gateway) in NSX Manager ($($vcfNsxtDetails.fqdn)): PRE_VALIDATION_FAILED" + } } } } - else { - Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" - } } } } @@ -3971,19 +3927,23 @@ Function Undo-SupervisorCluster { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Undo-SupervisorCluster +Export-ModuleMember -Function Undo-PrefixList -Function New-SupervisorClusterCSR { +Function Add-RouteMap { <# .SYNOPSIS - Create a new certificate signing request for the defined Supervisor Cluster + The Add-RouteMap cmdlet creates NSX Prefix List in the NSX Management Cluster. The cmdlet connects to SDDC + Manager using the -server, -user, and -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to NSX Manager + - Create an NSX Route Map if not already created in NSX Manager .DESCRIPTION - The New-SupervisorClusterCSR cmdlet creates a new certificate signing request for the defined Supervisor Cluster + The Add-RouteMap cmdlet creates an NSX Route Map .EXAMPLE - New-SupervisorClusterCSR -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -cluster sfo-w01-cl01 -commonName sfo-m01-cl01.sfo.rainpole.io -organization Rainpole -organizationalUnit Rainpole -country US -stateOrProvince California -locality "Palo Alto" -adminEmailAddress admin@rainpole.io -keySize 2048 -filePath ".\SupervisorCluster.csr" - This example returns a certificate signing request for the Supervisor Cluster sfo-w01-cl01 in Workload domain sfo-w01 + Add-RouteMap -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -tier0Gateway sfo-w01-ec01-t0-gw01 -routeMapName sfo-w01-ec01-t0-gw01-routemap -prefixListName sfo-w01-ec01-t0-gw01-mgmt-prefixlist -action PERMIT -applyPolicy:$true + This example creates an NSX Route Map in workload domain sfo-w01 #> Param ( @@ -3991,49 +3951,47 @@ Function New-SupervisorClusterCSR { [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$commonName, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$organization, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$organizationalUnit, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$country, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$stateOrProvince, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$locality, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$adminEmailAddress, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$keySize, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$filePath + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tier0Gateway, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$routeMapName, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$prefixListName, + [Parameter (Mandatory = $true)] [ValidateSet("PERMIT", "DENY")][String]$action, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Bool]$applyPolicy ) Try { if (Test-VCFConnection -server $server) { if (Test-VCFAuthentication -server $server -user $user -pass $pass) { - if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) { - if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) { - if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { - if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { - if (Test-vSphereApiConnection -server $($vcfVcenterDetails.fqdn)) { - if (Test-vSphereApiAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { - if ($PsBoundParameters.ContainsKey("keySize")) { - Request-WMClusterCSR -cluster $cluster -commonName $commonName -organization $organization -organizationalUnit $organizationalUnit -country $country -stateOrProvince $stateOrProvince -locality $locality -adminEmailAddress $adminEmailAddress -keySize $keySize -filePath $filePath | Out-Null - } - else { - Request-WMClusterCSR -cluster $cluster -commonName $commonName -organization $organization -organizationalUnit $organizationalUnit -country $country -stateOrProvince $stateOrProvince -locality $locality -adminEmailAddress $adminEmailAddress -filePath $filePath | Out-Null - } - if (Test-Path -Path $filePath) { - Write-Output "Creating Certificate Signing Request (.csr) file for ($commonName) to file ($filePath): SUCCESSFUL" + if (($vcfNsxtDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain)) { + if (Test-NSXTConnection -server $vcfNsxtDetails.fqdn) { + if (Test-NSXTAuthentication -server $vcfNsxtDetails.fqdn -user $vcfNsxtDetails.adminUser -pass $vcfNsxtDetails.adminPass) { + if (Get-NsxtTier0Gateway -name $tier0Gateway) { + if (!(Get-NsxtRouteMap -tier0Gateway $tier0Gateway -name $routeMapName -ErrorAction SilentlyContinue)) { + if (Get-NsxtTier0Gateway -name $tier0Gateway | Get-NsxtPrefixList -name $prefixListName -ErrorAction SilentlyContinue) { + Get-NsxtTier0Gateway -name $tier0Gateway | New-NsxtRouteMap -name $routeMapName -prefixList $prefixListName -action $Action | Out-Null + if (Get-NsxtRouteMap -tier0Gateway $tier0Gateway -name $routeMapName -ErrorAction SilentlyContinue) { + if ($applyPolicy -eq $true) { + Get-NsxtRouteRedistributionPolicy -tier0Gateway $tier0Gateway | Set-NsxtRouteRedistributionPolicy -routeMap $routeMapName | Out-Null + } + Write-Output "Adding NSX Route Map in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($routeMapName): SUCCESSFUL" } else { - Write-Error "Creating Certificate Signing Request (.csr) file for ($commonName) to file ($filePath): POST_VALIDATION_FAILED" + Write-Error "Adding NSX Route Map in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($routeMapName): POST_VALIDATION_FAILED" } } + else { + Write-Error "Unable to find NSX Prefix List in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($prefixListName): PRE_VALIDATION_FAILED" + } + } + else { + Write-Warning "Adding NSX Route Map in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($routeMapName), already exists: SKIPPED" } } - Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue + else { + Write-Error "Unable to find NSX Tier0 Gateway ($tier0Gateway) in NSX Manager ($($vcfNsxtDetails.fqdn)): PRE_VALIDATION_FAILED" + } } } } - else { - Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" - } } } } @@ -4041,19 +3999,23 @@ Function New-SupervisorClusterCSR { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function New-SupervisorClusterCSR +Export-ModuleMember -Function Add-RouteMap -Function Install-SupervisorClusterCertificate { +Function Undo-RouteMap { <# .SYNOPSIS - Add a signed TLS certificate for the defined Supervisor Cluster + The Undo-RouteMap cmdlet removes NSX Route Map from the NSX Management Cluster. The cmdlet connects to SDDC + Manager using the -server, -user, and -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to NSX Manager + - Removes an NSX Route Map from NSX Manager .DESCRIPTION - The Install-SupervisorClusterCertificate cmdlet adds a signed TLS certificate for the defined Supervisor Cluster + The Undo-RouteMap cmdlet removes an NSX Route Map .EXAMPLE - Install-SupervisorClusterCertificate -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -Cluster sfo-w01-cl01 -FilePath ".\SupervisorCluster.cer" - This example applies the signed TLS certificate to Supervisor Cluster sfo-w01-cl01 in Workload domain sfo-w01 + Undo-RouteMap -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -tier0Gateway sfo-w01-ec01-t0-gw01 -routeMapName sfo-w01-ec01-t0-gw01-routemap + This example removes an NSX Route Map in the workload domain sfo-w01 #> Param ( @@ -4061,43 +4023,36 @@ Function Install-SupervisorClusterCertificate { [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$filePath + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tier0Gateway, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$routeMapName ) - if (!$PsBoundParameters.ContainsKey("filePath")) { - $filePath = Get-ExternalFileName -title "Select the Supervisor Cluster Certificate File (.cer)" -fileType "cer" -location "default" - } - elseif ($PsBoundParameters.ContainsKey("filePath")) { - if (!(Test-Path -Path $filePath)) { - Write-Error "Certificate (cer) file for the Supervisor Cluster '$filePath' File Not Found" - Break - } - } - Try { if (Test-VCFConnection -server $server) { if (Test-VCFAuthentication -server $server -user $user -pass $pass) { - if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) { - if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) { - if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { - if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { - Request-vSphereApiToken -fqdn $vcfVcenterDetails.fqdn -username $vcfVcenterDetails.ssoAdmin -password $vcfVcenterDetails.ssoAdminPass | Out-Null - $response = Install-WMClusterCertificate -cluster $cluster -filePath $filePath - if ($response -match "successfully applied") { - Write-Output "Installing Signed Certificate ($filePath) to Supervisor Cluster ($cluster): SUCCESSFUL" + if (($vcfNsxtDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain)) { + if (Test-NSXTConnection -server $vcfNsxtDetails.fqdn) { + if (Test-NSXTAuthentication -server $vcfNsxtDetails.fqdn -user $vcfNsxtDetails.adminUser -pass $vcfNsxtDetails.adminPass) { + if (Get-NsxtTier0Gateway -name $tier0Gateway) { + if (Get-NsxtRouteMap -tier0Gateway $tier0Gateway -name $routeMapName -ErrorAction SilentlyContinue) { + Remove-NsxtRouteMap -name $routeMapName -tier0Gateway $tier0Gateway | Out-Null + if (!(Get-NsxtRouteMap -tier0Gateway $tier0Gateway -name $routeMapName -ErrorAction SilentlyContinue)) { + Write-Output "Removing NSX Route Map in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($routeMapName): SUCCESSFUL" + } + else { + Write-Error "Removing NSX Route Map in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($routeMapName): POST_VALIDATION_FAILED" + } } else { - Write-Error "Installing Signed Certificate ($filePath) to Supervisor Cluster ($cluster): POST_VALIDATION_FAILED" + Write-Warning "Removing NSX Route Map in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($routeMapName), does not exist: SKIPPED" } } - Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue + else { + Write-Error "Unable to find NSX Tier0 Gateway ($tier0Gateway) in NSX Manager ($($vcfNsxtDetails.fqdn)): PRE_VALIDATION_FAILED" + } } } } - else { - Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" - } } } } @@ -4105,19 +4060,23 @@ Function Install-SupervisorClusterCertificate { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Install-SupervisorClusterCertificate +Export-ModuleMember -Function Undo-RouteMap -Function Add-Namespace { +Function Set-DatastoreTag { <# .SYNOPSIS - Creates a Namespace and applies extra configuration to it + The Function Set-DatastoreTag cmdlet creates and applies a vSphere Tag to the primary datastore. The cmdlet + connects to SDDC Manager using the -server, -user, and -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to vCenter Server + - Creates and applies a vSphere Tag to the primary datastore .DESCRIPTION - The Add-Namespace cmdlet creates a Namespace and applies extra configuration to it + The Set-DatastoreTag cmdlet creates and applies a vSphere Tag to the primary datastore .EXAMPLE - Add-Namespace -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -cluster sfo-w01-cl01 -namespace sfo-w01-ns01 -storagePolicy vsphere-with-tanzu-storage-policy - This example creates a Namespace named sfo-w01-ns01 in the Supervisor Cluster sfo-w01-cl01 with a vSphere Storage Policy vsphere-with-tanzu-storage-policy + Set-DatastoreTag -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -tagName vsphere-with-tanzu-tag -tagCategoryName vsphere-with-tanzu-category + This example creates a new tag and assigns it to the primary datastore of Workload Domain sfo-w01 #> Param ( @@ -4125,41 +4084,40 @@ Function Add-Namespace { [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$namespace, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$storagePolicy + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tagName, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tagCategoryName ) Try { - if (Test-VCFConnection -server $server) { if (Test-VCFAuthentication -server $server -user $user -pass $pass) { if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) { if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) { if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { - if (!(Get-WMNamespace -Name $namespace -ErrorAction SilentlyContinue)) { - if (Get-Cluster -Name $cluster -ErrorAction SilentlyContinue) { - if (Get-SpbmStoragePolicy -Name $storagePolicy -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue) { - New-WMNamespace -Name $namespace -Cluster $cluster | Out-Null - if (Get-WMNamespace -Name $namespace -ErrorAction SilentlyContinue) { - New-WMNamespaceStoragePolicy -Namespace $namespace -StoragePolicy $storagePolicy | Out-Null - Write-Output "Creating Namespace ($namespace) in Supervisor Cluster ($cluster) in vCenter Server ($($vcfVcenterDetails.fqdn)): SUCCESSFUL" - } - else { - Write-Error "Creating Namespace ($namespace) in Supervisor Cluster ($cluster) in vCenter Server ($($vcfVcenterDetails.fqdn)): POST_VALIDATION_FAILED" - } + $datastore = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }).clusters.id) }).primaryDatastoreName + if ($datastoreExist = Get-Datastore -Name $datastore -ErrorAction SilentlyContinue | Where-Object {$_.Name -eq $datastore}) { + if (!(Get-TagAssignment -Entity $datastoreExist.Name -Category $tagCategoryName -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue)) { + if (!(Get-TagCategory -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue | Where-Object { $_.Name -eq $tagCategoryName })) { + New-TagCategory -Name $tagCategoryName -EntityType Datastore -Server $vcfVcenterDetails.fqdn -Confirm:$false | Out-Null + } + if (!(Get-Tag -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue | Where-Object { $_.Name -eq $tagName })) { + New-Tag -Name $tagName -Category $tagCategoryName -Server $vcfVcenterDetails.fqdn -Confirm:$false | Out-Null + } + Get-Datastore -Name $Datastore -Server $vcfVcenterDetails.fqdn | New-TagAssignment -Tag $tagName -Server $vcfVcenterDetails.fqdn -Confirm:$false | Out-Null + if ((Get-TagAssignment -Entity $datastoreExist.Name -Category $tagCategoryName -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue)) { + Write-Output "Creating vSphere Tag ($tagName) and applying to datastore ($datastore) in vCenter Server ($($vcfVcenterDetails.fqdn)): SUCCESSFUL" } else { - Write-Error "Unable to find vSphere Storage Policy ($storagePolicy) in vCenter Server ($($vcfVcenterDetails.fqdn)): PRE_VALIDATION_FAILED" + Write-Error "Creating vSphere Tag ($tagName) and applying to datastore ($datastore) in vCenter Server ($($vcfVcenterDetails.fqdn)): POST_VALIDATION_FAILED" } } else { - Write-Error "Unable to find Cluster ($cluster) in vCenter Server ($($vcfVcenterDetails.fqdn)): PRE_VALIDATION_FAILED" + Write-Warning "Creating vSphere Tag ($tagName) and applying to datastore ($datastore) in vCenter Server ($($vcfVcenterDetails.fqdn)), already exists: SKIPPED" } } else { - Write-Warning "Creating Namespace ($namespace) in Supervisor Cluster ($cluster) in vCenter Server ($($vcfVcenterDetails.fqdn)), already exists: SKIPPED" + Write-Error "Unable to find datastore ($datastore) in vCenter Server ($($vcfVcenterDetails.fqdn)): PRE_VALIDATION_FAILED" } } Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue @@ -4176,19 +4134,23 @@ Function Add-Namespace { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-Namespace +Export-ModuleMember -Function Set-DatastoreTag -Function Undo-Namespace { +Function Undo-DatastoreTag { <# .SYNOPSIS - Remove a Namespace + The Function Undo-DatastoreTag cmdlet removes a vSphere Category and Tag. The cmdlet connects to SDDC Manager using the + -server, -user, and -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to vCenter Server + - Removes the vSphere Tag .DESCRIPTION - The Undo-Namespace cmdlet removes a Namespace from the Supervisor Cluster + The Undo-DatastoreTag cmdlet removes the vSphere Tag .EXAMPLE - Undo-Namespace -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -namespace sfo-w01-ns02 - This example removes the Namespace named sfo-w01-ns02 + Undo-DatastoreTag -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -tagName vsphere-with-tanzu-tag -tagCategoryName vsphere-with-tanzu-category + This example removes the vSphere tag from the Workload Domain sfo-w01 vCenter Server #> Param ( @@ -4196,7 +4158,8 @@ Function Undo-Namespace { [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$namespace + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tagName, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tagCategoryName ) Try { @@ -4206,17 +4169,18 @@ Function Undo-Namespace { if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) { if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { - if (Get-WMNamespace -Name $namespace -Server $vcfVcenterDetails.fqdn -ErrorAction Ignore) { - Remove-WMNamespace -Namespace $namespace -Server $vcfVcenterDetails.fqdn -Confirm:$false | Out-Null - if (!(Get-WMNamespace -Name $namespace -Server $vcfVcenterDetails.fqdn -ErrorAction Ignore)) { - Write-Output "Removing Namespace ($namespace) from vCenter Server ($($vcfVcenterDetails.fqdn)): SUCCESSFUL" + if (Get-Tag -Server $vcfVcenterDetails.fqdn -ErrorAction Ignore | Where-Object { $_.Name -eq $tagName }) { + Remove-Tag -Tag $tagName -Server $vcfVcenterDetails.fqdn -Confirm:$false | Out-Null + Remove-TagCategory -Category $tagCategoryName -Server $vcfVcenterDetails.fqdn -Confirm:$false | Out-Null + if (!(Get-Tag -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue | Where-Object { $_.Name -eq $tagName })) { + Write-Output "Removing vSphere Tag ($tagName) and vSphere Category ($tagCategoryName) from vCenter Server ($($vcfVcenterDetails.fqdn)): SUCCESSFUL" } else { - Write-Error "Removing Namespace ($namespace) from vCenter Server ($($vcfVcenterDetails.fqdn)): POST_VALIDATION_FAILED" + Write-Error "Removing vSphere Tag ($tagName) and vSphere Category ($tagCategoryName) from vCenter Server ($($vcfVcenterDetails.fqdn)): POST_VALIDATION_FAILED" } } else { - Write-Warning "Removing Namespace ($namespace) from vCenter Server ($($vcfVcenterDetails.fqdn)), does not exist: SKIPPED" + Write-Warning "Removing vSphere Tag ($tagName) and Category ($tagCategoryName) from vCenter Server ($($vcfVcenterDetails.fqdn)), does not exist: SKIPPED" } } Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue @@ -4233,136 +4197,118 @@ Function Undo-Namespace { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Undo-Namespace +Export-ModuleMember -Function Undo-DatastoreTag -Function Add-NamespacePermission { +Function Add-StoragePolicy { <# .SYNOPSIS - Adds permissions to a Namespace + The Add-StoragePolicy cmdlet creates a vSphere Storage Policy. The cmdlet connects to SDDC Manager using the + -server, -user, and -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to vCenter Server + - Creates a VM vSphere Storage Policy .DESCRIPTION - The Add-NamespacePermission cmdlet adds permissions to a Namespace + The Add-StoragePolicy cmdlet creates a VM vSphere Storage Policy .EXAMPLE - Add-NamespacePermission -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -sddcDomain sfo-w01 -domain sfo.rainpole.io -domainBindUser svc-vsphere-ad -domainBindPass VMw@re1! -namespace sfo-w01-ns01 -principal gg-kub-admins -role edit -type group - This example adds the edit role to the group gg-kub-admins in the domain sfo.rainpole.io to the Namespace sfo-w01-ns01 + Add-StoragePolicy -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -policyName vsphere-with-tanzu-storage-policy -tagName vsphere-with-tanzu-tag + This example creates a VM Storage Policy named vsphere-with-tanzu-policy in the Wrkload Domain vCenter Server #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcDomain, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domainBindUser, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domainBindPass, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$namespace, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$principal, - [Parameter (Mandatory = $true)] [ValidateSet("edit", "view")] [String]$role, - [Parameter (Mandatory = $true)] [ValidateSet("group", "user")] [String]$type + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$policyName, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tagName ) Try { - $checkAdAuthentication = Test-ADAuthentication -user $domainBindUser -pass $domainBindPass -server $domain -domain $domain -ErrorAction SilentlyContinue - if ($checkAdAuthentication[1] -match "Authentication Successful") { - $securePass = ConvertTo-SecureString -String $domainBindPass -AsPlainText -Force - $domainCreds = New-Object System.Management.Automation.PSCredential ($domainBindUser, $securePass) - if (Test-VCFConnection -server $server) { - if (Test-VCFAuthentication -server $server -user $user -pass $pass) { - if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $sddcDomain }) { - if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $sddcDomain)) { - if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { - if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { - if (Get-WMNamespace -Name $namespace -ErrorAction SilentlyContinue) { - if ($type -eq "group") { $adObjectCheck = (Get-ADGroup -Server $domain -Credential $domainCreds -Filter { SamAccountName -eq $principal }) } - elseif ($type -eq "user") { $adObjectCheck = (Get-ADUser -Server $domain -Credential $domainCreds -Filter { SamAccountName -eq $principal }) } - if ($adObjectCheck) { - if (!(Get-WMNamespacePermission -Namespace $namespace -Domain $domain -PrincipalName $principal)) { - New-WMNamespacePermission -Namespace $namespace -Role $role -Domain $domain -PrincipalType $type -PrincipalName $principal | Out-Null - if (Get-WMNamespacePermission -Namespace $namespace -Domain $domain -PrincipalName $principal) { - Write-Output "Assigning Role ($role) to $type ($principal) in Namespace ($namespace): SUCCESSFUL" - } - else { - Write-Error "Assigning Role ($role) to $type ($principal) in Namespace ($namespace): POST_VALIDATION_FAILED" - } - } - else { - Write-Warning "Assigning Role ($role) to $type ($principal) in Namespace ($namespace), already assigned: SKIPPED" - } + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) { + if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) { + if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + if (!(Get-SpbmStoragePolicy -Name $policyName -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue)) { + if (Get-Tag -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue | Where-Object { $_.Name -eq $tagName }) { + New-SpbmStoragePolicy -Name $policyName -AnyOfRuleSets (New-SpbmRuleSet -AllOfRules (New-SpbmRule -AnyOfTags $tagName -Server $vcfVcenterDetails.fqdn)) -Server $vcfVcenterDetails.fqdn | Out-Null + if (Get-SpbmStoragePolicy -Name $policyName -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue) { + Write-Output "Creating Storage Policy in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($policyName): SUCCESSFUL" } else { - Write-Error "Active Directory $type ($principal) not found in the Active Directory Domain: PRE_VALIDATION_FAILED" + Write-Error "Creating Storage Policy in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($policyName): POST_VALIDATION_FAILED" } } else { - Write-Error "Unable to find Namespace ($namespace) in vCenter Server ($($vcfVcenterDetails.fqdn)): PRE_VALIDATION_FAILED" + Write-Error "Unable to find vSphere Tag ($tagName) in vCenter Server ($($vcfVcenterDetails.fqdn)): PRE_VALIDATION_FAILED" } } - Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue + else { + Write-Warning "Creating Storage Policy in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($policyName), already exists: SKIPPED" + } } + Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue } } - else { - Write-Error "Unable to find Workload Domain named ($sddcDomain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" - } + } + else { + Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" } } } - else { - Write-Error "Unable to authenticate to Active Directory with user ($domainBindUser) and password ($domainBindPass), check details: PRE_VALIDATION_FAILED" - } } Catch { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-NamespacePermission +Export-ModuleMember -Function Add-StoragePolicy -Function Undo-NamespacePermission { +Function Undo-StoragePolicy { <# .SYNOPSIS - Remove permissions from a Namespace + The Undo-StoragePolicy cmdlet removes a vSphere Storage Policy. The cmdlet connects to SDDC Manager using the + -server, -user, and -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to vCenter Server + - Removes a VM vSphere Storage Policy .DESCRIPTION - The Undo-NamespacePermission cmdlet removes a permissions from a Namespace + The Undo-StoragePolicy cmdlet removes a VM vSphere Storage Policy .EXAMPLE - Undo-NamespacePermission -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -sddcDomain sfo-w01 -namespace sfo-w01-ns01 -principal gg-kub-admins - This example removes the edit role from the Namespace sfo-w01-ns01 + Undo-StoragePolicy -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -policyName vsphere-with-tanzu-storage-policy + This example removes a VM Storage Policy named vsphere-with-tanzu-storage-policy from the Wrkload Domain vCenter Server #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcDomain, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$namespace, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$principal + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$policyName ) Try { if (Test-VCFConnection -server $server) { if (Test-VCFAuthentication -server $server -user $user -pass $pass) { - if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $sddcDomain }) { - if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $sddcDomain)) { + if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) { + if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) { if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { - if (Get-WMNamespace -Name $namespace -ErrorAction SilentlyContinue) { - if (Get-WMNamespacePermission -Namespace $namespace -PrincipalName $principal) { - Get-WMNamespacePermission -Namespace $namespace -PrincipalName $principal | Remove-WMNamespacePermission -Confirm:$false | Out-Null - if (!(Get-WMNamespacePermission -Namespace $namespace -PrincipalName $principal)) { - Write-Output "Removing access for principal ($principal) from Namespace ($namespace): SUCCESSFUL" - } - else { - Write-Error "Removing access for principal ($principal) from Namespace ($namespace): POST_VALIDATION_FAILED" - } + if (Get-SpbmStoragePolicy -Name $policyName -Server $vcfVcenterDetails.fqdn -ErrorAction Ignore) { + Remove-SpbmStoragePolicy -StoragePolicy $policyName -Server $vcfVcenterDetails.fqdn -Confirm:$false | Out-Null + if (!(Get-SpbmStoragePolicy -Name $policyName -Server $vcfVcenterDetails.fqdn -ErrorAction Ignore)) { + Write-Output "Removing Storage Policy in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($policyName): SUCCESSFUL" } else { - Write-Warning "Removing access for principal ($principal) from Namespace ($namespace), does not exist: SKIPPED" + Write-Error "Removing Storage Policy in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($policyName): POST_VALIDATION_FAILED" } } else { - Write-Error "Unable to find Namespace ($namespace) in vCenter Server ($($vcfVcenterDetails.fqdn)): PRE_VALIDATION_FAILED" + Write-Warning "Removing Storage Policy in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($policyName), does not exist: SKIPPED" } } Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue @@ -4370,7 +4316,7 @@ Function Undo-NamespacePermission { } } else { - Write-Error "Unable to find Workload Domain named ($sddcDomain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" + Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" } } } @@ -4379,19 +4325,31 @@ Function Undo-NamespacePermission { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Undo-NamespacePermission +Export-ModuleMember -Function Undo-StoragePolicy -Function Enable-Registry { +Function Add-ContentLibrary { <# .SYNOPSIS - Enable the embedded Harbor Registry on a Supervisor Cluster - + Creates a content library + .DESCRIPTION - The Enable-Registry cmdlet enables the embedded Harbor Registry on a Supervisor Cluster - + The Add-ContentLibrary cmdlet creates a subscribed or published content library. The cmdlet connects to SDDC + Manager using the -server, -user, and -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to vCenter Server + - Creates a content library + .EXAMPLE - Enable-Registry -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -storagePolicy vsphere-with-tanzu-storage-policy - This example enables the embedded Harbor Registry on Supervisor Cluster sfo-w01-cl01 with vSPhere Storage Policy vsphere-with-tanzu-policy + Add-ContentLibrary -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -contentLibraryName sfo-w01-lib01 -published + This example creates published content library named sfo-w01-lib01 on the primary datastore in workload domain sfo-w01 + + .EXAMPLE + Add-ContentLibrary -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -contentLibraryName sfo-w01-lib01 -datastore sfo-w01-ds-nfs01 -published + This example creates published content library named sfo-w01-lib01 on a specific datastore in workload domain sfo-w01 + + .EXAMPLE + Add-ContentLibrary -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -contentLibraryName Kubernetes -subscriptionUrl "https://wp-content.vmware.com/v2/latest/lib.json" + This example creates subscribed content library named Kubernetes on the primary datastore in workload domain sfo-w01 #> Param ( @@ -4399,7 +4357,10 @@ Function Enable-Registry { [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$storagePolicy + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$contentLibraryName, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$datastore, + [Parameter (ParameterSetName = 'Subscription', Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$subscriptionUrl, + [Parameter (ParameterSetName = 'Local', Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$published ) Try { @@ -4409,30 +4370,45 @@ Function Enable-Registry { if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) { if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { - if (Test-vSphereApiConnection -server $($vcfVcenterDetails.fqdn)) { - if (Test-vSphereApiAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { - $cluster = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.Name -eq $domain }).clusters.id) }).Name - if (!(Get-WMRegistry -cluster $cluster -ErrorAction SilentlyContinue)) { - if (Get-SpbmStoragePolicy -Name $storagePolicy -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue) { - Enable-WMRegistry -cluster $cluster -StoragePolicy $storagePolicy | Out-Null - Do { - $configStatus = Get-WMRegistry -cluster $cluster | Get-WMRegistryHealth - } Until ($configStatus -eq "RUNNING") - if (Get-WMRegistry -cluster $cluster -ErrorAction SilentlyContinue) { - Write-Output "Enabling Embedded Harbour Registry in vCenter Server ($($vcfVcenterDetails.fqdn)) for Cluster ($cluster): SUCCESSFUL" - } - else { - Write-Error "Enabling Embedded Harbour Registry in vCenter Server ($($vcfVcenterDetails.fqdn)) for Cluster ($cluster): POST_VALIDATION_FAILED" - } - } - else { - Write-Error "Unable to find vSphere Storage Policy ($storagePolicy) in vCenter Server ($($vcfVcenterDetails.fqdn)): PRE_VALIDATION_FAILED" + if (!(Get-ContentLibrary -Name $contentLibraryName -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue)) { + if (!$PsBoundParameters.ContainsKey('datastore')) { + $datastore = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }).clusters.id) }).primaryDatastoreName + } + if (Get-Datastore -Name $datastore -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue | Where-Object {$_.Name -eq $datastore}) { + if ($subscriptionUrl) { + #attribution to William Lam (https://gist.github.com/lamw/988e4599c0f88d9fc25c9f2af8b72c92) for this snippet + Invoke-RestMethod -Uri $subscriptionUrl -Method Get | Out-Null + + $endpointRequest = [System.Net.Webrequest]::Create("$subscriptionUrl") + $sslThumbprint = $endpointRequest.ServicePoint.Certificate.GetCertHashString() + $sslThumbprint = $sslThumbprint -replace '(..(?!$))', '$1:' + + $contentLibraryInput = @{ + Name = $contentLibraryName + Datastore = $datastore + AutomaticSync = $true + SubscriptionUrl = $subscriptionUrl + SslThumbprint = $sslThumbprint } + + New-ContentLibrary @contentLibraryInput -Server $vcfVcenterDetails.fqdn | Out-Null + } + elseif ($published) { + New-ContentLibrary -Name $contentLibraryName -Published -Datastore $datastore -Server $vcfVcenterDetails.fqdn | Out-Null + } + if (Get-ContentLibrary -Name $contentLibraryName -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue) { + Write-Output "Creating Content Library in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($contentLibraryName): SUCCESSFUL" } else { - Write-Warning "Enabling Embedded Harbour Registry in vCenter Server ($($vcfVcenterDetails.fqdn)) for Cluster ($cluster), already performed: SKIPPED" + Write-Error "Creating Content Library in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($contentLibraryName): POST_VALIDATION_FAILED" } } + else { + Write-Error "Unable to find Datastore named ($datastore) in vCenter Server ($($vcfVcenterDetails.fqdn)): PRE_VALIDATION_FAILED" + } + } + else { + Write-Warning "Creating Content Library in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($contentLibraryName), already exists: SKIPPED" } } Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue @@ -4449,26 +4425,31 @@ Function Enable-Registry { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Enable-Registry +Export-ModuleMember -Function Add-ContentLibrary -Function Undo-Registry { +Function Undo-ContentLibrary { <# .SYNOPSIS - Disable the embedded Harbor Registry on a Supervisor Cluster + Remove Content Library .DESCRIPTION - The Undo-Registry cmdlet disables the embedded Harbor Registry on a Supervisor Cluster + The Undo-ContentLibrary cmdlet removes a content library. The cmdlet connects to SDDC Manager using the + -server, -user, and -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to vCenter Server + - Deletes a content library .EXAMPLE - Undo-Registry -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 - This example disables the embedded Harbor Registry on Supervisor Cluster sfo-w01-cl01 with vSPhere Storage Policy vsphere-with-tanzu-policy + Undo-ContentLibrary -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -contentLibraryName sfo-w01-lib01 + This example removes the content library from the Workload Domain vCenter Server #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$contentLibraryName ) Try { @@ -4478,26 +4459,18 @@ Function Undo-Registry { if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) { if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { - if (Test-vSphereApiConnection -server $($vcfVcenterDetails.fqdn)) { - if (Test-vSphereApiAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { - $cluster = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.Name -eq $domain }).clusters.id) }).Name - if (Get-WMRegistry -cluster $cluster -ErrorAction Ignore) { - Remove-WMRegistry -cluster $cluster | Out-Null - Do { - $configStatus = Get-WMRegistry -cluster $cluster -ErrorAction Ignore #| Get-WMRegistryHealth -ErrorAction Ignore - } Until (!($configStatus)) - if (!(Get-WMRegistry -cluster $cluster -ErrorAction Ignore)) { - Write-Output "Disabling Embedded Harbour Registry in vCenter Server ($($vcfVcenterDetails.fqdn)) for Cluster ($cluster): SUCCESSFUL" - } - else { - Write-Error "Disabling Embedded Harbour Registry in vCenter Server ($($vcfVcenterDetails.fqdn)) for Cluster ($cluster): POST_VALIDATION_FAILED" - } - } - else { - Write-Warning "Disabling Embedded Harbour Registry in vCenter Server ($($vcfVcenterDetails.fqdn)) for Cluster ($cluster), already performed: SKIPPED" - } + if (Get-ContentLibrary -Name $contentLibraryName -ErrorAction Ignore) { + Remove-ContentLibrary -ContentLibrary $contentLibraryName -Server $vcfVcenterDetails.fqdn -Confirm:$false | Out-Null + if (!(Get-ContentLibrary -Name $contentLibraryName -ErrorAction Ignore)) { + Write-Output "Removing Content Library from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($contentLibraryName): SUCCESSFUL" + } + else { + Write-Error "Removing Content Library from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($contentLibraryName): POST_VALIDATION_FAILED" } } + else { + Write-Warning "Removing Content Library from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($contentLibraryName), does not exist: SKIPPED" + } } Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue } @@ -4513,55 +4486,493 @@ Function Undo-Registry { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Undo-Registry +Export-ModuleMember -Function Undo-ContentLibrary -Function Add-NamespaceVmClass { +Function Enable-SupervisorCluster { <# .SYNOPSIS - Add a Virtual Machine class to a Namespace + Enables Workload Management on a VCF cluster .DESCRIPTION - The Add-NamespaceVmClass cmdlet adds a Virtual Machine Class to a Namespace + The Enable-SupervisorCluster cmdlet enables Workload Management on a VCF cluster. The cmdlet connects to SDDC + Manager using the -server, -user, and -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to vCenter Server + - Validates that network connectivity and authentication is possible to NSX Management Cluster + - Performs validation of in puts unless skipped using a switch + - Enables Workload Management on the vSphere cluster .EXAMPLE - Add-NamespaceVmClass -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -namespace sfo-w01-tkc01 -vmClass guaranteed-small - This example adds the VM Class guaranteed-small to Supervisor Namespace sfo-tkc-01 in Workload domain sfo-w01 - #> + $wmClusterInput = @{ + server = "sfo-vcf01.sfo.rainpole.io" + user = "administrator@vsphere.local" + pass = 'VMw@re1!' + domain = "sfo-w01" + cluster = "sfo-w01-cl01" + sizeHint = "Tiny" + managementVirtualNetwork = "sfo-w01-kub-seg01" + managementNetworkMode = "StaticRange" + managementNetworkStartIpAddress = "192.168.20.10" + managementNetworkAddressRangeSize = 5 + managementNetworkGateway = "192.168.20.1" + managementNetworkSubnetMask = "255.255.255.0" + masterDnsName = "sfo-w01-cl01.sfo.rainpole.io" + masterDnsServers = @("172.16.11.4", "172.16.11.5") + masterNtpServers = @("172.16.11.253", "172.16.12.253") + contentLibrary = "Kubernetes" + ephemeralStoragePolicy = "vsphere-with-tanzu-storage-policy" + imageStoragePolicy = "vsphere-with-tanzu-storage-policy" + masterStoragePolicy = "vsphere-with-tanzu-storage-policy" + nsxEdgeCluster = "sfo-w01-ec01" + distributedSwitch = "sfo-w01-cl01-vds01" + podCIDRs = "100.100.0.0/20" + serviceCIDR = "100.200.0.0/22" + externalIngressCIDRs = "192.168.21.0/24" + externalEgressCIDRs = "192.168.22.0/24" + workerDnsServers = @("172.16.11.4", "172.16.11.5") + masterDnsSearchDomain = "sfo.rainpole.io" + } + + .EXAMPLE + Enable-SupervisorCluster @wmClusterInput + This example enables Workload Management on a vSphere Cluster in workload domain sfo-w01 + + .EXAMPLE + Enable-SupervisorCluster -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -sizeHint Tiny -managementVirtualNetwork sfo-w01-kub-seg01 -managementNetworkMode StaticRange -managementNetworkStartIpAddress 192.168.20.10 -managementNetworkAddressRangeSize 5 -managementNetworkGateway 192.168.20.1 -managementNetworkSubnetMask 255.255.255.0 -cluster sfo-w01-cl01 -contentLibrary Kubernetes -ephemeralStoragePolicy vsphere-with-tanzu-storage-policy -imageStoragePolicy vsphere-with-tanzu-storage-policy -masterStoragePolicy vsphere-with-tanzu-storage-policy -nsxEdgeCluster sfo-w01-ec01 -distributedSwitch sfo-w01-sfo-w01-vc01-sfo-w01-cl01-vds01 -podCIDRs "100.100.0.0/20" -serviceCIDR "100.200.0.0/22" -externalIngressCIDRs "192.168.21.0/24" -externalEgressCIDRs "192.168.22.0/24" -masterNtpServers @("172.16.11.253", "172.16.12.253") -masterDnsServers @("172.16.11.4", "172.16.11.5") -masterDnsName sfo-w01-cl01.sfo.rainpole.io -masterDnsSearchDomain sfo.rainpole.io -workerDnsServers @("172.16.11.4", "172.16.11.5") + This example enables Workload Management on a vSphere Cluster in workload domain sfo-w01 + #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$namespace, - [Parameter (Mandatory = $false)] [ValidateSet("guaranteed-medium","guaranteed-large","guaranteed-xlarge","best-effort-4xlarge","guaranteed-small","best-effort-medium","best-effort-2xlarge","guaranteed-2xlarge","best-effort-large","guaranteed-4xlarge","best-effort-8xlarge","best-effort-xsmall","guaranteed-xsmall","best-effort-xlarge","guaranteed-8xlarge","best-effort-small")] [String]$vmClass + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster, + [Parameter (Mandatory = $true)] [ValidateSet("Tiny", "Small", "Medium", "Large")] [String]$sizeHint, + [Parameter (Mandatory = $true)] [ValidateSet("DHCP", "StaticRange")][String]$managementNetworkMode, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$managementVirtualNetwork, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$managementNetworkStartIpAddress, + [Parameter (Mandatory = $true)] [ValidateRange(5,10)][int]$managementNetworkAddressRangeSize, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$managementNetworkGateway, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$managementNetworkSubnetMask, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Array]$masterDnsName, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Array]$masterNtpServers, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Array]$masterDnsServers, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$contentLibrary, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ephemeralStoragePolicy, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$imageStoragePolicy, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$masterStoragePolicy, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$nsxEdgeCluster, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$distributedSwitch, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$podCIDRs, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$serviceCIDR, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$externalIngressCIDRs, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$externalEgressCIDRs, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$masterDnsSearchDomain, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Array]$workerDnsServers, + [Parameter (Mandatory = $false)] [ValidateRange(300,18000)]$ConfigurationTimeoutSeconds=3600, + [Parameter (Mandatory = $false)] [Switch]$skipValidation, + [Parameter (Mandatory = $false)] [Switch]$validateOnly ) Try { if (Test-VCFConnection -server $server) { if (Test-VCFAuthentication -server $server -user $user -pass $pass) { - if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) { - if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) { - if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { - if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { - if (Test-vSphereApiConnection -server $($vcfVcenterDetails.fqdn)) { - if (Test-vSphereApiAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { - if (Get-WMNamespace -Name $namespace -ErrorAction Ignore) { - if (!(Get-VMClass -namespace $namespace | Where-Object {$_ -eq $vmClass})) { - Add-VMClass -namespace $namespace -vmClass $vmClass | Out-Null - if (Get-VMClass -namespace $namespace | Where-Object {$_ -eq $vmClass}) { - Write-Output "Adding Virtual Machine Class ($vmClass) to Namespace ($namespace): SUCCESSFUL" + if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) { + if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + Request-vSphereApiToken -Fqdn $vcfVcenterDetails.fqdn -Username $vcfVcenterDetails.ssoadmin -Password $vcfVcenterDetails.ssoAdminPass | Out-Null + if (($vcfNsxtDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain)) { + if (Test-NSXTConnection -server $vcfNsxtDetails.fqdn) { + if (Test-NSXTAuthentication -server $vcfNsxtDetails.fqdn -user $vcfNsxtDetails.adminUser -pass $vcfNsxtDetails.adminPass) { + [bool]$inputParameterValidation = $true + + #Check SkipValidation parameter + if (($SkipValidation.isPreset)) { + + # Validate if vCenter uses 'local' + if ($vcfVcenterDetails.fqdn) { + if (($vcfVcenterDetails.fqdn.split(".")[$_.count-1] -eq "local") -and ($masterDnsSearchDomain.split(".")[$_.count-1] -ne "local")) { + Write-Warning "'local' domain detected in ($(vcfVcenterDetails.fqdn)), make sure you have provided masterDnsSearchDomain ($masterDnsSearchDomain) to match" } - else { - Write-Error "Adding Virtual Machine Class ($vmClass) to Namespace ($namespace): POST_VALIDATION_FAILED" + } + + + # Validate management network inputs + # Valid Starting IP Address is an actual IPv4 address + if ($managementNetworkStartIpAddress) { + if (!(Test-IPaddressArray -IPaddressArray $managementNetworkStartIpAddress)) { + Write-Error "Invalid Management Network Start IP address ($managementNetworkStartIpAddress): PRE_VALIDATION_FAILED" + $inputParameterValidation = $false } } - else { - Write-Warning "Adding Virtual Machine Class ($vmClass) to Namespace ($namespace), already exists: SKIPPED" - } + + # Valid Subnet Mask + if ($managementNetworkSubnetMask) { + if (!(Test-IPaddressArray -IPaddressArray $managementNetworkSubnetMask)) { + Write-Error "Management Network Subnet Mask ($managementNetworkSubnetMask) validation failed: PRE_VALIDATION_FAILED" + $inputParameterValidation = $false + } + + } + + # Validate Gateway IP Address is an actual IPv4 address and exists in the same subnet as the management starting address + if ($managementNetworkGateway) { + Try { + if (Test-IPaddressArray $managementNetworkGateway) { + #Validate the Gateway IP address and the starting IP address are in the same subnet + $checkManagementNetworkGatewayInSubnet = $null + Try { + $checkManagementNetworkGatewayInSubnet = Test-IpAddress -IpAddress $managementNetworkGateway -Subnet "$managementNetworkStartIpAddress/$managementNetworkCidr" + } catch {} + + if ($checkManagementNetworkGatewayInSubnet.Validated -eq $false) { + Write-Error "Cannot validate the gateway IP address for the Management Network ($managementNetworkGateway) is from the same subnet as the Management Network Starting IP Address ($managementNetworkStartIpAddress/$managementNetworkCidr): PRE_VLALIDATION_FAILED" + $inputParameterValidation = $false + } + } + } + Catch { + Write-Error "Invalid IP address ($managementNetworkGateway) : PRE_VALIDATION_FAILED" + $inputParameterValidation = $false + } + } + + # Validate Management Virtual Network (dvPortGroup) exists + if ($ManagementVirtualNetwork) { + Try { + $checkManagementVirtualNetwork = Get-VirtualNetwork -Name $ManagementVirtualNetwork -ErrorAction SilentlyContinue + } + Catch { + #Do nothing + } + + if (!$checkManagementVirtualNetwork -or !$managementVirtualNetwork) { + Write-Error "Invalid Management Virtual Network ($ManagementVirtualNetwork): PRE_VALIDATION_FAILED" + $inputParameterValidation = $false + } + } + + # Validate Ephemeral Storage Policy exists + if ($ephemeralStoragePolicy){ + $checkEphemeralStoragePolicy = $null + Try { + $checkEphemeralStoragePolicy = Get-SpbmStoragePolicy -Name $EphemeralStoragePolicy -ErrorAction SilentlyContinue + } + Catch { + #Do nothing + } + + if (!$checkEphemeralStoragePolicy -or !$ephemeralStoragePolicy) { + Write-Error "Invalid Ephemeral Storage Policy ($EphemeralStoragePolicy): PRE_VALIDATION_FAILED" + $inputParameterValidation = $false + } + } + + # Validate Image Storage Policy exists + if ($imageStoragePolicy) { + $checkImageStoragePolicy = $null + Try { + $checkImageStoragePolicy = Get-SpbmStoragePolicy -Name $ImageStoragePolicy -ErrorAction SilentlyContinue + } + Catch { + #Do nothing + } + + if (!$checkImageStoragePolicy -or !$imageStoragePolicy) { + Write-Error "Invalid Image Storage Policy ($ImageStoragePolicy): PRE_VALIDATION_FAILED" + $inputParameterValidation = $false + } + } + + #Validate Master Storage Policy exists + if ($masterStoragePolicy) { + $checkMasterStoragePolicy = $null + Try { + $checkMasterStoragePolicy = Get-SpbmStoragePolicy -Name $MasterStoragePolicy -ErrorAction SilentlyContinue + } + Catch { + #Do nothing + } + + if (!$checkMasterStoragePolicy -or !$masterStoragePolicy) { + Write-Error "Invalid Master Storage Policy ($MasterStoragePolicy): PRE_VALIDATION_FAILED" + $inputParameterValidation = $false + } + } + + #Validate NSX Edge Cluster exists and lookup ID. TBD chech status of the Edge Cluster and TNs + if ($nsxEdgeCluster) { + $nsxEdgeClusterId = $null + $checkNsxEdgeCluster = $null + Try { + $checkNsxEdgeCluster = Get-NsxEdgeCluster -Name $nsxEdgeCluster -ErrorAction SilentlyContinue + $nsxEdgeClusterId = $checkNsxEdgeCluster.Id + } + Catch { + #Do nothing + } + + if (!$nsxEdgeClusterId -or !$nsxEdgeCluster) { + Write-Error "Invalid NSX Edge Cluster ($NsxEdgeCluster): PRE_VALIDATION_FAILED" + $inputParameterValidation = $false + } + } + + #Validate control plane NTP servers exist and are functional + if ($masterNtpServers) { + Foreach ($masterNtpServer in $masterNtpServers) { + $checkNtpServer = $null + $checkNtpServer = Test-ntpServer $masterNtpServer + if (!($checkNtpServer)) { + Write-Error "Invalid master NTP server ($masterNtpServer) : PRE_VALIDATION_FAILED" + $inputParameterValidation = $false + + } + } + } + + #Validate control plane DNS servers exist and are functional + if ($masterDnsServers) { + $checkDnsServers = $null + $checkDnsServers = Test-DnsServers $masterDnsServers + if (!($checkDnsServers)) { + Write-Error "Invalid master dns servers ($masterDnsServers) : PRE_VALIDATION_FAILED" + $inputParameterValidation = $false + } + } + + #Validate worker DNS servers exist and are functional + if ($workerDnsServers) { + $checkDnsServers = $null + $checkDnsServers = Test-DnsServers $workerDnsServers + if (!($checkDnsServers)) { + Write-Error "Invalid worker dns servers ($workerDnsServers) : PRE_VALIDATION_FAILED" + $inputParameterValidation = $false + } + } + + #Validate ContentLibrary exists + #Full validation (checking type, subscription, etc.) is TBD + if ($contentLibrary) { + $checkContentLibrary = $null + Try { + $checkContentLibrary = Get-SubscribedLibrary -Name $contentLibrary -ErrorAction SilentlyContinue + } + Catch { + Debug-ExceptionWriter -object $_ + } + if ($checkContentLibrary.Name -ne $contentLibrary -or !$contentLibrary) { + Write-Error "Invalid Content Library ($contentLibrary): PRE_VALIDATION_FAILED" + $inputParameterValidation = $false + } + } + + #Validate Distributed Virtual Switch exists + if ($distributedSwitch) { + $checkDistributedSwitch = $null + Try { + $checkDistributedSwitch = Get-VDSwitch -Name $distributedSwitch -ErrorAction SilentlyContinue + } + Catch { + Debug-ExceptionWriter -object $_ + } + if ($checkDistributedSwitch.Name -ne $distributedSwitch -or !$distributedSwitch) { + Write-Error "Invalid Virtual Distributed Switch ($distributedSwitch): PRE_VALIDATION_FAILED" + $inputParameterValidation = $false + } + } + + # Validates Pod subnet inputs are formatted correctly and sized to meet minimum requirements + if ($podCIDRs) { + $checkPodCidr = $null + $checkPodCidr = Test-WMSubnetInput -Subnet $podCIDRs -SubnetType "Pod" + if (!($checkPodCidr)) { + Write-Error "Invalid podCIDRs ($podCIDRs) : PRE_VALIDATION_FAILED" + $inputParameterValidation = $false + } + } + + # Validates Service subnet inputs are formatted correctly and sized to meet minimum requirements + if ($serviceCIDR) { + $checkServiceCidr = $null + $checkServiceCidr = Test-WMSubnetInput -Subnet $serviceCIDR -SubnetType "Service" + if (!($checkServiceCidr)) { + Write-Error "Invalid ServiceCIDR ($serviceCIDR) : PRE_VALIDATION_FAILED" + $inputParameterValidation = $false + } + } + + + # Validates Ingress subnet inputs are formatted correctly and sized to meet minimum requirements + if ($externalIngressCIDRs) { + $checkIngressCidr = $null + $checkIngressCidr = Test-WMSubnetInput -Subnet $serviceCIDR -SubnetType "Ingress" + if (!($checkIngressCidr)) { + Write-Error "Invalid IngressCIDR ($externalIngressCIDRs) : PRE_VALIDATION_FAILED" + $inputParameterValidation = $false + } + } + + + # Validates Egress subnet inputs are formatted correctly and sized to meet minimum requirements + if ($externalEgressCIDRs) { + $checkEgressCidr = $null + $checkEgressCidr = Test-WMSubnetInput -Subnet $externalEgressCIDRs -SubnetType "Egress" + if (!($checkEgressCidr)) { + Write-Error "Invalid EgressCIDR ($externalEgressCIDRs) : PRE_VALIDATION_FAILED" + $inputParameterValidation = $false + } + } + + #Validate control plane Kubernetes API endpoint is valid and in DNS + # TBD as this is not mandatory parameter + if ($masterDnsName) { + + foreach ($dnsName in $masterDnsName) { + $checkDnsName = $null + + Try { + $checkDnsName = Resolve-DnsName -Name $DnsName -Type A -QuickTimeout -ErrorAction Stop + } + Catch [System.ComponentModel.Win32Exception] { + Write-Error "Invalid control plane DNS name ($DnsName): PRE_VALIDATION_FAILED" + $inputParameterValidation = $false + } + + + if ($checkDnsName) { + $checkMasterIpAddress = $null + Try { + $checkMasterIpAddress = Test-IpAddress -IpAddress $checkDnsName.Answers[0].Address.IPAddressToString -Subnet $externalIngressCIDRs + } + Catch { + #Do nothing + } + + if ($checkMasterIpAddress.Validated -eq $false) { + Write-Error -Message "Cannot validate the IP address for $DnsName ($DnsNameIpAddress) is from the external ingress CIDR ($externalIngressCIDRs). : PRE_VALIDATION_FAILED" + $inputParameterValidation = $false + } + } + } + } + + #Validate master DNS search domain is formatted correctly and exists in DNS + if ($masterDnsSearchDomain) { + $checkMasterDnsSearchDomain = $null + + Try { + $checkMasterDnsSearchDomain = Resolve-DnsName -Name $masterDnsSearchDomain -Type A -QuickTimeout -ErrorAction Stop + } + Catch [System.ComponentModel.Win32Exception] { + Write-Error "Invalid control plane DNS search domain ($masterDnsSearchDomain): PRE_VALIDATION_FAILED" + $inputParameterValidation = $false + } + + + } + + #Validate vSphere license is in place + + Try { + $checkLicense = Get-WMLicenseStatus -server $server -domain $domain -ErrorAction SilentlyContinue + + if ($checkLicense.namespaces_licensed -eq $false) { + Write-Error -Message "The vSphere license applied to cluster $cluster does not support Workload Management or is expired. Please resolve this and try again : PRE_VALIDATION_FAILED" + $inputParameterValidation = $false + } + elseif ($checklicense.namespaces_supported -eq $false) { + Write-Error -Message "The cluster $cluster does not support Workload Management. Please resolve this and try again. : PRE_VALIDATION_FAILED" + $inputParameterValidation = $false + } + } + Catch { + Debug-ExceptionWriter -object $_ + } + + #Validate the cluster is present + if ($cluster) { + $checkCluster = $null + Try { + $checkCluster = Get-Cluster -Name $cluster -ErrorAction SilentlyContinue + } + Catch { + #Do nothing + } + + if (!$checkCluster -or ($checkCluster.Name -ne $cluster)) { + Write-Error "Invalid vSphere cluster $cluster. : PRE_VALIDATION_FAILED" + $inputParameterValidation = $false + } + + $checkWmCluster = $null + Try { + $checkWmCluster = Get-WMCluster -Cluster $cluster -ErrorAction SilentlyContinue + } + Catch { + #Do nothing + } + if ($checkWmCluster) { + Write-Error "Cluster $cluster is already enabled for Workload management : PRE_VALIDATION_FAILED" + $inputParameterValidation = $false + } + } + + + + # If any of the prevalidation failed + if ($inputParameterValidation) { + Write-Output "Pre-validation : SUCESSFULL" + } + else { + Write-Error "At least one input parameter validation failed : PRE_VALIDATION_FAILED" + Break + } + } + + # TBD MasterDnsServerIpAddress = $masterDnsServers + if ($inputParameterValidation) { + $internalWMClusterInput = @{ + SizeHint = $SizeHint + ManagementVirtualNetwork = (Get-VirtualNetwork -Name $managementVirtualNetwork) + ManagementNetworkMode = $managementNetworkMode + ManagementNetworkStartIpAddress = $managementNetworkStartIpAddress + ManagementNetworkAddressRangeSize = $managementNetworkAddressRangeSize + ManagementNetworkGateway = $managementNetworkGateway + ManagementNetworkSubnetMask = $managementNetworkSubnetMask + MasterDnsNames = $masterDnsName + MasterNtpServer = $masterNtpServers + Cluster = (Get-Cluster -Name $cluster) + ContentLibrary = $contentLibrary + EphemeralStoragePolicy = (Get-SpbmStoragePolicy -Name $ephemeralStoragePolicy) + ImageStoragePolicy = (Get-SpbmStoragePolicy -Name $imageStoragePolicy) + MasterStoragePolicy = (Get-SpbmStoragePolicy -Name $masterStoragePolicy) + NsxEdgeClusterId = ((Get-NsxEdgeCluster -Name $nsxEdgeCluster).id) + DistributedSwitch = (Get-VDSwitch -Name $distributedSwitch) + PodCIDRs = $podCIDRs + ServiceCIDR = $serviceCIDR + ExternalIngressCIDRs = $externalIngressCIDRs + ExternalEgressCIDRs = $externalEgressCIDRs + WorkerDnsServer = $workerDnsServers + MasterDnsServerIpAddress = $masterDnsServers + MasterDnsSearchDomain = $masterDnsSearchDomain + } + + } + + if ($ValidateOnly.isPresent) { + Write-Output "Validation completed : SUCCESSFUL" } else { - Write-Error "Unable to find Namespace ($namespace) in vCenter Server ($($vcfVcenterDetails.fqdn)): PRE_VALIDATION_FAILED" + Enable-WMCluster @internalWMClusterInput -RunAsync -ConfigurationTimeoutSeconds $ConfigurationTimeoutSeconds | Out-Null + Write-Output "Submitted Creation of Supervisor Cluster $cluster in vCenter Server $($vcfVcenterDetails.fqdn). This may take a while to complete. Operation will timeout after ($ConfigurationTimeoutSeconds) seconds" + $startSleep = 300 + $SleepTime = 60 + Start-Sleep $startSleep + if (Get-WMCluster -Cluster $cluster -ErrorAction SilentlyContinue) { + Watch-WmClusterConfigStatus -wmClusterName $cluster -sleepTime $SleepTime -retriesCount (($ConfigurationTimeoutSeconds-$startSleep)/$sleepTime) + } } } } @@ -4571,24 +4982,28 @@ Function Add-NamespaceVmClass { } } } - } - Catch { - Write-Error $_.Exception.Response + } Catch { + Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-NamespaceVmClass +Export-ModuleMember -Function Enable-SupervisorCluster -Function Add-TanzuKubernetesCluster { +Function Undo-SupervisorCluster { <# .SYNOPSIS - Create a new Tanzu Kubernetes Cluster on a Supervisor Cluster + Remove Supervisor Cluster .DESCRIPTION - The Add-TanzuKubernetesCluster cmdlet creates a new Tanzu Kubernetes Cluster on a Supervisor Cluster + The Undo-SupervisorCluster cmdlet removes the Supervisor Cluster from a Workload Domain. The cmdlet connects to + SDDC Manager using the -server, -user, and -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to vCenter Server + - Performs validation of in puts unless skipped using a switch + - Disables Workload Management on the vSphere cluster .EXAMPLE - Add-TanzuKubernetesCluster -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -cluster sfo-w01-cl01 -yaml .\SampleYaml\sfo-w01-tkc01-cluster.yaml - This example creates a Tanzu Kubernetes cluster based on the YAML file .\SampleYaml\sfo-w01-tkc01-cluster.yaml as the vSphere SSO user administrator@vsphere.local on Supervisor Cluster sfo-w01-cl01 + Undo-SupervisorCluster -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -cluster sfo-w01-cl01 + This example disables Workload Management on a vSphere Cluster in workload domain sfo-w01 #> Param ( @@ -4597,19 +5012,9 @@ Function Add-TanzuKubernetesCluster { [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$yaml + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$RunAsync ) - if (!$PsBoundParameters.ContainsKey("yaml")) { - $yaml = Get-ExternalFileName -title "Select the YAML File (.yaml)" -fileType "yaml" -location "default" - } - else { - if (!(Test-Path -Path $yaml)) { - Write-Error "YAML File '$yaml' File Not Found" - Break - } - } - Try { if (Test-VCFConnection -server $server) { if (Test-VCFAuthentication -server $server -user $user -pass $pass) { @@ -4617,12 +5022,29 @@ Function Add-TanzuKubernetesCluster { if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) { if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { - Connect-WMCluster -cluster $cluster -user $user -pass $pass | Out-Null - New-TanzuKubernetesCluster -YAML $yaml | Out-Null - Write-Output "Creating Tanzu Kubernetes Cluster in Supervisor Cluster ($cluster) using YAMP ($yaml): SUCCESSFUL" + if (Test-vSphereApiConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-vSphereApiAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + if (Get-WMCluster -cluster $cluster -ErrorAction Ignore) { + if (!$PsBoundParameters.ContainsKey("RunAsync")) { + Disable-WMCluster -WMCluster $cluster -RunAsync -Server $vcfVcenterDetails.fqdn -Confirm:$false | Out-Null + } + else { + Disable-WMCluster -WMCluster $cluster -Server $vcfVcenterDetails.fqdn -Confirm:$false | Out-Null + } + if (!(Get-WMCluster -cluster $cluster -ErrorAction Ignore)) { + Write-Output "Removing Supervisor Cluster ($cluster) from vCenter Server ($($vcfVcenterDetails.fqdn)): SUCCESSFUL" + } + else { + Write-Error "Removing Supervisor Cluster ($cluster) from vCenter Server ($($vcfVcenterDetails.fqdn)): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Removing Supervisor Cluster ($cluster) from vCenter Server ($($vcfVcenterDetails.fqdn)), does not exist: SKIPPED" + } + } + } } Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue - Disconnect-WMCluster | Out-Null } } } @@ -4636,19 +5058,23 @@ Function Add-TanzuKubernetesCluster { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-TanzuKubernetesCluster +Export-ModuleMember -Function Undo-SupervisorCluster -Function Undo-TanzuKubernetesCluster { +Function New-SupervisorClusterCSR { <# .SYNOPSIS - Remove a Tanzu Kubernetes Cluster + Create a new certificate signing request for the defined Supervisor Cluster .DESCRIPTION - The Undo-TanzuKubernetesCluster cmdlet removes a new Tanzu Kubernetes Cluster + The New-SupervisorClusterCSR cmdlet creates a new certificate signing request for the defined Supervisor + Cluster. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to vCenter Server + - Requests the certificate signing request file .EXAMPLE - Undo-TanzuKubernetesCluster -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -cluster sfo-w01-cl01 -namespace sfo-w01-tkc01 -tkc sfo-w01-tkc01 - This example removes a Tanzu Kubernetes Cluster from the a Supervisor Cluster + New-SupervisorClusterCSR -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -cluster sfo-w01-cl01 -commonName sfo-m01-cl01.sfo.rainpole.io -organization Rainpole -organizationalUnit Rainpole -country US -stateOrProvince California -locality "Palo Alto" -adminEmailAddress admin@rainpole.io -keySize 2048 -filePath ".\SupervisorCluster.csr" + This example returns a certificate signing request for the Supervisor Cluster sfo-w01-cl01 in Workload domain sfo-w01 #> Param ( @@ -4657,8 +5083,15 @@ Function Undo-TanzuKubernetesCluster { [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$namespace, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tkc + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$commonName, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$organization, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$organizationalUnit, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$country, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$stateOrProvince, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$locality, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$adminEmailAddress, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$keySize, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$filePath ) Try { @@ -4668,27 +5101,24 @@ Function Undo-TanzuKubernetesCluster { if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) { if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { - if (Get-WMCluster -cluster $cluster -Server $vcfVcenterDetails.fqdn -ErrorAction Ignore) { - Connect-WMCluster -cluster $cluster -user $user -pass $pass | Out-Null - if (Get-TanzuKubernetesCluster -name $namespace -tkc $tkc -ErrorAction Ignore | Out-Null ) { - Remove-TanzuKubernetesCluster -cluster $tkc -namespace $namespace | Out-Null - if (!(Get-TanzuKubernetesCluster -name $namespace -tkc $tkc -ErrorAction Ignore | Out-Null )) { - Write-Output "Removing Tanzu Kubernetes Cluster from Supervisor Cluster ($cluster) Namespace ($namespace) called ($tkc): SUCCESSFUL" + if (Test-vSphereApiConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-vSphereApiAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + if ($PsBoundParameters.ContainsKey("keySize")) { + Request-WMClusterCSR -cluster $cluster -commonName $commonName -organization $organization -organizationalUnit $organizationalUnit -country $country -stateOrProvince $stateOrProvince -locality $locality -adminEmailAddress $adminEmailAddress -keySize $keySize -filePath $filePath | Out-Null } else { - Write-Error "Removing Tanzu Kubernetes Cluster from Supervisor Cluster ($cluster) Namespace ($namespace) called ($tkc): POST_VALIDATION_FAILED" + Request-WMClusterCSR -cluster $cluster -commonName $commonName -organization $organization -organizationalUnit $organizationalUnit -country $country -stateOrProvince $stateOrProvince -locality $locality -adminEmailAddress $adminEmailAddress -filePath $filePath | Out-Null + } + if (Test-Path -Path $filePath) { + Write-Output "Creating Certificate Signing Request (.csr) file for ($commonName) to file ($filePath): SUCCESSFUL" + } + else { + Write-Error "Creating Certificate Signing Request (.csr) file for ($commonName) to file ($filePath): POST_VALIDATION_FAILED" } } - else { - Write-Warning "Removing Tanzu Kubernetes Cluster from Supervisor Cluster ($cluster) Namespace ($namespace) called ($tkc), does not exist: SKIPPED" - } - } - else { - Write-Warning "Workload Management is not enabled on Cluster ($server) in vCenter Server ($($vcfVcenterDetails.fqdn))" } } Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue - Disconnect-WMCluster | Out-Null } } } @@ -4702,319 +5132,245 @@ Function Undo-TanzuKubernetesCluster { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Undo-TanzuKubernetesCluster - -########################################## E N D O F F U N C T I O N S ########################################## -####################################################################################################################### - - -####################################################################################################################### -################# I N T E L L I G E N T L O G G I N G & A N A L Y T I C S F U N C T I O N S ################ +Export-ModuleMember -Function New-SupervisorClusterCSR -Function Export-vRLIJsonSpec { +Function Request-SignedCertificate { <# .SYNOPSIS - Create vRealize Log Insight Deployment JSON specification using the Planning and Preparation workbook + Request a Signed Certificate from a Microsoft Enterprise Certificate Authority by providing generated + Certificate Signing Request (CSR) file. .DESCRIPTION - The Export-vRLIJsonSpec cmdlet creates the JSON specification file using the Planning and Preparation workbook - to deploy vRealize Log Insight using vRealize Suite Lifecycle Manager. The cmdlet connects to SDDC Manager - using the -server, -user, and -password values. - - Validates that the Planning and Preparation provided is available - - Validates that network connectivity and authentication is possible to SDDC Manager - - Validates that vRealize Suite Lifecycle Manager has been deployed in VCF-aware mode and retrieves its details - - Validates that network connectivity and authentication is possible to vRealize Suite Lifecycle Manager - - Validates that the License, Certificate and Password in the Planning and Prep Preparation workbook have been - created in vRealize Suite Lifecycle Manager Locker - - Generates the deployment JSON specification file using the Planning and Preparation workbook and details - from vRealize Suite Lifecycle Manager named 'vrliDeploymentSpec.json' + The Request-SignedCertificate cmdlet requests a Signed Certificate from a Microsoft Enterprise Certificate + Authority by providing Certificate Signing Request (CSR) file. Issued certificate is written to Base64-encoded + output file. .EXAMPLE - Export-vRLIJsonSpec -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -workbook .\pnp-workbook.xlsx - This example creates a JSON specification file for deploying vRealize Log Insight using the Planning and Preparation Workbook data + Request-SignedCertificate -mscaComputerName dc-rpl01.rainpole.io -mscaName rainpole-DC-RPL01-CA -domainUsername "administrator@rainpole.io" -domainPassword "VMw@re1!" -certificateTemplate VMware -certificateRequestFile "c:\temp\SupervisorCluster.csr" -CertificateFile "c:\temp\SupervisorCluster.cer" + This example requests a Signed Certificate from a Microsoft Enterprise Certificate Authority providing certificate signing request in file "c:\temp\SupervisorCluster.csr" and if the CA policy is configured to automaticaly issue certificate the certificate will be issued to Base64-encoded output file "c:\temp\SupervisorCluster.cer" #> - Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$workbook + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$mscaComputerName, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$mscaName, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domainUsername, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domainPassword, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$certificateTemplate = "webserver", + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$certificateRequestFile, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$certificateFile, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$SkipValidation, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$ValidateOnly ) Try { - - if (!$PsBoundParameters.ContainsKey("workbook")) { - $workbook = Get-ExternalFileName -title "Select the Planning and Preparation Workbook (.xlsx)" -fileType "xlsx" -location "default" - } - else { - if (!(Test-Path -Path $workbook)) { - Write-Error "Planning and Preparation Workbook (.xlsx) '$workbook' File Not Found" - Break + [Bool]$preValidation = $true + if (!($SkipValidation.IsPresent)) { + # Validate if CSR exists + if (!(Test-Path -Path $certificateRequestFile -ErrorAction SilentlyContinue)) { + Write-Error "Certificate Signning Request (CSR) file ($certificateRequestFile) not found: PRE_VALIDATION_FAILED" + $preValidation = $false + } + # Validate if output file exisits + if ((Test-Path -Path $certificateFile -ErrorAction SilentlyContinue)) { + Write-Error "Certificate file ($certificateFile) already exists: PRE_VALIDATION_FAILED" + $preValidation = $false + } + # Validate if can get Win32_ComputerSystem + if ((Get-WmiObject Win32_ComputerSystem -ComputerName $mscaComputerName -ErrorAction SilentlyContinue).Status -ne "OK") { + Write-Error "Getting Win32_ComputerSystem object for ($mscaComputerName): PRE_VALIDATION_FAILED" + $preValidation = $false + } + # Validate if can connect on port 135 + if ((Test-NetConnection -ComputerName $mscaComputerName -Port 135 -ErrorAction SilentlyContinue).TcpTestSucceeded -ne $true) { + Write-Error "Connecting to ($mscaComputerName) on port 135: PRE_VALIDATION_FAILED" + $preValidation = $false } } - - $pnpWorkbook = Open-ExcelPackage -Path $workbook - - ### Obtain Configuration Information from vRealize Suite Lifecycle Manager - if (Test-VCFConnection -server $server) { - if (Test-VCFAuthentication -server $server -user $user -pass $pass) { - if (($vcfVrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass)) { - if (Test-vRSLCMConnection -server $vcfVrslcmDetails.fqdn) { - if (Test-vRSLCMAuthentication -server $vcfVrslcmDetails.fqdn -user $vcfVrslcmDetails.adminUser -pass $vcfVrslcmDetails.adminPass) { - if ($pnpWorkbook.Workbook.Names["vrli_license"].Value) { - $licenseKey = $pnpWorkbook.Workbook.Names["vrli_license"].Value - } - else { - $licenseKey = $pnpWorkbook.Workbook.Names["vrs_license"].Value - } - $vrliLicense = Get-vRSLCMLockerLicense | Where-Object {$_.key -eq $licenseKey} - if ($vrliLicense.key -eq $licenseKey) { - if ($vrliCertificate = Get-vRSLCMLockerCertificate | Where-Object {$_.alias -eq $pnpWorkbook.Workbook.Names["region_vrli_virtual_hostname"].Value}) { - if ($vrliPassword = Get-vRSLCMLockerPassword -alias $pnpWorkbook.Workbook.Names["region_vrli_admin_password_alias"].Value) { - $vcCredentials = Get-vRSLCMLockerPassword -alias (($pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value).Split(".")[0] + "-" + $pnpWorkbook.Workbook.Names["mgmt_datacenter"].Value) - $datacenterName = Get-vRSLCMDatacenter | Where-Object {$_.dataCenterName -eq $pnpWorkbook.Workbook.Names["mgmt_datacenter"].Value} - - $infrastructurePropertiesObject = @() - $infrastructurePropertiesObject += [pscustomobject]@{ - 'dataCenterVmid' = $datacenterName.dataCenterVmid - 'regionName' = "default" - 'zoneName' = "default" - 'vCenterName' = ($pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value).Split(".")[0] - 'vCenterHost' = $pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value - 'vcUsername' = $vcCredentials.userName - 'vcPassword' = ("locker:password:" + $($vcCredentials.vmid) + ":" + $($vcCredentials.alias)) - 'acceptEULA' = "true" - 'enableTelemetry' = "true" - 'defaultPassword' = ("locker:password:" + $($vrliPassword.vmid) + ":" + $($vrliPassword.alias)) - 'certificate' = ("locker:certificate:" + $($vrliCertificate.vmid) + ":" + $($vrliCertificate.alias)) - 'cluster' = ($pnpWorkbook.Workbook.Names["mgmt_datacenter"].Value + "#" + $pnpWorkbook.Workbook.Names["mgmt_cluster"].Value) - 'storage' = $pnpWorkbook.Workbook.Names["mgmt_vsan_datastore"].Value - 'diskMode' = "thin" - 'network' = $pnpWorkbook.Workbook.Names["reg_seg01_name"].Value - 'masterVidmEnabled' = "false" - 'dns' = ($pnpWorkbook.Workbook.Names["region_dns1_ip"].Value + "," + $pnpWorkbook.Workbook.Names["region_dns2_ip"].Value) - 'domain' = $pnpWorkbook.Workbook.Names["region_ad_child_fqdn"].Value - 'gateway' = $pnpWorkbook.Workbook.Names["reg_seg01_gateway_ip"].Value - 'netmask' = $pnpWorkbook.Workbook.Names["reg_seg01_mask_overlay_backed"].Value - 'searchpath' = $pnpWorkbook.Workbook.Names["child_dns_zone"].Value - 'timeSyncMode' = "ntp" - 'ntp' = $pnpWorkbook.Workbook.Names["region_ntp1_server"].Value - 'isDhcp' = "false" - 'vcfProperties' = '{"vcfEnabled":true,"sddcManagerDetails":[{"sddcManagerHostName":"' + $pnpWorkbook.Workbook.Names["sddc_mgr_fqdn"].Value + '","sddcManagerName":"default","sddcManagerVmid":"default"}]}' - } - - $infrastructureObject = @() - $infrastructureObject += [pscustomobject]@{ - 'properties' = ($infrastructurePropertiesObject | Select-Object -Skip 0) - } - - ### Generate the Properties Details - $productPropertiesObject = @() - $productPropertiesObject += [pscustomobject]@{ - 'certificate' = ("locker:certificate:" + $($vrliCertificate.vmid) + ":" + $($vrliCertificate.alias)) - 'productPassword' = ("locker:password:" + $($vrliPassword.vmid) + ":" + $($vrliPassword.alias)) - 'adminEmail' = $pnpWorkbook.Workbook.Names["region_vrli_admin_email"].Value - 'fipsMode' = "false" - 'licenseRef' = ("locker:license:" + $($vrliLicense.vmid) + ":" + $($vrliLicense.alias)) - 'nodeSize' = $pnpWorkbook.Workbook.Names["region_vrli_appliance_size"].Value.ToLower() - 'configureClusterVIP' = "false" - 'affinityRule' = $false - 'isUpgradeVmCompatibility' = $false - 'vrliAlwaysUseEnglish' = $false - 'masterVidmEnabled' = $false - 'configureAffinitySeparateAll' = "true" - 'ntp' = $pnpWorkbook.Workbook.Names["region_ntp1_server"].Value - 'timeSyncMode' = "ntp" - } - - #### Generate vRealize Log Insight Cluster Details - $clusterVipProperties = @() - $clusterVipProperties += [pscustomobject]@{ - 'hostName' = $pnpWorkbook.Workbook.Names["region_vrli_virtual_fqdn"].Value - 'ip' = $pnpWorkbook.Workbook.Names["region_vrli_virtual_ip"].Value - } - - $clusterVipsObject = @() - $clusterVipsObject += [pscustomobject]@{ - 'type' = "vrli-cluster-1" - 'properties' = ($clusterVipProperties | Select-Object -Skip 0) - } - - $clusterObject = @() - $clusterObject += [pscustomobject]@{ - 'clusterVips' = $clusterVipsObject - } - - #### Generate vRealize Log Insight Node Details - $masterProperties = @() - $masterProperties += [pscustomobject]@{ - 'vmName' = $pnpWorkbook.Workbook.Names["region_vrli_nodea_hostname"].Value - 'hostName' = $pnpWorkbook.Workbook.Names["region_vrli_nodea_fqdn"].Value - 'ip' = $pnpWorkbook.Workbook.Names["region_vrli_nodea_ip"].Value - 'folderName' = $pnpWorkbook.Workbook.Names["region_vrli_vm_folder"].Value - } - - $worker1Properties = @() - $worker1Properties += [pscustomobject]@{ - 'vmName' = $pnpWorkbook.Workbook.Names["region_vrli_nodeb_hostname"].Value - 'hostName' = $pnpWorkbook.Workbook.Names["region_vrli_nodeb_fqdn"].Value - 'ip' = $pnpWorkbook.Workbook.Names["region_vrli_nodeb_ip"].Value - } - - $worker2Properties = @() - $worker2Properties += [pscustomobject]@{ - 'vmName' = $pnpWorkbook.Workbook.Names["region_vrli_nodec_hostname"].Value - 'hostName' = $pnpWorkbook.Workbook.Names["region_vrli_nodec_fqdn"].Value - 'ip' = $pnpWorkbook.Workbook.Names["region_vrli_nodec_ip"].Value - } - - $nodesObject = @() - $nodesobject += [pscustomobject]@{ - 'type' = "vrli-master" - 'properties' = ($masterProperties | Select-Object -Skip 0) - } - $nodesobject += [pscustomobject]@{ - 'type' = "vrli-worker" - 'properties' = ($worker1Properties | Select-Object -Skip 0) - } - $nodesobject += [pscustomobject]@{ - 'type' = "vrli-worker" - 'properties' = ($worker2Properties | Select-Object -Skip 0) - } - - #### Generate the vRealize Log Insight Properties Section - $vcfVersion = ((Get-VCFManager).version -Split ('\.\d{1}\-\d{8}')) -split '\s+' -match '\S' - if ($vcfVersion -eq "4.3.0") { $vrliVersion = "8.4.0"} - if ($vcfVersion -eq "4.3.1") { $vrliVersion = "8.4.1"} - if ($vcfVersion -eq "4.4.0") { $vrliVersion = "8.6.2"} - $productsObject = @() - $productsObject += [pscustomobject]@{ - 'id' = "vrli" - 'version' = $vrliVersion - 'properties' = ($productPropertiesObject | Select-Object -Skip 0) - 'clusterVIP' = ($clusterObject | Select-Object -Skip 0) - 'nodes' = $nodesObject - } - - $vrliDeploymentObject = @() - $vrliDeploymentObject += [pscustomobject]@{ - 'environmentName' = $pnpWorkbook.Workbook.Names["vrslcm_reg_env"].Value - 'infrastructure' = ($infrastructureObject | Select-Object -Skip 0) - 'products' = $productsObject - } - - $vrliDeploymentObject | ConvertTo-Json -Depth 12 | Out-File -Encoding UTF8 -FilePath "vrliDeploymentSpec.json" - - Close-ExcelPackage $pnpWorkbook -NoSave -ErrorAction SilentlyContinue - Write-Output "Creation of Deployment JSON Specification file for vRealize Log Insight: SUCCESSFUL" - } - else { - Write-Error "Unable to find Admin Password with alias ($($pnpWorkbook.Workbook.Names["region_vrli_admin_password_alias"].Value)) in the vRealize Suite Lifecycle Manager Locker: PRE_VALIDATION_FAILED" - } - } - else { - Write-Error "Unable to find Certificate with alias ($($pnpWorkbook.Workbook.Names["region_vrli_virtual_hostname"].Value)) in the vRealize Suite Lifecycle Manager Locker: PRE_VALIDATION_FAILED" - } - } - else { - Write-Error "Unable to find License key ($licenseKey) in the vRealize Suite Lifecycle Manager Locker: PRE_VALIDATION_FAILED" - } - } - } + if ($preValidation) { + if (!($ValidateOnly.isPresent)) { + $CertificateAttributes = "CertificateTemplate:$certificateTemplate" + $commandToExecute = "certreq -submit -f -q -UserName $domainUsername -p $domainPassword -config `"$mscaComputerName`\$mscaName`" -attrib `"$CertificateAttributes`" $certificateRequestFile $certificateFile" + $resultExecution = Invoke-Expression -Command $commandToExecute + Start-Sleep 5 + if ($resultExecution -match "(Issued)") { + Write-Output "Issued certificate ($certificateFile): SUCCESSFUL" + } + else { + Write-Error "Certificate issuing to file ($certificateFile) failed with ($resultExecution): FAILED" + break } } + else { + Write-Output "Pre-validate Only: SUCCESSFUL" + } + } + else { + Write-Error "At least one Pre-Validation check failed: PRE_VALIDATION_FAILED" + break } } Catch { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Export-vRLIJsonSpec +Export-ModuleMember -Function Request-SignedCertificate -Function New-vRLIDeployment { +Function Install-SupervisorClusterCertificate { <# .SYNOPSIS - Deploy vRealize Log Insight Cluster via vRealize Suite Lifecycle Manager + Add a signed TLS certificate for the defined Supervisor Cluster .DESCRIPTION - The New-vRLIDeployment cmdlet deploys vRealize Log Insight via vRealize Suite Lifecycle Manager. The cmdlet - connects to SDDC Manager using the -server, -user, and -password values. - - Validates that the Planning and Preparation provided is available + The Install-SupervisorClusterCertificate cmdlet adds a signed TLS certificate for the defined Supervisor + Cluster. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - Validates that network connectivity and authentication is possible to SDDC Manager - - Validates that vRealize Suite Lifecycle Manager has been deployed in VCF-aware mode and retrieves its details - - Validates that network connectivity and authentication is possible to vRealize Suite Lifecycle Manager - - Validates that the environment does not already exist in vRealize Suite Lifecycle Manager - - Requests a new deployment of vRealize Log Insight via vRealize Suite Lifecycle Manager + - Validates that network connectivity and authentication is possible to vCenter Server + - Installs the Signed Certificate to the Supervisor Cluster .EXAMPLE - New-vRLIDeployment -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -workbook .\pnp-workbook.xlsx - This example starts a deployment of vRealize Log Inisght via vRealize Suite Lifecycle Manager using the Planning and Preparation Workbook data + Install-SupervisorClusterCertificate -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -Cluster sfo-w01-cl01 -FilePath ".\SupervisorCluster.cer" + This example applies the signed TLS certificate to Supervisor Cluster sfo-w01-cl01 in Workload domain sfo-w01 #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$workbook, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$monitor + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$filePath ) - Try { - - if (!$PsBoundParameters.ContainsKey("workbook")) { - $workbook = Get-ExternalFileName -title "Select the Planning and Preparation Workbook (.xlsx)" -fileType "xlsx" -location "default" + if (!$PsBoundParameters.ContainsKey("filePath")) { + $filePath = Get-ExternalFileName -title "Select the Supervisor Cluster Certificate File (.cer)" -fileType "cer" -location "default" + } + elseif ($PsBoundParameters.ContainsKey("filePath")) { + if (!(Test-Path -Path $filePath)) { + Write-Error "Certificate (cer) file for the Supervisor Cluster '$filePath' File Not Found" + Break } - else { - if (!(Test-Path -Path $workbook)) { - Write-Error "Planning and Preparation Workbook (.xlsx) ($workbook), File Not Found" - Break + } + + Try { + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) { + if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) { + if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + Request-vSphereApiToken -fqdn $vcfVcenterDetails.fqdn -username $vcfVcenterDetails.ssoAdmin -password $vcfVcenterDetails.ssoAdminPass | Out-Null + $response = Install-WMClusterCertificate -cluster $cluster -filePath $filePath + if ($response -match "successfully applied") { + Write-Output "Installing Signed Certificate ($filePath) to Supervisor Cluster ($cluster): SUCCESSFUL" + } + else { + Write-Error "Installing Signed Certificate ($filePath) to Supervisor Cluster ($cluster): POST_VALIDATION_FAILED" + } + } + Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue + } + } + } + else { + Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" + } } } + } + Catch { + Debug-ExceptionWriter -object $_ + } +} +Export-ModuleMember -Function Install-SupervisorClusterCertificate +Function Add-SupervisorClusterLicense { + <# + .SYNOPSIS + Adds a Supervisor Cluster license + + .DESCRIPTION + The Add-SupervisorClusterLicense cmdlet adds a Supervisor Cluster licence.. The cmdlet connects to SDDC Manager + using the -server, -user, and -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to vCenter Server + - Adds a new Supervisor Cluster license + + .EXAMPLE + Add-SupervisorClusterLicense -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -Cluster sfo-w01-cl01 -LicenseKey "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX" + This example adds a license to the Supervisor Cluster sfo-w01-cl01 in Workload domain sfo-w01 + #> + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$licenseKey + ) + Try { if (Test-VCFConnection -server $server) { if (Test-VCFAuthentication -server $server -user $user -pass $pass) { - if (($vcfVrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass)) { - if (Test-vRSLCMConnection -server $vcfVrslcmDetails.fqdn) { - if (Test-vRSLCMAuthentication -server $vcfVrslcmDetails.fqdn -user $vcfVrslcmDetails.adminUser -pass $vcfVrslcmDetails.adminPass) { - Export-vRLIJsonSpec -server $server -user $user -pass $pass -workbook $workbook | Out-Null - $json = (Get-Content -Raw .\vrliDeploymentSpec.json) - $jsonSpec = $json | ConvertFrom-Json - if (!($environmentExists = (Get-vRSLCMEnvironment | Where-Object {$_.environmentName -eq $($jsonSpec.environmentName)}))) { - if (Get-vRSLCMLockerPassword -alias $($jsonSpec.products.properties.productPassword.Split(":")[3])) { - if (Get-vRSLCMLockerCertificate | Where-Object {$_.alias -Match $($jsonSpec.products.properties.certificate.Split(":")[3])}) { - if (Get-vRSLCMLockerLicense | Where-Object {$_.alias -Match $($jsonSpec.products.properties.licenseRef.Split(":")[3])}) { - $newRequest = Add-vRSLCMEnvironment -json $json - if ($newRequest) { - if ($PsBoundParameters.ContainsKey("monitor")) { + if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) { + if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) { + $clusterId = ((Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}).clusters | Where-Object {$_.id -eq (Get-VCFCluster | Where-Object {$_.name -eq $cluster}).id}).id + if ($clusterId){ + if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + Connect-vSphereMobServer -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass + $licenseExists = $null + Try { + $licenseExists = Get-VCFLicenseKey -key $licenseKey -ErrorAction SilentlyContinue + } + Catch { + # Do nothing + } + If (!($licenseExists)) { + New-VCFLicenseKey -key $licenseKey -productType WCP -description "WCP license" + Start-Sleep 10 + if (Get-VCFLicenseKey -key $licenseKey) { + Write-Output "Adding license key ($licenseKey) in SDDC manager ($sddcManager): SUCCESSFUL" + $clusterId = ((Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}).clusters | Where-Object {$_.id -eq (Get-VCFCluster | Where-Object {$_.name -eq $cluster}).id}).id + + $uri = "https://$sddcManager/v1/wcps/$clusterId/licensing" + $json = '{"licenseKey": "'+ $licenseKey +'"}' + $response = Invoke-RestMethod -Method POST -URI $uri -headers $headers -ContentType application/json -body $json + Try { + $taskStatus = $null + Do { + $taskStatus = (Get-VCFTask -id $response.id).status Start-Sleep 10 - Watch-vRSLCMRequest -vmid $($newRequest.requestId) + } while ($taskStatus -eq "In Progress") + if ($taskStatus -eq "Successful") { + Write-Output "Assign license key ($licenseKey) to Supervisior cluster ($cluster) : SUCCESSFUL" } else { - Write-Output "Deployment Request for vRealize Log Insight Submitted Successfully (Request Ref: $($newRequest.requestId))" - } + Write-Error "Assign license key ($licenseKey) to Supervisior cluster ($cluster) : FAILED" + break + } } - else { - Write-Error "Request to deploy vRealize Log Insight failed, check the vRealize Suite Lifecycle Manager UI: POST_VALIDATION_FAILED" + Catch { + Debug-ExceptionWriter -object $_ } } else { - Write-Error "License with alias ($($jsonSpec.products.properties.licenseRef.Split(":")[3])) does not exist in the locker: PRE_VALIDATION_FAILED" + Write-Error "Adding license key ($licenseKey) in SDDC manager ($sddcManager): POST_VALIDATION_FAILED" + break } + } else { + Write-Warning "Adding license key ($licenseKey) in SDDC manager ($sddcManager), already exists: SKIPPED" } - else { - Write-Error "Certificate with alias ($($jsonSpec.products.properties.certificate.Split(":")[3])) does not exist in the locker: PRE_VALIDATION_FAILED" - } - } - else { - Write-Error "Password with alias ($($jsonSpec.products.properties.productPassword.Split(":")[3])) does not exist in the locker: PRE_VALIDATION_FAILED" + } + Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue } - else { - Write-Warning "Environment with name ($($jsonSpec.environmentName)) already exists in vRealize Suite Lifecyle Manager ($($vcfVrslcmDetails.fqdn)) with a status of ($($environmentExists.environmentStatus)): SKIPPED" - } + } + else { + Write-Error "Unable to find cluster named ($cluster) in the Workload Domain named ($domain) in the invenotry of SDDC Manager ($server): PRE_VALIDATION_FAILED" } } - } + } + else { + Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" + } } } } @@ -5022,64 +5378,74 @@ Function New-vRLIDeployment { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function New-vRLIDeployment +Export-ModuleMember -Function Add-SupervisorClusterLicense -Function Add-vRLISmtpConfiguration { +Function Add-Namespace { <# - .SYNOPSIS - Configure SMTP settings in vRealize Log Insight + .SYNOPSIS + Creates a Namespace and applies extra configuration to it .DESCRIPTION - The Add-vRLISmtpConfiguration cmdlet configures the SMTP sever settings in vRealize Log Insight. The cmdlet - connects to SDDC Manager using the -server, -user, and -password values. + The Add-Namespace cmdlet creates a Namespace and applies its configuration.. The cmdlet connects to SDDC + Manager using the -server, -user, and -password values: - Validates that network connectivity and authentication is possible to SDDC Manager - - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details - - Validates that network connectivity and authentication is possible to vRealize Log Insight - - Validates that network connectivity is possible to the SMTP server - - Configures SMTP server settings in vRealize Log Insight if not already configured + - Validates that network connectivity and authentication is possible to vCenter Server + - Creates the Namespace .EXAMPLE - Add-vRLISmtpConfiguration -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -smtpServer smtp.rainpole.io -port 25 -sender administrator@rainpole.io - This example configures the SMTP server settings on vRealize Log Insight + Add-Namespace -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -cluster sfo-w01-cl01 -namespace sfo-w01-ns01 -storagePolicy vsphere-with-tanzu-storage-policy + This example creates a Namespace named sfo-w01-ns01 in the Supervisor Cluster sfo-w01-cl01 with a vSphere Storage Policy vsphere-with-tanzu-storage-policy #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$smtpServer, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$port, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sender, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$smtpUser, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$smtpPass + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$namespace, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$storagePolicy ) Try { + if (Test-VCFConnection -server $server) { if (Test-VCFAuthentication -server $server -user $user -pass $pass) { - if (($vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass)) { - if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) { - if (Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass) { - if (Test-Connection -ComputerName $smtpServer -Quiet -Count 1) { - if (!(Get-vRLISmtpConfiguration | Where-Object {$_.server -eq $smtpServer})) { - Set-vRLISmtpConfiguration -smtpServer $smtpServer -port $port -sender $sender -username $smtpUser -password $smtpPass | Out-Null - if (Get-vRLISmtpConfiguration | Where-Object {$_.server -eq $smtpServer}) { - Write-Output "Configuring SMTP Server in vRealize Log Insight ($($vcfVrliDetails.fqdn)) with SMTP server ($smtpServer): SUCCESSFUL" + if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) { + if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) { + if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + if (!(Get-WMNamespace -Name $namespace -ErrorAction SilentlyContinue)) { + if (Get-Cluster -Name $cluster -ErrorAction SilentlyContinue) { + if (Get-SpbmStoragePolicy -Name $storagePolicy -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue) { + New-WMNamespace -Name $namespace -Cluster $cluster | Out-Null + if (Get-WMNamespace -Name $namespace -ErrorAction SilentlyContinue) { + New-WMNamespaceStoragePolicy -Namespace $namespace -StoragePolicy $storagePolicy | Out-Null + Write-Output "Creating Namespace ($namespace) in Supervisor Cluster ($cluster) in vCenter Server ($($vcfVcenterDetails.fqdn)): SUCCESSFUL" + } + else { + Write-Error "Creating Namespace ($namespace) in Supervisor Cluster ($cluster) in vCenter Server ($($vcfVcenterDetails.fqdn)): POST_VALIDATION_FAILED" + } + } + else { + Write-Error "Unable to find vSphere Storage Policy ($storagePolicy) in vCenter Server ($($vcfVcenterDetails.fqdn)): PRE_VALIDATION_FAILED" + } } else { - Write-Error "Configuring SMTP Server in vRealize Log Insight ($($vcfVrliDetails.fqdn)) with SMTP server ($smtpServer): POST_VALIDATION_FAILED" + Write-Error "Unable to find Cluster ($cluster) in vCenter Server ($($vcfVcenterDetails.fqdn)): PRE_VALIDATION_FAILED" } } else { - Write-Warning "Configuring SMTP Server in vRealize Log Insight ($($vcfVrliDetails.fqdn)) with SMTP server ($smtpServer), already exists: SKIPPED" + Write-Warning "Creating Namespace ($namespace) in Supervisor Cluster ($cluster) in vCenter Server ($($vcfVcenterDetails.fqdn)), already exists: SKIPPED" } } - else { - Write-Error "Unable to communicate with SMTP Server ($smtpServer), check details: PRE_VALIDATION_FAILED" - } + Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue } } } + else { + Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" + } } } } @@ -5087,226 +5453,214 @@ Function Add-vRLISmtpConfiguration { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-vRLISmtpConfiguration +Export-ModuleMember -Function Add-Namespace -Function Add-vRLIAuthenticationWSA { +Function Undo-Namespace { <# - .SYNOPSIS - Configure vRealize Log Insight Intergration with Workspace ONE Access + .SYNOPSIS + Remove a Namespace .DESCRIPTION - The Add-vRLIAuthenticationWSA cmdlet configures role assignments in NSX Manager. The cmdlet connects to SDDC - Manager using the -server, -user, and -password values. + The Undo-Namespace cmdlet removes a Namespace from the Supervisor Cluster.. The cmdlet connects to SDDC Manager + using the -server, -user, and -password values: - Validates that network connectivity and authentication is possible to SDDC Manager - - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details - - Validates that network connectivity and authentication is possible to vRealize Log Insight - - Validates that network connectivity is possible to Workspace ONE Access - - Configures Workspace ONE Access Integration on vRealize Log Insight if not already configured + - Validates that network connectivity and authentication is possible to vCenter Server + - Removes a Namespace .EXAMPLE - Add-vRLIAuthenticationWSA -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -wsaFqdn sfo-wsa01.sfo.rainpole.io -wsaUser admin -wsaPass VMw@re1! - This example enables Workspace ONE Access integration on vRealize Suite Lifecycle Manager + Undo-Namespace -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -namespace sfo-w01-ns02 + This example removes the Namespace named sfo-w01-ns02 #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaFqdn, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaUser, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaPass + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$namespace ) Try { if (Test-VCFConnection -server $server) { if (Test-VCFAuthentication -server $server -user $user -pass $pass) { - if (($vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass)) { - if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) { - if (Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass) { - if (Test-Connection -ComputerName $wsaFqdn -Quiet -Count 1) { - if ((Get-vRLIAuthenticationWSA).enabled -eq $false) { - Set-vRLIAuthenticationWSA -hostname $wsaFqdn -port 443 -redirectUrl $vcfVrliDetails.fqdn -username $wsaUser -password $wsaPass - if ((Get-vRLIAuthenticationWSA).enabled -eq $true) { - Write-Output "Configuring Workspace ONE Access Integration in vRealize Log Insight ($($vcfVrliDetails.fqdn)) with ($wsaFqdn): SUCCESSFUL" + if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) { + if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) { + if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + if (Get-WMNamespace -Name $namespace -Server $vcfVcenterDetails.fqdn -ErrorAction Ignore) { + Remove-WMNamespace -Namespace $namespace -Server $vcfVcenterDetails.fqdn -Confirm:$false | Out-Null + if (!(Get-WMNamespace -Name $namespace -Server $vcfVcenterDetails.fqdn -ErrorAction Ignore)) { + Write-Output "Removing Namespace ($namespace) from vCenter Server ($($vcfVcenterDetails.fqdn)): SUCCESSFUL" } else { - Write-Error "Configuring Workspace ONE Access Integration in vRealize Log Insight ($($vcfVrliDetails.fqdn)) with ($wsaFqdn): POST_VALIDATION_FAILED" + Write-Error "Removing Namespace ($namespace) from vCenter Server ($($vcfVcenterDetails.fqdn)): POST_VALIDATION_FAILED" } } else { - Write-Warning "Configuring Workspace ONE Access Integration in vRealize Log Insight ($($vcfVrliDetails.fqdn)) with ($wsaFqdn), already exists: SKIPPED" + Write-Warning "Removing Namespace ($namespace) from vCenter Server ($($vcfVcenterDetails.fqdn)), does not exist: SKIPPED" } } - else { - Write-Error "Unable to communicate with Workspace ONE Access Instance ($wsaFqdn), check details: POST_VALIDATION_FAILED" - } + Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue } } } + else { + Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" + } } - } + } } Catch { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-vRLIAuthenticationWSA +Export-ModuleMember -Function Undo-Namespace -Function Install-vRLIPhotonAgent { +Function Add-NamespacePermission { <# - .SYNOPSIS - Install vRealize Log Insight Photon Agent in a Virtual Machine + .SYNOPSIS + Adds permissions to a Namespace .DESCRIPTION - The Install-vRLIPhotonAgent cmdlet installs and configures the vRealize Log Insight Photon Agent on a virtual - machine. The cmdlet connects to SDDC Manager using the -server, -user, and -password values. + The Add-NamespacePermission cmdlet adds permissions to a Namespace. The cmdlet connects to SDDC Manager using + the -server, -user, and -password values: - Validates that network connectivity and authentication is possible to SDDC Manager - - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details - - Validates that network connectivity and authentication is possible to vRealize Log Insight - Validates that network connectivity and authentication is possible to vCenter Server - - Validates that the Virtual Machine exists in the vCenter Server inventory - - Downloads and Installs the Photon Agent on the Virtual Machne - - Configures the liagent.ini file to communicate with vRealize Log Insight + - Assigns permissions to a Namespace .EXAMPLE - Install-vRLIPhotonAgent -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -vmName sfo-wsa01 -vmRootPass VMw@re1! - This example installs and configures the vRealize Log Insight Agent on the virtual machine named 'sfo-wsa01' + Add-NamespacePermission -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -sddcDomain sfo-w01 -domain sfo.rainpole.io -domainBindUser svc-vsphere-ad -domainBindPass VMw@re1! -namespace sfo-w01-ns01 -principal gg-kub-admins -role edit -type group + This example adds the edit role to the group gg-kub-admins in the domain sfo.rainpole.io to the Namespace sfo-w01-ns01 #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vmName, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vmRootPass + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcDomain, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domainBindUser, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domainBindPass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$namespace, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$principal, + [Parameter (Mandatory = $true)] [ValidateSet("edit", "view")] [String]$role, + [Parameter (Mandatory = $true)] [ValidateSet("group", "user")] [String]$type ) Try { - if (Test-VCFConnection -server $server) { - if (Test-VCFAuthentication -server $server -user $user -pass $pass) { - if (($vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass)) { - if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) { - if (Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass) { - if (($vcfVcenterDetails = Get-VcenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) { - if (Test-VsphereConnection -server $vcfVcenterDetails.fqdn) { - if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { - if (Get-VM -Name $vmName -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue) { - $output = Invoke-VMScript -VM $vmName -ScriptText "systemctl status liagentd" -GuestUser root -GuestPassword $vmRootPass -Server $vcfVcenterDetails.fqdn - if ($output.ScriptOutput.Contains("/lib/systemd/system/liagentd.service; enabled")) { - Write-Warning "Installing and Configuring vRealize Log Insight Agent Installed and Configured on ($vmName), already exists: SKIPPED" - } - else { - Invoke-VMScript -VM $vmName -ScriptText "rm /tmp/liagent.rpm && rm /tmp/installAgent.sh && /tmp/configureAgent.sh" -GuestUser root -GuestPassword $vmRootPass -Server $vcfVcenterDetails.fqdn | Out-Null - $installAgent = @( - "curl -k -o /tmp/liagent.rpm https://$($vcfVrliDetails.fqdn)/api/v1/agent/packages/types/rpm; rpm -Uvh /tmp/liagent.rpm", - "systemctl enable liagentd", - "systemctl status liagentd" - ) - foreach ($line in $installAgent) { - Invoke-VMScript -VM $vmName -ScriptText "echo ""$line"">>/tmp/installAgent.sh" -GuestUser root -GuestPassword $vmRootPass -Server $vcfVcenterDetails.fqdn | Out-Null - } - $output = Invoke-VMScript -VM $vmName -ScriptText "chmod 777 /tmp/installAgent.sh && /tmp/installAgent.sh" -GuestUser root -GuestPassword $vmRootPass -Server $vcfVcenterDetails.fqdn - if ($output.ScriptOutput.Contains("/lib/systemd/system/liagentd.service; enabled")) { - $configureAgent = @( - "sed -i 's/;hostname=LOGINSIGHT/hostname=$($vcfVrliDetails.fqdn)/' /var/lib/loginsight-agent/liagent.ini", - "sed -i 's/;proto=cfapi/proto=cfapi/' /var/lib/loginsight-agent/liagent.ini", - "sed -i 's/;port=9543/port=9000/' /var/lib/loginsight-agent/liagent.ini", - "sed -i 's/;ssl=yes/ssl=no/' /var/lib/loginsight-agent/liagent.ini", - "systemctl restart liagentd", - "systemctl status liagentd" - ) - foreach ($line in $configureAgent) { - Invoke-VMScript -VM $vmName -ScriptText "echo ""$line"">>/tmp/configureAgent.sh" -GuestUser root -GuestPassword $vmRootPass -Server $vcfVcenterDetails.fqdn | Out-Null - } - $output = Invoke-VMScript -VM $vmName -ScriptText "chmod 777 /tmp/configureAgent.sh && /tmp/configureAgent.sh" -GuestUser root -GuestPassword $vmRootPass -Server $vcfVcenterDetails.fqdn - if ($output.ScriptOutput.Contains("active (running)")) { - Write-Output "Installing and Configuring vRealize Log Insight Agent Installed and Configured on ($vmName): SUCCESSFUL" - } - else { - Write-Error "Installing and Configuring vRealize Log Insight Agent Installed and Configured on ($vmName): POST_VALIDATION_FAILED" - } + $checkAdAuthentication = Test-ADAuthentication -user $domainBindUser -pass $domainBindPass -server $domain -domain $domain -ErrorAction SilentlyContinue + if ($checkAdAuthentication[1] -match "Authentication Successful") { + $securePass = ConvertTo-SecureString -String $domainBindPass -AsPlainText -Force + $domainCreds = New-Object System.Management.Automation.PSCredential ($domainBindUser, $securePass) + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $sddcDomain }) { + if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $sddcDomain)) { + if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + if (Get-WMNamespace -Name $namespace -ErrorAction SilentlyContinue) { + if ($type -eq "group") { $adObjectCheck = (Get-ADGroup -Server $domain -Credential $domainCreds -Filter { SamAccountName -eq $principal }) } + elseif ($type -eq "user") { $adObjectCheck = (Get-ADUser -Server $domain -Credential $domainCreds -Filter { SamAccountName -eq $principal }) } + if ($adObjectCheck) { + if (!(Get-WMNamespacePermission -Namespace $namespace -Domain $domain -PrincipalName $principal)) { + New-WMNamespacePermission -Namespace $namespace -Role $role -Domain $domain -PrincipalType $type -PrincipalName $principal | Out-Null + if (Get-WMNamespacePermission -Namespace $namespace -Domain $domain -PrincipalName $principal) { + Write-Output "Assigning Role ($role) to $type ($principal) in Namespace ($namespace): SUCCESSFUL" } else { - Write-Error "Enabling vRealize Log Insight Agent Installed and Configured on ($vmName): POST_VALIDATION_FAILED" + Write-Error "Assigning Role ($role) to $type ($principal) in Namespace ($namespace): POST_VALIDATION_FAILED" } } + else { + Write-Warning "Assigning Role ($role) to $type ($principal) in Namespace ($namespace), already assigned: SKIPPED" + } } else { - Write-Error "Virtual Machine ($vmName), not Found in vCenter Server ($($vcfVcenterDetails.fqdn)) Inventory, check details and try again: PRE_VALIDATION_FAILED" + Write-Error "Active Directory $type ($principal) not found in the Active Directory Domain: PRE_VALIDATION_FAILED" } } + else { + Write-Error "Unable to find Namespace ($namespace) in vCenter Server ($($vcfVcenterDetails.fqdn)): PRE_VALIDATION_FAILED" + } } + Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue } } } + else { + Write-Error "Unable to find Workload Domain named ($sddcDomain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" + } } } } + else { + Write-Error "Unable to authenticate to Active Directory with user ($domainBindUser) and password ($domainBindPass), check details: PRE_VALIDATION_FAILED" + } } Catch { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Install-vRLIPhotonAgent +Export-ModuleMember -Function Add-NamespacePermission -Function Add-vRLIAgentGroup { +Function Undo-NamespacePermission { <# - .SYNOPSIS - Creates an agent group in vRealize Log Insight + .SYNOPSIS + Remove permissions from a Namespace .DESCRIPTION - The Add-vRLIAgentGroup cmdlet creates a new agent group in vRealize Log Insight. The cmdlet connects to SDDC - Manager using the -server, -user, and -password values. + The Undo-NamespacePermission cmdlet removes a permissions from a Namespace. The cmdlet connects to SDDC Manager + using the -server, -user, and -password values: - Validates that network connectivity and authentication is possible to SDDC Manager - - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details - - Validates that network connectivity and authentication is possible to vRealize Log Insight - - Creates an agent group in the vRealize Log Insight if not already configured - - .EXAMPLE - Add-vRLIAgentGroup -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -agentGroupType wsa -criteria "xint-wsa01a.rainpole.io","xint-wsa01b.rainpole.io","xint-wsa01c.rainpole.io" - This example creates an agent group for Workspace ONE Access in vRealize Log Insight and assigns the Cluster Virtual Machines + - Validates that network connectivity and authentication is possible to vCenter Server + - Removes permissions from a Namespace .EXAMPLE - Add-vRLIAgentGroup -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -agentGroupType photon -criteria "sfo-vcf01.sfo.rainpole.io","xint-vrslcm01.rainpole.io","xint-wsa01a.rainpole.io","xint-wsa01b.rainpole.io","xint-wsa01c.rainpole.io" - This example creates an agent group for Photon OS in vRealize Log Insight and assigns the SDDC Manager, vRealize Suite Lifecycle Manager and Workspace ONE Access Cluster Virtual Machines + Undo-NamespacePermission -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -sddcDomain sfo-w01 -namespace sfo-w01-ns01 -principal gg-kub-admins + This example removes the edit role from the Namespace sfo-w01-ns01 #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, - [Parameter (Mandatory = $true)] [ValidateSet("wsa","photon")] [ValidateNotNullOrEmpty()] [String]$agentGroupType, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Array]$criteria + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcDomain, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$namespace, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$principal ) Try { if (Test-VCFConnection -server $server) { if (Test-VCFAuthentication -server $server -user $user -pass $pass) { - if (($vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass)) { - if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) { - if (Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass) { - if ($agentGroupType -eq "wsa") { - $agentName = "Workspace ONE Access - Appliance Agent Group" - } - elseif ($agentGroupType -eq "photon") { - $agentName = "Photon OS - Appliance Agent Group" - } - - if (!(Get-vRLIAgentGroup | Select-Object name | Where-Object {$_.name -eq $agentName})) { - New-vRLIAgentGroup -agentGroupType $agentGroupType -criteria $criteria | Out-Null - if (Get-vRLIAgentGroup | Select-Object name | Where-Object {$_.name -eq $agentName}) { - Write-Output "Creating Agent Group in vRealize Log Insight ($($vcfVrliDetails.fqdn)) for ($agentName): SUCCESSFUL" + if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $sddcDomain }) { + if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $sddcDomain)) { + if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + if (Get-WMNamespace -Name $namespace -ErrorAction SilentlyContinue) { + if (Get-WMNamespacePermission -Namespace $namespace -PrincipalName $principal) { + Get-WMNamespacePermission -Namespace $namespace -PrincipalName $principal | Remove-WMNamespacePermission -Confirm:$false | Out-Null + if (!(Get-WMNamespacePermission -Namespace $namespace -PrincipalName $principal)) { + Write-Output "Removing access for principal ($principal) from Namespace ($namespace): SUCCESSFUL" + } + else { + Write-Error "Removing access for principal ($principal) from Namespace ($namespace): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Removing access for principal ($principal) from Namespace ($namespace), does not exist: SKIPPED" + } } else { - Write-Error "Creating Agent Group in vRealize Log Insight ($($vcfVrliDetails.fqdn)) for ($agentName): POST_VALIDATION_FAILED" + Write-Error "Unable to find Namespace ($namespace) in vCenter Server ($($vcfVcenterDetails.fqdn)): PRE_VALIDATION_FAILED" } } - else { - Write-Warning "Creating Agent Group in vRealize Log Insight ($($vcfVrliDetails.fqdn)) for ($agentName), already exists: SKIPPED" - } + Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue } } } + else { + Write-Error "Unable to find Workload Domain named ($sddcDomain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" + } } } } @@ -5314,29 +5668,23 @@ Function Add-vRLIAgentGroup { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-vRLIAgentGroup +Export-ModuleMember -Function Undo-NamespacePermission -Function Register-vRLIWorkloadDomain { +Function Enable-Registry { <# - .SYNOPSIS - Connect a Workload Domain to vRealize Log Insight + .SYNOPSIS + Enable the embedded Harbor Registry on a Supervisor Cluster .DESCRIPTION - The Register-vRLIWorkloadDomain cmdlet connects a Workload Domain to vRealize Log Insight. The cmdlet connects - to SDDC Manager using the -server, -user, and -password values. + The Enable-Registry cmdlet enables the embedded Harbor Registry on a Supervisor Cluster. The cmdlet connects to + SDDC Manager using the -server, -user, and -password values: - Validates that network connectivity and authentication is possible to SDDC Manager - - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details - - Validates that network connectivity and authentication is possible to vRealize Log Insight - - Obtains the Workload Domain details from the SDDC Manager inventory - - Connects the Workload Domain with vRealize Log Insight if not already configured - - .EXAMPLE - Register-vRLIWorkloadDomain -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -status ENABLED - This example ENABLES the Workload Domain in vRealize Log Insight + - Validates that network connectivity and authentication is possible to vCenter Server + - Enables the embedded Harbour Registry on the Supervisor Cluster .EXAMPLE - Register-vRLIWorkloadDomain -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -status DISABLED - This example DISABLES the Workload Domain in vRealize Log Insight + Enable-Registry -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -storagePolicy vsphere-with-tanzu-storage-policy + This example enables the embedded Harbor Registry on Supervisor Cluster sfo-w01-cl01 with vSPhere Storage Policy vsphere-with-tanzu-policy #> Param ( @@ -5344,38 +5692,49 @@ Function Register-vRLIWorkloadDomain { [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, - [Parameter (Mandatory = $true)] [ValidateSet("ENABLED", "DISABLED")] [String]$status + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$storagePolicy ) Try { if (Test-VCFConnection -server $server) { if (Test-VCFAuthentication -server $server -user $user -pass $pass) { - if (($vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass)) { - if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) { - if (Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass) { - if (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}) { - if ((Get-VCFvRLIConnection | Where-Object {$_.domainId -eq (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}).id}).status -ne $status) { - Set-VCFvRLIConnection -domainId (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}).id -status $status | Out-Null - Do { - $configStatus = (Get-VCFvRLIConnection | Where-Object {$_.domainId -eq (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}).id}).status - } Until ($configStatus -ne "IN_PROGRESS") - if ((Get-VCFvRLIConnection | Where-Object {$_.domainId -eq (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}).id}).status -eq $status) { - Write-Output "Workload Domain Intergration in vRealize Log Insight ($($vcfVrliDetails.fqdn)) for Workload Domain ($domain): SUCCESSFUL" - } - else { - Write-Error "Workload Domain Intergration in vRealize Log Insight ($($vcfVrliDetails.fqdn)) for Workload Domain ($domain): POST_VALIDATION_FAILED" + if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) { + if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) { + if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + if (Test-vSphereApiConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-vSphereApiAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + $cluster = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.Name -eq $domain }).clusters.id) }).Name + if (!(Get-WMRegistry -cluster $cluster -ErrorAction SilentlyContinue)) { + if (Get-SpbmStoragePolicy -Name $storagePolicy -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue) { + Enable-WMRegistry -cluster $cluster -StoragePolicy $storagePolicy | Out-Null + Do { + $configStatus = Get-WMRegistry -cluster $cluster | Get-WMRegistryHealth + } Until ($configStatus -eq "RUNNING") + if (Get-WMRegistry -cluster $cluster -ErrorAction SilentlyContinue) { + Write-Output "Enabling Embedded Harbour Registry in vCenter Server ($($vcfVcenterDetails.fqdn)) for Cluster ($cluster): SUCCESSFUL" + } + else { + Write-Error "Enabling Embedded Harbour Registry in vCenter Server ($($vcfVcenterDetails.fqdn)) for Cluster ($cluster): POST_VALIDATION_FAILED" + } + } + else { + Write-Error "Unable to find vSphere Storage Policy ($storagePolicy) in vCenter Server ($($vcfVcenterDetails.fqdn)): PRE_VALIDATION_FAILED" + } + } + else { + Write-Warning "Enabling Embedded Harbour Registry in vCenter Server ($($vcfVcenterDetails.fqdn)) for Cluster ($cluster), already performed: SKIPPED" + } } } - else { - Write-Warning "Workload Domain Intergration in vRealize Log Insight ($($vcfVrliDetails.fqdn)) for Workload Domain ($domain), already exists: SKIPPED" - } - } - else { - Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" } + Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue } } } + else { + Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" + } } } } @@ -5383,66 +5742,67 @@ Function Register-vRLIWorkloadDomain { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Register-vRLIWorkloadDomain +Export-ModuleMember -Function Enable-Registry -Function Set-vRLISyslogEdgeCluster { +Function Undo-Registry { <# - .SYNOPSIS - Configure Syslog settings on NSX Edge Cluster Nodes + .SYNOPSIS + Disable the embedded Harbor Registry on a Supervisor Cluster .DESCRIPTION - The Set-vRLISyslogEdgeCluster cmdlet configures Syslog settings on NSX Edge Cluster The cmdlet connects to SDDC - Manager using the -server, -user, and -password values. + The Undo-Registry cmdlet disables the embedded Harbor Registry on a Supervisor Cluster. The cmdlet connects to + SDDC Manager using the -server, -user, and -password values: - Validates that network connectivity and authentication is possible to SDDC Manager - - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details - - Validates that network connectivity and authentication is possible to vRealize Log Insight - - Validates that network connectivity and authentication is possible to NSX Management Cluster - - Gathers the NSX Edge Node details from NSX Management Cluster - - Configures the Syslog settings on the NSX Edge Node if not already configured + - Validates that network connectivity and authentication is possible to vCenter Server + - Disables the Harbour Registry on the Supervisor Cluster .EXAMPLE - Set-vRLISyslogEdgeCluster -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -exportname SFO-VRLI - This example configures the Syslog settings for each NSX Edge node to sent logs to vRealize Log Insight + Undo-Registry -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 + This example disables the embedded Harbor Registry on Supervisor Cluster sfo-w01-cl01 with vSPhere Storage Policy vsphere-with-tanzu-policy #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$exportName + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain ) Try { if (Test-VCFConnection -server $server) { if (Test-VCFAuthentication -server $server -user $user -pass $pass) { - $vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass - if ($nsxtManagerDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain -listNodes) { - if (Test-NSXTConnection -server $nsxtManagerDetails.fqdn) { - if (Test-NSXTAuthentication -server $nsxtManagerDetails.fqdn -user $nsxtManagerDetails.adminUser -pass $nsxtManagerDetails.AdminPass) { - [Array]$edgeNodeIds = ($edgeCluster = Get-NsxtEdgeCluster).members.transport_node_id - foreach ($nodeId in $edgeNodeIds) { - if (!(Get-NsxtSyslogExporter -transport -id $nodeId | Where-Object {$_.exporter_name -eq $exportName})) { - if (!(Get-NsxtSyslogExporter -transport -id $nodeId | Where-Object {$_.server -eq $vcfVrliDetails.fqdn})) { - Set-NsxtSyslogExporter -transport -id $nodeId -exporterName $exportName -logLevel INFO -port 514 -protocol TCP -server $vcfVrliDetails.fqdn | Out-Null - if (Get-NsxtSyslogExporter -transport -id $nodeId | Where-Object {$_.exporter_name -eq $exportName}) { - Write-Output "Configuring Syslog Exporter ($exportName) on Edge Node ($nodeId): SUCCESSFUL" + if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) { + if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) { + if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + if (Test-vSphereApiConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-vSphereApiAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + $cluster = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.Name -eq $domain }).clusters.id) }).Name + if (Get-WMRegistry -cluster $cluster -ErrorAction Ignore) { + Remove-WMRegistry -cluster $cluster | Out-Null + Do { + $configStatus = Get-WMRegistry -cluster $cluster -ErrorAction Ignore #| Get-WMRegistryHealth -ErrorAction Ignore + } Until (!($configStatus)) + if (!(Get-WMRegistry -cluster $cluster -ErrorAction Ignore)) { + Write-Output "Disabling Embedded Harbour Registry in vCenter Server ($($vcfVcenterDetails.fqdn)) for Cluster ($cluster): SUCCESSFUL" + } + else { + Write-Error "Disabling Embedded Harbour Registry in vCenter Server ($($vcfVcenterDetails.fqdn)) for Cluster ($cluster): POST_VALIDATION_FAILED" + } } else { - Write-Error "Configuring Syslog Exporter ($exportName) on Edge Node ($nodeId): POST_VALIDATION_FAILED" + Write-Warning "Disabling Embedded Harbour Registry in vCenter Server ($($vcfVcenterDetails.fqdn)) for Cluster ($cluster), already performed: SKIPPED" } } - else { - Write-Warning "Configuring Syslog Server ($($vcfVrliDetails.fqdn)) on Edge Node ($nodeId), already exists: SKIPPED" - } - } - else { - Write-Warning "Configuring Syslog Exporter ($exportName) on Edge Node ($nodeId), already exists: SKIPPED" } } + Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue } } - } + } + else { + Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" + } } } } @@ -5450,50 +5810,63 @@ Function Set-vRLISyslogEdgeCluster { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Set-vRLISyslogEdgeCluster +Export-ModuleMember -Function Undo-Registry -Function Add-vRLILogArchive { +Function Add-NamespaceVmClass { <# - .SYNOPSIS - Configure log archiving in vRealize Log Insight + .SYNOPSIS + Add a Virtual Machine class to a Namespace .DESCRIPTION - The Add-vRLILogArchive cmdlet configure log archiving in vRealize Log Insight. The cmdlet connects to SDDC - Manager using the -server, -user, and -password values. + The Add-NamespaceVmClass cmdlet adds a Virtual Machine Class to a Namespace. The cmdlet connects to SDDC + Manager using the -server, -user, and -password values: - Validates that network connectivity and authentication is possible to SDDC Manager - - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details - - Validates that network connectivity and authentication is possible to vRealize Log Insight - - Configure an email address to send notifications to in vRealize Log Insight - - Configure the log retention threshold in vRealize Log Insight - - Configure log archive location in vRealize Log Insight + - Validates that network connectivity and authentication is possible to vCenter Server + - Adds a VM Class to the Namespace .EXAMPLE - Add-vRLILogArchive -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -emailAddress administrator@rainpole.io -retentionNotificationDays 1 -retentionInterval weeks -retentionPeriodDays 7 -archiveLocation "nfs://172.27.11.4/sfo-m01-vrli01-400GB" - This example configures the log archive and retention period in vRealize Log Insight + Add-NamespaceVmClass -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -namespace sfo-w01-tkc01 -vmClass guaranteed-small + This example adds the VM Class guaranteed-small to Supervisor Namespace sfo-tkc-01 in Workload domain sfo-w01 #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$emailAddress, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Int]$retentionNotificationDays, - [Parameter (Mandatory = $true)] [ValidateSet("minutes","hours","days","weeks","months")] [ValidateNotNullOrEmpty()] [String]$retentionInterval, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Int]$retentionPeriodDays, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$archiveLocation + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$namespace, + [Parameter (Mandatory = $false)] [ValidateSet("guaranteed-medium","guaranteed-large","guaranteed-xlarge","best-effort-4xlarge","guaranteed-small","best-effort-medium","best-effort-2xlarge","guaranteed-2xlarge","best-effort-large","guaranteed-4xlarge","best-effort-8xlarge","best-effort-xsmall","guaranteed-xsmall","best-effort-xlarge","guaranteed-8xlarge","best-effort-small")] [String]$vmClass ) Try { if (Test-VCFConnection -server $server) { if (Test-VCFAuthentication -server $server -user $user -pass $pass) { - if (($vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass)) { - if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) { - if (Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass) { - Set-vRLIEmailNotification -emailAddress $emailAddress | Out-Null - Set-vRLIRetentionThreshold -enable true -interval $retentionNotificationDays -intervalUnit $retentionInterval | Out-Null - $partitionId = (Get-vRLIIndexPartition).id - Set-vRLILogArchive -id $partitionId -enable true -retentionPeriod $retentionPeriodDays -archiveEnable true -archiveLocation $archiveLocation - Write-Output "Configuring Email Notifications, Retention Period and Archive Location in vRealize Log Insight ($($vrliDetails.fqdn)): SUCCESSFUL" + if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) { + if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) { + if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + if (Test-vSphereApiConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-vSphereApiAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + if (Get-WMNamespace -Name $namespace -ErrorAction Ignore) { + if (!(Get-VMClass -namespace $namespace | Where-Object {$_ -eq $vmClass})) { + Add-VMClass -namespace $namespace -vmClass $vmClass | Out-Null + if (Get-VMClass -namespace $namespace | Where-Object {$_ -eq $vmClass}) { + Write-Output "Adding Virtual Machine Class ($vmClass) to Namespace ($namespace): SUCCESSFUL" + } + else { + Write-Error "Adding Virtual Machine Class ($vmClass) to Namespace ($namespace): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Adding Virtual Machine Class ($vmClass) to Namespace ($namespace), already exists: SKIPPED" + } + } + else { + Write-Error "Unable to find Namespace ($namespace) in vCenter Server ($($vcfVcenterDetails.fqdn)): PRE_VALIDATION_FAILED" + } + } + } + } } } } @@ -5501,29 +5874,26 @@ Function Add-vRLILogArchive { } } Catch { - Debug-ExceptionWriter -object $_ + Write-Error $_.Exception.Response } } -Export-ModuleMember -Function Add-vRLILogArchive +Export-ModuleMember -Function Add-NamespaceVmClass -Function Add-vRLIAuthenticationGroup { +Function Add-TanzuKubernetesCluster { <# - .SYNOPSIS - Adds a group from the authentication provider in vRealize Log Insight + .SYNOPSIS + Create a new Tanzu Kubernetes Cluster on a Supervisor Cluster .DESCRIPTION - The Add-vRLIAuthenticationGroup cmdlet assigns access to a group based on the authentication providor. The cmdlet - connects to SDDC Manager using the -server, -user, and -password values: + The Add-TanzuKubernetesCluster cmdlet creates a new Tanzu Kubernetes Cluster on a Supervisor Cluster. The + cmdlet connects to SDDC Manager using the -server, -user, and -password values: - Validates that network connectivity and authentication is possible to SDDC Manager - - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details - - Validates that network connectivity and authentication is possible to vRealize Log Insight - - Validates that integration with Workspace ONE Access has been enabled - - Validates that the group has not already been assigned access to vRealize Log Insight - - Adds the group to the access control assigning the role provided in vRealize Log Insight + - Validates that network connectivity and authentication is possible to vCenter Server + - Creates a Tanzu Kubernetes Cluster .EXAMPLE - Add-vRLIAuthenticationGroup -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo.rainpole.io -group gg-vrli-admins -role 'Super Admin' - This example adds the group gg-vrli-admins with Super Admin role in vRealize Log Insight + Add-TanzuKubernetesCluster -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -cluster sfo-w01-cl01 -yaml .\SampleYaml\sfo-w01-tkc01-cluster.yaml + This example creates a Tanzu Kubernetes cluster based on the YAML file .\SampleYaml\sfo-w01-tkc01-cluster.yaml as the vSphere SSO user administrator@vsphere.local on Supervisor Cluster sfo-w01-cl01 #> Param ( @@ -5531,36 +5901,39 @@ Function Add-vRLIAuthenticationGroup { [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$group, - [ValidateSet("Super Admin","User","Dashboard User","View Only Admin")] [ValidateNotNullOrEmpty()] [String]$role + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$yaml ) + if (!$PsBoundParameters.ContainsKey("yaml")) { + $yaml = Get-ExternalFileName -title "Select the YAML File (.yaml)" -fileType "yaml" -location "default" + } + else { + if (!(Test-Path -Path $yaml)) { + Write-Error "YAML File '$yaml' File Not Found" + Break + } + } + Try { if (Test-VCFConnection -server $server) { if (Test-VCFAuthentication -server $server -user $user -pass $pass) { - if ($vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass) { - if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) { - if (Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass) { - if (Get-vRLIAuthenticationWSA -eq "True") { - if (!(Get-vRLIGroup -authProvider vidm | Where-Object {$_.name -eq $group + "@" + $domain})) { - Add-vRLIGroup -authProvider vidm -domain $domain -group $group -role $role | Out-Null - if (Get-vRLIGroup -authProvider vidm | Where-Object {$_.name -eq $group + "@" + $domain}) { - Write-Output "Adding Group to vRealize Log Insight ($($vcfVrliDetails.fqdn)), named ($group): SUCCESSFUL" - } - else { - Write-Warning "Adding Group to vRealize Log Insight ($($vcfVrliDetails.fqdn)), named ($group): POST_VALIDATION_FAILED" - } - } - else { - Write-Warning "Adding Group to vRealize Log Insight ($($vcfVrliDetails.fqdn)), named ($group), already exists: SKIPPED" - } - } - else { - Write-Error "Workspace ONE Integration on vRealize Log Insight ($($vcfVrliDetails.fqdn)), not enabled: PRE_VALIDATION_FAILED" + if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) { + if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) { + if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + Connect-WMCluster -cluster $cluster -user $user -pass $pass | Out-Null + New-TanzuKubernetesCluster -YAML $yaml | Out-Null + Write-Output "Creating Tanzu Kubernetes Cluster in Supervisor Cluster ($cluster) using YAMP ($yaml): SUCCESSFUL" } + Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue + Disconnect-WMCluster | Out-Null } } } + else { + Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" + } } } } @@ -5568,114 +5941,1240 @@ Function Add-vRLIAuthenticationGroup { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-vRLIAuthenticationGroup +Export-ModuleMember -Function Add-TanzuKubernetesCluster -Function Add-vRLIAlertDatacenter { +Function Undo-TanzuKubernetesCluster { <# - .SYNOPSIS - Adds datacenter based alerts in vRealize Log Insight + .SYNOPSIS + Remove a Tanzu Kubernetes Cluster .DESCRIPTION - The Add-vRLIAlertsDatacenter cmdlet adds datacenter based alerts to vRealize Log Insight. The cmdlet connects - to SDDC Manager using the -server, -user, and -password values: + The Undo-TanzuKubernetesCluster cmdlet removes a new Tanzu Kubernetes Cluster. The cmdlet connects to SDDC + Manager using the -server, -user, and -password values: - Validates that network connectivity and authentication is possible to SDDC Manager - - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details - - Validates that network connectivity and authentication is possible to vRealize Log Insight - Validates that network connectivity and authentication is possible to vCenter Server - - Validates that vRealize Operations Manager has been deployed in VCF-aware mode and retrieves its details - - Validates that network connectivity and authentication is possible to vRealize Operations Manager - - Validates that the Datacenter object provided is valid in the vCenter Server inventory - - Creates the alert in vRealize Log Insight for the Datacenter object if not already configured - - Integrates with vRealize Operations Manager if the -vropsIntegration switch is provided + - Removes a Tanzu Kubernetes Cluster .EXAMPLE - Add-vRLIAlertDatacenter -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -sddcDomainName sfo-m01 -datacenterName sfo-m01-dc01 -email administrator@rainpole.io -alertTemplate ".\SampleNotifications\vrli-vcf-datacenter.json" -vropsIntegration - This example adds the alerts provided in the JSON file + Undo-TanzuKubernetesCluster -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -cluster sfo-w01-cl01 -namespace sfo-w01-tkc01 -tkc sfo-w01-tkc01 + This example removes a Tanzu Kubernetes Cluster from the a Supervisor Cluster #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcDomainName, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$datacenterName, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$email, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$alertTemplate, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$vropsIntegration + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$namespace, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tkc ) - $adapter = "VMWARE" # Defines the vRealize Operations Manager Adapter type - $resource = "Datacenter" # Defines the vRealize Operations Manager Resource type associated with the Adapter - Try { - if (Test-Path -Path $alertTemplate) { - if (Test-VCFConnection -server $server) { - if (Test-VCFAuthentication -server $server -user $user -pass $pass) { - if (($vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass)) { - if ($PsBoundParameters.ContainsKey("vropsIntegration")) { - if (!($vcfVropsDetails = Get-vROPSServerDetail -fqdn $server -username $user -password $pass)) { - Break - } - else { - if (!(Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn)) { Break } - if (!(Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass)) { Break } - } - } - if (($vcfVcenterDetails = Get-VcenterServerDetail -server $server -user $user -pass $pass -domain $sddcDomainName)) { - if (Test-VsphereConnection -server $vcfVcenterDetails.fqdn) { - if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { - if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) { - if (Get-Datacenter $datacenterName -ErrorAction Ignore ) { - if (Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass) { - $templateAlerts = (Get-Content -path $alertTemplate -Raw) - $templateAlerts = $templateAlerts -replace '!!datacenterName!!',$datacenterName - $templateAlerts = $templateAlerts -replace '!!email!!',$email - [Array]$allAlerts = $templateAlerts | ConvertFrom-Json - foreach ($alert in $allAlerts) { - $json = $alert | ConvertTo-Json - if ($PsBoundParameters.ContainsKey("vropsIntegration")) { - $entityObjectId =(Get-vROPSResourceDetail -adapter $adapter -resource $resource -objectname $datacenterName | Where-Object {$_.identifierType.name -eq "VMEntityObjectID"}).value - $entityVcid =(Get-vROPSResourceDetail -adapter $adapter -resource $resource -objectname $datacenterName | Where-Object {$_.identifierType.name -eq "VMEntityVCID"}).value - $vcopsResourceKindKey = '"vcopsResourceKindKey": "' + 'resourceName='+$datacenterName+'&adapterKindKey='+$adapter+'&resourceKindKey='+$resource+'&identifiers=VMEntityName::'+$datacenterName+'$$$VMEntityObjectID::'+$entityObjectId+'$$$VMEntityVCID::'+$entityVcid + '"' - $json = $json -replace '"vcopsEnabled": false','"vcopsEnabled": true' - $json = $json -replace '"vcopsResourceKindKey": ""',$vcopsResourceKindKey - } - if (!((Get-vRLIAlert | Select-Object name ) | Where-Object {$_.name -eq $alert.name})) { - Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass | Out-Null - New-vRLIAlert -json $json | Out-Null - } - } - Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue - Write-Output "Adding Datacenter Alerts in vRealize Log Insight ($($vcfVrliDetails.fqdn)) using template Alert JSON ($alertTemplate) for Workload Domain ($sddcDomainName): SUCCESSFUL" - } + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) { + if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) { + if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + if (Get-WMCluster -cluster $cluster -Server $vcfVcenterDetails.fqdn -ErrorAction Ignore) { + Connect-WMCluster -cluster $cluster -user $user -pass $pass | Out-Null + if (Get-TanzuKubernetesCluster -name $namespace -tkc $tkc -ErrorAction Ignore | Out-Null ) { + Remove-TanzuKubernetesCluster -cluster $tkc -namespace $namespace | Out-Null + if (!(Get-TanzuKubernetesCluster -name $namespace -tkc $tkc -ErrorAction Ignore | Out-Null )) { + Write-Output "Removing Tanzu Kubernetes Cluster from Supervisor Cluster ($cluster) Namespace ($namespace) called ($tkc): SUCCESSFUL" } else { - Write-Error "Unable to find Dataceter ($datacenterName) in vCenter Server ($($vcfVcenterDetails.fqdn)): PRE_VALIDATION_FAILED" + Write-Error "Removing Tanzu Kubernetes Cluster from Supervisor Cluster ($cluster) Namespace ($namespace) called ($tkc): POST_VALIDATION_FAILED" } } + else { + Write-Warning "Removing Tanzu Kubernetes Cluster from Supervisor Cluster ($cluster) Namespace ($namespace) called ($tkc), does not exist: SKIPPED" + } + } + else { + Write-Warning "Workload Management is not enabled on Cluster ($server) in vCenter Server ($($vcfVcenterDetails.fqdn))" } } + Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue + Disconnect-WMCluster | Out-Null } - } + } + } + else { + Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" } } } - else { - Write-Error "Unable to find template Alert JSON ($alertTemplate): PRE_VALIDATION_FAILED" - } } Catch { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-vRLIAlertDatacenter +Export-ModuleMember -Function Undo-TanzuKubernetesCluster -Function Add-vRLIAlertVirtualMachine { - <# - .SYNOPSIS - Adds virtual machine based alerts in vRealize Log Insight +########################################## E N D O F F U N C T I O N S ########################################## +####################################################################################################################### - .DESCRIPTION + +####################################################################################################################### +################# I N T E L L I G E N T L O G G I N G & A N A L Y T I C S F U N C T I O N S ################ + +Function Export-vRLIJsonSpec { + <# + .SYNOPSIS + Create vRealize Log Insight Deployment JSON specification using the Planning and Preparation workbook + + .DESCRIPTION + The Export-vRLIJsonSpec cmdlet creates the JSON specification file using the Planning and Preparation workbook + to deploy vRealize Log Insight using vRealize Suite Lifecycle Manager. The cmdlet connects to SDDC Manager + using the -server, -user, and -password values. + - Validates that the Planning and Preparation provided is available + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that vRealize Suite Lifecycle Manager has been deployed in VCF-aware mode and retrieves its details + - Validates that network connectivity and authentication is possible to vRealize Suite Lifecycle Manager + - Validates that the License, Certificate and Password in the Planning and Prep Preparation workbook have been + created in vRealize Suite Lifecycle Manager Locker + - Generates the deployment JSON specification file using the Planning and Preparation workbook and details + from vRealize Suite Lifecycle Manager named 'vrliDeploymentSpec.json' + + .EXAMPLE + Export-vRLIJsonSpec -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -workbook .\pnp-workbook.xlsx + This example creates a JSON specification file for deploying vRealize Log Insight using the Planning and Preparation Workbook data + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$workbook + ) + + Try { + + if (!$PsBoundParameters.ContainsKey("workbook")) { + $workbook = Get-ExternalFileName -title "Select the Planning and Preparation Workbook (.xlsx)" -fileType "xlsx" -location "default" + } + else { + if (!(Test-Path -Path $workbook)) { + Write-Error "Planning and Preparation Workbook (.xlsx) '$workbook' File Not Found" + Break + } + } + + $pnpWorkbook = Open-ExcelPackage -Path $workbook + + ### Obtain Configuration Information from vRealize Suite Lifecycle Manager + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-vRSLCMConnection -server $vcfVrslcmDetails.fqdn) { + if (Test-vRSLCMAuthentication -server $vcfVrslcmDetails.fqdn -user $vcfVrslcmDetails.adminUser -pass $vcfVrslcmDetails.adminPass) { + if ($pnpWorkbook.Workbook.Names["vrli_license"].Value) { + $licenseKey = $pnpWorkbook.Workbook.Names["vrli_license"].Value + } + else { + $licenseKey = $pnpWorkbook.Workbook.Names["vrs_license"].Value + } + $vrliLicense = Get-vRSLCMLockerLicense | Where-Object {$_.key -eq $licenseKey} + if ($vrliLicense.key -eq $licenseKey) { + if ($vrliCertificate = Get-vRSLCMLockerCertificate | Where-Object {$_.alias -eq $pnpWorkbook.Workbook.Names["region_vrli_virtual_hostname"].Value}) { + if ($vrliPassword = Get-vRSLCMLockerPassword -alias $pnpWorkbook.Workbook.Names["region_vrli_admin_password_alias"].Value) { + $vcCredentials = Get-vRSLCMLockerPassword -alias (($pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value).Split(".")[0] + "-" + $pnpWorkbook.Workbook.Names["mgmt_datacenter"].Value) + $datacenterName = Get-vRSLCMDatacenter | Where-Object {$_.dataCenterName -eq $pnpWorkbook.Workbook.Names["mgmt_datacenter"].Value} + + $infrastructurePropertiesObject = @() + $infrastructurePropertiesObject += [pscustomobject]@{ + 'dataCenterVmid' = $datacenterName.dataCenterVmid + 'regionName' = "default" + 'zoneName' = "default" + 'vCenterName' = ($pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value).Split(".")[0] + 'vCenterHost' = $pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value + 'vcUsername' = $vcCredentials.userName + 'vcPassword' = ("locker:password:" + $($vcCredentials.vmid) + ":" + $($vcCredentials.alias)) + 'acceptEULA' = "true" + 'enableTelemetry' = "true" + 'defaultPassword' = ("locker:password:" + $($vrliPassword.vmid) + ":" + $($vrliPassword.alias)) + 'certificate' = ("locker:certificate:" + $($vrliCertificate.vmid) + ":" + $($vrliCertificate.alias)) + 'cluster' = ($pnpWorkbook.Workbook.Names["mgmt_datacenter"].Value + "#" + $pnpWorkbook.Workbook.Names["mgmt_cluster"].Value) + 'storage' = $pnpWorkbook.Workbook.Names["mgmt_vsan_datastore"].Value + 'diskMode' = "thin" + 'network' = $pnpWorkbook.Workbook.Names["reg_seg01_name"].Value + 'masterVidmEnabled' = "false" + 'dns' = ($pnpWorkbook.Workbook.Names["region_dns1_ip"].Value + "," + $pnpWorkbook.Workbook.Names["region_dns2_ip"].Value) + 'domain' = $pnpWorkbook.Workbook.Names["region_ad_child_fqdn"].Value + 'gateway' = $pnpWorkbook.Workbook.Names["reg_seg01_gateway_ip"].Value + 'netmask' = $pnpWorkbook.Workbook.Names["reg_seg01_mask_overlay_backed"].Value + 'searchpath' = $pnpWorkbook.Workbook.Names["child_dns_zone"].Value + 'timeSyncMode' = "ntp" + 'ntp' = $pnpWorkbook.Workbook.Names["region_ntp1_server"].Value + 'isDhcp' = "false" + 'vcfProperties' = '{"vcfEnabled":true,"sddcManagerDetails":[{"sddcManagerHostName":"' + $pnpWorkbook.Workbook.Names["sddc_mgr_fqdn"].Value + '","sddcManagerName":"default","sddcManagerVmid":"default"}]}' + } + + $infrastructureObject = @() + $infrastructureObject += [pscustomobject]@{ + 'properties' = ($infrastructurePropertiesObject | Select-Object -Skip 0) + } + + ### Generate the Properties Details + $productPropertiesObject = @() + $productPropertiesObject += [pscustomobject]@{ + 'certificate' = ("locker:certificate:" + $($vrliCertificate.vmid) + ":" + $($vrliCertificate.alias)) + 'productPassword' = ("locker:password:" + $($vrliPassword.vmid) + ":" + $($vrliPassword.alias)) + 'adminEmail' = $pnpWorkbook.Workbook.Names["region_vrli_admin_email"].Value + 'fipsMode' = "false" + 'licenseRef' = ("locker:license:" + $($vrliLicense.vmid) + ":" + $($vrliLicense.alias)) + 'nodeSize' = $pnpWorkbook.Workbook.Names["region_vrli_appliance_size"].Value.ToLower() + 'configureClusterVIP' = "false" + 'affinityRule' = $false + 'isUpgradeVmCompatibility' = $false + 'vrliAlwaysUseEnglish' = $false + 'masterVidmEnabled' = $false + 'configureAffinitySeparateAll' = "true" + 'ntp' = $pnpWorkbook.Workbook.Names["region_ntp1_server"].Value + 'timeSyncMode' = "ntp" + } + + #### Generate vRealize Log Insight Cluster Details + $clusterVipProperties = @() + $clusterVipProperties += [pscustomobject]@{ + 'hostName' = $pnpWorkbook.Workbook.Names["region_vrli_virtual_fqdn"].Value + 'ip' = $pnpWorkbook.Workbook.Names["region_vrli_virtual_ip"].Value + } + + $clusterVipsObject = @() + $clusterVipsObject += [pscustomobject]@{ + 'type' = "vrli-cluster-1" + 'properties' = ($clusterVipProperties | Select-Object -Skip 0) + } + + $clusterObject = @() + $clusterObject += [pscustomobject]@{ + 'clusterVips' = $clusterVipsObject + } + + #### Generate vRealize Log Insight Node Details + $masterProperties = @() + $masterProperties += [pscustomobject]@{ + 'vmName' = $pnpWorkbook.Workbook.Names["region_vrli_nodea_hostname"].Value + 'hostName' = $pnpWorkbook.Workbook.Names["region_vrli_nodea_fqdn"].Value + 'ip' = $pnpWorkbook.Workbook.Names["region_vrli_nodea_ip"].Value + 'folderName' = $pnpWorkbook.Workbook.Names["region_vrli_vm_folder"].Value + } + + $worker1Properties = @() + $worker1Properties += [pscustomobject]@{ + 'vmName' = $pnpWorkbook.Workbook.Names["region_vrli_nodeb_hostname"].Value + 'hostName' = $pnpWorkbook.Workbook.Names["region_vrli_nodeb_fqdn"].Value + 'ip' = $pnpWorkbook.Workbook.Names["region_vrli_nodeb_ip"].Value + } + + $worker2Properties = @() + $worker2Properties += [pscustomobject]@{ + 'vmName' = $pnpWorkbook.Workbook.Names["region_vrli_nodec_hostname"].Value + 'hostName' = $pnpWorkbook.Workbook.Names["region_vrli_nodec_fqdn"].Value + 'ip' = $pnpWorkbook.Workbook.Names["region_vrli_nodec_ip"].Value + } + + $nodesObject = @() + $nodesobject += [pscustomobject]@{ + 'type' = "vrli-master" + 'properties' = ($masterProperties | Select-Object -Skip 0) + } + $nodesobject += [pscustomobject]@{ + 'type' = "vrli-worker" + 'properties' = ($worker1Properties | Select-Object -Skip 0) + } + $nodesobject += [pscustomobject]@{ + 'type' = "vrli-worker" + 'properties' = ($worker2Properties | Select-Object -Skip 0) + } + + #### Generate the vRealize Log Insight Properties Section + $vcfVersion = ((Get-VCFManager).version -Split ('\.\d{1}\-\d{8}')) -split '\s+' -match '\S' + if ($vcfVersion -eq "4.3.0") { $vrliVersion = "8.4.0"} + if ($vcfVersion -eq "4.3.1") { $vrliVersion = "8.4.1"} + if ($vcfVersion -eq "4.4.0") { $vrliVersion = "8.6.2"} + $productsObject = @() + $productsObject += [pscustomobject]@{ + 'id' = "vrli" + 'version' = $vrliVersion + 'properties' = ($productPropertiesObject | Select-Object -Skip 0) + 'clusterVIP' = ($clusterObject | Select-Object -Skip 0) + 'nodes' = $nodesObject + } + + $vrliDeploymentObject = @() + $vrliDeploymentObject += [pscustomobject]@{ + 'environmentName' = $pnpWorkbook.Workbook.Names["vrslcm_reg_env"].Value + 'infrastructure' = ($infrastructureObject | Select-Object -Skip 0) + 'products' = $productsObject + } + + $vrliDeploymentObject | ConvertTo-Json -Depth 12 | Out-File -Encoding UTF8 -FilePath "vrliDeploymentSpec.json" + + Close-ExcelPackage $pnpWorkbook -NoSave -ErrorAction SilentlyContinue + Write-Output "Creation of Deployment JSON Specification file for vRealize Log Insight: SUCCESSFUL" + } + else { + Write-Error "Unable to find Admin Password with alias ($($pnpWorkbook.Workbook.Names["region_vrli_admin_password_alias"].Value)) in the vRealize Suite Lifecycle Manager Locker: PRE_VALIDATION_FAILED" + } + } + else { + Write-Error "Unable to find Certificate with alias ($($pnpWorkbook.Workbook.Names["region_vrli_virtual_hostname"].Value)) in the vRealize Suite Lifecycle Manager Locker: PRE_VALIDATION_FAILED" + } + } + else { + Write-Error "Unable to find License key ($licenseKey) in the vRealize Suite Lifecycle Manager Locker: PRE_VALIDATION_FAILED" + } + } + } + } + } + } + } + Catch { + Debug-ExceptionWriter -object $_ + } +} +Export-ModuleMember -Function Export-vRLIJsonSpec + +Function New-vRLIDeployment { + <# + .SYNOPSIS + Deploy vRealize Log Insight Cluster via vRealize Suite Lifecycle Manager + + .DESCRIPTION + The New-vRLIDeployment cmdlet deploys vRealize Log Insight via vRealize Suite Lifecycle Manager. The cmdlet + connects to SDDC Manager using the -server, -user, and -password values. + - Validates that the Planning and Preparation provided is available + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that vRealize Suite Lifecycle Manager has been deployed in VCF-aware mode and retrieves its details + - Validates that network connectivity and authentication is possible to vRealize Suite Lifecycle Manager + - Validates that the environment does not already exist in vRealize Suite Lifecycle Manager + - Requests a new deployment of vRealize Log Insight via vRealize Suite Lifecycle Manager + + .EXAMPLE + New-vRLIDeployment -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -workbook .\pnp-workbook.xlsx + This example starts a deployment of vRealize Log Inisght via vRealize Suite Lifecycle Manager using the Planning and Preparation Workbook data + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$workbook, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$monitor + ) + + Try { + + if (!$PsBoundParameters.ContainsKey("workbook")) { + $workbook = Get-ExternalFileName -title "Select the Planning and Preparation Workbook (.xlsx)" -fileType "xlsx" -location "default" + } + else { + if (!(Test-Path -Path $workbook)) { + Write-Error "Planning and Preparation Workbook (.xlsx) ($workbook), File Not Found" + Break + } + } + + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-vRSLCMConnection -server $vcfVrslcmDetails.fqdn) { + if (Test-vRSLCMAuthentication -server $vcfVrslcmDetails.fqdn -user $vcfVrslcmDetails.adminUser -pass $vcfVrslcmDetails.adminPass) { + Export-vRLIJsonSpec -server $server -user $user -pass $pass -workbook $workbook | Out-Null + $json = (Get-Content -Raw .\vrliDeploymentSpec.json) + $jsonSpec = $json | ConvertFrom-Json + if (!($environmentExists = (Get-vRSLCMEnvironment | Where-Object {$_.environmentName -eq $($jsonSpec.environmentName)}))) { + if (Get-vRSLCMLockerPassword -alias $($jsonSpec.products.properties.productPassword.Split(":")[3])) { + if (Get-vRSLCMLockerCertificate | Where-Object {$_.alias -Match $($jsonSpec.products.properties.certificate.Split(":")[3])}) { + if (Get-vRSLCMLockerLicense | Where-Object {$_.alias -Match $($jsonSpec.products.properties.licenseRef.Split(":")[3])}) { + $newRequest = Add-vRSLCMEnvironment -json $json + if ($newRequest) { + if ($PsBoundParameters.ContainsKey("monitor")) { + Start-Sleep 10 + Watch-vRSLCMRequest -vmid $($newRequest.requestId) + } + else { + Write-Output "Deployment Request for vRealize Log Insight Submitted Successfully (Request Ref: $($newRequest.requestId))" + } + } + else { + Write-Error "Request to deploy vRealize Log Insight failed, check the vRealize Suite Lifecycle Manager UI: POST_VALIDATION_FAILED" + } + } + else { + Write-Error "License with alias ($($jsonSpec.products.properties.licenseRef.Split(":")[3])) does not exist in the locker: PRE_VALIDATION_FAILED" + } + } + else { + Write-Error "Certificate with alias ($($jsonSpec.products.properties.certificate.Split(":")[3])) does not exist in the locker: PRE_VALIDATION_FAILED" + } + } + else { + Write-Error "Password with alias ($($jsonSpec.products.properties.productPassword.Split(":")[3])) does not exist in the locker: PRE_VALIDATION_FAILED" + } + } + else { + Write-Warning "Environment with name ($($jsonSpec.environmentName)) already exists in vRealize Suite Lifecyle Manager ($($vcfVrslcmDetails.fqdn)) with a status of ($($environmentExists.environmentStatus)): SKIPPED" + } + } + } + } + } + } + } + Catch { + Debug-ExceptionWriter -object $_ + } +} +Export-ModuleMember -Function New-vRLIDeployment + +Function Undo-vRLIDeployment { + <# + .SYNOPSIS + Remove the vRealize Log Insight Environment from vRealize Suite Lifecycle Manager + + .DESCRIPTION + The Undo-vRLIDeployment cmdlet removes vRealize Log Insight from vRealize Suite Lifecycle Manager. The cmdlet + connects to SDDC Manager using the -server, -user, and -password values. + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to vRealize Suite Lifecycle Manager + - Validates that the environment exist in vRealize Suite Lifecycle Manager + - Requests a the deletion of vRealize Log Insight from vRealize Suite Lifecycle Manager + + .EXAMPLE + Undo-vRLIDeployment -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -environmentName sfo-region-env + This example starts a removal of vRealize Log Inisght from vRealize Suite Lifecycle Manager + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$environmentName, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$monitor + ) + + Try { + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if ($vcfVrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass) { + if (Test-vRSLCMConnection -server $vcfVrslcmDetails.fqdn) { + if (Test-vRSLCMAuthentication -server $vcfVrslcmDetails.fqdn -user $vcfVrslcmDetails.adminUser -pass $vcfVrslcmDetails.adminPass) { + if (Get-vRSLCMEnvironment | Where-Object {$_.environmentName -eq $environmentName}) { + $newRequest = Remove-vRSLCMEnvironment -environmentId (Get-vRSLCMEnvironment | Where-Object {$_.environmentName -eq $environmentName}).environmentId + if ($newRequest) { + if ($PsBoundParameters.ContainsKey("monitor")) { + Start-Sleep 10 + Watch-vRSLCMRequest -vmid $($newRequest.requestId) + if (!(Get-vRSLCMEnvironment | Where-Object {$_.environmentName -eq $environmentName})) { + Write-Output "Removal of vRealize Log Insight from vRealize Suite Lifecyle Manager ($($vcfVrslcmDetails.fqdn)): SUCCESSFUL" + } + else { + Write-Error "Removal of vRealize Log Insight from vRealize Suite Lifecyle Manager ($($vcfVrslcmDetails.fqdn)): POST_VALIDATION_FAILED" + } + } + else { + Write-Output "Removal request of vRealize Log Insight Submitted Successfully (Request Ref: $($newRequest.requestId))" + } + } + else { + Write-Error "Removel request of vRealize Log Insight failed, check the vRealize Suite Lifecycle Manager UI: POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Environment with name ($environmentName) in vRealize Suite Lifecyle Manager ($($vcfVrslcmDetails.fqdn)), already removed: SKIPPED" + } + } + } + } + } + } + } + Catch { + Debug-ExceptionWriter -object $_ + } +} +Export-ModuleMember -Function Undo-vRLIDeployment + +Function Add-vRLISmtpConfiguration { + <# + .SYNOPSIS + Configure SMTP settings in vRealize Log Insight + + .DESCRIPTION + The Add-vRLISmtpConfiguration cmdlet configures the SMTP sever settings in vRealize Log Insight. The cmdlet + connects to SDDC Manager using the -server, -user, and -password values. + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details + - Validates that network connectivity and authentication is possible to vRealize Log Insight + - Validates that network connectivity is possible to the SMTP server + - Configures SMTP server settings in vRealize Log Insight if not already configured + + .EXAMPLE + Add-vRLISmtpConfiguration -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -smtpServer smtp.rainpole.io -port 25 -sender administrator@rainpole.io + This example configures the SMTP server settings on vRealize Log Insight + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$smtpServer, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$port, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sender, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$smtpUser, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$smtpPass + ) + + Try { + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) { + if (Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass) { + if (Test-Connection -ComputerName $smtpServer -Quiet -Count 1) { + if (!(Get-vRLISmtpConfiguration | Where-Object {$_.server -eq $smtpServer})) { + Set-vRLISmtpConfiguration -smtpServer $smtpServer -port $port -sender $sender -username $smtpUser -password $smtpPass | Out-Null + if (Get-vRLISmtpConfiguration | Where-Object {$_.server -eq $smtpServer}) { + Write-Output "Configuring SMTP Server in vRealize Log Insight ($($vcfVrliDetails.fqdn)) with SMTP server ($smtpServer): SUCCESSFUL" + } + else { + Write-Error "Configuring SMTP Server in vRealize Log Insight ($($vcfVrliDetails.fqdn)) with SMTP server ($smtpServer): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Configuring SMTP Server in vRealize Log Insight ($($vcfVrliDetails.fqdn)) with SMTP server ($smtpServer), already exists: SKIPPED" + } + } + else { + Write-Error "Unable to communicate with SMTP Server ($smtpServer), check details: PRE_VALIDATION_FAILED" + } + } + } + } + } + } + } + Catch { + Debug-ExceptionWriter -object $_ + } +} +Export-ModuleMember -Function Add-vRLISmtpConfiguration + +Function Add-vRLIAuthenticationWSA { + <# + .SYNOPSIS + Configure vRealize Log Insight Intergration with Workspace ONE Access + + .DESCRIPTION + The Add-vRLIAuthenticationWSA cmdlet configures role assignments in NSX Manager. The cmdlet connects to SDDC + Manager using the -server, -user, and -password values. + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details + - Validates that network connectivity and authentication is possible to vRealize Log Insight + - Validates that network connectivity is possible to Workspace ONE Access + - Configures Workspace ONE Access Integration on vRealize Log Insight if not already configured + + .EXAMPLE + Add-vRLIAuthenticationWSA -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -wsaFqdn sfo-wsa01.sfo.rainpole.io -wsaUser admin -wsaPass VMw@re1! + This example enables Workspace ONE Access integration on vRealize Suite Lifecycle Manager + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaFqdn, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaUser, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaPass + ) + + Try { + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) { + if (Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass) { + if (Test-Connection -ComputerName $wsaFqdn -Quiet -Count 1) { + if ((Get-vRLIAuthenticationWSA).enabled -eq $false) { + Set-vRLIAuthenticationWSA -hostname $wsaFqdn -port 443 -redirectUrl $vcfVrliDetails.fqdn -username $wsaUser -password $wsaPass + if ((Get-vRLIAuthenticationWSA).enabled -eq $true) { + Write-Output "Configuring Workspace ONE Access Integration in vRealize Log Insight ($($vcfVrliDetails.fqdn)) with ($wsaFqdn): SUCCESSFUL" + } + else { + Write-Error "Configuring Workspace ONE Access Integration in vRealize Log Insight ($($vcfVrliDetails.fqdn)) with ($wsaFqdn): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Configuring Workspace ONE Access Integration in vRealize Log Insight ($($vcfVrliDetails.fqdn)) with ($wsaFqdn), already exists: SKIPPED" + } + } + else { + Write-Error "Unable to communicate with Workspace ONE Access Instance ($wsaFqdn), check details: POST_VALIDATION_FAILED" + } + } + } + } + } + } + } + Catch { + Debug-ExceptionWriter -object $_ + } +} +Export-ModuleMember -Function Add-vRLIAuthenticationWSA + +Function Install-vRLIPhotonAgent { + <# + .SYNOPSIS + Install vRealize Log Insight Photon Agent in a Virtual Machine + + .DESCRIPTION + The Install-vRLIPhotonAgent cmdlet installs and configures the vRealize Log Insight Photon Agent on a virtual + machine. The cmdlet connects to SDDC Manager using the -server, -user, and -password values. + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details + - Validates that network connectivity and authentication is possible to vRealize Log Insight + - Validates that network connectivity and authentication is possible to vCenter Server + - Validates that the Virtual Machine exists in the vCenter Server inventory + - Downloads and Installs the Photon Agent on the Virtual Machne + - Configures the liagent.ini file to communicate with vRealize Log Insight + + .EXAMPLE + Install-vRLIPhotonAgent -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -vmName sfo-wsa01 -vmRootPass VMw@re1! + This example installs and configures the vRealize Log Insight Agent on the virtual machine named 'sfo-wsa01' + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vmName, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vmRootPass + ) + + Try { + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) { + if (Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass) { + if (($vcfVcenterDetails = Get-VcenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) { + if (Test-VsphereConnection -server $vcfVcenterDetails.fqdn) { + if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + if (Get-VM -Name $vmName -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue) { + $output = Invoke-VMScript -VM $vmName -ScriptText "systemctl status liagentd" -GuestUser root -GuestPassword $vmRootPass -Server $vcfVcenterDetails.fqdn + if ($output.ScriptOutput.Contains("/lib/systemd/system/liagentd.service; enabled")) { + Write-Warning "Installing and Configuring vRealize Log Insight Agent Installed and Configured on ($vmName), already exists: SKIPPED" + } + else { + Invoke-VMScript -VM $vmName -ScriptText "rm /tmp/liagent.rpm && rm /tmp/installAgent.sh && /tmp/configureAgent.sh" -GuestUser root -GuestPassword $vmRootPass -Server $vcfVcenterDetails.fqdn | Out-Null + $installAgent = @( + "curl -k -o /tmp/liagent.rpm https://$($vcfVrliDetails.fqdn)/api/v1/agent/packages/types/rpm; rpm -Uvh /tmp/liagent.rpm", + "systemctl enable liagentd", + "systemctl status liagentd" + ) + foreach ($line in $installAgent) { + Invoke-VMScript -VM $vmName -ScriptText "echo ""$line"">>/tmp/installAgent.sh" -GuestUser root -GuestPassword $vmRootPass -Server $vcfVcenterDetails.fqdn | Out-Null + } + $output = Invoke-VMScript -VM $vmName -ScriptText "chmod 777 /tmp/installAgent.sh && /tmp/installAgent.sh" -GuestUser root -GuestPassword $vmRootPass -Server $vcfVcenterDetails.fqdn + if ($output.ScriptOutput.Contains("/lib/systemd/system/liagentd.service; enabled")) { + $configureAgent = @( + "sed -i 's/;hostname=LOGINSIGHT/hostname=$($vcfVrliDetails.fqdn)/' /var/lib/loginsight-agent/liagent.ini", + "sed -i 's/;proto=cfapi/proto=cfapi/' /var/lib/loginsight-agent/liagent.ini", + "sed -i 's/;port=9543/port=9000/' /var/lib/loginsight-agent/liagent.ini", + "sed -i 's/;ssl=yes/ssl=no/' /var/lib/loginsight-agent/liagent.ini", + "systemctl restart liagentd", + "systemctl status liagentd" + ) + foreach ($line in $configureAgent) { + Invoke-VMScript -VM $vmName -ScriptText "echo ""$line"">>/tmp/configureAgent.sh" -GuestUser root -GuestPassword $vmRootPass -Server $vcfVcenterDetails.fqdn | Out-Null + } + $output = Invoke-VMScript -VM $vmName -ScriptText "chmod 777 /tmp/configureAgent.sh && /tmp/configureAgent.sh" -GuestUser root -GuestPassword $vmRootPass -Server $vcfVcenterDetails.fqdn + if ($output.ScriptOutput.Contains("active (running)")) { + Write-Output "Installing and Configuring vRealize Log Insight Agent Installed and Configured on ($vmName): SUCCESSFUL" + } + else { + Write-Error "Installing and Configuring vRealize Log Insight Agent Installed and Configured on ($vmName): POST_VALIDATION_FAILED" + } + } + else { + Write-Error "Enabling vRealize Log Insight Agent Installed and Configured on ($vmName): POST_VALIDATION_FAILED" + } + } + } + else { + Write-Error "Virtual Machine ($vmName), not Found in vCenter Server ($($vcfVcenterDetails.fqdn)) Inventory, check details and try again: PRE_VALIDATION_FAILED" + } + } + } + } + } + } + } + } + } + } + Catch { + Debug-ExceptionWriter -object $_ + } +} +Export-ModuleMember -Function Install-vRLIPhotonAgent + +Function Undo-vRLIPhotonAgent { + <# + .SYNOPSIS + Removes the vRealize Log Insight Photon Agent from a Virtual Machine + + .DESCRIPTION + The Undo-vRLIPhotonAgent cmdlet removes the vRealize Log Insight Photon Agent from a virtual + machine. The cmdlet connects to SDDC Manager using the -server, -user, and -password values. + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details + - Validates that network connectivity and authentication is possible to vRealize Log Insight + - Validates that network connectivity and authentication is possible to vCenter Server + - Validates that the Virtual Machine exists in the vCenter Server inventory + - Removes the Photon Agent from the Virtual Machne + + .EXAMPLE + Undo-vRLIPhotonAgent -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -vmName sfo-wsa01 -vmRootPass VMw@re1! + This example removes the vRealize Log Insight Agent from the virtual machine named 'sfo-wsa01' + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vmName, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vmRootPass + ) + + Try { + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) { + if (($vcfVcenterDetails = Get-VcenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) { + if (Test-VsphereConnection -server $vcfVcenterDetails.fqdn) { + if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + if (Get-VM -Name $vmName -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue) { + $output = Invoke-VMScript -VM $vmName -ScriptText "systemctl status liagentd" -GuestUser root -GuestPassword $vmRootPass -Server $vcfVcenterDetails.fqdn + if ($output.ScriptOutput.Contains("/lib/systemd/system/liagentd.service; enabled")) { + Invoke-VMScript -VM $vmName -ScriptText "curl -k -o /tmp/liagent.rpm https://$($vcfVrliDetails.fqdn)/api/v1/agent/packages/types/rpm; package=`$(rpm -q /tmp/liagent.rpm); rpm -e `$package; systemctl daemon-reload" -GuestUser root -GuestPassword $vmRootPass -Server $vcfVcenterDetails.fqdn | Out-Null + $output = Invoke-VMScript -VM $vmName -ScriptText "systemctl status liagentd" -GuestUser root -GuestPassword $vmRootPass -Server $vcfVcenterDetails.fqdn + if ($output.ScriptOutput.Contains("liagentd.service could not be found")) { + Write-Output "Removing vRealize Log Insight Agent from ($vmName): SUCCESSFUL" + } + else { + Write-Error "Removing vRealize Log Insight Agent from ($vmName): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Removing vRealize Log Insight Agent from ($vmName), already performed: SKIPPED" + } + } + else { + Write-Error "Virtual Machine ($vmName), not Found in vCenter Server ($($vcfVcenterDetails.fqdn)) Inventory, check details and try again: PRE_VALIDATION_FAILED" + } + } + } + } + } + } + } + } + } + Catch { + Debug-ExceptionWriter -object $_ + } +} +Export-ModuleMember -Function Undo-vRLIPhotonAgent + +Function Add-vRLIAgentGroup { + <# + .SYNOPSIS + Creates an agent group in vRealize Log Insight + + .DESCRIPTION + The Add-vRLIAgentGroup cmdlet creates a new agent group in vRealize Log Insight. The cmdlet connects to SDDC + Manager using the -server, -user, and -password values. + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details + - Validates that network connectivity and authentication is possible to vRealize Log Insight + - Creates an agent group in the vRealize Log Insight if not already configured + + .EXAMPLE + Add-vRLIAgentGroup -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -agentGroupType wsa -agentGroupName "Workspace ONE Access - Appliance Agent Group" -criteria "xint-wsa01a.rainpole.io","xint-wsa01b.rainpole.io","xint-wsa01c.rainpole.io" + This example creates an agent group for Workspace ONE Access in vRealize Log Insight and assigns the Cluster Virtual Machines + + .EXAMPLE + Add-vRLIAgentGroup -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -agentGroupType photon -agentGroupName "Photon OS - Appliance Agent Group" -criteria "sfo-vcf01.sfo.rainpole.io","xint-vrslcm01.rainpole.io","xint-wsa01a.rainpole.io","xint-wsa01b.rainpole.io","xint-wsa01c.rainpole.io" + This example creates an agent group for Photon OS in vRealize Log Insight and assigns the SDDC Manager, vRealize Suite Lifecycle Manager and Workspace ONE Access Cluster Virtual Machines + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$agentGroupName, + [Parameter (Mandatory = $true)] [ValidateSet("wsa","photon")] [ValidateNotNullOrEmpty()] [String]$agentGroupType, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Array]$criteria + ) + + Try { + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) { + if (Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass) { + if (!(Get-vRLIAgentGroup | Select-Object name | Where-Object {$_.name -eq $agentGroupName})) { + New-vRLIAgentGroup -agentGroupType $agentGroupType -criteria $criteria -agentGroupName $agentGroupName | Out-Null + if (Get-vRLIAgentGroup | Select-Object name | Where-Object {$_.name -eq $agentGroupName}) { + Write-Output "Creating Agent Group in vRealize Log Insight ($($vcfVrliDetails.fqdn)) for ($agentGroupName): SUCCESSFUL" + } + else { + Write-Error "Creating Agent Group in vRealize Log Insight ($($vcfVrliDetails.fqdn)) for ($agentGroupName): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Creating Agent Group in vRealize Log Insight ($($vcfVrliDetails.fqdn)) for ($agentGroupName), already exists: SKIPPED" + } + } + } + } + } + } + } + Catch { + Debug-ExceptionWriter -object $_ + } +} +Export-ModuleMember -Function Add-vRLIAgentGroup + +Function Register-vRLIWorkloadDomain { + <# + .SYNOPSIS + Connect a Workload Domain to vRealize Log Insight + + .DESCRIPTION + The Register-vRLIWorkloadDomain cmdlet connects a Workload Domain to vRealize Log Insight. The cmdlet connects + to SDDC Manager using the -server, -user, and -password values. + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details + - Validates that network connectivity and authentication is possible to vRealize Log Insight + - Obtains the Workload Domain details from the SDDC Manager inventory + - Connects the Workload Domain with vRealize Log Insight if not already configured + + .EXAMPLE + Register-vRLIWorkloadDomain -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -status ENABLED + This example ENABLES the Workload Domain in vRealize Log Insight + + .EXAMPLE + Register-vRLIWorkloadDomain -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -status DISABLED + This example DISABLES the Workload Domain in vRealize Log Insight + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, + [Parameter (Mandatory = $true)] [ValidateSet("ENABLED", "DISABLED")] [String]$status + ) + + Try { + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) { + if (Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass) { + if (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}) { + if ((Get-VCFvRLIConnection | Where-Object {$_.domainId -eq (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}).id}).status -ne $status) { + Set-VCFvRLIConnection -domainId (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}).id -status $status | Out-Null + Do { + $configStatus = (Get-VCFvRLIConnection | Where-Object {$_.domainId -eq (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}).id}).status + } Until ($configStatus -ne "IN_PROGRESS") + if ((Get-VCFvRLIConnection | Where-Object {$_.domainId -eq (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}).id}).status -eq $status) { + Write-Output "Workload Domain Intergration in vRealize Log Insight ($($vcfVrliDetails.fqdn)) for Workload Domain ($domain): SUCCESSFUL" + } + else { + Write-Error "Workload Domain Intergration in vRealize Log Insight ($($vcfVrliDetails.fqdn)) for Workload Domain ($domain): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Workload Domain Intergration in vRealize Log Insight ($($vcfVrliDetails.fqdn)) for Workload Domain ($domain), already exists: SKIPPED" + } + } + else { + Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" + } + } + } + } + } + } + } + Catch { + Debug-ExceptionWriter -object $_ + } +} +Export-ModuleMember -Function Register-vRLIWorkloadDomain + +Function Set-vRLISyslogEdgeCluster { + <# + .SYNOPSIS + Configure Syslog settings on NSX Edge Cluster Nodes + + .DESCRIPTION + The Set-vRLISyslogEdgeCluster cmdlet configures Syslog settings on NSX Edge Cluster The cmdlet connects to SDDC + Manager using the -server, -user, and -password values. + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details + - Validates that network connectivity and authentication is possible to NSX Management Cluster + - Gathers the NSX Edge Node details from NSX Management Cluster + - Configures the Syslog settings on the NSX Edge Node if not already configured + + .EXAMPLE + Set-vRLISyslogEdgeCluster -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -exportname SFO-VRLI + This example configures the Syslog settings for each NSX Edge node to sent logs to vRealize Log Insight + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$exportName + ) + + Try { + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + $vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass + if ($nsxtManagerDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain -listNodes) { + if (Test-NSXTConnection -server $nsxtManagerDetails.fqdn) { + if (Test-NSXTAuthentication -server $nsxtManagerDetails.fqdn -user $nsxtManagerDetails.adminUser -pass $nsxtManagerDetails.AdminPass) { + [Array]$edgeNodeIds = (Get-NsxtEdgeCluster).members.transport_node_id + foreach ($nodeId in $edgeNodeIds) { + if (!(Get-NsxtSyslogExporter -transport -id $nodeId | Where-Object {$_.exporter_name -eq $exportName})) { + if (!(Get-NsxtSyslogExporter -transport -id $nodeId | Where-Object {$_.server -eq $vcfVrliDetails.fqdn})) { + Set-NsxtSyslogExporter -transport -id $nodeId -exporterName $exportName -logLevel INFO -port 514 -protocol TCP -server $vcfVrliDetails.fqdn | Out-Null + if (Get-NsxtSyslogExporter -transport -id $nodeId | Where-Object {$_.exporter_name -eq $exportName}) { + Write-Output "Configuring Syslog Exporter ($exportName) on Edge Node ($nodeId): SUCCESSFUL" + } + else { + Write-Error "Configuring Syslog Exporter ($exportName) on Edge Node ($nodeId): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Configuring Syslog Server ($($vcfVrliDetails.fqdn)) on Edge Node ($nodeId), already exists: SKIPPED" + } + } + else { + Write-Warning "Configuring Syslog Exporter ($exportName) on Edge Node ($nodeId), already exists: SKIPPED" + } + } + } + } + } + } + } + } + Catch { + Debug-ExceptionWriter -object $_ + } +} +Export-ModuleMember -Function Set-vRLISyslogEdgeCluster + +Function Undo-vRLISyslogEdgeCluster { + <# + .SYNOPSIS + Removes the Syslog settings on NSX Edge Cluster Nodes + + .DESCRIPTION + The Undo-vRLISyslogEdgeCluster cmdlet removes the Syslog settings on NSX Edge Cluster. The cmdlet connects to + SDDC Manager using the -server, -user, and -password values. + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details + - Validates that network connectivity and authentication is possible to NSX Management Cluster + - Gathers the NSX Edge Node details from NSX Management Cluster + - Removes the Syslog settings on the NSX Edge Node + + .EXAMPLE + Undo-vRLISyslogEdgeCluster -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -exportname SFO-VRLI + This example removes the Syslog settings for each NSX Edge node + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$exportName + ) + + Try { + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if ($nsxtManagerDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain -listNodes) { + if (Test-NSXTConnection -server $nsxtManagerDetails.fqdn) { + if (Test-NSXTAuthentication -server $nsxtManagerDetails.fqdn -user $nsxtManagerDetails.adminUser -pass $nsxtManagerDetails.AdminPass) { + [Array]$edgeNodeIds = (Get-NsxtEdgeCluster).members.transport_node_id + Foreach ($nodeId in $edgeNodeIds) { + if (Get-NsxtSyslogExporter -transport -id $nodeId | Where-Object {$_.exporter_name -eq $exportName}) { + Remove-NsxtSyslogExporter -transport -id $nodeId -exporterName $exportName | Out-Null + if (!(Get-NsxtSyslogExporter -transport -id $nodeId | Where-Object {$_.exporter_name -eq $exportName})) { + Write-Output "Removing Syslog Exporter ($exportName) on Edge Node ($nodeId): SUCCESSFUL" + } + else { + Write-Error "Removing Syslog Exporter ($exportName) on Edge Node ($nodeId): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Removing Syslog Exporter ($exportName) on Edge Node ($nodeId), already removed: SKIPPED" + } + } + } + } + } + } + } + } + Catch { + Debug-ExceptionWriter -object $_ + } +} +Export-ModuleMember -Function Undo-vRLISyslogEdgeCluster + +Function Add-vRLILogArchive { + <# + .SYNOPSIS + Configure log archiving in vRealize Log Insight + + .DESCRIPTION + The Add-vRLILogArchive cmdlet configure log archiving in vRealize Log Insight. The cmdlet connects to SDDC + Manager using the -server, -user, and -password values. + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details + - Validates that network connectivity and authentication is possible to vRealize Log Insight + - Configure an email address to send notifications to in vRealize Log Insight + - Configure the log retention threshold in vRealize Log Insight + - Configure log archive location in vRealize Log Insight + + .EXAMPLE + Add-vRLILogArchive -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -emailAddress administrator@rainpole.io -retentionNotificationDays 1 -retentionInterval weeks -retentionPeriodDays 7 -archiveLocation "nfs://172.27.11.4/sfo-m01-vrli01-400GB" + This example configures the log archive and retention period in vRealize Log Insight + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$emailAddress, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Int]$retentionNotificationDays, + [Parameter (Mandatory = $true)] [ValidateSet("minutes","hours","days","weeks","months")] [ValidateNotNullOrEmpty()] [String]$retentionInterval, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Int]$retentionPeriodDays, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$archiveLocation + ) + + Try { + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) { + if (Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass) { + Set-vRLIEmailNotification -emailAddress $emailAddress | Out-Null + Set-vRLIRetentionThreshold -enable true -interval $retentionNotificationDays -intervalUnit $retentionInterval | Out-Null + $partitionId = (Get-vRLIIndexPartition).id + Set-vRLILogArchive -id $partitionId -enable true -retentionPeriod $retentionPeriodDays -archiveEnable true -archiveLocation $archiveLocation + Write-Output "Configuring Email Notifications, Retention Period and Archive Location in vRealize Log Insight ($($vrliDetails.fqdn)): SUCCESSFUL" + } + } + } + } + } + } + Catch { + Debug-ExceptionWriter -object $_ + } +} +Export-ModuleMember -Function Add-vRLILogArchive + +Function Add-vRLIAuthenticationGroup { + <# + .SYNOPSIS + Adds a group from the authentication provider in vRealize Log Insight + + .DESCRIPTION + The Add-vRLIAuthenticationGroup cmdlet assigns access to a group based on the authentication providor. The cmdlet + connects to SDDC Manager using the -server, -user, and -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details + - Validates that network connectivity and authentication is possible to vRealize Log Insight + - Validates that integration with Workspace ONE Access has been enabled + - Validates that the group has not already been assigned access to vRealize Log Insight + - Adds the group to the access control assigning the role provided in vRealize Log Insight + + .EXAMPLE + Add-vRLIAuthenticationGroup -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo.rainpole.io -group gg-vrli-admins -role 'Super Admin' + This example adds the group gg-vrli-admins with Super Admin role in vRealize Log Insight + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$group, + [ValidateSet("Super Admin","User","Dashboard User","View Only Admin")] [ValidateNotNullOrEmpty()] [String]$role + ) + + Try { + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if ($vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass) { + if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) { + if (Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass) { + if (Get-vRLIAuthenticationWSA -eq "True") { + if (!(Get-vRLIGroup -authProvider vidm | Where-Object {$_.name -eq $group + "@" + $domain})) { + Add-vRLIGroup -authProvider vidm -domain $domain -group $group -role $role | Out-Null + if (Get-vRLIGroup -authProvider vidm | Where-Object {$_.name -eq $group + "@" + $domain}) { + Write-Output "Adding Group to vRealize Log Insight ($($vcfVrliDetails.fqdn)), named ($group): SUCCESSFUL" + } + else { + Write-Warning "Adding Group to vRealize Log Insight ($($vcfVrliDetails.fqdn)), named ($group): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Adding Group to vRealize Log Insight ($($vcfVrliDetails.fqdn)), named ($group), already exists: SKIPPED" + } + } + else { + Write-Error "Workspace ONE Integration on vRealize Log Insight ($($vcfVrliDetails.fqdn)), not enabled: PRE_VALIDATION_FAILED" + } + } + } + } + } + } + } + Catch { + Debug-ExceptionWriter -object $_ + } +} +Export-ModuleMember -Function Add-vRLIAuthenticationGroup + +Function Add-vRLIAlertDatacenter { + <# + .SYNOPSIS + Adds datacenter based alerts in vRealize Log Insight + + .DESCRIPTION + The Add-vRLIAlertsDatacenter cmdlet adds datacenter based alerts to vRealize Log Insight. The cmdlet connects + to SDDC Manager using the -server, -user, and -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details + - Validates that network connectivity and authentication is possible to vRealize Log Insight + - Validates that network connectivity and authentication is possible to vCenter Server + - Validates that vRealize Operations Manager has been deployed in VCF-aware mode and retrieves its details + - Validates that network connectivity and authentication is possible to vRealize Operations Manager + - Validates that the Datacenter object provided is valid in the vCenter Server inventory + - Creates the alert in vRealize Log Insight for the Datacenter object if not already configured + - Integrates with vRealize Operations Manager if the -vropsIntegration switch is provided + + .EXAMPLE + Add-vRLIAlertDatacenter -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -sddcDomainName sfo-m01 -datacenterName sfo-m01-dc01 -email administrator@rainpole.io -alertTemplate ".\SampleNotifications\vrli-vcf-datacenter.json" -vropsIntegration + This example adds the alerts provided in the JSON file + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcDomainName, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$datacenterName, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$email, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$alertTemplate, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$vropsIntegration + ) + + $adapter = "VMWARE" # Defines the vRealize Operations Manager Adapter type + $resource = "Datacenter" # Defines the vRealize Operations Manager Resource type associated with the Adapter + + Try { + if (Test-Path -Path $alertTemplate) { + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass)) { + if ($PsBoundParameters.ContainsKey("vropsIntegration")) { + if (!($vcfVropsDetails = Get-vROPSServerDetail -fqdn $server -username $user -password $pass)) { + Break + } + else { + if (!(Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn)) { Break } + if (!(Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass)) { Break } + } + } + if (($vcfVcenterDetails = Get-VcenterServerDetail -server $server -user $user -pass $pass -domain $sddcDomainName)) { + if (Test-VsphereConnection -server $vcfVcenterDetails.fqdn) { + if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) { + if (Get-Datacenter $datacenterName -ErrorAction Ignore ) { + if (Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass) { + $templateAlerts = (Get-Content -path $alertTemplate -Raw) + $templateAlerts = $templateAlerts -replace '!!datacenterName!!',$datacenterName + $templateAlerts = $templateAlerts -replace '!!email!!',$email + [Array]$allAlerts = $templateAlerts | ConvertFrom-Json + foreach ($alert in $allAlerts) { + $json = $alert | ConvertTo-Json + if ($PsBoundParameters.ContainsKey("vropsIntegration")) { + $entityObjectId =(Get-vROPSResourceDetail -adapter $adapter -resource $resource -objectname $datacenterName | Where-Object {$_.identifierType.name -eq "VMEntityObjectID"}).value + $entityVcid =(Get-vROPSResourceDetail -adapter $adapter -resource $resource -objectname $datacenterName | Where-Object {$_.identifierType.name -eq "VMEntityVCID"}).value + $vcopsResourceKindKey = '"vcopsResourceKindKey": "' + 'resourceName='+$datacenterName+'&adapterKindKey='+$adapter+'&resourceKindKey='+$resource+'&identifiers=VMEntityName::'+$datacenterName+'$$$VMEntityObjectID::'+$entityObjectId+'$$$VMEntityVCID::'+$entityVcid + '"' + $json = $json -replace '"vcopsEnabled": false','"vcopsEnabled": true' + $json = $json -replace '"vcopsResourceKindKey": ""',$vcopsResourceKindKey + } + if (!((Get-vRLIAlert | Select-Object name ) | Where-Object {$_.name -eq $alert.name})) { + Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass | Out-Null + New-vRLIAlert -json $json | Out-Null + } + } + Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue + Write-Output "Adding Datacenter Alerts in vRealize Log Insight ($($vcfVrliDetails.fqdn)) using template Alert JSON ($alertTemplate) for Workload Domain ($sddcDomainName): SUCCESSFUL" + } + } + else { + Write-Error "Unable to find Dataceter ($datacenterName) in vCenter Server ($($vcfVcenterDetails.fqdn)): PRE_VALIDATION_FAILED" + } + } + } + } + } + } + } + } + } + else { + Write-Error "Unable to find template Alert JSON ($alertTemplate): PRE_VALIDATION_FAILED" + } + } + Catch { + Debug-ExceptionWriter -object $_ + } +} +Export-ModuleMember -Function Add-vRLIAlertDatacenter + +Function Add-vRLIAlertVirtualMachine { + <# + .SYNOPSIS + Adds virtual machine based alerts in vRealize Log Insight + + .DESCRIPTION The Add-vRLIAlertVirtualMachine cmdlet adds virtual machine based alerts to vRealize Log Insight. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - Validates that network connectivity and authentication is possible to SDDC Manager @@ -5871,18 +7370,17 @@ Function Add-NsxtNodeProfileSyslogExporter { if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) { if (Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass) { if ($profileExists = Get-NsxtNodeProfile -id $id -ErrorAction SilentlyContinue) { - $displayName = $profileExists.display_name - if (!($checkSyslogExporter = (Get-NsxtNodeProfile -id $id).syslog.exporters | Where-Object {$_.server -eq $vcfVrliDetails.fqdn -and $_.port -eq 514 -and $_.protocol -eq "TCP" -and $_.max_log_level -eq "INFO"})) { + if (!((Get-NsxtNodeProfile -id $id).syslog.exporters | Where-Object {$_.server -eq $vcfVrliDetails.fqdn -and $_.port -eq 514 -and $_.protocol -eq "TCP" -and $_.max_log_level -eq "INFO"})) { Set-NsxtNodeProfileSyslogExporter -id $id -server $vcfVrliDetails.fqdn -port 514 -protocol "TCP" -logLevel "INFO" | Out-Null - if ($checkSyslogExporter = (Get-NsxtNodeProfile -id $id).syslog.exporters | Where-Object {$_.server -eq $vcfVrliDetails.fqdn -and $_.port -eq 514 -and $_.protocol -eq "TCP" -and $_.max_log_level -eq "INFO"}) { - Write-Output "Adding the syslog exporter ($($vcfVrliDetails.fqdn)) to the NSX node profile ($displayName) on NSX Manager ($($vcfNsxDetails.fqdn)): SUCCESSFUL" + if ((Get-NsxtNodeProfile -id $id).syslog.exporters | Where-Object {$_.server -eq $vcfVrliDetails.fqdn -and $_.port -eq 514 -and $_.protocol -eq "TCP" -and $_.max_log_level -eq "INFO"}) { + Write-Output "Adding the syslog exporter ($($vcfVrliDetails.fqdn)) to the NSX node profile ($($profileExists.display_name)) on NSX Manager ($($vcfNsxDetails.fqdn)): SUCCESSFUL" } else { - Write-Error "Adding the syslog exporter ($($vcfVrliDetails.fqdn)) to the NSX node profile ($id) in NSX Manager ($($vcfNsxDetails.fqdn)), check id: FAILED" + Write-Error "Adding the syslog exporter ($($vcfVrliDetails.fqdn)) to the NSX node profile ($id) in NSX Manager ($($vcfNsxDetails.fqdn)): POST_VALIDATION_FAILED" } } else { - Write-Warning "Adding the syslog exporter ($($vcfVrliDetails.fqdn)) to the NSX node profile ($displayName) in NSX Manager ($($vcfNsxDetails.fqdn)), settings already exist: SKIPPED" + Write-Warning "Adding the syslog exporter ($($vcfVrliDetails.fqdn)) to the NSX node profile ($($profileExists.display_name)) in NSX Manager ($($vcfNsxDetails.fqdn)), already exist: SKIPPED" } } else { @@ -5944,22 +7442,21 @@ Function Undo-NsxtNodeProfileSyslogExporter { if (Test-NSXTConnection -server $vcfNsxDetails.fqdn) { if (Test-NSXTAuthentication -server $vcfNsxDetails.fqdn -user $vcfNsxDetails.adminUser -pass $vcfNsxDetails.adminPass) { if ($profileExists = Get-NsxtNodeProfile -id $id -ErrorAction SilentlyContinue) { - $displayName = $profileExists.display_name - if (!($checkSyslogExporter = (Get-NsxtNodeProfile -id $id | Where-Object {$_.syslog -eq $null}))) { + if (!(Get-NsxtNodeProfile -id $id | Where-Object {$null -eq $_.syslog})) { Remove-NsxtNodeProfileSyslogExporter -id $id | Out-Null - if ($checkSyslogExporter = (Get-NsxtNodeProfile -id $id | Where-Object {$_.syslog -eq $null})) { - Write-Output "Removing all syslog exporters from the NSX node profile ($displayName) on NSX Manager ($($vcfNsxDetails.fqdn)): SUCCESSFUL" - } - else { - Write-Error "Removing all syslog exporters from the NSX node profile ($id) in NSX Manager ($($vcfNsxDetail.fqdn)), check id: FAILED" - } + if (Get-NsxtNodeProfile -id $id | Where-Object {$null -eq $_.syslog}) { + Write-Output "Removing all syslog exporters from the NSX node profile ($($profileExists.display_name)) on NSX Manager ($($vcfNsxDetails.fqdn)): SUCCESSFUL" + } + else { + Write-Error "Removing all syslog exporters from the NSX node profile ($id) in NSX Manager ($($vcfNsxDetails.fqdn)): POST_VALIDATION_FAILED" + } } else { - Write-Warning "Removing all syslog exporters from the NSX node profile ($displayName) in NSX Manager ($($vcfNsxDetail.fqdn)), no settings already exist: SKIPPED" + Write-Warning "Removing all syslog exporters from the NSX node profile ($($profileExists.display_name)) in NSX Manager ($($vcfNsxDetails.fqdn)), already removed: SKIPPED" } } else { - Write-Error "The NSX node profile ($id) does not exist in NSX Manager ($($vcfNsxDetail.fqdn)): PRE_VALIDATION_FAILED" + Write-Error "The NSX node profile ($id) does not exist in NSX Manager ($($vcfNsxDetails.fqdn)): PRE_VALIDATION_FAILED" } } } @@ -6938,11 +8435,15 @@ Function Add-vROPSAdapterNsxt { .EXAMPLE Add-vROPSAdapterNsxt -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -collectorGroupName "sfo-remote-collectors" - This example creates an NSX credential for the Management Workload Domain named 'sfo-m01' in vRealize Opertations Manager + This example creates an NSX Adapter for the Management Workload Domain named in vRealize Opertations Manager and assigns to the remote collector group defined .EXAMPLE Add-vROPSAdapterNsxt -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -collectorGroupName "sfo-remote-collectors" - This example creates an NSX credential for the VI Workload Domain named 'sfo-w01' in vRealize Opertations Manager + This example creates an NSX Adapter for the VI Workload Domain named in vRealize Opertations Manager and assigns to the remote collector group defined + + .EXAMPLE + Add-vROPSAdapterNsxt -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 + This example creates an NSX Adapter for the Management Workload Domain named in vRealize Opertations Manager and assigns to the "Default collector group" #> Param ( @@ -6950,7 +8451,7 @@ Function Add-vROPSAdapterNsxt { [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$collectorGroupName + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$collectorGroupName="Default collector group" ) Try { @@ -6964,48 +8465,52 @@ Function Add-vROPSAdapterNsxt { if (Get-vROPSCollectorGroup | Where-Object {$_.name -eq $collectorGroupName}) { if (!(Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $vcfNsxDetails.fqdn})) { if (!(Get-vROPSCredential | Where-Object {$_.name -eq $vcfNsxDetails.fqdn})) { - $json = '{ - "name": "'+ $vcfNsxDetails.fqdn +'", - "description": "NSX-T Adapter - '+ $vcfNsxDetails.fqdn +'", - "adapterKindKey": "NSXTAdapter", - "monitoringInterval": 5, - "collectorGroupId": "'+ (Get-vROPSCollectorGroup | Where-Object {$_.name -eq $collectorGroupName}).id +'", - "resourceIdentifiers": [ - { - "name": "NSXTHOST", - "value": "'+ $vcfNsxDetails.fqdn +'" - } - ], - "credential": { - "name": "'+ $vcfNsxDetails.fqdn +'", - "adapterKindKey": "NSXTAdapter", - "credentialKindKey": "NSXTCREDENTIAL", - "fields": [{ - "name": "USERNAME", - "value": "'+ $vcfNsxDetails.adminUser +'" - }, - { - "name": "PASSWORD", - "value": "'+ $vcfNsxDetails.adminPass +'" - } - ] + $credentialJson = '{ + "name": "'+ $vcfNsxDetails.fqdn +'", + "adapterKindKey": "NSXTAdapter", + "credentialKindKey": "NSXTCREDENTIAL", + "fields": [ + { "name": "USERNAME", "value": "'+ $vcfNsxDetails.adminUser +'" }, + { "name": "PASSWORD", "value": "'+ $vcfNsxDetails.adminPass +'" } + ]}' + $credentialJson | Out-File .\addCredential.json + Add-vROPSCredential -json .\addCredential.json | Out-Null + Remove-Item .\addCredential.json -Force -Confirm:$false + } + $adapterJson = '{ + "name": "'+ $vcfNsxDetails.fqdn +'", + "description": "NSX-T Adapter - '+ $vcfNsxDetails.fqdn +'", + "adapterKindKey": "NSXTAdapter", + "monitoringInterval": 5, + "collectorGroupId": "'+ (Get-vROPSCollectorGroup | Where-Object {$_.name -eq $collectorGroupName}).id +'", + "resourceIdentifiers": [ + { "name": "NSXTHOST", "value": "'+ $vcfNsxDetails.fqdn +'" } + ], + "credential": { + "id": "'+ (Get-vROPSCredential | Where-Object {$_.name -eq $vcfNsxDetails.fqdn}).id +'" } - }' - $json | Out-File .\addAdapter.json - Add-vROPSAdapter -json .\addAdapter.json | Out-Null - - if (Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $vcfNsxDetails.fqdn}) { - Start-vROPSAdapter -adapterId (Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $vcfNsxDetails.fqdn}).id | Out-Null - Write-Output "Adding NSX Adapter in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($($vcfNsxDetails.fqdn)): SUCCESSFUL" - } - else { - Write-Error "Adding NSX Adapter in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($($vcfNsxDetails.fqdn)): POST_VALIDATION_FAILED" - } - Remove-Item .\addAdapter.json -Force -Confirm:$false + }' + $adapterJson | Out-File .\addAdapter.json + Add-vROPSAdapter -json .\addAdapter.json | Out-Null + $testAdapter = Test-vROPSAdapterConnection -json .\addAdapter.json + $testAdapter | ConvertTo-Json -Depth 10 | Out-File .\createdAdapter.json + Test-vROPSAdapterConnection -json .\createdAdapter.json -patch + $adapterDetail = Get-Content -Path .\createdAdapter.json -Raw | ConvertFrom-Json + $adapterDetail.PSObject.Properties.Remove('links') + $adapterDetail.'adapter-certificates' = $adapterDetail.'adapter-certificates' | Select-Object * -ExcludeProperty certificateDetails + $adapterDetail.id = (Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $vcfNsxDetails.fqdn}).id + $adapterDetail | ConvertTo-Json -Depth 100 | Out-File .\patchAdapter.json -Force + Set-vROPSAdapter -json .\patchAdapter.json -patch | Out-Null + if (Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $vcfNsxDetails.fqdn}) { + Start-vROPSAdapter -adapterId (Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $vcfNsxDetails.fqdn}).id | Out-Null + Write-Output "Adding NSX Adapter in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($($vcfNsxDetails.fqdn)): SUCCESSFUL" } else { - Write-Error "Credential in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($($vcfNsxDetails.fqdn)), already exists: PRE_VALIDATION_FAILED" + Write-Error "Adding NSX Adapter in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($($vcfNsxDetails.fqdn)): POST_VALIDATION_FAILED" } + Remove-Item .\addAdapter.json -Force -Confirm:$false + Remove-Item .\createdAdapter.json -Force -Confirm:$false + Remove-Item .\patchAdapter.json -Force -Confirm:$false } else { Write-Warning "Adding NSX Adapter in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($($vcfNsxDetails.fqdn)), already exists: SKIPPED" @@ -7048,6 +8553,10 @@ Function Add-vROPSAdapterPing { .EXAMPLE Add-vROPSAdapterPing -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -addressList "192.168.11.30,192.168.11.31,192.168.11.32,192.168.11.33" -adapterName xint-vrops01 -collectorGroupName "sfo-remote-collectors" This example creates a new Ping adapter called 'xint-vrops01', assigns the IP Addresses provided and assigned the remote collector group called 'sfo-remote-collectors' + + .EXAMPLE + Add-vROPSAdapterPing -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -addressList "192.168.11.50,192.168.11.51,192.168.11.52,192.168.11.53" -adapterName xint-vra01 + This example creates a new Ping adapter called 'xint-vra01', assigns the IP Addresses provided and assigns to the 'Default collector group' #> Param ( @@ -7056,7 +8565,7 @@ Function Add-vROPSAdapterPing { [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$addressList, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$adapterName, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$collectorGroupName + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$collectorGroupName="Default collector group" ) Try { @@ -7763,8 +9272,7 @@ Function New-vRADeployment { .DESCRIPTION The New-vRADeployment cmdlet deploys vRealize Automation via vRealize Suite Lifecycle Manager. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible + - Validates that network connectivity and authentication is possible to SDDC Manager - Validates that vRealize Automation has not been deployed in VMware Cloud Foundation aware mode and retrives its details - Requests a new deployment of vRealize Automation @@ -7858,11 +9366,9 @@ Function Update-vRAOrganizationDisplayName { .DESCRIPTION The Update-vRAOrganizationDisplayName cmdlet configures the organization display name in vRealize Automation. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible + - Validates that network connectivity and authentication is possible to SDDC Manager - Validates that vRealize Automation has been deployed in VMware Cloud Foundation aware mode and retrives its details - - Validates that network connectivity is available to the vRealize Automation instance - - Makes a connection to the vRealize Automation + - Validates that network connectivity and authentication is possible to vRealize Automation - Verifies if the organization name is already configured based on the input - Configures the organization name @@ -7920,11 +9426,9 @@ Function New-vRACloudAccount { .DESCRIPTION The New-vRACloudAccount cmdlet creates the vSphere and NSX-T Cloud Accounts for a Workload Domain in vRealize Automation. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible + - Validates that network connectivity and authentication is possible to SDDC Manager - Validates that vRealize Automation has been deployed in VMware Cloud Foundation aware mode and retrives its details - - Validates that network connectivity is available to the vRealize Automation instance - - Makes a connection to the vRealize Automation + - Validates that network connectivity and authentication is possible to vRealize Automation - Retrives details from SDDC Manager for the vCenter Server and NSX Management Cluster - Adds a Cloud Account for vCenter Server and NSX Management Cluster @@ -8028,11 +9532,9 @@ Function Undo-vRACloudAccount { .DESCRIPTION The Undo-vRACloudAccount cmdlet removes the vSphere and NSX-T Cloud Accounts for a Workload Domain in vRealize Automation. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible + - Validates that network connectivity and authentication is possible to SDDC Manager - Validates that vRealize Automation has been deployed in VMware Cloud Foundation aware mode and retrives its details - - Validates that network connectivity is available to the vRealize Automation instance - - Makes a connection to the vRealize Automation + - Validates that network connectivity and authentication is possible to vRealize Automation - Retrives details from SDDC Manager for the vCenter Server and NSX Management Cluster - Removes the Cloud Accounts for vCenter Server and NSX Management Cluster @@ -8107,12 +9609,10 @@ Function Update-vRACloudAccountZone { .DESCRIPTION The Update-vRACloudAccountZone cmdlet updated the Cloud Zone with folder and tags on the resource pool for a Workload Domain in vRealize Automation. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible + - Validates that network connectivity and authentication is possible to SDDC Manager - Validates the Workload Domain is available in the SDDC Manager Inventory - Validates that vRealize Automation has been deployed in VMware Cloud Foundation aware mode and retrives its details - - Validates that network connectivity is available to the vRealize Automation instance - - Makes a connection to the vRealize Automation + - Validates that network connectivity and authentication is possible to vRealize Automation - Validates that a Cloud Account exists for the Workload Domain in vRealize Automation instance - Validates that the Resource Pool is availble in vRealize Automation as a Compute Resource - Adds the tag to the Resource Pool Compute Resource @@ -8576,10 +10076,9 @@ Function Add-vRANotification { .DESCRIPTION The Add-vRANotification cmdlet adds notification settings to vRealize Automation. The cmdlet connects to SDDC Manager using the -server, -user, -password, and -domain values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible + - Validates that network connectivity and authentication is possible to SDDC Manager - Validates that vRealize Automation has been deployed in VMware Cloud Foundation aware mode and retrives its details - - Makes a connection to the vRealize Automation Cluster + - MValidates that network connectivity and authentication is possible to vRealize Automation - Adds notifications settings to vRealize Automation .EXAMPLE @@ -8632,10 +10131,9 @@ Function Add-vRAUser { .DESCRIPTION The Add-vRAUser cmdlet adds user access in vRealize Automation. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible + - Validates that network connectivity and authentication is possible to SDDC Manager - Validates that vRealize Automation has been deployed in VMware Cloud Foundation aware mode and retrives its details - - Makes a connection to the vRealize Automation Cluster + - Validates that network connectivity and authentication is possible to vRealize Automation - Adds the user to both an organization role and a service role .EXAMPLE @@ -8703,10 +10201,9 @@ Function Undo-vRAUser { .DESCRIPTION The Undo-vRAUser cmdlet removes user access in vRealize Automation. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible + - Validates that network connectivity and authentication is possible to SDDC Manager - Validates that vRealize Automation has been deployed in VMware Cloud Foundation aware mode and retrives its details - - Makes a connection to the vRealize Automation Cluster + - Validates that network connectivity and authentication is possible to vRealize Automation - Removes the user from an organization role and all service roles .EXAMPLE @@ -8826,10 +10323,9 @@ Function Add-vRAGroup { .DESCRIPTION The Add-vRAGroup cmdlet adds a group in vRealize Automation. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible + - Validates that network connectivity and authentication is possible to SDDC Manager - Validates that vRealize Automation has been deployed in VMware Cloud Foundation aware mode and retrives its details - - Makes a connection to the vRealize Automation Cluster + - Validates that network connectivity and authentication is possible to vRealize Automation - Adds the group to an organization role and a service role .EXAMPLE @@ -8917,10 +10413,9 @@ Function Undo-vRAGroup { .DESCRIPTION The Undo-vRAGroup cmdlet removes a group in vRealize Automation. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible + - Validates that network connectivity and authentication is possible to SDDC Manager - Validates that vRealize Automation has been deployed in VMware Cloud Foundation aware mode and retrives its details - - Makes a connection to the vRealize Automation Cluster + - Validates that network connectivity and authentication is possible to vRealize Automation - Removes the group from an organization role and all service roles .EXAMPLE @@ -8984,18 +10479,17 @@ Export-ModuleMember -Function Undo-vRAGroup Function Add-vCenterGlobalPermission { <# .SYNOPSIS - Adds a Global Permission to user/group + Adds a Global Permission to a user or group .DESCRIPTION The Add-vCenterGlobalPermission cmdlets assigns the vCenter Server Global Permission to the user or group provided. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible - - Connects to the Management Domain vCenter Server instance + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to vCenter Server - Validates that the bind credentials are valid - Validates that the domain is present in vCenter Server as an Identity Provider - Validates the user or group exists in Active Directory - - Assigns the user or group to the Global Permission + - Assigns the user or group to the vCenter Global Permission If -localDomain is selected, then AD authentication check is skipped and user/group is checked for in the local directory @@ -9038,49 +10532,63 @@ Function Add-vCenterGlobalPermission { if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) { if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { - if (Test-SSOConnection -server $($vcfVcenterDetails.fqdn)) { - if (Test-SSOAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { - if (!(Get-IdentitySource | Where-Object { $_.Name -eq $domain })) { - Write-Error "Unable to find Identity Source in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($domain)" - } - else { - if ($type -eq "group") { - if (!$localDomain) { - $objectCheck = (Get-ADGroup -Server $domain -Credential $domainCreds -Filter { SamAccountName -eq $principal }) - } - else { - $principal = $domain.ToUpper() + "\" + $principal - $objectCheck = (Get-VIAccount -Group -Domain vsphere.local | Where-Object { $_.Name -eq $principal }) - } + Connect-vSphereMobServer -server $vcfVcenterDetails.fqdn -username $vcfVcenterDetails.ssoAdmin -password $vcfVcenterDetails.ssoAdminPass | Out-Null + $roleAssigned = (Get-GlobalPermission | Where-Object {$_.Principal -match $principal}) + if (!($roleAssigned | Where-Object {$_.Role -eq $role})) { + if (Test-SSOConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-SSOAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + if (!(Get-IdentitySource | Where-Object { $_.Name -eq $domain })) { + Write-Error "Unable to find Identity Source in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($domain)" } - elseif ($type -eq "user") { - if (!$localDomain){ - $objectCheck = (Get-ADUser -Server $domain -Credential $domainCreds -Filter { SamAccountName -eq $principal }) - $principal = $domain.ToUpper() + "\" + $principal + else { + if ($type -eq "group") { + if (!$localDomain) { + $objectCheck = (Get-ADGroup -Server $domain -Credential $domainCreds -Filter { SamAccountName -eq $principal }) + } + else { + $principal = $domain.ToUpper() + "\" + $principal + $objectCheck = (Get-VIAccount -Group -Domain $domain -server $vcfVcenterDetails.fqdn | Where-Object { $_.Name -eq $principal }) + } } - else { - $principal = $domain.ToUpper() + "\" + $principal - $objectCheck = (Get-VIAccount -User -Domain vsphere.local | Where-Object { $_.Name -eq $principal }) + elseif ($type -eq "user") { + if (!$localDomain){ + $objectCheck = (Get-ADUser -Server $domain -Credential $domainCreds -Filter { SamAccountName -eq $principal }) + $principal = $domain.ToUpper() + "\" + $principal + } + else { + $principal = $domain.ToUpper() + "\" + $principal + $objectCheck = (Get-VIAccount -User -Domain $domain -server $vcfVcenterDetails.fqdn | Where-Object { $_.Name -eq $principal }) + } } - } - if ($objectCheck) { - $roleId = (Get-VIRole -Name $role | Select-Object -ExpandProperty Id) - Add-GlobalPermission -vcServer $vcfVcenterDetails.fqdn -vcUsername $vcfVcenterDetails.ssoAdmin -vcPassword $vcfVcenterDetails.ssoAdminPass -roleId $roleId -user $principal -propagate $propagate -type $type - Write-Output "Adding Global Permission with Role ($role) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal): SUCCESSFUL" - } - else { - if ($localDomain) { - Write-Error "Unable to find $type ($principal) in Local Domain, create and retry: PRE_VALIDATION_FAILED" + if ($objectCheck) { + $roleId = (Get-VIRole -Name $role -Server $vcfVcenterDetails.fqdn | Select-Object -ExpandProperty Id) + Add-GlobalPermission -principal $principal -roleId $roleId -propagate $propagate -type $type | Out-Null + $roleAssigned = (Get-GlobalPermission | Where-Object {$_.Principal -match $principal.Split("\")[-1]}) + if ($roleAssigned | Where-Object {$_.Role -eq $role}) { + Write-Output "Adding Global Permission with Role ($role) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal): SUCCESSFUL" + } + else { + Write-Error "Adding Global Permission with Role ($role) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal): POST_VALIDATION_FAILED" + } } else { - Write-Error "Unable to find $type ($principal) in Active Directory Domain ($domain), create and retry: PRE_VALIDATION_FAILED" + if ($localDomain) { + Write-Error "Unable to find $type ($principal) in Local Domain, create and retry: PRE_VALIDATION_FAILED" + } + else { + Write-Error "Unable to find $type ($principal) in Active Directory Domain ($domain), create and retry: PRE_VALIDATION_FAILED" + } } } } + Disconnect-SsoAdminServer -Server $vcfVcenterDetails.fqdn -WarningAction SilentlyContinue } } - Disconnect-SsoAdminServer $vcfVcenterDetails.fqdn -WarningAction SilentlyContinue - Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue + else { + Write-Warning "Adding Global Permission with Role ($role) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal), already applied: SKIPPED" + } + Disconnect-VIServer -Server $vcfVcenterDetails.fqdn -Confirm:$false -Force -WarningAction SilentlyContinue + Disconnect-vSphereMobServer } } } @@ -9093,6 +10601,77 @@ Function Add-vCenterGlobalPermission { } Export-ModuleMember -Function Add-vCenterGlobalPermission +Function Undo-vCenterGlobalPermission { + <# + .SYNOPSIS + Removes a Global Permission to a user or group + + .DESCRIPTION + The Undo-vCenterGlobalPermission cmdlets removes the vCenter Server Global Permission for the user or group provided. + The cmdlet connects to SDDC Manager using the -server, -user, and -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to vCenter Server + - Removes the user or group from the vCenter Global Permission + + If -localDomain is selected, then AD authentication check is skipped and user/group is checked for in the local directory + + .EXAMPLE + Undo-vCenterGlobalPermission -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo.rainpole.io -principal gg-vc-admins -type group + This example remove the group gg-vc-admins from the vCenter Global Permission + + .EXAMPLE + Undo-vCenterGlobalPermission -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain vsphere.local -principal testUser -type user -localdomain + This example remove the group testUser from the vCenter Global Permission + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$principal, + [Parameter (Mandatory = $true)] [ValidateSet("group", "user")] [String]$type, + [Parameter (Mandatory = $false)] [Switch]$localDomain = $false + ) + + Try { + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) { + if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + Connect-vSphereMobServer -server $vcfVcenterDetails.fqdn -username $vcfVcenterDetails.ssoAdmin -password $vcfVcenterDetails.ssoAdminPass | Out-Null + if (Get-GlobalPermission | Where-Object {$_.Principal -match $principal}) { + if ($PsBoundParameters.ContainsKey("localDomain")) { + Remove-GlobalPermission -principal ($domain.ToUpper()+"\"+$principal) -type $type | Out-Null + } + else { + Remove-GlobalPermission -principal $principal -type $type | Out-Null + } + if (!(Get-GlobalPermission | Where-Object {$_.Principal -match $principal})) { + Write-Output "Removing Global Permission in vCenter Server ($($vcfVcenterDetails.vmName)) for $type ($principal): SUCCESSFUL" + } + else { + Write-Error "Removing Global Permission in vCenter Server ($($vcfVcenterDetails.vmName)) for $type ($principal): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Removing Global Permission in vCenter Server ($($vcfVcenterDetails.vmName)) for $type ($principal), already removed: SKIPPED" + } + Disconnect-VIServer -Server $vcfVcenterDetails.fqdn -Confirm:$false -Force -WarningAction SilentlyContinue + Disconnect-vSphereMobServer + } + } + } + } + } + } + Catch { + Debug-ExceptionWriter -object $_ + } +} +Export-ModuleMember -Function Undo-vCenterGlobalPermission + Function Set-vCenterPermission { <# .SYNOPSIS @@ -9161,76 +10740,248 @@ Function Set-vCenterPermission { } } else { - Write-Error "Unable to find $($folderType.ToLower()) folder ($folderName) in vCenter Server ($($vcfVcenterDetails.vmName)): PRE_VAILIDATION_FAILED" + Write-Error "Unable to find $($folderType.ToLower()) folder ($folderName) in vCenter Server ($($vcfVcenterDetails.vmName)): PRE_VAILIDATION_FAILED" + } + } + else { + if ($folderName -or $folderType) { + Write-Error "Only one of -folderName or -folderType parameters provided: PRE_VALIDATATION_FAILED" + } + else { + if ($objectCheck = Get-VIPermission -Server $vcfVcenterDetails.fqdn -Principal $principal -Entity (Get-Folder "Datacenters" -Type Datacenter | Where-Object {$_.Uid -like "*"+$vcfVcenterDetails.fqdn+"*"})) { + if (!($objectCheck.Role -eq $role)) { + New-VIPermission -Server $vcfVcenterDetails.fqdn -Role $role -Principal $principal -Entity (Get-Folder "Datacenters" -Type Datacenter | Where-Object {$_.Uid -like "*"+$vcfVcenterDetails.fqdn+"*"}) | Out-Null + $objectCheck = Get-VIPermission -Server $vcfVcenterDetails.fqdn -Principal $principal -Entity (Get-Folder "Datacenters" -Type Datacenter | Where-Object {$_.Uid -like "*"+$vcfVcenterDetails.fqdn+"*"}) + if ($objectCheck.Role -eq $role) { + Write-Output "Assigning role ($role) in vCenter Server ($($vcfVcenterDetails.vmName)) to ($principal): SUCCESSFUL" + } + else { + Write-Error "Assigning role ($role) in vCenter Server ($($vcfVcenterDetails.vmName)) to ($principal): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Assigning role ($role) in vCenter Server ($($vcfVcenterDetails.vmName)) to ($principal), already assigned: SKIPPED" + } + } + } + } + } + else { + Write-Error "Unable to find ($principal) in vCenter Server ($($vcfVcenterDetails.vmName)): PRE_VAILIDATION_FAILED" + } + } + } + } + } + } + } + else { + Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" + } + } + } + } + Catch { + Debug-ExceptionWriter -object $_ + } +} +Export-ModuleMember -Function Set-vCenterPermission + +Function Add-SsoPermission { + <# + .SYNOPSIS + Assign vCenter Single Sign-On Group to user/group + + .DESCRIPTION + The Add-SsoPermission cmdlet assigns the vCenter Single Sign-On Role to the user or group provided. The cmdlet + connects to SDDC Manager using the -server, -user, and -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to vCenter Server + - Validates that the bind credetials are valid + - Validates that the domain is present in vCenter Server as an Identity Provider + - Validates the user or group exists in Active Directory + - Assigns the user or group to the vCenter Single Sign-On Role + + .EXAMPLE + Add-SsoPermission -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -sddcDomain sfo-m01 -domain sfo.rainpole.io -domainBindUser svc-vsphere-ad -domainBindPass VMw@re1! -principal gg-sso-admins -ssoGroup "Administrators" -type group -source external + This example adds the group gg-sso-admins from domain sfo.rainpole.io to the Administrators vCenter Single Sign-On Group + + .EXAMPLE + Add-SsoPermission -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -sddcDomain sfo-m01 -domain vsphere.local -principal svc-sfo-m01-nsx01-sfo-m01-vc01 -ssoGroup "License.Administrators" -type user -source local + This example adds the user svc-sfo-m01-nsx01-sfo-m01-vc01 from domain vspherel.local to the License.Administrators vCenter Single Sign-On Group + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcDomain, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$domainBindUser, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$domainBindPass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$principal, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ssoGroup, + [Parameter (Mandatory = $true)] [ValidateSet("group", "user")] [String]$type, + [Parameter (Mandatory = $true)] [ValidateSet("local", "external")] [String]$source + ) + + Try { + if ($source -eq "external") { + $checkAdAuthentication = Test-ADAuthentication -user $domainBindUser -pass $domainBindPass -server $domain -domain $domain -ErrorAction SilentlyContinue + if ($checkAdAuthentication[1] -match "Authentication Successful") { + $securePass = ConvertTo-SecureString -String $domainBindPass -AsPlainText -Force + $domainCreds = New-Object System.Management.Automation.PSCredential ($domainBindUser, $securePass) + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $sddcDomain }) { + if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $sddcDomain)) { + if (Test-SSOConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-SSOAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + if ($targetGroup = Get-SsoGroup -Domain vsphere.local -Name $ssoGroup -Server $ssoConnectionDetail) { + if (Get-IdentitySource -Server $ssoConnectionDetail | Where-Object { $_.Name -eq $domain }) { + if ($type -eq "group") { + $adObjectCheck = (Get-ADGroup -Server $domain -Credential $domainCreds -Filter { SamAccountName -eq $principal }) + if ($adObjectCheck) { + if (!(Get-SsoGroup -Group $targetGroup -Name $principal)) { + $ldapGroup = Get-SsoGroup -Domain $domain -Name $principal -Server $ssoConnectionDetail + $ldapGroup | Add-GroupToSsoGroup -TargetGroup $targetGroup -ErrorAction SilentlyContinue + if (Get-SsoGroup -Group $targetGroup -Name $principal) { + Write-Output "Assigning SSO Group ($ssoGroup) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal) for domain ($domain): SUCCESSFUL" + } + else { Write-Error "Assigning SSO Group ($ssoGroup) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal) for domain ($domain): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Assigning SSO Group ($ssoGroup) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal) for domain ($domain), already exists: SKIPPED" + } + } + else { + Write-Error "Unable to find $type ($principal) in Active Directory Domain ($domain), create and retry: PRE_VALIDATION_FAILED" + } + } + elseif ($type -eq "user") { + $adObjectCheck = (Get-ADUser -Server $domain -Credential $domainCreds -Filter { SamAccountName -eq $principal }) + if ($adObjectCheck) { + if (!(Get-SsoPersonUser -Group $targetGroup | Where-Object {$_.Name -eq $principal})) { + $ldapUser = Get-SsoPersonUser -Domain $domain -Name $principal -Server $ssoConnectionDetail + $ldapUser | Add-UserToSsoGroup -TargetGroup $targetGroup -ErrorAction SilentlyContinue + if (Get-SsoPersonUser -Group $targetGroup | Where-Object {$_.Name -eq $principal}) { + Write-Output "Assigning SSO Group ($ssoGroup) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal) for domain ($domain): SUCCESSFUL" + } + else { Write-Error "Assigning SSO Group ($ssoGroup) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal) for domain ($domain): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Assigning SSO Group ($ssoGroup) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal) for domain ($domain), already exists: SKIPPED" + } + } + else { + Write-Error "Unable to find $type ($principal) in Active Directory Domain ($domain), create and retry: PRE_VALIDATION_FAILED" + } + } + } + else { + Write-Error "Unable to find Identity Source in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($domain): PRE_VALIDATION_FAILED" + } + } + else { + Write-Error "Unable to find SSO Group in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($ssoGroup): PRE_VALIDATION_FAILED" + } + Disconnect-SsoAdminServer -Server $vcfVcenterDetails.fqdn + } + } + } + } + else { + Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" + } + } + } + } + else { + Write-Error "Unable to authenticate to Active Directory with user ($domainBindUser) and password ($domainBindPass), check details: PRE_VALIDATION_FAILED" + } + } + elseif ($source -eq "local") { + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $sddcDomain)) { + if (Test-SSOConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-SSOAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + if ($targetGroup = Get-SsoGroup -Domain vsphere.local -Name $ssoGroup -Server $ssoConnectionDetail) { + if (Get-IdentitySource | Where-Object { $_.Name -eq $domain }) { + if ($type -eq "group") { + if (!(Get-SsoGroup -Group $targetGroup -Name $principal -Server $ssoConnectionDetail)) { + $ldapGroup = Get-SsoGroup -Domain $domain -Name $principal -Server $ssoConnectionDetail + $ldapGroup | Add-GroupToSsoGroup -TargetGroup $targetGroup -ErrorAction SilentlyContinue + if (Get-SsoGroup -Group $targetGroup -Name $principal -Server $ssoConnectionDetail) { + Write-Output "Assigning SSO Group ($ssoGroup) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal) for domain ($domain): SUCCESSFUL" + } + else { + Write-Error "Assigning SSO On Group ($ssoGroup) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal) for domain ($domain): POST_VALIDATION_FAILED" } } else { - if ($folderName -or $folderType) { - Write-Error "Only one of -folderName or -folderType parameters provided: PRE_VALIDATATION_FAILED" + Write-Warning "Assigning SSO Group ($ssoGroup) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal) for domain ($domain).already exists: SKIPPED" } + } + elseif ($type -eq "user") { + if (!(Get-SsoPersonUser -Group $targetGroup -Server $ssoConnectionDetail | Where-Object {$_.Name -eq $principal})) { + $ldapUser = Get-SsoPersonUser -Domain $domain -Name $principal -Server $ssoConnectionDetail + $ldapUser | Add-UserToSsoGroup -TargetGroup $targetGroup -ErrorAction SilentlyContinue + if (Get-SsoPersonUser -Group $targetGroup -Server $ssoConnectionDetail| Where-Object {$_.Name -eq $principal}) { + Write-Output "Assigning SSO Group ($ssoGroup) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal) for domain ($domain): SUCCESSFUL" + } else { - if ($objectCheck = Get-VIPermission -Server $vcfVcenterDetails.fqdn -Principal $principal -Entity (Get-Folder "Datacenters" -Type Datacenter | Where-Object {$_.Uid -like "*"+$vcfVcenterDetails.fqdn+"*"})) { - if (!($objectCheck.Role -eq $role)) { - New-VIPermission -Server $vcfVcenterDetails.fqdn -Role $role -Principal $principal -Entity (Get-Folder "Datacenters" -Type Datacenter | Where-Object {$_.Uid -like "*"+$vcfVcenterDetails.fqdn+"*"}) | Out-Null - $objectCheck = Get-VIPermission -Server $vcfVcenterDetails.fqdn -Principal $principal -Entity (Get-Folder "Datacenters" -Type Datacenter | Where-Object {$_.Uid -like "*"+$vcfVcenterDetails.fqdn+"*"}) - if ($objectCheck.Role -eq $role) { - Write-Output "Assigning role ($role) in vCenter Server ($($vcfVcenterDetails.vmName)) to ($principal): SUCCESSFUL" - } - else { - Write-Error "Assigning role ($role) in vCenter Server ($($vcfVcenterDetails.vmName)) to ($principal): POST_VALIDATION_FAILED" - } - } - else { - Write-Warning "Assigning role ($role) in vCenter Server ($($vcfVcenterDetails.vmName)) to ($principal), already assigned: SKIPPED" - } - } + Write-Error "Assigning SSO Group ($ssoGroup) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal) for domain ($domain): POST_VALIDATION_FAILED" } } + else { + Write-Warning "Assigning SSO Group ($ssoGroup) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal) for domain ($domain), already exists: SKIPPED" + } } - else { - Write-Error "Unable to find ($principal) in vCenter Server ($($vcfVcenterDetails.vmName)): PRE_VAILIDATION_FAILED" - } + } + else { + Write-Error "Unable to find Identity Source in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($domain): PRE_VALIDATION_FAILED" } } + else { + Write-Error "Unable to find SSO Group in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($ssoGroup): PRE_VALIDATION_FAILED" + } + Disconnect-SsoAdminServer -Server $vcfVcenterDetails.fqdn } } } - } - else { - Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" - } + } } } - } + } Catch { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Set-vCenterPermission +Export-ModuleMember -Function Add-SsoPermission -Function Add-SsoPermission { +Function Undo-SsoPermission { <# .SYNOPSIS - Assign vCenter Single Sign-On Group to user/group + Remove user/group from vCenter Single Sign-On Group .DESCRIPTION - The Add-SsoPermission cmdlet assigns the vCenter Single Sign-On Role to the user or group provided. The cmdlet + The Undo-SsoPermission cmdlet removes the user or group provided from vCenter Single Sign-On Role. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible - - Connects to the Management Domain vCenter Server instance - - Validates that the bind credetials are valid + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to vCenter Server - Validates that the domain is present in vCenter Server as an Identity Provider - - Validates the user or group exists in Active Directory - - Assigns the user or group to the vCenter Single Sign-On Role + - Removes the user or group from the vCenter Single Sign-On Role .EXAMPLE - Add-SsoPermission -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -sddcDomain sfo-m01 -domain sfo.rainpole.io -domainBindUser svc-vsphere-ad -domainBindPass VMw@re1! -principal gg-sso-admins -ssoGroup "Administrators" -type group -source external - This example adds the group gg-sso-admins from domain sfo.rainpole.io to the Administrators vCenter Single Sign-On Group + Undo-SsoPermission -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -sddcDomain sfo-m01 -domain sfo.rainpole.io -principal gg-sso-admins -ssoGroup "Administrators" -type group -source external + This example removes the group gg-sso-admins in domain sfo.rainpole.io from the Administrators vCenter Single Sign-On Group .EXAMPLE - Add-SsoPermission -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -sddcDomain sfo-m01 -domain vsphere.local -principal svc-sfo-m01-nsx01-sfo-m01-vc01 -ssoGroup "License.Administrators" -type user -source local - This example adds the user svc-sfo-m01-nsx01-sfo-m01-vc01 from domain vspherel.local to the License.Administrators vCenter Single Sign-On Group + Undo-SsoPermission -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -sddcDomain sfo-m01 -domain vsphere.local -principal svc-sfo-m01-nsx01-sfo-m01-vc01 -ssoGroup "LicenseService.Administrators" -type user -source local + This example removes the user svc-sfo-m01-nsx01-sfo-m01-vc01 in domain vspherel.local from the LicenseService.Administrators vCenter Single Sign-On Group #> Param ( @@ -9239,8 +10990,6 @@ Function Add-SsoPermission { [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcDomain, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$domainBindUser, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$domainBindPass, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$principal, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ssoGroup, [Parameter (Mandatory = $true)] [ValidateSet("group", "user")] [String]$type, @@ -9249,76 +10998,60 @@ Function Add-SsoPermission { Try { if ($source -eq "external") { - $checkAdAuthentication = Test-ADAuthentication -user $domainBindUser -pass $domainBindPass -server $domain -domain $domain -ErrorAction SilentlyContinue - if ($checkAdAuthentication[1] -match "Authentication Successful") { - $securePass = ConvertTo-SecureString -String $domainBindPass -AsPlainText -Force - $domainCreds = New-Object System.Management.Automation.PSCredential ($domainBindUser, $securePass) - if (Test-VCFConnection -server $server) { - if (Test-VCFAuthentication -server $server -user $user -pass $pass) { - if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $sddcDomain }) { - if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $sddcDomain)) { - if (Test-SSOConnection -server $($vcfVcenterDetails.fqdn)) { - if (Test-SSOAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { - $targetGroup = Get-SsoGroup -Domain vsphere.local -Name $ssoGroup -Server $ssoConnectionDetail + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $sddcDomain }) { + if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $sddcDomain)) { + if (Test-SSOConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-SSOAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + if ($targetGroup = Get-SsoGroup -Domain vsphere.local -Name $ssoGroup -Server $ssoConnectionDetail) { if (Get-IdentitySource -Server $ssoConnectionDetail | Where-Object { $_.Name -eq $domain }) { if ($type -eq "group") { - $adObjectCheck = (Get-ADGroup -Server $domain -Credential $domainCreds -Filter { SamAccountName -eq $principal }) - if ($adObjectCheck) { + if (Get-SsoGroup -Group $targetGroup -Name $principal) { + $ldapGroup = Get-SsoGroup -Domain $domain -Name $principal -Server $ssoConnectionDetail + $ldapGroup | Remove-GroupFromSsoGroup -TargetGroup $targetGroup -ErrorAction SilentlyContinue if (!(Get-SsoGroup -Group $targetGroup -Name $principal)) { - $ldapGroup = Get-SsoGroup -Domain $domain -Name $principal -Server $ssoConnectionDetail - $ldapGroup | Add-GroupToSsoGroup -TargetGroup $targetGroup -ErrorAction SilentlyContinue - if (Get-SsoGroup -Group $targetGroup -Name $principal) { - Write-Output "Assigning SSO Group ($ssoGroup) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal) for domain ($domain): SUCCESSFUL" - } - else { Write-Error "Assigning SSO Group ($ssoGroup) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal) for domain ($domain): POST_VALIDATION_FAILED" - } + Write-Output "Removing SSO Group ($ssoGroup) from vCenter Server ($($vcfVcenterDetails.vmName)) for $type ($principal) for domain ($domain): SUCCESSFUL" } - else { - Write-Warning "Assigning SSO Group ($ssoGroup) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal) for domain ($domain), already exists: SKIPPED" + else { Write-Error "Removing SSO Group ($ssoGroup) from vCenter Server ($($vcfVcenterDetails.vmName)) for $type ($principal) for domain ($domain): POST_VALIDATION_FAILED" } } else { - Write-Error "Unable to find $type ($principal) in Active Directory Domain ($domain), create and retry: PRE_VALIDATION_FAILED" + Write-Warning "Removing SSO Group ($ssoGroup) from vCenter Server ($($vcfVcenterDetails.vmName)) for $type ($principal) for domain ($domain), already removed: SKIPPED" } } elseif ($type -eq "user") { - $adObjectCheck = (Get-ADUser -Server $domain -Credential $domainCreds -Filter { SamAccountName -eq $principal }) - if ($adObjectCheck) { + if (Get-SsoPersonUser -Group $targetGroup | Where-Object {$_.Name -eq $principal}) { + $ldapUser = Get-SsoPersonUser -Domain $domain -Name $principal -Server $ssoConnectionDetail + $ldapUser | Remove-UserFromSsoGroup -TargetGroup $targetGroup -ErrorAction SilentlyContinue if (!(Get-SsoPersonUser -Group $targetGroup | Where-Object {$_.Name -eq $principal})) { - $ldapUser = Get-SsoPersonUser -Domain $domain -Name $principal -Server $ssoConnectionDetail - $ldapUser | Add-UserToSsoGroup -TargetGroup $targetGroup -ErrorAction SilentlyContinue - if (Get-SsoPersonUser -Group $targetGroup | Where-Object {$_.Name -eq $principal}) { - Write-Output "Assigning SSO Group ($ssoGroup) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal) for domain ($domain): SUCCESSFUL" - } - else { Write-Error "Assigning SSO Group ($ssoGroup) in vCenter Server ($($vcfVcenterDetails.vmName)) to$type ($principal) for domain ($domain): POST_VALIDATION_FAILED" - } + Write-Output "Removing SSO Group ($ssoGroup) from vCenter Server ($($vcfVcenterDetails.vmName)) for $type ($principal) for domain ($domain): SUCCESSFUL" } - else { - Write-Warning "Assigning SSO Group ($ssoGroup) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal) for domain ($domain). already exists: SKIPPED" + else { Write-Error "Removing SSO Group ($ssoGroup) from vCenter Server ($($vcfVcenterDetails.vmName)) for $type ($principal) for domain ($domain): POST_VALIDATION_FAILED" } } - else { - Write-Error "Unable to find $type ($principal) in Active Directory Domain ($domain), create and retry: PRE_VALIDATION_FAILED" + else { + Write-Warning "Removing SSO Group ($ssoGroup) from vCenter Server ($($vcfVcenterDetails.vmName)) for $type ($principal) for domain ($domain), already exists: SKIPPED" } } } else { Write-Error "Unable to find Identity Source in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($domain): PRE_VALIDATION_FAILED" } - Disconnect-SsoAdminServer -Server $vcfVcenterDetails.fqdn } + else { + Write-Error "Unable to find SSO Group in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($ssoGroup): PRE_VALIDATION_FAILED" + } + Disconnect-SsoAdminServer -Server $vcfVcenterDetails.fqdn } } } - else { - Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" - } + } + else { + Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" } } } - else { - Write-Error "Unable to authenticate to Active Directory with user ($domainBindUser) and password ($domainBindPass), check details: PRE_VALIDATION_FAILED" - } } elseif ($source -eq "local") { if (Test-VCFConnection -server $server) { @@ -9326,41 +11059,45 @@ Function Add-SsoPermission { if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $sddcDomain)) { if (Test-SSOConnection -server $($vcfVcenterDetails.fqdn)) { if (Test-SSOAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { - $targetGroup = Get-SsoGroup -Domain vsphere.local -Name $ssoGroup -Server $ssoConnectionDetail - if (Get-IdentitySource | Where-Object { $_.Name -eq $domain }) { - if ($type -eq "group") { - if (!(Get-SsoGroup -Group $targetGroup -Name $principal -Server $ssoConnectionDetail)) { - $ldapGroup = Get-SsoGroup -Domain $domain -Name $principal -Server $ssoConnectionDetail - $ldapGroup | Add-GroupToSsoGroup -TargetGroup $targetGroup -ErrorAction SilentlyContinue + if ($targetGroup = Get-SsoGroup -Domain vsphere.local -Name $ssoGroup -Server $ssoConnectionDetail) { + if (Get-IdentitySource | Where-Object { $_.Name -eq $domain }) { + if ($type -eq "group") { if (Get-SsoGroup -Group $targetGroup -Name $principal -Server $ssoConnectionDetail) { - Write-Output "Assigning SSO Group ($ssoGroup) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal) for domain ($domain): SUCCESSFUL" + $ldapGroup = Get-SsoGroup -Domain $domain -Name $principal -Server $ssoConnectionDetail + $ldapGroup | Remove-GroupFromSsoGroup -TargetGroup $targetGroup -ErrorAction SilentlyContinue + if (!(Get-SsoGroup -Group $targetGroup -Name $principal -Server $ssoConnectionDetail)) { + Write-Output "Removing SSO Group ($ssoGroup) from vCenter Server ($($vcfVcenterDetails.vmName)) for $type ($principal) for domain ($domain): SUCCESSFUL" + } + else { + Write-Error "Removing SSO On Group ($ssoGroup) from vCenter Server ($($vcfVcenterDetails.vmName)) for $type ($principal) for domain ($domain): POST_VALIDATION_FAILED" + } } else { - Write-Error "Assigning SSO On Group ($ssoGroup) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal) for domain ($domain): POST_VALIDATION_FAILED" + Write-Warning "Removing SSO Group ($ssoGroup) from vCenter Server ($($vcfVcenterDetails.vmName)) for $type ($principal) for domain ($domain), already removed: SKIPPED" } } - else { - Write-Warning "Assigning SSO Group ($ssoGroup) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal) for domain ($domain).already exists: SKIPPED" - } - } - elseif ($type -eq "user") { - if (!(Get-SsoPersonUser -Group $targetGroup -Server $ssoConnectionDetail | Where-Object {$_.Name -eq $principal})) { - $ldapUser = Get-SsoPersonUser -Domain $domain -Name $principal -Server $ssoConnectionDetail - $ldapUser | Add-UserToSsoGroup -TargetGroup $targetGroup -ErrorAction SilentlyContinue - if (Get-SsoPersonUser -Group $targetGroup -Server $ssoConnectionDetail| Where-Object {$_.Name -eq $principal}) { - Write-Output "Assigning SSO Group ($ssoGroup) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal) for domain ($domain): SUCCESSFUL" + elseif ($type -eq "user") { + if (Get-SsoPersonUser -Group $targetGroup -Server $ssoConnectionDetail | Where-Object {$_.Name -eq $principal}) { + $ldapUser = Get-SsoPersonUser -Domain $domain -Name $principal -Server $ssoConnectionDetail + $ldapUser | Remove-UserFromSsoGroup -TargetGroup $targetGroup -ErrorAction SilentlyContinue + if (!(Get-SsoPersonUser -Group $targetGroup -Server $ssoConnectionDetail| Where-Object {$_.Name -eq $principal})) { + Write-Output "Removing SSO Group ($ssoGroup) from vCenter Server ($($vcfVcenterDetails.vmName)) for $type ($principal) for domain ($domain): SUCCESSFUL" + } + else { + Write-Error "Removing SSO Group ($ssoGroup) from vCenter Server ($($vcfVcenterDetails.vmName)) for $type ($principal) for domain ($domain): POST_VALIDATION_FAILED" + } } else { - Write-Error "Assigning SSO Group ($ssoGroup) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal) for domain ($domain): POST_VALIDATION_FAILED" + Write-Warning "Removing SSO Group ($ssoGroup) from vCenter Server ($($vcfVcenterDetails.vmName)) for $type ($principal) for domain ($domain), already removed: SKIPPED" } } - else { - Write-Warning "Assigning SSO Group ($ssoGroup) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal) for domain ($domain), already exists: SKIPPED" - } + } + else { + Write-Error "Unable to find Identity Source in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($domain): PRE_VALIDATION_FAILED" } } else { - Write-Error "Unable to find Identity Source in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($domain): PRE_VALIDATION_FAILED" + Write-Error "Unable to find SSO Group in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($ssoGroup): PRE_VALIDATION_FAILED" } Disconnect-SsoAdminServer -Server $vcfVcenterDetails.fqdn } @@ -9374,7 +11111,7 @@ Function Add-SsoPermission { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-SsoPermission +Export-ModuleMember -Function Undo-SsoPermission Function Add-SsoUser { <# @@ -9384,9 +11121,8 @@ Function Add-SsoUser { .DESCRIPTION The Add-SsoUser cmdlet adds a user to the vCenter Single Sign-On domain The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible - - Connects to the Management Domain vCenter Server instance + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to Management Domain vCenter Server - Validates that the user does not exist - Adds the user to the vCenter Single Sign-On domain @@ -9443,15 +11179,14 @@ Function Add-vSphereRole { .DESCRIPTION The Add-vSphereRole cmdlet creates a role in vCenter Server. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible - - Connects to the Management Domain vCenter Server instance + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to vCenter Server - Verifies if the role already exists and if not creates it - Assigns permissions to the role based on the template file provided .EXAMPLE Add-vSphereRole -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -roleName "NSX-T Data Center to vSphere Integration" -template .\vSphereRoles\nsx-vsphere-integration.role - This example adds the nsx-vsphere-integration role in the management domain vCenter Server + This example adds the "NSX-T Data Center to vSphere Integration" role in the management domain vCenter Server #> Param ( @@ -9509,6 +11244,61 @@ Function Add-vSphereRole { } Export-ModuleMember -Function Add-vSphereRole +Function Undo-vSphereRole { + <# + .SYNOPSIS + Remove a vSphere role + + .DESCRIPTION + The Undo-vSphereRole cmdlet removes a role from vCenter Server. The cmdlet connects to SDDC Manager using the + -server, -user, and -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to vCenter Server + - Verifies if the role exists and if it does removes it + + .EXAMPLE + Undo-vSphereRole -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -roleName "NSX-T Data Center to vSphere Integration" + This example removes the "NSX-T Data Center to vSphere Integration" role from the management domain vCenter Server + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$roleName + ) + + Try { + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) { + if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + if (Get-VIRole -Server $vcfVcenterDetails.fqdn | Where-Object { $_.Name -eq $roleName }) { + Remove-VIRole -Role $roleName -Server $vcfVcenterDetails.fqdn -Force -Confirm:$false | Out-Null + if (!(Get-VIRole -Server $vcfVcenterDetails.fqdn | Where-Object { $_.Name -eq $roleName })) { + Write-Output "Removing a role from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($roleName): SUCCESSFUL" + } + else { + Write-Error "Removing a role from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($roleName): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Removing a role from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($roleName), already exists: SKIPPED" + } + Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue + } + } + } + } + } + } + Catch { + Debug-ExceptionWriter -object $_ + } +} +Export-ModuleMember -Function Undo-vSphereRole + Function Add-VMFolder { <# .SYNOPSIS @@ -9517,12 +11307,10 @@ Function Add-VMFolder { .DESCRIPTION The Add-VMFolder cmdlet creates a VM and Template folder. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible + - Validates that network connectivity and authentication is possible to SDDC Manager - Validates that the Workload Domain exists in the SDDC Manager inventory - Retrives the details of the vCenter Server for the Workload Domain provided - - Validates that network connectivity is available to the vCenter Server instance - - Makes a connection to the vCenter Server instance and validates that authentication possible + - Validates that network connectivity and authentication is possible to vCenter Server - Validates that the VM and Template folder is not present in the vCenter Server inventory - Creates VM and Template folder the folder in the vCenter Server inventory @@ -9585,12 +11373,10 @@ Function Undo-VMFolder { .DESCRIPTION The Undo-VMFolder cmdlet removes a VM and Template folder. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible + - Validates that network connectivity and authentication is possible to SDDC Manager - Validates that the Workload Domain exists in the SDDC Manager inventory - Retrives the details of the vCenter Server for the Workload Domain provided - - Validates that network connectivity is available to the vCenter Server instance - - Makes a connection to the vCenter Server instance and validates that authentication possible + - Validates that network connectivity and authentication is possible to vCenter Server - Validates that the VM and Template folder is present in the vCenter Server inventory - Removes the VM and Template folder from the vCenter Server inventory @@ -9646,20 +11432,20 @@ Export-ModuleMember -Function Undo-VMFolder Function Add-ResourcePool { <# - .SYNOPSIS - Create a resource pool + .SYNOPSIS + Create a resource pool - .DESCRIPTION - The Add-ResourcePool cmdlet creates a resource pool. The cmdlet connects to SDDC Manager using the -server, -user, and -password values + .DESCRIPTION + The Add-ResourcePool cmdlet creates a resource pool. The cmdlet connects to SDDC Manager using the -server, -user, and -password values to retrive the vCenter Server details from the SDDC Manager inventory and then: - Connects to the vCenter Server - Verifies that the resource pool has not already been created - Creates the resource pool - .EXAMPLE - Add-ResourcePool -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -resourcePoolName "sfo-w01-cl01-rp-workload" - This example shows how to create the folder myFolder within the VMware Cloud Foundation domain sfo-m01 - #> + .EXAMPLE + Add-ResourcePool -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -resourcePoolName "sfo-w01-cl01-rp-workload" + This example shows how to create the folder myFolder within the VMware Cloud Foundation domain sfo-m01 + #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, @@ -9716,20 +11502,20 @@ Export-ModuleMember -Function Add-ResourcePool Function Undo-ResourcePool { <# - .SYNOPSIS - Remove a resource pool + .SYNOPSIS + Remove a resource pool - .DESCRIPTION - The Undo-ResourcePool cmdlet removes a resource pool. The cmdlet connects to SDDC Manager using the -server, -user, and -password values + .DESCRIPTION + The Undo-ResourcePool cmdlet removes a resource pool. The cmdlet connects to SDDC Manager using the -server, -user, and -password values to retrive the vCenter Server details from the SDDC Manager inventory and then: - Connects to the vCenter Server - Verifies that the resource pool exists in the vCenter Server inventory - Removes the resource pool - .EXAMPLE - Undo-ResourcePool -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -resourcePoolName "sfo-w01-cl01-rp-workload" - This example shows how to create the folder myFolder within the VMware Cloud Foundation domain sfo-m01 - #> + .EXAMPLE + Undo-ResourcePool -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -resourcePoolName "sfo-w01-cl01-rp-workload" + This example shows how to create the folder myFolder within the VMware Cloud Foundation domain sfo-m01 + #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, @@ -9767,39 +11553,104 @@ Function Undo-ResourcePool { } } else { - Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server)" + Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server)" + } + } + else { + Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials" + } + } + else { + Write-Error "Unable to communicate with SDDC Manager ($server), check fqdn/ip address" + } + } + Catch { + Debug-ExceptionWriter -object $_ + } +} +Export-ModuleMember -Function Undo-ResourcePool + +Function Add-AntiAffinityRule { + <# + .SYNOPSIS + Creates a vSphere Anti-Affinity rule + + .DESCRIPTION + The Add-AntiAffinityRule cmdlet creates a vSphere Anti-Affinity rule. The cmdlet connects to SDDC Manager using + the -server, -user, and -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to vCenter Server + - Validates that the anti-affinity rule has not already been created in the vCenter Server inventory + - Creates the anti-affinity rule in the vCenter Server inventory + + .EXAMPLE + Add-AntiAffinityRule -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -ruleName sfo-m01-anti-affinity-rule-wsa -antiAffinityVMs "xreg-wsa01a,xreg-wsa01b,xreg-wsa01c" + This example shows how to create a vSphere Anti-Affinity rule in the vCenter Server of the sfo-m01 workload domain + #> + + Param ( + [Parameter (Mandatory = $true)] [String]$server, + [Parameter (Mandatory = $true)] [String]$user, + [Parameter (Mandatory = $true)] [String]$pass, + [Parameter (Mandatory = $true)] [String]$domain, + [Parameter (Mandatory = $true)] [String]$ruleName, + [Parameter (Mandatory = $true)] [String]$antiAffinityVMs + ) + + Try { + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) { + if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) { + if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + $cluster = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }).clusters.id) }).Name + if (!(Get-Cluster -Name $cluster | Get-DrsRule | Where-Object {$_.Name -eq $ruleName})) { + $vmNames = $antiAffinityVMs.split(",") + $vms = foreach ($name in $vmNames) { Get-VM -name $name -ErrorAction SilentlyContinue } + New-DrsRule -Cluster $cluster -Name $ruleName -VM $vms -KeepTogether $false -Enabled $true | Out-Null + if ((Get-Cluster -Name $cluster | Get-DrsRule | Where-Object {$_.Name -eq $ruleName})) { + Write-Output "Adding Anti-Affinity Rule to vCenter Server ($($vcfVcenterDetails.fqdn)) named ($ruleName): SUCCESSFUL" + } + else { + Write-Error "Adding Anti-Affinity Rule to vCenter Server ($($vcfVcenterDetails.fqdn)) named ($ruleName): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Adding Anti-Affinity Rule to vCenter Server ($($vcfVcenterDetails.fqdn)) named ($ruleName), already exists: SKIPPED" + } + Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue + } + } + } + } + else { + Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" } } - else { - Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials" - } - } - else { - Write-Error "Unable to communicate with SDDC Manager ($server), check fqdn/ip address" } } Catch { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Undo-ResourcePool +Export-ModuleMember -Function Add-AntiAffinityRule -Function Add-AntiAffinityRule { +Function Undo-AntiAffinityRule { <# .SYNOPSIS - Creates a vSphere Anti-Affinity rule + Removes a vSphere Anti-Affinity rule .DESCRIPTION - The Add-AntiAffinityRule cmdlet creates a vSphere Anti-Affinity rule. The cmdlet connects to SDDC Manager using + The Undo-AntiAffinityRule cmdlet removes a vSphere Anti-Affinity rule. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible - - Retrives the details of the vCenter Server for the Workload Domain provided - - Validates that the anti-affinity rule has not already been created in the vCenter Server inventory - - Creates the anti-affinity rule in the vCenter Server inventory + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to vCenter Server + - Validates that the anti-affinity rule has not already been removed from the vCenter Server inventory + - Removes the anti-affinity rule from the vCenter Server inventory .EXAMPLE - Add-AntiAffinityRule -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -ruleName sfo-m01-anti-affinity-rule-wsa -antiAffinityVMs "xreg-wsa01a,xreg-wsa01b,xreg-wsa01c" + Undo-AntiAffinityRule -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -ruleName sfo-m01-anti-affinity-rule-wsa This example shows how to create a vSphere Anti-Affinity rule in the vCenter Server of the sfo-m01 workload domain #> @@ -9808,35 +11659,32 @@ Function Add-AntiAffinityRule { [Parameter (Mandatory = $true)] [String]$user, [Parameter (Mandatory = $true)] [String]$pass, [Parameter (Mandatory = $true)] [String]$domain, - [Parameter (Mandatory = $true)] [String]$ruleName, - [Parameter (Mandatory = $true)] [String]$antiAffinityVMs + [Parameter (Mandatory = $true)] [String]$ruleName ) Try { if (Test-VCFConnection -server $server) { if (Test-VCFAuthentication -server $server -user $user -pass $pass) { - if ($vcenter = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain -ErrorAction SilentlyContinue) { - Connect-VIServer -Server $vcenter.fqdn -User $vcenter.ssoAdmin -pass $vcenter.ssoAdminPass | Out-Null - if ($DefaultVIServer.Name -eq $($vcenter.fqdn)) { - $cluster = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }).clusters.id) }).Name - if ((Get-Cluster -Name $cluster | Get-DrsRule | Where-Object {$_.Name -eq $ruleName})) { - Write-Warning "Adding Anti-Affinity Rule to vCenter Server ($($vcenter.fqdn)) named ($ruleName), already exists: SKIPPED" - } - else { - $vmNames = $antiAffinityVMs.split(",") - $vms = foreach ($name in $vmNames) { Get-VM -name $name -ErrorAction SilentlyContinue } - New-DrsRule -Cluster $cluster -Name $ruleName -VM $vms -KeepTogether $false -Enabled $true | Out-Null - if ((Get-Cluster -Name $cluster | Get-DrsRule | Where-Object {$_.Name -eq $ruleName})) { - Write-Output "Adding Anti-Affinity Rule to vCenter Server ($($vcenter.fqdn)) named ($ruleName): SUCCESSFUL" - } - else { - Write-Error "Adding Anti-Affinity Rule to vCenter Server ($($vcenter.fqdn)) named ($ruleName): POST_VALIDATION_FAILED" + if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) { + if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) { + if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + $cluster = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }).clusters.id) }).Name + if (Get-Cluster -Name $cluster | Get-DrsRule | Where-Object {$_.Name -eq $ruleName}) { + Remove-DrsRule -Rule (Get-Cluster -Name $cluster | Get-DrsRule | Where-Object {$_.Name -eq $ruleName}) -Confirm:$false | Out-Null + if (!(Get-Cluster -Name $cluster | Get-DrsRule | Where-Object {$_.Name -eq $ruleName})) { + Write-Output "Removing Anti-Affinity Rule from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($ruleName): SUCCESSFUL" + } + else { + Write-Error "Removing Anti-Affinity Rule from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($ruleName): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Removing Anti-Affinity Rule from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($ruleName), already removed: SKIPPED" + } + Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue } } - Disconnect-VIServer $vcenter.fqdn -Confirm:$false -WarningAction SilentlyContinue - } - else { - Write-Error "Unable to connect to vCenter Server ($($vcenter.fqdn)): PRE_VALIDATION_FAILED" } } else { @@ -9849,7 +11697,7 @@ Function Add-AntiAffinityRule { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-AntiAffinityRule +Export-ModuleMember -Function Undo-AntiAffinityRule Function Add-ClusterGroup { <# @@ -9859,12 +11707,8 @@ Function Add-ClusterGroup { .DESCRIPTION The Add-ClusterGroup cmdlet creates a vSphere DRS Cluster Group. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible - - Validates that the Workload Domain in present in the SDDC Manager inventory - - Retrives the details of the vCenter Server for the Workload Domain provided - - Validates that network connectivity is available to the vCenter Server instance - - Makes a connection to the vCenter Server instance and validates that authentication possible + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to vCenter Server - Validates that that the vSphere DRS Cluster Group does not already exist in the vCenter Server inventory - Creates the vSphere DRS Cluster Group in the vCenter Server inventory @@ -9925,23 +11769,19 @@ Export-ModuleMember -Function Add-ClusterGroup Function Undo-ClusterGroup { <# .SYNOPSIS - Creates a vSphere DRS Cluster Group + Removes a vSphere DRS Cluster Group .DESCRIPTION The Undo-ClusterGroup cmdlet removes the vSphere DRS Cluster Group. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible - - Validates that the Workload Domain in present in the SDDC Manager inventory - - Retrives the details of the vCenter Server for the Workload Domain provided - - Validates that network connectivity is available to the vCenter Server instance - - Makes a connection to the vCenter Server instance and validates that authentication possible + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to vCenter Server - Validates that that the vSphere DRS Cluster Group exist in the vCenter Server inventory - Removes the vSphere DRS Cluster Group in the vCenter Server inventory .EXAMPLE - Undo-ClusterGroup -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -drsGroupName "xint-vm-group-wsa" - This example shows how to create a vSphere DRS Cluster group in the vCenter Server of the sfo-m01 workload domain + Undo-ClusterGroup -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -drsGroupName "sfo-m01-vm-group-wsa" + This example shows how to delete a vSphere DRS Cluster group from the vCenter Server of the sfo-m01 workload domain #> Param ( @@ -9971,7 +11811,7 @@ Function Undo-ClusterGroup { } } else { - Write-Warning "Removing vSphere DRS Group from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($drsGroupName), already exists: SKIPPED" + Write-Warning "Removing vSphere DRS Group from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($drsGroupName), already removed: SKIPPED" } } @@ -9997,22 +11837,21 @@ Export-ModuleMember -Function Undo-ClusterGroup Function Add-VmStartupRule { <# - .SYNOPSIS - Creates a VM to VM DRS rule + .SYNOPSIS + Creates a VM to VM DRS rule - .DESCRIPTION - The Add-VmStartupRule cmdlet creates a vSphere DRS Virtual Machine to Virtual Machine startup rule. The cmdlet + .DESCRIPTION + The Add-VmStartupRule cmdlet creates a vSphere DRS Virtual Machine to Virtual Machine startup rule. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible - - Retrives the details of the vCenter Server for the Workload Domain provided + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to vCenter Server - Validates that that the Virtual Machine to Virtual Machine startup rule does not already exist in the vCenter Server inventory - Creates the vSphere DRS Virtual Machine to Virtual Machine startup rule in the vCenter Server inventory - .EXAMPLE - Add-VmStartupRule -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -ruleName vm-vm-rule-wsa-vra -vmGroup sfo-m01-vm-group-wsa -dependOnVmGroup sfo-m01-vm-group-vra - This example shows how to create a vSphere DRS Cluster group in the vCenter Server of the sfo-m01 workload domain - #> + .EXAMPLE + Add-VmStartupRule -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -ruleName vm-vm-rule-wsa-vra -vmGroup sfo-m01-vm-group-wsa -dependOnVmGroup sfo-m01-vm-group-vra + This example shows how to create a vSphere DRS Cluster group in the vCenter Server of the sfo-m01 workload domain + #> Param ( [Parameter (Mandatory = $true)] [String]$server, @@ -10027,38 +11866,101 @@ Function Add-VmStartupRule { Try { if (Test-VCFConnection -server $server) { if (Test-VCFAuthentication -server $server -user $user -pass $pass) { - if ($vcenter = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain -ErrorAction SilentlyContinue) { - Connect-VIServer -Server $vcenter.fqdn -User $vcenter.ssoAdmin -pass $vcenter.ssoAdminPass | Out-Null - if ($DefaultVIServer.Name -eq $($vcenter.fqdn)) { - $cluster = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }).clusters.id) }).Name - if (Get-Cluster -Name $cluster | Get-DrsClusterGroup | Where-Object {$_.Name -eq $vmGroup}) { - if (Get-Cluster -Name $cluster | Get-DrsClusterGroup | Where-Object {$_.Name -eq $dependOnVmGroup}) { - $ruleNameExists = Get-DrsVmToVmGroup -Cluster $cluster -Name $ruleName - if ($ruleNameExists) { - Write-Warning "Adding vSphere DRS Virtual Machine to Virtual Machine Group to vCenter Server ($($vcenter.fqdn)) named ($ruleName), already exists: SKIPPED" + if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) { + if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) { + if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + $cluster = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }).clusters.id) }).Name + if (Get-Cluster -Name $cluster | Get-DrsClusterGroup | Where-Object {$_.Name -eq $vmGroup}) { + if (Get-Cluster -Name $cluster | Get-DrsClusterGroup | Where-Object {$_.Name -eq $dependOnVmGroup}) { + if (!(Get-DrsVmToVmGroup -Cluster $cluster -Name $ruleName)) { + Add-DrsVmToVmGroup -name $ruleName -vmGroup $vmGroup -dependOnVmGroup $dependOnVmGroup -Enabled -cluster $cluster | Out-Null + Start-Sleep 5 + if (Get-DrsVmToVmGroup -Cluster $cluster -Name $ruleName) { + Write-Output "Adding vSphere DRS Virtual Machine to Virtual Machine Group to vCenter Server ($($vcfVcenterDetails.fqdn)) named ($ruleName): SUCCESSFUL" + } + else { + Write-Error "Adding vSphere DRS Virtual Machine to Virtual Machine Group to vCenter Server ($($vcfVcenterDetails.fqdn)) named ($ruleName): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Adding vSphere DRS Virtual Machine to Virtual Machine Group to vCenter Server ($($vcfVcenterDetails.fqdn)) named ($ruleName), already exists: SKIPPED" + } + } + else { + Write-Error "vSphere DRS Group (VM Group to start after dependency) in vCenter Server ($($vcfVcenterDetails.fqdnn)) named ($dependOnVmGroup), does not exist: PRE_VALIDATION_FAILED" + } } else { - Add-DrsVmToVmGroup -name $ruleName -vmGroup $vmGroup -dependOnVmGroup $dependOnVmGroup -Enabled -cluster $cluster | Out-Null - Start-Sleep 5 - if (Get-DrsVmToVmGroup -Cluster $cluster -Name $ruleName) { - Write-Output "Adding vSphere DRS Virtual Machine to Virtual Machine Group to vCenter Server ($($vcenter.fqdn)) named ($ruleName): SUCCESSFUL" + Write-Error "vSphere DRS Group (VM Group to start first) in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($vmGroup), does not exist: PRE_VALIDATION_FAILED" + } + Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue + } + } + } + } + else { + Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" + } + } + } + } + Catch { + Debug-ExceptionWriter -object $_ + } +} +Export-ModuleMember -Function Add-VmStartupRule + +Function Undo-VmStartupRule { + <# + .SYNOPSIS + Remove a VM to VM DRS rule + + .DESCRIPTION + The Undo-VmStartupRule cmdlet removes a vSphere DRS Virtual Machine to Virtual Machine startup rule. The cmdlet + connects to SDDC Manager using the -server, -user, and -password values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to vCenter Server + - Validates that that the Virtual Machine to Virtual Machine startup rule has not already been removed from the vCenter Server inventory + - Removes the vSphere DRS Virtual Machine to Virtual Machine startup rule from the vCenter Server inventory + + .EXAMPLE + Undo-VmStartupRule -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -ruleName vm-vm-rule-wsa-vrli + This example shows how to remove a vSphere DRS Cluster group from the vCenter Server of the sfo-m01 workload domain + #> + + Param ( + [Parameter (Mandatory = $true)] [String]$server, + [Parameter (Mandatory = $true)] [String]$user, + [Parameter (Mandatory = $true)] [String]$pass, + [Parameter (Mandatory = $true)] [String]$domain, + [Parameter (Mandatory = $true)] [String]$ruleName + ) + + Try { + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) { + if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) { + if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + $cluster = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }).clusters.id) }).Name + if (Get-DrsVmToVmGroup -Cluster $cluster -Name $ruleName) { + Remove-DrsVmToVmGroup -name $ruleName -cluster $cluster | Out-Null + Start-Sleep 3 + if (!(Get-DrsVmToVmGroup -Cluster $cluster -Name $ruleName)) { + Write-Output "Removing vSphere DRS Virtual Machine to Virtual Machine Group from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($ruleName): SUCCESSFUL" } else { - Write-Error "Adding vSphere DRS Virtual Machine to Virtual Machine Group to vCenter Server ($($vcenter.fqdn)) named ($ruleName): POST_VALIDATION_FAILED" + Write-Error "Removing vSphere DRS Virtual Machine to Virtual Machine Group from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($ruleName): POST_VALIDATION_FAILED" } } + else { + Write-Warning "Removing vSphere DRS Virtual Machine to Virtual Machine Group from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($ruleName), already exists: SKIPPED" + } + Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue } - else { - Write-Error "vSphere DRS Group (VM Group to start after dependency) in vCenter Server ($($vcenter.fqdn)) named ($dependOnVmGroup), does not exist: PRE_VALIDATION_FAILED" - } - } - else { - Write-Error "vSphere DRS Group (VM Group to start first) in vCenter Server ($($vcenter.fqdn)) named ($vmGroup), does not exist: PRE_VALIDATION_FAILED" } - Disconnect-VIServer $vcenter.fqdn -Confirm:$false -WarningAction SilentlyContinue - } - else { - Write-Error "Unable to connect to vCenter Server ($($vcenter.fqdn)): PRE_VALIDATION_FAILED" } } else { @@ -10071,27 +11973,26 @@ Function Add-VmStartupRule { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-VmStartupRule +Export-ModuleMember -Function Undo-VmStartupRule Function Move-VMtoFolder { <# - .SYNOPSIS - Moves VMs to a folder + .SYNOPSIS + Moves VMs to a folder - .DESCRIPTION - The Move-VMtoFolder cmdlet moves the Virtual Machines to a folder. The cmdlet connects to SDDC Manager using + .DESCRIPTION + The Move-VMtoFolder cmdlet moves the Virtual Machines to a folder. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible + - Validates that network connectivity and authentication is possible to SDDC Manager - Retrives the details of the vCenter Server for the Workload Domain provided - - Validates that the folder provided exists in the vCenter Server inventory + - Validates that network connectivity and authentication is possible to vCenter Server - Validates the virtual machine exists in the vCenter Server inventory - Moves the virtual machines provided in the -vmlist parameter - .EXAMPLE - Move-VMtoFolder -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -vmList "xreg-wsa01a,xreg-wsa01b,xreg-wsa01c" -folder xinst-m01-fd-wsa - This example shows how to move a list of virtual machines to a new folder - #> + .EXAMPLE + Move-VMtoFolder -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -vmList "xreg-wsa01a,xreg-wsa01b,xreg-wsa01c" -folder xinst-m01-fd-wsa + This example shows how to move a list of virtual machines to a new folder + #> Param ( [Parameter (Mandatory = $true)] [String]$server, @@ -10148,9 +12049,9 @@ Function Import-vRSLCMLockerCertificate { .DESCRIPTION The Import-vRSLCMLockerCertificate cmdlet imports a PEM encoded chain file to the vRealize Suite Lifecycle - Manager Locker. The cmdlet connects to SDDC Manager using the -server, -user, and -password values to retrive the vRealize Suite - Lifecycle Manager server details from the SDDC Manager inventory and then: - - Connects to the vRealize Suite Lifecycle Manager instance + Manager Locker. The cmdlet connects to SDDC Manager using the -server, -user, and -password values then: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to vRealize Suite Lifecycle Manager - Verifies that the certificate is not present in the vRealize Suite Lifecycle Manager Locker - Imports the certificate chain to the vRealize Suite Lifecycle Manager Locker @@ -10220,9 +12121,9 @@ Function Undo-vRSLCMLockerCertificate { .DESCRIPTION The Undo-vRSLCMLockerCertificate cmdlet removes a certificate from the vRealize Suite Lifecycle Manager Locker. - The cmdlet connects to SDDC Manager using the -server, -user, and -password values to retrive the vRealize Suite - Lifecycle Manager server details from the SDDC Manager inventory and then: - - Connects to the vRealize Suite Lifecycle Manager instance + The cmdlet connects to SDDC Manager using the -server, -user, and -password values then: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to vRealize Suite Lifecycle Manager - Verifies that the certificate is present in the vRealize Suite Lifecycle Manager Locker - Removes the certificate from vRealize Suite Lifecycle Manager Locker @@ -10276,9 +12177,9 @@ Function New-vRSLCMLockerPassword { .DESCRIPTION The New-vRSLCMLockerPassword cmdlet adds a password to the vRealize Suite Lifecycle Manager Locker Locker. The - cmdlet connects to SDDC Manager using the -server, -user, and -password values to retrive the vRealize Suite - Lifecycle Manager server details from the SDDC Manager inventory and then: - - Connects to the vRealize Suite Lifecycle Manager instance + cmdlet connects to SDDC Manager using the -server, -user, and -password values then: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to vRealize Suite Lifecycle Manager - Verifies that the password is not present in the vRealize Suite Lifecycle Manager Locker - Adds the password to the vRealize Suite Lifecycle Manager Locker @@ -10339,9 +12240,9 @@ Function Undo-vRSLCMLockerPassword { .DESCRIPTION The Undo-vRSLCMLockerPassword cmdlet removes a password from the vRealize Suite Lifecycle Manager Locker. The - cmdlet connects to SDDC Manager using the -server, -user, and -password values to retrive the vRealize Suite - Lifecycle Manager server details from the SDDC Manager inventory and then: - - Connects to the vRealize Suite Lifecycle Manager instance + cmdlet connects to SDDC Manager using the -server, -user, and -password values then: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to vRealize Suite Lifecycle Manager - Verifies that the password is present in the vRealize Suite Lifecycle Manager Locker - Removes the password from the vRealize Suite Lifecycle Manager Locker @@ -10394,9 +12295,9 @@ Function New-vRSLCMLockerLicense { .DESCRIPTION The New-vRSLCMLockerLicense cmdlet adds a license to the vRealize Suite Lifecycle Manager Locker. The cmdlet - connects to SDDC Manager using the -server, -user, and -password values to retrive the vRealize Suite - Lifecycle Manager server details from the SDDC Manager inventory and then: - - Connects to the vRealize Suite Lifecycle Manager instance + connects to SDDC Manager using the -server, -user, and -password values then: + - Validates that network connectivity and authentication is possible to SDDC Manager + - CValidates that network connectivity and authentication is possible to vRealize Suite Lifecycle Manager - Verifies that the license is not present in the vRealize Suite Lifecycle Manager Locker - Adds the license to the vRealize Suite Lifecycle Manager Locker @@ -10462,9 +12363,9 @@ Function Undo-vRSLCMLockerLicense { .DESCRIPTION The Undo-vRSLCMLockerLicense cmdlet removes a license from the vRealize Suite Lifecycle Manager Locker. The - cmdlet connects to SDDC Manager using the -server, -user, and -password values to retrive the vRealize Suite - Lifecycle Manager server details from the SDDC Manager inventory and then: - - Connects to the vRealize Suite Lifecycle Manager instance + cmdlet connects to SDDC Manager using the -server, -user, and -password values then: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to vRealize Suite Lifecycle Manager - Verifies that the license is present in the vRealize Suite Lifecycle Manager Locker - Removes the license to the vRealize Suite Lifecycle Manager Locker @@ -10518,9 +12419,8 @@ Function New-vRSLCMDatacenter { .DESCRIPTION The New-vRSLCMDatacenter cmdlet adds a datacenter to the vRealize Suite Lifecycle Manager inventory. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible - - Retrives the details of the vRealize Suite Lifecycle Manager + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to vRealize Suite Lifecycle Manager - Validates that the datacenter has not already been created in the inventory - Creates the datacenter in the inventory @@ -10575,9 +12475,8 @@ Function New-vRSLCMDatacenterVcenter { .DESCRIPTION The New-vRSLCMDatacenterVcenter cmdlet adds a vCenter Server to a Datacenter to the vRealize Suite Lifecycle Manager inventory. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible - - Retrives the details of the vRealize Suite Lifecycle Manager + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to vRealize Suite Lifecycle Manager - Validates that the vCenter Server has not already been added to the Datacenter - Adds the vCenter Server to the Datacenter @@ -10644,9 +12543,8 @@ Function Undo-vRSLCMDatacenter { .DESCRIPTION The Undo-vRSLCMDatacenter cmdlet deletes a datacenter from the vRealize Suite Lifecycle Manager inventory. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible - - Retrives the details of the vRealize Suite Lifecycle Manager + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to vRealize Suite Lifecycle Manager - Validates that the datacenter has not already been removed from the inventory - Deletes the datacenter from the inventory @@ -10696,21 +12594,20 @@ Export-ModuleMember -Function Undo-vRSLCMDatacenter Function Add-VmGroup { <# .SYNOPSIS - Add a VM Group + Add a VM Group - .DESCRIPTION - The Add-VmGroup cmdlet adds a Virtual Machine to an existing VM Group. The cmdlet connects to SDDC Manager + .DESCRIPTION + The Add-VmGroup cmdlet adds a Virtual Machine to an existing VM Group. The cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible - - Retrives the details of the vCenter Server for the Workload Domain provided + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to vCenter Server - Validates that the the VM Group provided exists and that its a VM Group not a VM Host Group - Adds the Virtual Machines provided using -vmList .EXAMPLE - Add-VmGroup -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -name "primary_az_vmgroup" -vmList "xint-vra01a,xint-vra01b,xint-vra01c" + Add-VmGroup -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -name "primary_az_vmgroup" -vmList "xint-vra01a,xint-vra01b,xint-vra01c" This example adds the vRealize Automation cluster VMs to the VM Group called primary_az_vmgroup - #> + #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, @@ -10721,26 +12618,131 @@ Function Add-VmGroup { [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vmList ) - Try { - if (Test-VCFConnection -server $server) { - if (Test-VCFAuthentication -server $server -user $user -pass $pass) { - if ($vcenter = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain) { - Connect-VIServer -Server $vcenter.fqdn -User $vcenter.ssoAdmin -Pass $vcenter.ssoAdminPass | Out-Null - if ($DefaultVIServer.Name -eq $($vcenter.fqdn)) { - $vmGroupExists = Get-DrsClusterGroup -Server $vcenter.fqdn -Name $name -ErrorAction Ignore - if ($vmGroupExists.GroupType -eq "VMGroup") { - $vmNames = $vmList.split(",") - foreach ($vm in $vmNames) { Set-DrsClusterGroup -VM $vm -Server $vcenter.fqdn -DrsClusterGroup (Get-DrsClusterGroup | Where-Object {$_.Name -eq $name} -WarningAction SilentlyContinue -ErrorAction Ignore) -Add | Out-Null } - Write-Output "Adding Virtual Machines ($vmList) to VM/Host Group in vCenter Server ($($vcenter.fqdn)) named ($name): SUCCESSFUL" + Try { + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if ($vcenter = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain) { + Connect-VIServer -Server $vcenter.fqdn -User $vcenter.ssoAdmin -Pass $vcenter.ssoAdminPass | Out-Null + if ($DefaultVIServer.Name -eq $($vcenter.fqdn)) { + $vmGroupExists = Get-DrsClusterGroup -Server $vcenter.fqdn -Name $name -ErrorAction Ignore + if ($vmGroupExists.GroupType -eq "VMGroup") { + $vmNames = $vmList.split(",") + foreach ($vm in $vmNames) { Set-DrsClusterGroup -VM $vm -Server $vcenter.fqdn -DrsClusterGroup (Get-DrsClusterGroup | Where-Object {$_.Name -eq $name} -WarningAction SilentlyContinue -ErrorAction Ignore) -Add | Out-Null } + Write-Output "Adding Virtual Machines ($vmList) to VM/Host Group in vCenter Server ($($vcenter.fqdn)) named ($name): SUCCESSFUL" + } + else { + Write-Error "Adding Virtual Machines ($vmList) to VM/Host Group in vCenter Server ($($vcenter.fqdn)) named ($name), does not exist or not a VM Group: POST_VALIDATION_FAILED" + } + } + else { + Write-Error "Unable to connect to vCenter Server ($($vcenter.fqdn)): PRE_VALIDATION_FAILED" + } + } + } + } + } + Catch { + Debug-ExceptionWriter -object $_ + } +} +Export-ModuleMember -Function Add-VmGroup + +Function Add-WorkspaceOneDirectoryGroup { + <# + .SYNOPSIS + Adds Active Directory Group to sync in Workspace ONE Access Appliance + + .DESCRIPTION + The Add-WorkspaceOneDirectoryGroup cmdlet adds an Active Directory Group to sync in Workspace ONE Access Appliance + - Validates that network connectivity and authentication is possible to Workspace ONE Access + - Adds Active Directory Groups to Workspace ONE Access + + .EXAMPLE + Add-WorkspaceOneDirectoryGroup -server sfo-wsa01.sfo.rainpole.io -user admin -pass VMw@re1! -domain sfo.rainpole.io -bindUser svc-vsphere-ad -bindPass VMw@re1! -baseDnGroup "ou=Security Groups,dc=sfo,dc=rainpole,dc=io" -adGroups "gg-vrli-admins","gg-vrli-users","gg-vrli-viewers" + This example adds Active Directory groups to Workspace ONE Access directory + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$bindUser, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$bindPass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$baseDnGroup, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Array]$adGroups + ) + + Try { + if (Test-WSAConnection -server $server) { + if (Test-WSAAuthentication -server $server -user $user -pass $pass) { + if ((Test-ADAuthentication -user $bindUser -pass $bindPass -server $domain -domain $domain) -match "AD Authentication Successful") { + if (Get-WSADirectory | Where-Object { ($_.name -eq $domain) }) { + $configuredGroups = New-Object System.Collections.Generic.List[System.Object] + $allGroups = New-Object System.Collections.Generic.List[System.Object] + $existingGroupList = Get-WSAGroup | Where-Object {$_.displayName -Match $domain} | Select-Object displayName + foreach ($existingGroup in $existingGroupList) { + $groupName = ($existingGroup.displayname.Split("@"))[0] + $configuredGroups.Add($groupName) + $allGroups.Add($groupName) + } + $missingGroups = Compare-Object $adGroups $configuredGroups | Where-Object { $_.SideIndicator -eq '<=' } | Foreach-Object { $_.InputObject } + foreach ($newGroup in $missingGroups) { + $allGroups.Add($newGroup) + } + $allGroups.ToArray() | Out-Null + + $mappedGroupObject = @() + foreach ($group in $allGroups) { + $adGroupDetails = Get-ADPrincipalGuid -domain $domain -user $bindUser -pass $bindPass -principal $group + if ($adGroupDetails) { + $groupsObject = @() + $groupsObject += [pscustomobject]@{ + 'horizonName' = $adGroupDetails.Name + 'dn' = $adGroupDetails.DistinguishedName + 'objectGuid' = $adGroupDetails.ObjectGuid + 'groupBaseDN' = $baseDnGroup + 'source' = "DIRECTORY" + } + $mappedGroupObject += [pscustomobject]@{ + 'mappedGroup' = ($groupsObject | Select-Object -Skip 0) + 'selected' = $true + } + } + else { + Write-Error "Group $group is not available in Active Directory Domain" + } } - else { - Write-Error "Adding Virtual Machines ($vmList) to VM/Host Group in vCenter Server ($($vcenter.fqdn)) named ($name), does not exist or not a VM Group: POST_VALIDATION_FAILED" + $mappedGroupObjectData = @() + $mappedGroupObjectData += [pscustomobject]@{ + 'mappedGroupData' = $mappedGroupObject + 'selected' = $false + } + $identityGroupObject = @() + $identityGroupObject += [pscustomobject]@{ + $baseDnGroup = ($mappedGroupObjectData | Select-Object -Skip 0) + } + $adGroupObject = @() + $adGroupObject += [pscustomobject]@{ + 'identityGroupInfo' = ($identityGroupObject | Select-Object -Skip 0) + 'excludeNestedGroupMembers' = $false } + $adGroupJson = $adGroupObject | ConvertTo-Json -Depth 10 + + $adGroupJson | Out-File -Encoding UTF8 -FilePath .\adGroups.json + + Set-WSADirectoryGroup -directoryId (Get-WSADirectory | Where-Object { ($_.name -eq $domain) }).directoryId -json $adGroupJson | Out-Null + Start-WSADirectorySync -directoryId (Get-WSADirectory | Where-Object { ($_.name -eq $domain) }).directoryId | Out-Null + Remove-Item .\adGroups.json -Force -Confirm:$false + Write-Output "Adding Active Directory Groups in Workspace ONE Access ($server): SUCCESSFUL" } else { - Write-Error "Unable to connect to vCenter Server ($($vcenter.fqdn)): PRE_VALIDATION_FAILED" + Write-Error "Active Directory Domain ($domain) does not exist, check details and try again: PRE_VALIDATION_FAILED" } } + else { + Write-Error "Domain User ($bindUser) Authentication Failed: PRE_VALIDATION_FAILED" + } } } } @@ -10748,22 +12750,24 @@ Function Add-VmGroup { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-VmGroup +Export-ModuleMember -Function Add-WorkspaceOneDirectoryGroup -Function Add-WorkspaceOneDirectoryGroup { +Function Undo-WorkspaceOneDirectoryGroup { <# .SYNOPSIS - Adds Active Directory Group to sync in Workspace ONE Access Appliance + Removes Active Directory Group from Workspace ONE Access - .DESCRIPTION - The Add-WorkspaceOneDirectoryGroup cmdlet adds an Active Directory Group to sync in Workspace ONE Access Appliance + .DESCRIPTION + The Undo-WorkspaceOneDirectoryGroup cmdlet removes an Active Directory Group from Workspace ONE Access. + - Validates that network connectivity and authentication is possible to Workspace ONE Access + - Remove Active Directory Groups from Workspace ONE Access - .EXAMPLE - Add-WorkspaceOneDirectory -server sfo-wsa01.sfo.rainpole.io -user admin -pass VMw@re1! -domain sfo.rainpole.io -baseDn "OU=VVD,DC=sfo,DC=rainpole,DC=io" -bindUserDn "CN=svc-wsa-ad,OU=VVD,DC=sfo,DC=rainpole,DC=io" -bindUserPass VMw@re1! -adGroups "gg-nsx-enterprise-admins","gg-nsx-network-admins","gg-nsx-auditors","gg-wsa-admins","gg-wsa-directory-admins","gg-wsa-read-only" -protocol "ldaps" -certificate "F:\platformtools-l1-dev\certificates\Root64.pem" - This example adds Active Directory groups to Workspace ONE Access directory - #> + .EXAMPLE + Undo-WorkspaceOneDirectoryGroup -server sfo-wsa01.sfo.rainpole.io -user admin -pass VMw@re1! -domain sfo.rainpole.io -bindUser svc-vsphere-ad -bindPass VMw@re1! -baseDnGroup "ou=Security Groups,dc=sfo,dc=rainpole,dc=io" -adGroups "gg-vrli-admins","gg-vrli-users","gg-vrli-viewers" + This example removes Active Directory groups from Workspace ONE Access directory + #> - Param ( + Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, @@ -10778,18 +12782,16 @@ Function Add-WorkspaceOneDirectoryGroup { if (Test-WSAConnection -server $server) { if (Test-WSAAuthentication -server $server -user $user -pass $pass) { if ((Test-ADAuthentication -user $bindUser -pass $bindPass -server $domain -domain $domain) -match "AD Authentication Successful") { - $checkDirectoryExist = Get-WSADirectory | Where-Object { ($_.name -eq $domain) } - if ($checkDirectoryExist) { + if (Get-WSADirectory | Where-Object { ($_.name -eq $domain) }) { $configuredGroups = New-Object System.Collections.Generic.List[System.Object] $allGroups = New-Object System.Collections.Generic.List[System.Object] $existingGroupList = Get-WSAGroup | Where-Object {$_.displayName -Match $domain} | Select-Object displayName foreach ($existingGroup in $existingGroupList) { $groupName = ($existingGroup.displayname.Split("@"))[0] $configuredGroups.Add($groupName) - $allGroups.Add($groupName) } - $missingGroups = Compare-Object $adGroups $configuredGroups | Where-Object { $_.SideIndicator -eq '<=' } | Foreach-Object { $_.InputObject } - foreach ($newGroup in $missingGroups) { + $requiredGroups = Compare-Object $adGroups $configuredGroups | Foreach-Object { $_.InputObject } #| Where-Object { $_.SideIndicator -eq '==' } | Foreach-Object { $_.InputObject } + foreach ($newGroup in $requiredGroups) { $allGroups.Add($newGroup) } $allGroups.ToArray() | Out-Null @@ -10831,14 +12833,14 @@ Function Add-WorkspaceOneDirectoryGroup { } $adGroupJson = $adGroupObject | ConvertTo-Json -Depth 10 - $adGroupJson | Out-File -Encoding UTF8 -FilePath "adGroups.json" - - Set-WSADirectoryGroup -directoryId $checkDirectoryExist.directoryId -json $adGroupJson | Out-Null - Start-WSADirectorySync -directoryId $checkDirectoryExist.directoryId | Out-Null - Write-Output "Adding Active Directory Directory Groups in Workspace One Access ($server): SUCCESSFUL" + $adGroupJson | Out-File -Encoding UTF8 -FilePath .\adGroups.json + Set-WSADirectoryGroup -directoryId (Get-WSADirectory | Where-Object { ($_.name -eq $domain) }).directoryId -json $adGroupJson | Out-Null + Start-WSADirectorySync -directoryId (Get-WSADirectory | Where-Object { ($_.name -eq $domain) }).directoryId | Out-Null + Remove-Item .\adGroups.json -Force -Confirm:$false + Write-Output "Removing Active Directory Groups in Workspace ONE Access ($server): SUCCESSFUL" } else { - Write-Error "Active Directory Directory Domain ($domain) does not exist, check details and try again: PRE_VALIDATION_FAILED" + Write-Error "Active Directory Domain ($domain) does not exist, check details and try again: PRE_VALIDATION_FAILED" } } else { @@ -10851,7 +12853,7 @@ Function Add-WorkspaceOneDirectoryGroup { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-WorkspaceOneDirectoryGroup +Export-ModuleMember -Function Undo-WorkspaceOneDirectoryGroup Function Add-WorkspaceOneDirectoryConnector { <# @@ -10917,6 +12919,62 @@ Function Add-WorkspaceOneDirectoryConnector { } Export-ModuleMember -Function Add-WorkspaceOneDirectoryConnector +Function Update-SddcDeployedFlavor { + <# + .SYNOPSIS + Add a Validated Solution tag + + .DESCRIPTION + The Update-SddcDeployedFlavor cmdlet adds a Validated Solution tag to the vCenter Server Advanced Setting + `config.SDDC.Deployed.Flavor`. The cmdlet connects to SDDC Manager using the -server, -user, and -password + values: + - Validates that network connectivity and authentication is possible to SDDC Manager + - Validates that network connectivity and authentication is possible to vCenter Server + - Adds a Validated Solution tag to the vCenter Server Advanced Setting `config.SDDC.Deployed.Flavor` + + .EXAMPLE + Update-SddcDeployedFlavor -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -vvsTag IAM + This example adds the IAM tag to the `config.SDDC.Deployed.Flavor` vCenter Server Advanced Setting + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateSet("IAM","DRI","ILA","IOM","PCA","PDR","ALB")] [String]$vvsTag + ) + + Try { + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) { + if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + $advancedSetting = Get-AdvancedSetting -Name "config.SDDC.Deployed.Flavor" -Entity $vcfVcenterDetails.fqdn -Server $vcfVcenterDetails.fqdn + [Array]$flavours = $advancedSetting.Value -Split ", " + $newFlavours = New-Object System.Collections.Generic.List[System.Object] + Foreach ($flavour in $flavours) { + if (!($flavour -eq $vvsTag)) { + $newFlavours += $flavour + } + } + $newFlavours += $vvsTag + $newFlavours = $newFlavours | Sort-Object + [String]$updatedFlavour = $newFlavours -Join ", " + Set-AdvancedSetting -AdvancedSetting $advancedSetting -Value $updatedFlavour -Confirm:$false | Out-Null + Disconnect-VIServer -Server $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue | Out-Null + } + } + } + } + } + } + Catch { + Debug-ExceptionWriter -object $_ + } +} +Export-ModuleMember -Function Update-SddcDeployedFlavor + ########################################## E N D O F F U N C T I O N S ########################################## ####################################################################################################################### @@ -11172,6 +13230,8 @@ Function Get-vRSLCMServerDetail { $vrslcmDetails | Add-Member -notepropertyname 'fqdn' -notepropertyvalue $vRSLCMFQDN.fqdn $vrslcmDetails | Add-Member -notepropertyname 'adminUser' -notepropertyvalue ($vRSLCMCreds | Where-Object { ($_.credentialType -eq "API" -and $_.accountType -eq "SYSTEM") }).username $vrslcmDetails | Add-Member -notepropertyname 'adminPass' -notepropertyvalue ($vRSLCMCreds | Where-Object { ($_.credentialType -eq "API" -and $_.accountType -eq "SYSTEM") }).password + $vrslcmDetails | Add-Member -notepropertyname 'rootUser' -notepropertyvalue ($vRSLCMCreds | Where-Object { ($_.credentialType -eq "SSH" -and $_.accountType -eq "SYSTEM") }).username + $vrslcmDetails | Add-Member -notepropertyname 'rootPassword' -notepropertyvalue ($vRSLCMCreds | Where-Object { ($_.credentialType -eq "SSH" -and $_.accountType -eq "SYSTEM") }).password $vrslcmDetails } else { @@ -11387,6 +13447,48 @@ Function Get-vRLIServerDetail { } Export-ModuleMember -Function Get-vRLIServerDetail +Function Get-VCFDnsSearchDomain { + <# + .SYNOPSIS + Get the search domains configured in an SDDC Manager appliance + + .DESCRIPTION + The Get-VCFSearchDomain cmdlet gets the search domains configured in an SDDC Manager appliance + + .EXAMPLE + Get-VCFSearchDomain + This example gets all search domains configured in an SDDC Manager appliance + #> + + Param ( + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$sddcManagerVmName, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$sddcManagerRootPass + ) + + Try { + $scriptCommand = "cat /etc/resolv.conf" + $output = Invoke-VMScript -VM $sddcManagerVmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $sddcManagerRootPass -Server $vcfVcenterDetails.fqdn + $outputArray = ($output.Scriptoutput.Split("`r`n") | Where-Object {$_ -match "search" -and $_ -notmatch "search domains"}).Split(" ") + $searchDomains = @() + foreach ($item in $outputArray) { + if ($item -notmatch "search") { + $searchDomains += $item + } + } + } + Catch { + Write-Error $_.Exception.Message + } + + if ($searchDomains) { + return $searchDomains + } else { + Write-Error "Unable to locate any DNS search domains on ($sddcManagerVmName) : POST_VALIDATION_FAILED" + } + +} +Export-ModuleMember -Function Get-VCFDnsSearchDomain + ############## End Cloud Foundation Functions ############## ############################################################## @@ -11519,6 +13621,84 @@ Function Request-vSphereApiToken { } Export-ModuleMember -Function Request-vSphereApiToken +Function Connect-vSphereMobServer { + <# + .SYNOPSIS + Connect to the vSphere Managed Object Browser (MOB) + + .DESCRIPTION + The Connect-vSphereMobServer cmdlet is used to connect to the vSphere Managed Object Browser (MOB) + + .EXAMPLE + Connect-vSphereMobServer -server sfo-m01-vc01.sfo.rainpole.io -username administrator@vsphere.local -password VMw@re1! + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String] $server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String] $username, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String] $password + ) + + Try { + $securePassword = ConvertTo-SecureString $password -AsPlainText -Force + $credential = New-Object System.Management.Automation.PSCredential($username, $securePassword) + $Global:DefaultMobServer = @{ + Server = $server + Credential = $credential + skipCertificateCheck = $true + } + $uri = "https://$($Global:DefaultMobServer.Server)/invsvc/mob3/?moid=authorizationService&" + "method=AuthorizationService.GetRoles" + $params = @{ + Uri = $uri + SessionVariable = "mobSession" + Credential = $Global:DefaultMobServer.Credential + Method = "GET" + } + $response = Invoke-WebRequest @params -UseBasicParsing + if ($response.StatusCode -eq 200) { + $null = $response -match 'name="vmware-session-nonce" type="hidden" value="?([^\s^"]+)"' + $Global:DefaultMobServer.SessionNonce = $matches[1] + $Global:DefaultMobServer.WebSession = $mobSession + Write-Verbose "Connected to vSphere MOB Server ($($Global:DefaultMobServer.Server))" + } + else { + Throw "Failed to login to vSphere MOB Server ($($Global:DefaultMobServer.Server))" + } + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Connect-vSphereMobServer + +Function Disconnect-vSphereMobServer { + <# + .SYNOPSIS + Disconnects from the vSphere Managed Object Browser (MOB) + + .DESCRIPTION + The Disconnect-vSphereMobServer cmdlet is used to disconnect from the vSphere Managed Object Browser (MOB) + + .EXAMPLE + Disconnect-vSphereMobServer + #> + + Try { + $uri = "https://$($Global:DefaultMobServer.Server)/invsvc/mob3/logout" + $response = Invoke-WebRequest -Method GET -Uri $uri -WebSession $Global:DefaultMobServer.WebSession -UseBasicParsing + $Global:DefaultMobServer.Server = $null + $Global:DefaultMobServer.WebSession = $null + $Global:DefaultMobServer.SessionOnce = $null + if ($response.StatusCode -eq 200) { + Write-Verbose "Disconnect from vSphere MOB Server ($($Global:DefaultMobServer.Server))" + } + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Disconnect-vSphereMobServer + Function Get-VCVersion { <# .SYNOPSIS @@ -11710,90 +13890,162 @@ Function Set-VCPasswordExpiry { } Export-ModuleMember -Function Set-VCPasswordExpiry -Function Add-GlobalPermission { +Function Get-GlobalPermission { <# .SYNOPSIS - Script to add vSphere Global Permission + Get vSphere Global Permission .DESCRIPTION - The Add-GlobalPermission cmdlet adds a new vSphere Global Permission + The Get-GlobalPermission cmdlet gets a list of vSphere Global Permission - .NOTES - Author: William Lam. Modified by Ken Gould to permit principal type (user or group) and Gary Blake to include - in this function - Reference: http://www.virtuallyghetto.com/2017/02/automating-vsphere-global-permissions-with-powercli.html + .EXAMPLE + Get-GlobalPermission + This example shows how to gets a list of vSphere Global Permission + #> + + Try { + $uri = "https://$($Global:DefaultMobServer.Server)/invsvc/mob3/?moid=authorizationService&" + "method=AuthorizationService.GetGlobalAccessControlList" + $body = "vmware-session-nonce=$($Global:DefaultMobServer.SessionNonce)" + $params = @{ + Uri = $uri + WebSession = $Global:DefaultMobServer.WebSession + Credential = $Global:DefaultMobServer.Credential + Method = "POST" + Body = $body + UseBasicParsing = $false + } + $response = Invoke-WebRequest @params + $vsphereRoles = Get-VIRole | Select-Object Name, @{N="Id";E={@($_.Id)}} # Gather vSphere Roles and their Id + $roleLookup = @{} + foreach ($role in $vsphereRoles) { + $roleLookup."$($role.Id)" = $role.Name + } + # Extract the data from the parsed HTML + $table = $response.ParsedHtml.body.getElementsByTagName("table")[3] + $td = $table.getElementsByTagName("tr")[4].getElementsByTagName("td")[2] + $li = $td.getElementsByTagName("ul")[0].getElementsByTagName("li") + + foreach ($item in $li) { + if ($item.innerHTML.StartsWith(" Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vcServer, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vcUsername, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vcPassword, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$principal, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$roleId, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$propagate, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$type + [Parameter (Mandatory = $true)] [ValidateSet("true","false")] [String]$propagate, + [Parameter (Mandatory = $true)] [ValidateSet("group","user")] [String]$type ) Try { - $secpasswd = ConvertTo-SecureString $vcPassword -AsPlainText -Force - $credential = New-Object System.Management.Automation.PSCredential($vcUsername, $secpasswd) - $mob_url = "https://$vcServer/invsvc/mob3/?moid=authorizationService&method=AuthorizationService.AddGlobalAccessControlList" # vSphere MOB URL to private enableMethods - - # Ignore SSL Warnings - add-type -TypeDefinition @" - 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; - } - } -"@ - [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy - $results = Invoke-WebRequest -Uri $mob_url -SessionVariable vmware -Credential $credential -Method GET -UseBasicParsing # Initial login to vSphere MOB using GET and store session using $vmware variable - # Extract hidden vmware-session-nonce which must be included in future requests to prevent CSRF error - # Credit to https://blog.netnerds.net/2013/07/use-powershell-to-keep-a-cookiejar-and-post-to-a-web-form/ for parsing vmware-session-nonce via Powershell - if ($results.StatusCode -eq 200) { - $null = $results -match 'name="vmware-session-nonce" type="hidden" value="?([^\s^"]+)"' - $sessionnonce = $matches[1] + $userEscaped = [uri]::EscapeUriString($principal) # Escape username + $uri = "https://$($Global:DefaultMobServer.Server)/invsvc/mob3/?moid=authorizationService&" + "method=AuthorizationService.AddGlobalAccessControlList" # vSphere MOB URL to private enableMethods + # The POST data payload must include the vmware-session-nonce variable + URL-encoded + if ($type -eq "group") { + $body = "vmware-session-nonce=$($Global:DefaultMobServer.SessionNonce)&permissions=%3Cpermissions%3E%0D%0A+++%3Cprincipal%3E%0D%0A++++++%3Cname%3E$userEscaped%3C%2Fname%3E%0D%0A++++++%3Cgroup%3Etrue%3C%2Fgroup%3E%0D%0A+++%3C%2Fprincipal%3E%0D%0A+++%3Croles%3E$roleId%3C%2Froles%3E%0D%0A+++%3Cpropagate%3E$propagate%3C%2Fpropagate%3E%0D%0A%3C%2Fpermissions%3E" } else { - Write-Error "Failed to login to vSphere MOB" - exit 1 + $body = "vmware-session-nonce=$($Global:DefaultMobServer.SessionNonce)&permissions=%3Cpermissions%3E%0D%0A+++%3Cprincipal%3E%0D%0A++++++%3Cname%3E$userEscaped%3C%2Fname%3E%0D%0A++++++%3Cgroup%3Efalse%3C%2Fgroup%3E%0D%0A+++%3C%2Fprincipal%3E%0D%0A+++%3Croles%3E$roleId%3C%2Froles%3E%0D%0A+++%3Cpropagate%3E$propagate%3C%2Fpropagate%3E%0D%0A%3C%2Fpermissions%3E" + } + $params = @{ + Uri = $uri + WebSession = $Global:DefaultMobServer.WebSession + Credential = $Global:DefaultMobServer.Credential + Method = "POST" + Body = $body + UseBasicParsing = $true + } + $response = Invoke-WebRequest @params + if ($response.StatusCode -eq 200) { + Write-Verbose "Successfully added vCenter Global Permission for ($principal)" } - - $vc_user_escaped = [uri]::EscapeUriString($user) # Escape username - - # The POST data payload must include the vmware-session-nonce variable + URL-encoded - If ($type -eq "group") { - $body = @" -vmware-session-nonce=$sessionnonce&permissions=%3Cpermissions%3E%0D%0A+++%3Cprincipal%3E%0D%0A++++++%3Cname%3E$vc_user_escaped%3C%2Fname%3E%0D%0A++++++%3Cgroup%3Etrue%3C%2Fgroup%3E%0D%0A+++%3C%2Fprincipal%3E%0D%0A+++%3Croles%3E$roleId%3C%2Froles%3E%0D%0A+++%3Cpropagate%3E$propagate%3C%2Fpropagate%3E%0D%0A%3C%2Fpermissions%3E -"@ } - else { - $body = @" -vmware-session-nonce=$sessionnonce&permissions=%3Cpermissions%3E%0D%0A+++%3Cprincipal%3E%0D%0A++++++%3Cname%3E$vc_user_escaped%3C%2Fname%3E%0D%0A++++++%3Cgroup%3Efalse%3C%2Fgroup%3E%0D%0A+++%3C%2Fprincipal%3E%0D%0A+++%3Croles%3E$roleId%3C%2Froles%3E%0D%0A+++%3Cpropagate%3E$propagate%3C%2Fpropagate%3E%0D%0A%3C%2Fpermissions%3E -"@ + Catch { + Write-Error $_.Exception.Message } +} +Export-ModuleMember -Function Add-GlobalPermission + +Function Remove-GlobalPermission { + <# + .SYNOPSIS + Remove a vSphere Global Permission + + .DESCRIPTION + The Remove-GlobalPermission cmdlet removes a user or group from a vSphere Global Permission + + .EXAMPLE + Remove-GlobalPermission -principal gg-vc-admins -type group + This example shows how to remove the Administrator global permission from the group called svc-vc-admins + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$principal, + [Parameter (Mandatory = $true)] [ValidateSet("group","user")] [String]$type + ) - $results = Invoke-WebRequest -Uri $mob_url -WebSession $vmware -Method POST -Body $body -UseBasicParsing # Second request using a POST and specifying our session from initial login + body request - if ($results.StatusCode -eq 200) { - Write-Verbose "Successfully added global permission for: $user" + Try { + $userEscaped = [uri]::EscapeUriString($principal) # Escape username + $uri = "https://$($Global:DefaultMobServer.Server)/invsvc/mob3/?moid=authorizationService&" + "method=AuthorizationService.RemoveGlobalAccess" + if ($type -eq "group") { + $body = "vmware-session-nonce=$($Global:DefaultMobServer.SessionNonce)&principals=%3Cprincipals%3E%0D%0A+++%3Cname%3E$userEscaped%3C%2Fname%3E%0D%0A+++%3Cgroup%3Etrue%3C%2Fgroup%3E%0D%0A%3C%2Fprincipals%3E" + } + else { + $body = "vmware-session-nonce=$($Global:DefaultMobServer.SessionNonce)&principals=%3Cprincipals%3E%0D%0A+++%3Cname%3E$userEscaped%3C%2Fname%3E%0D%0A+++%3Cgroup%3Efalse%3C%2Fgroup%3E%0D%0A%3C%2Fprincipals%3E" + } + $params = @{ + Uri = $uri + WebSession = $Global:DefaultMobServer.WebSession + Credential = $Global:DefaultMobServer.Credential + Method = "POST" + Body = $body + UseBasicParsing = $true + } + $response = Invoke-WebRequest @params + if ($response.StatusCode -eq 200) { + Write-Verbose "Successfully removed vCenter Gobal Permission for ($principal)" } - $mob_logout_url = "https://$vcServer/invsvc/mob3/logout" # Logout out of vSphere MOB - $results = Invoke-WebRequest -Uri $mob_logout_url -WebSession $vmware -Method GET -UseBasicParsing } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Add-GlobalPermission +Export-ModuleMember -Function Remove-GlobalPermission Function Get-SsoPasswordPolicies { <# @@ -11869,7 +14121,43 @@ Function Add-DrsVmToVmGroup { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Add-DrsVmToVmGroup +Export-ModuleMember -Function Add-DrsVmToVmGroup + +Function Remove-DrsVmToVmGroup { + <# + .SYNOPSIS + Remove a vSphere VM to VM Group + + .DESCRIPTION + The Remove-DrsVmToVmGroup cmdlet removes a vSphere VM to VM Group + + .EXAMPLE + Remove-DrsVmToVmGroup -name vm-vm-rule-wsa-vrli -cluster sfo-m01-cl01 + This example shows how to remove a vSphere VM to VM group from vCenter Server + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$name, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster + ) + + Try { + $updateCluster = Get-Cluster | Where-Object {$_.Name -eq $cluster} + + $spec = New-Object VMware.Vim.ClusterConfigSpecEx + $spec.RulesSpec = New-Object VMware.Vim.ClusterRuleSpec[] (1) + $spec.RulesSpec[0] = New-Object VMware.Vim.ClusterRuleSpec + $spec.RulesSpec[0].RemoveKey = (Get-DrsVmToVmGroup -name $name -cluster $cluster).Key + $spec.RulesSpec[0].Operation = 'remove' + + $ClusterToReconfig = Get-View -Id $updateCluster.ExtensionData.MoRef + $ClusterToReconfig.ReconfigureComputeResource_Task($spec, $true) + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Remove-DrsVmToVmGroup Function Get-DrsVmToVmGroup { <# @@ -13332,18 +15620,25 @@ Function Set-NsxtVidm { #> Param ( - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$wsaHostname, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$thumbprint, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$clientId, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$sharedSecret, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$nsxHostname + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaHostname, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$thumbprint, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$clientId, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sharedSecret, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$nsxHostname, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$disable ) Try { $uri = "https://$nsxtManager/api/v1/node/aaa/providers/vidm" + if ($PsBoundParameters.ContainsKey("disable")) { + $status = "false" + } + else { + $status = "true" + } $body = '{ "lb_enable": false, - "vidm_enable": true, + "vidm_enable": ' + $status + ', "host_name": "' + $wsaHostname + '", "thumbprint": "' + $thumbprint + '", "client_id": "' + $clientId + '", @@ -15517,126 +17812,454 @@ Function New-vRealizeLoadBalancerSpec { } Export-ModuleMember -Function New-vRealizeLoadBalancerSpec -Function Get-NsxtGlobalSegmentID { +Function Get-NsxtGlobalSegmentID { + Param ( + [Parameter (Mandatory=$true)] + [String]$segmentName + ) + + Try { + $uri = "https://$nsxtmanager/policy/api/v1/global-infra/segments/" + + $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders + $segmentObjectId = ($response.results | where-object {$_.display_name -eq $segmentName}).id + } + Catch { + Write-Error $_.Exception.Message + } + Return $segmentObjectId +} +Export-ModuleMember -Function Get-NsxtGlobalSegmentID + +Function Add-CertToNsxCertificateStore { + Param ( + [Parameter (Mandatory = $true)] [String]$certName + ) + + Try { + $pemFile = Get-ExternalFileName -title "Select the Certificate Chain PEM File for Clustered WSA (.pem)" -fileType "pem" -location "default" + } + Catch { + Write-Error $_.Exception.Message + } + Try { + $keyFile = Get-ExternalFileName -title "Select the Key File for Clustered WSA (.key)" -fileType "key" -location "default" + } + Catch { + Write-Error $_.Exception.Message + } + + $certAlreadyImported = "" + + #check for existing certificate + Try { + $certAlreadyImported = Get-NsxtCertificate -certificateName $certName -ErrorAction SilentlyContinue + } + Catch { + $certAlreadyImported = $false + } + + # report on existing cert or install new cert + if ($certAlreadyImported) { + $wsaCertPresent = $true + } + else { + $pemContent = (Get-Content $pemFile) -join "\n" + $keyContent = (Get-Content $keyFile) -join "\n" + $body = + '{ + "pem_encoded": "", + "private_key": "" + } + ' + $body = $body | ForEach-Object { $_ ` + -replace '', $pemContent ` + -replace '', $keyContent ` + } + Try { + Set-NsxtCertificate -certificateName $certName -json $body + $wsaCertPresent = $true + } + Catch { + Debug-ExceptionWriter -object $_ + } + } + Return $wsaCertPresent +} +Export-ModuleMember -Function Add-CertToNsxCertificateStore + +Function Get-NsxtEdgeCluster { + <# + .SYNOPSIS + Gets NSX-T Edge Cluster Id + + .DESCRIPTION + The Get-NsxtEdgeCluster cmdlet gets the Edge Cluster Id + + .EXAMPLE + Get-NsxtEdgeCluster + This example creates a new Route Map on a Tier 0 Gateway + #> + + Try { + $uri = "https://$nsxtmanager/api/v1/edge-clusters" + $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders + $response.results + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Get-NsxtEdgeCluster + +Function New-NsxtTier1 { + <# + .SYNOPSIS + Creates a Tier 1 Gateway + + .DESCRIPTION + The New-NsxtTier1 cmdlet creates a Teir 1 Gateway + + .EXAMPLE + New-NsxtTier1 -tier1Gateway sfo-w01-ec01-t0-lb01 -json $ConfigJson + This example creates a new Tier 1 Gateway + #> + + Param ( + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$tier1Gateway, + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$json + ) + + Try { + $uri = "https://$nsxtmanager/policy/api/v1/infra/tier-1s/$($tier1Gateway)" + $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -headers $nsxtHeaders -body $json + $response + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function New-NsxtTier1 + +Function Set-NsxtTier1 { + <# + .SYNOPSIS + Configures Tier 1 Gateway + + .DESCRIPTION + The Set-NsxtTier1 cmdlet configures a Tier 1 Gateway + + .EXAMPLE + Set-NsxtTier1 -tier1Gateway -json + This example sets the configuration on a Tier 1 Gateway + #> + + Param ( + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$tier1Gateway, + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$json + ) + + Try { + $uri = "https://$nsxtmanager/policy/api/v1/infra/tier-1s/$($tier1Gateway)/locale-services/default" + $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -headers $nsxtHeaders -body $json + $response + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Set-NsxtTier1 + +Function New-NsxtTier1ServiceInterface { + <# + .SYNOPSIS + Creates Service Interface on Tier 1 Gateway + + .DESCRIPTION + The New-NsxtTier1ServiceInterface cmdlet configures a Service Interface on Tier 1 Gateway + + .EXAMPLE + New-NsxtTier1ServiceInterface -tier1Gateway -interfaceId -json + This example configures a Service Interface on a Tier 1 Gateway + #> + + Param ( + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$tier1Gateway, + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$interfaceId, + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$json + ) + + Try { + $uri = "https://$nsxtmanager/policy/api/v1/infra/tier-1s/$($tier1Gateway)/locale-services/default/interfaces/$($interfaceId)" + $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -headers $nsxtHeaders -body $json + $response + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function New-NsxtTier1ServiceInterface + +Function New-NsxtTier1StaticRoute { + <# + .SYNOPSIS + Creates Static Route on Tier 1 Gateway + + .DESCRIPTION + The New-New-NsxtTier1StaticRoute cmdlet creates a static route on Tier 1 Gateway + + .EXAMPLE + New-NsxtTier1StaticRoute -tier1Gateway -segment -json + This example configures a Service Interface on a Tier 1 Gateway + #> + + Param ( + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$tier1Gateway, + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$segment, + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$json + ) + + Try { + $uri = "https://$nsxtmanager/policy/api/v1/infra/tier-1s/$($tier1Gateway)/static-routes/$($segment)" + $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -headers $nsxtHeaders -body $json + $response + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function New-NsxtTier1StaticRoute + +Function New-NsxtLoadBalancer { + <# + .SYNOPSIS + Creates a Load Balancer + + .DESCRIPTION + The New-NsxtLoadBalancer cmdlet creates a load balancer + + .EXAMPLE + New-NsxtLoadBalancer -lbName -json + This example creates a load balancer + #> + + Param ( + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$lbName, + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$json + ) + + Try { + $uri = "https://$nsxtmanager/policy/api/v1/infra/lb-services/$($lbName)" + $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -headers $nsxtHeaders -body $json + $response + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function New-NsxtLoadBalancer + +Function New-NsxtLBServiceMonitor { + <# + .SYNOPSIS + Creates a Load Balancer Service Monitor + + .DESCRIPTION + The New-NsxtLBServiceMonitor cmdlet creates a Load Balancer Service Monitor + + .EXAMPLE + New-NsxtLBServiceMonitor -monitorName -json + This example creates a Load Balancer Serviec Monitor + #> + Param ( - [Parameter (Mandatory=$true)] - [String]$segmentName + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$monitorName, + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$json ) Try { - $uri = "https://$nsxtmanager/policy/api/v1/global-infra/segments/" - - $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders - $segmentObjectId = ($response.results | where-object {$_.display_name -eq $segmentName}).id + $uri = "https://$nsxtmanager/policy/api/v1/infra/lb-monitor-profiles/$($monitorName)" + $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -headers $nsxtHeaders -body $json + $response } Catch { Write-Error $_.Exception.Message } - Return $segmentObjectId } -Export-ModuleMember -Function Get-NsxtGlobalSegmentID +Export-ModuleMember -Function New-NsxtLBServiceMonitor + +Function New-NsxtLBAppProfile { + <# + .SYNOPSIS + Creates a Load Balancer Application Profile + + .DESCRIPTION + The New-NsxtLBAppProfile cmdlet creates a Load Balancer Application Profile + + .EXAMPLE + New-NsxtLBAppProfile -appProfileName -json + This example creates a Load Balancer Application Profile + #> -Function Add-CertToNsxCertificateStore { Param ( - [Parameter (Mandatory = $true)] [String]$certName + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$appProfileName, + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$json ) - + Try { - $pemFile = Get-ExternalFileName -title "Select the Certificate Chain PEM File for Clustered WSA (.pem)" -fileType "pem" -location "default" + $uri = "https://$nsxtmanager/policy/api/v1/infra/lb-app-profiles/$($appProfileName)" + $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -headers $nsxtHeaders -body $json + $response } Catch { Write-Error $_.Exception.Message } +} +Export-ModuleMember -Function New-NsxtLBAppProfile + +Function New-NsxtLBPersistenceAppProfile { + <# + .SYNOPSIS + Creates a Load Balancer Persistence Application Profile + + .DESCRIPTION + The New-NsxtLBPersistenceAppProfile cmdlet creates a Load Balancer Persistence Application Profile + + .EXAMPLE + New-NsxtLBPersistenceAppProfile -appProfileName -json + This example creates a Load Balancer Persistence Application Profile + #> + + Param ( + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$appProfileName, + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$json + ) + Try { - $keyFile = Get-ExternalFileName -title "Select the Key File for Clustered WSA (.key)" -fileType "key" -location "default" + $uri = "https://$nsxtmanager/policy/api/v1/infra/lb-persistence-profiles/$($appProfileName)" + $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -headers $nsxtHeaders -body $json + $response } Catch { Write-Error $_.Exception.Message } +} +Export-ModuleMember -Function New-NsxtLBPersistenceAppProfile + +Function New-NsxtLBPool { + <# + .SYNOPSIS + Creates a Load Balancer Pool - $certAlreadyImported = "" + .DESCRIPTION + The New-NsxtLBPool cmdlet creates a Load Balancer Pool - #check for existing certificate + .EXAMPLE + New-NsxtLBPool -poolName -json + This example creates a Load Balancer Pool + #> + + Param ( + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$poolName, + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$json + ) + Try { - $certAlreadyImported = Get-NsxtCertificate -certificateName $certName -ErrorAction SilentlyContinue + $uri = "https://$nsxtmanager/policy/api/v1/infra/lb-pools/$($poolName)" + $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -headers $nsxtHeaders -body $json + $response } Catch { - $certAlreadyImported = $false + Write-Error $_.Exception.Message } +} +Export-ModuleMember -Function New-NsxtLBPool + +Function New-NsxtLBVirtualServer { + <# + .SYNOPSIS + Creates a Load Balancer Virtual Server - # report on existing cert or install new cert - if ($certAlreadyImported) { - $wsaCertPresent = $true + .DESCRIPTION + The New-NsxtLBVirtualServer cmdlet creates a Load Balancer Virtual Server + + .EXAMPLE + New-NsxtLBVirtualServer -virtualServerName -json + This example creates a Load Balancer Virtual Server + #> + + Param ( + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$virtualServerName, + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$json + ) + + Try { + $uri = "https://$nsxtmanager/policy/api/v1/infra/lb-virtual-servers/$($virtualServerName)" + $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -headers $nsxtHeaders -body $json + $response } - else { - $pemContent = (Get-Content $pemFile) -join "\n" - $keyContent = (Get-Content $keyFile) -join "\n" - $body = - '{ - "pem_encoded": "", - "private_key": "" - } - ' - $body = $body | ForEach-Object { $_ ` - -replace '', $pemContent ` - -replace '', $keyContent ` - } - Try { - Set-NsxtCertificate -certificateName $certName -json $body - $wsaCertPresent = $true - } - Catch { - Debug-ExceptionWriter -object $_ - } + Catch { + Write-Error $_.Exception.Message } - Return $wsaCertPresent } -Export-ModuleMember -Function Add-CertToNsxCertificateStore +Export-ModuleMember -Function New-NsxtLBVirtualServer -Function Get-NsxtEdgeCluster { +Function Get-NsxtCertificate { <# .SYNOPSIS - Gets NSX-T Edge Cluster Id + Gets NSX-T Certificates .DESCRIPTION - The Get-NsxtEdgeCluster cmdlet gets the Edge Cluster Id + The Get-NsxtCertificates cmdlet gets certificates installed in NSX-T .EXAMPLE - Get-NsxtEdgeCluster - This example creates a new Route Map on a Tier 0 Gateway + PS C:\> Get-NsxtCertificates + This example gets the certificates installed in NSX-T #> + Param ( + [Parameter (Mandatory=$false)] [ValidateNotNullOrEmpty()] [String]$certificateName + ) + Try { - $uri = "https://$nsxtmanager/api/v1/edge-clusters" - $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders - $response.results + if (!$PsBoundParameters.ContainsKey("certificateName")) { + $uri = "https://$nsxtmanager/policy/api/v1/infra/certificates" + $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders + $response.results + } + elseif ($PsBoundParameters.ContainsKey("certificateName")) { + $uri = "https://$nsxtmanager/policy/api/v1/infra/certificates/$($certificateName)" + $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders + $response + } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-NsxtEdgeCluster +Export-ModuleMember -Function Get-NsxtCertificate -Function New-NsxtTier1 { +Function Set-NsxtCertificate +{ <# .SYNOPSIS - Creates a Tier 1 Gateway + Installs a Certificate in NSX-T .DESCRIPTION - The New-NsxtTier1 cmdlet creates a Teir 1 Gateway + The Set-NsxtCertificates cmdlet installs certificates in NSX-T .EXAMPLE - New-NsxtTier1 -tier1Gateway sfo-w01-ec01-t0-lb01 -json $ConfigJson - This example creates a new Tier 1 Gateway + Set-NsxtCertificates + This example installs the certificates in NSX-T #> Param ( - [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$tier1Gateway, + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$certificateName, [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$json ) Try { - $uri = "https://$nsxtmanager/policy/api/v1/infra/tier-1s/$($tier1Gateway)" + $uri = "https://$nsxtmanager/policy/api/v1/infra/certificates/$($certificateName)" $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -headers $nsxtHeaders -body $json $response } @@ -15644,1534 +18267,1586 @@ Function New-NsxtTier1 { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function New-NsxtTier1 +Export-ModuleMember -Function Set-NsxtCertificate -Function Set-NsxtTier1 { +Function Get-NsxtNodeProfile { <# .SYNOPSIS - Configures Tier 1 Gateway - + Get the NSX node profiles. + .DESCRIPTION - The Set-NsxtTier1 cmdlet configures a Tier 1 Gateway - + The Get-NsxtNodeProfile cmdlet returns the node profiles from the NSX Manager + .EXAMPLE - Set-NsxtTier1 -tier1Gateway -json - This example sets the configuration on a Tier 1 Gateway + Get-NsxtNodeProfile + This example returns all the node profiles from the NSX Manager. + + .EXAMPLE + Get-NsxtNodeProfile -id $id + This example returns the node profiles from the NSX Manager using the id. #> Param ( - [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$tier1Gateway, - [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$json + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id ) Try { - $uri = "https://$nsxtmanager/policy/api/v1/infra/tier-1s/$($tier1Gateway)/locale-services/default" - $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -headers $nsxtHeaders -body $json - $response + + if ($PsBoundParameters.ContainsKey('id')) { + $uri = "https://$nsxtManager/api/v1/configs/central-config/node-config-profiles/$id" + $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $nsxtHeaders + $response + } + else { + $uri = "https://$nsxtManager/api/v1/configs/central-config/node-config-profiles/" + $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $nsxtHeaders + $response.results + } } Catch { Write-Error $_.Exception.Message } + } -Export-ModuleMember -Function Set-NsxtTier1 +Export-ModuleMember -Function Get-NsxtNodeProfile -Function New-NsxtTier1ServiceInterface { - <# +Function Set-NsxtNodeProfileSyslogExporter { + <# .SYNOPSIS - Creates Service Interface on Tier 1 Gateway - + Sets a node profile syslog exporter. + .DESCRIPTION - The New-NsxtTier1ServiceInterface cmdlet configures a Service Interface on Tier 1 Gateway - + The Set-NsxtNodeProfileSyslogExporter cmdlet adds a syslog exporter to an NSX node profie for configuration + of NSX components included in the node profile. + .EXAMPLE - New-NsxtTier1ServiceInterface -tier1Gateway -interfaceId -json - This example configures a Service Interface on a Tier 1 Gateway + Set-NsxtNodeProfileSyslogExporter -id "00000000-0000-0000-0000-000000000001" -server "sfo-vrli01.sfo.rainpole.io" -port 514 -protocol TCP -logLevel INFO + This example add a single syslog exporter to the NSX node profile the id of the profile. + + Note: This function only supports a single syslog exporter. #> Param ( - [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$tier1Gateway, - [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$interfaceId, - [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$json + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [int]$port, + [Parameter (Mandatory = $true)] [ValidateSet('TCP', 'UDP', 'LI')] [ValidateNotNullOrEmpty()] [String]$protocol, + [Parameter (Mandatory = $true)] [ValidateSet('EMERG', 'ALERT', 'CRIT', 'ERR', 'WARNING', 'NOTICE', 'INFO', 'DEBUG')] [ValidateNotNullOrEmpty()] [String]$logLevel ) Try { - $uri = "https://$nsxtmanager/policy/api/v1/infra/tier-1s/$($tier1Gateway)/locale-services/default/interfaces/$($interfaceId)" - $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -headers $nsxtHeaders -body $json - $response + $revision = (Get-NsxtNodeProfile -id $id)._revision + $body = '{ + "syslog" : { + "exporters" : [ { + "server" : "' + $server + '", + "port" : ' + $port + ', + "protocol" : "' + $protocol + '", + "max_log_level" : "' + $logLevel + '" + } ] + }, + "_revision" : ' + $revision + ' + }' + $uri = "https://$nsxtManager/api/v1/configs/central-config/node-config-profiles/$id" + $response = Invoke-RestMethod -Method 'PUT' -Uri $uri -Headers $nsxtHeaders -Body $body + $response.results } Catch { Write-Error $_.Exception.Message } + } -Export-ModuleMember -Function New-NsxtTier1ServiceInterface +Export-ModuleMember -Function Set-NsxtNodeProfileSyslogExporter -Function New-NsxtTier1StaticRoute { +Function Remove-NsxtNodeProfileSyslogExporter { <# .SYNOPSIS - Creates Static Route on Tier 1 Gateway - + Removes all node profile syslog exporters. + .DESCRIPTION - The New-New-NsxtTier1StaticRoute cmdlet creates a static route on Tier 1 Gateway - + The Remove-NsxtNodeProfileSyslogExporter cmdlet removes all syslog exporters from an NSX node profie for configuration + of NSX components included in the node profile. + .EXAMPLE - New-NsxtTier1StaticRoute -tier1Gateway -segment -json - This example configures a Service Interface on a Tier 1 Gateway + Remove-NsxtNodeProfileSyslogExporter -id "00000000-0000-0000-0000-000000000001" + This example add a single syslog exporter to the NSX node profile the id of the profile. #> Param ( - [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$tier1Gateway, - [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$segment, - [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$json + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id ) Try { - $uri = "https://$nsxtmanager/policy/api/v1/infra/tier-1s/$($tier1Gateway)/static-routes/$($segment)" - $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -headers $nsxtHeaders -body $json - $response + $revision = (Get-NsxtNodeProfile -id $id)._revision + $body = '{ + "syslog" : { + "exporters" : [] + }, + "_revision" : ' + $revision + ' + }' + $uri = "https://$nsxtManager/api/v1/configs/central-config/node-config-profiles/$id" + $response = Invoke-RestMethod -Method 'PUT' -Uri $uri -Headers $nsxtHeaders -Body $body + $response.results } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function New-NsxtTier1StaticRoute +Export-ModuleMember -Function Remove-NsxtNodeProfileSyslogExporter -Function New-NsxtLoadBalancer { +################## End NSX-T Functions ####################### +############################################################### + + +############################################################### +############ Begin vSphere with Tanzu Functions ############## + +Function Enable-WMRegistry { <# .SYNOPSIS - Creates a Load Balancer - + Enable the embedded Harbor Registry on a Supervisor Cluster + .DESCRIPTION - The New-NsxtLoadBalancer cmdlet creates a load balancer - + The Enable-WMRegistry cmdlet enables the embedded Harbor Registry on a Supervisor Cluster + .EXAMPLE - New-NsxtLoadBalancer -lbName -json - This example creates a load balancer + Enable-WMRegistry -cluster sfo-w01-cl01 -ctoragePolicy vsphere-with-tanzu-policy + This example enables the embedded Harbor Registry on Supervisor Cluster sfo-w01-cl01 + + .EXAMPLE + Get-WMCluster -cluster sfo-w01-cl01 | Enable-WMRegistry + This example enables the embedded Harbor Registry on Supervisor Cluster sfo-w01-cl01 via pipeline from Get-WMCluster with the default image storage policy for the Supervisor Cluster #> Param ( - [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$lbName, - [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$json + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$domain, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$cluster, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$storagePolicy, + [Parameter (ValueFromPipeline, Mandatory = $false)] [psObject]$inputObject ) + if ($inputObject) { + $cluster = $inputObject.Name + } + Try { - $uri = "https://$nsxtmanager/policy/api/v1/infra/lb-services/$($lbName)" - $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -headers $nsxtHeaders -body $json - $response + if ($vCenterApi -le 701) { + $getHarborInstalled = (Invoke-RestMethod -Method GET -URI https://$vcApiServer/rest/vcenter/content/registries/harbor -Headers $vcApiHeaders).value + } + elseif ($vCenterApi -ge 702) { + $getHarborInstalled = Invoke-RestMethod -Method GET -URI https://$vcApiServer/api/vcenter/content/registries/harbor -Headers $vcApiHeaders + } } Catch { - Write-Error $_.Exception.Message + Write-Error = $_.Exception + } + + if (!$getHarborInstalled) { + Try { + $wmClusterId = (Invoke-RestMethod -Method GET -URI https://$vcApiServer/api/vcenter/namespace-management/clusters -Headers $vcApiHeaders | Where-Object { $_.cluster_name -eq $Cluster }).cluster + } + Catch { + Write-Error $_.Exception.Message + } + + if (!$StoragePolicy) { + Try { + $storagePolicyId = (Invoke-RestMethod -Method GET -URI https://$vcApiServer/api/vcenter/namespace-management/clusters/$wmClusterId -Headers $vcApiHeaders).image_storage.storage_policy + } + Catch { + Write-Error $_.Exception.Message + } + } + elseif ($StoragePolicy) { + Try { + if ($vCenterApi -ge 702) { + $storagePolicyId = ((Invoke-WebRequest -Method GET -URI https://$vcApiServer/api/vcenter/storage/policies -Headers $vcApiHeaders -UseBasicParsing | ConvertFrom-Json) | Where-Object { $_.name -eq $StoragePolicy }).policy + $json = @" +{ + "cluster" : "$wmClusterId", + "storage" : + [ + { + "policy" : "$storagePolicyId" + } + ] +} +"@ + } + elseif ($vCenterApi -le 701) { + $storagePolicyId = ((Invoke-WebRequest -Method GET -URI https://$vcApiServer/rest/vcenter/storage/policies -Headers $vcApiHeaders -UseBasicParsing | ConvertFrom-Json).value | Where-Object { $_.name -eq $StoragePolicy }).policy + $json = @" +{ + "spec" : + { + "cluster" : "$wmClusterId", + "storage" : + [ + { + "policy" : "$storagePolicyId" + } + ] } } -Export-ModuleMember -Function New-NsxtLoadBalancer +"@ + } + } + Catch { + Write-Error $_.Exception.Message + } + } + } + # Send a REST API call to vCenter Server to instantiate the new Harbor registry + if ($vCenterApi -le 701) { + Try { + $installHarbor = Invoke-RestMethod -Method POST -URI https://$vcApiServer/rest/vcenter/content/registries/harbor -Headers $vcApiHeaders -Body $json -ContentType application/json + } + Catch { + Write-Error $_.Exception.Message + } -Function New-NsxtLBServiceMonitor { + if ($installHarbor) { + $installHarborValue = $installHarbor.value + Write-Output "Embedded registry $installHarborValue deployment successfully started on Supervisor Cluster $cluster" + } + } + elseif ($vCenterApi -ge 702) { + Try { + $installHarbor = Invoke-RestMethod -Method POST -URI https://$vcApiServer/api/vcenter/content/registries/harbor -Headers $vcApiHeaders -Body $json -ContentType application/json + } + Catch { + Write-Error $_.Exception.Message + } + + if ($installHarbor) { + Write-Output "Embedded registry $installHarbor deployment successfully started on Supervisor Cluster $cluster" + } + } +} +Export-ModuleMember -Function Enable-WMRegistry + +Function Get-WMRegistry { <# .SYNOPSIS - Creates a Load Balancer Service Monitor - + Retrieves the embedded Harbor Registry on a Supervisor Cluster + .DESCRIPTION - The New-NsxtLBServiceMonitor cmdlet creates a Load Balancer Service Monitor - + The Get-WMRegistry cmdlet retrieves the embedded Harbor Registry on a Supervisor Cluster + .EXAMPLE - New-NsxtLBServiceMonitor -monitorName -json - This example creates a Load Balancer Serviec Monitor + Get-WMRegistry + This example retrieves all embedded Harbor Registries in vCenter Server inventory + + .EXAMPLE + Get-WMRegistry -Cluster sfo-w01-cl01 + This example enables the embedded Harbor Registry on Supervisor Cluster "sfo-w01-cl01" + + .EXAMPLE + Get-WMCluster -Cluster sfo-w01-cl01 | Get-WMRegistry + This example enables the embedded Harbor Registry on Supervisor Cluster "sfo-w01-cl01" via pipeline from Get-WMCluster #> Param ( - [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$monitorName, - [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$json + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$cluster, + [Parameter (ValueFromPipeline, Mandatory = $false)] [ValidateNotNullOrEmpty()] [psObject]$inputObject ) + if ($inputObject) { + $cluster = $inputObject.Name + } + + if ($Cluster) { + Try { + $wmClusterId = (Invoke-RestMethod -Method GET -URI https://$vcApiServer/api/vcenter/namespace-management/clusters -Headers $vcApiHeaders | Where-Object { $_.cluster_name -eq $Cluster }).cluster + } + Catch { + Write-Error $_.Exception.Message + } + } + Try { - $uri = "https://$nsxtmanager/policy/api/v1/infra/lb-monitor-profiles/$($monitorName)" - $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -headers $nsxtHeaders -body $json - $response + if (!$PsBoundParameters.ContainsKey("Cluster")) { + if ($vCenterApi -le 701) { + $response = Invoke-RestMethod -Method GET -URI https://$vcApiServer/rest/vcenter/content/registries/harbor -ContentType application/json -headers $vcApiHeaders + $response.value + } + elseif ($vCenterApi -ge 702) { + $response = Invoke-RestMethod -Method GET -URI https://$vcApiServer/api/vcenter/content/registries/harbor -ContentType application/json -headers $vcApiHeaders + $response + } + } + elseif ($PsBoundParameters.ContainsKey("Cluster")) { + if ($vCenterApi -le 701) { + $response = Invoke-RestMethod -Method GET -URI https://$vcApiServer/rest/vcenter/content/registries/harbor -ContentType application/json -headers $vcApiHeaders + $response.value | Where-Object { $_.cluster -eq $wmClusterId } + } + elseif ($vCenterApi -ge 702) { + $response = Invoke-RestMethod -Method GET -URI https://$vcApiServer/api/vcenter/content/registries/harbor -ContentType application/json -headers $vcApiHeaders + $response | Where-Object { $_.cluster -eq $wmClusterId } + } + } } Catch { - Write-Error $_.Exception.Message + Write-Error = $_.Exception } } -Export-ModuleMember -Function New-NsxtLBServiceMonitor +Export-ModuleMember -Function Get-WMRegistry -Function New-NsxtLBAppProfile { +Function Remove-WMRegistry { <# .SYNOPSIS - Creates a Load Balancer Application Profile - + Disable the embedded Harbor Registry on a Supervisor Cluster + .DESCRIPTION - The New-NsxtLBAppProfile cmdlet creates a Load Balancer Application Profile - - .EXAMPLE - New-NsxtLBAppProfile -appProfileName -json - This example creates a Load Balancer Application Profile - #> + The Remove-WMRegistry cmdlet disables the embedded Harbor Registry on a Supervisor Cluster - Param ( - [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$appProfileName, - [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$json - ) - - Try { - $uri = "https://$nsxtmanager/policy/api/v1/infra/lb-app-profiles/$($appProfileName)" - $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -headers $nsxtHeaders -body $json - $response - } - Catch { - Write-Error $_.Exception.Message - } -} -Export-ModuleMember -Function New-NsxtLBAppProfile + .EXAMPLE + Get-WMRegistry -cluster sfo-w01-cl01 | Remove-WMRegistry + This example disables the embedded Harbor Registry on Supervisor Cluster sfo-w01-cl01 via pipeline from Get-WMCluster -Function New-NsxtLBPersistenceAppProfile { - <# - .SYNOPSIS - Creates a Load Balancer Persistence Application Profile - - .DESCRIPTION - The New-NsxtLBPersistenceAppProfile cmdlet creates a Load Balancer Persistence Application Profile - .EXAMPLE - New-NsxtLBPersistenceAppProfile -appProfileName -json - This example creates a Load Balancer Persistence Application Profile + Remove-WMRegistry -cluster sfo-w01-cl01 + This example disables the embedded Harbor Registry on Supervisor Cluster sfo-w01-cl01 #> Param ( - [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$appProfileName, - [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$json + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster, + [Parameter (ValueFromPipeline, Mandatory = $false)] [ValidateNotNullOrEmpty()] [psObject]$inputObject ) - + Try { - $uri = "https://$nsxtmanager/policy/api/v1/infra/lb-persistence-profiles/$($appProfileName)" - $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -headers $nsxtHeaders -body $json - $response + if ($inputObject) { + $harborRegistryId = $inputObject.registry + } + else { + $harborRegistryId = (Get-WMRegistry -cluster $cluster).registry + } + + if ($vCenterApi -le 701) { + $uri = "https://$vcApiServer/rest/vcenter/content/registries/harbor/$harborRegistryId" + } + elseif ($vCenterApi -ge 702) { + $uri = "https://$vcApiServer/api/vcenter/content/registries/harbor/$harborRegistryId" + } + $response = Invoke-WebRequest -Method DELETE -URI $uri -ContentType application/json -headers $vcApiHeaders -UseBasicParsing + if ($response.StatusCode -eq 200 -or $response.StatusCode -eq 204) { + Write-Output "Disable embedded Harbor Registry successfully started for Supervisor Cluster $cluster" + } } Catch { - Write-Error $_.Exception.Message + Write-Error = $_.Exception } } -Export-ModuleMember -Function New-NsxtLBPersistenceAppProfile +Export-ModuleMember -Function Remove-WMRegistry -Function New-NsxtLBPool { +Function Get-WMRegistryHealth { <# .SYNOPSIS - Creates a Load Balancer Pool - + Retrieves the embedded Harbor Registry Health + .DESCRIPTION - The New-NsxtLBPool cmdlet creates a Load Balancer Pool - + The Get-WMRegistry cmdlet retrieves the embedded Harbor Registry Health + .EXAMPLE - New-NsxtLBPool -poolName -json - This example creates a Load Balancer Pool + Get-WMRegistryHealth -registry + This example gets the health status of the embedded Harbor Registry + + .EXAMPLE + Get-WMRegistry -cluster sfo-w01-cl01 | Get-WMRegistryHealth + This example enables the embedded Harbor Registry on Supervisor Cluster sfo-w01-cl01 via pipeline from Get-WMCluster #> Param ( - [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$poolName, - [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$json + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$registry, + [Parameter (ValueFromPipeline, Mandatory = $false)] [ValidateNotNullOrEmpty()] [psObject]$inputObject ) Try { - $uri = "https://$nsxtmanager/policy/api/v1/infra/lb-pools/$($poolName)" - $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -headers $nsxtHeaders -body $json - $response + if ($inputObject) { + $registry = $inputObject.registry + } + $uri = "https://$vcApiServer/rest/vcenter/content/registries/$registry/health" + $response = Invoke-RestMethod -Method 'GET' -URI $uri -Headers $vcApiHeaders -ContentType application/json + $response.value.status } Catch { - Write-Error $_.Exception.Message + Write-Error = $_.Exception } } -Export-ModuleMember -Function New-NsxtLBPool +Export-ModuleMember -Function Get-WMRegistryHealth -Function New-NsxtLBVirtualServer { +Function Connect-WMCluster { <# .SYNOPSIS - Creates a Load Balancer Virtual Server - + Connect to the Supervisor Cluster + .DESCRIPTION - The New-NsxtLBVirtualServer cmdlet creates a Load Balancer Virtual Server - + The Connect-WMCluster cmdlet connect to the Supervisor Cluster + .EXAMPLE - New-NsxtLBVirtualServer -virtualServerName -json - This example creates a Load Balancer Virtual Server + Connect-WMCluster -cluster sfo-w01-cl01 -user administrator@vsphere.local -pass VMw@re1! + This example connects with the vSphere SSO user administrator@vsphere.local to the Supervisor Cluster sfo-w01-cl01 #> Param ( - [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$virtualServerName, - [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$json - ) + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass + ) Try { - $uri = "https://$nsxtmanager/policy/api/v1/infra/lb-virtual-servers/$($virtualServerName)" - $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -headers $nsxtHeaders -body $json - $response + $server = (Get-WMCluster -Cluster $cluster).KubernetesHostname + $env:KUBECTL_VSPHERE_PASSWORD = $pass + Invoke-Expression "kubectl vsphere login --server $server --vsphere-username $user --insecure-skip-tls-verify" | Out-Null + if (Invoke-Expression "kubectl get nodes") { + Write-Output "Successfully connected to Supervisor Cluster: $server" + } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function New-NsxtLBVirtualServer +Export-ModuleMember -Function Connect-WMCluster -Function Get-NsxtCertificate { +Function Disconnect-WMCluster { <# .SYNOPSIS - Gets NSX-T Certificates - + Disconnect from o the Supervisor Cluster + .DESCRIPTION - The Get-NsxtCertificates cmdlet gets certificates installed in NSX-T - + The Disconnect-WMCluster cmdlet disconnects from the Supervisor Cluster + .EXAMPLE - PS C:\> Get-NsxtCertificates - This example gets the certificates installed in NSX-T + Disconnect-WMCluster + This example disconnects from the Supervisor Cluster #> - Param ( - [Parameter (Mandatory=$false)] [ValidateNotNullOrEmpty()] [String]$certificateName - ) - Try { - if (!$PsBoundParameters.ContainsKey("certificateName")) { - $uri = "https://$nsxtmanager/policy/api/v1/infra/certificates" - $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders - $response.results - } - elseif ($PsBoundParameters.ContainsKey("certificateName")) { - $uri = "https://$nsxtmanager/policy/api/v1/infra/certificates/$($certificateName)" - $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders - $response - } + Invoke-Expression "kubectl vsphere logout" | Out-Null + $env:KUBECTL_VSPHERE_PASSWORD = $null + Write-Output "Successfully disconnected from Supervisor Cluster" } Catch { - Write-Error $_.Exception.Message + Write-Error = $_.Exception } } -Export-ModuleMember -Function Get-NsxtCertificate +Export-ModuleMember -Function Disconnect-WMCluster -Function Set-NsxtCertificate -{ +Function New-TanzuKubernetesCluster { <# .SYNOPSIS - Installs a Certificate in NSX-T - + Adds a Tanzu Kubernetes Cluster based on the specified YAML file. + .DESCRIPTION - The Set-NsxtCertificates cmdlet installs certificates in NSX-T - + The New-TanzuKubernetesCluster cmdlet adds a Tanzu Kubernetes Cluster based on the specified YAML file. + .EXAMPLE - Set-NsxtCertificates - This example installs the certificates in NSX-T + New-TanzuKubernetesCluster -YAML .\SampleYaml\sfo-w01-tkc01-cluster.yaml + This example creates a Tanzu Kubernetes Cluster based on the yaml file #> Param ( - [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$certificateName, - [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$json + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$YAML ) Try { - $uri = "https://$nsxtmanager/policy/api/v1/infra/certificates/$($certificateName)" - $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -headers $nsxtHeaders -body $json - $response + Invoke-Expression "kubectl apply -f $YAML" } Catch { - Write-Error $_.Exception.Message + Write-Error = $_.Exception } } -Export-ModuleMember -Function Set-NsxtCertificate +Export-ModuleMember -Function New-TanzuKubernetesCluster -Function Get-NsxtNodeProfile { +Function Get-TanzuKubernetesCluster { <# .SYNOPSIS - Get the NSX node profiles. + Retrieves a Tanzu Kubernetes Cluster .DESCRIPTION - The Get-NsxtNodeProfile cmdlet returns the node profiles from the NSX Manager + The Get-TanzuKuberntesCluster cmdlet retrieves a Tanzu Kubernetes Cluster .EXAMPLE - Get-NsxtNodeProfile - This example returns all the node profiles from the NSX Manager. + Get-TanzuKubernetesCluster + This example retrieves all Tanzu Kubernetes Clusters from all Namespaces .EXAMPLE - Get-NsxtNodeProfile -id $id - This example returns the node profiles from the NSX Manager using the id. + Get-TanzuKubernetesCluster -namespace sfo-w01-tkc01 -tkc sfo-w01-tkc01 + This example retrieves a Tanzu Kubernetes Cluster named "sfo-w01-tkc01" from the Namespace specified "sfo-w01-tkc01" #> Param ( - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$namespace, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$tkc, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$detail ) Try { - - if ($PsBoundParameters.ContainsKey('id')) { - $uri = "https://$nsxtManager/api/v1/configs/central-config/node-config-profiles/$id" - $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $nsxtHeaders - $response + if ($PsBoundParameters.ContainsKey("detail")) { + if (!$tkc -and !$namespace) { + Invoke-Expression "kubectl describe tkc --all-namespaces" + } + elseif (!$tkc -and $namespace) { + Invoke-Expression "kubectl describe tkc -n $namespace" + } + elseif ($tkc -and !$namespace) { + Write-Error "A resource cannot be retrieved by tkc name across all namespaces" + } + elseif ($tkc -and $namespace) { + Invoke-Expression "kubectl describe tkc $tkc -n $namespace" + } } else { - $uri = "https://$nsxtManager/api/v1/configs/central-config/node-config-profiles/" - $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $nsxtHeaders - $response.results + if (!$tkc -and !$namespace) { + Invoke-Expression "kubectl get tkc --all-namespaces" + } + elseif (!$tkc -and $namespace) { + Invoke-Expression "kubectl get tkc -n $namespace" + } + elseif ($tkc -and !$namespace) { + Write-Error "A resource cannot be retrieved by name across all namespaces" + } + elseif ($tkc -and $namespace) { + Invoke-Expression "kubectl get tkc $tkc -n $namespace" + } } } Catch { - Write-Error $_.Exception.Message + Write-Error = $_.Exception } - } -Export-ModuleMember -Function Get-NsxtNodeProfile +Export-ModuleMember -Function Get-TanzuKubernetesCluster -Function Set-NsxtNodeProfileSyslogExporter { +Function Remove-TanzuKubernetesCluster { <# .SYNOPSIS - Sets a node profile syslog exporter. + Remove a Tanzu Kubernetes cluster .DESCRIPTION - The Set-NsxtNodeProfileSyslogExporter cmdlet adds a syslog exporter to an NSX node profie for configuration - of NSX components included in the node profile. + The Remove-TanzuKubernetesCluster cmdlet removes a Tanzu Kubernetes cluster .EXAMPLE - Set-NsxtNodeProfileSyslogExporter -id "00000000-0000-0000-0000-000000000001" -server "sfo-vrli01.sfo.rainpole.io" -port 514 -protocol TCP -logLevel INFO - This example add a single syslog exporter to the NSX node profile the id of the profile. - - Note: This function only supports a single syslog exporter. + Remove-TanzuKubernetesCluster -cluster sfo-w01-tkc01 -namespace sfo-w01-tkc01 + This example removes the Tanzu Kubernetes cluster #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [int]$port, - [Parameter (Mandatory = $true)] [ValidateSet('TCP', 'UDP', 'LI')] [ValidateNotNullOrEmpty()] [String]$protocol, - [Parameter (Mandatory = $true)] [ValidateSet('EMERG', 'ALERT', 'CRIT', 'ERR', 'WARNING', 'NOTICE', 'INFO', 'DEBUG')] [ValidateNotNullOrEmpty()] [String]$logLevel + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$namespace ) Try { - $revision = (Get-NsxtNodeProfile -id $id)._revision - $body = '{ - "syslog" : { - "exporters" : [ { - "server" : "' + $server + '", - "port" : ' + $port + ', - "protocol" : "' + $protocol + '", - "max_log_level" : "' + $logLevel + '" - } ] - }, - "_revision" : ' + $revision + ' - }' - $uri = "https://$nsxtManager/api/v1/configs/central-config/node-config-profiles/$id" - $response = Invoke-RestMethod -Method 'PUT' -Uri $uri -Headers $nsxtHeaders -Body $body - $response.results + Invoke-Expression "kubectl delete tkc $cluster -n $namespace" } Catch { Write-Error $_.Exception.Message } - } -Export-ModuleMember -Function Set-NsxtNodeProfileSyslogExporter +Export-ModuleMember -Function Remove-TanzuKubernetesCluster -Function Remove-NsxtNodeProfileSyslogExporter { +Function Get-VMClass { <# .SYNOPSIS - Removes all node profile syslog exporters. + Retrieves information on a Virtual Machine class .DESCRIPTION - The Remove-NsxtNodeProfileSyslogExporter cmdlet removes all syslog exporters from an NSX node profie for configuration - of NSX components included in the node profile. + The Get-VMClass cmdlet retrieves information on a Virtual Machine class .EXAMPLE - Remove-NsxtNodeProfileSyslogExporter -id "00000000-0000-0000-0000-000000000001" - This example add a single syslog exporter to the NSX node profile the id of the profile. + Get-VMClass + This example retrieves all Virtual Machine classes + + .EXAMPLE + Get-VMClass -vmClass guaranteed-small + This example retrieves information on the Virtual Machine Class guaranteed-small + + .EXAMPLE + Get-VMClass -namespace sfo-w01-tkc01 + This example retrieves Virtual Machine Classes assigned to the namespace sfo-w01-tkc01 #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id + [Parameter (Mandatory = $false)] [ValidateSet("guaranteed-medium","guaranteed-large","guaranteed-xlarge","best-effort-4xlarge","guaranteed-small","best-effort-medium","best-effort-2xlarge","guaranteed-2xlarge","best-effort-large","guaranteed-4xlarge","best-effort-8xlarge","best-effort-xsmall","guaranteed-xsmall","best-effort-xlarge","guaranteed-8xlarge","best-effort-small")] [String]$vmClass, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$namespace ) Try { - $revision = (Get-NsxtNodeProfile -id $id)._revision - $body = '{ - "syslog" : { - "exporters" : [] - }, - "_revision" : ' + $revision + ' - }' - $uri = "https://$nsxtManager/api/v1/configs/central-config/node-config-profiles/$id" - $response = Invoke-RestMethod -Method 'PUT' -Uri $uri -Headers $nsxtHeaders -Body $body - $response.results + if ($PsBoundParameters.ContainsKey("name")) { + $uri = "https://$vcApiServer/api/vcenter/namespace-management/virtual-machine-classes/$vmClass" + $response = Invoke-RestMethod -Method 'GET' -URI $uri -Headers $vcApiHeaders + $response + } + elseif ($PsBoundParameters.ContainsKey("namespace")) { + $uri = "https://$vcApiServer/api/vcenter/namespaces/instances/$namespace" + $response = Invoke-RestMethod -Method 'GET' -URI $uri -Headers $vcApiHeaders + $response.vm_service_spec.vm_classes + } + else { + $uri = " https://$vcApiServer/api/vcenter/namespace-management/virtual-machine-classes" + $response = Invoke-RestMethod -Method 'GET' -URI $uri -Headers $vcApiHeaders + $response + } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Remove-NsxtNodeProfileSyslogExporter - -################## End NSX-T Functions ####################### -############################################################### - - -############################################################### -############ Begin vSphere with Tanzu Functions ############## +Export-ModuleMember -Function Get-VMClass -Function Enable-WMRegistry { +Function Add-VMClass { <# .SYNOPSIS - Enable the embedded Harbor Registry on a Supervisor Cluster + Retrieves information on a Virtual Machine class .DESCRIPTION - The Enable-WMRegistry cmdlet enables the embedded Harbor Registry on a Supervisor Cluster - - .EXAMPLE - Enable-WMRegistry -cluster sfo-w01-cl01 -ctoragePolicy vsphere-with-tanzu-policy - This example enables the embedded Harbor Registry on Supervisor Cluster sfo-w01-cl01 + The Add-VMClass cmdlet retrieves information on a Virtual Machine class .EXAMPLE - Get-WMCluster -cluster sfo-w01-cl01 | Enable-WMRegistry - This example enables the embedded Harbor Registry on Supervisor Cluster sfo-w01-cl01 via pipeline from Get-WMCluster with the default image storage policy for the Supervisor Cluster + Add-VMClass -namespace sfo-w01-tkc01 -vmClass guaranteed-small + This example retrieves all Virtual Machine classes #> Param ( - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$domain, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$cluster, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$storagePolicy, - [Parameter (ValueFromPipeline, Mandatory = $false)] [psObject]$inputObject + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$namespace, + [Parameter (Mandatory = $false)] [ValidateSet("guaranteed-medium","guaranteed-large","guaranteed-xlarge","best-effort-4xlarge","guaranteed-small","best-effort-medium","best-effort-2xlarge","guaranteed-2xlarge","best-effort-large","guaranteed-4xlarge","best-effort-8xlarge","best-effort-xsmall","guaranteed-xsmall","best-effort-xlarge","guaranteed-8xlarge","best-effort-small")] [String]$vmClass ) - if ($inputObject) { - $cluster = $inputObject.Name - } - Try { - if ($vCenterApi -le 701) { - $getHarborInstalled = (Invoke-RestMethod -Method GET -URI https://$vcApiServer/rest/vcenter/content/registries/harbor -Headers $vcApiHeaders).value - } - elseif ($vCenterApi -ge 702) { - $getHarborInstalled = Invoke-RestMethod -Method GET -URI https://$vcApiServer/api/vcenter/content/registries/harbor -Headers $vcApiHeaders - } - } - Catch { - Write-Error = $_.Exception - } + $existingVmClass = Get-VMClass -namespace $namespace -ErrorAction Ignore + if ($existingVmClass) { + $newVmClass = New-Object System.Collections.Generic.List[System.Object] + foreach ($assignedVMclass in $existingVmClass) { + if (!($assignedVMclass -eq $vmClass)) { + $newVmClass += $assignedVMclass + } + } + $newVmClass += $vmClass + $jsonFormat = ConvertTo-Json $newVmClass - if (!$getHarborInstalled) { - Try { - $wmClusterId = (Invoke-RestMethod -Method GET -URI https://$vcApiServer/api/vcenter/namespace-management/clusters -Headers $vcApiHeaders | Where-Object { $_.cluster_name -eq $Cluster }).cluster + $body = '{"vm_service_spec": { "vm_classes": '+ $jsonFormat +'}}' } - Catch { - Write-Error $_.Exception.Message + else { + $body = '{ "vm_service_spec": { "vm_classes": [ "' + $vmClass + '" ] }}' } - if (!$StoragePolicy) { - Try { - $storagePolicyId = (Invoke-RestMethod -Method GET -URI https://$vcApiServer/api/vcenter/namespace-management/clusters/$wmClusterId -Headers $vcApiHeaders).image_storage.storage_policy - } - Catch { - Write-Error $_.Exception.Message - } - } - elseif ($StoragePolicy) { - Try { - if ($vCenterApi -ge 702) { - $storagePolicyId = ((Invoke-WebRequest -Method GET -URI https://$vcApiServer/api/vcenter/storage/policies -Headers $vcApiHeaders -UseBasicParsing | ConvertFrom-Json) | Where-Object { $_.name -eq $StoragePolicy }).policy - $json = @" -{ - "cluster" : "$wmClusterId", - "storage" : - [ - { - "policy" : "$storagePolicyId" - } - ] -} -"@ - } - elseif ($vCenterApi -le 701) { - $storagePolicyId = ((Invoke-WebRequest -Method GET -URI https://$vcApiServer/rest/vcenter/storage/policies -Headers $vcApiHeaders -UseBasicParsing | ConvertFrom-Json).value | Where-Object { $_.name -eq $StoragePolicy }).policy - $json = @" -{ - "spec" : - { - "cluster" : "$wmClusterId", - "storage" : - [ - { - "policy" : "$storagePolicyId" - } - ] + $uri = "https://$vcApiServer/api/vcenter/namespaces/instances/$namespace" + $response = Invoke-RestMethod -Method 'PATCH' -Uri $uri -Headers $vcApiHeaders -body $body + $response } -} -"@ - } - } - Catch { - Write-Error $_.Exception.Message - } - } + Catch { + Write-Error $_.Exception.Message } - # Send a REST API call to vCenter Server to instantiate the new Harbor registry - if ($vCenterApi -le 701) { - Try { - $installHarbor = Invoke-RestMethod -Method POST -URI https://$vcApiServer/rest/vcenter/content/registries/harbor -Headers $vcApiHeaders -Body $json -ContentType application/json - } - Catch { - Write-Error $_.Exception.Message - } - - if ($installHarbor) { - $installHarborValue = $installHarbor.value - Write-Output "Embedded registry $installHarborValue deployment successfully started on Supervisor Cluster $cluster" - } - } - elseif ($vCenterApi -ge 702) { - Try { - $installHarbor = Invoke-RestMethod -Method POST -URI https://$vcApiServer/api/vcenter/content/registries/harbor -Headers $vcApiHeaders -Body $json -ContentType application/json - } - Catch { - Write-Error $_.Exception.Message - } - - if ($installHarbor) { - Write-Output "Embedded registry $installHarbor deployment successfully started on Supervisor Cluster $cluster" - } - } } -Export-ModuleMember -Function Enable-WMRegistry +Export-ModuleMember -Function Add-VMClass -Function Get-WMRegistry { +Function Get-WMLicenseStatus { <# .SYNOPSIS - Retrieves the embedded Harbor Registry on a Supervisor Cluster + Get Workload Management license status .DESCRIPTION - The Get-WMRegistry cmdlet retrieves the embedded Harbor Registry on a Supervisor Cluster + The Get-WMLicenseStatus cmdlet gets the license status from vCenter Server for Workload Management .EXAMPLE - Get-WMRegistry - This example retrieves all embedded Harbor Registries in vCenter Server inventory + Get-WMLicenseStatus + This example gets the vSphere with Tanzu licenses status from vCenter Server for Workload Management + #> + + # Param ( + # [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + # [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain + # ) + + Try { + $uri = "https://$vcApiServer/api/vcenter/namespace-management/capability" + $response = Invoke-RestMethod -Method GET -Uri $uri -Headers $vcApiHeaders + $response + + } + Catch { + Debug-ExceptionWriter -object $_ + } +} +Export-ModuleMember -Function Get-WMLicenseStatus - .EXAMPLE - Get-WMRegistry -Cluster sfo-w01-cl01 - This example enables the embedded Harbor Registry on Supervisor Cluster "sfo-w01-cl01" +Function Request-WMClusterCSR { + <# + .SYNOPSIS + Request Certificate Signing Request filr + .DESCRIPTION + The Request-WMClusterCSR cmdlet requests a Certificate Signing Request file for the Supervisor Cluster .EXAMPLE - Get-WMCluster -Cluster sfo-w01-cl01 | Get-WMRegistry - This example enables the embedded Harbor Registry on Supervisor Cluster "sfo-w01-cl01" via pipeline from Get-WMCluster + Request-WMClusterCSR -cluster sfo-w01-cl01 -commonName sfo-w01-cl01.sfo.rainpole.io -organization Rainpole -organizationalUnit Rainpole -country US -stateOrProvince California -locality "Palo Alto" -adminEmailAddress admin@rainpole.io -keySize 2048 -filePath ".\SupervisorCluster.csr" + This example requetes a Certificate Signing Request file for the Supervisor Cluster sfo-w01-cl01 #> Param ( - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$cluster, - [Parameter (ValueFromPipeline, Mandatory = $false)] [ValidateNotNullOrEmpty()] [psObject]$inputObject + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$commonName, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$organization, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$organizationalUnit, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$country, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$stateOrProvince, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$locality, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$adminEmailAddress, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$keySize, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$filePath ) - if ($inputObject) { - $cluster = $inputObject.Name - } - - if ($Cluster) { - Try { - $wmClusterId = (Invoke-RestMethod -Method GET -URI https://$vcApiServer/api/vcenter/namespace-management/clusters -Headers $vcApiHeaders | Where-Object { $_.cluster_name -eq $Cluster }).cluster - } - Catch { - Write-Error $_.Exception.Message - } - } - Try { - if (!$PsBoundParameters.ContainsKey("Cluster")) { - if ($vCenterApi -le 701) { - $response = Invoke-RestMethod -Method GET -URI https://$vcApiServer/rest/vcenter/content/registries/harbor -ContentType application/json -headers $vcApiHeaders - $response.value - } - elseif ($vCenterApi -ge 702) { - $response = Invoke-RestMethod -Method GET -URI https://$vcApiServer/api/vcenter/content/registries/harbor -ContentType application/json -headers $vcApiHeaders - $response - } - } - elseif ($PsBoundParameters.ContainsKey("Cluster")) { - if ($vCenterApi -le 701) { - $response = Invoke-RestMethod -Method GET -URI https://$vcApiServer/rest/vcenter/content/registries/harbor -ContentType application/json -headers $vcApiHeaders - $response.value | Where-Object { $_.cluster -eq $wmClusterId } - } - elseif ($vCenterApi -ge 702) { - $response = Invoke-RestMethod -Method GET -URI https://$vcApiServer/api/vcenter/content/registries/harbor -ContentType application/json -headers $vcApiHeaders - $response | Where-Object { $_.cluster -eq $wmClusterId } - } + $uri = "https://$vcApiServer/api/vcenter/namespace-management/clusters" + $clusterId = (Invoke-RestMethod -Method GET -URI $uri -Headers $vcApiHeaders | Where-Object { $_.cluster_name -eq $cluster }).cluster + + $output = New-Object -TypeName PSCustomObject + $output | Add-Member -notepropertyname 'common_name' -notepropertyvalue $commonName + $output | Add-Member -notepropertyname 'organization_name' -notepropertyvalue $organization + $output | Add-Member -notepropertyname 'organization_unit_name' -notepropertyvalue $organizationalUnit + $output | Add-Member -notepropertyname 'country' -notepropertyvalue $country + $output | Add-Member -notepropertyname 'state_or_province' -notepropertyvalue $stateOrProvince + $output | Add-Member -notepropertyname 'locality' -notepropertyvalue $locality + $output | Add-Member -notepropertyname 'email_address' -notepropertyvalue $adminEmailAddress + if ($PsBoundParameters.ContainsKey("keySize")){ + $output | Add-Member -notepropertyname 'keySize' -notepropertyvalue $keySize } + $body = $output | ConvertTo-Json + $uri = "https://$vcApiServer/api/$clusterId/csr/tls-endpoint/" + $response = Invoke-RestMethod -Method POST -Uri $uri -Headers $vcApiHeaders -body $body + $response | Out-File -FilePath $filePath + Write-Output "Certificate Signing Request (.csr) file for ($commonName) has been successfully saved to file ($filePath)" } Catch { - Write-Error = $_.Exception + Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-WMRegistry +Export-ModuleMember -Function Request-WMClusterCSR -Function Remove-WMRegistry { +Function Install-WMClusterCertificate { <# .SYNOPSIS - Disable the embedded Harbor Registry on a Supervisor Cluster + Installs a signed TLS certificate for the defined Supervisor Cluster .DESCRIPTION - The Remove-WMRegistry cmdlet disables the embedded Harbor Registry on a Supervisor Cluster - - .EXAMPLE - Get-WMRegistry -cluster sfo-w01-cl01 | Remove-WMRegistry - This example disables the embedded Harbor Registry on Supervisor Cluster sfo-w01-cl01 via pipeline from Get-WMCluster + The Install-WMClusterCertificate cmdlet installs a signed TLS certificate for the defined Supervisor Cluster .EXAMPLE - Remove-WMRegistry -cluster sfo-w01-cl01 - This example disables the embedded Harbor Registry on Supervisor Cluster sfo-w01-cl01 + Install-WMClusterCertificate -cluster sfo-w01-cl01 -filePath ".\SupervisorCluster.cer" + This example installs the signed TLS certificate to Supervisor Cluster sfo-w01-cl01 in Workload domain sfo-w01 #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster, - [Parameter (ValueFromPipeline, Mandatory = $false)] [ValidateNotNullOrEmpty()] [psObject]$inputObject + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$filePath ) Try { - if ($inputObject) { - $harborRegistryId = $inputObject.registry + if ($PsBoundParameters.ContainsKey("filepath")) { + if (!(Test-Path $filepath)) { + Throw "Certificate File Not Found" + } + else { + $certificate = Get-Content -Path $filePath -Raw -ErrorAction SilentlyContinue + $inputFileName = Split-Path -Path $filePath -Leaf -ErrorAction SilentlyContinue + } + } + if ($isMacOS -eq $true -or $isLinux -eq $true) { + $certificateFormatted = $Certificate -Replace "`n","\n" + } + elseif ($isWindows -eq $true -or $PSEdition -eq "Desktop") { + $certificateFormatted = $Certificate -Replace "`r`n","\n" } else { - $harborRegistryId = (Get-WMRegistry -cluster $cluster).registry + Write-Error "Unsupported Operating System" + Break } - - if ($vCenterApi -le 701) { - $uri = "https://$vcApiServer/rest/vcenter/content/registries/harbor/$harborRegistryId" + if (($certificateFormatted | Measure-object -Line).Count -ne 1) { + Write-Error "Error parsing TLS certificate" + Break } - elseif ($vCenterApi -ge 702) { - $uri = "https://$vcApiServer/api/vcenter/content/registries/harbor/$harborRegistryId" + $body = '{ "tls_endpoint_certificate": "'+ $certificateFormatted +'" }' + $uri = "https://$vcApiServer/api/vcenter/namespace-management/clusters" + $clusterId = (Invoke-RestMethod -Method GET -URI $uri -Headers $vcApiHeaders | Where-Object { $_.cluster_name -eq $cluster }).cluster + $uri = "https://$vcApiServer/api/vcenter/namespace-management/clusters/$clusterId/" + if ($PSEdition -eq 'Core') { + $response = Invoke-WebRequest -Method PATCH -Uri $uri -Headers $vcApiHeaders -body $body -SkipCertificateCheck -UseBasicParsing # PS Core has -SkipCertificateCheck implemented } - $response = Invoke-WebRequest -Method DELETE -URI $uri -ContentType application/json -headers $vcApiHeaders -UseBasicParsing - if ($response.StatusCode -eq 200 -or $response.StatusCode -eq 204) { - Write-Output "Disable embedded Harbor Registry successfully started for Supervisor Cluster $cluster" + else { + $response = Invoke-WebRequest -Method PATCH -Uri $uri -Headers $vcApiHeaders -body $body -UseBasicParsing + } + if ($response.StatusCode -lt 300) { + if ($inputFileName) { + Write-Output "Signed Certificate ($inputFileName) has been successfully applied to Supervisor Cluster ($cluster)" + } + else { + Write-Output "Signed Certificate has been successfully applied to Supervisor Cluster ($cluster)" + } } } Catch { - Write-Error = $_.Exception + Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Remove-WMRegistry +Export-ModuleMember -Function Install-WMClusterCertificate -Function Get-WMRegistryHealth { +Function Watch-WmClusterConfigStatus { <# .SYNOPSIS - Retrieves the embedded Harbor Registry Health + Poll request .DESCRIPTION - The Get-WMRegistry cmdlet retrieves the embedded Harbor Registry Health + The Watch-WmClusterConfigStatus cmdlet polls the status of wmCluster .EXAMPLE - Get-WMRegistryHealth -registry - This example gets the health status of the embedded Harbor Registry - - .EXAMPLE - Get-WMRegistry -cluster sfo-w01-cl01 | Get-WMRegistryHealth - This example enables the embedded Harbor Registry on Supervisor Cluster sfo-w01-cl01 via pipeline from Get-WMCluster + Watch-WmClusterConfigStatus -wmClusterName + This example polls the status of wmCluster #> Param ( - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$registry, - [Parameter (ValueFromPipeline, Mandatory = $false)] [ValidateNotNullOrEmpty()] [psObject]$inputObject + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wmClusterName, + [Parameter (Mandatory = $false)] [int]$retriesCount = 10, + [Parameter (Mandatory = $false)] [int]$sleepTime = 30 ) + Try { - if ($inputObject) { - $registry = $inputObject.registry + $try = 1 + Do { + $wmCluster = (Get-WMCluster -Cluster $wmClusterName -ErrorAction SilentlyContinue) + Start-Sleep $sleepTime + $try++ + } + Until (($wmCluster.ConfigStatus -ne "Configuring") -or ($try -gt $retriesCount)) + if ($try -gt $retriesCount) { + Write-Error "Retries exeeded max count $retriesCount : CONFIGURATION_FAILED" + } + if ($wmCluster.ConfigStatus -ne "Running") { + Write-Error "Workload management on cluster: $wmClusterName status: $($wmCluster.ConfigStatus)" + write-Error "Workload management on cluster: $wmClusterName status messages: $($wmCluster.StatusMessages.Messages)" + } + else { + Write-Output "Workload Management on cluster: $wmClusterName completed with status: $($wmCluster.ConfigStatus)" } - $uri = "https://$vcApiServer/rest/vcenter/content/registries/$registry/health" - $response = Invoke-RestMethod -Method 'GET' -URI $uri -Headers $vcApiHeaders -ContentType application/json - $response.value.status } Catch { - Write-Error = $_.Exception + Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-WMRegistryHealth +Export-ModuleMember -Function Watch-WmClusterConfigStatus -Function Connect-WMCluster { +############# End vSphere with Tanzu Functions ############### +############################################################### + + +######################################################################################## +################## Start vRealize Suite Lifecycle Manager Functions ################### + +Function Request-vRSLCMToken { <# .SYNOPSIS - Connect to the Supervisor Cluster + Connects to the specified vRealize Suite Lifecycle Manager and obtains authorization token .DESCRIPTION - The Connect-WMCluster cmdlet connect to the Supervisor Cluster + The Request-vRSLCMToken cmdlet connects to the specified vRealize Suite Lifecycle Manager and + obtains an authorization token. It is required once per session before running all other cmdlets. .EXAMPLE - Connect-WMCluster -cluster sfo-w01-cl01 -user administrator@vsphere.local -pass VMw@re1! - This example connects with the vSphere SSO user administrator@vsphere.local to the Supervisor Cluster sfo-w01-cl01 + Request-vRSLCMToken -fqdn xreg-vrslcm.rainpole.io -username admin@local -password VMware1! + This example shows how to connect to the vRealize Suite Lifecycle Manager appliance #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$fqdn, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$username, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$password ) + if ( -not $PsBoundParameters.ContainsKey("username") -or ( -not $PsBoundParameters.ContainsKey("password"))) { + $creds = Get-Credential # Request Credentials + $username = $creds.UserName.ToString() + $password = $creds.GetNetworkCredential().password + } + + $Global:vrslcmHeaders = createBasicAuthHeader $username $password + $Global:vrslcmAppliance = $fqdn + Try { - $server = (Get-WMCluster -Cluster $cluster).KubernetesHostname - $env:KUBECTL_VSPHERE_PASSWORD = $pass - Invoke-Expression "kubectl vsphere login --server $server --vsphere-username $user --insecure-skip-tls-verify" | Out-Null - if (Invoke-Expression "kubectl get nodes") { - Write-Output "Successfully connected to Supervisor Cluster: $server" + # Validate credentials by executing an API call + $uri = "https://$vrslcmAppliance/lcmversion" + if ($PSEdition -eq 'Core') { + $vrslcmResponse = Invoke-WebRequest -Method GET -Uri $uri -Headers $vrslcmHeaders -SkipCertificateCheck -UseBasicParsing # PS Core has -SkipCertificateCheck implemented, PowerShell 5.x does not + } + else { + $vrslcmResponse = Invoke-WebRequest -Method GET -Uri $uri -Headers $vrslcmHeaders -UseBasicParsing + } + if ($vrslcmResponse.StatusCode -eq 200) { + Write-Output "Successfully connected to the vRealize Suite Lifecycle Manager Appliance: $vrslcmAppliance" } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Connect-WMCluster +Export-ModuleMember -Function Request-vRSLCMToken -Function Disconnect-WMCluster { +Function Get-vRSLCMHealth { <# .SYNOPSIS - Disconnect from o the Supervisor Cluster + Check vRealize Suite Lifecycle Manager Health Status .DESCRIPTION - The Disconnect-WMCluster cmdlet disconnects from the Supervisor Cluster + The Get-vRSLCMHealth cmdlet checks vRealize Suite Lifecycle Manager Health Status .EXAMPLE - Disconnect-WMCluster - This example disconnects from the Supervisor Cluster + Get-vRSLCMHealth + This example checks vRealize Suite Lifecycle Manager Health Status #> Try { - Invoke-Expression "kubectl vsphere logout" | Out-Null - $env:KUBECTL_VSPHERE_PASSWORD = $null - Write-Output "Successfully disconnected from Supervisor Cluster" + $uri = "https://$vrslcmAppliance/lcm/health/api/v2/status" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders + $response } Catch { - Write-Error = $_.Exception + Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Disconnect-WMCluster +Export-ModuleMember -Function Get-vRSLCMHealth -Function New-TanzuKubernetesCluster { +Function Get-vRSLCMLockerPassword { <# .SYNOPSIS - Adds a Tanzu Kubernetes Cluster based on the specified YAML file. + Get paginated list of Passwords available in the Store .DESCRIPTION - The New-TanzuKubernetesCluster cmdlet adds a Tanzu Kubernetes Cluster based on the specified YAML file. + The Get-vRSLCMLockerPassword cmdlet gets a paginated list of passwords available in the Locker + + .EXAMPLE + Get-vRSLCMLockerPassword + This example gets all passwords in the Locker + + .EXAMPLE + Get-vRSLCMLockerPassword -vmid 83abd0fd-c92d-4d8f-a5e8-9a1fc4fa6009 + This example gets the details of a password based on the vmid .EXAMPLE - New-TanzuKubernetesCluster -YAML .\SampleYaml\sfo-w01-tkc01-cluster.yaml - This example creates a Tanzu Kubernetes Cluster based on the yaml file + Get-vRSLCMLockerPassword -alias xint-env-admin + This example gets the details of a password based on the alias #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$YAML + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vmid, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$alias ) Try { - Invoke-Expression "kubectl apply -f $YAML" + if ($PsBoundParameters.ContainsKey("vmid")) { + $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/passwords/$vmid" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders + $response + } + elseif ($PsBoundParameters.ContainsKey("alias")){ + $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/passwords?aliasQuery=$alias" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders + $response.passwords + } + else { + $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/passwords?size=19" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders + $response.passwords + } } Catch { - Write-Error = $_.Exception + Write-Error $_.Exception.Message } } -Export-ModuleMember -Function New-TanzuKubernetesCluster +Export-ModuleMember -Function Get-vRSLCMLockerPassword -Function Get-TanzuKubernetesCluster { +Function Add-vRSLCMLockerPassword { <# .SYNOPSIS - Retrieves a Tanzu Kubernetes Cluster + Creates a new Password in a Locker .DESCRIPTION - The Get-TanzuKuberntesCluster cmdlet retrieves a Tanzu Kubernetes Cluster - - .EXAMPLE - Get-TanzuKubernetesCluster - This example retrieves all Tanzu Kubernetes Clusters from all Namespaces + The Add-vRSLCMLockerPassword cmdlet add as new passwords to the Locker .EXAMPLE - Get-TanzuKubernetesCluster -namespace sfo-w01-tkc01 -tkc sfo-w01-tkc01 - This example retrieves a Tanzu Kubernetes Cluster named "sfo-w01-tkc01" from the Namespace specified "sfo-w01-tkc01" + Add-vRSLCMLockerPassword -userName admin -alias xint-admin -password VMw@re1! -description "Password for Cross-Instance Admin" + This example adda a password to the locker #> Param ( - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$namespace, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$tkc, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$detail + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$userName, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$alias, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$password, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$description ) Try { - if ($PsBoundParameters.ContainsKey("detail")) { - if (!$tkc -and !$namespace) { - Invoke-Expression "kubectl describe tkc --all-namespaces" - } - elseif (!$tkc -and $namespace) { - Invoke-Expression "kubectl describe tkc -n $namespace" - } - elseif ($tkc -and !$namespace) { - Write-Error "A resource cannot be retrieved by tkc name across all namespaces" - } - elseif ($tkc -and $namespace) { - Invoke-Expression "kubectl describe tkc $tkc -n $namespace" - } + $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/passwords" + + if ($PsBoundParameters.ContainsKey("description")) { + $body = '{ + "alias": "'+ $alias +'", + "password": "'+ $password +'", + "passwordDescription": "'+ $description +'", + "userName": "'+ $userName +'" + }' } else { - if (!$tkc -and !$namespace) { - Invoke-Expression "kubectl get tkc --all-namespaces" - } - elseif (!$tkc -and $namespace) { - Invoke-Expression "kubectl get tkc -n $namespace" - } - elseif ($tkc -and !$namespace) { - Write-Error "A resource cannot be retrieved by name across all namespaces" - } - elseif ($tkc -and $namespace) { - Invoke-Expression "kubectl get tkc $tkc -n $namespace" - } + $body = '{ + "alias": "'+ $alias +'", + "password": "'+ $password +'", + "userName": "'+ $userName +'" + }' } + + $response = Invoke-RestMethod $uri -Method 'POST' -Headers $vrslcmHeaders -Body $body + $response } Catch { - Write-Error = $_.Exception + Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-TanzuKubernetesCluster +Export-ModuleMember -Function Add-vRSLCMLockerPassword -Function Remove-TanzuKubernetesCluster { +Function Remove-vRSLCMLockerPassword { <# .SYNOPSIS - Remove a Tanzu Kubernetes cluster + Delete a Password based on vmid .DESCRIPTION - The Remove-TanzuKubernetesCluster cmdlet removes a Tanzu Kubernetes cluster + The Remove-vRSLCMLockerPassword cmdlet deletes a password from the Locker .EXAMPLE - Remove-TanzuKubernetesCluster -cluster sfo-w01-tkc01 -namespace sfo-w01-tkc01 - This example removes the Tanzu Kubernetes cluster + Remove-vRSLCMLockerPassword -vmid + This example delets the password with the vmid #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$namespace + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vmid ) Try { - Invoke-Expression "kubectl delete tkc $cluster -n $namespace" + $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/passwords/$vmid" + $response = Invoke-RestMethod $uri -Method 'DELETE' -Headers $vrslcmHeaders + $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Remove-TanzuKubernetesCluster +Export-ModuleMember -Function Remove-vRSLCMLockerPassword -Function Get-VMClass { +Function Get-vRSLCMLockerCertificate { <# .SYNOPSIS - Retrieves information on a Virtual Machine class + Get paginated list of Certificates available in the Store .DESCRIPTION - The Get-VMClass cmdlet retrieves information on a Virtual Machine class + The Get-vRSLCMLockerCertificate cmdlet gets a paginated list of certificates available in the Locker .EXAMPLE - Get-VMClass - This example retrieves all Virtual Machine classes + Get-vRSLCMLockerCertificate + This example gets all certificates in the Locker .EXAMPLE - Get-VMClass -vmClass guaranteed-small - This example retrieves information on the Virtual Machine Class guaranteed-small + Get-vRSLCMLockerCertificate -vmid 83abd0fd-c92d-4d8f-a5e8-9a1fc4fa6009 + This example gets the details of a certificate based on the vmid .EXAMPLE - Get-VMClass -namespace sfo-w01-tkc01 - This example retrieves Virtual Machine Classes assigned to the namespace sfo-w01-tkc01 + Get-vRSLCMLockerCertificate -alias xint-vrops01 + This example gets the details of a certificate based on the vmid #> Param ( - [Parameter (Mandatory = $false)] [ValidateSet("guaranteed-medium","guaranteed-large","guaranteed-xlarge","best-effort-4xlarge","guaranteed-small","best-effort-medium","best-effort-2xlarge","guaranteed-2xlarge","best-effort-large","guaranteed-4xlarge","best-effort-8xlarge","best-effort-xsmall","guaranteed-xsmall","best-effort-xlarge","guaranteed-8xlarge","best-effort-small")] [String]$vmClass, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$namespace + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vmid, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$alias ) Try { - if ($PsBoundParameters.ContainsKey("name")) { - $uri = "https://$vcApiServer/api/vcenter/namespace-management/virtual-machine-classes/$vmClass" - $response = Invoke-RestMethod -Method 'GET' -URI $uri -Headers $vcApiHeaders + if ($PsBoundParameters.ContainsKey("vmid")) { + $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/certificates/$vmid" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders $response } - elseif ($PsBoundParameters.ContainsKey("namespace")) { - $uri = "https://$vcApiServer/api/vcenter/namespaces/instances/$namespace" - $response = Invoke-RestMethod -Method 'GET' -URI $uri -Headers $vcApiHeaders - $response.vm_service_spec.vm_classes + elseif ($PsBoundParameters.ContainsKey("alias")) { + $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/certificates" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders + $response.certificates | Where-Object {$_.alias -eq $alias} } else { - $uri = " https://$vcApiServer/api/vcenter/namespace-management/virtual-machine-classes" - $response = Invoke-RestMethod -Method 'GET' -URI $uri -Headers $vcApiHeaders - $response + $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/certificates" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders + $response.certificates } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-VMClass +Export-ModuleMember -Function Get-vRSLCMLockerCertificate -Function Add-VMClass { +Function Add-vRSLCMLockerCertificate { <# .SYNOPSIS - Retrieves information on a Virtual Machine class + Add a certificate to the vRSLCM locker .DESCRIPTION - The Add-VMClass cmdlet retrieves information on a Virtual Machine class + The Add-vRSLCMLockerCertificate cmdlet adds a certificate to the vRSLCM locker .EXAMPLE - Add-VMClass -namespace sfo-w01-tkc01 -vmClass guaranteed-small - This example retrieves all Virtual Machine classes + Add-vRSLCMLockerCertificate + This example gets all certificates in the Locker + + .EXAMPLE + Add-vRSLCMLockerCertificate -vmid 83abd0fd-c92d-4d8f-a5e8-9a1fc4fa6009 + This example gets the details of a certificate based on the vmid #> Param ( - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$namespace, - [Parameter (Mandatory = $false)] [ValidateSet("guaranteed-medium","guaranteed-large","guaranteed-xlarge","best-effort-4xlarge","guaranteed-small","best-effort-medium","best-effort-2xlarge","guaranteed-2xlarge","best-effort-large","guaranteed-4xlarge","best-effort-8xlarge","best-effort-xsmall","guaranteed-xsmall","best-effort-xlarge","guaranteed-8xlarge","best-effort-small")] [String]$vmClass + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vrslcmFQDN, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$certificateAlias, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$certificatePassphrase, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$certChainPath ) Try { - $existingVmClass = Get-VMClass -namespace $namespace -ErrorAction Ignore - if ($existingVmClass) { - $newVmClass = New-Object System.Collections.Generic.List[System.Object] - foreach ($assignedVMclass in $existingVmClass) { - if (!($assignedVMclass -eq $vmClass)) { - $newVmClass += $assignedVMclass - } - } - $newVmClass += $vmClass - $jsonFormat = ConvertTo-Json $newVmClass - - $body = '{"vm_service_spec": { "vm_classes": '+ $jsonFormat +'}}' + $newPEMString + foreach ($line in Get-Content $certChainPath) { + $stringToAdd = $line + '\n' + $newPEMString += $stringToAdd } - else { - $body = '{ "vm_service_spec": { "vm_classes": [ "' + $vmClass + '" ] }}' + $chain = [regex]::split($newPEMString, "-----BEGIN RSA PRIVATE KEY-----")[0] -replace ".{2}$" + $key = [regex]::split($newPEMString, "-----END CERTIFICATE-----")[-1].substring(2) + if (!$PsBoundParameters.ContainsKey("certificatePassphrase")) { + $body = '{ + "alias": "'+$certificateAlias+'", + "certificateChain": "'+$chain+'", + "privateKey": "'+$key+'" + }' + } + else { + $body = '{ + "alias": "'+$certificateAlias+'", + "certificateChain": "'+$chain+'", + "certificatePassphrase": "'+$certificatePassphrase+'", + "privateKey": "'+$key+'" + }' } - $uri = "https://$vcApiServer/api/vcenter/namespaces/instances/$namespace" - $response = Invoke-RestMethod -Method 'PATCH' -Uri $uri -Headers $vcApiHeaders -body $body - $response + $uri = "https://$vrslcmFQDN/lcm/locker/api/v2/certificates/import" + $response = Invoke-RestMethod $uri -Method 'POST' -Headers $vrslcmHeaders -ContentType application/json -body $body + $response.certInfo } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Add-VMClass +Export-ModuleMember -Function Add-vRSLCMLockerCertificate -Function Get-WMLicenseStatus { +Function Remove-vRSLCMLockerCertificate { <# .SYNOPSIS - Get Workload Management license status + Delete a certificate based on vmid .DESCRIPTION - The Get-WMLicenseStatus cmdlet gets the license status from vCenter Server for Workload Management - - .EXAMPLE - Get-WMLicenseStatus - This example gets the vSphere with Tanzu licenses status from vCenter Server for Workload Management - #> - - # Param ( - # [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, - # [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain - # ) - - Try { - $uri = "https://$vcApiServer/api/vcenter/namespace-management/capability" - $response = Invoke-RestMethod -Method GET -Uri $uri -Headers $vcApiHeaders - $response - - } - Catch { - Debug-ExceptionWriter -object $_ - } -} -Export-ModuleMember -Function Get-WMLicenseStatus - -Function Request-WMClusterCSR { - <# - .SYNOPSIS - Request Certificate Signing Request filr + The Remove-vRSLCMLockerCertificate cmdlet deletes a certificate from the Locker - .DESCRIPTION - The Request-WMClusterCSR cmdlet requests a Certificate Signing Request file for the Supervisor Cluster .EXAMPLE - Request-WMClusterCSR -cluster sfo-w01-cl01 -commonName sfo-w01-cl01.sfo.rainpole.io -organization Rainpole -organizationalUnit Rainpole -country US -stateOrProvince California -locality "Palo Alto" -adminEmailAddress admin@rainpole.io -keySize 2048 -filePath ".\SupervisorCluster.csr" - This example requetes a Certificate Signing Request file for the Supervisor Cluster sfo-w01-cl01 + Remove-vRSLCMLockerCertificate -vmid + This example delets the certificate with the vmid #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$commonName, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$organization, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$organizationalUnit, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$country, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$stateOrProvince, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$locality, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$adminEmailAddress, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$keySize, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$filePath + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vmid ) Try { - $uri = "https://$vcApiServer/api/vcenter/namespace-management/clusters" - $clusterId = (Invoke-RestMethod -Method GET -URI $uri -Headers $vcApiHeaders | Where-Object { $_.cluster_name -eq $cluster }).cluster - - $output = New-Object -TypeName PSCustomObject - $output | Add-Member -notepropertyname 'common_name' -notepropertyvalue $commonName - $output | Add-Member -notepropertyname 'organization_name' -notepropertyvalue $organization - $output | Add-Member -notepropertyname 'organization_unit_name' -notepropertyvalue $organizationalUnit - $output | Add-Member -notepropertyname 'country' -notepropertyvalue $country - $output | Add-Member -notepropertyname 'state_or_province' -notepropertyvalue $stateOrProvince - $output | Add-Member -notepropertyname 'locality' -notepropertyvalue $locality - $output | Add-Member -notepropertyname 'email_address' -notepropertyvalue $adminEmailAddress - if ($PsBoundParameters.ContainsKey("keySize")){ - $output | Add-Member -notepropertyname 'keySize' -notepropertyvalue $keySize - } - $body = $output | ConvertTo-Json - $uri = "https://$vcApiServer/api/$clusterId/csr/tls-endpoint/" - $response = Invoke-RestMethod -Method POST -Uri $uri -Headers $vcApiHeaders -body $body - $response | Out-File -FilePath $filePath - Write-Output "Certificate Signing Request (.csr) file for ($commonName) has been successfully saved to file ($filePath)" + $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/certificates/$vmid" + $response = Invoke-RestMethod $uri -Method 'DELETE' -Headers $vrslcmHeaders + $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Request-WMClusterCSR +Export-ModuleMember -Function Remove-vRSLCMLockerCertificate -Function Install-WMClusterCertificate { +Function Get-vRSLCMLockerLicense { <# .SYNOPSIS - Installs a signed TLS certificate for the defined Supervisor Cluster + Get paginated list of License available in the Store .DESCRIPTION - The Install-WMClusterCertificate cmdlet installs a signed TLS certificate for the defined Supervisor Cluster + The Get-vRSLCMLockerLicense cmdlet gets a paginated list of license available in the Locker .EXAMPLE - Install-WMClusterCertificate -cluster sfo-w01-cl01 -filePath ".\SupervisorCluster.cer" - This example installs the signed TLS certificate to Supervisor Cluster sfo-w01-cl01 in Workload domain sfo-w01 + Get-vRSLCMLockerLicense + This example gets all license in the Locker + + .EXAMPLE + Get-vRSLCMLockerLicense -vmid 2b54b028-9eba-4d2f-b6ee-66428ea2b297 + This example gets the details of a license based on the vmid + + .EXAMPLE + Get-vRSLCMLockerLicense -alias "vRealize Operations Manager" + This example gets the details of a license based on the alias name #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$filePath + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vmid, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$alias ) Try { - if ($PsBoundParameters.ContainsKey("filepath")) { - if (!(Test-Path $filepath)) { - Throw "Certificate File Not Found" - } - else { - $certificate = Get-Content -Path $filePath -Raw -ErrorAction SilentlyContinue - $inputFileName = Split-Path -Path $filePath -Leaf -ErrorAction SilentlyContinue - } - } - if ($isMacOS -eq $true -or $isLinux -eq $true) { - $certificateFormatted = $Certificate -Replace "`n","\n" - } - elseif ($isWindows -eq $true -or $PSEdition -eq "Desktop") { - $certificateFormatted = $Certificate -Replace "`r`n","\n" - } - else { - Write-Error "Unsupported Operating System" - Break - } - if (($certificateFormatted | Measure-object -Line).Count -ne 1) { - Write-Error "Error parsing TLS certificate" - Break + if ($PsBoundParameters.ContainsKey("vmid")) { + $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/licenses/detail/$vmid" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders + $response } - $body = '{ "tls_endpoint_certificate": "'+ $certificateFormatted +'" }' - $uri = "https://$vcApiServer/api/vcenter/namespace-management/clusters" - $clusterId = (Invoke-RestMethod -Method GET -URI $uri -Headers $vcApiHeaders | Where-Object { $_.cluster_name -eq $cluster }).cluster - $uri = "https://$vcApiServer/api/vcenter/namespace-management/clusters/$clusterId/" - if ($PSEdition -eq 'Core') { - $response = Invoke-WebRequest -Method PATCH -Uri $uri -Headers $vcApiHeaders -body $body -SkipCertificateCheck -UseBasicParsing # PS Core has -SkipCertificateCheck implemented + elseif ($PsBoundParameters.ContainsKey("alias")) { + $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/licenses/alias/$alias" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders + $response } else { - $response = Invoke-WebRequest -Method PATCH -Uri $uri -Headers $vcApiHeaders -body $body -UseBasicParsing - } - if ($response.StatusCode -lt 300) { - if ($inputFileName) { - Write-Output "Signed Certificate ($inputFileName) has been successfully applied to Supervisor Cluster ($cluster)" - } - else { - Write-Output "Signed Certificate has been successfully applied to Supervisor Cluster ($cluster)" - } + $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/licenses" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders + $response } } Catch { - Debug-ExceptionWriter -object $_ + Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Install-WMClusterCertificate - -############# End vSphere with Tanzu Functions ############### -############################################################### - - -######################################################################################## -################## Start vRealize Suite Lifecycle Manager Functions ################### +Export-ModuleMember -Function Get-vRSLCMLockerLicense -Function Request-vRSLCMToken { +Function Add-vRSLCMLockerLicense { <# .SYNOPSIS - Connects to the specified vRealize Suite Lifecycle Manager and obtains authorization token + Creates a new License in a Locker .DESCRIPTION - The Request-vRSLCMToken cmdlet connects to the specified vRealize Suite Lifecycle Manager and - obtains an authorization token. It is required once per session before running all other cmdlets. + The Add-vRSLCMLockerLicense cmdlet adds as new license to the Locker .EXAMPLE - Request-vRSLCMToken -fqdn xreg-vrslcm.rainpole.io -username admin@local -password VMware1! - This example shows how to connect to the vRealize Suite Lifecycle Manager appliance + Add-vRSLCMLockerLicense -alias "vRealise Operations Manager" -license "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX" + This example adds a license to the Locker #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$fqdn, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$username, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$password + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$alias, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$license ) - if ( -not $PsBoundParameters.ContainsKey("username") -or ( -not $PsBoundParameters.ContainsKey("password"))) { - $creds = Get-Credential # Request Credentials - $username = $creds.UserName.ToString() - $password = $creds.GetNetworkCredential().password - } - - $Global:vrslcmHeaders = createBasicAuthHeader $username $password - $Global:vrslcmAppliance = $fqdn - Try { - # Validate credentials by executing an API call - $uri = "https://$vrslcmAppliance/lcmversion" - if ($PSEdition -eq 'Core') { - $vrslcmResponse = Invoke-WebRequest -Method GET -Uri $uri -Headers $vrslcmHeaders -SkipCertificateCheck -UseBasicParsing # PS Core has -SkipCertificateCheck implemented, PowerShell 5.x does not - } - else { - $vrslcmResponse = Invoke-WebRequest -Method GET -Uri $uri -Headers $vrslcmHeaders -UseBasicParsing - } - if ($vrslcmResponse.StatusCode -eq 200) { - Write-Output "Successfully connected to the vRealize Suite Lifecycle Manager Appliance: $vrslcmAppliance" - } + $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/license/validate-and-add" + $body = '{ + "alias": "'+ $alias +'", + "serialKey": "'+ $license +'" + }' + + $response = Invoke-RestMethod $uri -Method 'POST' -Headers $vrslcmHeaders -Body $body + $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Request-vRSLCMToken +Export-ModuleMember -Function Add-vRSLCMLockerLicense -Function Get-vRSLCMHealth { +Function Remove-vRSLCMLockerLicense { <# .SYNOPSIS - Check vRealize Suite Lifecycle Manager Health Status + Delete a License based on vmid .DESCRIPTION - The Get-vRSLCMHealth cmdlet checks vRealize Suite Lifecycle Manager Health Status + The Remove-vRSLCMLockerLicense cmdlet deletes a license from the Locker .EXAMPLE - Get-vRSLCMHealth - This example checks vRealize Suite Lifecycle Manager Health Status + Remove-vRSLCMLockerLicense -vmid + This example delets the license with the vmid #> + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vmid + ) + Try { - $uri = "https://$vrslcmAppliance/lcm/health/api/v2/status" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders + $uri = "https://$vrslcmAppliance/lcm/locker/api/licenses/$vmid" + $response = Invoke-RestMethod $uri -Method 'DELETE' -Headers $vrslcmHeaders $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-vRSLCMHealth +Export-ModuleMember -Function Remove-vRSLCMLockerLicense -Function Get-vRSLCMLockerPassword { +Function Get-vRSLCMDatacenter { <# .SYNOPSIS - Get paginated list of Passwords available in the Store + Get paginated list of datacenters in vRealize Suite Lifecycle Manager .DESCRIPTION - The Get-vRSLCMLockerPassword cmdlet gets a paginated list of passwords available in the Locker + The Get-vRSLCMDatacenter cmdlet gets a paginated list of datacenters in vRealize Suite Lifecycle Manager .EXAMPLE - Get-vRSLCMLockerPassword - This example gets all passwords in the Locker + Get-vRSLCMDatacenter + This example gets all datacenters in vRealize Suite Lifecycle Manager .EXAMPLE - Get-vRSLCMLockerPassword -vmid 83abd0fd-c92d-4d8f-a5e8-9a1fc4fa6009 - This example gets the details of a password based on the vmid + Get-vRSLCMDatacenter -vmid 2b54b028-9eba-4d2f-b6ee-66428ea2b297 + This example gets the details of a datacenter based on the vmid .EXAMPLE - Get-vRSLCMLockerPassword -alias xint-env-admin - This example gets the details of a password based on the alias + Get-vRSLCMDatacenter -name sfo-m01-dc01 + This example gets the details of a datacenter based on the name #> Param ( [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vmid, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$alias + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$datacenterName ) Try { if ($PsBoundParameters.ContainsKey("vmid")) { - $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/passwords/$vmid" + $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/datacenters/$vmid" $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders $response } - elseif ($PsBoundParameters.ContainsKey("alias")){ - $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/passwords?aliasQuery=$alias" + elseif ($PsBoundParameters.ContainsKey("datacenterName")) { + $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/datacenters/$datacenterName" $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders - $response.passwords + $response } else { - $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/passwords?size=19" + $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/datacenters" $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders - $response.passwords + $response } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-vRSLCMLockerPassword +Export-ModuleMember -Function Get-vRSLCMDatacenter -Function Add-vRSLCMLockerPassword { +Function Add-vRSLCMDatacenter { <# .SYNOPSIS - Creates a new Password in a Locker + Add a datacenter in vRealize Suite Lifecycle Manager .DESCRIPTION - The Add-vRSLCMLockerPassword cmdlet add as new passwords to the Locker + The Add-vRSLCMDatacenter cmdlet adds a datacenter in vRealize Suite Lifecycle Manager .EXAMPLE - Add-vRSLCMLockerPassword -userName admin -alias xint-admin -password VMw@re1! -description "Password for Cross-Instance Admin" - This example adda a password to the locker + Add-vRSLCMDatacenter -datacenterName xint-m01-dc01 -location "San Francisco;California;US;37.77493;-122.41942" + This example adds a datacenter in vRealize Suite Lifecycle Manager #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$userName, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$alias, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$password, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$description - ) - - Try { - $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/passwords" - - if ($PsBoundParameters.ContainsKey("description")) { - $body = '{ - "alias": "'+ $alias +'", - "password": "'+ $password +'", - "passwordDescription": "'+ $description +'", - "userName": "'+ $userName +'" - }' - } - else { - $body = '{ - "alias": "'+ $alias +'", - "password": "'+ $password +'", - "userName": "'+ $userName +'" - }' - } + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$datacenterName, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$location + ) + Try { + $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/datacenters" + $body = '{ + "dataCenterName": "'+ $datacenterName +'", + "primaryLocation": "'+ $location +'" + }' $response = Invoke-RestMethod $uri -Method 'POST' -Headers $vrslcmHeaders -Body $body $response - } +} Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Add-vRSLCMLockerPassword +Export-ModuleMember -Function Add-vRSLCMDatacenter -Function Remove-vRSLCMLockerPassword { +Function Remove-vRSLCMDatacenter { <# .SYNOPSIS - Delete a Password based on vmid + Remove a datacenter from vRealize Suite Lifecycle Manager .DESCRIPTION - The Remove-vRSLCMLockerPassword cmdlet deletes a password from the Locker + The Remove-vRSLCMDatacenter cmdlet removes a datacenter from vRealize Suite Lifecycle Manager .EXAMPLE - Remove-vRSLCMLockerPassword -vmid - This example delets the password with the vmid + Remove-vRSLCMDatacenter -datacenterVmid + This example removes a datacenter from vRealize Suite Lifecycle Manager #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vmid + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$datacenterVmid ) Try { - $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/passwords/$vmid" + $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/datacenters/$datacenterVmid" $response = Invoke-RestMethod $uri -Method 'DELETE' -Headers $vrslcmHeaders $response - } +} Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Remove-vRSLCMLockerPassword +Export-ModuleMember -Function Remove-vRSLCMDatacenter -Function Get-vRSLCMLockerCertificate { +Function Get-vRSLCMDatacenterVcenter { <# .SYNOPSIS - Get paginated list of Certificates available in the Store + Get paginated list of vCenter Servers in vRealize Suite Lifecycle Manager .DESCRIPTION - The Get-vRSLCMLockerCertificate cmdlet gets a paginated list of certificates available in the Locker + The Get-vRSLCMDatacenterVcenter cmdlet gets a paginated list of vCenter Servers in vRealize Suite Lifecycle Manager .EXAMPLE - Get-vRSLCMLockerCertificate - This example gets all certificates in the Locker + Get-vRSLCMDatacenterVcenter -datacenterVmid + This example gets all vCenter Servers for a Datacenter .EXAMPLE - Get-vRSLCMLockerCertificate -vmid 83abd0fd-c92d-4d8f-a5e8-9a1fc4fa6009 - This example gets the details of a certificate based on the vmid + Get-vRSLCMDatacenterVcenter -datacenterVmid -vcenterName sfo-m01-vc01 + This example gets a named vCenter Server for a datacenter .EXAMPLE - Get-vRSLCMLockerCertificate -alias xint-vrops01 - This example gets the details of a certificate based on the vmid + Get-vRSLCMDatacenterVcenter -datacenterVmid -vcenterName sfo-m01-vc01 -environments + This example gets all vCenter Servers for a Datacenter that is assigned to an Environemnt #> Param ( - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vmid, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$alias + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$datacenterVmid, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vcenterName, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$environments ) Try { - if ($PsBoundParameters.ContainsKey("vmid")) { - $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/certificates/$vmid" + if ($PsBoundParameters.ContainsKey("datacenterVmid") -and $PsBoundParameters.ContainsKey("vcenterName")) { + $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/datacenters/$datacenterVmid/vcenters/$vcenterName" $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders $response } - elseif ($PsBoundParameters.ContainsKey("alias")) { - $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/certificates" + elseif ($PsBoundParameters.ContainsKey("datacenterVmid") -and $PsBoundParameters.ContainsKey("vcenterName") -and $PsBoundParameters.ContainsKey("environments")) { + $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/datacenters/$datacenterVmid/vcenters/$vcenterName/environments" $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders - $response.certificates | Where-Object {$_.alias -eq $alias} + $response } else { - $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/certificates" + $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/datacenters/$datacenterVmid/vcenters" $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders - $response.certificates + $response } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-vRSLCMLockerCertificate +Export-ModuleMember -Function Get-vRSLCMDatacenterVcenter -Function Add-vRSLCMLockerCertificate { +Function Add-vRSLCMDatacenterVcenter { <# .SYNOPSIS - Add a certificate to the vRSLCM locker + Add a vCenter Server to a Datacenter in vRealize Suite Lifecycle Manager .DESCRIPTION - The Add-vRSLCMLockerCertificate cmdlet adds a certificate to the vRSLCM locker - - .EXAMPLE - Add-vRSLCMLockerCertificate - This example gets all certificates in the Locker + The Add-vRSLCMDatacenterVcenter cmdlet adds a vCenter Servers to a Datacenter in vRealize Suite Lifecycle Manager .EXAMPLE - Add-vRSLCMLockerCertificate -vmid 83abd0fd-c92d-4d8f-a5e8-9a1fc4fa6009 - This example gets the details of a certificate based on the vmid + Add-vRSLCMDatacenterVcenter -datacenterVmid -vcenterFqdn -userLockerAlias + This example adds a vCenter Server to a Datacenter #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vrslcmFQDN, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$certificateAlias, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$certificatePassphrase, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$certChainPath + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$datacenterVmid, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vcenterFqdn, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$userLockerAlias ) Try { - $newPEMString - foreach ($line in Get-Content $certChainPath) { - $stringToAdd = $line + '\n' - $newPEMString += $stringToAdd - } - $chain = [regex]::split($newPEMString, "-----BEGIN RSA PRIVATE KEY-----")[0] -replace ".{2}$" - $key = [regex]::split($newPEMString, "-----END CERTIFICATE-----")[-1].substring(2) - if (!$PsBoundParameters.ContainsKey("certificatePassphrase")) { - $body = '{ - "alias": "'+$certificateAlias+'", - "certificateChain": "'+$chain+'", - "privateKey": "'+$key+'" - }' - } - else { + $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/datacenters/$datacenterVmid/vcenters" $body = '{ - "alias": "'+$certificateAlias+'", - "certificateChain": "'+$chain+'", - "certificatePassphrase": "'+$certificatePassphrase+'", - "privateKey": "'+$key+'" + "vCenterHost": "' + $vcenterFqdn + '", + "vCenterName": "' + ($vcenterFqdn.Split("."))[0] + '", + "vcPassword": "locker:password:' + (Get-vRSLCMLockerPassword -alias $userLockerAlias).vmid + ':' + $userLockerAlias + '", + "vcUsedAs": "MANAGEMENT", + "vcUsername": "' + (Get-vRSLCMLockerPassword -alias $userLockerAlias).userName +'" }' - } - - $uri = "https://$vrslcmFQDN/lcm/locker/api/v2/certificates/import" - $response = Invoke-RestMethod $uri -Method 'POST' -Headers $vrslcmHeaders -ContentType application/json -body $body - $response.certInfo + $response = Invoke-RestMethod $uri -Method 'POST' -Headers $vrslcmHeaders -Body $body + $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Add-vRSLCMLockerCertificate +Export-ModuleMember -Function Add-vRSLCMDatacenterVcenter -Function Remove-vRSLCMLockerCertificate { +Function Get-vRSLCMEnvironment { <# .SYNOPSIS - Delete a certificate based on vmid + Get paginated list of environments in vRealize Suite Lifecycle Manager .DESCRIPTION - The Remove-vRSLCMLockerCertificate cmdlet deletes a certificate from the Locker + The Get-vRSLCMEnvironment cmdlet gets a paginated list of environments in vRealize Suite Lifecycle Manager .EXAMPLE - Remove-vRSLCMLockerCertificate -vmid - This example delets the certificate with the vmid + Get-vRSLCMEnvironment + This example gets all environments in vRealize Suite Lifecycle Manager #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vmid + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vmid ) Try { - $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/certificates/$vmid" - $response = Invoke-RestMethod $uri -Method 'DELETE' -Headers $vrslcmHeaders - $response + if ($PsBoundParameters.ContainsKey("vmid")) { + $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/environments/$vmid" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders + $response + } + else { + $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/environments" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders + $response + } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Remove-vRSLCMLockerCertificate +Export-ModuleMember -Function Get-vRSLCMEnvironment -Function Get-vRSLCMLockerLicense { +Function Add-vRSLCMEnvironment { <# .SYNOPSIS - Get paginated list of License available in the Store + Create an environment in vRealize Suite Lifecycle Manager .DESCRIPTION - The Get-vRSLCMLockerLicense cmdlet gets a paginated list of license available in the Locker - - .EXAMPLE - Get-vRSLCMLockerLicense - This example gets all license in the Locker + The Add-vRSLCMEnvironment cmdlet to create an environment in vRealize Suite Lifecycle Manager .EXAMPLE - Get-vRSLCMLockerLicense -vmid 2b54b028-9eba-4d2f-b6ee-66428ea2b297 - This example gets the details of a license based on the vmid + Add-vRSLCMEnvironment -json (Get-Content -Raw .\vrli.json) + This example creates an environment in vRealize Suite Lifecycle Manager .EXAMPLE - Get-vRSLCMLockerLicense -alias "vRealize Operations Manager" - This example gets the details of a license based on the alias name + Add-vRSLCMEnvironment -json (Get-Content -Raw .\vrli.json) -vmid c907c25b-1c61-465b-b7cb-4100ac1ce331 -addProduct + This example adds a new product to an existing environment in vRealize Suite Lifecycle Manager #> Param ( - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vmid, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$alias + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$json, + [Parameter (Mandatory = $false, ParameterSetName = 'growth')] [ValidateNotNullOrEmpty()] [String]$environmentId, + [Parameter (Mandatory = $false, ParameterSetName = 'growth')] [ValidateNotNullOrEmpty()] [Switch]$addProduct ) Try { - if ($PsBoundParameters.ContainsKey("vmid")) { - $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/licenses/detail/$vmid" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders - $response - } - elseif ($PsBoundParameters.ContainsKey("alias")) { - $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/licenses/alias/$alias" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders + if ($PsBoundParameters.ContainsKey("json") -and ($PsBoundParameters.ContainsKey("addProduct")) -and ($PsBoundParameters.ContainsKey("environmentId"))) { + $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/environments/$environmentId/products" + $response = Invoke-RestMethod $uri -Method 'POST' -Headers $vrslcmHeaders -Body $json $response } else { - $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/licenses" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders + $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/environments" + $response = Invoke-RestMethod $uri -Method 'POST' -Headers $vrslcmHeaders -Body $json $response } } @@ -17179,411 +19854,621 @@ Function Get-vRSLCMLockerLicense { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-vRSLCMLockerLicense +Export-ModuleMember -Function Add-vRSLCMEnvironment -Function Add-vRSLCMLockerLicense { +Function Remove-vRSLCMEnvironment { <# .SYNOPSIS - Creates a new License in a Locker + Remove an environment from vRealize Suite Lifecycle Manager .DESCRIPTION - The Add-vRSLCMLockerLicense cmdlet adds as new license to the Locker + The Remove-vRSLCMEnvironment cmdlet removes an environment from vRealize Suite Lifecycle Manager .EXAMPLE - Add-vRSLCMLockerLicense -alias "vRealise Operations Manager" -license "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX" - This example adds a license to the Locker + Remove-vRSLCMEnvironment -environmentId + This example removes an environment from vRealize Suite Lifecycle Manager #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$alias, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$license + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$environmentId ) Try { - $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/license/validate-and-add" - $body = '{ - "alias": "'+ $alias +'", - "serialKey": "'+ $license +'" - }' - - $response = Invoke-RestMethod $uri -Method 'POST' -Headers $vrslcmHeaders -Body $body + $body = '{ "deleteFromInventory": true, "deleteFromVcenter": true, "deleteLbFromSddc": true, "deleteWindowsVMs": true }' + $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/environments/$environmentId" + $response = Invoke-RestMethod $uri -Method 'DELETE' -Headers $vrslcmHeaders -Body $body $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Add-vRSLCMLockerLicense +Export-ModuleMember -Function Remove-vRSLCMEnvironment -Function Remove-vRSLCMLockerLicense { +Function Get-vRSLCMRequest { + <# + .SYNOPSIS + Get all Requests + + .DESCRIPTION + The Get-vRSLCMRequest cmdlet gets all requests in vRealize Suite Lifecycle Manager + + .EXAMPLE + Get-vRSLCMRequest + This example gets all requests vRealize Suite Lifecycle Manager + + .EXAMPLE + Get-vRSLCMRequest -requestId 0ee1a4a0-203a-4c87-a40e-65d9a450e398 + This example gets the request by id from vRealize Suite Lifecycle Manager + + .EXAMPLE + Get-vRSLCMRequest -requestId 0ee1a4a0-203a-4c87-a40e-65d9a450e398 -errorCauses + This example gets the errors for a request by id from vRealize Suite Lifecycle Manager + #> + + Param ( + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$requestId, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$errorCauses + ) + + Try { + if ($PsBoundParameters.ContainsKey("requestId")) { + $uri = "https://$vrslcmAppliance/lcm/request/api/v2/requests/$requestId" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders + $response + } + elseif ($PsBoundParameters.ContainsKey("errorCauses")) { + $uri = "https://$vrslcmAppliance/lcm/request/api/v2/requests/$requestId/error-causes" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders + $response + } + else { + $uri = "https://$vrslcmAppliance/lcm/request/api/v2/requests" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders + $response | Select-Object -Property vmid, state, requestReason, requestType + } + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Get-vRSLCMRequest + +Function Remove-vRSLCMRequest { <# .SYNOPSIS - Delete a License based on vmid + Delete a Request .DESCRIPTION - The Remove-vRSLCMLockerLicense cmdlet deletes a license from the Locker + The Remove-vRSLCMRequest cmdlet removes a request from vRealize Suite Lifecycle Manager .EXAMPLE - Remove-vRSLCMLockerLicense -vmid - This example delets the license with the vmid + Remove-vRSLCMRequest -requestId + This example removes a request from vRealize Suite Lifecycle Manager #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vmid - ) + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$requestId ) Try { - $uri = "https://$vrslcmAppliance/lcm/locker/api/licenses/$vmid" - $response = Invoke-RestMethod $uri -Method 'DELETE' -Headers $vrslcmHeaders - $response + + $uri = "https://$vrslcmAppliance/lcm/request/requests/$requestId" + $response = Invoke-RestMethod $uri -Method 'DELETE' -Headers $vrslcmHeaders + $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Remove-vRSLCMLockerLicense +Export-ModuleMember -Function Remove-vRSLCMRequest -Function Get-vRSLCMDatacenter { +Function Watch-vRSLCMRequest { <# .SYNOPSIS - Get paginated list of datacenters in vRealize Suite Lifecycle Manager + Poll request .DESCRIPTION - The Get-vRSLCMDatacenter cmdlet gets a paginated list of datacenters in vRealize Suite Lifecycle Manager - - .EXAMPLE - Get-vRSLCMDatacenter - This example gets all datacenters in vRealize Suite Lifecycle Manager - - .EXAMPLE - Get-vRSLCMDatacenter -vmid 2b54b028-9eba-4d2f-b6ee-66428ea2b297 - This example gets the details of a datacenter based on the vmid + The Watch-vRSLCMRequest cmdlet polls a request in vRealize Suite Lifecycle Manager .EXAMPLE - Get-vRSLCMDatacenter -name sfo-m01-dc01 - This example gets the details of a datacenter based on the name + Watch-vRSLCMRequest -vmid + This example polls the request in vRealize Suite Lifecycle Manager #> Param ( - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vmid, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$datacenterName + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vmid ) Try { - if ($PsBoundParameters.ContainsKey("vmid")) { - $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/datacenters/$vmid" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders - $response - } - elseif ($PsBoundParameters.ContainsKey("datacenterName")) { - $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/datacenters/$datacenterName" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders - $response - } - else { - $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/datacenters" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders - $response - } + Do { + $requestStatus = (Get-vRSLCMRequest | Where-Object {$_.vmid -eq $vmid}).state + } + Until ($requestStatus -ne "INPROGRESS") + Write-Output "vRealize Suite Lifecycle Manager request: $vmid completed with the following state: $requestStatus" } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-vRSLCMDatacenter +Export-ModuleMember -Function Watch-vRSLCMRequest -Function Add-vRSLCMDatacenter { +Function Resume-vRSLCMRequest { <# .SYNOPSIS - Add a datacenter in vRealize Suite Lifecycle Manager + Retry a request .DESCRIPTION - The Add-vRSLCMDatacenter cmdlet adds a datacenter in vRealize Suite Lifecycle Manager + The Resume-vRSLCMRequest cmdlet reties a request .EXAMPLE - Add-vRSLCMDatacenter -datacenterName xint-m01-dc01 -location "San Francisco;California;US;37.77493;-122.41942" - This example adds a datacenter in vRealize Suite Lifecycle Manager + Resume-vRSLCMRequest -requestId 0ee1a4a0-203a-4c87-a40e-65d9a450e398 + This example reties the request based on the request ID provided #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$datacenterName, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$location + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$requestId ) Try { - $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/datacenters" - $body = '{ - "dataCenterName": "'+ $datacenterName +'", - "primaryLocation": "'+ $location +'" - }' - $response = Invoke-RestMethod $uri -Method 'POST' -Headers $vrslcmHeaders -Body $body + $uri = "https://$vrslcmAppliance/lcm/request/api/v2/requests/$requestId/retry" + $response = Invoke-RestMethod $uri -Method 'PATCH' -Headers $vrslcmHeaders $response -} + } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Add-vRSLCMDatacenter +Export-ModuleMember -Function Resume-vRSLCMRequest -Function Remove-vRSLCMDatacenter { +Function Export-WsaJsonSpec { <# .SYNOPSIS - Remove a datacenter from vRealize Suite Lifecycle Manager + Create Clustered Workspace ONE Access JSON specification .DESCRIPTION - The Remove-vRSLCMDatacenter cmdlet removes a datacenter from vRealize Suite Lifecycle Manager + The Export-WsaJsonSpec cmdlet creates the JSON specification file using the Planning and Preparation workbook + to deploy Clustered Workspace ONE Access using vRealize Suite Lifecycle Manager: + - Validates that the Planning and Preparation is available + - Validates that network connectivity is available to vRealize Suite Lifecycle Manager + - Makes a connection to the vRealize Suite Lifecycle Manager instance and validates that authentication possible + - Generates the JSON specification file using the Planning and Preparation workbook and details from vRealize Suite Lifecycle Manager .EXAMPLE - Remove-vRSLCMDatacenter -datacenterVmid - This example removes a datacenter from vRealize Suite Lifecycle Manager + Export-WsaJsonSpec -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -workbook .\pnp-workbook.xlsx + This example creates a JSON deployment specification of Clustered Workspace ONE Access using the Planning and Preparation Workbook #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$datacenterVmid + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$workbook ) Try { - $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/datacenters/$datacenterVmid" - $response = Invoke-RestMethod $uri -Method 'DELETE' -Headers $vrslcmHeaders - $response -} - Catch { - Write-Error $_.Exception.Message - } -} -Export-ModuleMember -Function Remove-vRSLCMDatacenter -Function Get-vRSLCMDatacenterVcenter { - <# - .SYNOPSIS - Get paginated list of vCenter Servers in vRealize Suite Lifecycle Manager + if (!$PsBoundParameters.ContainsKey("workbook")) { + $workbook = Get-ExternalFileName -title "Select the Planning and Preparation Workbook (.xlsx)" -fileType "xlsx" -location "default" + } + else { + if (!(Test-Path -Path $workbook)) { + Write-Error "Planning and Preparation Workbook (.xlsx) '$workbook' File Not Found" + Break + } + } - .DESCRIPTION - The Get-vRSLCMDatacenterVcenter cmdlet gets a paginated list of vCenter Servers in vRealize Suite Lifecycle Manager + $pnpWorkbook = Open-ExcelPackage -Path $workbook - .EXAMPLE - Get-vRSLCMDatacenterVcenter -datacenterVmid - This example gets all vCenter Servers for a Datacenter + ### Obtain Configuration Information from vRealize Suite Lifecycle Manager + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-vRSLCMConnection -server $vcfVrslcmDetails.fqdn) { + if (Test-vRSLCMAuthentication -server $vcfVrslcmDetails.fqdn -user $vcfVrslcmDetails.adminUser -pass $vcfVrslcmDetails.adminPass) { + if ($wsaCertificate = Get-vRSLCMLockerCertificate | Where-Object {$_.alias -eq $pnpWorkbook.Workbook.Names["xreg_wsa_cert_name"].Value}) { + if ($defaultPassword = Get-vRSLCMLockerPassword -alias $pnpWorkbook.Workbook.Names["global_env_admin_password_alias"].Value) { + if ($configAdminPassword = Get-vRSLCMLockerPassword -alias $pnpWorkbook.Workbook.Names["local_configadmin_password_alias"].Value) { + if ($wsaPassword = Get-vRSLCMLockerPassword -alias $pnpWorkbook.Workbook.Names["local_admin_password_alias"].Value) { + $vcCredentials = Get-vRSLCMLockerPassword -alias (($pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value).Split(".")[0] + "-" + $pnpWorkbook.Workbook.Names["mgmt_datacenter"].Value) + if ($datacenterName = Get-vRSLCMDatacenter | Where-Object {$_.dataCenterName -eq $pnpWorkbook.Workbook.Names["vrslcm_xreg_dc"].Value}) { + $xintEnvironment = Get-vRSLCMEnvironment | Where-Object {$_.environmentName -eq $pnpWorkbook.Workbook.Names["vrslcm_xreg_env"].Value} + $infrastructurePropertiesObject = @() + $infrastructurePropertiesObject += [pscustomobject]@{ + 'acceptEULA' = "true" + 'enableTelemetry' = "true" + 'regionName' = "default" + 'zoneName' = "default" + 'dataCenterVmid' = $datacenterName.dataCenterVmid + 'vCenterName' = ($pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value).Split(".")[0] + 'vCenterHost' = $pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value + 'vcUsername' = $vcCredentials.userName + 'vcPassword' = ("locker:password:" + $($vcCredentials.vmid) + ":" + $($vcCredentials.alias)) + 'defaultPassword' = ("locker:password:" + $($defaultPassword.vmid) + ":" + $($defaultPassword.alias)) + 'certificate' = ("locker:certificate:" + $($wsaCertificate.vmid) + ":" + $($wsaCertificate.alias)) + 'cluster' = ($pnpWorkbook.Workbook.Names["mgmt_datacenter"].Value + "#" + $pnpWorkbook.Workbook.Names["mgmt_cluster"].Value) + 'storage' = $pnpWorkbook.Workbook.Names["mgmt_vsan_datastore"].Value + 'diskMode' = "thin" + 'network' = $pnpWorkbook.Workbook.Names["xreg_seg01_name"].Value + 'masterVidmEnabled' = "false" + 'dns' = ($pnpWorkbook.Workbook.Names["region_dns1_ip"].Value + "," + $pnpWorkbook.Workbook.Names["region_dns2_ip"].Value) + 'domain' = $pnpWorkbook.Workbook.Names["region_ad_parent_fqdn"].Value + 'gateway' = $pnpWorkbook.Workbook.Names["xreg_seg01_gateway_ip"].Value + 'netmask' = $pnpWorkbook.Workbook.Names["xreg_seg01_mask"].Value + 'searchpath' = $pnpWorkbook.Workbook.Names["parent_dns_zone"].Value + 'timeSyncMode' = "ntp" + 'ntp' = $pnpWorkbook.Workbook.Names["xregion_ntp1_server"].Value + 'vcfProperties' = '{"vcfEnabled":true,"sddcManagerDetails":[{"sddcManagerHostName":"' + $pnpWorkbook.Workbook.Names["sddc_mgr_fqdn"].Value + '","sddcManagerName":"default","sddcManagerVmid":"default"}]}' + } - .EXAMPLE - Get-vRSLCMDatacenterVcenter -datacenterVmid -vcenterName sfo-m01-vc01 - This example gets a named vCenter Server for a datacenter + $infrastructureObject = @() + $infrastructureObject += [pscustomobject]@{ + 'properties' = ($infrastructurePropertiesObject | Select-Object -Skip 0) + } - .EXAMPLE - Get-vRSLCMDatacenterVcenter -datacenterVmid -vcenterName sfo-m01-vc01 -environments - This example gets all vCenter Servers for a Datacenter that is assigned to an Environemnt - #> + ### Generate the Properties Details + $productPropertiesObject = @() + $productPropertiesObject += [pscustomobject]@{ + 'vidmAdminPassword' = ("locker:password:" + $($wsaPassword.vmid) + ":" + $($wsaPassword.alias)) + 'syncGroupMembers' = $true + 'nodeSize' = ($pnpWorkbook.Workbook.Names["xreg_wsa_node_size"].Value).ToLower() + 'defaultConfigurationEmail' = $pnpWorkbook.Workbook.Names["xreg_configadmin_email"].Value + 'defaultConfigurationUsername' = $pnpWorkbook.Workbook.Names["local_configadmin_username"].Value + 'defaultConfigurationPassword' = ("locker:password:" + $($configAdminPassword.vmid) + ":" + $($configAdminPassword.alias)) + 'defaultTenantAlias' = "" + 'vidmDomainName' = "" + 'certificate' = ("locker:certificate:" + $($wsaCertificate.vmid) + ":" + $($wsaCertificate.alias)) + 'contentLibraryItemId' = "" + 'fipsMode' = "false" + } + + #### Generate Workspace ONE Access Cluster Details + $clusterLbProperties = @() + $clusterLbProperties += [pscustomobject]@{ + 'hostName' = $pnpWorkbook.Workbook.Names["xreg_wsa_virtual_fqdn"].Value + 'lockerCertificate' = ("locker:certificate:" + $($wsaCertificate.vmid) + ":" + $($wsaCertificate.alias)) + } + + $clusterDelegateObject = @() + $clusterDelegateObject += [pscustomobject]@{ + 'ip' = $pnpWorkbook.Workbook.Names["xreg_wsa_delegate_ip"].Value + } + + $clusterVipsObject = @() + $clusterVipsObject += [pscustomobject]@{ + 'type' = "vidm-lb" + 'properties' = ($clusterLbProperties | Select-Object -Skip 0) + } + $clusterVipsObject += [pscustomobject]@{ + 'type' = "vidm-delegate" + 'properties' = ($clusterDelegateObject | Select-Object -Skip 0) + } + + $clusterObject = @() + $clusterObject += [pscustomobject]@{ + 'clusterVips' = $clusterVipsObject + } + + #### Generate vRealize Log Insight Node Details + $wsaPrimaryProperties = @() + $wsaPrimaryProperties += [pscustomobject]@{ + 'hostName' = $pnpWorkbook.Workbook.Names["xreg_wsa_nodea_fqdn"].Value + 'vmName' = $pnpWorkbook.Workbook.Names["xreg_wsa_nodea_hostname"].Value + 'ip' = $pnpWorkbook.Workbook.Names["xreg_wsa_nodea_ip"].Value + } + + $wsaSecondary1Properties = @() + $wsaSecondary1Properties += [pscustomobject]@{ + 'hostName' = $pnpWorkbook.Workbook.Names["xreg_wsa_nodeb_fqdn"].Value + 'vmName' = $pnpWorkbook.Workbook.Names["xreg_wsa_nodeb_hostname"].Value + 'ip' = $pnpWorkbook.Workbook.Names["xreg_wsa_nodeb_ip"].Value + } + + $wsaSecondary2Properties = @() + $wsaSecondary2Properties += [pscustomobject]@{ + 'hostName' = $pnpWorkbook.Workbook.Names["xreg_wsa_nodec_fqdn"].Value + 'vmName' = $pnpWorkbook.Workbook.Names["xreg_wsa_nodec_hostname"].Value + 'ip' = $pnpWorkbook.Workbook.Names["xreg_wsa_nodec_ip"].Value + } + + $nodesObject = @() + $nodesobject += [pscustomobject]@{ + 'type' = "vidm-primary" + 'properties' = ($wsaPrimaryProperties | Select-Object -Skip 0) + } + $nodesobject += [pscustomobject]@{ + 'type' = "vidm-secondary" + 'properties' = ($wsaSecondary1Properties | Select-Object -Skip 0) + } + $nodesobject += [pscustomobject]@{ + 'type' = "vidm-secondary" + 'properties' = ($wsaSecondary2Properties | Select-Object -Skip 0) + } - Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$datacenterVmid, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vcenterName, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$environments - ) + #### Generate the vRealize Log Insight Properties Section + $vcfVersion = ((Get-VCFManager).version -Split ('\.\d{1}\-\d{8}')) -split '\s+' -match '\S' + if ($vcfVersion -eq "4.3.0") { $wsaVersion = "3.3.5"} + if ($vcfVersion -eq "4.3.1") { $wsaVersion = "3.3.5"} + if ($vcfVersion -eq "4.4.0") { $wsaVersion = "3.3.6"} + $productsObject = @() + $productsObject += [pscustomobject]@{ + 'id' = "vidm" + 'version' = $wsaVersion + 'properties' = ($productPropertiesObject | Select-Object -Skip 0) + 'clusterVIP' = ($clusterObject | Select-Object -Skip 0) + 'nodes' = $nodesObject + } + + $wsaDeploymentObject = @() + $wsaDeploymentObject += [pscustomobject]@{ + 'environmentId' = "globalenvironment" + 'environmentName' = "globalenvironment" + 'infrastructure' = ($infrastructureObject | Select-Object -Skip 0) + 'products' = $productsObject + } - Try { - if ($PsBoundParameters.ContainsKey("datacenterVmid") -and $PsBoundParameters.ContainsKey("vcenterName")) { - $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/datacenters/$datacenterVmid/vcenters/$vcenterName" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders - $response - } - elseif ($PsBoundParameters.ContainsKey("datacenterVmid") -and $PsBoundParameters.ContainsKey("vcenterName") -and $PsBoundParameters.ContainsKey("environments")) { - $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/datacenters/$datacenterVmid/vcenters/$vcenterName/environments" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders - $response - } - else { - $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/datacenters/$datacenterVmid/vcenters" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders - $response + $wsaDeploymentObject | ConvertTo-Json -Depth 12 | Out-File -Encoding UTF8 -FilePath "wsaDeploymentSpec.json" + + Write-Output "Creation of Deployment JSON Specification file for Clustered Workspace ONE Access: SUCCESSFUL" + } + else { + Write-Error "Datacenter Provided in the Planning and Preparation Workbook '$($pnpWorkbook.Workbook.Names["vrslcm_xreg_dc"].Value)' does not exist, create and retry" + } + } + else { + Write-Error "Root Password with alias '$($pnpWorkbook.Workbook.Names["local_admin_password_alias"].Value)' not found in the vRealize Suite Lifecycle Manager Locker, add and retry" + } + } + else { + Write-Error "Admin Password with alias '$($pnpWorkbook.Workbook.Names["global_env_admin_password_alias"].Value)' not found in the vRealize Suite Lifecycle Manager Locker, add and retry" + } + } + else { + Write-Error "Certificate with alias '$($pnpWorkbook.Workbook.Names["local_configadmin_password_alias"].Value)' not found in the vRealize Suite Lifecycle Manager Locker, add and retry" + } + } + else { + Write-Error "Certificate with alias '$($pnpWorkbook.Workbook.Names["xreg_wsa_cert_name"].Value)' not found in the vRealize Suite Lifecycle Manager Locker, add and retry" + } + } + } + } + } } + Close-ExcelPackage $pnpWorkbook -NoSave -ErrorAction SilentlyContinue } Catch { - Write-Error $_.Exception.Message + Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Get-vRSLCMDatacenterVcenter +Export-ModuleMember -Function Export-WsaJsonSpec -Function Add-vRSLCMDatacenterVcenter { +Function New-WSADeployment { <# .SYNOPSIS - Add a vCenter Server to a Datacenter in vRealize Suite Lifecycle Manager + Deploy Clustered Workspace ONE Access to vRealize Suite Lifecycle Manager .DESCRIPTION - The Add-vRSLCMDatacenterVcenter cmdlet adds a vCenter Servers to a Datacenter in vRealize Suite Lifecycle Manager + The New-WSADeployment cmdlet deploys Clustered Workspace ONE Access via vRealize Suite Lifecycle Manager. The + cmdlet connects to SDDC Manager using the -server, -user, and -password values: + - Validates that network connectivity is available to the SDDC Manager instance + - Makes a connection to the SDDC Manager instance and validates that authentication possible + - Validates that Clustered Workspace ONE Access has not been deployed in VMware Cloud Foundation aware mode + - Requests a new deployment of Clustered Workspace ONE Access .EXAMPLE - Add-vRSLCMDatacenterVcenter -datacenterVmid -vcenterFqdn -userLockerAlias - This example adds a vCenter Server to a Datacenter + New-WSADeployment -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -workbook .\pnp-workbook.xlsx + This example starts a deployment of Clustered Workspace ONE Access using the Planning and Preparation Workbook #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$datacenterVmid, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vcenterFqdn, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$userLockerAlias + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$workbook, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$monitor ) + if (!$PsBoundParameters.ContainsKey("workbook")) { + $workbook = Get-ExternalFileName -title "Select the Planning and Preparation Workbook (.xlsx)" -fileType "xlsx" -location "default" + } + else { + if (!(Test-Path -Path $workbook)) { + Write-Error "Planning and Preparation Workbook (.xlsx) '$workbook' File Not Found" + Break + } + } + Try { - $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/datacenters/$datacenterVmid/vcenters" - $body = '{ - "vCenterHost": "' + $vcenterFqdn + '", - "vCenterName": "' + ($vcenterFqdn.Split("."))[0] + '", - "vcPassword": "locker:password:' + (Get-vRSLCMLockerPassword -alias $userLockerAlias).vmid + ':' + $userLockerAlias + '", - "vcUsedAs": "MANAGEMENT", - "vcUsername": "' + (Get-vRSLCMLockerPassword -alias $userLockerAlias).userName +'" - }' - $response = Invoke-RestMethod $uri -Method 'POST' -Headers $vrslcmHeaders -Body $body - $response + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-vRSLCMConnection -server $vcfVrslcmDetails.fqdn) { + if (Test-vRSLCMAuthentication -server $vcfVrslcmDetails.fqdn -user $vcfVrslcmDetails.adminUser -pass $vcfVrslcmDetails.adminPass) { + Export-WSAJsonSpec -server $server -user $user -pass $pass -workbook $workbook | Out-Null + $json = (Get-Content -Raw .\wsaDeploymentSpec.json) + $jsonSpec = $json | ConvertFrom-Json + if (!(Get-vRSLCMEnvironment | Where-Object {$_.environmentName -eq $jsonSpec.environmentName})) { + if (Get-vRSLCMLockerPassword -alias $($jsonSpec.products.properties.vidmAdminPassword.Split(":")[3])) { + if (Get-vRSLCMLockerPassword -alias $($jsonSpec.products.properties.defaultConfigurationPassword.Split(":")[3])) { + if (Get-vRSLCMLockerCertificate | Where-Object {$_.alias -Match $($jsonSpec.products.properties.certificate.Split(":")[3])}) { + $newRequest = Add-vRSLCMEnvironment -json $json + if ($newRequest) { + if ($PsBoundParameters.ContainsKey("monitor")) { + Start-Sleep 10 + Watch-vRSLCMRequest -vmid $($newRequest.requestId) + } + else { + Write-Output "Deployment Rquest for Clustered Workspace ONE Access (Request Ref: $($newRequest.requestId))" + } + } + else { + Write-Error "Request to deploy Clustered Workspace ONE Access failed, check the vRealize Suite Lifecycle Manager UI" + } + + } + else { + Write-Error "Certificate in vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($($jsonSpec.products.properties.certificate.Split(":")[3])), does not exist: FAILED" + } + } + else { + Write-Error "Password in vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($($jsonSpec.products.properties.defaultConfigurationPassword.Split(":")[3])), does not exist: FAILED" + } + } + else { + Write-Error "Password in vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($($jsonSpec.products.properties.vidmAdminPassword.Split(":")[3])), does not exist: FAILED" + } + } + else { + Write-Warning "Clustered Workspace ONE Access in environment ($($jsonSpec.environmentName)) on vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)), already exists: SKIPPED" + } + } + } + } + } + } } Catch { - Write-Error $_.Exception.Message + Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-vRSLCMDatacenterVcenter +Export-ModuleMember -Function New-WSADeployment -Function Get-vRSLCMEnvironment { +Function Set-WorkspaceOneApplianceNtpConfig { <# .SYNOPSIS - Get paginated list of environments in vRealize Suite Lifecycle Manager + Configure Workspace ONE Access appliance NTP servers .DESCRIPTION - The Get-vRSLCMEnvironment cmdlet gets a paginated list of environments in vRealize Suite Lifecycle Manager + The Set-WorkspaceOneApplianceNtpConfig cmdlet configures Workspace ONE Access appliance NTP servers .EXAMPLE - Get-vRSLCMEnvironment - This example gets all environments in vRealize Suite Lifecycle Manager + Set-WorkspaceOneApplianceNtpConfig -vmName sfo-wsa01 -rootPass VMw@re1! -ntpServer "ntp.sfo.rainpole.io,ntp.lax.rainpole.io" + This example sets the NTP servers for Workspace ONE Access node sfo-wsa01 to ntp.sfo.rainpole.io and ntp.lax.rainpole.io #> Param ( - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vmid + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vmName, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$rootPass, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$ntpServer ) - Try { - if ($PsBoundParameters.ContainsKey("vmid")) { - $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/environments/$vmid" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders - $response + try { + $scriptCommand = '/usr/local/horizon/scripts/ntpServer.hzn --get' + $output = Invoke-VMScript -VM $vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $rootPass -Server $vcfVcenterDetails.fqdn + if ($output.ScriptOutput -match "^server=$ntpServer$") { + Write-Warning "Configuring NTP on Workspace ONE Access Instance ($vmName) to NTP Server ($ntpServer), already performed: SKIPPED" } else { - $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/environments" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders - $response + $scriptCommand = '/usr/local/horizon/scripts/ntpServer.hzn --set ' + $ntpServer + $output = Invoke-VMScript -VM $vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $rootPass -Server $vcfVcenterDetails.fqdn + $scriptCommand = '/usr/local/horizon/scripts/ntpServer.hzn --get' + $output = Invoke-VMScript -VM $vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $rootPass -Server $vcfVcenterDetails.fqdn + if ($output.ScriptOutput -match "^server=$ntpServer$") { + Write-Output "Configuring NTP on Workspace ONE Access Instance ($vmName) to NTP Server ($ntpServer): SUCCESSFUL" + } + else { + Write-Error "Configuring NTP on Workspace ONE Access Instance ($vmName) to NTP Server ($ntpServer): POST_VALIDATION_FAILED" + } } } - Catch { + catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-vRSLCMEnvironment +Export-ModuleMember -Function Set-WorkspaceOneApplianceNtpConfig -Function Add-vRSLCMEnvironment { +Function New-vRSLCMAdapterOperation { <# .SYNOPSIS - Create an environment in vRealize Suite Lifecycle Manager + Add a vRealize Operations Adapter via vRealize Suite Lifecycle Manager .DESCRIPTION - The Add-vRSLCMEnvironment cmdlet to create an environment in vRealize Suite Lifecycle Manager - - .EXAMPLE - Add-vRSLCMEnvironment -json (Get-Content -Raw .\vrli.json) - This example creates an environment in vRealize Suite Lifecycle Manager + The New-vRSLCMAdapterOperation cmdlet to create a vRealize Operations Manager Afapter in vRealize Suite Lifecycle Manager .EXAMPLE - Add-vRSLCMEnvironment -json (Get-Content -Raw .\vrli.json) -vmid c907c25b-1c61-465b-b7cb-4100ac1ce331 -addProduct - This example adds a new product to an existing environment in vRealize Suite Lifecycle Manager + New-vRSLCMAdapterOperation -json .\addAdapter.json + This example creates an adapter in vRealize Operations via vRealize Suite Lifecycle Manager #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$json, - [Parameter (Mandatory = $false, ParameterSetName = 'growth')] [ValidateNotNullOrEmpty()] [String]$environmentId, - [Parameter (Mandatory = $false, ParameterSetName = 'growth')] [ValidateNotNullOrEmpty()] [Switch]$addProduct + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$environmentId ) Try { - if ($PsBoundParameters.ContainsKey("json") -and ($PsBoundParameters.ContainsKey("addProduct")) -and ($PsBoundParameters.ContainsKey("environmentId"))) { - $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/environments/$environmentId/products" - $response = Invoke-RestMethod $uri -Method 'POST' -Headers $vrslcmHeaders -Body $json - $response - } - else { - $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/environments" - $response = Invoke-RestMethod $uri -Method 'POST' -Headers $vrslcmHeaders -Body $json - $response + if ($PsBoundParameters.ContainsKey("json")) { + if (!(Test-Path $json)) { + Throw "JSON File Not Found" + } + else { + $body = (Get-Content $json) # Read the json file contents into the $body variable + } } + + $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/environments/$environmentId/vrops/adapterOperation" + $response = Invoke-RestMethod -Method 'POST' -Uri $Uri -Headers $vrslcmHeaders -Body $body + $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Add-vRSLCMEnvironment +Export-ModuleMember -Function New-vRSLCMAdapterOperation -Function Get-vRSLCMRequest { +Function Get-vRSLCMProductNtpServer { <# .SYNOPSIS - Get all Requests + Get paginated list of product NTP servers in vRealize Suite Lifecycle Manager .DESCRIPTION - The Get-vRSLCMRequest cmdlet gets all requests in vRealize Suite Lifecycle Manager + The Get-vRSLCMProductNtpServer cmdlet gets a paginated list of product NTP servers in vRealize Suite Lifecycle Manager .EXAMPLE - Get-vRSLCMRequest - This example gets all requests vRealize Suite Lifecycle Manager - - .EXAMPLE - Get-vRSLCMRequest -requestId 0ee1a4a0-203a-4c87-a40e-65d9a450e398 - This example gets the request by id from vRealize Suite Lifecycle Manager - - .EXAMPLE - Get-vRSLCMRequest -requestId 0ee1a4a0-203a-4c87-a40e-65d9a450e398 -errorCauses - This example gets the errors for a request by id from vRealize Suite Lifecycle Manager + Get-vRSLCMProductNtpServer + This example gets all product NTP servers in vRealize Suite Lifecycle Manager #> Param ( - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$requestId, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$errorCauses + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$ntpServer ) Try { - if ($PsBoundParameters.ContainsKey("requestId")) { - $uri = "https://$vrslcmAppliance/lcm/request/api/v2/requests/$requestId" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders - $response - } - elseif ($PsBoundParameters.ContainsKey("errorCauses")) { - $uri = "https://$vrslcmAppliance/lcm/request/api/v2/requests/$requestId/error-causes" + if ($PsBoundParameters.ContainsKey("ntpServer")) { + $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/settings/ntp-servers" $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders - $response + $response | Where-Object {$_.hostName -match $ntpServer} } else { - $uri = "https://$vrslcmAppliance/lcm/request/api/v2/requests" + $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/settings/ntp-servers" $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders - $response | Select-Object -Property vmid, state, requestReason, requestType + $response } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-vRSLCMRequest +Export-ModuleMember -Function Get-vRSLCMProductNtpServer -Function Remove-vRSLCMRequest { +Function Remove-vRSLCMProductNtpServer { <# .SYNOPSIS - Delete a Request + Removes a specified NTP server from vRealize Suite Lifecycle Manager .DESCRIPTION - The Remove-vRSLCMRequest cmdlet removes a request from vRealize Suite Lifecycle Manager + The Remove-vRSLCMProductNtpServer cmdlet removes a specified NTP server from vRealize Suite Lifecycle Manager .EXAMPLE - Remove-vRSLCMRequest -requestId - This example removes a request from vRealize Suite Lifecycle Manager + Remove-vRSLCMProductNtpServer -ntpServer ntp.lax.rainpole.io + This example gets all product NTP servers in vRealize Suite Lifecycle Manager #> Param ( - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$requestId ) + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$ntpServer + ) Try { - - $uri = "https://$vrslcmAppliance/lcm/request/requests/$requestId" + $uri = "https://$vrslcmAppliance/lcm/lcops/api/v3/settings/ntp-servers?ntpHostname=$ntpServer" $response = Invoke-RestMethod $uri -Method 'DELETE' -Headers $vrslcmHeaders $response } @@ -17591,378 +20476,231 @@ Function Remove-vRSLCMRequest { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Remove-vRSLCMRequest +Export-ModuleMember -Function Remove-vRSLCMProductNtpServer -Function Watch-vRSLCMRequest { +Function Get-vRSLCMApplianceNtpConfig { <# .SYNOPSIS - Poll request + Get appliance NTP configuration in vRealize Suite Lifecycle Manager .DESCRIPTION - The Watch-vRSLCMRequest cmdlet polls a request in vRealize Suite Lifecycle Manager + The Get-vRSLCMApplianceNtpConfig cmdlet gets appliance NTP configuration in vRealize Suite Lifecycle Manager + .EXAMPLE - Watch-vRSLCMRequest -vmid - This example polls the request in vRealize Suite Lifecycle Manager + Get-vRSLCMApplianceNtpConfig + This example gets the appliance NTP configuration in vRealize Suite Lifecycle Manager #> - Param ( - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vmid - ) - Try { - Do { - $requestStatus = (Get-vRSLCMRequest | Where-Object {$_.vmid -eq $vmid}).state - } - Until ($requestStatus -ne "INPROGRESS") - Write-Output "vRealize Suite Lifecycle Manager request: $vmid completed with the following state: $requestStatus" + + $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/settings/system-details/time" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders + $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Watch-vRSLCMRequest +Export-ModuleMember -Function Get-vRSLCMApplianceNtpConfig -Function Resume-vRSLCMRequest { +Function Add-vRSLCMProductNtpServer { <# .SYNOPSIS - Retry a request + Add a server to product NTP configuration in vRealize Suite Lifecycle Manager .DESCRIPTION - The Resume-vRSLCMRequest cmdlet reties a request + The Add-vRSLCMProductNtpServer cmdlet adds a server tp product NTP configuration in vRealize Suite Lifecycle Manager .EXAMPLE - Resume-vRSLCMRequest -requestId 0ee1a4a0-203a-4c87-a40e-65d9a450e398 - This example reties the request based on the request ID provided + Add-vRSLCMProductNtpServer -ntpServer "ntp.lax.rainpole.io" -ntpServerDesc "VCF NTP Server 2" + This adds the server ntp.lax.rainpole.io to the product NTP configuration in vRealize Suite Lifecycle Manager #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$requestId + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ntpServer, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ntpServerDesc ) + $body = @" +{ + "hostName": "$ntpServer", + "name": "$ntpServerDesc" +} +"@ + Try { - $uri = "https://$vrslcmAppliance/lcm/request/api/v2/requests/$requestId/retry" - $response = Invoke-RestMethod $uri -Method 'PATCH' -Headers $vrslcmHeaders - $response - } + $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/settings/ntp-servers" + $response = Invoke-RestMethod $uri -Method 'POST' -Headers $vrslcmHeaders -Body $body + $response + } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Resume-vRSLCMRequest +Export-ModuleMember -Function Add-vRSLCMProductNtpServer -Function Export-WsaJsonSpec { +Function Add-vRSLCMApplianceNtpConfig { <# .SYNOPSIS - Create Clustered Workspace ONE Access JSON specification + Add a server to appliance NTP configuration in vRealize Suite Lifecycle Manager .DESCRIPTION - The Export-WsaJsonSpec cmdlet creates the JSON specification file using the Planning and Preparation workbook - to deploy Clustered Workspace ONE Access using vRealize Suite Lifecycle Manager: - - Validates that the Planning and Preparation is available - - Validates that network connectivity is available to vRealize Suite Lifecycle Manager - - Makes a connection to the vRealize Suite Lifecycle Manager instance and validates that authentication possible - - Generates the JSON specification file using the Planning and Preparation workbook and details from vRealize Suite Lifecycle Manager + The Add-vRSLCMApplianceNtpConfig cmdlet adds a server to appliance NTP configuration in vRealize Suite Lifecycle Manager .EXAMPLE - Export-WsaJsonSpec -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -workbook .\pnp-workbook.xlsx - This example creates a JSON deployment specification of Clustered Workspace ONE Access using the Planning and Preparation Workbook + Add-vRSLCMApplianceNtpConfig -ntpServer ntp.lax.rainpole.io + This adds the server ntp.lax.rainpole.io to the appliance NTP configuration in vRealize Suite Lifecycle Manager #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$workbook + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ntpServer ) - Try { - - if (!$PsBoundParameters.ContainsKey("workbook")) { - $workbook = Get-ExternalFileName -title "Select the Planning and Preparation Workbook (.xlsx)" -fileType "xlsx" -location "default" - } - else { - if (!(Test-Path -Path $workbook)) { - Write-Error "Planning and Preparation Workbook (.xlsx) '$workbook' File Not Found" - Break - } - } - - $pnpWorkbook = Open-ExcelPackage -Path $workbook - - ### Obtain Configuration Information from vRealize Suite Lifecycle Manager - if (Test-VCFConnection -server $server) { - if (Test-VCFAuthentication -server $server -user $user -pass $pass) { - if (($vcfVrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass)) { - if (Test-vRSLCMConnection -server $vcfVrslcmDetails.fqdn) { - if (Test-vRSLCMAuthentication -server $vcfVrslcmDetails.fqdn -user $vcfVrslcmDetails.adminUser -pass $vcfVrslcmDetails.adminPass) { - if ($wsaCertificate = Get-vRSLCMLockerCertificate | Where-Object {$_.alias -eq $pnpWorkbook.Workbook.Names["xreg_wsa_cert_name"].Value}) { - if ($defaultPassword = Get-vRSLCMLockerPassword -alias $pnpWorkbook.Workbook.Names["global_env_admin_password_alias"].Value) { - if ($configAdminPassword = Get-vRSLCMLockerPassword -alias $pnpWorkbook.Workbook.Names["local_configadmin_password_alias"].Value) { - if ($wsaPassword = Get-vRSLCMLockerPassword -alias $pnpWorkbook.Workbook.Names["local_admin_password_alias"].Value) { - $vcCredentials = Get-vRSLCMLockerPassword -alias (($pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value).Split(".")[0] + "-" + $pnpWorkbook.Workbook.Names["mgmt_datacenter"].Value) - if ($datacenterName = Get-vRSLCMDatacenter | Where-Object {$_.dataCenterName -eq $pnpWorkbook.Workbook.Names["vrslcm_xreg_dc"].Value}) { - $xintEnvironment = Get-vRSLCMEnvironment | Where-Object {$_.environmentName -eq $pnpWorkbook.Workbook.Names["vrslcm_xreg_env"].Value} - $infrastructurePropertiesObject = @() - $infrastructurePropertiesObject += [pscustomobject]@{ - 'acceptEULA' = "true" - 'enableTelemetry' = "true" - 'regionName' = "default" - 'zoneName' = "default" - 'dataCenterVmid' = $datacenterName.dataCenterVmid - 'vCenterName' = ($pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value).Split(".")[0] - 'vCenterHost' = $pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value - 'vcUsername' = $vcCredentials.userName - 'vcPassword' = ("locker:password:" + $($vcCredentials.vmid) + ":" + $($vcCredentials.alias)) - 'defaultPassword' = ("locker:password:" + $($defaultPassword.vmid) + ":" + $($defaultPassword.alias)) - 'certificate' = ("locker:certificate:" + $($wsaCertificate.vmid) + ":" + $($wsaCertificate.alias)) - 'cluster' = ($pnpWorkbook.Workbook.Names["mgmt_datacenter"].Value + "#" + $pnpWorkbook.Workbook.Names["mgmt_cluster"].Value) - 'storage' = $pnpWorkbook.Workbook.Names["mgmt_vsan_datastore"].Value - 'diskMode' = "thin" - 'network' = $pnpWorkbook.Workbook.Names["xreg_seg01_name"].Value - 'masterVidmEnabled' = "false" - 'dns' = ($pnpWorkbook.Workbook.Names["region_dns1_ip"].Value + "," + $pnpWorkbook.Workbook.Names["region_dns2_ip"].Value) - 'domain' = $pnpWorkbook.Workbook.Names["region_ad_parent_fqdn"].Value - 'gateway' = $pnpWorkbook.Workbook.Names["xreg_seg01_gateway_ip"].Value - 'netmask' = $pnpWorkbook.Workbook.Names["xreg_seg01_mask"].Value - 'searchpath' = $pnpWorkbook.Workbook.Names["parent_dns_zone"].Value - 'timeSyncMode' = "ntp" - 'ntp' = $pnpWorkbook.Workbook.Names["xregion_ntp1_server"].Value - 'vcfProperties' = '{"vcfEnabled":true,"sddcManagerDetails":[{"sddcManagerHostName":"' + $pnpWorkbook.Workbook.Names["sddc_mgr_fqdn"].Value + '","sddcManagerName":"default","sddcManagerVmid":"default"}]}' - } - - $infrastructureObject = @() - $infrastructureObject += [pscustomobject]@{ - 'properties' = ($infrastructurePropertiesObject | Select-Object -Skip 0) - } - - ### Generate the Properties Details - $productPropertiesObject = @() - $productPropertiesObject += [pscustomobject]@{ - 'vidmAdminPassword' = ("locker:password:" + $($wsaPassword.vmid) + ":" + $($wsaPassword.alias)) - 'syncGroupMembers' = $true - 'nodeSize' = ($pnpWorkbook.Workbook.Names["xreg_wsa_node_size"].Value).ToLower() - 'defaultConfigurationEmail' = $pnpWorkbook.Workbook.Names["xreg_configadmin_email"].Value - 'defaultConfigurationUsername' = $pnpWorkbook.Workbook.Names["local_configadmin_username"].Value - 'defaultConfigurationPassword' = ("locker:password:" + $($configAdminPassword.vmid) + ":" + $($configAdminPassword.alias)) - 'defaultTenantAlias' = "" - 'vidmDomainName' = "" - 'certificate' = ("locker:certificate:" + $($wsaCertificate.vmid) + ":" + $($wsaCertificate.alias)) - 'contentLibraryItemId' = "" - 'fipsMode' = "false" - } - - #### Generate Workspace ONE Access Cluster Details - $clusterLbProperties = @() - $clusterLbProperties += [pscustomobject]@{ - 'hostName' = $pnpWorkbook.Workbook.Names["xreg_wsa_virtual_fqdn"].Value - 'lockerCertificate' = ("locker:certificate:" + $($wsaCertificate.vmid) + ":" + $($wsaCertificate.alias)) - } - - $clusterDelegateObject = @() - $clusterDelegateObject += [pscustomobject]@{ - 'ip' = $pnpWorkbook.Workbook.Names["xreg_wsa_delegate_ip"].Value - } - - $clusterVipsObject = @() - $clusterVipsObject += [pscustomobject]@{ - 'type' = "vidm-lb" - 'properties' = ($clusterLbProperties | Select-Object -Skip 0) - } - $clusterVipsObject += [pscustomobject]@{ - 'type' = "vidm-delegate" - 'properties' = ($clusterDelegateObject | Select-Object -Skip 0) - } - - $clusterObject = @() - $clusterObject += [pscustomobject]@{ - 'clusterVips' = $clusterVipsObject - } - - #### Generate vRealize Log Insight Node Details - $wsaPrimaryProperties = @() - $wsaPrimaryProperties += [pscustomobject]@{ - 'hostName' = $pnpWorkbook.Workbook.Names["xreg_wsa_nodea_fqdn"].Value - 'vmName' = $pnpWorkbook.Workbook.Names["xreg_wsa_nodea_hostname"].Value - 'ip' = $pnpWorkbook.Workbook.Names["xreg_wsa_nodea_ip"].Value - } + $existingNtpServers = (Get-vRSLCMApplianceNtpConfig).ntpServers - $wsaSecondary1Properties = @() - $wsaSecondary1Properties += [pscustomobject]@{ - 'hostName' = $pnpWorkbook.Workbook.Names["xreg_wsa_nodeb_fqdn"].Value - 'vmName' = $pnpWorkbook.Workbook.Names["xreg_wsa_nodeb_hostname"].Value - 'ip' = $pnpWorkbook.Workbook.Names["xreg_wsa_nodeb_ip"].Value - } + $body = @" +{ + "syncWithHost": false, + "ntpServerEnabled": true, + "ntpServers": "$existingNtpServers,$ntpServer" +} +"@ - $wsaSecondary2Properties = @() - $wsaSecondary2Properties += [pscustomobject]@{ - 'hostName' = $pnpWorkbook.Workbook.Names["xreg_wsa_nodec_fqdn"].Value - 'vmName' = $pnpWorkbook.Workbook.Names["xreg_wsa_nodec_hostname"].Value - 'ip' = $pnpWorkbook.Workbook.Names["xreg_wsa_nodec_ip"].Value - } + Try { + $uri = "https://$vrslcmAppliance/lcm/lcops/api/settings/ntpsetting" + $response = Invoke-RestMethod $uri -Method 'POST' -Headers $vrslcmHeaders -Body $body + $response + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Add-vRSLCMApplianceNtpConfig - $nodesObject = @() - $nodesobject += [pscustomobject]@{ - 'type' = "vidm-primary" - 'properties' = ($wsaPrimaryProperties | Select-Object -Skip 0) - } - $nodesobject += [pscustomobject]@{ - 'type' = "vidm-secondary" - 'properties' = ($wsaSecondary1Properties | Select-Object -Skip 0) - } - $nodesobject += [pscustomobject]@{ - 'type' = "vidm-secondary" - 'properties' = ($wsaSecondary2Properties | Select-Object -Skip 0) - } +Function Set-vRSLCMApplianceNtpConfig { + <# + .SYNOPSIS + Sets the appliance NTP configuration in vRealize Suite Lifecycle Manager to use only a specified NTP server - #### Generate the vRealize Log Insight Properties Section - $vcfVersion = ((Get-VCFManager).version -Split ('\.\d{1}\-\d{8}')) -split '\s+' -match '\S' - if ($vcfVersion -eq "4.3.0") { $wsaVersion = "3.3.5"} - if ($vcfVersion -eq "4.3.1") { $wsaVersion = "3.3.5"} - if ($vcfVersion -eq "4.4.0") { $wsaVersion = "3.3.6"} - $productsObject = @() - $productsObject += [pscustomobject]@{ - 'id' = "vidm" - 'version' = $wsaVersion - 'properties' = ($productPropertiesObject | Select-Object -Skip 0) - 'clusterVIP' = ($clusterObject | Select-Object -Skip 0) - 'nodes' = $nodesObject - } - - $wsaDeploymentObject = @() - $wsaDeploymentObject += [pscustomobject]@{ - 'environmentId' = "globalenvironment" - 'environmentName' = "globalenvironment" - 'infrastructure' = ($infrastructureObject | Select-Object -Skip 0) - 'products' = $productsObject - } + .DESCRIPTION + The Set-vRSLCMApplianceNtpConfig cmdlet sets the appliance NTP configuration in vRealize Suite Lifecycle Manager to use only a specified NTP server - $wsaDeploymentObject | ConvertTo-Json -Depth 12 | Out-File -Encoding UTF8 -FilePath "wsaDeploymentSpec.json" - - Write-Output "Creation of Deployment JSON Specification file for Clustered Workspace ONE Access: SUCCESSFUL" - } - else { - Write-Error "Datacenter Provided in the Planning and Preparation Workbook '$($pnpWorkbook.Workbook.Names["vrslcm_xreg_dc"].Value)' does not exist, create and retry" - } - } - else { - Write-Error "Root Password with alias '$($pnpWorkbook.Workbook.Names["local_admin_password_alias"].Value)' not found in the vRealize Suite Lifecycle Manager Locker, add and retry" - } - } - else { - Write-Error "Admin Password with alias '$($pnpWorkbook.Workbook.Names["global_env_admin_password_alias"].Value)' not found in the vRealize Suite Lifecycle Manager Locker, add and retry" - } - } - else { - Write-Error "Certificate with alias '$($pnpWorkbook.Workbook.Names["local_configadmin_password_alias"].Value)' not found in the vRealize Suite Lifecycle Manager Locker, add and retry" - } - } - else { - Write-Error "Certificate with alias '$($pnpWorkbook.Workbook.Names["xreg_wsa_cert_name"].Value)' not found in the vRealize Suite Lifecycle Manager Locker, add and retry" - } - } - } - } - } + .EXAMPLE + Add-vRSLCMApplianceNtpConfig -ntpServer ntp.sfo.rainpole.io + This sets the appliance NTP configuration in vRealize Suite Lifecycle Manager to use only NTP server ntp.sfo.rainpole.io. + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ntpServer + ) + $body = @" +{ + "syncWithHost": false, + "ntpServerEnabled": true, + "ntpServers": "$ntpServer" +} +"@ + + Try { + $uri = "https://$vrslcmAppliance/lcm/lcops/api/settings/ntpsetting" + $response = Invoke-RestMethod $uri -Method 'POST' -Headers $vrslcmHeaders -Body $body + $response } - Close-ExcelPackage $pnpWorkbook -NoSave -ErrorAction SilentlyContinue + Catch { + Write-Error $_.Exception.Message } +} +Export-ModuleMember -Function Set-vRSLCMApplianceNtpConfig + +Function Get-vRSLCMProductNode { + <# + .SYNOPSIS + Gets the nodes in the vRealize Suite Lifecycle Manager inventory for a specified environment and product + + .DESCRIPTION + The Get-vRSLCMProductNode cmdlet gets the nodes in the vRealize Suite Lifecycle Manager inventory for a specified environment and product + + .EXAMPLE + Get-vRSLCMProductNode -environmentName globalenvironment -product vidm + This returns a list of nodes in the Workspace ONE Access instance managed by vRealize Suite Lifecycle Manager + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$environmentName, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$product + ) + + $environmentId = (Get-vRSLCMEnvironment | Where-Object {$_.environmentName -match $environmentName}).environmentId + + Try { + $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/environments/$environmentId/products/$product/deployed-vms" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders + $response + } Catch { - Debug-ExceptionWriter -object $_ + Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Export-WsaJsonSpec +Export-ModuleMember -Function Get-vRSLCMProductNode -Function New-WSADeployment { +Function Stop-vRSLCMProductNode { <# .SYNOPSIS - Deploy Clustered Workspace ONE Access to vRealize Suite Lifecycle Manager + Shuts down nodes in a vRealize Suite Lifecycle Manager-managed product .DESCRIPTION - The New-WSADeployment cmdlet deploys Clustered Workspace ONE Access via vRealize Suite Lifecycle Manager. The - cmdlet connects to SDDC Manager using the -server, -user, and -password values: - - Validates that network connectivity is available to the SDDC Manager instance - - Makes a connection to the SDDC Manager instance and validates that authentication possible - - Validates that Clustered Workspace ONE Access has not been deployed in VMware Cloud Foundation aware mode - - Requests a new deployment of Clustered Workspace ONE Access + The Stop-vRSLCMProductNode cmdlet shuts down nodes in a vRealize Suite Lifecycle Manager-managed product .EXAMPLE - New-WSADeployment -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -workbook .\pnp-workbook.xlsx - This example starts a deployment of Clustered Workspace ONE Access using the Planning and Preparation Workbook + Stop-vRSLCMProductNode -environment globalenvironment -product vidm + This example shuts down all nodes in the Workspace ONE Access instance managed by vRealize Suite Lifecycle Manager #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$workbook, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$monitor + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$environment, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$product ) - if (!$PsBoundParameters.ContainsKey("workbook")) { - $workbook = Get-ExternalFileName -title "Select the Planning and Preparation Workbook (.xlsx)" -fileType "xlsx" -location "default" + Try { + $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/environments/$environment/products/$product/power-off" + $response = Invoke-RestMethod $uri -Method 'POST' -Headers $vrslcmHeaders + $response } - else { - if (!(Test-Path -Path $workbook)) { - Write-Error "Planning and Preparation Workbook (.xlsx) '$workbook' File Not Found" - Break - } + Catch { + Write-Error $_.Exception.Message } +} +Export-ModuleMember -Function Stop-vRSLCMProductNode + +Function Start-vRSLCMProductNode { + <# + .SYNOPSIS + Starts nodes in a vRealize Suite Lifecycle Manager-managed product + + .DESCRIPTION + The Start-vRSLCMProductNode cmdlet starts nodes in a vRealize Suite Lifecycle Manager-managed product + + .EXAMPLE + Start-vRSLCMProductNode -environment globalenvironment -product vidm + This example starts all nodes in the Workspace ONE Access instance managed by vRealize Suite Lifecycle Manager + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$environment, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$product + ) Try { - if (Test-VCFConnection -server $server) { - if (Test-VCFAuthentication -server $server -user $user -pass $pass) { - if (($vcfVrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass)) { - if (Test-vRSLCMConnection -server $vcfVrslcmDetails.fqdn) { - if (Test-vRSLCMAuthentication -server $vcfVrslcmDetails.fqdn -user $vcfVrslcmDetails.adminUser -pass $vcfVrslcmDetails.adminPass) { - Export-WSAJsonSpec -server $server -user $user -pass $pass -workbook $workbook | Out-Null - $json = (Get-Content -Raw .\wsaDeploymentSpec.json) - $jsonSpec = $json | ConvertFrom-Json - if (!(Get-vRSLCMEnvironment | Where-Object {$_.environmentName -eq $jsonSpec.environmentName})) { - if (Get-vRSLCMLockerPassword -alias $($jsonSpec.products.properties.vidmAdminPassword.Split(":")[3])) { - if (Get-vRSLCMLockerPassword -alias $($jsonSpec.products.properties.defaultConfigurationPassword.Split(":")[3])) { - if (Get-vRSLCMLockerCertificate | Where-Object {$_.alias -Match $($jsonSpec.products.properties.certificate.Split(":")[3])}) { - $newRequest = Add-vRSLCMEnvironment -json $json - if ($newRequest) { - if ($PsBoundParameters.ContainsKey("monitor")) { - Start-Sleep 10 - Watch-vRSLCMRequest -vmid $($newRequest.requestId) - } - else { - Write-Output "Deployment Rquest for Clustered Workspace ONE Access (Request Ref: $($newRequest.requestId))" - } - } - else { - Write-Error "Request to deploy Clustered Workspace ONE Access failed, check the vRealize Suite Lifecycle Manager UI" - } - - } - else { - Write-Error "Certificate in vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($($jsonSpec.products.properties.certificate.Split(":")[3])), does not exist: FAILED" - } - } - else { - Write-Error "Password in vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($($jsonSpec.products.properties.defaultConfigurationPassword.Split(":")[3])), does not exist: FAILED" - } - } - else { - Write-Error "Password in vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($($jsonSpec.products.properties.vidmAdminPassword.Split(":")[3])), does not exist: FAILED" - } - } - else { - Write-Warning "Clustered Workspace ONE Access in environment ($($jsonSpec.environmentName)) on vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)), already exists: SKIPPED" - } - } - } - } - } - } + $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/environments/$environment/products/$product/power-on" + $response = Invoke-RestMethod $uri -Method 'POST' -Headers $vrslcmHeaders + $response } Catch { - Debug-ExceptionWriter -object $_ + Write-Error $_.Exception.Message } } -Export-ModuleMember -Function New-WSADeployment +Export-ModuleMember -Function Start-vRSLCMProductNode ################### End vRealize Suite Lifecycle Manager Functions #################### ######################################################################################## @@ -20079,12 +22817,12 @@ Function Get-vROPSAdapter { Try { if ($PsBoundParameters.ContainsKey("id")) { $uri = "https://$vropsAppliance/suite-api/api/adapters/$id" - $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders + $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vropsHeaders $response } else { $uri = "https://$vropsAppliance/suite-api/api/adapters" - $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders + $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vropsHeaders $response.adapterInstancesInfoDto } } @@ -20108,7 +22846,8 @@ Function Set-vROPSAdapter { #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$json + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$json, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$patch ) Try { @@ -20120,9 +22859,16 @@ Function Set-vROPSAdapter { $body = (Get-Content $json) # Read the json file contents into the $body variable } } - $uri = "https://$vropsAppliance/suite-api/api/adapters" - $response = Invoke-RestMethod -Method 'PUT' -Uri $Uri -Headers $vropsHeaders -Body $body - $response + + if ($PsBoundParameters.ContainsKey("patch")) { + $uri = "https://$vropsAppliance/suite-api/api/adapters" + Invoke-RestMethod -Method 'PATCH' -Uri $uri -Headers $vropsHeaders -Body $body + } + else { + $uri = "https://$vropsAppliance/suite-api/api/adapters" + $response = Invoke-RestMethod -Method 'PUT' -Uri $uri -Headers $vropsHeaders -Body $body + $response + } } Catch { Write-Error $_.Exception.Message @@ -20158,7 +22904,7 @@ Function Add-vROPSAdapter { } $uri = "https://$vropsAppliance/suite-api/api/adapters" - $response = Invoke-RestMethod -Method 'POST' -Uri $Uri -Headers $vropsHeaders -Body $body + $response = Invoke-RestMethod -Method 'POST' -Uri $uri -Headers $vropsHeaders -Body $body $response } Catch { @@ -20178,11 +22924,16 @@ Function Test-vROPSAdapterConnection { .EXAMPLE Test-vROPSAdapterConnection -json This example tests the connection based on the JSON file provided + + .EXAMPLE + Test-vROPSAdapterConnection -json -patch + This example patches the adapter based on the response from the test in JSON format #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$json + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$json, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$patch ) Try { @@ -20195,9 +22946,15 @@ Function Test-vROPSAdapterConnection { } } - $uri = "https://$vropsAppliance/suite-api/api/adapters/testConnection" - $response = Invoke-RestMethod -Method 'POST' -Uri $Uri -Headers $vropsHeaders -Body $body - $response + if ($PsBoundParameters.ContainsKey("patch")) { + $uri = "https://$vropsAppliance/suite-api/api/adapters/testConnection" + Invoke-RestMethod -Method 'PATCH' -Uri $uri -Headers $vropsHeaders -Body $body + } + else { + $uri = "https://$vropsAppliance/suite-api/api/adapters/testConnection" + $response = Invoke-RestMethod -Method 'POST' -Uri $uri -Headers $vropsHeaders -Body $body + $response + } } Catch { Write-Error $_.Exception.Message @@ -21542,15 +24299,14 @@ Function New-vRLIAgentGroup { Param ( [Parameter (Mandatory = $true)] [ValidateSet("wsa","photon")] [ValidateNotNullOrEmpty()] [String]$agentGroupType, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$agentGroupName, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Array]$criteria ) if ($agentGroupType -eq "wsa") { - $agentGroupName = "Workspace ONE Access - Appliance Agent Group" $agentGroupConfig = '[filelog|gb-onprem]\n; IMPORTANT: Change the directory as per the environment\ndirectory=/opt/vmware/horizon/workspace/logs\ninclude=greenbox*.log\nevent_marker=^\\d{4}-\\d{2}-\\d{2}\nparser=gb-parser-onprem\ntags={\"product\":\"vidm-aws\",\"component\":\"greenbox\"}\n\n[parser|gb-parser-onprem]\nbase_parser=clf\nformat=%t %{priority}i (%{thread}i) [%{java_class}i] - %M\n; Analytics Log InSight agent section\n\n[filelog|analytics-onprem]\n; IMPORTANT: Change the directory as per the environment\ndirectory=/opt/vmware/horizon/workspace/logs\ninclude=analytics-*.log\nevent_marker=^\\d{4}-\\d{2}-\\d{2}\nparser=analytics-parser-onprem\ntags={\"product\":\"vidm-aws\",\"component\":\"analytics\"}\n\n[parser|analytics-parser-onprem]\nbase_parser=clf\nformat=%t %{timezone}i %{priority}i %{instance}i:%{service}i (%{thread}i) [%{src_str}i] %{java_class}i - %M\n; Password vault Log InSight agent section\n\n[filelog|pwvault-onprem]\n; IMPORTANT: Change the directory as per the environment\ndirectory=/opt/vmware/horizon/workspace/logs\ninclude=pwvault-*.log\nevent_marker=^\\d{4}-\\d{2}-\\d{2}\nparser=pwvault-parser-onprem\ntags={\"product\":\"vidm-aws\",\"component\":\"pwvault\"}\n\n[parser|pwvault-parser-onprem]\nbase_parser=clf\nformat=%t %{timezone}i %{priority}i %{instance}i:%{service}i (%{thread}i) [%{src_str}i] %{java_class}i - %M\n\n[filelog|cert-proxy-onprem]\n; IMPORTANT: Change the directory as per the environment\ndirectory=/opt/vmware/horizon/workspace/logs\ninclude=cert-proxy*.log\nevent_marker=^\\d{4}-\\d{2}-\\d{2}\nparser=cert-proxy-parser-onprem\ntags={\"product\":\"vidm-aws\",\"component\":\"cert-proxy\"}\n\n[parser|cert-proxy-parser-onprem]\nbase_parser=clf\nformat=%t %{priority}i (%{thread}i) [%{src_str}i] %{java_class}i - %M\n; vIDM SaaS Log InSight agent section\n\n[filelog|vidm-onprem]\n; IMPORTANT: Change the directory as per the environment\ndirectory=/opt/vmware/horizon/workspace/logs\ninclude=*.log\nevent_marker=^\\d{4}-\\d{2}-\\d{2}\nparser=vidm-parser-onprem\ntags={\"product\":\"vidm-aws\",\"component\":\"vidm\"}\n\n[parser|vidm-parser-onprem]\nbase_parser=clf\nformat=%t %{priority}i (%{thread}i) [%{authentication}i] %{java_class}i - %M\nfield_decoder={\"authentication\":\"vidm-authentication-decoder-onprem\",\"log_message\":\"vidm-message-decoder-onprem\"}\nexclude_fields=log_message\n; vIDM SaaS Log InSight agent section for *.txt file\n\n[filelog|vidm-txt-onprem]\n; IMPORTANT: Change the directory as per the environment\ndirectory=/opt/vmware/horizon/workspace/logs\ninclude=*.txt\nevent_marker=^\nparser=vidm-txt-parser-onprem\ntags={\"product\":\"vidm-aws\",\"component\":\"vidm\"}\n\n[parser|vidm-txt-parser-onprem]\nbase_parser=clf\nformat=%h %l %u [%t] \"%{request}i\" %{status_code}i %b %{response_time}i\n\n[filelog|kdc-onprem]\n; IMPORTANT: Change the directory as per the environment\ndirectory=/opt/vmware/horizon/workspace/logs\ninclude=kdc*.log\ntags={\"product\":\"vidm-aws\",\"component\":\"kdc\"}\n\n[filelog|kdc-mtkadmin-onprem]\n; IMPORTANT: Change the directory as per the environment\ndirectory=/opt/vmware/horizon/workspace/logs\ninclude=mtkadmin.log\ntags={\"product\":\"vidm-aws\",\"component\":\"kdc\"}\n;cfn-init Log InSight agent section\n\n[filelog|cfn-init-onprem]\n; IMPORTANT: Change the directory as per the environment\ndirectory=/opt/vmware/horizon/workspace/logs/\ninclude=cfn.*.log\nevent_marker=^\nparser=cfn-init-parser-onprem\ntags={\"product\":\"vidm-aws\",\"component\":\"cfn-init\"}\n\n[parser|cfn-init-parser-onprem]\nbase_parser=clf\n\n[parser|vidm-authentication-decoder-onprem]\nbase_parser=csv\ndelimiter=\";\"\nfields=tenant, user_uuid, remote_host\n\n[parser|vidm-message-decoder-onprem]\nbase_parser=clf\nformat=%{status}i %{operation}i (%{referer}i)\nfield_decoder={\"referer\":\"vidm-referer-decoder-onprem\"}\n\n[parser|vidm-referer-decoder-onprem]\nbase_parser=csv\nfields=url, , mime_type, method, ,' } elseif ($agentGroupType -eq "photon") { - $agentGroupName = "Photon OS - Appliance Agent Group" $agentGroupConfig = '[journaldlog|journal_config]\njournal_files=all\ntags={\"generator\":\"journald\"}\n\n[filelog|audit]\ndirectory=/root/\ninclude=.bash_history\ntags={\"audit\":\"bash_history\"}' } @@ -22850,91 +25606,101 @@ Function Test-WSAAuthentication { } Export-ModuleMember -Function Test-WSAAuthentication -Function Test-SubnetInput { +Function Test-WMSubnetInput { <# .SYNOPSIS Tests whether an IPv4 subnet is sized correctly for Developer Ready Infrastructure pools .DESCRIPTION - The Test-SubnetInput cmdlet tests whether an IPv4 subnet is sized correctly for Developer Ready Infrastructure pools + The Test-WMSubnetInput cmdlet tests whether an IPv4 subnet is sized correctly for Developer Ready Infrastructure pools .EXAMPLE - Test-SubnetInput -Subnet 192.168.21.0/24 -SubnetType Ingress - This example will return that the subnet 192.168.21.0/24 is valid for the type Ingress. + Test-WMSubnetInput -Subnet 192.168.21.0/24 -SubnetType Ingress + This example will return as 'true' #> Param ( [Parameter (Mandatory = $true)] [String]$Subnet, - [Parameter (Mandatory = $true)] [String]$SubnetType + [Parameter (Mandatory = $true)][ValidateSet("Pod", "Service", "Egress", "Ingress")] [String]$SubnetType ) - if ($SubnetType -eq "Pod") { - $subnetMinimum = 23 - $subnetFormat = "100.100.0.0/20" - } elseif ($SubnetType -eq "Service") { - $subnetMinimum = 22 - $subnetFormat = "100.200.0.0/22" - } elseif ($SubnetType -eq "Egress") { - $subnetMinimum = 27 - $subnetFormat = "192.168.22.0/24" - } elseif ($subnettype -eq "Ingress") { - $subnetMinimum = 27 - $subnetFormat = "192.168.21.0/24" + + Switch ($subnetType) { + "Pod" { + $subnetMinimum = 23 + Break + } + "Service" { + $subnetMinimum = 22 + Break + } + "Egress" { + $subnetMinimum = 27 + Break + } + "Ingress" { + $subnetMinimum = 27 + Break + } + default { + Write-Error "Unsuported Subnet Type ($subnetType)" + Break + } } + + + Try { + $checkSubnet = $null + $subnetStart = $null + [bool]$testElement = $false - - $alteredSubnet = $false - - do { - try { - $checkSubnet = $null - $subnetStart = $null - - $subnetStart = $Subnet.Split("/")[0] - try { - $checkSubnet = [IPAddress]$subnetStart - } catch {} - - if ($checksubnet.IPAddressToString -ne $subnetStart -or !$checkSubnet) { - $alteredSubnet = $true - $Subnet = Read-Host "Improperly formatted $subnetType subnet ($subnet). Please enter a correctly formatted (CIDR notation - e.g., $subnetFormat) subnet and press Enter" - } else { - $subnetFormatValidated = $true - } - } catch { - Debug-ExceptionWriter -object $_ + $subnetStart = $Subnet.Split("/")[0] + Try { + $checkSubnet = [IPAddress]$subnetStart + } + Catch { + #Do nothing } - if ($subnetFormatValidated) { - $suffix = $Subnet.Split("/")[1] - $checkSuffix = [int[]]$suffix - - try { - if ($checkSuffix -gt $subnetMinimum -or !$checkSuffix) { - $alteredSubnet = $true - do { - [Int[]]$newSuffix = Read-Host "Improperly sized $subnetType subnet ($subnet). Please enter a new host prefix length (At least $subnetminimum) and press Enter" - }until ($newSuffix.length -ne [int]::empty -and $newSuffix -le $subnetMinimum) + if ($checksubnet.IPAddressToString -ne $subnetStart -or !$checkSubnet) { + + Write-Error "Improperly formatted subnet ($subnet) : VALIDATION_FAILED" + + } + else { + $testElement = $true + } + } + Catch { + Debug-ExceptionWriter -object $_ + } - $newSubnetAddress = $subnet.Split("/")[0] - $subnet = "$newSubnetAddress/$newSuffix" - } else { - $subnetSizeValidated = $true - } - } catch { - Debug-ExceptionWriter -object $_ - } + Try { + [bool]$testSufix = $false + $suffix = $Subnet.Split("/")[1] + $checkSuffix = [int[]]$suffix + if ($checkSuffix -gt $subnetMinimum -or !$checkSuffix) { + Write-Error "Improperly sized $subnetType subnet ($subnet). Host prefix length should be at least {$subnetminimum)" + } - } until ($subnetFormatValidated -eq $true -and $subnetSizeValidated -eq $true) + else { + $testSufix = $true + } + } + Catch { + Debug-ExceptionWriter -object $_ + } - $output = New-Object -TypeName PSCustomObject - $output | Add-Member -notepropertyname 'Validated' -notepropertyvalue $true - $output | Add-Member -notepropertyname 'Altered' -notepropertyvalue $alteredSubnet - $output | Add-Member -notepropertyname 'Subnet' -notepropertyvalue $subnet - $output + if ($testElement -and $testSufix) { + Return $true + } + else { + Return $false + } + } -Export-ModuleMember -Function Test-SubnetInput +Export-ModuleMember -Function Test-WMSubnetInput Function Test-IpAddress { <# @@ -23010,16 +25776,111 @@ Function Test-IpAddress { } Export-ModuleMember -Function Test-IpAddress -Function Get-NtpServer { +Function Test-IPaddressArray { + + <# + .SYNOPSIS + Tests whether an array of strings can be converted to valid IPv4 addresses. + + .DESCRIPTION + The Test-IpAddressArray cmdlet tests whether an array of strings can be converted to valid IPv4 addresses. + Returns $true if all strings are valid IPv4 address or $false when at least one is not valid IPv4 address + + .EXAMPLE + Test-IpAddressArray -ipAddressArray @("192.168.20.10","172.16.31.1") + This example will test whether the strings "192.168.20.10","172.16.31.1" can be converted to valid IPv4 addresses. + + .EXAMPLE + Test-IpAddressArray -ipAddressArray "192.168.20.10" + This example will test whether the string "192.168.20.10" can be converted to valid IPv4 addresses. + #> + + Param ( + [Parameter (Mandatory = $true)] [Array]$IPaddressArray + ) + + Foreach ($ipAddress in $IPaddressArray) { + [bool]$testElement = $false + Try { + $convertToIPv4 = [ipaddress]$ipAddress + } + Catch { + Write-Error "Can not convert $ipAddress to valid IPv4 address." + Return $false + } + if (($convertToIPv4.IPAddressToString -ne $ipAddress) -or (!$convertToIPv4)) { + Write-Error "Can not convert $ipAddress to valid IPv4 address due to missing octet" + Return $false + } + else { + $testElement = $true + } + } + Return $testElement + +} +Export-ModuleMember -Function Test-IPaddressArray + +Function Test-DnsServers { + + <# + .SYNOPSIS + Tests whether an array of DNS servers can resolve given domain name.. + + .DESCRIPTION + The Test-DnsServers cmdlet tests whether an array of DNS servers can resolve given domain name. + Returns $true if all servers can resolve the given domain name or $false when at least one fails. + + .EXAMPLE + Test-DnsServers -dnsServers @("192.168.20.10","172.16.31.1") -domainName vmware.com + This example will test whether all dns servers "192.168.20.10","172.16.31.1" can can resolve domain name vmware.com. + + .EXAMPLE + Test-DnsServers -dnsServers "192.168.20.10" -domainName vmware.com + This example will test whether dns server "192.168.20.10" can resolve domain name vmware.com. + #> + + Param ( + [Parameter (Mandatory = $true)] [Array]$dnsServers, + [Parameter (Mandatory = $false)] [string]$domainName="vmware.com" + ) + + if (Test-IPaddressArray -IPaddressArray $dnsServers) { + + Foreach ($dnsServer in $dnsServers) { + [bool]$resolveResult=$false + + Try { + $checkDnsServer = Resolve-DnsName -Name $domainName -Type A -Server $dnsServer -QuickTimeout -ErrorAction Stop + } + Catch [System.ComponentModel.Win32Exception] { + Write-Error "Can not resolve: $domainName using dns server: $dnsServer" + Return $false + } + if (!$checkDnsServer) { + Write-Error "Can not resolve: $domainName using dns server: $dnsServer" + $resolveResult = $false + } + else { + $resolveResult = $true + } + + } + Return $resolveResult + } +} +Export-ModuleMember -Function Test-DnsServers + +Function Test-NtpServer { <# .SYNOPSIS Checks the status of an NTP server .DESCRIPTION - The Get-NtpServer cmdlet checks the status of an NTP server + The Test-NtpServer cmdlet checks the status of an NTP server .EXAMPLE - Get-NtpServer -Server pool.ntp.org + Test-NtpServer -Server pool.ntp.org This example will return the status of the NTP server responding at pool.ntp.org #> @@ -23027,7 +25888,8 @@ Function Get-NtpServer { [Parameter (Mandatory = $true)] [String]$server ) - try { + $ntpStatus = $null + Try { [Byte[]]$NtpData = ,0 * 48 $NtpData[0] = 0x1B @@ -23043,21 +25905,21 @@ Function Get-NtpServer { [Void]$Socket.Send($NtpData) [Void]$Socket.Receive($NtpData) $Socket.Close() - } catch {} + } + Catch { + # Do nothing + } if ($ntpData -eq 0x1B) { - $ntpFunction = "Not Working" - } else { - $ntpFunction = "Working" + $ntpStatus = $false } - - $properties = @{'NTP_Server'=$server; - 'Results'=$ntpFunction} + else { + $ntpStatus = $true + } + Return $ntpStatus - $output = New-Object -TypeName PSObject -Property $properties - $output } -Export-ModuleMember -Function Get-NtpServer +Export-ModuleMember -Function Test-NtpServer ########################### End of Test Functions ########################### ################################################################################# diff --git a/README.md b/README.md index d88858a9..22cfad54 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,6 @@ -[PowerShell Gallery](https://www.powershellgallery.com/packages/PowerValidatedSolutions/1.4.0)   [PowerShell Gallery](https://www.powershellgallery.com/packages/PowerValidatedSolutions/1.4.0)   [Changelog](CHANGELOG.md) +![](https://img.shields.io/powershellgallery/v/PowerValidatedSolutions?style=for-the-badge) +[Changelog](CHANGELOG.md) +![](https://img.shields.io/powershellgallery/dt/PowerValidatedSolutions?style=for-the-badge) # PowerValidatedSolutions ## Overview @@ -17,7 +19,7 @@ Install-Module -Name VMware.PowerCLI -MinimumVersion 12.4.1 Install-Module -Name VMware.vSphere.SsoAdmin -MinimumVersion 1.3.7 Install-Module -Name ImportExcel -MinimumVersion 7.1.1 Install-Module -Name PowerVCF -MinimumVersion 2.1.7 -Install-Module -Name PowerValidatedSolutions -MinimumVersion 1.4.0 +Install-Module -Name PowerValidatedSolutions -MinimumVersion 1.5.0 ``` To verify the modules are installed, run the following command in the PowerShell console. @@ -31,7 +33,7 @@ Once installed, any new cmdlet associated with PowerValidatedSolutions will be a ## Known Issues Currently tracking no known issues. - + ## Contributing The PowerValidatedSolutions project team welcomes contributions from the community. Before you start working with PowerValidatedSolutions, please @@ -41,7 +43,7 @@ as an open-source patch. For more detailed information, refer to [CONTRIBUTING.m ## License -Copyright 2021 VMware, Inc. +Copyright 2021-2022 VMware, Inc. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -49,4 +51,4 @@ Redistribution and use in source and binary forms, with or without modification, 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/SampleScripts/dri/driConfigureSupervisorCluster.ps1 b/SampleScripts/dri/driConfigureSupervisorCluster.ps1 new file mode 100644 index 00000000..fa9b746a --- /dev/null +++ b/SampleScripts/dri/driConfigureSupervisorCluster.ps1 @@ -0,0 +1,201 @@ +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +<# + .NOTES + =================================================================================================================== + Created by: Gary Blake - Senior Staff Solutions Architect + Date: 2022-03-23 + Copyright 2021-2022 VMware, Inc. + =================================================================================================================== + + .SYNOPSIS + Configure vSphere/NSX/Supervisor Cluster for Developer Ready Infrastructure + + .DESCRIPTION + The driConfigureSupervisorCluster.ps1 provides a single script to configure vSphere, NSX and enable the Supervisor + Cluster as defined by the Developer Ready Infrastrucutre for VMware Cloud Foundation Validated Solution + + .EXAMPLE + driConfigureSupervisorCluster.ps1 -sddcManagerFqdn sfo-vcf01.sfo.rainpole.io -sddcManagerUser administrator@vsphere.local -sddcManagerPass VMw@re1! -workbook F:\vvs\PnP.xlsx -filePath F:\vvs + This example performs the configuration of vSphere, NSX and enable the Supervisor Cluster using the parameters provided within the Planning and Preparation Workbook +#> + +Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerFqdn, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerUser, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerPass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$workbook, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$filePath +) + +Clear-Host; Write-Host "" + +Start-SetupLogFile -Path $filePath -ScriptName $MyInvocation.MyCommand.Name +Write-LogMessage -Type INFO -Message "Starting the Process of Configuring vSphere / NSX / Supervisor Cluster on Developer Ready Infrastrucutre for VMware Cloud Foundation Validated Solution" -Colour Yellow +Write-LogMessage -Type INFO -Message "Setting up the log file to path $logfile" + +Try { + Write-LogMessage -Type INFO -Message "Checking Existance of Planning and Preparation Workbook: $workbook" + if (!(Test-Path $workbook )) { + Write-LogMessage -Type ERROR -Message "Unable to Find Planning and Preparation Workbook: $workbook, check details and try again" -Colour Red + Break + } + else { + Write-LogMessage -Type INFO -Message "Found Planning and Preparation Workbook: $workbook" + } + Write-LogMessage -Type INFO -Message "Checking a Connection to SDDC Manager: $sddcManagerFqdn" + if (Test-VCFConnection -server $sddcManagerFqdn ) { + Write-LogMessage -Type INFO -Message "Attempting to connect to VMware Cloud Foundation to Gather System Details" + if (Test-VCFAuthentication -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass) { + Write-LogMessage -Type INFO -Message "Gathering Details from SDDC Manager Inventory and Extracting Worksheet Data from the Excel Workbook" + Write-LogMessage -type INFO -message "Opening the Excel Workbook: $Workbook" + $pnpWorkbook = Open-ExcelPackage -Path $Workbook + Write-LogMessage -type INFO -message "Checking Valid Planning and Prepatation Workbook Provided" + if (($pnpWorkbook.Workbook.Names["vcf_version"].Value -ne "v4.3.x") -and ($pnpWorkbook.Workbook.Names["vcf_version"].Value -ne "v4.4.x")) { + Write-LogMessage -type INFO -message "Planning and Prepatation Workbook Provided Not Supported" -colour Red + Break + } + + $domainFqdn = $pnpWorkbook.Workbook.Names["region_ad_child_fqdn"].Value + $wldSddcDomainName = $pnpWorkbook.Workbook.Names["wld_sddc_domain"].Value + + $kubSegmentName = $pnpWorkbook.Workbook.Names["k8s_mgmt_seg"].Value + $wldTier1GatewayName = $pnpWorkbook.Workbook.Names["wld_tier1_name"].Value + $kubSegmentGatewayCIDR = $pnpWorkbook.Workbook.Names["k8s_segment_gateway_ip_cidr"].Value + $overlayTzName = "overlay-tz-" + $pnpWorkbook.Workbook.Names["wld_nsxt_vip_fqdn"].Value + $wldTier0GatewayName = $pnpWorkbook.Workbook.Names["wld_tier0_name"].Value + $wldPrefixListName = $pnpWorkbook.Workbook.Names["k8s_ip_prefixlist"].Value + $kubSegmentSubnetCidr = $pnpWorkbook.Workbook.Names["k8s_segment_cidr"].Value + $ingressSubnetCidr = $pnpWorkbook.Workbook.Names["k8s_ingress_pool_cidr"].Value + $egressSubnetCidr = $pnpWorkbook.Workbook.Names["k8s_egress_pool_cidr"].Value + $wldRouteMapName = $pnpWorkbook.Workbook.Names["k8s_ip_routemap"].Value + $tagCategoryName = $pnpWorkbook.Workbook.Names["k8s_vcenter_category"].Value + $tagName = $pnpWorkbook.Workbook.Names["k8s_vcenter_tag"].Value + $spbmPolicyName = $pnpWorkbook.Workbook.Names["k8s_vcenter_storage_policy"].Value + $contentLibraryName = $pnpWorkbook.Workbook.Names["k8s_vcenter_content_library"].Value + $wmClusterName = $pnpWorkbook.Workbook.Names["wld_cluster"].Value + $CommonName = $pnpWorkbook.Workbook.Names["k8s_cluster_endpoint_fqdn"].Value + $Organization = $pnpWorkbook.Workbook.Names["ca_organization"].Value + $OrganizationalUnit = $pnpWorkbook.Workbook.Names["ca_organization_unit"].Value + $Country = $pnpWorkbook.Workbook.Names["ca_country"].Value + $StateOrProvince = $pnpWorkbook.Workbook.Names["ca_state"].Value + $Locality = $pnpWorkbook.Workbook.Names["ca_locality"].Value + $AdminEmailAddress = $pnpWorkbook.Workbook.Names["ca_email_address"].Value + $KeySize = $pnpWorkbook.Workbook.Names["ca_key_size"].Value + $domainBindUser = $pnpWorkbook.Workbook.Names["child_svc_vsphere_ad_user"].Value + $domainBindPass = $pnpWorkbook.Workbook.Names["child_svc_vsphere_ad_password"].Value + $wmNamespaceName = $pnpWorkbook.Workbook.Names["k8s_namepsace"].Value + $wmNamespaceEditUserGroup = $pnpWorkbook.Workbook.Names["group_gg_kub_admins"].Value + $wmNamespaceViewUserGroup = $pnpWorkbook.Workbook.Names["group_gg_kub_readonly"].Value + $licenseKey = $pnpWorkbook.Workbook.Names["esx_k8s_license"].Value + $certificateRequestFile = $filePath + "\supervisorCluster.csr" + $certificateFile = $filePath + "\supervisorCluster.cer" + + $wmClusterInput = @{ + server = $sddcManagerFqdn + user = $sddcManagerUser + pass = $sddcManagerPass + domain = $wldSddcDomainName + cluster = $wmClusterName + sizeHint = "Tiny" + managementNetworkMode = "StaticRange" + managementVirtualNetwork = $kubSegmentName + managementNetworkStartIpAddress = $pnpWorkbook.Workbook.Names["k8s_mgmt_pool_start_ip"].Value + managementNetworkAddressRangeSize = "5" + managementNetworkGateway = $pnpWorkbook.Workbook.Names["k8s_segment_gateway_ip"].Value + managementNetworkSubnetMask = $pnpWorkbook.Workbook.Names["k8s_segment_mask"].Value + masterDnsName = $wmClusterName + "." + $domainFqdn + masterNtpServers = @($pnpWorkbook.Workbook.Names["region_ntp1_server"].Value) + masterDnsServers = @($pnpWorkbook.Workbook.Names["region_dns1_ip"].Value) + contentLibrary = $contentLibraryName + ephemeralStoragePolicy = $spbmPolicyName + imageStoragePolicy = $spbmPolicyName + masterStoragePolicy = $spbmPolicyName + nsxEdgeCluster = $pnpWorkbook.Workbook.Names["wld_ec_name"].Value + distributedSwitch = $pnpWorkbook.Workbook.Names["wld_vds_name"].Value + podCIDRs = $pnpWorkbook.Workbook.Names["k8s_supervisor_cluster_pod_pool_cidr"].Value + serviceCIDR = $pnpWorkbook.Workbook.Names["k8s_supervisor_cluster_service_pool_cidr"].Value + externalIngressCIDRs = $ingressSubnetCidr + externalEgressCIDRs = $egressSubnetCidr + masterDnsSearchDomain = $pnpWorkbook.Workbook.Names["child_dns_zone"].Value + workerDnsServers = @($pnpWorkbook.Workbook.Names["region_dns1_ip"].Value) + } + + # Add a Network Segment for Tanzu to NSX-T Data Center + Write-LogMessage -Type INFO -Message "Add a Network Segment for Tanzu to NSX-T Data Center" + $StatusMsg = Add-NetworkSegment -Server $sddcManagerFqdn -User $sddcManagerUser -Pass $sddcManagerPass -Domain $wldSddcDomainName -SegmentName $kubSegmentName -ConnectedGateway $wldTier1GatewayName -Cidr $kubSegmentGatewayCIDR -TransportZone $overlayTzName -GatewayType Tier1 -SegmentType Overlay -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Add IP Prefix Lists to the Tier-0 Gateway for Tanzu to NSX-T Data Center + Write-LogMessage -Type INFO -Message "Add IP Prefix Lists to the Tier-0 Gateway for Tanzu to NSX-T Data Center" + $StatusMsg = Add-PrefixList -Server $sddcManagerFqdn -User $sddcManagerUser -Pass $sddcManagerPass -Domain $wldSddcDomainName -Tier0Gateway $wldTier0GatewayName -PrefixListName $wldPrefixListName -SubnetCIDR $kubSegmentSubnetCidr -ingressSubnetCidr $ingressSubnetCidr -egressSubnetCidr $egressSubnetCidr -GE "28" -LE "32" -Action PERMIT -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Create a Route Map on the Tier-0 Gateway for Tanzu to NSX-T Data Center + Write-LogMessage -Type INFO -Message "Create a Route Map on the Tier-0 Gateway for Tanzu to NSX-T Data Center" + $StatusMsg = Add-RouteMap -Server $sddcManagerFqdn -User $sddcManagerUser -Pass $sddcManagerPass -Domain $wldSddcDomainName -Tier0Gateway $wldTier0GatewayName -RouteMap $wldRouteMapName -PrefixListName $wldPrefixListName -Action PERMIT -ApplyPolicy:$True -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Assign a New Tag to the vSAN Datastore in vCenter Server + Write-LogMessage -Type INFO -Message "Assign a New Tag to the vSAN Datastore in vCenter Server" + $StatusMsg = Set-DatastoreTag -Server $sddcManagerFqdn -User $sddcManagerUser -Pass $sddcManagerPass -Domain $wldSddcDomainName -TagName $tagName -TagCategoryName $tagCategoryName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg"; $ErrorMsg = $null } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Create a Storage Policy that Uses the New vSphere Tag in vCenter Server + Write-LogMessage -Type INFO -Message "Create a Storage Policy that Uses the New vSphere Tag in vCenter Server" + $StatusMsg = Add-StoragePolicy -Server $sddcManagerFqdn -User $sddcManagerUser -Pass $sddcManagerPass -Domain $wldSddcDomainName -PolicyName $spbmPolicyName -TagName $tagName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg"; $ErrorMsg = $null } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Create a Subscribed Content Library for Tanzu in vCenter Server + Write-LogMessage -Type INFO -Message "Create a Subscribed Content Library for Tanzu in vCenter Server" + $StatusMsg = Add-ContentLibrary -Server $sddcManagerFqdn -User $sddcManagerUser -Pass $sddcManagerPass -Domain $wldSddcDomainName -ContentLibraryName $contentLibraryName -SubscriptionUrl "https://wp-content.vmware.com/v2/latest/lib.json" -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg"; $ErrorMsg = $null } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Deploy a Supervisor Cluster for Developer Ready Infrastructure + Write-LogMessage -Type INFO -Message "Deploy a Supervisor Cluster for Developer Ready Infrastructure" + $StatusMsg = Enable-SupervisorCluster @wmClusterInput -RunAsync -SkipValidation $true -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg"; $ErrorMsg = '' } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Replace the Supervisor Cluster Kubernetes API Endpoint Certificate for Developer Ready Infrastructure + Write-LogMessage -Type INFO -Message "Replace the Supervisor Cluster Kubernetes API Endpoint Certificate for Developer Ready Infrastructure" + Write-LogMessage -Type INFO -Message "Generating the Supervisor Cluster CSR File" + $StatusMsg = New-SupervisorClusterCSR -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $wldSddcDomainName -cluster $wmClusterName -CommonName $CommonName -Organization $Organization -OrganizationalUnit $OrganizationalUnit -Country $Country -StateOrProvince $StateOrProvince -Locality $Locality -AdminEmailAddress $AdminEmailAddress -KeySize $Keysize -FilePath $certificateRequestFile -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + + Write-LogMessage -Type INFO -Message "Requesting a Signed Certificate from the Microsoft Certificate Authority" + $StatusMsg = Request-SignedCertificate -mscaComputerName $mscaComputerName -mscaName $mscaName -domainUsername $domainBindUser -domainPassword $domainBindPass -certificateTempalate $certificateTempalate -certificateRequestFile $certificateRequestFile -certificateFile $certificateFile -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + Write-LogMessage -Type INFO -Message "Installing the Supervisor Cluster Signed-Certificate" + $StatusMsg = Add-SupervisorClusterCertificate -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $wldSddcDomainName -cluster $wmClusterName -FilePath F:\vvs\supervisorCluster.cer -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # License the Supervisor Cluster for Developer Ready Infrastructure + Write-LogMessage -Type INFO -Message "License the Supervisor Cluster for Developer Ready Infrastructure" + $StatusMsg = Add-SupervisorClusterLicense -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $wldSddcDomainName -Cluster $wmClusterName -LicenseKey $licenseKey -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Deploy a Supervisor Namespace for Developer Ready Infrastructure + Write-LogMessage -Type INFO -Message "Deploy a Supervisor Namespace for Developer Ready Infrastructure" + $StatusMsg = Add-Namespace -Server $sddcManagerFqdn -User $sddcManagerUser -Pass $sddcManagerPass -Domain $wldSddcDomainName -Cluster $wmClusterName -Namespace $wmNamespaceName -StoragePolicy $spbmPolicyName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg"; $ErrorMsg = '' } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Assign the Supervisor Namespace Roles to Active Directory Groups + Write-LogMessage -Type INFO -Message "Assign the Supervisor Namespace Roles to Active Directory Groups" + $StatusMsg = Add-NamespacePermission -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -sddcDomain $wldSddcDomainName -domain $domainFqdn -domainBindUser $domainBindUser -domainBindPass $domainBindPass -namespace $wmNamespaceName -principal $wmNamespaceEditUserGroup -role edit -type group -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + $StatusMsg = Add-NamespacePermission -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -sddcDomain $wldSddcDomainName -domain $domainFqdn -domainBindUser $domainBindUser -domainBindPass $domainBindPass -namespace $wmNamespaceName -principal $wmNamespaceViewUserGroup -role view -type group -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Enable the Registry Service on the Supervisor Cluster for Developer Ready Infrastructure + Write-LogMessage -Type INFO -Message "Enable the Registry Service on the Supervisor Cluster for Developer Ready Infrastructure" + $StatusMsg = Enable-Registry -Server $sddcManagerFqdn -User $sddcManagerUser -Pass $sddcManagerPass -Domain $wldSddcDomainName -StoragePolicy $spbmPolicyName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + } + } +} +Catch { + Debug-CatchWriter -object $_ +} \ No newline at end of file diff --git a/SampleScripts/dri/driDeployTanzuCluster.ps1 b/SampleScripts/dri/driDeployTanzuCluster.ps1 new file mode 100644 index 00000000..0205df09 --- /dev/null +++ b/SampleScripts/dri/driDeployTanzuCluster.ps1 @@ -0,0 +1,125 @@ +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +<# + .NOTES + =========================================================================== + Created by: Gary Blake - Senior Staff Solutions Architect + Date: 2021-03-23 + Copyright 2021-2022 VMware, Inc. + =========================================================================== + + .SYNOPSIS + Deploy a Tanzu Cluster for Developer Ready Infrastructure + + .DESCRIPTION + The driDeployTanzuCluster.ps1 provides a single script to deploy a Tanzu Kubernetes Cluster as defined by the + Developer Ready Infrastrucutre for VMware Cloud Foundation Validated Solution + + .EXAMPLE + driDeployTanzuCluster.ps1 -sddcManagerFqdn sfo-vcf01.sfo.rainpole.io -sddcManagerUser administrator@vsphere.local -sddcManagerPass VMw@re1! -workbook F:\vvs\PnP.xlsx -filePath F:\vvs + This example performs the deployment of a Tanzu Kubernetes Cluster using the parameters provided within the Planning and Preparation Workbook +#> + +Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerFqdn, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerUser, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerPass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$workbook, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$filePath +) + +Clear-Host; Write-Host "" + +Start-SetupLogFile -Path $filePath -ScriptName $MyInvocation.MyCommand.Name +Write-LogMessage -Type INFO -Message "Starting the Process of Deploying a Tanzu Cluster on Developer Ready Infrastrucutre for VMware Cloud Foundation Validated Solution" -Colour Yellow +Write-LogMessage -Type INFO -Message "Setting up the log file to path $logfile" + +# Perform validation on inputs +Try { + Write-LogMessage -Type INFO -Message "Checking a Connection to SDDC Manager: $sddcManagerFqdn" + if (!(Test-Connection -ComputerName $sddcManagerFqdn -Count 1 -ErrorAction SilentlyContinue)) { + Write-LogMessage -Type ERROR -Message "Unable to connect to server: $sddcManagerFqdn, check details and try again" -Colour Red + Break + } + else { + Write-LogMessage -Type INFO -Message "Connection to SDDC Manager: $sddcManagerFqdn was Successful" + } + Write-LogMessage -Type INFO -Message "Checking Existance of Planning and Preparation Workbook: $workbook" + if (!(Test-Path $workbook )) { + Write-LogMessage -Type ERROR -Message "Unable to Find Planning and Preparation Workbook: $workbook, check details and try again" -Colour Red + Break + } + else { + Write-LogMessage -Type INFO -Message "Found Planning and Preparation Workbook: $workbook" + } +} +Catch { + Debug-CatchWriter -object $_ +} + +Try { + Write-LogMessage -Type INFO -Message "Attempting to connect to VMware Cloud Foundation to Gather System Details" + $StatusMsg = Request-VCFToken -fqdn $sddcManagerFqdn -username $sddcManagerUser -password $sddcManagerPass -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message $StatusMsg } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + if ($accessToken) { + Write-LogMessage -Type INFO -Message "Gathering Details from SDDC Manager Inventory and Extracting Worksheet Data from the Excel Workbook" + + Write-LogMessage -type INFO -message "Opening the Excel Workbook: $Workbook" + $pnpWorkbook = Open-ExcelPackage -Path $Workbook + + Write-LogMessage -type INFO -message "Checking Valid Planning and Prepatation Workbook Provided" + if (($pnpWorkbook.Workbook.Names["vcf_version"].Value -ne "v4.3.x") -and ($pnpWorkbook.Workbook.Names["vcf_version"].Value -ne "v4.4.x")) { + Write-LogMessage -type INFO -message "Planning and Prepatation Workbook Provided Not Supported" -colour Red + Break + } + + $domainFqdn = $pnpWorkbook.Workbook.Names["region_ad_child_fqdn"].Value + $wldSddcDomainName = $pnpWorkbook.Workbook.Names["wld_sddc_domain"].Value + + $wmClusterName = $pnpWorkbook.Workbook.Names["wld_cluster"].Value + $wmNamespaceName = $pnpWorkbook.Workbook.Names["k8s_cluster_name"].Value + $spbmPolicyName = $pnpWorkbook.Workbook.Names["k8s_vcenter_storage_policy"].Value + $domainBindUser = $pnpWorkbook.Workbook.Names["child_svc_vsphere_ad_user"].Value + $domainBindPass = $pnpWorkbook.Workbook.Names["child_svc_vsphere_ad_password"].Value + $wmNamespaceEditUserGroup = $pnpWorkbook.Workbook.Names["group_gg_kub_admins"].Value + $wmNamespaceViewUserGroup = $pnpWorkbook.Workbook.Names["group_gg_kub_readonly"].Value + $vmClass = $pnpWorkbook.Workbook.Names["k8s_vm_class"].Value + } + else { + Write-LogMessage -Type ERROR -Message "Unable to connect to SDDC Manager $server" -Colour Red + Exit + } +} +Catch { + Debug-CatchWriter -object $_ +} + +Try { + # Deploy a Namespace for the Tanzu Kubernetes Cluster + Write-LogMessage -Type INFO -Message "Deploy a Namespace for the Tanzu Kubernetes Cluster" + $StatusMsg = Add-Namespace -Server $sddcManagerFqdn -User $sddcManagerUser -Pass $sddcManagerPass -Domain $wldSddcDomainName -Cluster $wmClusterName -Namespace $wmNamespaceName -StoragePolicy $spbmPolicyName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg"; $ErrorMsg = $null } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Assign the New Tanzu Cluster Namespace Roles to Active Directory Groups + Write-LogMessage -Type INFO -Message "Assign the New Tanzu Cluster Namespace Roles to Active Directory Groups" + $StatusMsg = Add-NamespacePermission -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -sddcDomain $wldSddcDomainName -domain $domainFqdn -domainBindUser $domainBindUser -domainBindPass $domainBindPass -namespace $wmNamespaceName -principal $wmNamespaceEditUserGroup -role edit -type group -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + $StatusMsg = Add-NamespacePermission -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -sddcDomain $wldSddcDomainName -domain $domainFqdn -domainBindUser $domainBindUser -domainBindPass $domainBindPass -namespace $wmNamespaceName -principal $wmNamespaceViewUserGroup -role view -type group -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Enable a Virtual Machine Class for the Tanzu Kubernetes Cluster + Write-LogMessage -Type INFO -Message "Enable a Virtual Machine Class for the Tanzu Kubernetes Cluster" + $StatusMsg = Add-NamespaceVmClass -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $wldSddcDomainName -Namespace $wmNamespaceName -VMClass $vmClass -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Provision a Tanzu Kubernetes Cluster + Write-LogMessage -Type INFO -Message "Provision a Tanzu Kubernetes Cluster" + $StatusMsg = Add-TanzuKubernetesCluster -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $wldSddcDomainName -cluster $wmClusterName -yaml .\SampleYaml\sfo-w01-tkc01-cluster.yaml -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } +} +Catch { + Debug-CatchWriter -object $_ +} \ No newline at end of file diff --git a/SampleScripts/dri/driUndoDeployment.ps1 b/SampleScripts/dri/driUndoDeployment.ps1 new file mode 100644 index 00000000..a781f027 --- /dev/null +++ b/SampleScripts/dri/driUndoDeployment.ps1 @@ -0,0 +1,135 @@ +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +<# + .NOTES + =================================================================================================================== + Created by: Gary Blake - Senior Staff Solutions Architect + Date: 2022-03-23 + Copyright 2021-2022 VMware, Inc. + =================================================================================================================== + + .SYNOPSIS + Remove Developer Ready Infrastructure from a VMware Cloud Foundation Instance + + .DESCRIPTION + The driUndoDeployment.ps1 provides a single script to remove Developer Ready Infrastructure from a VMware Cloud + Foundation Instance + + .EXAMPLE + driUndoDeployment.ps1 -sddcManagerFqdn sfo-vcf01.sfo.rainpole.io -sddcManagerUser administrator@vsphere.local -sddcManagerPass VMw@re1! -workbook F:\vvs\PnP.xlsx -filePath F:\vvs + This example performs the removal of Developer Ready Infrastructure from a VMware Cloud Foundation Instance using the parameters provided within the Planning and Preparation Workbook +#> + +Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerFqdn, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerUser, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerPass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$workbook, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$filePath +) + +Clear-Host; Write-Host "" + +Start-SetupLogFile -Path $filePath -ScriptName $MyInvocation.MyCommand.Name +Write-LogMessage -Type INFO -Message "Starting the Process of Removing Developer Ready Infrastrucutre from VMware Cloud Foundation Instance" -Colour Yellow +Write-LogMessage -Type INFO -Message "Setting up the log file to path $logfile" + +Try { + Write-LogMessage -Type INFO -Message "Checking Existance of Planning and Preparation Workbook: $workbook" + if (!(Test-Path $workbook )) { + Write-LogMessage -Type ERROR -Message "Unable to Find Planning and Preparation Workbook: $workbook, check details and try again" -Colour Red + Break + } + else { + Write-LogMessage -Type INFO -Message "Found Planning and Preparation Workbook: $workbook" + } + Write-LogMessage -Type INFO -Message "Checking a Connection to SDDC Manager: $sddcManagerFqdn" + if (Test-VCFConnection -server $sddcManagerFqdn ) { + Write-LogMessage -Type INFO -Message "Attempting to connect to VMware Cloud Foundation to Gather System Details" + if (Test-VCFAuthentication -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass) { + Write-LogMessage -Type INFO -Message "Gathering Details from SDDC Manager Inventory and Extracting Worksheet Data from the Excel Workbook" + Write-LogMessage -type INFO -message "Opening the Excel Workbook: $Workbook" + $pnpWorkbook = Open-ExcelPackage -Path $Workbook + Write-LogMessage -type INFO -message "Checking Valid Planning and Prepatation Workbook Provided" + if (($pnpWorkbook.Workbook.Names["vcf_version"].Value -ne "v4.3.x") -and ($pnpWorkbook.Workbook.Names["vcf_version"].Value -ne "v4.4.x")) { + Write-LogMessage -type INFO -message "Planning and Prepatation Workbook Provided Not Supported" -colour Red + Break + } + + $wldSddcDomainName = $pnpWorkbook.Workbook.Names["wld_sddc_domain"].Value + $wmClusterName = $pnpWorkbook.Workbook.Names["wld_cluster"].Value + $wmNamespaceName = $pnpWorkbook.Workbook.Names["k8s_cluster_name"].Value + $wmTkcName = $pnpWorkbook.Workbook.Names["k8s_cluster_name"].Value + $supervisorNamespace = $pnpWorkbook.Workbook.Names["k8s_namepsace"].Value + $contentLibraryName = $pnpWorkbook.Workbook.Names["k8s_vcenter_content_library"].Value + $storagePolicy = $pnpWorkbook.Workbook.Names["k8s_vcenter_storage_policy"].Value + $tagCategoryName = $pnpWorkbook.Workbook.Names["k8s_vcenter_category"].Value + $tagName = $pnpWorkbook.Workbook.Names["k8s_vcenter_tag"].Value + $wldTier0Gateway = $pnpWorkbook.Workbook.Names["wld_tier0_name"].Value + $kubSegmentName = $pnpWorkbook.Workbook.Names["k8s_mgmt_seg"].Value + $wldRouteMapName = $pnpWorkbook.Workbook.Names["k8s_ip_routemap"].Value + $wldPrefixListName = $pnpWorkbook.Workbook.Names["k8s_ip_prefixlist"].Value + + # Remove a Tanzu Kubernetes Cluster from Supervisor Cluster + Write-LogMessage -Type INFO -Message "Remove a Tanzu Kubernetes Cluster from Supervisor Cluster" + $StatusMsg = Undo-TanzuKubernetesCluster -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $wldSddcDomainName -cluster $wmClusterName -tkc $wmTkcName -namespace $wmNamespaceName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg"; $ErrorMsg = '' } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Remove a Namespace from Supervisor Cluster + Write-LogMessage -Type INFO -Message "Remove a Namespace from Supervisor Cluster" + $StatusMsg = Undo-Namespace -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $wldSddcDomainName -namespace $wmNamespaceName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg"; $ErrorMsg = '' } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Remove Embedded Harbour Registry from Supervisor Cluster + Write-LogMessage -Type INFO -Message "Remove Embedded Harbour Registry from Supervisor Cluster" + $StatusMsg = Undo-Registry -Server $sddcManagerFqdn -User $sddcManagerUser -Pass $sddcManagerPass -Domain $wldSddcDomainName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Remove Supervisor Namespace + Write-LogMessage -Type INFO -Message "Remove Supervisor Namespace" + $StatusMsg = Undo-Namespace -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $wldSddcDomainName -namespace $supervisorNamespace -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Remove Supervisor Cluster + Write-LogMessage -Type INFO -Message "Remove Supervisor Cluster" + $StatusMsg = Undo-SupervisorCluster -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $wldSddcDomainName -cluster $wmClusterName -RunAsync -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Remove Content Library from vCenter Server + Write-LogMessage -Type INFO -Message "Remove Content Library from vCenter Server" + $StatusMsg = Undo-ContentLibrary -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $wldSddcDomainName -contentLibraryName $contentLibraryName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Remove a Storage Policy that Uses the vSphere Tag + Write-LogMessage -Type INFO -Message "Remove a Storage Policy that Uses the vSphere Tag" + $StatusMsg = Undo-StoragePolicy -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $wldSddcDomainName -policyName $storagePolicy -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg"; $ErrorMsg = '' } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Remove the Tag from the vSAN Datastore + Write-LogMessage -Type INFO -Message "Remove the Tag from the vSAN Datastore" + $StatusMsg = Undo-DatastoreTag -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $wldSddcDomainName -tagName $tagName -tagCategoryName $tagCategoryName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Remove a Route Map from the Tier-0 Gateway + Write-LogMessage -Type INFO -Message "Remove a Route Map from the Tier-0 Gateway" + $StatusMsg = Undo-RouteMap -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $wldSddcDomainName -tier0Gateway $wldTier0Gateway -routeMapName $wldRouteMapName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Remove a Route Map from the Tier-0 Gateway + Write-LogMessage -Type INFO -Message "Remove a Route Map from the Tier-0 Gateway" + $StatusMsg = Undo-PrefixList -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $wldSddcDomainName -tier0Gateway $wldTier0Gateway -prefixListName $wldPrefixListName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Remove a Network Segment + Write-LogMessage -Type INFO -Message "Remove a Network Segment" + $StatusMsg = Undo-NetworkSegment -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $wldSddcDomainName -segmentName $kubSegmentName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + } + } +} +Catch { + Debug-CatchWriter -object $_ +} \ No newline at end of file diff --git a/SampleScripts/iam/iamConfigureNsx.ps1 b/SampleScripts/iam/iamConfigureNsx.ps1 index 2133741b..1be0ed51 100644 --- a/SampleScripts/iam/iamConfigureNsx.ps1 +++ b/SampleScripts/iam/iamConfigureNsx.ps1 @@ -1,9 +1,14 @@ +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + <# .NOTES =================================================================================================================== Created by: Gary Blake - Senior Staff Solutions Architect Date: 2021-11-09 - Copyright 2022 VMware, Inc. + Copyright 2021-2022 VMware, Inc. =================================================================================================================== .CHANGE_LOG @@ -84,9 +89,9 @@ Try { # Attempting to Integrate NSX-T Data Center with the Standalone Workspace ONE Access Instance Write-LogMessage -Type INFO -Message "Attempting to Integrate NSX-T Data Center with the Standalone Workspace ONE Access Instance" $StatusMsg = Set-WorkspaceOneNsxtIntegration -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $mgmtSddcDomainName -wsaFqdn $wsaFqdn -wsaUser admin -wsaPass $wsaAdminPassword -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg - if ( $StatusMsg -match "SUCCESFUL" ) { Write-LogMessage -Type INFO -Message "Integrating NSX-T Data Center with Workspace ONE Access for Workload Domain ($mgmtSddcDomainName): SUCCESFUL" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + if ( $StatusMsg -match "SUCCESSFUL" ) { Write-LogMessage -Type INFO -Message "Integrating NSX-T Data Center with Workspace ONE Access for Workload Domain ($mgmtSddcDomainName): SUCCESSFUL" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } $StatusMsg = Set-WorkspaceOneNsxtIntegration -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $wldSddcDomainName -wsaFqdn $wsaFqdn -wsaUser admin -wsaPass $wsaAdminPassword -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg - if ( $StatusMsg -match "SUCCESFUL" ) { Write-LogMessage -Type INFO -Message "Integrating NSX-T Data Center with Workspace ONE Access for Workload Domain ($wldSddcDomainName): SUCCESFUL" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + if ( $StatusMsg -match "SUCCESSFUL" ) { Write-LogMessage -Type INFO -Message "Integrating NSX-T Data Center with Workspace ONE Access for Workload Domain ($wldSddcDomainName): SUCCESSFUL" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } # Attempting to Assign NSX-T Data Center Roles to Active Directory Groups Write-LogMessage -Type INFO -Message "Attempting to Assign NSX-T Data Center Roles to Active Directory Groups" diff --git a/SampleScripts/iam/iamConfigureVsphere.ps1 b/SampleScripts/iam/iamConfigureVsphere.ps1 index d1f16898..625952ec 100644 --- a/SampleScripts/iam/iamConfigureVsphere.ps1 +++ b/SampleScripts/iam/iamConfigureVsphere.ps1 @@ -1,9 +1,14 @@ +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + <# .NOTES =================================================================================================================== Created by: Gary Blake - Senior Staff Solutions Architect Date: 2021-11-09 - Copyright 2022 VMware, Inc. + Copyright 2021-2022 VMware, Inc. =================================================================================================================== .CHANGE_LOG @@ -129,6 +134,29 @@ Try { Get-SsoPasswordPolicy | Set-SsoPasswordPolicy -ProhibitedPreviousPasswordsCount $passwordCount -MinLength $minLength -MaxLength $maxLength -MinNumericCount $minNumericCount -MinSpecialCharCount $minSpecialCharCount -MaxIdenticalAdjacentCharacters $maxIdenticalAdjacentCharacters -MinAlphabeticCount $minAlphabeticCount -MinUppercaseCount $minUppercaseCount -MinLowercaseCount $minLowercaseCount -PasswordLifetimeDays $passwordLifetimeDays | Out-Null Disconnect-SsoAdminServer -Server $ssoServerFqdn | Out-Null Write-LogMessage -Type INFO -Message "Configuring vCenter Single Sign-On Password Policy: SUCCESSFUL" + + # Attempting to Configure the vCenter Single Sign-On Lockout Policy + Write-LogMessage -Type INFO -Message "Attempting to Configure the vCenter Single Sign-On Lockout Policy" + Connect-SsoAdminServer -Server $ssoServerFqdn -User $ssoServerUser -Password $ssoServerPass | Out-Null + Get-SsoLockoutPolicy | Set-SsoLockoutPolicy -AutoUnlockIntervalSec $autoUnlockIntervalSec -FailedAttemptIntervalSec $failedAttemptIntervalSec -MaxFailedAttempts $maxFailedAttempts | Out-Null + Disconnect-SsoAdminServer -Server $ssoServerFqdn | Out-Null + Write-LogMessage -Type INFO -Message "Configuring vCenter Single Sign-On Lockout Policy: SUCCESSFUL" + + # Attempting to Assign Active Directory Groups to Roles in SDDC Manager + Write-LogMessage -Type INFO -Message "Attempting to Assign Active Directory Groups to Roles in SDDC Manager" + $StatusMsg = Add-SddcManagerRole -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $domainFqdn -domainBindUser $domainBindUser -domainBindPass $domainBindPass -principal $vcfAdminGroup -role ADMIN -type group -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + $StatusMsg = Add-SddcManagerRole -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $domainFqdn -domainBindUser $domainBindUser -domainBindPass $domainBindPass -principal $vcfOperatorGroup -role OPERATOR -type group -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + $StatusMsg = Add-SddcManagerRole -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $domainFqdn -domainBindUser $domainBindUser -domainBindPass $domainBindPass -principal $vcfViewerGroup -role VIEWER -type group -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Attempting to Configure ESXi Hosts Password and Lockout Policies + Write-LogMessage -Type INFO -Message "Attempting to Configure ESXi Hosts Password and Lockout Policies" + $StatusMsg = Set-EsxiPasswordPolicy -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $mgmtSddcDomainName -cluster $mgmtCluster -policy $policy -detail false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + $StatusMsg = Set-EsxiPasswordPolicy -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $wldSddcDomainName -cluster $wldCluster -policy $policy -detail false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } } } } diff --git a/SampleScripts/iam/iamConfigureWorkspaceOne.ps1 b/SampleScripts/iam/iamConfigureWorkspaceOne.ps1 index 282103a1..845d0fa0 100644 --- a/SampleScripts/iam/iamConfigureWorkspaceOne.ps1 +++ b/SampleScripts/iam/iamConfigureWorkspaceOne.ps1 @@ -1,14 +1,20 @@ +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + <# .NOTES =================================================================================================================== Created by: Gary Blake - Senior Staff Solutions Architect Date: 2021-11-10 - Copyright 2022 VMware, Inc. + Copyright 2021-2022 VMware, Inc. =================================================================================================================== .CHANGE_LOG - 1.0.001 (Gary Blake / 2022-01-04) - Improved the connection handling when starting the script - 1.0.002 (Gary Blake / 2022-02-16) - Added support for both VCF 4.3.x and VCF 4.4.x Planning and Prep Workbooks + - 1.0.003 (Gary Blake / 2022-03-01) - Updated input values to use latest VCF 4.4.x Planning and Prep Workbook =================================================================================================================== @@ -61,44 +67,44 @@ Try { Break } - $domainFqdn = $pnpWorkbook.Workbook.Names["region_ad_child_fqdn"].Value - $mgmtSddcDomainName = $pnpWorkbook.Workbook.Names["mgmt_sddc_domain"].Value - $wsaFolder = $pnpWorkbook.Workbook.Names["mgmt_region_wsa_vm_folder"].Value - $wsaIpAddress = $pnpWorkbook.Workbook.Names["region_wsa_ip"].Value - $wsaGateway = $pnpWorkbook.Workbook.Names["reg_seg01_gateway_ip"].Value - $wsaSubnetMask = $pnpWorkbook.Workbook.Names["reg_seg01_mask_overlay_backed"].Value - $wsaOvaFile = "identity-manager-3.3.5.0-18049997_OVF10.ova" + $domainFqdn = $pnpWorkbook.Workbook.Names["region_ad_child_fqdn"].Value + $mgmtSddcDomainName = $pnpWorkbook.Workbook.Names["mgmt_sddc_domain"].Value + $wsaFolder = $pnpWorkbook.Workbook.Names["mgmt_region_wsa_vm_folder"].Value + $wsaIpAddress = $pnpWorkbook.Workbook.Names["region_wsa_ip"].Value + $wsaGateway = $pnpWorkbook.Workbook.Names["reg_seg01_gateway_ip"].Value + $wsaSubnetMask = $pnpWorkbook.Workbook.Names["reg_seg01_mask_overlay_backed"].Value + $wsaOvaFile = "identity-manager-3.3.6.0-19203469_OVF10.ova" if (!(Test-Path ($filePath + "\" + $wsaOvaFile) )) { Write-LogMessage -Type ERROR -Message "Unable to Find OVA File: $wsaOvaFile, check details and try again" -Colour Red; Break } else { Write-LogMessage -Type INFO -Message "Found OVA File: $wsaOvaFile" } - $wsaFqdn = $pnpWorkbook.Workbook.Names["region_wsa_fqdn"].Value - $wsaHostname = $wsaFqdn.Split(".")[0] - $drsGroupName = "sfo-m01-vm-group-wsa" - $drsGroupVMs = "sfo-wsa01" - $wsaAdminPassword = $pnpWorkbook.Workbook.Names["standalone_wsa_appliance_admin_password"].Value - $wsaRootPassword = $pnpWorkbook.Workbook.Names["standalone_wsa_appliance_root_password"].Value - $wsaSshUserPassword = $pnpWorkbook.Workbook.Names["standalone_wsa_appliance_sshuser_password"].Value - $smtpServerFqdn = $pnpWorkbook.Workbook.Names["smtp_server"].Value - $smtpServerPort = $pnpWorkbook.Workbook.Names["smtp_server_port"].Value - $smtpEmailAddress = $pnpWorkbook.Workbook.Names["standalone_wsa_appliance_notifications_address"].Value - $baseGroupDn = $pnpWorkbook.Workbook.Names["child_ad_groups_ou"].Value - $baseUserDn = $pnpWorkbook.Workbook.Names["child_ad_users_ou"].Value - $wsabindUserDn = "cn=" + $pnpWorkbook.Workbook.Names["child_svc_wsa_ad_user"].Value + "," + $pnpWorkbook.Workbook.Names["child_ad_users_ou"].Value - $wsabindUserPassword = $pnpWorkbook.Workbook.Names["child_svc_wsa_ad_password"].Value - $wsaSuperAdminGroup = $pnpWorkbook.Workbook.Names["group_child_gg_wsa_admins"].Value - $wsaDirAdminGroup = $pnpWorkbook.Workbook.Names["group_child_gg_wsa_directory_admins"].Value - $wsaReadOnlyGroup = $pnpWorkbook.Workbook.Names["group_child_gg_wsa_read_only"].Value - $adGroups = "$($pnpWorkbook.Workbook.Names["group_gg_nsx_enterprise_admins"].Value)","$($pnpWorkbook.Workbook.Names["group_gg_nsx_network_admins"].Value)","$($pnpWorkbook.Workbook.Names["group_gg_nsx_auditors"].Value)","$wsaSuperAdminGroup","$wsaDirAdminGroup","$wsaReadOnlyGroup" - $minLen = $pnpWorkbook.Workbook.Names["standalone_wsa_password_min_length"].Value - $minLower = $pnpWorkbook.Workbook.Names["standalone_wsa_password_lowercase_chars"].Value - $minUpper = $pnpWorkbook.Workbook.Names["standalone_wsa_password_uppercase_chars"].Value - $minDigit = $pnpWorkbook.Workbook.Names["standalone_wsa_password_numerical_chars"].Value - $minSpecial = $pnpWorkbook.Workbook.Names["standalone_wsa_password_special_chars"].Value - $history = $pnpWorkbook.Workbook.Names["standalone_wsa_password_history"].Value - $maxConsecutiveIdenticalCharacters = $pnpWorkbook.Workbook.Names["standalone_wsa_password_consecutive_identical_chars"].Value - $tempPasswordTtlInHrs = $pnpWorkbook.Workbook.Names["standalone_wsa_password_temp_lifetime"].Value + $wsaFqdn = $pnpWorkbook.Workbook.Names["region_wsa_fqdn"].Value + $wsaHostname = $wsaFqdn.Split(".")[0] + $drsGroupName = $pnpWorkbook.Workbook.Names["mgmt_sddc_domain"].Value + "-vm-group-wsa" + $drsGroupVMs = $wsaHostname + $wsaAdminPassword = $pnpWorkbook.Workbook.Names["standalone_wsa_appliance_admin_password"].Value + $wsaRootPassword = $pnpWorkbook.Workbook.Names["standalone_wsa_appliance_root_password"].Value + $wsaSshUserPassword = $pnpWorkbook.Workbook.Names["standalone_wsa_appliance_sshuser_password"].Value + $smtpServerFqdn = $pnpWorkbook.Workbook.Names["smtp_server"].Value + $smtpServerPort = $pnpWorkbook.Workbook.Names["smtp_server_port"].Value + $smtpEmailAddress = $pnpWorkbook.Workbook.Names["standalone_wsa_appliance_notifications_address"].Value + $baseGroupDn = $pnpWorkbook.Workbook.Names["child_ad_groups_ou"].Value + $baseUserDn = $pnpWorkbook.Workbook.Names["child_ad_users_ou"].Value + $wsabindUserDn = "cn=" + $pnpWorkbook.Workbook.Names["child_svc_wsa_ad_user"].Value + "," + $pnpWorkbook.Workbook.Names["child_ad_users_ou"].Value + $wsabindUserPassword = $pnpWorkbook.Workbook.Names["child_svc_wsa_ad_password"].Value + $wsaSuperAdminGroup = $pnpWorkbook.Workbook.Names["group_child_gg_wsa_admins"].Value + $wsaDirAdminGroup = $pnpWorkbook.Workbook.Names["group_child_gg_wsa_directory_admins"].Value + $wsaReadOnlyGroup = $pnpWorkbook.Workbook.Names["group_child_gg_wsa_read_only"].Value + $adGroups = "$($pnpWorkbook.Workbook.Names["group_gg_nsx_enterprise_admins"].Value)","$($pnpWorkbook.Workbook.Names["group_gg_nsx_network_admins"].Value)","$($pnpWorkbook.Workbook.Names["group_gg_nsx_auditors"].Value)","$wsaSuperAdminGroup","$wsaDirAdminGroup","$wsaReadOnlyGroup" + $minLen = $pnpWorkbook.Workbook.Names["standalone_wsa_password_min_length"].Value + $minLower = $pnpWorkbook.Workbook.Names["standalone_wsa_password_lowercase_chars"].Value + $minUpper = $pnpWorkbook.Workbook.Names["standalone_wsa_password_uppercase_chars"].Value + $minDigit = $pnpWorkbook.Workbook.Names["standalone_wsa_password_numerical_chars"].Value + $minSpecial = $pnpWorkbook.Workbook.Names["standalone_wsa_password_special_chars"].Value + $history = $pnpWorkbook.Workbook.Names["standalone_wsa_password_history"].Value + $maxConsecutiveIdenticalCharacters = $pnpWorkbook.Workbook.Names["standalone_wsa_password_consecutive_identical_chars"].Value + $tempPasswordTtlInHrs = $pnpWorkbook.Workbook.Names["standalone_wsa_password_temp_lifetime"].Value $maxPreviousPasswordCharactersReused = "0" - $passwordTtlInDays = "90" - $notificationThresholdInDays = "15" - $notificationIntervalInDays = "3" + $passwordTtlInDays = $pnpWorkbook.Workbook.Names["standalone_wsa_password_lifetime"].Value + $notificationThresholdInDays = $pnpWorkbook.Workbook.Names["standalone_wsa_password_reminder"].Value + $notificationIntervalInDays = $pnpWorkbook.Workbook.Names["standalone_wsa_password_reminder_notification_frequency"].Value $numAttempts = $pnpWorkbook.Workbook.Names["standalone_wsa_password_failed_attempts"].Value $attemptInterval = $pnpWorkbook.Workbook.Names["standalone_wsa_password_failed_auth_attempts_interval"].Value $unlockInterval = $pnpWorkbook.Workbook.Names["standalone_wsa_password_account_lockdown_duration"].Value diff --git a/SampleScripts/iam/iamUndoDeployment.ps1 b/SampleScripts/iam/iamUndoDeployment.ps1 new file mode 100644 index 00000000..a19adffa --- /dev/null +++ b/SampleScripts/iam/iamUndoDeployment.ps1 @@ -0,0 +1,171 @@ +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +<# + .NOTES + =================================================================================================================== + Created by: Gary Blake - Senior Staff Solutions Architect + Date: 2022-03-01 + Copyright 2021-2022 VMware, Inc. + =================================================================================================================== + + .SYNOPSIS + Remove Identity and Access Management from a VMware Cloud Foundation Instance + + .DESCRIPTION + The iamUndoDeployment.ps1 provides a single script to remove Identity and Access Management from a VMware Cloud + Foundation Instance + + .EXAMPLE + iamUndoDeployment.ps1 -sddcManagerFqdn sfo-vcf01.sfo.rainpole.io -sddcManagerUser administrator@vsphere.local -sddcManagerPass VMw@re1! -workbook F:\vvs\PnP.xlsx -filePath F:\vvs + This example performs the removal of Identity and Access Management from a VMware Cloud Foundation Instance using the parameters provided within the Planning and Preparation Workbook +#> + +Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerFqdn, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerUser, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerPass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$workbook, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$filePath +) + +Clear-Host; Write-Host "" + +Start-SetupLogFile -Path $filePath -ScriptName $MyInvocation.MyCommand.Name +Write-LogMessage -Type INFO -Message "Starting the Process of Removing Identity and Access Management from a VMware Cloud Foundation Instance" -Colour Yellow +Write-LogMessage -Type INFO -Message "Setting up the log file to path $logfile" + +Try { + Write-LogMessage -Type INFO -Message "Checking Existance of Planning and Preparation Workbook: $workbook" + if (!(Test-Path $workbook )) { + Write-LogMessage -Type ERROR -Message "Unable to Find Planning and Preparation Workbook: $workbook, check details and try again" -Colour Red + Break + } + else { + Write-LogMessage -Type INFO -Message "Found Planning and Preparation Workbook: $workbook" + } + Write-LogMessage -Type INFO -Message "Checking a Connection to SDDC Manager: $sddcManagerFqdn" + if (Test-VCFConnection -server $sddcManagerFqdn ) { + Write-LogMessage -Type INFO -Message "Attempting to connect to VMware Cloud Foundation to Gather System Details" + if (Test-VCFAuthentication -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass) { + Write-LogMessage -Type INFO -Message "Gathering Details from SDDC Manager Inventory and Extracting Worksheet Data from the Excel Workbook" + Write-LogMessage -type INFO -message "Opening the Excel Workbook: $Workbook" + $pnpWorkbook = Open-ExcelPackage -Path $Workbook + Write-LogMessage -type INFO -message "Checking Valid Planning and Prepatation Workbook Provided" + if (($pnpWorkbook.Workbook.Names["vcf_version"].Value -ne "v4.3.x") -and ($pnpWorkbook.Workbook.Names["vcf_version"].Value -ne "v4.4.x")) { + Write-LogMessage -type INFO -message "Planning and Prepatation Workbook Provided Not Supported" -colour Red + Break + } + + $domainFqdn = $pnpWorkbook.Workbook.Names["region_ad_child_fqdn"].Value + $ssoDomainFqdn = "vsphere.local" + $mgmtSddcDomainName = $pnpWorkbook.Workbook.Names["mgmt_sddc_domain"].Value + $wldSddcDomainName = $pnpWorkbook.Workbook.Names["wld_sddc_domain"].Value + $nsxEnterpriseAdminGroup = $pnpWorkbook.Workbook.Names["group_gg_nsx_enterprise_admins"].Value + "@" + $domainFqdn + $nsxNetworkEngineerGroup = $pnpWorkbook.Workbook.Names["group_gg_nsx_network_admins"].Value + "@" + $domainFqdn + $nsxAuditorGroup = $pnpWorkbook.Workbook.Names["group_gg_nsx_auditors"].Value + "@" + $domainFqdn + $wsaFqdn = $pnpWorkbook.Workbook.Names["region_wsa_fqdn"].Value + $wsaAdminPassword = $pnpWorkbook.Workbook.Names["standalone_wsa_appliance_admin_password"].Value + $wsaFolder = $pnpWorkbook.Workbook.Names["mgmt_region_wsa_vm_folder"].Value + $wsaHostname = $pnpWorkbook.Workbook.Names["region_wsa_hostname"].Value + $drsGroupName = $mgmtSddcDomainName + "-vm-group-wsa" + $vcfAdminGroup = $pnpWorkbook.Workbook.Names["group_gg_vcf_admins"].Value + $vcfOperatorGroup = $pnpWorkbook.Workbook.Names["group_gg_vcf_operators"].Value + $vcfViewerGroup = $pnpWorkbook.Workbook.Names["group_gg_vcf_viewers"].Value + $ssoAdminGroup = $pnpWorkbook.Workbook.Names["group_gg_sso_admins"].Value + $vcenterAdminGroup = $pnpWorkbook.Workbook.Names["group_gg_vc_admins"].Value + $vcenterReadOnlyGroup = $pnpWorkbook.Workbook.Names["group_gg_vc_read_only"].Value + $vsphereRoleName = $pnpWorkbook.Workbook.Names["nsxt_vsphere_role_name"].Value + $mgmtServiceAccount = "svc-" + $pnpWorkbook.Workbook.Names["mgmt_nsxt_hostname"].Value + "-" + $pnpWorkbook.Workbook.Names["mgmt_vc_hostname"].Value + $wldServiceAccount = "svc-" + $pnpWorkbook.Workbook.Names["wld_nsxt_hostname"].Value + "-" + $pnpWorkbook.Workbook.Names["wld_vc_hostname"].Value + + # Remove NSX-T Data Center Service Accounts from the vCenter Single Sign-On Built-In Identity Provider License Administrators Group + Write-LogMessage -Type INFO -Message "Attempting to Remove NSX-T Data Center Service Accounts from the vCenter Single Sign-On Built-In Identity Provider License Administrators Group" + $StatusMsg = Undo-SsoPermission -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -sddcDomain $mgmtSddcDomainName -domain $ssoDomainFqdn -principal $mgmtServiceAccount -ssoGroup "LicenseService.Administrators" -type user -source local -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + $StatusMsg = Undo-SsoPermission -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -sddcDomain $wldSddcDomainName -domain $ssoDomainFqdn -principal $wldServiceAccount -ssoGroup "LicenseService.Administrators" -type user -source local -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Remove Active Directory Groups from NSX-T Data Center Roles + Write-LogMessage -Type INFO -Message "Attempting to Remove Active Directory Groups from NSX-T Data Center Roles" + $StatusMsg = Undo-NsxtVidmRole -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $mgmtSddcDomainName -principal $nsxEnterpriseAdminGroup -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + $StatusMsg = Undo-NsxtVidmRole -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $mgmtSddcDomainName -principal $nsxNetworkEngineerGroup -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + $StatusMsg = Undo-NsxtVidmRole -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $mgmtSddcDomainName -principal $nsxAuditorGroup -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + $StatusMsg = Undo-NsxtVidmRole -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $wldSddcDomainName -principal $nsxEnterpriseAdminGroup -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + $StatusMsg = Undo-NsxtVidmRole -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $wldSddcDomainName -principal $nsxNetworkEngineerGroup -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + $StatusMsg = Undo-NsxtVidmRole -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $wldSddcDomainName -principal $nsxAuditorGroup -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Disable Integration between NSX-T Data Center with the Standalone Workspace ONE Access Instance + Write-LogMessage -Type INFO -Message "Attempting to Disable Integration between NSX-T Data Center with the Standalone Workspace ONE Access Instance" + $StatusMsg = Undo-WorkspaceOneNsxtIntegration -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $mgmtSddcDomainName -wsaFqdn $wsaFqdn -wsaUser admin -wsaPass $wsaAdminPassword -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + $StatusMsg = Undo-WorkspaceOneNsxtIntegration -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $wldSddcDomainName -wsaFqdn $wsaFqdn -wsaUser admin -wsaPass $wsaAdminPassword -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Remove the Standalone Workspace ONE Access Instance + Write-LogMessage -Type INFO -Message "Attempting to Remove the Standalone Workspace ONE Access Instance" + $StatusMsg = Undo-WorkspaceOne -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -wsaHostname $wsaHostname -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Remove a VM Group for the Standalone Workspace ONE Access Instance + Write-LogMessage -Type INFO -Message "Attempting to Remove a VM Group for the Standalone Workspace ONE Access Instance" + $StatusMsg = Undo-ClusterGroup -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $mgmtSddcDomainName -drsGroupName $drsGroupName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Remove Virtual Machine and Template Folder for the Standalone Workspace ONE Access Instance + Write-LogMessage -Type INFO -Message "Attempting to Remove Virtual Machine and Template Folder for the Standalone Workspace ONE Access Instance" + $StatusMsg = Undo-VMFolder -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $mgmtSddcDomainName -folderName $wsaFolder -folderType VM -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Remove Active Directory Groups from SDDC Manager Roles + Write-LogMessage -Type INFO -Message "Remove Active Directory Groups from SDDC Manager Roles" + $StatusMsg = Undo-SddcManagerRole -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -principal $vcfAdminGroup -type GROUP -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + $StatusMsg = Undo-SddcManagerRole -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -principal $vcfOperatorGroup -type GROUP -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + $StatusMsg = Undo-SddcManagerRole -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -principal $vcfViewerGroup -type GROUP -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Remove Active Directory Groups from vCenter Single Sign-On Roles + Write-LogMessage -Type INFO -Message "Attempting to Remove Active Directory Groups from vCenter Single Sign-On Roles" + $StatusMsg = Undo-SsoPermission -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -sddcDomain $mgmtSddcDomainName -domain $domainFqdn -principal $ssoAdminGroup -ssoGroup "Administrators" -type group -source external -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Remove Active Directory Groups from vCenter Server Roles + Write-LogMessage -Type INFO -Message "Attempting to Remove Active Directory Groups from vCenter Server Roles" + $StatusMsg = Undo-vCenterGlobalPermission -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $domainFqdn -principal $vcenterAdminGroup -type group -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + $StatusMsg = Undo-vCenterGlobalPermission -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $domainFqdn -principal $vcenterReadOnlyGroup -type group -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Remove Active Directory as Identity Provider from Management vCenter Server + Write-LogMessage -Type INFO -Message "Attempting to Remove Active Directory as Identity Provider from Management vCenter Server" + $StatusMsg = Undo-IdentitySource -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $domainFqdn -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Reconfigure the vSphere Role for NSX-T Data Center Service Accounts + Write-LogMessage -Type INFO -Message "Reconfigure the vSphere Role for NSX-T Data Center Service Accounts" + $StatusMsg = Set-vCenterPermission -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain vsphere.local -workloadDomain $mgmtSddcDomainName -principal $wldServiceAccount -role "Admin" -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + $StatusMsg = Set-vCenterPermission -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain vsphere.local -workloadDomain $wldSddcDomainName -principal $mgmtServiceAccount -role "Admin" -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Remove the Custom Role from vSphere for the NSX-T Data Center Service Accounts + Write-LogMessage -Type INFO -Message "Remove the Custom Role from vSphere for the NSX-T Data Center Service Accounts" + $StatusMsg = Undo-vSphereRole -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -roleName $vsphereRoleName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + } + } +} +Catch { + Debug-CatchWriter -object $_ +} \ No newline at end of file diff --git a/SampleScripts/ila/ilaConfigureVrealizeLogInsight.ps1 b/SampleScripts/ila/ilaConfigureVrealizeLogInsight.ps1 index 69212874..100454c0 100644 --- a/SampleScripts/ila/ilaConfigureVrealizeLogInsight.ps1 +++ b/SampleScripts/ila/ilaConfigureVrealizeLogInsight.ps1 @@ -1,9 +1,14 @@ +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + <# .NOTES =================================================================================================================== Created by: Gary Blake - Senior Staff Solutions Architect Date: 2021-11-27 - Copyright 2021 VMware, Inc. + Copyright 2021-2022 VMware, Inc. =================================================================================================================== .CHANGE_LOG @@ -64,8 +69,6 @@ Try { $sddcWldDomainName = $pnpWorkbook.Workbook.Names["wld_sddc_domain"].Value $domain = $pnpWorkbook.Workbook.Names["parent_dns_zone"].Value $subDomain = $pnpWorkbook.Workbook.Names["child_dns_zone"].Value - - $exportName = "ILA-VRLI" $vmNameNode1 = $pnpWorkbook.Workbook.Names["xreg_wsa_nodea_hostname"].Value $vmNameNode2 = $pnpWorkbook.Workbook.Names["xreg_wsa_nodeb_hostname"].Value $vmNameNode3 = $pnpWorkbook.Workbook.Names["xreg_wsa_nodec_hostname"].Value @@ -80,9 +83,9 @@ Try { # Configure the NSX Edge Nodes to Forward Log Events to vRealize Log Insight Write-LogMessage -Type INFO -Message "Configure the NSX Edge Nodes to Forward Log Events to vRealize Log Insight" - $StatusMsg = Set-vRLISyslogEdgeCluster -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcDomainName -exportname $exportName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + $StatusMsg = Add-NsxtNodeProfileSyslogExporter -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcDomainName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "Configuring the NSX Edge Nodes to Forward Log Events to vRealize Log Insight for Workload Domain ($sddcDomainName): SUCCESSFUL" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message "Configuring the NSX Edge Nodes to Forward Log Events to vRealize Log Insight for Workload Domain ($sddcWldDomainName), already exists: SKIPPED" -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } - $StatusMsg = Set-vRLISyslogEdgeCluster -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcWldDomainName -exportname $exportName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + $StatusMsg = Add-NsxtNodeProfileSyslogExporter -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcWldDomainName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "Configuring the NSX Edge Nodes to Forward Log Events to vRealize Log Insight for Workload Domain ($sddcWldDomainName): SUCCESSFUL" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message "Configuring the NSX Edge Nodes to Forward Log Events to vRealize Log Insight for Workload Domain ($sddcWldDomainName), already exists: SKIPPED" -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } # Download, Install and Configure the vRealize Log Insight Agent on the Clustered Workspace ONE Access Nodes diff --git a/SampleScripts/ila/ilaDeployVrealizeLogInsight.ps1 b/SampleScripts/ila/ilaDeployVrealizeLogInsight.ps1 index 218ef7cd..f5d3f9c9 100644 --- a/SampleScripts/ila/ilaDeployVrealizeLogInsight.ps1 +++ b/SampleScripts/ila/ilaDeployVrealizeLogInsight.ps1 @@ -1,9 +1,14 @@ +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + <# .NOTES =================================================================================================================== Created by: Gary Blake - Senior Staff Solutions Architect Date: 2021-11-27 - Copyright 2021 VMware, Inc. + Copyright 2021-2022 VMware, Inc. =================================================================================================================== .CHANGE_LOG @@ -104,7 +109,7 @@ Try { if (!(Test-Path ($filePath + "\" + $vrliPem) )) { Write-LogMessage -Type ERROR -Message "Unable to Find Certificate File: $vrliPem, check details and try again" -Colour Red; Break } else { Write-LogMessage -Type INFO -Message "Found Certificate File: $vrliPem" } # Add vRealize Log Insight License to vRealize Suite Lifecycle Manager - Write-LogMessage -Type INFO -Message "Add the vRealize Operations Manager License to vRealize Suite Lifecycle Manager" + Write-LogMessage -Type INFO -Message "Add the vRealize Log Insight License to vRealize Suite Lifecycle Manager" $StatusMsg = New-vRSLCMLockerLicense -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -alias $licenseAlias -license $licenseKey -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } @@ -169,7 +174,7 @@ Try { # Sync Active Directory Groups to Workspace ONE Access Write-LogMessage -Type INFO -Message "Sync Active Directory Groups to Workspace ONE Access" - $StatusMsg = Add-WorkspaceOneDirectoryGroup -server $wsaFqdn -user $wsaUser -pass $wsaPass -domain $domain -bindUser $bindUser -bindPass $bindPass -baseDnGroup $baseDnGroup -adGroups $adGroups -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + $StatusMsg = Add-WorkspaceOneDirectoryGroup -server $wsaFqdn -user $wsaUser -pass $wsaPass -domain $domain -bindUser $bindUser -bindPass $bindPass -baseDnGroup $baseDnGroup -adGroups $adGroups -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } # Assign vRealize Log Insight Roles to Active Directory Groups diff --git a/SampleScripts/ila/ilaUndoVrealizeLogInsight.ps1 b/SampleScripts/ila/ilaUndoVrealizeLogInsight.ps1 new file mode 100644 index 00000000..b695378a --- /dev/null +++ b/SampleScripts/ila/ilaUndoVrealizeLogInsight.ps1 @@ -0,0 +1,185 @@ +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +<# + .NOTES + =================================================================================================================== + Created by: Gary Blake - Senior Staff Solutions Architect + Date: 2022-03-04 + Copyright 2021-2022 VMware, Inc. + =================================================================================================================== + + .SYNOPSIS + Remove Intelligent Logging and Analytics from a VMware Cloud Foundation instance + + .DESCRIPTION + The ilaUndoVrealizeLogInsight.ps1 provides a single script to remove Intelligent Logging and Analytics from a + VMware Cloud Foundation instance + + .EXAMPLE + ilaConfigureVrealizeLogInsight.ps1 -sddcManagerFqdn sfo-vcf01.sfo.rainpole.io -sddcManagerUser administrator@vsphere.local -sddcManagerPass VMw@re1! -workbook F:\vvs\PnP.xlsx -filePath F:\vvs + This example performs the removal of Intelligent Logging and Analytics from a VMware Cloud Foundation instance using the parameters provided within the Planning and Preparation Workbook +#> + +Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerFqdn, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerUser, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerPass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$workbook, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$filePath +) + +Clear-Host; Write-Host "" + +Start-SetupLogFile -Path $filePath -ScriptName $MyInvocation.MyCommand.Name +Write-LogMessage -Type INFO -Message "Starting thw Process of Removing Intelligent Logging and Analytics from a VMware Cloud Foundation instance" -Colour Yellow +Write-LogMessage -Type INFO -Message "Setting up the log file to path $logfile" + +Try { + Write-LogMessage -Type INFO -Message "Checking Existance of Planning and Preparation Workbook: $workbook" + if (!(Test-Path $workbook )) { + Write-LogMessage -Type ERROR -Message "Unable to Find Planning and Preparation Workbook: $workbook, check details and try again" -Colour Red + Break + } + else { + Write-LogMessage -Type INFO -Message "Found Planning and Preparation Workbook: $workbook" + } + Write-LogMessage -Type INFO -Message "Checking a Connection to SDDC Manager: $sddcManagerFqdn" + if (Test-VCFConnection -server $sddcManagerFqdn ) { + Write-LogMessage -Type INFO -Message "Attempting to connect to VMware Cloud Foundation to Gather System Details" + if (Test-VCFAuthentication -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass) { + Write-LogMessage -Type INFO -Message "Gathering Details from SDDC Manager Inventory and Extracting Worksheet Data from the Excel Workbook" + Write-LogMessage -type INFO -message "Opening the Excel Workbook: $Workbook" + $pnpWorkbook = Open-ExcelPackage -Path $Workbook + Write-LogMessage -type INFO -message "Checking Valid Planning and Prepatation Workbook Provided" + if (($pnpWorkbook.Workbook.Names["vcf_version"].Value -ne "v4.3.x") -and ($pnpWorkbook.Workbook.Names["vcf_version"].Value -ne "v4.4.x")) { + Write-LogMessage -type INFO -message "Planning and Prepatation Workbook Provided Not Supported" -colour Red + Break + } + + # $sddcDomainName = $pnpWorkbook.Workbook.Names["mgmt_sddc_domain"].Value + + # $domain = $pnpWorkbook.Workbook.Names["parent_dns_zone"].Value + # $subDomain = $pnpWorkbook.Workbook.Names["child_dns_zone"].Value + + # $vidmVmList = "$vmNameNode1.$domain","$vmNameNode2.$domain","$vmNameNode2.$domain" + # $photonVmList = "$($pnpWorkbook.Workbook.Names["sddc_mgr_hostname"].Value).$subDomain","$($pnpWorkbook.Workbook.Names["xreg_vrslcm_hostname"].Value).$domain","$vmNameNode1.$domain","$vmNameNode2.$domain","$vmNameNode3.$domain" + # $licenseKey = if ($pnpWorkbook.Workbook.Names["vrs_license"].Value) { $pnpWorkbook.Workbook.Names["vrs_license"].Value } else { $pnpWorkbook.Workbook.Names["vrli_license"].Value } + # $password = $pnpWorkbook.Workbook.Names["region_vrli_admin_password"].Value + # $userName = "admin" + + # $vrliVmList = $pnpWorkbook.Workbook.Names["region_vrli_nodea_hostname"].Value + "," + $pnpWorkbook.Workbook.Names["region_vrli_nodeb_hostname"].Value + "," + $pnpWorkbook.Workbook.Names["region_vrli_nodec_hostname"].Value + + # $antiAffinityVMs = $vrliVmList + # $drsGroupNameWsa = $pnpWorkbook.Workbook.Names["xreg_wsa_vm_group_name"].Value + # $drsGroupVMs = $vrliVmList + # $groupName = "primary_az_vmgroup" + # $stretchedCluster = $pnpWorkbook.Workbook.Names["mgmt_stretched_cluster_chosen"].Value + # $vmList = $vrliVmList + + + # $antiAffinityVMs = $vrliVmList + # $drsGroupNameWsa = $pnpWorkbook.Workbook.Names["xreg_wsa_vm_group_name"].Value + # $drsGroupVMs = $vrliVmList + # $groupName = "primary_az_vmgroup" + # $stretchedCluster = $pnpWorkbook.Workbook.Names["mgmt_stretched_cluster_chosen"].Value + # $vmList = $vrliVmList + + + + $sddcDomainName = $pnpWorkbook.Workbook.Names["mgmt_sddc_domain"].Value + $sddcWldDomainName = $pnpWorkbook.Workbook.Names["wld_sddc_domain"].Value + $vmNameNode1 = $pnpWorkbook.Workbook.Names["xreg_wsa_nodea_hostname"].Value + $vmNameNode2 = $pnpWorkbook.Workbook.Names["xreg_wsa_nodeb_hostname"].Value + $vmNameNode3 = $pnpWorkbook.Workbook.Names["xreg_wsa_nodec_hostname"].Value + $vmRootPass = $pnpWorkbook.Workbook.Names["vrslcm_xreg_env_password"].Value + $wsaFqdn = $pnpWorkbook.Workbook.Names["region_wsa_fqdn"].Value + $wsaUser = "admin" + $wsaPass = $pnpWorkbook.Workbook.Names["standalone_wsa_appliance_admin_password"].Value + $domain = $pnpWorkbook.Workbook.Names["region_ad_child_fqdn"].Value + $bindUser = $pnpWorkbook.Workbook.Names["child_svc_wsa_ad_user"].Value + $bindPass = $pnpWorkbook.Workbook.Names["child_svc_wsa_ad_password"].Value + $baseDnGroup = $pnpWorkbook.Workbook.Names["child_ad_groups_ou"].Value + $vrliAdminGroup = $pnpWorkbook.Workbook.Names["group_gg_vrli_admins"].Value + $vrliUserGroup = $pnpWorkbook.Workbook.Names["group_gg_vrli_users"].Value + $vrliViewerGroup = $pnpWorkbook.Workbook.Names["group_gg_vrli_viewers"].Value + $adGroups = "$vrliAdminGroup","$vrliUserGroup","$vrliViewerGroup" + $environemntName = $pnpWorkbook.Workbook.Names["vrslcm_reg_env"].Value + $ruleName = "vm-vm-rule-wsa-vrli" + $drsGroupNameVrli = $pnpWorkbook.Workbook.Names["region_vrli_vm_group_name"].Value + $antiAffinityRuleName = $pnpWorkbook.Workbook.Names["region_vrli_anti_affinity_rule_name"].Value + $vrliFolder = $pnpWorkbook.Workbook.Names["region_vrli_vm_folder"].Value + $passwordAlias = $pnpWorkbook.Workbook.Names["region_vrli_admin_password_alias"].Value + $certificateAlias = $pnpWorkbook.Workbook.Names["region_vrli_virtual_hostname"].Value + $licenseAlias = "vRealize Log Insight" + + # Remove the vRealize Log Insight Agent on the Clustered Workspace ONE Access Nodes + Write-LogMessage -Type INFO -Message "Attempting to Remove the vRealize Log Insight Agent on the Clustered Workspace ONE Access Nodes" + $StatusMsg = Undo-vRLIPhotonAgent -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -vmName $vmNameNode1 -vmRootPass $vmRootPass -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + $StatusMsg = Undo-vRLIPhotonAgent -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -vmName $vmNameNode2 -vmRootPass $vmRootPass -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + $StatusMsg = Undo-vRLIPhotonAgent -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -vmName $vmNameNode3 -vmRootPass $vmRootPass -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Remove the vRealize Log Insight Configuration from the NSX Edge Nodes + Write-LogMessage -Type INFO -Message "Attempting to Remove the vRealize Log Insight Configuration from the NSX Edge Nodes" + $StatusMsg = Undo-NsxtNodeProfileSyslogExporter -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcDomainName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + $StatusMsg = Undo-NsxtNodeProfileSyslogExporter -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcWldDomainName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Disconnect a VI Workload Domain from vRealize Log Insight + Write-LogMessage -Type INFO -Message "Attempt to Disconnect a VI Workload Domain from vRealize Log Insight" + $StatusMsg = Register-vRLIWorkloadDomain -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcWldDomainName -status DISABLED -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Remove vRelize Log Insight Active Directory Groups from Workspace ONE Access + Write-LogMessage -Type INFO -Message "Attempting to Remove vRelize Log Insight Active Directory Groups from Workspace ONE Access" + $StatusMsg = Undo-WorkspaceOneDirectoryGroup -server $wsaFqdn -user $wsaUser -pass $wsaPass -domain $domain -bindUser $bindUser -bindPass $bindPass -baseDnGroup $baseDnGroup -adGroups $adGroups -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Delete vRealize Log Insight from vRealize Suite Lifecycle Manager + Write-LogMessage -Type INFO -Message "Attempting to Delete vRealize Log Insight from vRealize Suite Lifecycle Manager" + $StatusMsg = Undo-vRLIDeployment -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -environmentName $environemntName -monitor -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Delete the VM Group and Start Up Rule for the vRealize Log Insight Cluster + Write-LogMessage -Type INFO -Message "Attempting to Delete the VM Group and Start Up Rule for the vRealize Log Insight Cluster" + $StatusMsg = Undo-VmStartupRule -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcDomainName -ruleName $ruleName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + $StatusMsg = Undo-ClusterGroup -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcDomainName -drsGroupName $drsGroupNameVrli -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Delete the vSphere DRS Anti-Affinity Rule for vRealize Log Insight + Write-LogMessage -Type INFO -Message "Attempting to Delete the vSphere DRS Anti-Affinity Rule for vRealize Log Insight" + $StatusMsg = Undo-AntiAffinityRule -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcDomainName -ruleName $antiAffinityRuleName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Delete the Virtual Machine and Template Folder for vRealize Log Insight + Write-LogMessage -Type INFO -Message "Attempting Delete the Virtual Machine and Template Folder for vRealize Log Insight" + $StatusMsg = Undo-VMFolder -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcDomainName -foldername $vrliFolder -folderType VM -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Delete the vRealize Log Insight Admin Password from vRealize Suite Lifecycle Manager + Write-LogMessage -Type INFO -Message "Attempted to Delete the vRealize Log Insight Admin Password from vRealize Suite Lifecycle Manager" + $StatusMsg = Undo-vRSLCMLockerPassword -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -alias $passwordAlias -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Delete the vRealize Log Insight Certificate from vRealize Suite Lifecycle Manager + Write-LogMessage -Type INFO -Message "Attempting to Delete the vRealize Log Insight Certificate from vRealize Suite Lifecycle Manager" + $StatusMsg = Undo-vRSLCMLockerCertificate -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -certificateAlias $certificateAlias -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Delete vRealize Log Insight License from vRealize Suite Lifecycle Manager + Write-LogMessage -Type INFO -Message "Attempting to Delete vRealize Log Insight License from vRealize Suite Lifecycle Manager" + $StatusMsg = Undo-vRSLCMLockerLicense -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -alias $licenseAlias -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + } + } +} +Catch { + Debug-CatchWriter -object $_ +}