From 7c4336ed2544a13a366189f6139e77abb02d3cc6 Mon Sep 17 00:00:00 2001 From: GaryJBlake Date: Tue, 25 Jan 2022 11:53:34 +0000 Subject: [PATCH 1/5] Updated IAM SampleScripts Enhancements to handling checks when starting script Signed-off-by: Gary Blake --- SampleProjects/iam/iamConfigureNsx.ps1 | 230 ++++++-------- SampleProjects/iam/iamConfigureVsphere.ps1 | 231 ++++++-------- .../iam/iamConfigureWorkspaceOne.ps1 | 294 ++++++++---------- 3 files changed, 325 insertions(+), 430 deletions(-) diff --git a/SampleProjects/iam/iamConfigureNsx.ps1 b/SampleProjects/iam/iamConfigureNsx.ps1 index 5552d15f..569150a4 100644 --- a/SampleProjects/iam/iamConfigureNsx.ps1 +++ b/SampleProjects/iam/iamConfigureNsx.ps1 @@ -1,11 +1,16 @@ <# .NOTES - =========================================================================== + =================================================================================================================== Created by: Gary Blake - Senior Staff Solutions Architect Date: 11/10/2021 - Copyright 2021 VMware, Inc. - =========================================================================== - + Copyright 2022 VMware, Inc. + =================================================================================================================== + .CHANGE_LOG + + - 1.0.001 (Gary Blake / 2022-01-04) - Improved the connection handling when starting the script + + =================================================================================================================== + .SYNOPSIS Configure NSX-T Data Center for Identity and Access Management @@ -32,16 +37,7 @@ Start-SetupLogFile -Path $filePath -ScriptName $MyInvocation.MyCommand.Name Write-LogMessage -Type INFO -Message "Starting the Process of Configuring NSX-T Data Center Based on Identity and Access Management for VMware Cloud Foundation" -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 @@ -50,123 +46,101 @@ Try { 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") { - Write-LogMessage -type INFO -message "Planning and Prepatation Workbook Provided Not Supported" -colour Red - Break + 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") { + Write-LogMessage -type INFO -message "Planning and Prepatation Workbook Provided Not Supported" -colour Red + Break + } + + $domainFqdn = $pnpWorkbook.Workbook.Names["region_ad_child_fqdn"].Value + $domainBindUser = $pnpWorkbook.Workbook.Names["child_svc_vsphere_ad_user"].Value + $domainBindPass = $pnpWorkbook.Workbook.Names["child_svc_vsphere_ad_password"].Value + $mgmtSddcDomainName = $pnpWorkbook.Workbook.Names["mgmt_sddc_domain"].Value + $wldSddcDomainName = $pnpWorkbook.Workbook.Names["wld_sddc_domain"].Value + $wsaFqdn = $pnpWorkbook.Workbook.Names["region_wsa_fqdn"].Value + $wsaAdminPassword = $pnpWorkbook.Workbook.Names["standalone_wsa_appliance_admin_password"].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 + $apiLockoutPeriod = [Int]$pnpWorkbook.Workbook.Names["nsxt_password_api_lockout_period"].Value + $apiResetPeriod = [Int]$pnpWorkbook.Workbook.Names["nsxt_password_api_lockout_reset_period"].Value + $apiMaxAttempt = [Int]$pnpWorkbook.Workbook.Names["nsxt_password_api_max_auth_failures"].Value + $cliLockoutPeriod = [Int]$pnpWorkbook.Workbook.Names["nsxt_password_cli_lockout_period"].Value + $cliMaxAttempt = [Int]$pnpWorkbook.Workbook.Names["nsxt_password_cli_max_auth_failures"].Value + $minPasswordLength = [Int]$pnpWorkbook.Workbook.Names["nsxt_password_min_length"].Value + $vsphereRoleName = $pnpWorkbook.Workbook.Names["nsxt_vsphere_role_name"].Value + $ssoDomainFqdn = "vsphere.local" + $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 + + # 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 } + $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 } + + # 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" + $StatusMsg = Add-NsxtVidmRole -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $mgmtSddcDomainName -type group -principal $nsxEnterpriseAdminGroup -role enterprise_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 = Add-NsxtVidmRole -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $mgmtSddcDomainName -type group -principal $nsxNetworkEngineerGroup -role network_engineer -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-NsxtVidmRole -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $mgmtSddcDomainName -type group -principal $nsxAuditorGroup -role auditor -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-NsxtVidmRole -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $wldSddcDomainName -type group -principal $nsxEnterpriseAdminGroup -role enterprise_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 = Add-NsxtVidmRole -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $wldSddcDomainName -type group -principal $nsxNetworkEngineerGroup -role network_engineer -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-NsxtVidmRole -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $wldSddcDomainName -type group -principal $nsxAuditorGroup -role auditor -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 the Authentication Policy for NSX Managers + Write-LogMessage -Type INFO -Message "Attempting to Configure the Authentication Policy for NSX Managers" + $StatusMsg = Set-NsxtManagerAuthenticationPolicy -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $mgmtSddcDomainName -apiLockoutPeriod $apiLockoutPeriod -apiResetPeriod $apiResetPeriod -apiMaxAttempt $apiMaxAttempt -cliLockoutPeriod $cliLockoutPeriod -cliMaxAttempt $cliMaxAttempt -minPasswdLength $minPasswordLength -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-NsxtManagerAuthenticationPolicy -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $wldSddcDomainName -apiLockoutPeriod $apiLockoutPeriod -apiResetPeriod $apiResetPeriod -apiMaxAttempt $apiMaxAttempt -cliLockoutPeriod $cliLockoutPeriod -cliMaxAttempt $cliMaxAttempt -minPasswdLength $minPasswordLength -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 } + + # Attempting to Configure the Authentication Policy for NSX Edge Nodes + Write-LogMessage -Type INFO -Message "Attempting to Configure the Authentication Policy for NSX Edge Nodes" + $StatusMsg = Set-NsxtEdgeNodeAuthenticationPolicy -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $mgmtSddcDomainName -cliLockoutPeriod $cliLockoutPeriod -cliMaxAttempt $cliMaxAttempt -minPasswdLength $minPasswordLength -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-NsxtEdgeNodeAuthenticationPolicy -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $wldSddcDomainName -cliLockoutPeriod $cliLockoutPeriod -cliMaxAttempt $cliMaxAttempt -minPasswdLength $minPasswordLength -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 } + + # Define a Custom Role in vSphere for the NSX-T Data Center Service Accounts + Write-LogMessage -Type INFO -Message "Define a Custom Role in vSphere for the NSX-T Data Center Service Accounts" + $StatusMsg = Add-vSphereRole -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -roleName $vsphereRoleName -template ($filePath + "\" + "nsx-vsphere-integration.role") -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 NSX-T Data Center Service Accounts to the vCenter Single Sign-On Built-In Identity Provider License Administrators Group + Write-LogMessage -Type INFO -Message "Add NSX-T Data Center Service Accounts to the vCenter Single Sign-On Built-In Identity Provider License Administrators Group" + $StatusMsg = Add-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 = Add-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 } + + # Reconfigure the vSphere Role and Permissions Scope for NSX-T Data Center Service Accounts + Write-LogMessage -Type INFO -Message "Reconfigure the vSphere Role and Permissions Scope for NSX-T Data Center Service Accounts" + $StatusMsg = Add-vCenterGlobalPermission -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain vsphere.local -domainBindUser $domainBindUser -domainBindPass $domainBindPass -principal $mgmtServiceAccount -role $vsphereRoleName -propagate true -type user -localdomain -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-vCenterGlobalPermission -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain vsphere.local -domainBindUser $domainBindUser -domainBindPass $domainBindPass -principal $wldServiceAccount -role $vsphereRoleName -propagate true -type user -localdomain -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 $mgmtSddcDomainName -principal $wldServiceAccount -role "NoAccess" -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 "NoAccess" -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 } } - - $domainFqdn = $pnpWorkbook.Workbook.Names["region_ad_child_fqdn"].Value - $domainBindUser = $pnpWorkbook.Workbook.Names["child_svc_vsphere_ad_user"].Value - $domainBindPass = $pnpWorkbook.Workbook.Names["child_svc_vsphere_ad_password"].Value - - $mgmtSddcDomainName = $pnpWorkbook.Workbook.Names["mgmt_sddc_domain"].Value - $wldSddcDomainName = $pnpWorkbook.Workbook.Names["wld_sddc_domain"].Value - - $wsaFqdn = $pnpWorkbook.Workbook.Names["region_wsa_fqdn"].Value - $wsaAdminPassword = $pnpWorkbook.Workbook.Names["standalone_wsa_appliance_admin_password"].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 - - $apiLockoutPeriod = [Int]$pnpWorkbook.Workbook.Names["nsxt_password_api_lockout_period"].Value - $apiResetPeriod = [Int]$pnpWorkbook.Workbook.Names["nsxt_password_api_lockout_reset_period"].Value - $apiMaxAttempt = [Int]$pnpWorkbook.Workbook.Names["nsxt_password_api_max_auth_failures"].Value - $cliLockoutPeriod = [Int]$pnpWorkbook.Workbook.Names["nsxt_password_cli_lockout_period"].Value - $cliMaxAttempt = [Int]$pnpWorkbook.Workbook.Names["nsxt_password_cli_max_auth_failures"].Value - $minPasswordLength = [Int]$pnpWorkbook.Workbook.Names["nsxt_password_min_length"].Value - - $vsphereRoleName = $pnpWorkbook.Workbook.Names["nsxt_vsphere_role_name"].Value - - $ssoDomainFqdn = "vsphere.local" - $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 } - else { - Write-LogMessage -Type ERROR -Message "Unable to connect to SDDC Manager $server" -Colour Red - Exit - } -} -Catch { - Debug-CatchWriter -object $_ -} - -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 } - $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 } - - # 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" - $StatusMsg = Add-NsxtVidmGroupRole -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $mgmtSddcDomainName -group $nsxEnterpriseAdminGroup -role enterprise_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 = Add-NsxtVidmGroupRole -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $mgmtSddcDomainName -group $nsxNetworkEngineerGroup -role network_engineer -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-NsxtVidmGroupRole -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $mgmtSddcDomainName -group $nsxAuditorGroup -role auditor -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-NsxtVidmGroupRole -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $wldSddcDomainName -group $nsxEnterpriseAdminGroup -role enterprise_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 = Add-NsxtVidmGroupRole -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $wldSddcDomainName -group $nsxNetworkEngineerGroup -role network_engineer -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-NsxtVidmGroupRole -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $wldSddcDomainName -group $nsxAuditorGroup -role auditor -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 the Authentication Policy for NSX Managers - Write-LogMessage -Type INFO -Message "Attempting to Configure the Authentication Policy for NSX Managers" - $StatusMsg = Set-NsxtManagerAuthenticationPolicy -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $mgmtSddcDomainName -apiLockoutPeriod $apiLockoutPeriod -apiResetPeriod $apiResetPeriod -apiMaxAttempt $apiMaxAttempt -cliLockoutPeriod $cliLockoutPeriod -cliMaxAttempt $cliMaxAttempt -minPasswdLength $minPasswordLength -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-NsxtManagerAuthenticationPolicy -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $wldSddcDomainName -apiLockoutPeriod $apiLockoutPeriod -apiResetPeriod $apiResetPeriod -apiMaxAttempt $apiMaxAttempt -cliLockoutPeriod $cliLockoutPeriod -cliMaxAttempt $cliMaxAttempt -minPasswdLength $minPasswordLength -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 } - - # Attempting to Configure the Authentication Policy for NSX Edge Nodes - Write-LogMessage -Type INFO -Message "Attempting to Configure the Authentication Policy for NSX Edge Nodes" - $StatusMsg = Set-NsxtEdgeNodeAuthenticationPolicy -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $mgmtSddcDomainName -cliLockoutPeriod $cliLockoutPeriod -cliMaxAttempt $cliMaxAttempt -minPasswdLength $minPasswordLength -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-NsxtEdgeNodeAuthenticationPolicy -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $wldSddcDomainName -cliLockoutPeriod $cliLockoutPeriod -cliMaxAttempt $cliMaxAttempt -minPasswdLength $minPasswordLength -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 } - - # Define a Custom Role in vSphere for the NSX-T Data Center Service Accounts - Write-LogMessage -Type INFO -Message "Define a Custom Role in vSphere for the NSX-T Data Center Service Accounts" - $StatusMsg = Add-vSphereRole -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -roleName $vsphereRoleName -template ($filePath + "\" + "nsx-vsphere-integration.role") -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 NSX-T Data Center Service Accounts to the vCenter Single Sign-On Built-In Identity Provider License Administrators Group - Write-LogMessage -Type INFO -Message "Add NSX-T Data Center Service Accounts to the vCenter Single Sign-On Built-In Identity Provider License Administrators Group" - $StatusMsg = Add-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 = Add-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 } - - # Reconfigure the vSphere Role and Permissions Scope for NSX-T Data Center Service Accounts - Write-LogMessage -Type INFO -Message "Reconfigure the vSphere Role and Permissions Scope for NSX-T Data Center Service Accounts" - $StatusMsg = Add-vCenterGlobalPermission -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain vsphere.local -domainBindUser $domainBindUser -domainBindPass $domainBindPass -principal $mgmtServiceAccount -role $vsphereRoleName -propagate true -type user -localdomain -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-vCenterGlobalPermission -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain vsphere.local -domainBindUser $domainBindUser -domainBindPass $domainBindPass -principal $wldServiceAccount -role $vsphereRoleName -propagate true -type user -localdomain -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 $mgmtSddcDomainName -principal $wldServiceAccount -role "NoAccess" -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 "NoAccess" -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 $_ diff --git a/SampleProjects/iam/iamConfigureVsphere.ps1 b/SampleProjects/iam/iamConfigureVsphere.ps1 index 6f8ce2e3..191651b6 100644 --- a/SampleProjects/iam/iamConfigureVsphere.ps1 +++ b/SampleProjects/iam/iamConfigureVsphere.ps1 @@ -1,10 +1,15 @@ <# .NOTES - =========================================================================== + =================================================================================================================== Created by: Gary Blake - Senior Staff Solutions Architect Date: 11/09/2021 - Copyright 2021 VMware, Inc. - =========================================================================== + Copyright 2022 VMware, Inc. + =================================================================================================================== + .CHANGE_LOG + + - 1.0.001 (Gary Blake / 2022-01-04) - Improved the connection handling when starting the script + + =================================================================================================================== .SYNOPSIS Configure vCenter Server for Identity and Access Management @@ -32,16 +37,7 @@ Start-SetupLogFile -Path $filePath -ScriptName $MyInvocation.MyCommand.Name Write-LogMessage -Type INFO -Message "Starting the Process of Configuring vSphere Based on Identity and Access Management for VMware Cloud Foundation" -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 @@ -50,137 +46,90 @@ Try { 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") { - Write-LogMessage -type INFO -message "Planning and Prepatation Workbook Provided Not Supported" -colour Red - Break + 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") { + Write-LogMessage -type INFO -message "Planning and Prepatation Workbook Provided Not Supported" -colour Red + Break + } + + $domainFqdn = $pnpWorkbook.Workbook.Names["region_ad_child_fqdn"].Value + $mgmtSddcDomainName = $pnpWorkbook.Workbook.Names["mgmt_sddc_domain"].Value + $wldSddcDomainName = $pnpWorkbook.Workbook.Names["wld_sddc_domain"].Value + $domainBindUser = $pnpWorkbook.Workbook.Names["child_svc_vsphere_ad_user"].Value + $domainBindPass = $pnpWorkbook.Workbook.Names["child_svc_vsphere_ad_password"].Value + $domainControllerMachineName = $pnpWorkbook.Workbook.Names["domain_controller_hostname"].Value + $baseGroupDn = $pnpWorkbook.Workbook.Names["child_ad_groups_ou"].Value + $baseUserDn = $pnpWorkbook.Workbook.Names["child_ad_users_ou"].Value + $vcenterAdminGroup = $pnpWorkbook.Workbook.Names["group_gg_vc_admins"].Value + $vcenterReadOnlyGroup = $pnpWorkbook.Workbook.Names["group_gg_vc_read_only"].Value + $ssoAdminGroup = $pnpWorkbook.Workbook.Names["group_gg_sso_admins"].Value + $ssoServerFqdn = (Get-VCFvCenter | Where-Object {$_.domain.id -eq (Get-VCFWorkloadDomain | Where-Object {$_.type -eq "MANAGEMENT"}).id}).fqdn + $ssoServerUser = (Get-VCFCredential | Where-Object {$_.accountType -eq "SYSTEM" -and $_.credentialType -eq "SSO"}).username + $ssoServerPass = (Get-VCFCredential | Where-Object {$_.accountType -eq "SYSTEM" -and $_.credentialType -eq "SSO"}).password + $emailNotification = $pnpWorkbook.Workbook.Names["vcenter_password_validity_email_address"].Value + $maxDays = $pnpWorkbook.Workbook.Names["vcenter_password_validity"].Value + $passwordCount = $pnpWorkbook.Workbook.Names["sso_password_resuse"].Value + $minLength = $pnpWorkbook.Workbook.Names["sso_password_min_length"].Value + $maxLength = $pnpWorkbook.Workbook.Names["sso_password_max_length"].Value + $minNumericCount = $pnpWorkbook.Workbook.Names["sso_password_numeric_characters"].Value + $minSpecialCharCount = $pnpWorkbook.Workbook.Names["sso_password_special_characters"].Value + $maxIdenticalAdjacentCharacters = $pnpWorkbook.Workbook.Names["sso_password_indentical_adjacent_characters"].Value + $minAlphabeticCount = $pnpWorkbook.Workbook.Names["sso_password_alphabetic_characters"].Value + $minUppercaseCount = $pnpWorkbook.Workbook.Names["sso_password_uppercase_characters"].Value + $minLowercaseCount = $pnpWorkbook.Workbook.Names["sso_password_lowercase_characters"].Value + $passwordLifetimeDays = $pnpWorkbook.Workbook.Names["sso_password_validity"].Value + $autoUnlockIntervalSec = $pnpWorkbook.Workbook.Names["sso_unlock_time"].Value + $failedAttemptIntervalSec = $pnpWorkbook.Workbook.Names["sso_logon_failure_interval"].Value + $maxFailedAttempts = $pnpWorkbook.Workbook.Names["sso_max_logon_attempts"].Value + $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 + $mgmtCluster = $pnpWorkbook.Workbook.Names["mgmt_cluster"].Value + $wldCluster = $pnpWorkbook.Workbook.Names["wld_cluster"].Value + $policy = $pnpWorkbook.Workbook.Names["esxi_password_quality_control"].Value + + $rootCa = "Root64.cer" + if (!(Test-Path ($filePath + "\" + $rootCa) )) { Write-LogMessage -Type ERROR -Message "Unable to Find Certificate File: $rootCa, check details and try again" -Colour Red; Break } else { Write-LogMessage -Type INFO -Message "Found Certificate File: $rootCa" } + + # Add Active Directory as Identity Provider to the Management vCenter Server + Write-LogMessage -Type INFO -Message "Add Active Directory as Identity Provider to the Management vCenter Server" + $StatusMsg = Add-IdentitySource -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $domainFqdn -domainBindUser $domainBindUser -domainBindPass $domainBindPass -dcMachineName $domainControllerMachineName -baseGroupDn $baseGroupDn -baseUserDn $baseUserDn -protocol ldaps -certificate ($filePath + "\" + $rootCa) -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 Assign Active Directory Group Global Permissions in vCenter Server + Write-LogMessage -Type INFO -Message "Attempting Assign Active Directory Group Global Permissions in vCenter Server" + $StatusMsg = Add-vCenterGlobalPermission -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $domainFqdn -domainBindUser $domainBindUser -domainBindPass $domainBindPass -principal $vcenterAdminGroup -role Admin -propagate true -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-vCenterGlobalPermission -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $domainFqdn -domainBindUser $domainBindUser -domainBindPass $domainBindPass -principal $vcenterReadOnlyGroup -role ReadOnly -propagate true -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 Assign vCenter Single Sign-On Roles to Active Directory Groups + Write-LogMessage -Type INFO -Message "Attempting to Assign vCenter Single Sign-On Roles to Active Directory Groups" + $StatusMsg = Add-SsoPermission -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -sddcDomain $mgmtSddcDomainName -domain $domainFqdn -domainBindUser $domainBindUser -domainBindPass $domainBindPass -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 } + + # Attempting to Configure the vCenter Server Appliance Password Expiration Date + Write-LogMessage -Type INFO -Message "Attempting to Configure the vCenter Server Appliance Password Expiration Date" + $StatusMsg = Set-vCenterPasswordExpiration -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $mgmtSddcDomainName -passwordExpires $true -email $emailNotification -maxDaysBetweenPasswordChange $maxDays -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-vCenterPasswordExpiration -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $wldSddcDomainName -passwordExpires $true -email $emailNotification -maxDaysBetweenPasswordChange $maxDays -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 the vCenter Single Sign-On Password Policy + Write-LogMessage -Type INFO -Message "Attempting to Configure the vCenter Single Sign-On Password Policy" + Connect-SsoAdminServer -Server $ssoServerFqdn -User $ssoServerUser -Password $ssoServerPass | Out-Null + 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" } - - $domainFqdn = $pnpWorkbook.Workbook.Names["region_ad_child_fqdn"].Value - $mgmtSddcDomainName = $pnpWorkbook.Workbook.Names["mgmt_sddc_domain"].Value - $wldSddcDomainName = $pnpWorkbook.Workbook.Names["wld_sddc_domain"].Value - - $domainBindUser = $pnpWorkbook.Workbook.Names["child_svc_vsphere_ad_user"].Value - $domainBindPass = $pnpWorkbook.Workbook.Names["child_svc_vsphere_ad_password"].Value - $domainControllerMachineName = $pnpWorkbook.Workbook.Names["domain_controller_hostname"].Value - $baseGroupDn = $pnpWorkbook.Workbook.Names["child_ad_groups_ou"].Value - $baseUserDn = $pnpWorkbook.Workbook.Names["child_ad_users_ou"].Value - - $vcenterAdminGroup = $pnpWorkbook.Workbook.Names["group_gg_vc_admins"].Value - $vcenterReadOnlyGroup = $pnpWorkbook.Workbook.Names["group_gg_vc_read_only"].Value - $ssoAdminGroup = $pnpWorkbook.Workbook.Names["group_gg_sso_admins"].Value - - $ssoServerFqdn = (Get-VCFvCenter | Where-Object {$_.domain.id -eq (Get-VCFWorkloadDomain | Where-Object {$_.type -eq "MANAGEMENT"}).id}).fqdn - $ssoServerUser = (Get-VCFCredential | Where-Object {$_.accountType -eq "SYSTEM" -and $_.credentialType -eq "SSO"}).username - $ssoServerPass = (Get-VCFCredential | Where-Object {$_.accountType -eq "SYSTEM" -and $_.credentialType -eq "SSO"}).password - - $emailNotification = $pnpWorkbook.Workbook.Names["vcenter_password_validity_email_address"].Value - $maxDays = $pnpWorkbook.Workbook.Names["vcenter_password_validity"].Value - - $passwordCount = $pnpWorkbook.Workbook.Names["sso_password_resuse"].Value - $minLength = $pnpWorkbook.Workbook.Names["sso_password_min_length"].Value - $maxLength = $pnpWorkbook.Workbook.Names["sso_password_max_length"].Value - $minNumericCount = $pnpWorkbook.Workbook.Names["sso_password_numeric_characters"].Value - $minSpecialCharCount = $pnpWorkbook.Workbook.Names["sso_password_special_characters"].Value - $maxIdenticalAdjacentCharacters = $pnpWorkbook.Workbook.Names["sso_password_indentical_adjacent_characters"].Value - $minAlphabeticCount = $pnpWorkbook.Workbook.Names["sso_password_alphabetic_characters"].Value - $minUppercaseCount = $pnpWorkbook.Workbook.Names["sso_password_uppercase_characters"].Value - $minLowercaseCount = $pnpWorkbook.Workbook.Names["sso_password_lowercase_characters"].Value - $passwordLifetimeDays = $pnpWorkbook.Workbook.Names["sso_password_validity"].Value - - $autoUnlockIntervalSec = $pnpWorkbook.Workbook.Names["sso_unlock_time"].Value - $failedAttemptIntervalSec = $pnpWorkbook.Workbook.Names["sso_logon_failure_interval"].Value - $maxFailedAttempts = $pnpWorkbook.Workbook.Names["sso_max_logon_attempts"].Value - - $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 - - $mgmtCluster = $pnpWorkbook.Workbook.Names["mgmt_cluster"].Value - $wldCluster = $pnpWorkbook.Workbook.Names["wld_cluster"].Value - $policy = $pnpWorkbook.Workbook.Names["esxi_password_quality_control"].Value - - $rootCa = "Root64.cer" - if (!(Test-Path ($filePath + "\" + $rootCa) )) { Write-LogMessage -Type ERROR -Message "Unable to Find Certificate File: $rootCa, check details and try again" -Colour Red; Break } else { Write-LogMessage -Type INFO -Message "Found Certificate File: $rootCa" } } - else { - Write-LogMessage -Type ERROR -Message "Unable to connect to SDDC Manager $server" -Colour Red - Exit - } -} -Catch { - Debug-CatchWriter -object $_ -} - -Try { - # Add Active Directory as Identity Provider to the Management vCenter Server - Write-LogMessage -Type INFO -Message "Add Active Directory as Identity Provider to the Management vCenter Server" - $StatusMsg = Add-IdentitySource -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $domainFqdn -domainBindUser $domainBindUser -domainBindPass $domainBindPass -dcMachineName $domainControllerMachineName -baseGroupDn $baseGroupDn -baseUserDn $baseUserDn -protocol ldaps -certificate ($filePath + "\" + $rootCa) -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 Assign Active Directory Group Global Permissions in vCenter Server - Write-LogMessage -Type INFO -Message "Attempting Assign Active Directory Group Global Permissions in vCenter Server" - $StatusMsg = Add-vCenterGlobalPermission -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $domainFqdn -domainBindUser $domainBindUser -domainBindPass $domainBindPass -principal $vcenterAdminGroup -role Admin -propagate true -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-vCenterGlobalPermission -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $domainFqdn -domainBindUser $domainBindUser -domainBindPass $domainBindPass -principal $vcenterReadOnlyGroup -role ReadOnly -propagate true -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 Assign vCenter Single Sign-On Roles to Active Directory Groups - Write-LogMessage -Type INFO -Message "Attempting to Assign vCenter Single Sign-On Roles to Active Directory Groups" - $StatusMsg = Add-SsoPermission -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -sddcDomain $mgmtSddcDomainName -domain $domainFqdn -domainBindUser $domainBindUser -domainBindPass $domainBindPass -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 } - - # Attempting to Configure the vCenter Server Appliance Password Expiration Date - Write-LogMessage -Type INFO -Message "Attempting to Configure the vCenter Server Appliance Password Expiration Date" - $StatusMsg = Set-vCenterPasswordExpiration -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $mgmtSddcDomainName -passwordExpires $true -email $emailNotification -maxDaysBetweenPasswordChange $maxDays -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-vCenterPasswordExpiration -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $wldSddcDomainName -passwordExpires $true -email $emailNotification -maxDaysBetweenPasswordChange $maxDays -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 the vCenter Single Sign-On Password Policy - Write-LogMessage -Type INFO -Message "Attempting to Configure the vCenter Single Sign-On Password Policy" - Connect-SsoAdminServer -Server $ssoServerFqdn -User $ssoServerUser -Password $ssoServerPass | Out-Null - 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 } } Catch { Debug-CatchWriter -object $_ diff --git a/SampleProjects/iam/iamConfigureWorkspaceOne.ps1 b/SampleProjects/iam/iamConfigureWorkspaceOne.ps1 index 0bf02813..d8ecce9e 100644 --- a/SampleProjects/iam/iamConfigureWorkspaceOne.ps1 +++ b/SampleProjects/iam/iamConfigureWorkspaceOne.ps1 @@ -1,11 +1,16 @@ <# .NOTES - =========================================================================== + =================================================================================================================== Created by: Gary Blake - Senior Staff Solutions Architect Date: 11/10/2021 - Copyright 2021 VMware, Inc. - =========================================================================== - + Copyright 2022 VMware, Inc. + =================================================================================================================== + .CHANGE_LOG + + - 1.0.001 (Gary Blake / 2022-01-04) - Improved the connection handling when starting the script + + =================================================================================================================== + .SYNOPSIS Configure Workspace ONE Access for Identity and Access Management @@ -32,16 +37,8 @@ Start-SetupLogFile -Path $filePath -ScriptName $MyInvocation.MyCommand.Name Write-LogMessage -Type INFO -Message "Starting the Process of Deploying and Configuring Workspace ONE Access Based on Identity and Access Management for VMware Cloud Foundation" -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 @@ -50,156 +47,131 @@ Try { 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") { - Write-LogMessage -type INFO -message "Planning and Prepatation Workbook Provided Not Supported" -colour Red - Break + 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") { + Write-LogMessage -type INFO -message "Planning and Prepatation Workbook Provided Not Supported" -colour Red + 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" + 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 + $maxPreviousPasswordCharactersReused = "0" + $passwordTtlInDays = "90" + $notificationThresholdInDays = "15" + $notificationIntervalInDays = "3" + $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 + + $rootCa = "Root64.cer" + if (!(Test-Path ($filePath + "\" + $rootCa) )) { Write-LogMessage -Type ERROR -Message "Unable to Find Certificate File: $rootCa, check details and try again" -Colour Red; Break } else { Write-LogMessage -Type INFO -Message "Found Certificate File: $rootCa" } + $wsaCertKey = $wsaHostname + ".key" + if (!(Test-Path ($filePath + "\" + $wsaCertKey) )) { Write-LogMessage -Type ERROR -Message "Unable to Find Certificate File: $wsaCertKey, check details and try again" -Colour Red; Break } else { Write-LogMessage -Type INFO -Message "Found Certificate File: $wsaCertKey" } + $wsaCert = $wsaHostname + ".1.cer" + if (!(Test-Path ($filePath + "\" + $wsaCert) )) { Write-LogMessage -Type ERROR -Message "Unable to Find Certificate File: $wsaCert, check details and try again" -Colour Red; Break } else { Write-LogMessage -Type INFO -Message "Found Certificate File: $wsaCert" } + + # Attempting to Create Virtual Machine and Template Folder for the Standalone Workspace ONE Access Instance + Write-LogMessage -Type INFO -Message "Attempting to Create Virtual Machine and Template Folder for the Standalone Workspace ONE Access Instance" + $StatusMsg = Add-VMFolder -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $mgmtSddcDomainName -folderName $wsaFolder -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 } + + # Attempting to Deploy the Standalone Workspace ONE Access Instance + Write-LogMessage -Type INFO -Message "Attempting to Deploy the Standalone Workspace ONE Access Instance" + Write-LogMessage -Type INFO -Message "Deploying the Workspace ONE Access OVA" + $StatusMsg = Install-WorkspaceOne -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -wsaFqdn $wsaFqdn -wsaIpAddress $wsaIpAddress -wsaGateway $wsaGateway -wsaSubnetMask $wsaSubnetMask -wsaFolder $wsaFolder -wsaOvaPath ($filePath + "\" + $wsaOvaFile) -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg -match "SUCCESSFUL") { Write-LogMessage -Type INFO -Message "Deploying $wsaFqdn using $($filePath + "\" + $wsaOvaFile): SUCCESSFUL"; $ErrorMsg = '' } elseif ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + if (!(Test-Connection -ComputerName ($wsaFqdn) -Quiet -Count 1)) { + Write-LogMessage -Type INFO -Message "Going to Sleep for 10 mins Waiting for Workspace ONE Access to Start all Services" + Start-Sleep 600 + } + + # Attempting to Create a VM Group for the Standalone Workspace ONE Access Instance + Write-LogMessage -Type INFO -Message "Attempting to Create a VM Group for the Standalone Workspace ONE Access Instance" + $StatusMsg = Add-ClusterGroup -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $mgmtSddcDomainName -drsGroupName $drsGroupName -drsGroupVMs $drsGroupVMs -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 Perform Initial Configuration of Workspace ONE Access Virtual Appliance + Write-LogMessage -Type INFO -Message "Attempting to Perform Initial Configuration of Workspace ONE Access Virtual Appliance" + $StatusMsg = Initialize-WorkspaceOne -wsaFqdn $wsaFqdn -adminPass $wsaAdminPassword -rootPass $wsaRootPassword -sshUserPass $wsaSshUserPassword -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 NTP Server on Workspace ONE Access Appliance + Write-LogMessage -Type INFO -Message "Attempting to Configure NTP Server on Workspace ONE Access Appliance" + $StatusMsg = Set-WorkspaceOneNtpConfig -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -wsaFqdn $wsaFqdn -rootPass $wsaRootPassword -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 Replace the Certificate of the Standalone Workspace ONE Access Instance + Write-LogMessage -Type INFO -Message "Attempting to Replace the Certificate of the Standalone Workspace ONE Access Instance" + $StatusMsg = Install-WorkspaceOneCertificate -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -wsaFqdn $wsaFqdn -rootPass $wsaRootPassword -sshUserPass $wsaSshUserPassword -rootCa ($filePath + "\" + $rootCa) -wsaCertKey ($filePath + "\" + $wsaCertKey) -wsaCert ($filePath + "\" + $wsaCert) -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg -match "SUCCESSFUL") { Write-LogMessage -Type INFO -Message "$StatusMsg"; Write-LogMessage -Type INFO -Message "Waiting for Standalone Workspace ONE Access Instance Services to Restart"; Start-Sleep 200 } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Attempting to Configure SMTP on the Standalone Workspace ONE Access Instance + Write-LogMessage -Type INFO -Message "Attempting to Configure SMTP on the Standalone Workspace ONE Access Instance" + $StatusMsg = Set-WorkspaceOneSmtpConfig -server $wsaFqdn -user admin -pass $wsaAdminPassword -smtpFqdn $smtpServerFqdn -smtpPort $smtpServerPort -smtpEmail $smtpEmailAddress -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 Identity Source for the Standalone Workspace ONE Access Instance + Write-LogMessage -Type INFO -Message "Attempting to Configure Identity Source for the Standalone Workspace ONE Access Instance" + $StatusMsg = Add-WorkspaceOneDirectory -server $wsaFqdn -user admin -pass $wsaAdminPassword -domain $domainFqdn -baseDnUser $baseUserDn -baseDnGroup $baseGroupDn -bindUserDn $wsaBindUserDn -bindUserPass $wsaBindUserPassword -adGroups $adGroups -protocol ldaps -certificate ($filePath + "\" + $rootCa) -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg"; Write-LogMessage -Type INFO -Message "Going to Sleep for 60 seconds to allow Workspace ONE Access to syncronize with Active Directory"; Start-Sleep 60 } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Attempting to Configure Local Password Policy for the Standalone Workspace ONE Access Instance + Write-LogMessage -Type INFO -Message "Attempting to Configure Local Password Policy for the Standalone Workspace ONE Access Instance" + Request-WSAToken -fqdn $wsaFqdn -user admin -pass $wsaAdminPassword | Out-Null + $StatusMsg = Set-WSAPasswordPolicy -minLen $minLen -minLower $minLower -minUpper $minUpper -minDigit $minDigit -minSpecial $minSpecial -history $history -maxConsecutiveIdenticalCharacters $maxConsecutiveIdenticalCharacters -maxPreviousPasswordCharactersReused $maxPreviousPasswordCharactersReused -tempPasswordTtlInHrs $tempPasswordTtlInHrs -passwordTtlInDays $passwordTtlInDays -notificationThresholdInDays $notificationThresholdInDays -notificationIntervalInDays $notificationIntervalInDays | Get-WSAPasswordPolicy -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "Configure Password Policy on Workspace ONE Access Password ($wsaFqdn): SUCCESSFUL" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + $StatusMsg = Set-WSAPasswordLockout -numAttempts $numAttempts -attemptInterval $attemptInterval -unlockInterval $unlockInterval -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "Configure Lockout Policy on Workspace ONE Access Password ($wsaFqdn): SUCCESSFUL" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Attempting to Assign Workspace ONE Access Roles to Active Directory Groups + Write-LogMessage -Type INFO -Message "Attempting to Assign Workspace ONE Access Roles to Active Directory Groups" + $StatusMsg = Add-WorkspaceOneRole -server $wsaFqdn -user admin -pass $wsaAdminPassword -group $wsaSuperAdminGroup -role "Super 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 = Add-WorkspaceOneRole -server $wsaFqdn -user admin -pass $wsaAdminPassword -group $wsaDirAdminGroup -role "Directory 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 = Add-WorkspaceOneRole -server $wsaFqdn -user admin -pass $wsaAdminPassword -group $wsaReadOnlyGroup -role "ReadOnly 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 } } - - $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" - 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 - - $rootCa = "Root64.cer" - if (!(Test-Path ($filePath + "\" + $rootCa) )) { Write-LogMessage -Type ERROR -Message "Unable to Find Certificate File: $rootCa, check details and try again" -Colour Red; Break } else { Write-LogMessage -Type INFO -Message "Found Certificate File: $rootCa" } - $wsaCertKey = $wsaHostname + ".key" - if (!(Test-Path ($filePath + "\" + $wsaCertKey) )) { Write-LogMessage -Type ERROR -Message "Unable to Find Certificate File: $wsaCertKey, check details and try again" -Colour Red; Break } else { Write-LogMessage -Type INFO -Message "Found Certificate File: $wsaCertKey" } - $wsaCert = $wsaHostname + ".1.cer" - if (!(Test-Path ($filePath + "\" + $wsaCert) )) { Write-LogMessage -Type ERROR -Message "Unable to Find Certificate File: $wsaCert, check details and try again" -Colour Red; Break } else { Write-LogMessage -Type INFO -Message "Found Certificate File: $wsaCert" } - - $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" - - $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 } - else { - Write-LogMessage -Type ERROR -Message "Unable to connect to SDDC Manager $server" -Colour Red - Exit - } -} -Catch { - Debug-CatchWriter -object $_ -} - -Try { - # Attempting to Create Virtual Machine and Template Folder for the Standalone Workspace ONE Access Instance - Write-LogMessage -Type INFO -Message "Attempting to Create Virtual Machine and Template Folder for the Standalone Workspace ONE Access Instance" - $StatusMsg = Add-VMFolder -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $mgmtSddcDomainName -folderName $wsaFolder -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 } - - # Attempting to Deploy the Standalone Workspace ONE Access Instance - Write-LogMessage -Type INFO -Message "Attempting to Deploy the Standalone Workspace ONE Access Instance" - Write-LogMessage -Type INFO -Message "Deploying the Workspace ONE Access OVA" - $StatusMsg = Install-WorkspaceOne -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -wsaFqdn $wsaFqdn -wsaIpAddress $wsaIpAddress -wsaGateway $wsaGateway -wsaSubnetMask $wsaSubnetMask -wsaFolder $wsaFolder -wsaOvaPath ($filePath + "\" + $wsaOvaFile) -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg - if ( $StatusMsg -match "SUCCESSFUL") { Write-LogMessage -Type INFO -Message "Deploying $wsaFqdn using $($filePath + "\" + $wsaOvaFile): SUCCESSFUL"; $ErrorMsg = '' } elseif ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } - if (!(Test-Connection -ComputerName ($wsaFqdn) -Quiet -Count 1)) { - Write-LogMessage -Type INFO -Message "Going to Sleep for 10 mins Waiting for Workspace ONE Access to Start all Services" - Start-Sleep 600 - } - - # Attempting to Create a VM Group for the Standalone Workspace ONE Access Instance - Write-LogMessage -Type INFO -Message "Attempting to Create a VM Group for the Standalone Workspace ONE Access Instance" - $StatusMsg = Add-ClusterGroup -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $mgmtSddcDomainName -drsGroupName $drsGroupName -drsGroupVMs $drsGroupVMs -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 Perform Initial Configuration of Workspace ONE Access Virtual Appliance - Write-LogMessage -Type INFO -Message "Attempting to Perform Initial Configuration of Workspace ONE Access Virtual Appliance" - $StatusMsg = Initialize-WorkspaceOne -wsaFqdn $wsaFqdn -adminPass $wsaAdminPassword -rootPass $wsaRootPassword -sshUserPass $wsaSshUserPassword -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 NTP Server on Workspace ONE Access Appliance - Write-LogMessage -Type INFO -Message "Attempting to Configure NTP Server on Workspace ONE Access Appliance" - $StatusMsg = Set-WorkspaceOneNtpConfig -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -wsaFqdn $wsaFqdn -rootPass $wsaRootPassword -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 Replace the Certificate of the Standalone Workspace ONE Access Instance - Write-LogMessage -Type INFO -Message "Attempting to Replace the Certificate of the Standalone Workspace ONE Access Instance" - $StatusMsg = Install-WorkspaceOneCertificate -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -wsaFqdn $wsaFqdn -rootPass $wsaRootPassword -sshUserPass $wsaSshUserPassword -rootCa ($filePath + "\" + $rootCa) -wsaCertKey ($filePath + "\" + $wsaCertKey) -wsaCert ($filePath + "\" + $wsaCert) -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg - if ( $StatusMsg -match "SUCCESSFUL") { Write-LogMessage -Type INFO -Message "$StatusMsg"; Write-LogMessage -Type INFO -Message "Waiting for Standalone Workspace ONE Access Instance Services to Restart"; Start-Sleep 200 } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } - - # Attempting to Configure SMTP on the Standalone Workspace ONE Access Instance - Write-LogMessage -Type INFO -Message "Attempting to Configure SMTP on the Standalone Workspace ONE Access Instance" - $StatusMsg = Set-WorkspaceOneSmtpConfig -server $wsaFqdn -user admin -pass $wsaAdminPassword -smtpFqdn $smtpServerFqdn -smtpPort $smtpServerPort -smtpEmail $smtpEmailAddress -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 Identity Source for the Standalone Workspace ONE Access Instance - Write-LogMessage -Type INFO -Message "Attempting to Configure Identity Source for the Standalone Workspace ONE Access Instance" - $StatusMsg = Add-WorkspaceOneDirectory -server $wsaFqdn -user admin -pass $wsaAdminPassword -domain $domainFqdn -baseDnUser $baseUserDn -baseDnGroup $baseGroupDn -bindUserDn $wsaBindUserDn -bindUserPass $wsaBindUserPassword -adGroups $adGroups -protocol ldaps -certificate ($filePath + "\" + $rootCa) -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg - if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "$StatusMsg"; Write-LogMessage -Type INFO -Message "Going to Sleep for 60 seconds to allow Workspace ONE Access to syncronize with Active Directory"; Start-Sleep 60 } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } - - # Attempting to Configure Local Password Policy for the Standalone Workspace ONE Access Instance - Write-LogMessage -Type INFO -Message "Attempting to Configure Local Password Policy for the Standalone Workspace ONE Access Instance" - Request-WSAToken -fqdn $wsaFqdn -user admin -pass $wsaAdminPassword | Out-Null - $StatusMsg = Set-WSAPasswordPolicy -minLen $minLen -minLower $minLower -minUpper $minUpper -minDigit $minDigit -minSpecial $minSpecial -history $history -maxConsecutiveIdenticalCharacters $maxConsecutiveIdenticalCharacters -maxPreviousPasswordCharactersReused $maxPreviousPasswordCharactersReused -tempPasswordTtlInHrs $tempPasswordTtlInHrs -passwordTtlInDays $passwordTtlInDays -notificationThresholdInDays $notificationThresholdInDays -notificationIntervalInDays $notificationIntervalInDays | Get-WSAPasswordPolicy -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg - if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "Configure Password Policy on Workspace ONE Access Password ($wsaFqdn): SUCCESSFUL" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } - $StatusMsg = Set-WSAPasswordLockout -numAttempts $numAttempts -attemptInterval $attemptInterval -unlockInterval $unlockInterval -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg - if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "Configure Lockout Policy on Workspace ONE Access Password ($wsaFqdn): SUCCESSFUL" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } - - # Attempting to Assign Workspace ONE Access Roles to Active Directory Groups - Write-LogMessage -Type INFO -Message "Attempting to Assign Workspace ONE Access Roles to Active Directory Groups" - $StatusMsg = Add-WorkspaceOneRole -server $wsaFqdn -user admin -pass $wsaAdminPassword -group $wsaSuperAdminGroup -role "Super 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 = Add-WorkspaceOneRole -server $wsaFqdn -user admin -pass $wsaAdminPassword -group $wsaDirAdminGroup -role "Directory 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 = Add-WorkspaceOneRole -server $wsaFqdn -user admin -pass $wsaAdminPassword -group $wsaReadOnlyGroup -role "ReadOnly 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 } } Catch { Debug-CatchWriter -object $_ From 1f4f8d2fb7cc12d178c2dad2191173b0f43f66e6 Mon Sep 17 00:00:00 2001 From: GaryJBlake Date: Tue, 25 Jan 2022 11:54:29 +0000 Subject: [PATCH 2/5] Updates to ILA SampleScripts Enhancements to handling checks when starting script Signed-off-by: Gary Blake --- .../ila/ilaConfigureVrealizeLogInsight.ps1 | 148 ++++----- .../ila/ilaDeployVrealizeLogInsight.ps1 | 304 ++++++++---------- 2 files changed, 205 insertions(+), 247 deletions(-) diff --git a/SampleProjects/ila/ilaConfigureVrealizeLogInsight.ps1 b/SampleProjects/ila/ilaConfigureVrealizeLogInsight.ps1 index d575a0ea..d0514f0f 100644 --- a/SampleProjects/ila/ilaConfigureVrealizeLogInsight.ps1 +++ b/SampleProjects/ila/ilaConfigureVrealizeLogInsight.ps1 @@ -1,11 +1,16 @@ <# .NOTES - =========================================================================== + =================================================================================================================== Created by: Gary Blake - Senior Staff Solutions Architect Date: 11/27/2021 Copyright 2021 VMware, Inc. - =========================================================================== - + =================================================================================================================== + .CHANGE_LOG + + - 1.0.001 (Gary Blake / 2022-01-05) - Improved the connection handling when starting the script + + =================================================================================================================== + .SYNOPSIS Configure Integration of vRealize Log Insight for Intelligent Logging and Analytics @@ -32,17 +37,7 @@ Start-SetupLogFile -Path $filePath -ScriptName $MyInvocation.MyCommand.Name Write-LogMessage -Type INFO -Message "Starting the Process of Integration Configuration of vRealize Log Insight Based on Intelligent Logging and Analytics for VMware Cloud Foundation" -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 @@ -51,79 +46,64 @@ Try { 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") ) { - Write-LogMessage -type INFO -message "Planning and Prepatation Workbook Provided Not Supported" -colour Red - Break + 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") { + Write-LogMessage -type INFO -message "Planning and Prepatation Workbook Provided Not Supported" -colour Red + Break + } + + $sddcDomainName = $pnpWorkbook.Workbook.Names["mgmt_sddc_domain"].Value + $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 + $vmRootPass = $pnpWorkbook.Workbook.Names["vrslcm_xreg_env_password"].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" + + # Connect a VI Workload Domain to vRealize Log Insight + Write-LogMessage -Type INFO -Message "Connect a VI Workload Domain to vRealize Log Insight" + $StatusMsg = Register-vRLIWorkloadDomain -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcWldDomainName -status ENABLED -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 } + + # 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 + 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 + 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 + Write-LogMessage -Type INFO -Message "Download, Install and Configure the vRealize Log Insight Agent on the Clustered Workspace ONE Access Nodes" + $StatusMsg = Install-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 = Install-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 = Install-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 } + + # Configure the vRealize Log Insight Agent Group for the Clustered Workspace ONE Access + Write-LogMessage -Type INFO -Message "Configure the vRealize Log Insight Agent Group for the Clustered Workspace ONE Access" + $StatusMsg = Add-vRLIAgentGroup -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -agentGroupType wsa -criteria $vidmVmList -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 vRealize Log Insight Photon OS Agent Group for the Management Nodes + Write-LogMessage -Type INFO -Message "Create a vRealize Log Insight Photon OS Agent Group for the Management Nodes" + $StatusMsg = Add-vRLIAgentGroup -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -agentGroupType photon -criteria $photonVmList -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 } } - - $sddcDomainName = $pnpWorkbook.Workbook.Names["mgmt_sddc_domain"].Value - $sddcWldDomainName = $pnpWorkbook.Workbook.Names["wld_sddc_domain"].Value - $domain = $pnpWorkbook.Workbook.Names["parent_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 - $vmRootPass = $pnpWorkbook.Workbook.Names["vrslcm_xreg_env_password"].Value - $vidmVmList = "$vmNameNode1.$domain","$vmNameNode2.$domain","$vmNameNode2.$domain" - $photonVmList = "$($pnpWorkbook.Workbook.Names["sddc_mgr_hostname"].Value).$domain","$($pnpWorkbook.Workbook.Names["xreg_vrslcm_hostname"].Value).$domain","$vmNameNode1.$domain","$vmNameNode2.$domain","$vmNameNode2.$domain" } - else { - Write-LogMessage -Type ERROR -Message "Unable to connect to SDDC Manager $server" -Colour Red - Exit - } -} -Catch { - Debug-CatchWriter -object $_ -} - -Try { - # Connect a VI Workload Domain to vRealize Log Insight - Write-LogMessage -Type INFO -Message "Connect a VI Workload Domain to vRealize Log Insight" - $StatusMsg = Register-vRLIWorkloadDomain -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcWldDomainName -status ENABLED -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 } - - # 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 - 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-vRLISyslogEdgeCluster -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcWldDomainName -exportname $exportName -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 } - - # Download, Install and Configure the vRealize Log Insight Agent on the Clustered Workspace ONE Access Nodes - Write-LogMessage -Type INFO -Message "Download, Install and Configure the vRealize Log Insight Agent on the Clustered Workspace ONE Access Nodes" - $StatusMsg = Install-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 = Install-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 = Install-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 } - - # Configure the vRealize Log Insight Agent Group for the Clustered Workspace ONE Access - Write-LogMessage -Type INFO -Message "Configure the vRealize Log Insight Agent Group for the Clustered Workspace ONE Access" - $StatusMsg = Add-vRLIAgentGroup -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -agentGroupType wsa -criteria $vidmVmList -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 vRealize Log Insight Photon OS Agent Group for the Management Nodes - Write-LogMessage -Type INFO -Message "Create a vRealize Log Insight Photon OS Agent Group for the Management Nodes" - $StatusMsg = Add-vRLIAgentGroup -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -agentGroupType photon -criteria $photonVmList -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 $_ diff --git a/SampleProjects/ila/ilaDeployVrealizeLogInsight.ps1 b/SampleProjects/ila/ilaDeployVrealizeLogInsight.ps1 index 6c89dc56..d2a90981 100644 --- a/SampleProjects/ila/ilaDeployVrealizeLogInsight.ps1 +++ b/SampleProjects/ila/ilaDeployVrealizeLogInsight.ps1 @@ -1,11 +1,16 @@ <# .NOTES - =========================================================================== + =================================================================================================================== Created by: Gary Blake - Senior Staff Solutions Architect Date: 11/27/2021 Copyright 2021 VMware, Inc. - =========================================================================== - + =================================================================================================================== + .CHANGE_LOG + + - 1.0.001 (Gary Blake / 2022-01-05) - Improved the connection handling when starting the script + + =================================================================================================================== + .SYNOPSIS Deploy vRealize Log Insight for Intelligent Logging and Analytics @@ -32,17 +37,7 @@ Start-SetupLogFile -Path $filePath -ScriptName $MyInvocation.MyCommand.Name Write-LogMessage -Type INFO -Message "Starting the Process of Configuring vRealize Log Insight Based on Intelligent Logging and Analytics for VMware Cloud Foundation" -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 @@ -51,158 +46,141 @@ Try { 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") ) { - Write-LogMessage -type INFO -message "Planning and Prepatation Workbook Provided Not Supported" -colour Red - Break + 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") { + Write-LogMessage -type INFO -message "Planning and Prepatation Workbook Provided Not Supported" -colour Red + Break + } + + $sddcDomainName = $pnpWorkbook.Workbook.Names["mgmt_sddc_domain"].Value + $licenseAlias = "vRealize Log Insight" + $licenseKey = if ($pnpWorkbook.Workbook.Names["vrs_license"].Value) { $pnpWorkbook.Workbook.Names["vrs_license"].Value } else { $pnpWorkbook.Workbook.Names["vrli_license"].Value } + $certificateAlias = $pnpWorkbook.Workbook.Names["region_vrli_virtual_hostname"].Value + $passwordAlias = $pnpWorkbook.Workbook.Names["region_vrli_admin_password_alias"].Value + $password = $pnpWorkbook.Workbook.Names["region_vrli_admin_password"].Value + $userName = "admin" + $vrliFolder = $pnpWorkbook.Workbook.Names["region_vrli_vm_folder"].Value + $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 + $antiAffinityRuleName = $pnpWorkbook.Workbook.Names["region_vrli_anti_affinity_rule_name"].Value + $antiAffinityVMs = $vrliVmList + $ruleName = "vm-vm-rule-wsa-vrli" + $drsGroupNameVrli = $pnpWorkbook.Workbook.Names["region_vrli_vm_group_name"].Value + $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 + $smtpServer = $pnpWorkbook.Workbook.Names["smtp_server"].Value + $port = $pnpWorkbook.Workbook.Names["smtp_server_port"].Value + $sender = $pnpWorkbook.Workbook.Names["xreg_vra_smtp_sender_email_address"].Value + $smtpUser = $pnpWorkbook.Workbook.Names["smtp_sender_username"].Value + $smtpPass = $pnpWorkbook.Workbook.Names["smtp_sender_password"].Value + $emailAddress = $pnpWorkbook.Workbook.Names["region_vrli_admin_email"].Value + $retentionNotificationDays = $pnpWorkbook.Workbook.Names["region_vrli_log_retention_notification"].Value.Split(" ")[0] + $retentionInterval = $pnpWorkbook.Workbook.Names["region_vrli_log_retention_notification"].Value.Split(" ")[1] + $retentionPeriodDays = $pnpWorkbook.Workbook.Names["region_vrli_log_retention_period"].Value + $archiveLocation = "nfs://" + $pnpWorkbook.Workbook.Names["region_vrli_nfs_server"].Value + "/" + $pnpWorkbook.Workbook.Names["region_vrli_nfs_share"].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" + + $vrliPem = $certificateAlias + ".2.chain.pem" + 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" + $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 } + + # Import the vRealize Log Insight Certificate to vRealize Suite Lifecycle Manager + Write-LogMessage -Type INFO -Message "Import the vRealize Log Insight Certificate to vRealize Suite Lifecycle Manager" + $StatusMsg = Import-vRSLCMLockerCertificate -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -certificateAlias $certificateAlias -certChainPath ($filePath + "\" + $vrliPem) -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 the vRealize Log Insight Admin Password to vRealize Suite Lifecycle Manager + Write-LogMessage -Type INFO -Message "Add the vRealize Log Insight Admin Password to vRealize Suite Lifecycle Manager" + $StatusMsg = New-vRSLCMLockerPassword -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -alias $passwordAlias -password $password -userName $userName -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 vRealize Log Insight by Using vRealize Suite Lifecycle Manager + Write-LogMessage -Type INFO -Message "Deploy vRealize Log Insight by Using vRealize Suite Lifecycle Manager" + $StatusMsg = New-vRLIDeployment -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -workbook $workbook -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 } + + # Create Virtual Machine and Template Folder for vRealize Log Insight + Write-LogMessage -Type INFO -Message "Create Virtual Machine and Template Folder for vRealize Log Insight" + $StatusMsg = Add-VMFolder -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcDomainName -folderName $vrliFolder -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 } + + # Move the vRealize Log Insight Virtual Machines to the Dedicated Folder + Write-LogMessage -Type INFO -Message "Move the vRealize Log Insight Virtual Machines to the Dedicated Folder" + $StatusMsg = Move-VMtoFolder -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcDomainName -vmList $vrliVmList -folder $vrliFolder -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg -match "SUCCESSFUL" ) { Write-LogMessage -Type INFO -Message "Relocating vRealize Log Insight Cluster Virtual Machines to Dedicated Folder: SUCCESSFUL" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Configure a vSphere DRS Anti-Affinity Rule for vRealize Log Insight + Write-LogMessage -Type INFO -Message "Configure a vSphere DRS Anti-Affinity Rule for vRealize Log Insight" + $StatusMsg = Add-AntiAffinityRule -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcDomainName -ruleName $antiAffinityRuleName -antiAffinityVMs $antiAffinityVMs -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 VM Group and Define the Startup Order of the vRealize Log Insight Cluster + Write-LogMessage -Type INFO -Message "Create a VM Group and Define the Startup Order of the vRealize Log Insight Cluster" + $StatusMsg = Add-ClusterGroup -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcDomainName -drsGroupName $drsGroupNameVrli -drsGroupVMs $drsGroupVMs -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-VmStartupRule -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcDomainName -ruleName $ruleName -vmGroup $drsGroupNameVrli -dependOnVmGroup $drsGroupNameWsa -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 ($stretchedCluster -eq "Include") { + # Add the vRealize Log Insight Virtual Machines to the First Availability Zone VM Group + Write-LogMessage -Type INFO -Message "Add the vRealize Log Insight Virtual Machines to the First Availability Zone VM Group" + $StatusMsg = Add-VmGroup -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcDomainName -name $groupName -vmList $vmList -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 } + } + + # Configure SMTP for vRealize Log Insight + Write-LogMessage -Type INFO -Message "Configure SMTP for vRealize Log Insight" + $StatusMsg = Add-vRLISmtpConfiguation -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -smtpServer $smtpServer -port $port -sender $sender -smtpUser $smtpUser -smtpPass $smtpPass -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 } + + # Configure Log Retention and Archiving for vRealize Log Insight + Write-LogMessage -Type INFO -Message "Configure Log Retention and Archiving for vRealize Log Insight" + $StatusMsg = Add-vRLILogArchive -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -emailAddress $emailAddress -retentionNotificationDays $retentionNotificationDays -retentionInterval weeks -retentionPeriodDays $retentionPeriodDays -archiveLocation $archiveLocation -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 Authentication for vRealize Log Insight by Using Workspace ONE Access + Write-LogMessage -Type INFO -Message "Enable Authentication for vRealize Log Insight by Using Workspace ONE Access" + $StatusMsg = Add-vRLIAuthenticationWSA -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -wsaFqdn $wsaFqdn -wsaUser $wsaUser -wsaPass $wsaPass -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 } + + # 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 + 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 + Write-LogMessage -Type INFO -Message "Assign vRealize Log Insight Roles to Active Directory Groups" + $StatusMsg = Add-vRLIAuthenticationGroup -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $domain -group $vrliAdminGroup -role 'Super 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 = Add-vRLIAuthenticationGroup -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $domain -group $vrliUserGroup -role 'User' -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-vRLIAuthenticationGroup -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $domain -group $vrliViewerGroup -role 'View Only 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 } } - - $sddcDomainName = $pnpWorkbook.Workbook.Names["mgmt_sddc_domain"].Value - - $licenseAlias = "vRealize Log Insight" - $licenseKey = if ($pnpWorkbook.Workbook.Names["vrs_license"].Value) { $pnpWorkbook.Workbook.Names["vrs_license"].Value } else { $pnpWorkbook.Workbook.Names["vrli_license"].Value } - $certificateAlias = $pnpWorkbook.Workbook.Names["region_vrli_virtual_hostname"].Value - $passwordAlias = $pnpWorkbook.Workbook.Names["region_vrli_admin_password_alias"].Value - $password = $pnpWorkbook.Workbook.Names["region_vrli_admin_password"].Value - $userName = "admin" - $vrliFolder = $pnpWorkbook.Workbook.Names["region_vrli_vm_folder"].Value - $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 - $antiAffinityRuleName = $pnpWorkbook.Workbook.Names["region_vrli_anti_affinity_rule_name"].Value - $antiAffinityVMs = $vrliVmList - $ruleName = "vm-vm-rule-wsa-vrli" - $drsGroupNameVrli = $pnpWorkbook.Workbook.Names["region_vrli_vm_group_name"].Value - $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 - $smtpServer = $pnpWorkbook.Workbook.Names["smtp_server"].Value - $port = $pnpWorkbook.Workbook.Names["smtp_server_port"].Value - $sender = $pnpWorkbook.Workbook.Names["xreg_vra_smtp_sender_email_address"].Value - $smtpUser = $pnpWorkbook.Workbook.Names["smtp_sender_username"].Value - $smtpPass = $pnpWorkbook.Workbook.Names["smtp_sender_password"].Value - $emailAddress = $pnpWorkbook.Workbook.Names["region_vrli_admin_email"].Value - $retentionNotificationDays = $pnpWorkbook.Workbook.Names["region_vrli_log_retention_notification"].Value.Split(" ")[0] - $retentionInterval = $pnpWorkbook.Workbook.Names["region_vrli_log_retention_notification"].Value.Split(" ")[1] - $retentionPeriodDays = $pnpWorkbook.Workbook.Names["region_vrli_log_retention_period"].Value - $archiveLocation = "nfs://" + $pnpWorkbook.Workbook.Names["region_vrli_nfs_server"].Value + "/" + $pnpWorkbook.Workbook.Names["region_vrli_nfs_share"].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" - - $vrliPem = $certificateAlias + ".2.chain.pem" - 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" } } - else { - Write-LogMessage -Type ERROR -Message "Unable to connect to SDDC Manager $server" -Colour Red - Exit - } -} -Catch { - Debug-CatchWriter -object $_ -} - -Try { - # 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" - $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 } - - # Import the vRealize Log Insight Certificate to vRealize Suite Lifecycle Manager - Write-LogMessage -Type INFO -Message "Import the vRealize Log Insight Certificate to vRealize Suite Lifecycle Manager" - $StatusMsg = Import-vRSLCMLockerCertificate -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -certificateAlias $certificateAlias -certChainPath ($filePath + "\" + $vrliPem) -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 the vRealize Log Insight Admin Password to vRealize Suite Lifecycle Manager - Write-LogMessage -Type INFO -Message "Add the vRealize Log Insight Admin Password to vRealize Suite Lifecycle Manager" - $StatusMsg = New-vRSLCMLockerPassword -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -alias $passwordAlias -password $password -userName $userName -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 vRealize Log Insight by Using vRealize Suite Lifecycle Manager - Write-LogMessage -Type INFO -Message "Deploy vRealize Log Insight by Using vRealize Suite Lifecycle Manager" - $StatusMsg = New-vRLIDeployment -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -workbook $workbook -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 } - - # Create Virtual Machine and Template Folder for vRealize Log Insight - Write-LogMessage -Type INFO -Message "Create Virtual Machine and Template Folder for vRealize Log Insight" - $StatusMsg = Add-VMFolder -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcDomainName -folderName $vrliFolder -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 } - - # Move the vRealize Log Insight Virtual Machines to the Dedicated Folder - Write-LogMessage -Type INFO -Message "Move the vRealize Log Insight Virtual Machines to the Dedicated Folder" - $StatusMsg = Move-VMtoFolder -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcDomainName -vmList $vrliVmList -folder $vrliFolder -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg - if ( $StatusMsg -match "SUCCESSFUL" ) { Write-LogMessage -Type INFO -Message "Relocating vRealize Log Insight Cluster Virtual Machines to Dedicated Folder: SUCCESSFUL" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } - - # Configure a vSphere DRS Anti-Affinity Rule for vRealize Log Insight - Write-LogMessage -Type INFO -Message "Configure a vSphere DRS Anti-Affinity Rule for vRealize Log Insight" - $StatusMsg = Add-AntiAffinityRule -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcDomainName -ruleName $antiAffinityRuleName -antiAffinityVMs $antiAffinityVMs -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 VM Group and Define the Startup Order of the vRealize Log Insight Cluster - Write-LogMessage -Type INFO -Message "Create a VM Group and Define the Startup Order of the vRealize Log Insight Cluster" - $StatusMsg = Add-ClusterGroup -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcDomainName -drsGroupName $drsGroupNameVrli -drsGroupVMs $drsGroupVMs -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-VmStartupRule -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcDomainName -ruleName $ruleName -vmGroup $drsGroupNameVrli -dependOnVmGroup $drsGroupNameWsa -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 ($stretchedCluster -eq "Include") { - # Add the vRealize Log Insight Virtual Machines to the First Availability Zone VM Group - Write-LogMessage -Type INFO -Message "Add the vRealize Log Insight Virtual Machines to the First Availability Zone VM Group" - $StatusMsg = Add-VmGroup -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcDomainName -name $groupName -vmList $vmList -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 } - } - - # Configure SMTP for vRealize Log Insight - Write-LogMessage -Type INFO -Message "Configure SMTP for vRealize Log Insight" - $StatusMsg = Add-vRLISmtpConfiguation -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -smtpServer $smtpServer -port $port -sender $sender -smtpUser $smtpUser -smtpPass $smtpPass -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 } - - # Configure Log Retention and Archiving for vRealize Log Insight - Write-LogMessage -Type INFO -Message "Configure Log Retention and Archiving for vRealize Log Insight" - $StatusMsg = Add-vRLILogArchive -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -emailAddress $emailAddress -retentionNotificationDays $retentionNotificationDays -retentionInterval weeks -retentionPeriodDays $retentionPeriodDays -archiveLocation $archiveLocation -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 Authentication for vRealize Log Insight by Using Workspace ONE Access - Write-LogMessage -Type INFO -Message "Enable Authentication for vRealize Log Insight by Using Workspace ONE Access" - $StatusMsg = Add-vRLIAuthenticationWSA -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -wsaFqdn $wsaFqdn -wsaUser $wsaUser -wsaPass $wsaPass -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 } - - # 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 - 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 - Write-LogMessage -Type INFO -Message "Assign vRealize Log Insight Roles to Active Directory Groups" - $StatusMsg = Add-vRLIAuthenticationGroup -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $domain -group $vrliAdminGroup -role 'Super 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 } - Add-vRLIAuthenticationGroup -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $domain -group $vrliUserGroup -role 'User' -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-vRLIAuthenticationGroup -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $domain -group $vrliViewerGroup -role 'View Only 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 } } Catch { Debug-CatchWriter -object $_ From 27535eda885fc6261984e7d3625156cb9757c2c1 Mon Sep 17 00:00:00 2001 From: GaryJBlake Date: Tue, 25 Jan 2022 11:55:25 +0000 Subject: [PATCH 3/5] Added IOM SampleScripts Added end-to-end automation SampleScripts for IOM Signed-off-by: Gary Blake --- .../iam/iamConfigureNsx.ps1 | 0 .../iam/iamConfigureVsphere.ps1 | 0 .../iam/iamConfigureWorkspaceOne.ps1 | 0 .../ila/ilaConfigureVrealizeLogInsight.ps1 | 0 .../ila/ilaDeployVrealizeLogInsight.ps1 | 0 .../iom/iomConfigureVrealizeOperations.ps1 | 120 +++++++++++ .../iom/iomDeployVrealizeOperations.ps1 | 201 ++++++++++++++++++ 7 files changed, 321 insertions(+) rename {SampleProjects => SampleScripts}/iam/iamConfigureNsx.ps1 (100%) rename {SampleProjects => SampleScripts}/iam/iamConfigureVsphere.ps1 (100%) rename {SampleProjects => SampleScripts}/iam/iamConfigureWorkspaceOne.ps1 (100%) rename {SampleProjects => SampleScripts}/ila/ilaConfigureVrealizeLogInsight.ps1 (100%) rename {SampleProjects => SampleScripts}/ila/ilaDeployVrealizeLogInsight.ps1 (100%) create mode 100644 SampleScripts/iom/iomConfigureVrealizeOperations.ps1 create mode 100644 SampleScripts/iom/iomDeployVrealizeOperations.ps1 diff --git a/SampleProjects/iam/iamConfigureNsx.ps1 b/SampleScripts/iam/iamConfigureNsx.ps1 similarity index 100% rename from SampleProjects/iam/iamConfigureNsx.ps1 rename to SampleScripts/iam/iamConfigureNsx.ps1 diff --git a/SampleProjects/iam/iamConfigureVsphere.ps1 b/SampleScripts/iam/iamConfigureVsphere.ps1 similarity index 100% rename from SampleProjects/iam/iamConfigureVsphere.ps1 rename to SampleScripts/iam/iamConfigureVsphere.ps1 diff --git a/SampleProjects/iam/iamConfigureWorkspaceOne.ps1 b/SampleScripts/iam/iamConfigureWorkspaceOne.ps1 similarity index 100% rename from SampleProjects/iam/iamConfigureWorkspaceOne.ps1 rename to SampleScripts/iam/iamConfigureWorkspaceOne.ps1 diff --git a/SampleProjects/ila/ilaConfigureVrealizeLogInsight.ps1 b/SampleScripts/ila/ilaConfigureVrealizeLogInsight.ps1 similarity index 100% rename from SampleProjects/ila/ilaConfigureVrealizeLogInsight.ps1 rename to SampleScripts/ila/ilaConfigureVrealizeLogInsight.ps1 diff --git a/SampleProjects/ila/ilaDeployVrealizeLogInsight.ps1 b/SampleScripts/ila/ilaDeployVrealizeLogInsight.ps1 similarity index 100% rename from SampleProjects/ila/ilaDeployVrealizeLogInsight.ps1 rename to SampleScripts/ila/ilaDeployVrealizeLogInsight.ps1 diff --git a/SampleScripts/iom/iomConfigureVrealizeOperations.ps1 b/SampleScripts/iom/iomConfigureVrealizeOperations.ps1 new file mode 100644 index 00000000..ca8fdec0 --- /dev/null +++ b/SampleScripts/iom/iomConfigureVrealizeOperations.ps1 @@ -0,0 +1,120 @@ +<# + .NOTES + =========================================================================== + Created by: Gary Blake - Senior Staff Solutions Architect + Date: 12/15/2021 + Copyright 2021 VMware, Inc. + =========================================================================== + + .SYNOPSIS + Configure Integration of vRealize Operations Manager for Intelligent Operations Management + + .DESCRIPTION + The iomConfigureVrealizeOperations.ps1 provides a single script to configure the intergration of vRealize Operations Manager + as defined by the Intelligent Operations Management Validated Solution + + .EXAMPLE + iomConfigureVrealizeOperations.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 and configure of vRealize Operations Manager 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 Integration Configuration of vRealize Operations Manager Based on Intelligent Operations Management for VMware Cloud Foundation" -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") { + Write-LogMessage -type INFO -message "Planning and Prepatation Workbook Provided Not Supported" -colour Red + Break + } + + $sddcDomainName = $pnpWorkbook.Workbook.Names["mgmt_sddc_domain"].Value + $sddcWldDomainName = $pnpWorkbook.Workbook.Names["wld_sddc_domain"].Value + + $collectorGroupName = $pnpWorkbook.Workbook.Names["mgmt_sddc_domain"].Value + "-remote-collectors" + $defaultCollectorGroup = "Default collector group" + $vropsIpList = $pnpWorkbook.Workbook.Names["xreg_vrops_virtual_ip"].Value + "," + $pnpWorkbook.Workbook.Names["xreg_vrops_nodea_ip"].Value + "," + $pnpWorkbook.Workbook.Names["xreg_vrops_nodeb_ip"].Value + "," + $pnpWorkbook.Workbook.Names["xreg_vrops_nodec_ip"].Value + $vropsAdapterName = $pnpWorkbook.Workbook.Names["xreg_vrops_virtual_hostname"].Value + $vropsrcIpList = $pnpWorkbook.Workbook.Names["region_vropsca_ip"].Value + "," + $pnpWorkbook.Workbook.Names["region_vropscb_ip"].Value + $vropsrcAdapterName = $collectorGroupName + + # Connect vRealize Operations Manager to the VI Workload Domains in the First VMware Cloud Foundation Instance + Write-LogMessage -Type INFO -Message "Connect vRealize Operations Manager to the VI Workload Domains in the First VMware Cloud Foundation Instance" + $StatusMsg = Register-vROPSWorkloadDomain -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcWldDomainName -status ENABLED -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 } + + # Modify the vCenter Server Adapters for the First VMware Cloud Foundation Instance in vRealize Operations Manager + Write-LogMessage -Type INFO -Message "Modify the vCenter Server Adapters for the First VMware Cloud Foundation Instance in vRealize Operations Manager" + $StatusMsg = Update-vROPSAdapterVcenter -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -collectorGroupName $collectorGroupName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "Modifing the vCenter Server Adapters for the First VMware Cloud Foundation Instance: SUCCESSFUL" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message "Modifing the vCenter Server Adapters for the First VMware Cloud Foundation Instance, already modifed: SKIPPED" -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Add NSX-T Data Center Adapters in vRealize Operations Manager + Write-LogMessage -Type INFO -Message "Add NSX-T Data Center Adapters in vRealize Operations Manager" + $StatusMsg = Add-vROPSAdapterNsxt -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcDomainName -collectorGroupName $collectorGroupName -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-vROPSAdapterNsxt -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcWldDomainName -collectorGroupName $collectorGroupName -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 } + + # Install the SDDC Health Monitoring Solution in vRealize Operations Manager + Write-LogMessage -Type INFO -Message "Install the SDDC Health Monitoring Solution in vRealize Operations Manager" + $StatusMsg = Enable-vROPSManagementPack -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPAss -packType "SDDC Health" -pakFile "F:\vvs\vmware-mpforsddchealth-8-1619468209785.pak" -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 } + + # Rename the SDDC Health Adapters for the vRealize Operations Manager Analytics Cluster Nodes + Write-LogMessage -Type INFO -Message "Rename the SDDC Health Adapters for the vRealize Operations Manager Analytics Cluster Nodes" + $StatusMsg = Update-vROPSAdapterSddcHealth -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "Renaming the SDDC Health Adapters for the vRealize Operations Manager: SUCCESSFUL" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message "Renaming the SDDC Health Adapters for the vRealize Operations Manager, already performed: SKIPPED" -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Add SDDC Health Adapters for the vRealize Operations Manager Remote Collector Nodes + Write-LogMessage -Type INFO -Message "Add SDDC Health Adapters for the vRealize Operations Manager Remote Collector Nodes" + $StatusMsg = Add-vROPSAdapterSddcHealth -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg ) { Write-LogMessage -Type INFO -Message "Adding Adapter (SDDC Health Adapter Instance) for Remore Collectors to vRealize Operations Manager (xint-vrops01.rainpole.io): SUCCESSFUL" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message "Adding Adapter (SDDC Health Adapter Instance) for Remore Collectors to vRealize Operations Manager (xint-vrops01.rainpole.io), already performed: SKIPPED" -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Activate the Ping Management Pack in vRealize Operations Manager + Write-LogMessage -Type INFO -Message "Activate the Ping Management Pack in vRealize Operations Manager" + $StatusMsg = Register-vROPSManagementPack -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -state enable -packType Ping -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 Ping Adapters for the vRealize Operations Manager Nodes + Write-LogMessage -Type INFO -Message "Add Ping Adapters for the vRealize Operations Manager Nodes" + $StatusMsg = Add-vROPSAdapterPing -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -addressList $vropsIpList -adapterName $vropsAdapterName -collectorGroupName $defaultCollectorGroup -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-vROPSAdapterPing -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -addressList $vropsrcIpList -adapterName $vropsrcAdapterName -collectorGroupName $collectorGroupName -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 Notifications in vRealize Operations Manager for VMware Cloud Foundation Issues + Write-LogMessage -Type INFO -Message "Create Notifications in vRealize Operations Manager for VMware Cloud Foundation Issues" + $StatusMsg = Import-vROPSNotification -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -csvPath "F:\PowerValidatedSolutions\SampleNotifications\notifications-vcf.csv" -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/iom/iomDeployVrealizeOperations.ps1 b/SampleScripts/iom/iomDeployVrealizeOperations.ps1 new file mode 100644 index 00000000..fc35d9eb --- /dev/null +++ b/SampleScripts/iom/iomDeployVrealizeOperations.ps1 @@ -0,0 +1,201 @@ +<# + .NOTES + =========================================================================== + Created by: Gary Blake - Senior Staff Solutions Architect + Date: 12/14/2021 + Copyright 2021 VMware, Inc. + =========================================================================== + + .SYNOPSIS + Deploy vRealize Operations Manager for Intelligent Operations Management + + .DESCRIPTION + The iomDeployVrealizeOperations.ps1 provides a single script to deploy and configure vRealize Operations Manager + as defined by the Intelligent Operations Management Validated Solution + + .EXAMPLE + iomDeployVrealizeOperations.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 and configure of vRealize Operations Manager 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 vRealize Operations Manager Based on Intelligent Operations Management for VMware Cloud Foundation" -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") { + Write-LogMessage -type INFO -message "Planning and Prepatation Workbook Provided Not Supported" -colour Red + Break + } + + $sddcDomainName = $pnpWorkbook.Workbook.Names["mgmt_sddc_domain"].Value + $licenseAlias = if ($pnpWorkbook.Workbook.Names["vrs_license"].Value) { "vRealize Suite 2019" } else { "vRealize Operations Manager" } + $licenseKey = if ($pnpWorkbook.Workbook.Names["vrs_license"].Value) { $pnpWorkbook.Workbook.Names["vrs_license"].Value } else { $pnpWorkbook.Workbook.Names["vrops_license"].Value } + $certificateAlias = $pnpWorkbook.Workbook.Names["xreg_vrops_virtual_hostname"].Value + $rootPasswordAlias = $pnpWorkbook.Workbook.Names["xreg_vrops_root_password_alias"].Value + $rootPassword = $pnpWorkbook.Workbook.Names["xreg_vrops_root_password"].Value + $rootUserName = "root" + $xintPasswordAlias = $pnpWorkbook.Workbook.Names["vrslcm_xreg_env_password_alias"].Value + $xintPassword = $pnpWorkbook.Workbook.Names["vrslcm_xreg_env_password"].Value + $xintUserName = $pnpWorkbook.Workbook.Names["vrslcm_xreg_admin_username"].Value + $vropsFolder = $pnpWorkbook.Workbook.Names["xreg_vrops_vm_folder"].Value + $vropsrcFolder = $pnpWorkbook.Workbook.Names["region_vrops_collector_vm_folder"].Value + $vropsVmList = $pnpWorkbook.Workbook.Names["xreg_vrops_nodea_hostname"].Value + "," + $pnpWorkbook.Workbook.Names["xreg_vrops_nodeb_hostname"].Value + "," + $pnpWorkbook.Workbook.Names["xreg_vrops_nodec_hostname"].Value + $vropsrcVmList = $pnpWorkbook.Workbook.Names["region_vropsca_hostname"].Value + "," + $pnpWorkbook.Workbook.Names["region_vropscb_hostname"].Value + $vropsAntiAffinityRuleName = "anti-affinity-rule-vrops" + $vropsAntiAffinityVMs = $vropsVmList + $vropsrcAntiAffinityRuleName = "anti-affinity-rule-vropsrc" + $vropsrcAntiAffinityVMs = $vropsrcVmList + $ruleNameVrops = "vm-vm-rule-wsa-vrops" + $drsGroupNameVrops = $pnpWorkbook.Workbook.Names["xreg_vrops_vm_group_name"].Value + $drsGroupNameWsa = $pnpWorkbook.Workbook.Names["xreg_wsa_vm_group_name"].Value + $drsGroupVMsVrops = $vropsVmList + $ruleNameVropsrc = "vm-vm-rule-vrops-vropsrc" + $drsGroupNameVropsrc = $pnpWorkbook.Workbook.Names["region_vrops_collector_group_name"].Value + $drsGroupVMsVropsrc = $vropsrcVmList + $vmList = $pnpWorkbook.Workbook.Names["xreg_vrops_nodea_hostname"].Value + "," + $pnpWorkbook.Workbook.Names["xreg_vrops_nodeb_hostname"].Value + "," + $pnpWorkbook.Workbook.Names["xreg_vrops_nodec_hostname"].Value + "," + $pnpWorkbook.Workbook.Names["region_vropsca_hostname"].Value + "," + $pnpWorkbook.Workbook.Names["region_vropscb_hostname"].Value + $groupName = "primary_az_vmgroup" + $stretchedCluster = $pnpWorkbook.Workbook.Names["mgmt_stretched_cluster_chosen"].Value + $collectorGroupName = $pnpWorkbook.Workbook.Names["mgmt_sddc_domain"].Value + "-remote-collectors" + $currency = $pnpWorkbook.Workbook.Names["xreg_vrops_currency"].Value + $wsaFqdn = $pnpWorkbook.Workbook.Names["xreg_wsa_nodea_hostname"].Value + "." + $pnpWorkbook.Workbook.Names["parent_dns_zone"].Value + $wsaUser = $pnpWorkbook.Workbook.Names["local_admin_username"].Value + $wsaPass = $pnpWorkbook.Workbook.Names["local_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 + $adGroups = "$($pnpWorkbook.Workbook.Names["group_gg_vrops_admins"].Value)","$($pnpWorkbook.Workbook.Names["group_gg_vrops_content_admins"].Value)","$($pnpWorkbook.Workbook.Names["group_gg_vrops_read_only"].Value)" + $smtpServer = $pnpWorkbook.Workbook.Names["smtp_server"].Value + $smtpPort = $pnpWorkbook.Workbook.Names["smtp_server_port"].Value + $senderAddress = $pnpWorkbook.Workbook.Names["xreg_vrops_smtp_sender_email_address"].Value + $vropsAdminGroup = $pnpWorkbook.Workbook.Names["group_gg_vrops_admins"].Value + $vropsContentAdminGroup = $pnpWorkbook.Workbook.Names["group_gg_vrops_content_admins"].Value + $vropsReadOnlyGroup = $pnpWorkbook.Workbook.Names["group_gg_vrops_read_only"].Value + $vropsPem = $certificateAlias + ".2.chain.pem" + if (!(Test-Path ($filePath + "\" + $vropsPem) )) { Write-LogMessage -Type ERROR -Message "Unable to Find Certificate File: $vropsPem, check details and try again" -Colour Red; Break } else { Write-LogMessage -Type INFO -Message "Found Certificate File: $vropsPem" } + + # Add the vRealize Operations Manager License to vRealize Suite Lifecycle Manager + Write-LogMessage -Type INFO -Message "Add the vRealize Operations Manager 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 } + + # Import the Certificate for vRealize Operations Manager to vRealize Suite Lifecycle Manager + Write-LogMessage -Type INFO -Message "Import the Certificate for vRealize Operations Manager to vRealize Suite Lifecycle Manager" + $StatusMsg = Import-vRSLCMLockerCertificate -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -certificateAlias $certificateAlias -certChainPath ($filePath + "\" + $vropsPem) -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 the vRealize Operations Manager Password to vRealize Suite Lifecycle Manager + Write-LogMessage -Type INFO -Message "Add the vRealize Operations Manager Password to vRealize Suite Lifecycle Manager" + $StatusMsg = New-vRSLCMLockerPassword -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -alias $rootPasswordAlias -password $rootPassword -userName $rootUserName -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 = New-vRSLCMLockerPassword -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -alias $xintPasswordAlias -password $xintPassword -userName $xintUserName -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 vRealize Operations Manager by Using vRealize Suite Lifecycle Manager + Write-LogMessage -Type INFO -Message "Deploy vRealize Operations Manager by Using vRealize Suite Lifecycle Manager" + $StatusMsg = New-vROPSDeployment -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -workbook $workbook -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 } + + # Create Virtual Machine and Template Folders for the vRealize Operations Manager Virtual Machines + Write-LogMessage -Type INFO -Message "Create Virtual Machine and Template Folders for the vRealize Operations Manager Virtual Machines" + $StatusMsg = Add-VMFolder -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcDomainName -folderName $vropsFolder -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-VMFolder -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcDomainName -folderName $vropsrcFolder -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 } + + # Move the vRealize Operations Manager Virtual Machines to the Dedicated Folders + Write-LogMessage -Type INFO -Message "Move the vRealize Operations Manager Virtual Machines to the Dedicated Folders" + $StatusMsg = Move-VMtoFolder -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcDomainName -vmList $vropsVmList -folder $vropsFolder -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg -match "SUCCESSFUL") { Write-LogMessage -Type INFO -Message "Relocating vRealize Operations Manager Cluster Virtual Machines to Dedicated Folder: SUCCESSFUL" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + $StatusMsg = Move-VMtoFolder -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcDomainName -vmList $vropsrcVmList -folder $vropsrcFolder -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg + if ( $StatusMsg -match "SUCCESSFUL") { Write-LogMessage -Type INFO -Message "Relocating vRealize Operations Manager Remote Collector Virtual Machines to Dedicated Folder: SUCCESSFUL" } if ( $WarnMsg ) { Write-LogMessage -Type WARNING -Message $WarnMsg -Colour Magenta } if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg -Colour Red } + + # Configure vSphere DRS Anti-Affinity Rules for the vRealize Operations Manager Virtual Machines + Write-LogMessage -Type INFO -Message "Configure vSphere DRS Anti-Affinity Rules for the vRealize Operations Manager Virtual Machines" + $StatusMsg = Add-AntiAffinityRule -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcDomainName -ruleName $vropsAntiAffinityRuleName -antiAffinityVMs $vropsAntiAffinityVMs -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-AntiAffinityRule -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcDomainName -ruleName $vropsrcAntiAffinityRuleName -antiAffinityVMs $vropsrcAntiAffinityVMs -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 VM Group and Define the Startup Order of the vRealize Operations Manager Analytics Cluster Virtual Machines + Write-LogMessage -Type INFO -Message "Create a VM Group and Define the Startup Order of the vRealize Operations Manager Analytics Cluster Virtual Machines" + $StatusMsg = Add-ClusterGroup -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcDomainName -drsGroupName $drsGroupNameVrops -drsGroupVMs $drsGroupVMsVrops -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-VmStartupRule -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcDomainName -ruleName $ruleNameVrops -vmGroup $drsGroupNameVrops -dependOnVmGroup $drsGroupNameWsa -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 VM Group and Define the Startup Order of the vRealize Operations Manager Remote Collector Virtual Machines + Write-LogMessage -Type INFO -Message "Create a VM Group and Define the Startup Order of the vRealize Operations Manager Remote Collector Virtual Machines" + $StatusMsg = Add-ClusterGroup -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcDomainName -drsGroupName $drsGroupNameVropsrc -drsGroupVMs $drsGroupVMsVropsrc -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-VmStartupRule -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcDomainName -ruleName $ruleNameVropsrc -vmGroup $drsGroupNameVropsrc -dependOnVmGroup $drsGroupNameVrops -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 ($stretchedCluster -eq "Include") { + # Add the vRealize Operations Manager Virtual Machines to the First Availability Zone VM Group + Write-LogMessage -Type INFO -Message "Add the vRealize Operations Manager Virtual Machines to the First Availability Zone VM Group" + $StatusMsg = Add-VmGroup -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $sddcDomainName -name $groupName -vmList $vmList -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 } + } + + # Group the vRealize Operations Manager Remote Collector Nodes + Write-LogMessage -Type INFO -Message "Group the vRealize Operations Manager Remote Collector Nodes" + $StatusMsg = Add-vROPSGroupRemoteCollectors -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -collectorGroupName $collectorGroupName -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 } + + # Synchronize the Active Directory Groups for vRealize Operations Manager in Workspace ONE Access + Write-LogMessage -Type INFO -Message "Synchronize the Active Directory Groups for vRealize Operations Manager in 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 + 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 } + + # Configure User Access in vRealize Operations Manager + Write-LogMessage -Type INFO -Message "Configure User Access in vRealize Operations Manager" + $StatusMsg = Import-vROPSUserGroup -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $domain -groupName $vropsAdminGroup -role Administrator -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 = Import-vROPSUserGroup -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $domain -groupName $vropsContentAdminGroup -role ContentAdmin -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 = Import-vROPSUserGroup -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -domain $domain -groupName $vropsReadOnlyGroup -role ReadOnly -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 } + + # Set the Currency for Cost Calculation in vRealize Operations Manager + Write-LogMessage -Type INFO -Message "Set the Currency for Cost Calculation in vRealize Operations Manager" + $StatusMsg = Add-vROPSCurrency -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -currency $currency -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 } + + # Configure Email Alert Plug-in Settings for vRealize Operations Manager + Write-LogMessage -Type INFO -Message "Configure Email Alert Plug-in Settings for vRealize Operations Manager" + $StatusMsg = Add-vROPSAlertPluginEmail -server $sddcManagerFqdn -user $sddcManagerUser -pass $sddcManagerPass -pluginName "Email-Alert-Plugin" -smtpServer $smtpServer -smtpPort $smtpPort -senderAddress $senderAddress -secureConnection true -protocol TLS -authentication 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 } + } + } +} +Catch { + Debug-CatchWriter -object $_ +} From f3531ecf352e2f37ddd6d7ebeb567f3a38921d9d Mon Sep 17 00:00:00 2001 From: GaryJBlake Date: Tue, 25 Jan 2022 11:56:54 +0000 Subject: [PATCH 4/5] Add vRLI Alert and vROPS Notification Templates - Added vRLI Alerts json templates for virtual machine and datacenter email alerts - Added vROPS Notification csv template for alert definition notifications Signed-off-by: Gary Blake --- SampleNotifications/vrli-vcf-datacenter.json | 856 ++++++++++++++++++ SampleNotifications/vrli-vcf-vmVrslcm.json | 99 ++ .../vrops-vcf-notifications.csv | 28 + 3 files changed, 983 insertions(+) create mode 100644 SampleNotifications/vrli-vcf-datacenter.json create mode 100644 SampleNotifications/vrli-vcf-vmVrslcm.json create mode 100644 SampleNotifications/vrops-vcf-notifications.csv diff --git a/SampleNotifications/vrli-vcf-datacenter.json b/SampleNotifications/vrli-vcf-datacenter.json new file mode 100644 index 00000000..62fb181e --- /dev/null +++ b/SampleNotifications/vrli-vcf-datacenter.json @@ -0,0 +1,856 @@ +[ + { + "name": "*** CRITICAL *** ESXi: Core dump detected (!!datacenterName!!)", + "info":"A core dump has been detected, which indicates the failure of a component in ESXi. This issue may lead to VM crashes and/or host PSODs.

For more information, see: Trending Issues: Fault/Crash problems with ESXi", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType": "RATE_BASED", + "hitOperator": "GREATER_THAN", + "hitCount": 0, + "searchPeriod":3600000, + "searchInterval":600000, + "chartQuery": "{\"query\":\"\",\"startTimeMillis\":1565993612291,\"endTimeMillis\":1565997212290,\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":false,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"text\",\"operator\":\"DOES_NOT_CONTAIN\",\"value\":\"hostd: --> eventtypeid\"},{\"internalName\":\"ibadcoc7mnxw2ltwnv3wc4tffz3hg4dimvzgk5tno5pwk43ynfpxa4tpmjwgk3i0\",\"operator\":\"CONTAINS\",\"value\":\"dump*\"},{\"internalName\":\"appname\",\"operator\":\"CONTAINS\",\"value\":\"hostd*,vpxa,vobd,vmkernel,vmkwarning,sfcb-cimxml-processor,imageconfigmanager,rhttpproxy,vcenter-server\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[{\"displayName\":\"hostname\",\"internalName\":\"hostname\",\"displayNamespace\":null,\"numericGroupByType\":\"EACH_VALUE\",\"numericGroupByValue\":null}],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_esxi_problem\",\"preContext\":\"esx\\\\.problem\\\\.\",\"postContext\":\"\",\"regexValue\":\"\\\\w+(\\\\.\\\\w+)*\",\"internalName\":\"ibadcoc7mnxw2ltwnv3wc4tffz3hg4dimvzgk5tno5pwk43ynfpxa4tpmjwgk3i0\",\"constraints\":\"{\\\"filters\\\":[{\\\"internalName\\\":\\\"appname\\\",\\\"displayName\\\":\\\"appname\\\",\\\"operator\\\":\\\"CONTAINS\\\",\\\"value\\\":\\\"vcenter-server,vobd,hostd,vmkwarning,vmkernel\\\",\\\"fieldType\\\":\\\"NUMBER\\\",\\\"isExtracted\\\":false,\\\"hidden\\\":false}]}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + },{ + "name":"*** CRITICAL *** Hardware: Physical event detected (!!datacenterName!!)", + "info":"The purpose of this widget is to notify when the following physical hardware events have been detected, which indicates a hardware problem. Under most normal conditions, this widget should return no results. The following types of hardware events are returned

• Advanced Programmable Interrupt Controller (APIC)
• Machine Check Exception (MCE)
• Non-Maskable Interrupt (NMI) 

In the case of a \"Memory Controller Read Error\" MCE, run memtest on the impacted hosts and replace any bad DIMMs.

For more information, see:

• vHBAs and other PCI devices may stop responding in ESXi 6.0.x, ESXi 5.x and ESXi/ESX 4.1 when using Interrupt Remapping
• Identifying and addressing Non-Maskable Interrupt events on an ESXi host
• Decoding Machine Check Exception (MCE) output after a purple screen error
", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType": "RATE_BASED", + "hitOperator": "GREATER_THAN", + "hitCount": 0, + "searchPeriod":86400000, + "searchInterval":3600000, + "ChartQuery": "{\"query\":\"\",\"startTimeMillis\":1567101913277,\"endTimeMillis\":1567188313276,\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":false,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"appname\",\"operator\":\"CONTAINS\",\"value\":\"hostd, vpxa, vobd, vmkernel, vmkwarning, sfcb-cimxml-processor, imageconfigmanager\"},{\"internalName\":\"text\",\"operator\":\"CONTAINS\",\"value\":\"machine check, mce, mc, nmi, apic\"},{\"internalName\":\"text\",\"operator\":\"CONTAINS\",\"value\":\"alert,error,exception,not recoverable,unable to continue\"},{\"internalName\":\"text\",\"operator\":\"DOES_NOT_CONTAIN\",\"value\":\"error ip, recoverable error, fixed, recovery\"},{\"internalName\":\"hostname\",\"operator\":\"DOES_NOT_CONTAIN\",\"value\":\"mce, mc, nmi, apic\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[{\"displayName\":\"hostname\",\"internalName\":\"hostname\",\"displayNamespace\":null,\"numericGroupByType\":\"EACH_VALUE\",\"numericGroupByValue\":null}],\"contentPacksToIncludeFields\":[],\"extractedFields\":[]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + },{ + "name":"Hardware: Faulty memory detected (!!datacenterName!!)", + "info":"During the previous boot of an ESXi host faulty memory was detected. Unless a corresponding corrected message is seen, the memory should be replaced.

For more information, please see:

• Fatal memory detected on previous boot
• Recoverable memory error detected on previous boot
", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType": "RATE_BASED", + "hitOperator": "GREATER_THAN", + "hitCount": 0, + "searchPeriod":86400000, + "searchInterval":3600000, + "chartQuery": "{\"query\":\"\",\"startTimeMillis\":1567106335723,\"endTimeMillis\":1567192735722,\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":false,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"text\",\"operator\":\"CONTAINS\",\"value\":\"esx\"},{\"internalName\":\"text\",\"operator\":\"CONTAINS\",\"value\":\"problem.apei.bert.memory.error\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[{\"displayName\":\"hostname\",\"internalName\":\"hostname\",\"displayNamespace\":null,\"numericGroupByType\":\"EACH_VALUE\",\"numericGroupByValue\":null}],\"contentPacksToIncludeFields\":[],\"extractedFields\":[]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + },{ + "name":"*** CRITICAL *** ESXi: Stopped logging (!!datacenterName!!)", + "info":"The purpose of this alert is to notify when an ESXi host has stopped sending syslog to a remote server. If you want to detect whether an ESXi host has stopped sending syslog to your Log Insight instance, you can further add a filter for 'vc_remote_host equals'.

Certain versions of ESXi 5.0 and 5.1 will no longer forward remote syslog once a remote destination becomes unavailable. To address this issue the syslog process on the impacted ESXi hosts needs to be restarted. If you are using vSphere integration in Log Insight then this can be achieved by selecting View Details for each configured vCenter Server instance, selecting the top checkbox to select all hosts, and selecting the Configure button. Note, this will restart the syslog agent on all ESXi hosts, but this operation has no impact except on hosts that experience the remote syslog issue.

The impacted ESXi versions are:

• UDP - ESXi 5.0, 5.0 Update 1 (fixed in ESXi 5.0 Update 7)
• TCP - ESXi 5.0, 5.0 Update 1, 5.0 Update 2, 5.1, 5.1 Update 1 (fixed in ESXi 5.0 Update 7 and ESXi 5.1 Update 2)

For more information, please see: VMware ESXi 5.x host stops sending syslogs to remote server.
", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType": "RATE_BASED", + "hitOperator": "GREATER_THAN", + "hitCount": 0, + "searchPeriod":900000, + "searchInterval":300000, + "chartQuery": "{\"query\":\"\",\"startTimeMillis\":1567191964081,\"endTimeMillis\":1567192864080,\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":false,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"ibadcoc7mnxw2ltwnv3wc4tffz3hg4dimvzgk5tno5pwk43ynfpxa4tpmjwgk3i0\",\"operator\":\"CONTAINS\",\"value\":\"vmsyslogd.remote.failure\"},{\"internalName\":\"appname\",\"operator\":\"CONTAINS\",\"value\":\"hostd*,vpxa,vobd,vmkernel,vmkwarning,sfcb-cimxml-processor,imageconfigmanager,rhttpproxy,vcenter-server\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[{\"displayName\":\"hostname\",\"internalName\":\"hostname\",\"displayNamespace\":null,\"numericGroupByType\":\"EACH_VALUE\",\"numericGroupByValue\":null}],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_esxi_problem\",\"preContext\":\"esx\\\\.problem\\\\.\",\"postContext\":\"\",\"regexValue\":\"\\\\w+(\\\\.\\\\w+)*\",\"internalName\":\"ibadcoc7mnxw2ltwnv3wc4tffz3hg4dimvzgk5tno5pwk43ynfpxa4tpmjwgk3i0\",\"constraints\":\"{\\\"filters\\\":[{\\\"internalName\\\":\\\"appname\\\",\\\"displayName\\\":\\\"appname\\\",\\\"operator\\\":\\\"CONTAINS\\\",\\\"value\\\":\\\"vcenter-server,vobd,hostd,vmkwarning,vmkernel\\\",\\\"fieldType\\\":\\\"NUMBER\\\",\\\"isExtracted\\\":false,\\\"hidden\\\":false}]}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + },{ + "name":"*** CRITICAL *** ESXi: RAM disk / inode table is full (!!datacenterName!!)", + "info":"A root file system has reached its resource pool limit. Various administrative actions depend on the ability to write files to various parts of the root file system and might fail if the RAM disk and/or inode table is full. 

For more information, please see:

• The ramdisk 'root' is full
• 
RAM disk is full
• VMware ESXi 5.x host becomes unresponsive when attempting a vMotion migration or a configuration change
• 
ESXi 5.x host is disconnected from vCenter Server due to sfcbd exhausting inodes
• Many current.png.xxxx on the /tmp on ESXi host causes hostd to crash and disconnect

", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType": "RATE_BASED", + "hitOperator": "GREATER_THAN", + "hitCount": 0, + "searchPeriod":3600000, + "searchInterval":600000, + "chartQuery": "{\"query\":\"\",\"startTimeMillis\":1567189343813,\"endTimeMillis\":1567192943812,\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"text\",\"operator\":\"CONTAINS\",\"value\":\"ramdisk,inode table,vfat.filesystem.full\"},{\"internalName\":\"appname\",\"operator\":\"CONTAINS\",\"value\":\"hostd*,vpxa,vobd,vmkernel,vmkwarning,sfcb-cimxml-processor,imageconfigmanager,rhttpproxy,vcenter-server\"},{\"internalName\":\"text\",\"operator\":\"CONTAINS\",\"value\":\"full\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[{\"displayName\":\"hostname\",\"internalName\":\"hostname\",\"displayNamespace\":null,\"numericGroupByType\":\"EACH_VALUE\",\"numericGroupByValue\":null}],\"contentPacksToIncludeFields\":[],\"extractedFields\":[]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + },{ + "name":"ESXi: HA isolated events by hostname (!!datacenterName!!)", + "info":"During a health check, HA determined that a host was isolated. Depending on how HA is configured this may mean that VMs have been failed over from the isolated host.", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType": "RATE_BASED", + "hitOperator": "GREATER_THAN", + "hitCount": 0, + "searchPeriod":900000, + "searchInterval":300000, + "chartQuery": "{\"query\":\"isolate?=true\",\"startTimeMillis\":1567192111713,\"endTimeMillis\":1567193011712,\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":false,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"ibadcoc7mnxw2ltwnv3wc4tffz3hg4dimvzgk5tno5pwqyk7mnxw24dpnzsw45a0\",\"operator\":\"CONTAINS\",\"value\":\"clustermanagerimpl\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[{\"displayName\":\"hostname\",\"internalName\":\"hostname\",\"displayNamespace\":null,\"numericGroupByType\":\"EACH_VALUE\",\"numericGroupByValue\":null}],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_ha_component\",\"preContext\":\"(Fdm: \\\\[.*?\\\\] (\\\\[)?)|(Fdm: .*\\\\[)\",\"postContext\":\"::\\\\w+\",\"regexValue\":\"\\\\w+\",\"internalName\":\"ibadcoc7mnxw2ltwnv3wc4tffz3hg4dimvzgk5tno5pwqyk7mnxw24dpnzsw45a0\",\"constraints\":\"{\\\"filters\\\":[{\\\"internalName\\\":\\\"appname\\\",\\\"displayName\\\":\\\"appname\\\",\\\"operator\\\":\\\"CONTAINS\\\",\\\"value\\\":\\\"fdm\\\",\\\"fieldType\\\":\\\"NUMBER\\\",\\\"isExtracted\\\":false,\\\"hidden\\\":false}]}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + },{ + "name":"vCenter Server: HA connection failure detected (!!datacenterName!!)", + "info":"A HA cluster has detected one or more unresponsive ESXi hosts. If the host(s) are marked as dead then VMs running on those hosts will be migrated to other systems. ", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType": "RATE_BASED", + "hitOperator": "GREATER_THAN", + "hitCount": 0, + "searchPeriod":900000, + "searchInterval":300000, + "chartQuery": "{\"query\":\"\",\"startTimeMillis\":1567192173477,\"endTimeMillis\":1567193073476,\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Unique count\",\"value\":\"UCOUNT\",\"requiresField\":true,\"numericOnly\":false}],\"field\":{\"internalName\":\"hostname\",\"displayName\":\"hostname\",\"displayNamespace\":null}}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":false,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Unique count\",\"value\":\"UCOUNT\",\"requiresField\":true,\"numericOnly\":false},\"piqlFunctionField\":\"hostname\",\"fieldConstraints\":[{\"internalName\":\"text\",\"operator\":\"CONTAINS\",\"value\":\"error\"},{\"internalName\":\"text\",\"operator\":\"CONTAINS\",\"value\":\"ClusterSlave::LiveCheck\"},{\"internalName\":\"hostname\",\"operator\":\"EXISTS\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[{\"displayName\":\"hostname\",\"internalName\":\"hostname\",\"displayNamespace\":null,\"numericGroupByType\":\"EACH_VALUE\",\"numericGroupByValue\":null}],\"contentPacksToIncludeFields\":[],\"extractedFields\":[]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + },{ + "name":"Network: ESXi physical NIC down (!!datacenterName!!)", + "info":"ESXi has reported that a physical NIC has become unavailable. Assuming other NICs are still online this indicates a lack of redundancy and a potential performance impact. If all physical NICs for a vSwitch/dvSwitch are unavailable then communication problems to VMs and/or the ESXi host may be possible.", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType": "RATE_BASED", + "hitOperator": "GREATER_THAN", + "hitCount": 0, + "searchPeriod":900000, + "searchInterval":300000, + "chartQuery": "{\"query\":\"\",\"startTimeMillis\":1567192290736,\"endTimeMillis\":1567193190735,\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":false,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"ibadcoc7mnxw2ltwnv3wc4tffz3hg4dimvzgk5tno5pwk43ynfpxm3lonfrq0000\",\"operator\":\"EXISTS\"},{\"internalName\":\"ibadcoc7mnxw2ltwnv3wc4tffz3hg4dimvzgk5tno5pxm33cl5rw63lqn5xgk3tu\",\"operator\":\"CONTAINS\",\"value\":\"netcorrelator\"},{\"internalName\":\"ibadcoc7mnxw2ltwnv3wc4tffz3hg4dimvzgk5tno5pwk43ynfpxa4tpmjwgk3i0\",\"operator\":\"CONTAINS\",\"value\":\"net.redundancy.lost,net.vmnic.linkstate.down\"},{\"internalName\":\"text\",\"operator\":\"CONTAINS\",\"value\":\"Physical NIC\"},{\"internalName\":\"text\",\"operator\":\"CONTAINS\",\"value\":\"is down\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[{\"displayName\":\"hostname\",\"internalName\":\"hostname\",\"displayNamespace\":null,\"numericGroupByType\":\"EACH_VALUE\",\"numericGroupByValue\":null},{\"displayName\":\"vmw_esxi_vmnic\",\"internalName\":\"ibadcoc7mnxw2ltwnv3wc4tffz3hg4dimvzgk5tno5pwk43ynfpxm3lonfrq0000\",\"displayNamespace\":\"VMware - vSphere\",\"numericGroupByType\":\"EACH_VALUE\",\"numericGroupByValue\":null}],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_esxi_problem\",\"preContext\":\"esx\\\\.problem\\\\.\",\"postContext\":\"\",\"regexValue\":\"\\\\w+(\\\\.\\\\w+)*\",\"internalName\":\"ibadcoc7mnxw2ltwnv3wc4tffz3hg4dimvzgk5tno5pwk43ynfpxa4tpmjwgk3i0\",\"constraints\":\"{\\\"filters\\\":[{\\\"internalName\\\":\\\"appname\\\",\\\"displayName\\\":\\\"appname\\\",\\\"operator\\\":\\\"CONTAINS\\\",\\\"value\\\":\\\"vcenter-server,vobd,hostd,vmkwarning,vmkernel\\\",\\\"fieldType\\\":\\\"NUMBER\\\",\\\"isExtracted\\\":false,\\\"hidden\\\":false}]}\"},{\"displayName\":\"vmw_esxi_vmnic\",\"preContext\":\"\",\"postContext\":\"\",\"regexValue\":\"vmnic[0-9]+\",\"internalName\":\"ibadcoc7mnxw2ltwnv3wc4tffz3hg4dimvzgk5tno5pwk43ynfpxm3lonfrq0000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"vmnic*\\\"}\"},{\"displayName\":\"vmw_vob_component\",\"preContext\":\"vobd: \\\\[\",\"postContext\":\"\\\\] [0-9]+us:\",\"regexValue\":\"\\\\w+\",\"internalName\":\"ibadcoc7mnxw2ltwnv3wc4tffz3hg4dimvzgk5tno5pxm33cl5rw63lqn5xgk3tu\",\"constraints\":\"{\\\"filters\\\":[{\\\"internalName\\\":\\\"appname\\\",\\\"displayName\\\":\\\"appname\\\",\\\"operator\\\":\\\"CONTAINS\\\",\\\"value\\\":\\\"vobd\\\",\\\"fieldType\\\":\\\"NUMBER\\\",\\\"isExtracted\\\":false,\\\"hidden\\\":false}]}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + },{ + "name":"Network: ESXi uplink redundancy lost (!!datacenterName!!)", + "info":"Only one physical NIC is currently connected, one more failure will result in a loss of connectivity. 

For more information, please see: Physical Link Down with Loss of Redundancy
", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType": "RATE_BASED", + "hitOperator": "GREATER_THAN", + "hitCount": 0, + "searchPeriod":3600000, + "searchInterval":600000, + "chartQuery": "{\"query\":\"lost redundancy uplink\",\"startTimeMillis\":1567189677912,\"endTimeMillis\":1567193277911,\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":false,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"ibadcoc7mnxw2ltwnv3wc4tffz3hg4dimvzgk5tno5pwk43ynfpxm3lonfrq0000\",\"operator\":\"EXISTS\"},{\"internalName\":\"ibadcoc7mnxw2ltwnv3wc4tffz3hg4dimvzgk5tno5pwk43ynfpxm43xnf2gg2a0\",\"operator\":\"EXISTS\"},{\"internalName\":\"hostname\",\"operator\":\"EXISTS\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[{\"displayName\":\"hostname\",\"internalName\":\"hostname\",\"displayNamespace\":null,\"numericGroupByType\":\"EACH_VALUE\",\"numericGroupByValue\":null},{\"displayName\":\"vmw_esxi_vmnic\",\"internalName\":\"ibadcoc7mnxw2ltwnv3wc4tffz3hg4dimvzgk5tno5pwk43ynfpxm3lonfrq0000\",\"displayNamespace\":\"VMware - vSphere\",\"numericGroupByType\":\"EACH_VALUE\",\"numericGroupByValue\":null},{\"displayName\":\"vmw_esxi_vswitch\",\"internalName\":\"ibadcoc7mnxw2ltwnv3wc4tffz3hg4dimvzgk5tno5pwk43ynfpxm43xnf2gg2a0\",\"displayNamespace\":\"VMware - vSphere\",\"numericGroupByType\":\"EACH_VALUE\",\"numericGroupByValue\":null}],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_esxi_vmnic\",\"preContext\":\"\",\"postContext\":\"\",\"regexValue\":\"vmnic[0-9]+\",\"internalName\":\"ibadcoc7mnxw2ltwnv3wc4tffz3hg4dimvzgk5tno5pwk43ynfpxm3lonfrq0000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"vmnic*\\\"}\"},{\"displayName\":\"vmw_esxi_vswitch\",\"preContext\":\"virtual switch \\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\w+\",\"internalName\":\"ibadcoc7mnxw2ltwnv3wc4tffz3hg4dimvzgk5tno5pwk43ynfpxm43xnf2gg2a0\",\"constraints\":null}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + },{ + "name":"Network: Out of memory (!!datacenterName!!)", + "info":"If the result is dvport related, seeError message is displayed when a large number of dvPorts are in use in VMware ESXi 5.1.x

Otherwise, ESXi 5.0 or later hosts with NetQueue enabled, run out of memory when using jumbo frames (MTU is 9000 bytes). 
The lack of memory for network packets leads to lost virtual machine connectivity and may also lose connection with the vCenter Server. Other symptoms include:

• Network performance of network card is substantially degraded.
• NFS datastores mounted and accessed through this card become unmounted or flap between connected and disconnected state.vMotions time out.
• Restarting host management agents fail to complete when they attempt to re-initialize.

To resolve the out-of-memory issue, increase the size of the network packet buffer pool.

For more information, see:

• Out of memory with enabled NetQueue when using jumbo frames on ESXi 5.1 and later
• Out of heap memory in ESXi 5.0 with NetQueue and Jumbo Frames enabled
", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType": "RATE_BASED", + "hitOperator": "GREATER_THAN", + "hitCount": 0, + "searchPeriod":86400000, + "searchInterval":3600000, + "chartQuery": "{\"query\":\"\",\"startTimeMillis\":1567106939006,\"endTimeMillis\":1567193339005,\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":false,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"text\",\"operator\":\"CONTAINS\",\"value\":\"dvport, bytes for dynamic heap\"},{\"internalName\":\"text\",\"operator\":\"CONTAINS\",\"value\":\"out of memory\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[{\"displayName\":\"hostname\",\"internalName\":\"hostname\",\"displayNamespace\":null,\"numericGroupByType\":\"EACH_VALUE\",\"numericGroupByValue\":null}],\"contentPacksToIncludeFields\":[],\"extractedFields\":[]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + },{ + "name":"*** CRITICAL *** Storage: All Paths Down (APD) (!!datacenterName!!)", + "info":"One or more datastores has experienced an All Paths Down (APD) outage situation. This indicates that one or more datastores is or was unavailable. As a result of this issue, VMs are or were unavailable and ESXi hosts may have been disconnected from vCenter Server. This issue requires immediate attention.

The underlying query groups information by hostname and filesystem to make it clear what hosts and datastores are or were impacted. A query can be done for the filesystem (vmw_esxi_vobd_filesystem_id) to determine which VMs are or were impacted by this outage situation.

For more information, please see: Permanent Device Loss (PDL) and All-Paths-Down (APD) in vSphere 5.x and 6.x
", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType": "RATE_BASED", + "hitOperator": "GREATER_THAN", + "hitCount": 0, + "searchPeriod":900000, + "searchInterval":300000, + "chartQuery": "{\"query\":\"\",\"startTimeMillis\":1567194411094,\"endTimeMillis\":1567195311093,\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Unique count\",\"value\":\"UCOUNT\",\"requiresField\":true,\"numericOnly\":false}],\"field\":{\"internalName\":\"ibadcoc7mnxw2ltwnv3wc4tffz3hg4dimvzgk5tno5pwk43ynfpxm33cmrpwm2lmmvzxs43umvwv62le\",\"displayName\":\"vmw_esxi_vobd_filesystem_id\",\"displayNamespace\":\"VMware - vSphere\"}}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":false,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Unique count\",\"value\":\"UCOUNT\",\"requiresField\":true,\"numericOnly\":false},\"piqlFunctionField\":\"ibadcoc7mnxw2ltwnv3wc4tffz3hg4dimvzgk5tno5pwk43ynfpxm33cmrpwm2lmmvzxs43umvwv62le\",\"fieldConstraints\":[{\"internalName\":\"text\",\"operator\":\"CONTAINS\",\"value\":\"esx.problem.storage.apd.start, esx.problem.storage.apd.timeout\"},{\"internalName\":\"ibadcoc7mnxw2ltwnv3wc4tffz3hg4dimvzgk5tno5pxm33cl5rw63lqn5xgk3tu\",\"operator\":\"CONTAINS\",\"value\":\"apdcorrelator\"},{\"internalName\":\"ibadcoc7mnxw2ltwnv3wc4tffz3hg4dimvzgk5tno5pwk43ynfpxm33cmrpwm2lmmvzxs43umvwv62le\",\"operator\":\"EXISTS\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[{\"displayName\":\"hostname\",\"internalName\":\"hostname\",\"displayNamespace\":null,\"numericGroupByType\":\"EACH_VALUE\",\"numericGroupByValue\":null},{\"displayName\":\"vmw_esxi_vobd_filesystem_id\",\"internalName\":\"ibadcoc7mnxw2ltwnv3wc4tffz3hg4dimvzgk5tno5pwk43ynfpxm33cmrpwm2lmmvzxs43umvwv62le\",\"displayNamespace\":\"VMware - vSphere\",\"numericGroupByType\":\"EACH_VALUE\",\"numericGroupByValue\":null}],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_esxi_vobd_filesystem_id\",\"preContext\":\"Device or filesystem with identifier \\\\[\",\"postContext\":\"\\\\] \",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcoc7mnxw2ltwnv3wc4tffz3hg4dimvzgk5tno5pwk43ynfpxm33cmrpwm2lmmvzxs43umvwv62le\",\"constraints\":\"{\\\"searchTerms\\\":\\\"vobd\\\"}\"},{\"displayName\":\"vmw_vob_component\",\"preContext\":\"vobd: \\\\[\",\"postContext\":\"\\\\] [0-9]+us:\",\"regexValue\":\"\\\\w+\",\"internalName\":\"ibadcoc7mnxw2ltwnv3wc4tffz3hg4dimvzgk5tno5pxm33cl5rw63lqn5xgk3tu\",\"constraints\":\"{\\\"filters\\\":[{\\\"internalName\\\":\\\"appname\\\",\\\"displayName\\\":\\\"appname\\\",\\\"operator\\\":\\\"CONTAINS\\\",\\\"value\\\":\\\"vobd\\\",\\\"fieldType\\\":\\\"NUMBER\\\",\\\"isExtracted\\\":false,\\\"hidden\\\":false}]}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + },{ + "name":"*** CRITICAL *** Storage: VSAN device offline (!!datacenterName!!)", + "info":"A Virtual SAN storage device that backs up the datastores might fail.
This occurs due to a faulty device firmware, physical media, or storage controller or when certain storage devices are not readable or writeable.

Typically, such failures are irreversible. In some instances, permanent data loss might also occur, especially when data is not replicated on other nodes before failure. Virtual SAN automatically recovers data when new devices are added to the storage cluster, unless data lost is permanent.

To avoid permanent loss of data due to device failures, you must set the Number of failures to tolerate policy to greater than zero. For information about setting vSphere admission control policies, see Virtual SAN and Storage Policy-Based Management. Ensure that you have provisioned the hosts with enough disk space to accommodate any additional requirement for replication.

For more information, see: Virtual SAN device encounters a permanent error when devices are not readable or writeable", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType": "RATE_BASED", + "hitOperator": "GREATER_THAN", + "hitCount": 0, + "searchPeriod":900000, + "searchInterval":300000, + "chartQuery": "{\"query\":\"\",\"startTimeMillis\":1567194485669,\"endTimeMillis\":1567195385668,\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":false,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"text\",\"operator\":\"CONTAINS\",\"value\":\"esx.problem.vob.vsan.lsom.diskerror,esx.clear.vob.vsan.pdl.offline\"},{\"internalName\":\"appname\",\"operator\":\"CONTAINS\",\"value\":\"hostd*,vpxa,vobd,vmkernel,vmkwarning,sfcb-cimxml-processor,imageconfigmanager,rhttpproxy,vcenter-server\"},{\"internalName\":\"hostname\",\"operator\":\"EXISTS\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[{\"displayName\":\"hostname\",\"internalName\":\"hostname\",\"displayNamespace\":null,\"numericGroupByType\":\"EACH_VALUE\",\"numericGroupByValue\":null}],\"contentPacksToIncludeFields\":[],\"extractedFields\":[]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + },{ + "name":"Storage: NFS connectivity issue (!!datacenterName!!)", + "info":"The purpose of this alert is to notify when an NFS connectivity issue was detected. This means an NFS datastore is or was unavailable. Due to this issue, one or more VMs may be unavailable.

For more information, please see:

• Understanding the messages: Connectivity to NFS Server Lost and Connectivity to NFS Server Restored
• Connectivity to the NFS server is lost
• Connectivity to NFS Server Lost and Connectivity to NFS Server Restored
• NFS connectivity issues on NetApp NFS filers on ESXi 5.x
", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType": "RATE_BASED", + "hitOperator": "GREATER_THAN", + "hitCount": 0, + "searchPeriod":300000, + "searchInterval":60000, + "chartQuery": "{\"query\":\"\",\"startTimeMillis\":1567195155827,\"endTimeMillis\":1567195455826,\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"appname\",\"operator\":\"CONTAINS\",\"value\":\"vpxa, vobd, vmkernel, vmkwarning\"},{\"internalName\":\"text\",\"operator\":\"CONTAINS\",\"value\":\"esx.problem.vmfs.nfs.server.disconnect,Lost connection to the server\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[{\"displayName\":\"hostname\",\"internalName\":\"hostname\",\"displayNamespace\":null,\"numericGroupByType\":\"EACH_VALUE\",\"numericGroupByValue\":null}],\"contentPacksToIncludeFields\":[],\"extractedFields\":[]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + },{ + "name":"Storage: NFS lock file issue (!!datacenterName!!)", + "info":"The purpose of this alert is to notify when an NFS lock file issue has been detected. Stale NFS lock files can prevent VMs from powering on.

For more information, please see: Cannot power on a virtual machine located in an NFS datastore
", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType": "RATE_BASED", + "hitOperator": "GREATER_THAN", + "hitCount": 0, + "searchPeriod":3600000, + "searchInterval":600000, + "chartQuery": "{\"query\":\"nfslock failed\",\"startTimeMillis\":1567191915987,\"endTimeMillis\":1567195515986,\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"appname\",\"operator\":\"CONTAINS\",\"value\":\"vpxa, vobd, vmkernel, vmkwarning\"},{\"internalName\":\"hostname\",\"operator\":\"EXISTS\"},{\"internalName\":\"text\",\"operator\":\"DOES_NOT_CONTAIN\",\"value\":\"failed to get lock on file slotsfile\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[{\"displayName\":\"hostname\",\"internalName\":\"hostname\",\"displayNamespace\":null,\"numericGroupByType\":\"EACH_VALUE\",\"numericGroupByValue\":null}],\"contentPacksToIncludeFields\":[],\"extractedFields\":[]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + },{ + "name":"Storage: SCSI path dead (!!datacenterName!!)", + "info":"The purpose of this alert is to notify when a SCSI path has become unavailable. Assuming multiple paths are in use and the other paths are online this means reduced redundancy and performance. If all paths to a storage device become unavailable then VMs running on the storage device will become unavailable.", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType": "RATE_BASED", + "hitOperator": "GREATER_THAN", + "hitCount": 0, + "searchPeriod":300000, + "searchInterval":60000, + "chartQuery": "{\"query\":\"\",\"startTimeMillis\":1567195272180,\"endTimeMillis\":1567195572179,\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"appname\",\"operator\":\"CONTAINS\",\"value\":\"vobd\"},{\"internalName\":\"ibadcoc7mnxw2ltwnv3wc4tffz3hg4dimvzgk5tno5pxm33cl5rw63lqn5xgk3tu\",\"operator\":\"CONTAINS\",\"value\":\"scsicorrelator\"},{\"internalName\":\"ibadcoc7mnxw2ltwnv3wc4tffz3hg4dimvzgk5tno5pxgy3tnfpxaylunbpxg5dborsq0000\",\"operator\":\"CONTAINS\",\"value\":\"dead\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[{\"displayName\":\"hostname\",\"internalName\":\"hostname\",\"displayNamespace\":null,\"numericGroupByType\":\"EACH_VALUE\",\"numericGroupByValue\":null}],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_scsi_path_state\",\"preContext\":\"\\\\[vob\\\\.scsi\\\\.scsipath\\\\.pathstate\\\\.\",\"postContext\":\"\\\\]\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcoc7mnxw2ltwnv3wc4tffz3hg4dimvzgk5tno5pxgy3tnfpxaylunbpxg5dborsq0000\",\"constraints\":\"{\\\"filters\\\":[{\\\"internalName\\\":\\\"appname\\\",\\\"displayName\\\":\\\"appname\\\",\\\"operator\\\":\\\"CONTAINS\\\",\\\"value\\\":\\\"vobd\\\",\\\"fieldType\\\":\\\"NUMBER\\\",\\\"isExtracted\\\":false,\\\"hidden\\\":false}]}\"},{\"displayName\":\"vmw_vob_component\",\"preContext\":\"vobd: \\\\[\",\"postContext\":\"\\\\] [0-9]+us:\",\"regexValue\":\"\\\\w+\",\"internalName\":\"ibadcoc7mnxw2ltwnv3wc4tffz3hg4dimvzgk5tno5pxm33cl5rw63lqn5xgk3tu\",\"constraints\":\"{\\\"filters\\\":[{\\\"internalName\\\":\\\"appname\\\",\\\"displayName\\\":\\\"appname\\\",\\\"operator\\\":\\\"CONTAINS\\\",\\\"value\\\":\\\"vobd\\\",\\\"fieldType\\\":\\\"NUMBER\\\",\\\"isExtracted\\\":false,\\\"hidden\\\":false}]}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + },{ + "name":"Storage: Snapshot consolidation required (!!datacenterName!!)", + "info":"The purpose of this alert is to notify when a snapshot consolidation is required. A failed snapshot consolidation operation that is not manually addressed can lead to a full datastore. For more information, please see: Consolidating snapshots in vSphere 5.x", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType": "RATE_BASED", + "hitOperator": "GREATER_THAN", + "hitCount": 0, + "searchPeriod":21600000, + "searchInterval":3600000, + "chartQuery": "{\"query\":\"\",\"startTimeMillis\":1567174024701,\"endTimeMillis\":1567195624700,\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"appname\",\"operator\":\"CONTAINS\",\"value\":\"hostd\"},{\"internalName\":\"text\",\"operator\":\"DOES_NOT_CONTAIN\",\"value\":\"\\\"needConsolidate is false\\\"\"},{\"internalName\":\"text\",\"operator\":\"CONTAINS\",\"value\":\"snapshot needconsolidate\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[{\"displayName\":\"hostname\",\"internalName\":\"hostname\",\"displayNamespace\":null,\"numericGroupByType\":\"EACH_VALUE\",\"numericGroupByValue\":null}],\"contentPacksToIncludeFields\":[],\"extractedFields\":[]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + },{ + "name":"vSAN - SSD health change to unhealthy state (!!datacenterName!!)", + "info":"This alert will fire when the state of any SSD changes to unhealthy. The reason could be either because of permanent disk failure, disk decommissioning, node shutdown, etc. ", "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType": "RATE_BASED", + "hitOperator": "GREATER_THAN", + "hitCount": 0, + "searchPeriod":300000, + "searchInterval":60000, + "chartQuery": "{\"query\":\"\",\"startTimeMillis\":1567195784806,\"endTimeMillis\":1567196084805,\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"text\",\"operator\":\"CONTAINS\",\"value\":\"DOMTraceLeafSSDHealthChangeCb\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffz3hgyloozwxox3wonqw4x3tonsf62dfmfwhi2c7mzwgcz3t\",\"operator\":\"NOT_EQUAL\",\"value\":\"0x0\"},{\"internalName\":\"hostname\",\"operator\":\"EXISTS\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffz3hgyloozwxox3wonqw4x3tonsf65lvnfsf62dfmfwhi2c7mnugc3thmu000000\",\"operator\":\"EXISTS\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[{\"displayName\":\"hostname\",\"internalName\":\"hostname\",\"displayNamespace\":null,\"numericGroupByType\":\"EACH_VALUE\",\"numericGroupByValue\":null},{\"displayName\":\"vmw_vsan_ssd_uuid_health_change\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffz3hgyloozwxox3wonqw4x3tonsf65lvnfsf62dfmfwhi2c7mnugc3thmu000000\",\"displayNamespace\":\"VMware - VSAN\",\"numericGroupByType\":\"EACH_VALUE\",\"numericGroupByValue\":null}],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_vsan_ssd_health_flags\",\"preContext\":\"healthFlags': \",\"postContext\":\"\\\\}\",\"regexValue\":\"\\\\w+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffz3hgyloozwxox3wonqw4x3tonsf62dfmfwhi2c7mzwgcz3t\",\"constraints\":\"{\\\"searchTerms\\\":\\\"ssdUUID\\\"}\"},{\"displayName\":\"vmw_vsan_ssd_uuid_health_change\",\"preContext\":\"ssdUUID': '\",\"postContext\":\"'\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffz3hgyloozwxox3wonqw4x3tonsf65lvnfsf62dfmfwhi2c7mnugc3thmu000000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"healthFlags\\\"}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + },{ + "name":"vSAN - Configuration failure - Insufficient space (!!datacenterName!!)", + "info":"This alert indicates that we cannot create a configuration for a new object(VM) in the vSAN cluster because sufficient space is not available in the cluster. If we see this error, please check the error logs and try the provisioning operation after adding new hosts/disks.
", "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType": "RATE_BASED", + "hitOperator": "GREATER_THAN", + "hitCount": 0, + "searchPeriod":300000, + "searchInterval":60000, + "chartQuery": "{\"query\":\"\",\"startTimeMillis\":1567195840224,\"endTimeMillis\":1567196140223,\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"text\",\"operator\":\"CONTAINS\",\"value\":\"Not enough space available. Available:\"},{\"internalName\":\"appname\",\"operator\":\"CONTAINS\",\"value\":\"clomd\"},{\"internalName\":\"hostname\",\"operator\":\"EXISTS\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[{\"displayName\":\"hostname\",\"internalName\":\"hostname\",\"displayNamespace\":null,\"numericGroupByType\":\"EACH_VALUE\",\"numericGroupByValue\":null}],\"contentPacksToIncludeFields\":[],\"extractedFields\":[]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + },{ + "name":"*** CRITICAL *** Storage: VSAN device offline (!!datacenterName!!)", + "info":"A Virtual SAN storage device that backs up the datastores might fail.
This occurs due to a faulty device firmware, physical media, or storage controller or when certain storage devices are not readable or writeable.

Typically, such failures are irreversible. In some instances, permanent data loss might also occur, especially when data is not replicated on other nodes before failure. Virtual SAN automatically recovers data when new devices are added to the storage cluster, unless data lost is permanent.

To avoid permanent loss of data due to device failures, you must set the Number of failures to tolerate policy to greater than zero. For information about setting vSphere admission control policies, see Virtual SAN and Storage Policy-Based Management. Ensure that you have provisioned the hosts with enough disk space to accommodate any additional requirement for replication.

For more information, see: Virtual SAN device encounters a permanent error when devices are not readable or writeable", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType": "RATE_BASED", + "hitOperator": "GREATER_THAN", + "hitCount": 0, + "searchPeriod":300000, + "searchInterval":60000, + "chartQuery": "{\"query\":\"has gone offline\",\"startTimeMillis\":1567195898924,\"endTimeMillis\":1567196198923,\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"text\",\"operator\":\"CONTAINS\",\"value\":\"has gone offline\"},{\"internalName\":\"text\",\"operator\":\"MATCH\",\"value\":\"(v|Virtual )SAN device\"},{\"internalName\":\"appname\",\"operator\":\"CONTAINS\",\"value\":\"vmkernel\"},{\"internalName\":\"hostname\",\"operator\":\"EXISTS\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffz3hgyloozwxox3wonqw4x3pmztgy2lomvpwi2ltnnpxk5ljmq000000\",\"operator\":\"EXISTS\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[{\"displayName\":\"hostname\",\"internalName\":\"hostname\",\"displayNamespace\":null,\"numericGroupByType\":\"EACH_VALUE\",\"numericGroupByValue\":null},{\"displayName\":\"vmw_vsan_offline_disk_uuid\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffz3hgyloozwxox3wonqw4x3pmztgy2lomvpwi2ltnnpxk5ljmq000000\",\"displayNamespace\":\"VMware - VSAN\",\"numericGroupByType\":\"EACH_VALUE\",\"numericGroupByValue\":null}],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_vsan_offline_disk_uuid\",\"preContext\":\"(v|Virtual )SAN device \",\"postContext\":\" has gone offline\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffz3hgyloozwxox3wonqw4x3pmztgy2lomvpwi2ltnnpxk5ljmq000000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"LSOM\\\"}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + },{ + "name":"vSAN - Object component state changed to degraded (!!datacenterName!!)", + "info":"This alert will be triggered when vSAN object state changes to degraded state.Check the state of the adapters, disks and network settings associated with the vSAN cluster.

", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType": "RATE_BASED", + "hitOperator": "GREATER_THAN", + "hitCount": 0, + "searchPeriod":300000, + "searchInterval":60000, + "chartQuery": "{\"query\":\"\",\"startTimeMillis\":1567195960958,\"endTimeMillis\":1567196260957,\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"text\",\"operator\":\"CONTAINS\",\"value\":\"DOMTraceLeafObjectStateChange\"},{\"internalName\":\"text\",\"operator\":\"CONTAINS\",\"value\":\"newCompState,newLeafObjState\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffz3hgyloozwxox3wonqw4x3en5wv63tfo5pwg33nobxw4zloorpxg5dborsq0000\",\"operator\":\"CONTAINS\",\"value\":\"degraded\"},{\"internalName\":\"hostname\",\"operator\":\"EXISTS\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[{\"displayName\":\"hostname\",\"internalName\":\"hostname\",\"displayNamespace\":null,\"numericGroupByType\":\"EACH_VALUE\",\"numericGroupByValue\":null}],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_vsan_dom_new_component_state\",\"preContext\":\"newCompState': '\",\"postContext\":\"'\",\"regexValue\":\"\\\\w+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffz3hgyloozwxox3wonqw4x3en5wv63tfo5pwg33nobxw4zloorpxg5dborsq0000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"LEAF\\\"}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + },{ + "name":"NSX-T - SysCpuUsage (!!datacenterName!!)", + "info":"CPU usage is above 95% for more than 10 minutes.", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType":"RATE_BASED", + "hitOperator":"GREATER_THAN", + "hitCount":2.0, + "searchPeriod":660000, + "searchInterval":60000, + "chartQuery": "{\"query\":\"\",\"startTimeMillis\":1641908646169,\"endTimeMillis\":1641908946169,\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45djmq000000\",\"operator\":\"CONTAINS\",\"value\":\"vmwNSXPlatformSysCpuUsage\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45c7on2gc5df\",\"operator\":\"MATCH\",\"value\":\"^9[5-9]|100$\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_nsxt_event_state\",\"preContext\":\"\\\"event_state\\\":\\\\s?\",\"postContext\":\"(?:,|})\",\"regexValue\":\"\\\\S+?\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45c7on2gc5df\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp subcomp NSX\\\"}\"},{\"displayName\":\"vmw_nsxt_eventid\",\"preContext\":\"eventId=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45djmq000000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp subcomp NSX\\\"}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + },{ + "name":"NSX-T - SysMemUsage (!!datacenterName!!)", + "info":"Memory usage is above 95% for more than 10 minutes.", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType":"RATE_BASED", + "hitOperator":"GREATER_THAN", + "hitCount":2.0, + "searchPeriod":660000, + "searchInterval":60000, + "chartQuery": "{\"query\":\"\",\"startTimeMillis\":1641909320086,\"endTimeMillis\":1641909620086,\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45djmq000000\",\"operator\":\"CONTAINS\",\"value\":\"vmwNSXPlatformSysMemUsage\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45c7on2gc5df\",\"operator\":\"MATCH\",\"value\":\"^9[5-9]|100$\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_nsxt_event_state\",\"preContext\":\"\\\"event_state\\\":\\\\s?\",\"postContext\":\"(?:,|})\",\"regexValue\":\"\\\\S+?\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45c7on2gc5df\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp subcomp NSX\\\"}\"},{\"displayName\":\"vmw_nsxt_eventid\",\"preContext\":\"eventId=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45djmq000000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp subcomp NSX\\\"}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + },{ + "name":"NSX-T - SysDiskUsage (!!datacenterName!!)", + "info":"Disk usage for one or more partitions is above 89% for more than 10 minutes.", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType":"RATE_BASED", + "hitOperator":"GREATER_THAN", + "hitCount":2.0, + "searchPeriod":660000, + "searchInterval":60000, + "chartQuery":"{\"query\":\"\",\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45djmq000000\",\"operator\":\"CONTAINS\",\"value\":\"vmwNSXPlatformSysTmpDiskUsage,vmwNSXPlatformSysRootDiskUsage,vmwNSXPlatformSysDiskUsage,vmwNSXPlatformSysImageDiskUsage,vmwNSXPlatformSysConfigDiskUsage,vmwNSXPlatformSysRepositoryDiskUsage,vmwNSXPlatformSysVarDumpDiskUsage\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45c7on2gc5df\",\"operator\":\"MATCH\",\"value\":\"^9[0-9]|100$\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_nsxt_event_state\",\"preContext\":\"\\\"event_state\\\":\\\\s?\",\"postContext\":\"(?:,|})\",\"regexValue\":\"\\\\S+?\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45c7on2gc5df\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp subcomp NSX\\\"}\"},{\"displayName\":\"vmw_nsxt_eventid\",\"preContext\":\"eventId=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45djmq000000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp subcomp NSX\\\"}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + },{ + "name":"NSX-T - PasswordExpiry (!!datacenterName!!)", + "info":"Password for appliance user account is about to expire or expired.", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType":"RATE_BASED", + "hitOperator":"GREATER_THAN", + "hitCount":0.0, + "searchPeriod":660000, + "searchInterval":60000, + "chartQuery":"{\"query\":\"\",\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45djmq000000\",\"operator\":\"CONTAINS\",\"value\":\"vmwNSXPlatformPasswordExpiryStatus\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45c7on2gc5df\",\"operator\":\"MATCH\",\"value\":\"^[12]?[0-9]|-\\\\d+$\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_nsxt_event_state\",\"preContext\":\"\\\"event_state\\\":\\\\s?\",\"postContext\":\"(?:,|})\",\"regexValue\":\"\\\\S+?\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45c7on2gc5df\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp subcomp NSX\\\"}\"},{\"displayName\":\"vmw_nsxt_eventid\",\"preContext\":\"eventId=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45djmq000000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp subcomp NSX\\\"}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + }, { + "name":"NSX-T - CertificateExpiry (!!datacenterName!!)", + "info":"One or more CA signed certificate is expired.", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType":"RATE_BASED", + "hitOperator":"GREATER_THAN", + "hitCount":0.0, + "searchPeriod":660000, + "searchInterval":60000, + "chartQuery":"{\"query\":\"\",\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45djmq000000\",\"operator\":\"CONTAINS\",\"value\":\"vmwNSXPlatformCertificateExpiryStatus\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45c7on2gc5df\",\"operator\":\"MATCH\",\"value\":\"^[12]?[0-9]|-\\\\d+$\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_nsxt_event_state\",\"preContext\":\"\\\"event_state\\\":\\\\s?\",\"postContext\":\"(?:,|})\",\"regexValue\":\"\\\\S+?\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45c7on2gc5df\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp subcomp NSX\\\"}\"},{\"displayName\":\"vmw_nsxt_eventid\",\"preContext\":\"eventId=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45djmq000000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp subcomp NSX\\\"}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + }, { + "name":"NSX-T - ClusterNodeStatus (!!datacenterName!!)", + "info":"Local edge cluster node is down.", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType":"RATE_BASED", + "hitOperator":"GREATER_THAN", + "hitCount":0.0, + "searchPeriod":660000, + "searchInterval":60000, + "chartQuery":"{\"query\":\"\",\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45djmq000000\",\"operator\":\"CONTAINS\",\"value\":\"vmwNSXClusterNodeStatus\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45c7on2gc5df\",\"operator\":\"MATCH\",\"value\":\"^[3-9]|\\\\d{2,}$\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_nsxt_event_state\",\"preContext\":\"\\\"event_state\\\":\\\\s?\",\"postContext\":\"(?:,|})\",\"regexValue\":\"\\\\S+?\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45c7on2gc5df\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp subcomp NSX\\\"}\"},{\"displayName\":\"vmw_nsxt_eventid\",\"preContext\":\"eventId=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45djmq000000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp subcomp NSX\\\"}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + }, { + "name":"NSX-T - BackupFailure (!!datacenterName!!)", + "info":"NSX scheduled backup operation failed.", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType":"RATE_BASED", + "hitOperator":"GREATER_THAN", + "hitCount":0.0, + "searchPeriod":660000, + "searchInterval":60000, + "chartQuery":"{\"query\":\"Cluster backup failed\",\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":false,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3dn5wxa000\",\"operator\":\"CONTAINS\",\"value\":\"nsx-manager\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3tovrgg33noa000000\",\"operator\":\"CONTAINS\",\"value\":\"manager\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3tgjrw63lq\",\"operator\":\"CONTAINS\",\"value\":\"backup-restore\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_nsxt_comp\",\"preContext\":\"comp=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3dn5wxa000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"subcomp\\\"}\"},{\"displayName\":\"vmw_nsxt_s2comp\",\"preContext\":\"s2comp=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3tgjrw63lq\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp subcomp\\\"}\"},{\"displayName\":\"vmw_nsxt_subcomp\",\"preContext\":\"subcomp=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3tovrgg33noa000000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp\\\"}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + }, { + "name":"NSX-T - VipLeadership (!!datacenterName!!)", + "info":"NSX Management cluster VIP is down.", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType":"RATE_BASED", + "hitOperator":"GREATER_THAN", + "hitCount":0.0, + "searchPeriod":660000, + "searchInterval":60000, + "chartQuery":"{\"query\":\"\",\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3dn5wxa000\",\"operator\":\"CONTAINS\",\"value\":\"nsx-manager\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3tovrgg33noa000000\",\"operator\":\"CONTAINS\",\"value\":\"http\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fojzg64s7mnxwizi0\",\"operator\":\"CONTAINS\",\"value\":\"MP60401\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_nsxt_comp\",\"preContext\":\"comp=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3dn5wxa000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"subcomp\\\"}\"},{\"displayName\":\"vmw_nsxt_error_code\",\"preContext\":\"errorCode=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fojzg64s7mnxwizi0\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp subcomp\\\"}\"},{\"displayName\":\"vmw_nsxt_subcomp\",\"preContext\":\"subcomp=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3tovrgg33noa000000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp\\\"}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + }, { + "name":"NSX-T - ApiRateLimit (!!datacenterName!!)", + "info":"Client API reached 80% of the configured threshold.", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType":"RATE_BASED", + "hitOperator":"GREATER_THAN", + "hitCount":0.0, + "searchPeriod":660000, + "searchInterval":60000, + "chartQuery":"{\"query\":\"\",\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3dn5wxa000\",\"operator\":\"CONTAINS\",\"value\":\"nsx-manager\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3tovrgg33noa000000\",\"operator\":\"CONTAINS\",\"value\":\"http\"},{\"internalName\":\"text\",\"operator\":\"CONTAINS\",\"value\":\"New maximum of client API rate has exceeded 80% of the allowed limit.\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_nsxt_comp\",\"preContext\":\"comp=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3dn5wxa000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"subcomp\\\"}\"},{\"displayName\":\"vmw_nsxt_subcomp\",\"preContext\":\"subcomp=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3tovrgg33noa000000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp\\\"}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + }, { + "name":"NSX-T - CorfuQuorumLost (!!datacenterName!!)", + "info":"Two nodes went down in the cluster and lost corfu quorum.", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType":"RATE_BASED", + "hitOperator":"GREATER_THAN", + "hitCount":0.0, + "searchPeriod":660000, + "searchInterval":60000, + "chartQuery":"{\"query\":\"\",\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3dn5wxa000\",\"operator\":\"CONTAINS\",\"value\":\"cluster-boot-manager\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3tovrgg33noa000000\",\"operator\":\"CONTAINS\",\"value\":\"step\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fojzg64s7mnxwizi0\",\"operator\":\"CONTAINS\",\"value\":\"CBM38\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_nsxt_comp\",\"preContext\":\"comp=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3dn5wxa000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"subcomp\\\"}\"},{\"displayName\":\"vmw_nsxt_error_code\",\"preContext\":\"errorCode=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fojzg64s7mnxwizi0\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp subcomp\\\"}\"},{\"displayName\":\"vmw_nsxt_subcomp\",\"preContext\":\"subcomp=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3tovrgg33noa000000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp\\\"}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + }, { + "name":"NSX-T - DfwHeapMem (!!datacenterName!!)", + "info":"DFW heap memory exceeded configured threshold.", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType":"RATE_BASED", + "hitOperator":"GREATER_THAN", + "hitCount":0.0, + "searchPeriod":660000, + "searchInterval":60000, + "chartQuery":"{\"query\":\"\",\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3dn5wxa000\",\"operator\":\"CONTAINS\",\"value\":\"nsx-esx\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3tovrgg33noa000000\",\"operator\":\"CONTAINS\",\"value\":\"agg-service\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fojzg64s7mnxwizi0\",\"operator\":\"CONTAINS\",\"value\":\"MPA11015\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_nsxt_comp\",\"preContext\":\"comp=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3dn5wxa000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"subcomp\\\"}\"},{\"displayName\":\"vmw_nsxt_error_code\",\"preContext\":\"errorCode=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fojzg64s7mnxwizi0\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp subcomp\\\"}\"},{\"displayName\":\"vmw_nsxt_subcomp\",\"preContext\":\"subcomp=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3tovrgg33noa000000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp\\\"}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + }, { + "name":"NSX-T - ProcessStatus (!!datacenterName!!)", + "info":"Critical process status changed.", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType":"RATE_BASED", + "hitOperator":"GREATER_THAN", + "hitCount":0.0, + "searchPeriod":660000, + "searchInterval":60000, + "chartQuery":"{\"query\":\"\",\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45djmq000000\",\"operator\":\"CONTAINS\",\"value\":\"vmwNSXProcessStatus\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_nsxt_eventid\",\"preContext\":\"eventId=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45djmq000000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp subcomp NSX\\\"}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + }, { + "name":"NSX-T - ClusterFailoverStatus (!!datacenterName!!)", + "info":"SR high availability state changed or active/standby services failover.", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType":"RATE_BASED", + "hitOperator":"GREATER_THAN", + "hitCount":0.0, + "searchPeriod":660000, + "searchInterval":60000, + "chartQuery":"{\"query\":\"\",\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45djmq000000\",\"operator\":\"CONTAINS\",\"value\":\"vmwNSXClusterFailoverStatus\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45c7on2gc5df\",\"operator\":\"MATCH\",\"value\":\"^[1-9]|\\\\d{2,}$\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_nsxt_event_state\",\"preContext\":\"\\\"event_state\\\":\\\\s?\",\"postContext\":\"(?:,|})\",\"regexValue\":\"\\\\S+?\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45c7on2gc5df\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp subcomp NSX\\\"}\"},{\"displayName\":\"vmw_nsxt_eventid\",\"preContext\":\"eventId=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45djmq000000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp subcomp NSX\\\"}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + }, { + "name":"NSX-T - BfdTunnelStatus (!!datacenterName!!)", + "info":"BFD Tunnel status changed.", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType":"RATE_BASED", + "hitOperator":"GREATER_THAN", + "hitCount":0.0, + "searchPeriod":660000, + "searchInterval":60000, + "chartQuery":"{\"query\":\"\",\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45djmq000000\",\"operator\":\"CONTAINS\",\"value\":\"vmwNSXBfdTunnelStatus\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45c7on2gc5df\",\"operator\":\"MATCH\",\"value\":\"^[3-9]|\\\\d{2,}$\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_nsxt_event_state\",\"preContext\":\"\\\"event_state\\\":\\\\s?\",\"postContext\":\"(?:,|})\",\"regexValue\":\"\\\\S+?\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45c7on2gc5df\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp subcomp NSX\\\"}\"},{\"displayName\":\"vmw_nsxt_eventid\",\"preContext\":\"eventId=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45djmq000000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp subcomp NSX\\\"}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + }, { + "name":"NSX-T - RoutingBgpNeighborStatus (!!datacenterName!!)", + "info":"BGP neighbor status is down.", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType":"RATE_BASED", + "hitOperator":"GREATER_THAN", + "hitCount":0.0, + "searchPeriod":660000, + "searchInterval":60000, + "chartQuery":"{\"query\":\"\",\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45djmq000000\",\"operator\":\"CONTAINS\",\"value\":\"vmwNSXRoutingBgpNeighborStatus\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45c7on2gc5df\",\"operator\":\"MATCH\",\"value\":\"^0$\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_nsxt_event_state\",\"preContext\":\"\\\"event_state\\\":\\\\s?\",\"postContext\":\"(?:,|})\",\"regexValue\":\"\\\\S+?\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45c7on2gc5df\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp subcomp NSX\\\"}\"},{\"displayName\":\"vmw_nsxt_eventid\",\"preContext\":\"eventId=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45djmq000000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp subcomp NSX\\\"}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + }, { + "name":"NSX-T - RoutingStatus (!!datacenterName!!)", + "info":"Routing(BGP/BFD) is down.", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType":"RATE_BASED", + "hitOperator":"GREATER_THAN", + "hitCount":0.0, + "searchPeriod":660000, + "searchInterval":60000, + "chartQuery":"{\"query\":\"\",\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45djmq000000\",\"operator\":\"CONTAINS\",\"value\":\"vmwNSXRoutingStatus\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45c7on2gc5df\",\"operator\":\"MATCH\",\"value\":\"^0$\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_nsxt_event_state\",\"preContext\":\"\\\"event_state\\\":\\\\s?\",\"postContext\":\"(?:,|})\",\"regexValue\":\"\\\\S+?\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45c7on2gc5df\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp subcomp NSX\\\"}\"},{\"displayName\":\"vmw_nsxt_eventid\",\"preContext\":\"eventId=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fozsw45djmq000000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp subcomp NSX\\\"}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + }, { + "name":"NSX-T - TnConnDown_15min (!!datacenterName!!)", + "info":"Transport Node connection to a controller/Manager is down for at least 15 minutes.", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType":"NEW_EVENT_TYPE", + "hitOperator":"GREATER_THAN", + "hitCount":0.0, + "searchPeriod":660000, + "searchInterval":60000, + "chartQuery":"{\"query\":\"\",\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3dn5wxa000\",\"operator\":\"CONTAINS\",\"value\":\"nsx-esx,nsx-edge,nsx-kvm\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3tovrgg33noa000000\",\"operator\":\"CONTAINS\",\"value\":\"mpa,nsx-proxy\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fojzg64s7mnxwizi0\",\"operator\":\"CONTAINS\",\"value\":\"MPA1009,MPA1011,PRX0803,PRX0105,PRX0805\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_nsxt_comp\",\"preContext\":\"comp=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3dn5wxa000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"subcomp\\\"}\"},{\"displayName\":\"vmw_nsxt_error_code\",\"preContext\":\"errorCode=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fojzg64s7mnxwizi0\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp subcomp\\\"}\"},{\"displayName\":\"vmw_nsxt_subcomp\",\"preContext\":\"subcomp=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3tovrgg33noa000000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp\\\"}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + }, { + "name":"NSX-T - TnConnDown_5min (!!datacenterName!!)", + "info":"Transport Node connection to controller/Manager is down for at least 5 minutes.", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType":"NEW_EVENT_TYPE", + "hitOperator":"GREATER_THAN", + "hitCount":0.0, + "searchPeriod":660000, + "searchInterval":60000, + "chartQuery":"{\"query\":\"\",\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3dn5wxa000\",\"operator\":\"CONTAINS\",\"value\":\"nsx-esx,nsx-edge,nsx-kvm\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3tovrgg33noa000000\",\"operator\":\"CONTAINS\",\"value\":\"mpa,nsx-proxy\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fojzg64s7mnxwizi0\",\"operator\":\"CONTAINS\",\"value\":\"MPA1009,MPA1011,PRX0803,PRX0105,PRX0805\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_nsxt_comp\",\"preContext\":\"comp=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3dn5wxa000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"subcomp\\\"}\"},{\"displayName\":\"vmw_nsxt_error_code\",\"preContext\":\"errorCode=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fojzg64s7mnxwizi0\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp subcomp\\\"}\"},{\"displayName\":\"vmw_nsxt_subcomp\",\"preContext\":\"subcomp=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3tovrgg33noa000000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp\\\"}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + }, { + "name":"NSX-T - ServiceDown (!!datacenterName!!)", + "info":"One or more services are down.", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType":"RATE_BASED", + "hitOperator":"GREATER_THAN", + "hitCount":0.0, + "searchPeriod":660000, + "searchInterval":60000, + "chartQuery":"{\"query\":\"\",\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3dn5wxa000\",\"operator\":\"CONTAINS\",\"value\":\"heartbeatservice-server\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3tovrgg33noa000000\",\"operator\":\"CONTAINS\",\"value\":\"ServiceMonitor\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fojzg64s7mnxwizi0\",\"operator\":\"CONTAINS\",\"value\":\"HBS153\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_nsxt_comp\",\"preContext\":\"comp=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3dn5wxa000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"subcomp\\\"}\"},{\"displayName\":\"vmw_nsxt_error_code\",\"preContext\":\"errorCode=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fojzg64s7mnxwizi0\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp subcomp\\\"}\"},{\"displayName\":\"vmw_nsxt_subcomp\",\"preContext\":\"subcomp=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3tovrgg33noa000000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp\\\"}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + }, { + "name":"NSX-T - IpNotAvailableInPool (!!datacenterName!!)", + "info":"There is no IP available in the Pool or reaches configured threshold.", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType":"RATE_BASED", + "hitOperator":"GREATER_THAN", + "hitCount":0.0, + "searchPeriod":660000, + "searchInterval":60000, + "chartQuery":"{\"query\":\"\",\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3dn5wxa000\",\"operator\":\"CONTAINS\",\"value\":\"nsx-manager\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3tovrgg33noa000000\",\"operator\":\"CONTAINS\",\"value\":\"manager\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fojzg64s7mnxwizi0\",\"operator\":\"CONTAINS\",\"value\":\"MP5137,MP5109\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_nsxt_comp\",\"preContext\":\"comp=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3dn5wxa000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"subcomp\\\"}\"},{\"displayName\":\"vmw_nsxt_error_code\",\"preContext\":\"errorCode=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fojzg64s7mnxwizi0\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp subcomp\\\"}\"},{\"displayName\":\"vmw_nsxt_subcomp\",\"preContext\":\"subcomp=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3tovrgg33noa000000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp\\\"}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + }, { + "name":"NSX-T - LoadBalancerError (!!datacenterName!!)", + "info":"NSX Load Balancer Service status is ERROR.", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType":"RATE_BASED", + "hitOperator":"GREATER_THAN", + "hitCount":0.0, + "searchPeriod":660000, + "searchInterval":60000, + "chartQuery":"{\"query\":\"\",\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3dn5wxa000\",\"operator\":\"CONTAINS\",\"value\":\"nsx-manager\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3tovrgg33noa000000\",\"operator\":\"CONTAINS\",\"value\":\"manager\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fojzg64s7mnxwizi0\",\"operator\":\"CONTAINS\",\"value\":\"MP7505\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_nsxt_comp\",\"preContext\":\"comp=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3dn5wxa000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"subcomp\\\"}\"},{\"displayName\":\"vmw_nsxt_error_code\",\"preContext\":\"errorCode=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fojzg64s7mnxwizi0\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp subcomp\\\"}\"},{\"displayName\":\"vmw_nsxt_subcomp\",\"preContext\":\"subcomp=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3tovrgg33noa000000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp\\\"}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + }, { + "name":"NSX-T - LoadBalancerDown (!!datacenterName!!)", + "info":"NSX Load Balancer Service status is DOWN.", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType":"RATE_BASED", + "hitOperator":"GREATER_THAN", + "hitCount":0.0, + "searchPeriod":660000, + "searchInterval":60000, + "chartQuery":"{\"query\":\"\",\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3dn5wxa000\",\"operator\":\"CONTAINS\",\"value\":\"nsx-manager\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3tovrgg33noa000000\",\"operator\":\"CONTAINS\",\"value\":\"manager\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fojzg64s7mnxwizi0\",\"operator\":\"CONTAINS\",\"value\":\"MP7506\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_nsxt_comp\",\"preContext\":\"comp=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3dn5wxa000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"subcomp\\\"}\"},{\"displayName\":\"vmw_nsxt_error_code\",\"preContext\":\"errorCode=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fojzg64s7mnxwizi0\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp subcomp\\\"}\"},{\"displayName\":\"vmw_nsxt_subcomp\",\"preContext\":\"subcomp=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3tovrgg33noa000000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp\\\"}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + }, { + "name":"NSX-T - LoadBalancerVsDown (!!datacenterName!!)", + "info":"VS status: all pool members are down.", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType":"RATE_BASED", + "hitOperator":"GREATER_THAN", + "hitCount":0.0, + "searchPeriod":660000, + "searchInterval":60000, + "chartQuery":"{\"query\":\"\",\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3dn5wxa000\",\"operator\":\"CONTAINS\",\"value\":\"nsx-edge\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3tovrgg33noa000000\",\"operator\":\"CONTAINS\",\"value\":\"nsx-edge-lb.lb\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fojzg64s7mnxwizi0\",\"operator\":\"CONTAINS\",\"value\":\"EDG1200001\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_nsxt_comp\",\"preContext\":\"comp=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3dn5wxa000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"subcomp\\\"}\"},{\"displayName\":\"vmw_nsxt_error_code\",\"preContext\":\"errorCode=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fojzg64s7mnxwizi0\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp subcomp\\\"}\"},{\"displayName\":\"vmw_nsxt_subcomp\",\"preContext\":\"subcomp=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3tovrgg33noa000000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp\\\"}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + }, { + "name":"NSX-T - LoadBalancerPoolDown (!!datacenterName!!)", + "info":"Pool status: all pool members are down.", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType":"RATE_BASED", + "hitOperator":"GREATER_THAN", + "hitCount":0.0, + "searchPeriod":660000, + "searchInterval":60000, + "chartQuery":"{\"query\":\"\",\"startTimeMillis\":1560560370535,\"endTimeMillis\":1560560674224,\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3dn5wxa000\",\"operator\":\"CONTAINS\",\"value\":\"nsx-edge\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3tovrgg33noa000000\",\"operator\":\"CONTAINS\",\"value\":\"nsx-edge-lb.lb\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fojzg64s7mnxwizi0\",\"operator\":\"CONTAINS\",\"value\":\"EDG1200000\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_nsxt_comp\",\"preContext\":\"comp=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3dn5wxa000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"subcomp\\\"}\"},{\"displayName\":\"vmw_nsxt_error_code\",\"preContext\":\"errorCode=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3fojzg64s7mnxwizi0\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp subcomp\\\"}\"},{\"displayName\":\"vmw_nsxt_subcomp\",\"preContext\":\"subcomp=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3tovrgg33noa000000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp\\\"}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" +}, { + "name":"NSX-T - ProcessCrash (!!datacenterName!!)", + "info":"Process or daemon crashes in the datapath or other LB process like dispatcher, etc..", + "recommendation":"", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType":"RATE_BASED", + "hitOperator":"GREATER_THAN", + "hitCount":0.0, + "searchPeriod":660000, + "searchInterval":60000, + "chartQuery":"{\"query\":\"\",\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":true,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"EVENTS\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3dn5wxa000\",\"operator\":\"CONTAINS\",\"value\":\"nsx-manager,nsx-edge,nsx-autonomous-edge\"},{\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3tovrgg33noa000000\",\"operator\":\"CONTAINS\",\"value\":\"node-mgmt\"},{\"internalName\":\"text\",\"operator\":\"CONTAINS\",\"value\":\"Core file generated\"},{\"internalName\":\"vmw_datacenter\",\"operator\":\"CONTAINS\",\"value\":\"!!datacenterName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_nsxt_comp\",\"preContext\":\"comp=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3dn5wxa000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"subcomp\\\"}\"},{\"displayName\":\"vmw_nsxt_subcomp\",\"preContext\":\"subcomp=\\\"\",\"postContext\":\"\\\"\",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibadcnk7mnxw2ltwnv3wc4tffzxhg6duozwxox3oon4hix3tovrgg33noa000000\",\"constraints\":\"{\\\"searchTerms\\\":\\\"comp\\\"}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!datacenterName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + } +] \ No newline at end of file diff --git a/SampleNotifications/vrli-vcf-vmVrslcm.json b/SampleNotifications/vrli-vcf-vmVrslcm.json new file mode 100644 index 00000000..6cb6f6c2 --- /dev/null +++ b/SampleNotifications/vrli-vcf-vmVrslcm.json @@ -0,0 +1,99 @@ +[ + { + "name":"***CRITICAL*** vRSLCM - ADD PRODUCT environmental request Failed! (!!vmName!!)", + "info":"An error occurred while adding a product to an environment in vRSLCM.", + "recommendation":"Retry the failed Add Product environment request!", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType":"NEW_EVENT_TYPE", + "hitOperator":"GREATER_THAN", + "hitCount":0.0, + "searchPeriod":3600000, + "searchInterval":600000, + "chartQuery":"{\"query\":\"\",\"startTimeMillis\":1579501372185,\"endTimeMillis\":1579501932103,\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":false,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"FIELD_TABLE\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"product\",\"operator\":\"CONTAINS\",\"value\":\"vRSLCM\"},{\"internalName\":\"component\",\"operator\":\"CONTAINS\",\"value\":\"server\"},{\"internalName\":\"ibademc7mnxw2ltwnv3wc4tffz3he43mmnwtqmbrozwxox3wojzwyy3nl5zgk4lvmvzxix3jmq000000\",\"operator\":\"EXISTS\"},{\"internalName\":\"ibademc7mnxw2ltwnv3wc4tffz3he43mmnwtqmbrozwxox3wojzwyy3nl5zgk4lvmvzxix3torqxi5lt\",\"operator\":\"CONTAINS\",\"value\":\"FAILED\"},{\"internalName\":\"ibademc7mnxw2ltwnv3wc4tffz3he43mmnwtqmbrozwxox3wojzwyy3nl5zgk4lvmvzxix3upfygk000\",\"operator\":\"CONTAINS\",\"value\":\"ADD_PRODUCT\"},{\"internalName\":\"ibadax3wnv3v65tsonwgg3k7mvxhm2lsn5xg2zloorpw4ylnmu000000\",\"operator\":\"CONTAINS\"},{\"internalName\":\"vc_vm_name\",\"operator\":\"CONTAINS\",\"value\":\"!!vmName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_vrslcm_request_id\",\"preContext\":\" request ID : \",\"postContext\":\" \",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibademc7mnxw2ltwnv3wc4tffz3he43mmnwtqmbrozwxox3wojzwyy3nl5zgk4lvmvzxix3jmq000000\",\"constraints\":\"{\\\"filters\\\":[{\\\"internalName\\\":\\\"product\\\",\\\"displayName\\\":\\\"product\\\",\\\"operator\\\":\\\"CONTAINS\\\",\\\"value\\\":\\\"vRSLCM\\\",\\\"fieldType\\\":\\\"STRING\\\",\\\"isExtracted\\\":false,\\\"hidden\\\":false}]}\"},{\"displayName\":\"vmw_vrslcm_request_status\",\"preContext\":\"Updating the Environment request status to \",\"postContext\":\" for\",\"regexValue\":\"\\\\w+\",\"internalName\":\"ibademc7mnxw2ltwnv3wc4tffz3he43mmnwtqmbrozwxox3wojzwyy3nl5zgk4lvmvzxix3torqxi5lt\",\"constraints\":\"{\\\"filters\\\":[{\\\"hidden\\\":false,\\\"internalName\\\":\\\"product\\\",\\\"displayName\\\":\\\"product\\\",\\\"operator\\\":\\\"CONTAINS\\\",\\\"value\\\":\\\"vRSLCM\\\",\\\"fieldType\\\":\\\"STRING\\\",\\\"isExtracted\\\":false}]}\"},{\"displayName\":\"vmw_vrslcm_request_type\",\"preContext\":\" request type : \",\"postContext\":\".\",\"regexValue\":\"\\\\w+|\\\\S+\",\"internalName\":\"ibademc7mnxw2ltwnv3wc4tffz3he43mmnwtqmbrozwxox3wojzwyy3nl5zgk4lvmvzxix3upfygk000\",\"constraints\":\"{\\\"filters\\\":[{\\\"hidden\\\":false,\\\"internalName\\\":\\\"product\\\",\\\"displayName\\\":\\\"product\\\",\\\"operator\\\":\\\"CONTAINS\\\",\\\"value\\\":\\\"vRSLCM\\\",\\\"fieldType\\\":\\\"STRING\\\",\\\"isExtracted\\\":false}]}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!vmName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + },{ + "name":"***CRITICAL*** vRSLCM - ADD NODE environmental request Failed! (!!vmName!!)", + "info":"An error occurred while adding node(s) to a product in vRSLCM.", + "recommendation":"Retry the failed Add Node environment request!", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType":"NEW_EVENT_TYPE", + "hitOperator":"GREATER_THAN", + "hitCount":0.0, + "searchPeriod":3600000, + "searchInterval":600000, + "chartQuery":"{\"query\":\"\",\"startTimeMillis\":1579501372185,\"endTimeMillis\":1579502165842,\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":false,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"FIELD_TABLE\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"product\",\"operator\":\"CONTAINS\",\"value\":\"vRSLCM\"},{\"internalName\":\"component\",\"operator\":\"CONTAINS\",\"value\":\"server\"},{\"internalName\":\"ibademc7mnxw2ltwnv3wc4tffz3he43mmnwtqmbrozwxox3wojzwyy3nl5zgk4lvmvzxix3jmq000000\",\"operator\":\"EXISTS\"},{\"internalName\":\"ibademc7mnxw2ltwnv3wc4tffz3he43mmnwtqmbrozwxox3wojzwyy3nl5zgk4lvmvzxix3torqxi5lt\",\"operator\":\"CONTAINS\",\"value\":\"FAILED\"},{\"internalName\":\"ibademc7mnxw2ltwnv3wc4tffz3he43mmnwtqmbrozwxox3wojzwyy3nl5zgk4lvmvzxix3upfygk000\",\"operator\":\"CONTAINS\",\"value\":\"ADD_NODE\"},{\"internalName\":\"ibadax3wnv3v65tsonwgg3k7mvxhm2lsn5xg2zloorpw4ylnmu000000\",\"operator\":\"CONTAINS\"},{\"internalName\":\"vc_vm_name\",\"operator\":\"CONTAINS\",\"value\":\"!!vmName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_vrslcm_request_id\",\"preContext\":\" request ID : \",\"postContext\":\" \",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibademc7mnxw2ltwnv3wc4tffz3he43mmnwtqmbrozwxox3wojzwyy3nl5zgk4lvmvzxix3jmq000000\",\"constraints\":\"{\\\"filters\\\":[{\\\"internalName\\\":\\\"product\\\",\\\"displayName\\\":\\\"product\\\",\\\"operator\\\":\\\"CONTAINS\\\",\\\"value\\\":\\\"vRSLCM\\\",\\\"fieldType\\\":\\\"STRING\\\",\\\"isExtracted\\\":false,\\\"hidden\\\":false}]}\"},{\"displayName\":\"vmw_vrslcm_request_status\",\"preContext\":\"Updating the Environment request status to \",\"postContext\":\" for\",\"regexValue\":\"\\\\w+\",\"internalName\":\"ibademc7mnxw2ltwnv3wc4tffz3he43mmnwtqmbrozwxox3wojzwyy3nl5zgk4lvmvzxix3torqxi5lt\",\"constraints\":\"{\\\"filters\\\":[{\\\"hidden\\\":false,\\\"internalName\\\":\\\"product\\\",\\\"displayName\\\":\\\"product\\\",\\\"operator\\\":\\\"CONTAINS\\\",\\\"value\\\":\\\"vRSLCM\\\",\\\"fieldType\\\":\\\"STRING\\\",\\\"isExtracted\\\":false}]}\"},{\"displayName\":\"vmw_vrslcm_request_type\",\"preContext\":\" request type : \",\"postContext\":\".\",\"regexValue\":\"\\\\w+|\\\\S+\",\"internalName\":\"ibademc7mnxw2ltwnv3wc4tffz3he43mmnwtqmbrozwxox3wojzwyy3nl5zgk4lvmvzxix3upfygk000\",\"constraints\":\"{\\\"filters\\\":[{\\\"hidden\\\":false,\\\"internalName\\\":\\\"product\\\",\\\"displayName\\\":\\\"product\\\",\\\"operator\\\":\\\"CONTAINS\\\",\\\"value\\\":\\\"vRSLCM\\\",\\\"fieldType\\\":\\\"STRING\\\",\\\"isExtracted\\\":false}]}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!vmName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + },{ + "name":"***CRITICAL*** vRSLCM - CREATE ENVIRONMENT operation Failed! (!!vmName!!)", + "info":"An error occurred while deploying a product in vRSLCM.", + "recommendation":"Retry or re-deploy the failed Create Environment request!", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType":"NEW_EVENT_TYPE", + "hitOperator":"GREATER_THAN", + "hitCount":0.0, + "searchPeriod":3600000, + "searchInterval":600000, + "chartQuery":"{\"query\":\"\",\"startTimeMillis\":1579498709709,\"endTimeMillis\":1579499042269,\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":false,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"FIELD_TABLE\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"product\",\"operator\":\"CONTAINS\",\"value\":\"vRSLCM\"},{\"internalName\":\"component\",\"operator\":\"CONTAINS\",\"value\":\"server\"},{\"internalName\":\"ibademc7mnxw2ltwnv3wc4tffz3he43mmnwtqmbrozwxox3wojzwyy3nl5zgk4lvmvzxix3jmq000000\",\"operator\":\"EXISTS\"},{\"internalName\":\"ibademc7mnxw2ltwnv3wc4tffz3he43mmnwtqmbrozwxox3wojzwyy3nl5zgk4lvmvzxix3torqxi5lt\",\"operator\":\"CONTAINS\",\"value\":\"FAILED\"},{\"internalName\":\"ibademc7mnxw2ltwnv3wc4tffz3he43mmnwtqmbrozwxox3wojzwyy3nl5zgk4lvmvzxix3upfygk000\",\"operator\":\"CONTAINS\",\"value\":\"CREATE_ENVIRONMENT\"},{\"internalName\":\"ibadax3wnv3v65tsonwgg3k7mvxhm2lsn5xg2zloorpw4ylnmu000000\",\"operator\":\"CONTAINS\"},{\"internalName\":\"vc_vm_name\",\"operator\":\"CONTAINS\",\"value\":\"!!vmName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_vrslcm_request_id\",\"preContext\":\" request ID : \",\"postContext\":\" \",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibademc7mnxw2ltwnv3wc4tffz3he43mmnwtqmbrozwxox3wojzwyy3nl5zgk4lvmvzxix3jmq000000\",\"constraints\":\"{\\\"filters\\\":[{\\\"internalName\\\":\\\"product\\\",\\\"displayName\\\":\\\"product\\\",\\\"operator\\\":\\\"CONTAINS\\\",\\\"value\\\":\\\"vRSLCM\\\",\\\"fieldType\\\":\\\"STRING\\\",\\\"isExtracted\\\":false,\\\"hidden\\\":false}]}\"},{\"displayName\":\"vmw_vrslcm_request_status\",\"preContext\":\"Updating the Environment request status to \",\"postContext\":\" for\",\"regexValue\":\"\\\\w+\",\"internalName\":\"ibademc7mnxw2ltwnv3wc4tffz3he43mmnwtqmbrozwxox3wojzwyy3nl5zgk4lvmvzxix3torqxi5lt\",\"constraints\":\"{\\\"filters\\\":[{\\\"hidden\\\":false,\\\"internalName\\\":\\\"product\\\",\\\"displayName\\\":\\\"product\\\",\\\"operator\\\":\\\"CONTAINS\\\",\\\"value\\\":\\\"vRSLCM\\\",\\\"fieldType\\\":\\\"STRING\\\",\\\"isExtracted\\\":false}]}\"},{\"displayName\":\"vmw_vrslcm_request_type\",\"preContext\":\" request type : \",\"postContext\":\".\",\"regexValue\":\"\\\\w+|\\\\S+\",\"internalName\":\"ibademc7mnxw2ltwnv3wc4tffz3he43mmnwtqmbrozwxox3wojzwyy3nl5zgk4lvmvzxix3upfygk000\",\"constraints\":\"{\\\"filters\\\":[{\\\"hidden\\\":false,\\\"internalName\\\":\\\"product\\\",\\\"displayName\\\":\\\"product\\\",\\\"operator\\\":\\\"CONTAINS\\\",\\\"value\\\":\\\"vRSLCM\\\",\\\"fieldType\\\":\\\"STRING\\\",\\\"isExtracted\\\":false}]}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!vmName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + }, { + "name":"***CRITICAL*** vRSLCM Disk is full! (!!vmName!!)", + "info":"Disk Usage of the vRSLCM system is very high at 100%.", + "recommendation":"To avoid failures, please extend storage from system details page in the vRSLCM set-up!", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType":"NEW_EVENT_TYPE", + "hitOperator":"GREATER_THAN", + "hitCount":0.0, + "searchPeriod":3600000, + "searchInterval":600000, + "chartQuery":"{\"query\":\"\\\"storagePercentage\\\" : \\\"100%\\\"\",\"startTimeMillis\":1579330460183,\"endTimeMillis\":1579503291081,\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":false,\"includeAllContentPackFields\":false,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"FIELD_TABLE\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"product\",\"operator\":\"CONTAINS\",\"value\":\"vRSLCM\"},{\"internalName\":\"vc_vm_name\",\"operator\":\"CONTAINS\",\"value\":\"!!vmName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[{\"displayName\":\"vmw_vrslcm_request_type\",\"internalName\":\"ibademc7mnxw2ltwnv3wc4tffz3he43mmnwtqmbrozwxox3wojzwyy3nl5zgk4lvmvzxix3upfygk000\",\"displayNamespace\":\"VMware - vRSLCM 8.0.1+\",\"numericGroupByType\":\"EACH_VALUE\",\"numericGroupByValue\":null}],\"contentPacksToIncludeFields\":[{\"name\":\"General\",\"namespace\":\"com.vmware.loginsight.general\"},{\"name\":\"VMware - VSAN\",\"namespace\":\"com.vmware.vsan\"},{\"name\":\"VMware - vRops 6.7+\",\"namespace\":\"com.vmware.vrops67\"},{\"name\":\"VMware - vSphere\",\"namespace\":\"com.vmware.vsphere\"}],\"extractedFields\":[{\"displayName\":\"vmw_vrslcm_request_type\",\"preContext\":\" request type : \",\"postContext\":\".\",\"regexValue\":\"\\\\w+|\\\\S+\",\"internalName\":\"ibademc7mnxw2ltwnv3wc4tffz3he43mmnwtqmbrozwxox3wojzwyy3nl5zgk4lvmvzxix3upfygk000\",\"constraints\":\"{\\\"filters\\\":[{\\\"hidden\\\":false,\\\"internalName\\\":\\\"product\\\",\\\"displayName\\\":\\\"product\\\",\\\"operator\\\":\\\"CONTAINS\\\",\\\"value\\\":\\\"vRSLCM\\\",\\\"fieldType\\\":\\\"STRING\\\",\\\"isExtracted\\\":false}]}\"}]}", + "messageQuery":"", + "vcopsEnabled": false, + "vcopsResourceName": "!!vmName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + }, { + "name":"***CRITICAL*** vRSLCM - UPGRADE PRODUCT environmental request Failed! (!!vmName!!)", + "info":"An error occurred while upgrading a product in vRSLCM.", + "recommendation":"Retry the failed Upgrade Product environmental request!", + "enabled": true, + "emailEnabled": true, + "emails": "!!email!!", + "webhookEnabled": false, + "autoClearAlertAfterTimeout": false, + "alertType":"NEW_EVENT_TYPE", + "hitOperator":"GREATER_THAN", + "hitCount":0.0, + "searchPeriod":3600000, + "searchInterval":600000, + "chartQuery":"{\"query\":\"\",\"startTimeMillis\":1579499557918,\"endTimeMillis\":1579499893278,\"piqlFunctionGroups\":[{\"functions\":[{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false}],\"field\":null}],\"dateFilterPreset\":\"CUSTOM\",\"shouldGroupByTime\":true,\"includeAllContentPackFields\":false,\"eventSortOrder\":\"DESC\",\"summarySortOrder\":\"DESC\",\"compareQueryOrderBy\":\"TREND\",\"compareQuerySortOrder\":\"DESC\",\"compareQueryOptions\":null,\"messageViewType\":\"FIELD_TABLE\",\"constraintToggle\":\"ALL\",\"piqlFunction\":{\"label\":\"Count\",\"value\":\"COUNT\",\"requiresField\":false,\"numericOnly\":false},\"piqlFunctionField\":null,\"fieldConstraints\":[{\"internalName\":\"product\",\"operator\":\"CONTAINS\",\"value\":\"vRSLCM\"},{\"internalName\":\"component\",\"operator\":\"CONTAINS\",\"value\":\"server\"},{\"internalName\":\"ibademc7mnxw2ltwnv3wc4tffz3he43mmnwtqmbrozwxox3wojzwyy3nl5zgk4lvmvzxix3jmq000000\",\"operator\":\"EXISTS\"},{\"internalName\":\"ibademc7mnxw2ltwnv3wc4tffz3he43mmnwtqmbrozwxox3wojzwyy3nl5zgk4lvmvzxix3torqxi5lt\",\"operator\":\"CONTAINS\",\"value\":\"FAILED\"},{\"internalName\":\"ibademc7mnxw2ltwnv3wc4tffz3he43mmnwtqmbrozwxox3wojzwyy3nl5zgk4lvmvzxix3upfygk000\",\"operator\":\"CONTAINS\",\"value\":\"UPGRADE_PRODUCT\"},{\"internalName\":\"ibadax3wnv3v65tsonwgg3k7mvxhm2lsn5xg2zloorpw4ylnmu000000\",\"operator\":\"CONTAINS\"},{\"internalName\":\"vc_vm_name\",\"operator\":\"CONTAINS\",\"value\":\"!!vmName!!\"}],\"supplementalConstraints\":[],\"groupByFields\":[],\"contentPacksToIncludeFields\":[],\"extractedFields\":[{\"displayName\":\"vmw_vrslcm_request_id\",\"preContext\":\" request ID : \",\"postContext\":\" \",\"regexValue\":\"\\\\S+\",\"internalName\":\"ibademc7mnxw2ltwnv3wc4tffz3he43mmnwtqmbrozwxox3wojzwyy3nl5zgk4lvmvzxix3jmq000000\",\"constraints\":\"{\\\"filters\\\":[{\\\"internalName\\\":\\\"product\\\",\\\"displayName\\\":\\\"product\\\",\\\"operator\\\":\\\"CONTAINS\\\",\\\"value\\\":\\\"vRSLCM\\\",\\\"fieldType\\\":\\\"STRING\\\",\\\"isExtracted\\\":false,\\\"hidden\\\":false}]}\"},{\"displayName\":\"vmw_vrslcm_request_status\",\"preContext\":\"Updating the Environment request status to \",\"postContext\":\" for\",\"regexValue\":\"\\\\w+\",\"internalName\":\"ibademc7mnxw2ltwnv3wc4tffz3he43mmnwtqmbrozwxox3wojzwyy3nl5zgk4lvmvzxix3torqxi5lt\",\"constraints\":\"{\\\"filters\\\":[{\\\"hidden\\\":false,\\\"internalName\\\":\\\"product\\\",\\\"displayName\\\":\\\"product\\\",\\\"operator\\\":\\\"CONTAINS\\\",\\\"value\\\":\\\"vRSLCM\\\",\\\"fieldType\\\":\\\"STRING\\\",\\\"isExtracted\\\":false}]}\"},{\"displayName\":\"vmw_vrslcm_request_type\",\"preContext\":\" request type : \",\"postContext\":\".\",\"regexValue\":\"\\\\w+|\\\\S+\",\"internalName\":\"ibademc7mnxw2ltwnv3wc4tffz3he43mmnwtqmbrozwxox3wojzwyy3nl5zgk4lvmvzxix3upfygk000\",\"constraints\":\"{\\\"filters\\\":[{\\\"hidden\\\":false,\\\"internalName\\\":\\\"product\\\",\\\"displayName\\\":\\\"product\\\",\\\"operator\\\":\\\"CONTAINS\\\",\\\"value\\\":\\\"vRSLCM\\\",\\\"fieldType\\\":\\\"STRING\\\",\\\"isExtracted\\\":false}]}\"}]}", + "vcopsEnabled": false, + "vcopsResourceName": "!!vmName!!", + "vcopsResourceKindKey": "", + "vcopsCriticality": "critical" + } +] \ No newline at end of file diff --git a/SampleNotifications/vrops-vcf-notifications.csv b/SampleNotifications/vrops-vcf-notifications.csv new file mode 100644 index 00000000..ff3065e8 --- /dev/null +++ b/SampleNotifications/vrops-vcf-notifications.csv @@ -0,0 +1,28 @@ +"alertDefinition","adapterKindKey","resourceKindKey","alertPluginName","emailAddress","maxNotify","delay","resend","alertName" +"AlertDefinition-VMWARE-GuestOutOfDiskSpace","VMWARE","VirtualMachine","Email-Alert-Plugin","administrator@rainpole.io","3","15","15","One or more virtual machine guest file systems are running out of disk space" +"AlertDefinition-VMWARE-CPUContentionDueToCostop","VMWARE","VirtualMachine","Email-Alert-Plugin","administrator@rainpole.io","3","15","15","Virtual machine has CPU contention due to multi-vCPU scheduling issues (co-stop) caused by too many vCPUs" +"AlertDefinition-VMWARE-VMContentionDuetoSwap","VMWARE","VirtualMachine","Email-Alert-Plugin","administrator@rainpole.io","3","15","15","Virtual machine has CPU contention due to memory page swapping in the host" +"AlertDefinition-VMWARE-VMReadLatencySwapping","VMWARE","VirtualMachine","Email-Alert-Plugin","administrator@rainpole.io","3","15","15","Virtual machine has memory contention caused by swap wait and high disk read latency" +"AlertDefinition-VMWARE-DiskLatencyDueToSnapshot","VMWARE","VirtualMachine","Email-Alert-Plugin","administrator@rainpole.io","3","15","15","Virtual machine has disk I/O latency problem caused by snapshots" +"AlertDefinition-VMWARE-HighCostopSnapshots","VMWARE","VirtualMachine","Email-Alert-Plugin","administrator@rainpole.io","3","15","15","Virtual machine has CPU contention due to multi-vCPU scheduling issues (co-stop) caused by snapshots" +"AlertDefinition-VMWARE-CannotStartVMAlert","VMWARE","VirtualMachine","Email-Alert-Plugin","administrator@rainpole.io","3","15","15","Not enough resources for vSphere HA to start the virtual machine" +"AlertDefinition-VMWARE-VMFailoverFailedAlert","VMWARE","VirtualMachine","Email-Alert-Plugin","administrator@rainpole.io","3","15","15","vSphere HA cannot perform a failover operation for the virtual machine" +"AlertDefinition-VMWARE-HostCPUContentionNoSingleVM","VMWARE","HostSystem","Email-Alert-Plugin","administrator@rainpole.io","3","15","15","Standalone host has CPU contention caused by overpopulation of virtual machines" +"AlertDefinition-VMWARE-HostMemContentionNoSingleVM","VMWARE","HostSystem","Email-Alert-Plugin","administrator@rainpole.io","3","15","15","Standalone host has memory contention caused by overpopulation of virtual machines" +"AlertDefinition-VMWARE-ClusterCPUContentionNoSingleVM","VMWARE","ClusterComputeResource","Email-Alert-Plugin","administrator@rainpole.io","3","15","15","Fully-automated DRS-enabled cluster has CPU contention caused by overpopulation of virtual machines" +"AlertDefinition-VMWARE-ClusterUnexpectedCPUWorkload","VMWARE","ClusterComputeResource","Email-Alert-Plugin","administrator@rainpole.io","3","15","15","Fully-automated DRS-enabled cluster has high CPU workload" +"AlertDefinition-VMWARE-ClusterMemContentionNoSingleVM","VMWARE","ClusterComputeResource","Email-Alert-Plugin","administrator@rainpole.io","3","15","15","Fully-automated DRS-enabled cluster has memory contention caused by overpopulation of virtual machines" +"AlertDefinition-VMWARE-ClusterUnexpectedMemWorkload","VMWARE","ClusterComputeResource","Email-Alert-Plugin","administrator@rainpole.io","3","15","15","Fully-automated DRS-enabled cluster has high memory workload and contention" +"AlertDefinition-VMWARE-InsufficientFailoverResAlert","VMWARE","ClusterComputeResource","Email-Alert-Plugin","administrator@rainpole.io","3","15","15","vSphere HA fail over resources are insufficient" +"AlertDefinition-VMWARE-HostConfigOutOfSync","VMWARE","VmwareDistributedVirtualSwitch","Email-Alert-Plugin","administrator@rainpole.io","3","15","15","Distributed switch configuration is out of sync" +"AlertDefinition-SDDCHealthAdapter-NSXManagerMemoryUsageIsHigh","SDDCHealthAdapter","NSXManager","Email-Alert-Plugin","administrator@rainpole.io","3","15","15","NSX Manager Memory Usage is High" +"AlertDefinition-SDDCHealthAdapter-NSXManagerServiceNotRunning","SDDCHealthAdapter","NSXManager","Email-Alert-Plugin","administrator@rainpole.io","3","15","15","NSX Manager Service Not Running" +"AlertDefinition-NSXTComponentHealthDegraded","SDDCHealthAdapter","SDDC NSX World","Email-Alert-Plugin","administrator@rainpole.io","3","15","15","Health of NSX-T children objects is degraded" +"AlertDefinition-ManagementClusterStatusNotStable","NSXTAdapter","ManagementCluster","Email-Alert-Plugin","administrator@rainpole.io","3","15","15","Management cluster's management status is not stable" +"AlertDefinition-InsufficientControllerNodes","NSXTAdapter","ControllerCluster","Email-Alert-Plugin","administrator@rainpole.io","3","15","15","Less than 3 controller nodes are deployed" +"AlertDefinition-LoadBalancerServiceOperationalStatusDown","NSXTAdapter","LoadBalancerService","Email-Alert-Plugin","administrator@rainpole.io","3","15","15","Load Balancer Service operational status down" +"AlertDefinition-VMWARE-DatastoreUsage","VMWARE","Datastore","Email-Alert-Plugin","administrator@rainpole.io","3","15","15","Datastore is running out of disk space" +"AlertDefinition-VMWARE-StorageConnectivityLostAlert","VMWARE","Datastore","Email-Alert-Plugin","administrator@rainpole.io","3","15","15","Datastore has lost connectivity to a storage device" +"AlertDefinition-limits.limit1hf","VirtualAndPhysicalSANAdapter","VirtualSANDCCluster","Email-Alert-Plugin","administrator@rainpole.io","3","15","15","After one additional host failure, vSAN Cluster will not have enough resources to rebuild all objects" +"AlertDefinition-data.objecthealth","VirtualAndPhysicalSANAdapter","VirtualSANDCCluster","Email-Alert-Plugin","administrator@rainpole.io","3","15","15","Overall health of vSAN objects is reporting issues" +"AlertDefinition-ClusterReadCacheReservationHealthApproachingCapacity","VirtualAndPhysicalSANAdapter","VirtualSANDCCluster","Email-Alert-Plugin","administrator@rainpole.io","3","15","15","vSAN Cluster flash read cache reservation is approaching capacity" \ No newline at end of file From 1e8ed4d47ff40c8cf37c0ef81aedca40208bff09 Mon Sep 17 00:00:00 2001 From: GaryJBlake Date: Tue, 25 Jan 2022 12:08:41 +0000 Subject: [PATCH 5/5] Update Core Content for v1.3.0 Release - Updated CHANGELOG.md - Updated README.md - Updated PowerValidatedSolutions.psm1 with fixes and enhancements - Regenerated PowerValidatedSolutions.psd1 Signed-off-by: Gary Blake --- CHANGELOG.md | 78 +- PowerValidatedSolutions.psd1 | 78 +- PowerValidatedSolutions.psm1 | 22685 +++++++++++++++++++++------------ README.md | 4 +- 4 files changed, 14904 insertions(+), 7941 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a94ecb6c..69242dcf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,8 +1,58 @@ # Release History +## v1.3.0 (2022-25-01) +- Fixed `New-vRSLCMLockerLicense` cmdlet where depending on the speed of the system the license would be added but POST_VALIDATION would fail. +- Enhanced all Identity and Access Management Solution cmdlets for better error handling and message output. +- Enhanced all vRealize Operations Manager cmdlets for better error handling and message output. +- Enhanced all vRealize Log Insight cmdlets for better error handling and message output. +- Enhanced all vRealize Automation cmdlets for better error handling and message output. +- Enhanced `Set-vCenterPermission` cmdlet to set permissions on non-nested folders. +- Enhanced `Enable-SupervisorCluster` cmdlet with better pre-validation. +- Renamed `Add-NsxtVidmGroupRole` cmdlet to `Add-NsxtVidmRole`, to add support for assigning both users and groups roles in NSX-T Data Center. +- Added `Add-ResourcePool` cmdlet to create a resource pool in the Workload Domain specified. +- Added `Undo-ResourcePool` cmdlet to remove a resource pool based on the Workload Domain specified. +- Added `Update-vRAOrganizationDisplayName` cmdlet to configure the Organization Display Name in vRealize Automation. +- Added `Add-vROPSAdapterPing` cmdlet to add a Ping Adapter to vRealize Operations Manager +- Added `Enable-vROPSManagementPack` cmdlet to upload and install the SDDC Health Management Pack to vRealize Operations Manager +- Added `Update-vROPSAdapterSddcHealth` cmdlet to rename the SDDC Health Adapters in vRealize Operations Manager +- Added `Add-vROPSAdapterSddcHealth` cmdlet to add SDDC Health Adapters for the Remote Collectors in vRealize Operations Manager +- Added `Add-vROPSAlertPluginEmail` cmdlet to add an Email Alert Plugin to vRealize Operations Manager +- Added `Register-vROPSManagementPack` cmdlet to activate / deactivate Native Management Packs in vRealize Operations Manager +- Added `Import-vROPSUserGroup` cmdlet to import a user group and assign access in vRealize Operations Manager +- Added `Add-vROvCenterServer` cmdlet to add a workload domain vCenter Server instance to the embedded vRealize Orchestrator. +- Added `Remove-vROvCenterServer` cmdlet to remove a workload domain vCenter Server instance from the embedded vRealize Orchestrator. +- Added `Add-vROTrustedCertificate` cmdlet to import a trusted certificate to the embedded vRealize Orchestrator using a PEM-encoded file. +- Added `Import-vROPSNotification` cmdlet to import notifications using comma separated value file to vRealize Operations Manager. +- Added `Add-vRANotification` cmdlet to configure the smtp notification settings in vRealize Automation. +- Added `New-vRACloudAccount` cmdlet to add Cloud Accounts for a Workload Domains vCenter Server and NSX Management Cluster in vRealize Automation. +- Added `Undo-vRACloudAccount` cmdlet to remove the Cloud Accounts for a Workload Domains vCenter Server and NSX Management Cluster in vRealize Automation. +- Added `Update-vRACloudAccountZone` cmdlet to update the configuration of the Cloud Account Zone for a Workload Domain in vRealize Automation. +- Added `Add-vRAUser` cmdlet to add an organization role and a service role to a user account in vRealize Automation. +- Added `Undo-vRAUser` cmdlet to remove an organization role and all service roles from a user account in vRealize Automation. +- Added `Add-vRAGroup` cmdlet to add an organization role and a service role to a group in vRealize Automation. +- Added `Undo-vRAGroup` cmdlet to remove an organization role and all service roles from a group account in vRealize Automation. +- Added `Undo-IdentitySource` cmdlet to remove an Identity Provider from vCenter Server. +- Added `Undo-SddcManagerRole` cmdlet to remove access for a user in SDDC Manager. +- Added `Add-SsoUser` cmdlet to add a Single Sign-On domain user. +- Added `New-vRSLCMDatacenter` cmdlet to add a datacenter in vRealize Suite Lifecycle Manager. +- Added `Undo-vRSLCMDatacenter` cmdlet to remove a datacenter from vRealize Suite Lifecycle Manager. +- Added `New-vRSLCMDatacenterVcenter` cmdlet to add a vCenter Server to a datacenter in vRealize Lifecycle Manager. +- Added `Export-WSAJsonSpec` cmdlet to generate the deployment JSON for Clustered Workspace ONE Access. +- Added `New-WSADeployment` cmdlet to trigger the deployment of Clustered Workspace ONE Access via vRealize Suite Lifecycle Maneger. +- Added `Add-WorkspaceOneDirectoryConnector` cmdlet to add a connector to the Identity Provider in Workspace ONE Access. +- Added `Add-vRLIAlertDatacenter` cmdlet to create vRealize Log Insight alerts by datacenter +- Added `Add-vRLIAlertVirtualMachine` cmdlet to create vRealize Log Insight alerts by virtual machine +- Added `Undo-vRLIAlert` cmdlet to remove alerts from vRealize Log Insight. +- Added Sample Notification Templates in the SampleNotifications folder: + - `vrli-vcf-datacenter.json` defines the vRealize Log Insight alerts that should be configured for VMware Cloud Foundation at the datacenter level + - `vrli-vcf-vmVrslcm.json` defines the vRealize Log Insight alerts that should be configured for vRealize Suite Lifecycle Manager +- Added Sample Scripts in the SampleScripts\iom folder, each script uses the Planning and Preparation Workbook as the input source: + - `iomDeployVrealizeOperations.ps1` automates the install and config of vRealize Operations for Intelligent Operations Management for VMware Cloud Foundation. + - `iomConfigureVrealizeOperations.ps1` automates the integration config of vRealize Operations for Intelligent Operations Management for VMware Cloud Foundation. + ## v1.2.0 (2021-30-11) - Fixed `Add-GlobalPermission` where an error is thrown when Internet Explorer has not been launched in the operating system. -- Fixed `Set-DatastoreTag` where it was failing to create a single tag and catagory when multiple vCenter Servers in the Single-Sign On domain. -- Fixed `Add-StoragePolicy` where is was failing to add the storage policy when multiple vCenter Servers in the Single-Sign On domain +- Fixed `Set-DatastoreTag` where it was failing to create a single tag and category when multiple vCenter Servers in the Single-Sign On domain. +- Fixed `Add-StoragePolicy` where is was failing to add the storage policy when multiple vCenter Servers in the Single-Sign On domain. - Enhanced `Move-VMtoFolder` cmdlet to check the name of VM provided and skip if it does not exist. - Enhanced `Add-WorkspaceOneDirectory` cmdlet so that it can be used with Clustered Workspace ONE Access. - Enhanced `Set-WorkspaceOneSmtpConfig` cmdlet to skip the configuration if the SMTP Server configuration is already performed. @@ -15,21 +65,21 @@ - Added `Export-vRASJsonSpec` cmdlet to generate the Json specification file needed to deploy vRealize Automation via vRealize Lifecycle Suite Manager. - Added `New-vRADeployment` cmdlet to deploy vRealize Automation via vRealize Lifecycle Suite Manager in VMware Cloud Foundation aware mode. - Added `Install-vRLIPhotonAgent` cmdlet to download, install and configure the vRealize Log Insight Agent on Photon Operating System. -- Added `Add-vRLIAgentGroup` cmdlet to create an Agent Group in vRealize Log Insight +- Added `Add-vRLIAgentGroup` cmdlet to create an Agent Group in vRealize Log Insight. - Added `Register-vRLIWorkloadDomain` cmdlet to connect/disconnect a Workload Domain with vRealize Log Insight. - Added `Set-vRLISyslogEdgeCluster` cmdlet to configure the Syslog settings for each NSX Edge node within a Workload Domains NSX Edge Cluster. -- Added `Add-vRLISmtpConfiguation` cmdlet to configure the SMTP Server settings for vRealize Log Insight -- Added `Add-vRLILogArchive` cmdlet to configure Email Notifications, Retention and Archive Location for vRealize Log Insight +- Added `Add-vRLISmtpConfiguration` cmdlet to configure the SMTP Server settings for vRealize Log Insight. +- Added `Add-vRLILogArchive` cmdlet to configure Email Notifications, Retention and Archive Location for vRealize Log Insight. - Added `Register-vROPSWorkloadDomain` cmdlet to connect/disconnect a Workload Domain with vRealize Operations Manager. -- Added `Add-vROPSCurrency` cmdlet to configure the currency for vRealize Opertations Manager -- Added `Add-vROPSGroupRemoteCollectors` cmdlet to create a Remote Collector Group and assign the remote collectors in vRealize Operations Manager -- Added `Update-vROPSAdapterVcenter` cmdlet to update the Remote Collector Group assignment for the vCenter Server Adapter in vRealize Operations Manager -- Added `Add-vROPSCredentialNsxt` cmdlet to create an NSX credential in vRealize Operations Manager -- Added `Add-vROPSAdapterNsxt` cmdlet to create an NSX Adapter and Start Collection in vRealize Operations Manager +- Added `Add-vROPSCurrency` cmdlet to configure the currency for vRealize Operations Manager. +- Added `Add-vROPSGroupRemoteCollectors` cmdlet to create a Remote Collector Group and assign the remote collectors in vRealize Operations Manager. +- Added `Update-vROPSAdapterVcenter` cmdlet to update the Remote Collector Group assignment for the vCenter Server Adapter in vRealize Operations Manager. +- Added `Add-vROPSCredentialNsxt` cmdlet to create an NSX credential in vRealize Operations Manager. +- Added `Add-vROPSAdapterNsxt` cmdlet to create an NSX Adapter and Start Collection in vRealize Operations Manager. - Added `Undo-vRSLCMLockerPassword` cmdlet to remove a password from the vRealize Suite Lifecycle Manager Locker. - Added `Undo-vRSLCMLockerCertificate` cmdlet to remove a certificate from the vRealize Suite Lifecycle Manager Locker. - Added `Undo-vRSLCMLockerLicense` cmdlet to remove a license from the vRealize Suite Lifecycle Manager Locker. -- Added `Undo-VMFolder` cmdlet to remove a folder from vCenter Server +- Added `Undo-VMFolder` cmdlet to remove a folder from vCenter Server. - Added `Add-vRLIAuthenticationGroup` cmdlet to assign vRealize Log Insight roles to Workspace ONE Access Groups. - Added Sample Scripts in the SampleScripts\iam folder, each script uses the Planning and Preparation Workbook as the input source: - `iamConfigureVsphere.ps1` automates all the configuration of vSphere/SDDC Manager elements for Identity and Access Management for VMware Cloud Foundation. @@ -38,9 +88,9 @@ - Added Sample Scripts in the SampleScripts\ila folder, each script uses the Planning and Preparation Workbook as the input source: - `ilaDeployVrealizeLogInsight.ps1` automates the install and config of vRealize Log Insight for Intelligent Logging and Analytics for VMware Cloud Foundation. - `ilaConfigureVrealizeLogInsight.ps1` automates the integration config of vRealize Log Insight for Intelligent Logging and Analytics for VMware Cloud Foundation. -- Added `New-SupervisorClusterCSR` cmdlet to create a new certificate signing request for the defined Supervisor Cluster -- Added `Add-SupervisorClusterCertificate` cmdlet to add a signed TLS certificate for the defined Supervisor Cluster -- Added `Add-NamespaceVmClass` cmdlet to add an existing VM Class to a Supervisor Namespace +- Added `New-SupervisorClusterCSR` cmdlet to create a new certificate signing request for the defined Supervisor Cluster. +- Added `Add-SupervisorClusterCertificate` cmdlet to add a signed TLS certificate for the defined Supervisor Cluster. +- Added `Add-NamespaceVmClass` cmdlet to add an existing VM Class to a Supervisor Namespace. ## v1.1.0 (2021-05-10) - Fixed `Set-vCenterPermission` where a failure can occur if the workload domain does not follow the same naming as the vCenter Server. diff --git a/PowerValidatedSolutions.psd1 b/PowerValidatedSolutions.psd1 index 4967eabf..bc7e032b 100644 --- a/PowerValidatedSolutions.psd1 +++ b/PowerValidatedSolutions.psd1 @@ -1,9 +1,9 @@ # # Module manifest for module 'PowerValidatedSolutions' # -# Generated by: VMware Inc. +# Generated by: Gary Blake, Cloud Infrastructure Business Group (CIBG) # -# Generated on: 30/11/2021 +# Generated on: 1/25/2022 # @{ @@ -12,18 +12,23 @@ RootModule = 'PowerValidatedSolutions.psm1' # Version number of this module. - ModuleVersion = '1.2.0' + ModuleVersion = '1.3.0' # Supported PSEditions # CompatiblePSEditions = @() # ID used to uniquely identify this module - GUID = '04e25d59-f231-4a5c-8506-dee433cf99c7' + GUID = '081b7193-0d52-40e6-b148-a0a2bc9743fa' # Author of this module Author = 'Gary Blake, Cloud Infrastructure Business Group (CIBG)' + + # Company or vendor of this module CompanyName = 'VMware Inc.' + # Copyright statement for this module + Copyright = 'Copyright 2021-2022 VMware, Inc.' + # Description of the functionality provided by this module Description = 'PowerShell Module for VMware Validated Solutions' @@ -36,9 +41,30 @@ # Minimum version of the Windows PowerShell host required by this module # PowerShellHostVersion = '' + # Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. + # DotNetFrameworkVersion = '' + + # Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. + # CLRVersion = '' + + # Processor architecture (None, X86, Amd64) required by this module + # ProcessorArchitecture = '' + # Modules that must be imported into the global environment prior to importing this module # RequiredModules = @() + # Assemblies that must be loaded prior to importing this module + # RequiredAssemblies = @() + + # Script files (.ps1) that are run in the caller's environment prior to importing this module. + # ScriptsToProcess = @() + + # Type files (.ps1xml) to be loaded when importing this module + # TypesToProcess = @() + + # Format files (.ps1xml) to be loaded when importing this module + # FormatsToProcess = @() + # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess # NestedModules = @() @@ -51,4 +77,46 @@ # Variables to export from this module VariablesToExport = '*' - } \ No newline at end of file + # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. + AliasesToExport = '*' + + # DSC resources to export from this module + # DscResourcesToExport = @() + + # List of all modules packaged with this module + # ModuleList = @() + + # List of all files packaged with this module + # FileList = @() + + # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. + PrivateData = @{ + + PSData = @{ + + # Tags applied to this module. These help with module discovery in online galleries. + # Tags = @() + + # A URL to the license for this module. + # LicenseUri = '' + + # A URL to the main website for this project. + # ProjectUri = '' + + # A URL to an icon representing this module. + # IconUri = '' + + # ReleaseNotes of this module + # ReleaseNotes = '' + + } # End of PSData hashtable + + } # End of PrivateData hashtable + + # HelpInfo URI of this module + # HelpInfoURI = '' + + # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. + # DefaultCommandPrefix = '' + + } \ No newline at end of file diff --git a/PowerValidatedSolutions.psm1 b/PowerValidatedSolutions.psm1 index 6fc1fee1..2035bf3b 100644 --- a/PowerValidatedSolutions.psm1 +++ b/PowerValidatedSolutions.psm1 @@ -23,7 +23,7 @@ if ($PSEdition -eq 'Desktop') { [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12; if ("TrustAllCertificatePolicy" -as [type]) {} else { - add-type @" + Add-Type @" using System.Net; using System.Security.Cryptography.X509Certificates; public class TrustAllCertificatePolicy : ICertificatePolicy { @@ -39,8 +39,6 @@ if ($PSEdition -eq 'Desktop') { } } -#### Do not modify anything below this line. All user variables are in the accompanying JSON files ##### - Function Resolve-PSModule { <# .SYNOPSIS @@ -113,26 +111,27 @@ Function Resolve-PSModule { Function Add-IdentitySource { <# .SYNOPSIS - Add Active Directory over LDAP/LDAPS as an Identity Provider to vCenter Server + Add Active Directory over LDAP/LDAPS as an Identity Provider to vCenter Server - .DESCRIPTION - The Add-IdentitySource cmdlets adds Active Directory over LDAP/LDAPS as an Identity Provider to the vCenter + .DESCRIPTION + 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 to retrive the Management Domain vCenter Server details from from the SDDC Manager - inventory and then: + -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 - 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 - .EXAMPLE - Add-IdentitySource -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo.rainpole.io -domainBindUser svc-vsphere-ad -domainBindPass VMw@re1! -dcMachineName dc-sfo01 -baseGroupDn "ou=Security Groups,dc=sfo,dc=rainpole,dc=io" -baseUserDn "ou=Security Users,dc=sfo,dc=rainpole,dc=io" -protocol ldap + .EXAMPLE + Add-IdentitySource -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo.rainpole.io -domainBindUser svc-vsphere-ad -domainBindPass VMw@re1! -dcMachineName dc-sfo01 -baseGroupDn "ou=Security Groups,dc=sfo,dc=rainpole,dc=io" -baseUserDn "ou=Security Users,dc=sfo,dc=rainpole,dc=io" -protocol ldap This example adds the sfo.rainpole.io domain as the default Identity Provider to vCenter Server using LDAP .EXAMPLE - Add-IdentitySource -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo.rainpole.io -domainBindUser svc-vsphere-ad -domainBindPass VMw@re1! -dcMachineName dc-sfo01 -baseGroupDn "ou=Security Groups,dc=sfo,dc=rainpole,dc=io" -baseUserDn "ou=Security Users,dc=sfo,dc=rainpole,dc=io" -protocol ldaps -certificate F:\certificates\Root64.cer + Add-IdentitySource -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo.rainpole.io -domainBindUser svc-vsphere-ad -domainBindPass VMw@re1! -dcMachineName dc-sfo01 -baseGroupDn "ou=Security Groups,dc=sfo,dc=rainpole,dc=io" -baseUserDn "ou=Security Users,dc=sfo,dc=rainpole,dc=io" -protocol ldaps -certificate F:\certificates\Root64.cer This example adds the sfo.rainpole.io domain as the default Identity Provider to vCenter Server using LDAPS - #> + #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, @@ -168,51 +167,47 @@ Function Add-IdentitySource { } Try { - Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null - if ($accessToken) { - $ssoServer = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT - $ssoConnection = Connect-SsoAdminServer -Server $ssoServer.fqdn -User $ssoServer.ssoAdmin -Password $ssoServer.ssoAdminPass - if ($DefaultSsoAdminServers.Name -eq $($ssoServer.fqdn)) { - if (Get-IdentitySource -Server $ssoConnection | Where-Object { $_.Name -eq $domain }) { - Write-Warning "Adding Identity Source to vCenter Server ($($ssoServer.fqdn)) named ($domain), already exists: SKIPPED" - } - else { - if (Test-Connection -ComputerName ($dcMachineName + "." + $domain) -Quiet -Count 1) { - if ($protocol -eq "ldaps") { - Add-LDAPIdentitySource -ServerType ActiveDirectory -Name $domain -DomainName $domain -DomainAlias $domainAlias -PrimaryUrl $primaryUrl -BaseDNUsers $baseUserDn -BaseDNGroups $baseGroupDn -Username $bindUser -Password $domainBindPass -Certificate $certificate - } - else { - Add-LDAPIdentitySource -ServerType ActiveDirectory -Name $domain -DomainName $domain -DomainAlias $domainAlias -PrimaryUrl $primaryUrl -BaseDNUsers $baseUserDn -BaseDNGroups $baseGroupDn -Username $bindUser -Password $domainBindPass - } - if (Get-IdentitySource -Server $ssoConnection | Where-Object { $_.Name -eq $domain }) { - Connect-VIServer -Server $ssoServer.fqdn -User $ssoServer.ssoAdmin -Password $ssoServer.ssoAdminPass | Out-Null - if ($DefaultVIServer.Name -eq $($ssoServer.fqdn)) { - $scriptCommand = '/opt/vmware/bin/sso-config.sh -set_default_identity_sources -i ' + $domain + '' - $output = Invoke-VMScript -VM $ssoServer.vmName -ScriptText $scriptCommand -GuestUser $ssoServer.root -GuestPassword $ssoServer.rootPass - Write-Output "Adding Identity Source to vCenter Server ($($ssoServer.fqdn)) named ($domain): SUCCESSFUL" + 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-SSOConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-SSOAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + if (!(Get-IdentitySource -Server $ssoConnectionDetail | Where-Object { $_.Name -eq $domain })) { + if (Test-Connection -ComputerName ($dcMachineName + "." + $domain) -Quiet -Count 1) { + if ($protocol -eq "ldaps") { + Add-LDAPIdentitySource -ServerType ActiveDirectory -Name $domain -DomainName $domain -DomainAlias $domainAlias -PrimaryUrl $primaryUrl -BaseDNUsers $baseUserDn -BaseDNGroups $baseGroupDn -Username $bindUser -Password $domainBindPass -Certificate $certificate + } + else { + Add-LDAPIdentitySource -ServerType ActiveDirectory -Name $domain -DomainName $domain -DomainAlias $domainAlias -PrimaryUrl $primaryUrl -BaseDNUsers $baseUserDn -BaseDNGroups $baseGroupDn -Username $bindUser -Password $domainBindPass + } + if (Get-IdentitySource -Server $ssoConnectionDetail | Where-Object { $_.Name -eq $domain }) { + if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + $scriptCommand = '/opt/vmware/bin/sso-config.sh -set_default_identity_sources -i ' + $domain + '' + Invoke-VMScript -VM $vcfVcenterDetails.vmName -ScriptText $scriptCommand -GuestUser $vcfVcenterDetails.root -GuestPassword $vcfVcenterDetails.rootPass | Out-Null + #$output = Invoke-VMScript -VM $vcfVcenterDetails.vmName -ScriptText $scriptCommand -GuestUser $vcfVcenterDetails.root -GuestPassword $vcfVcenterDetails.rootPass + Write-Output "Adding Identity Source to vCenter Server ($($vcfVcenterDetails.fqdn)) named ($domain): SUCCESSFUL" + } + } + } + else { + Write-Error "Adding Identity Source to vCenter Server ($($vcfVcenterDetails.fqdn)) named ($domain): POST_VALIDATION_FAILED" + } + Disconnect-VIServer -Server $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue | Out-Null + } + else { + Write-Error "Unable to communicate with Active Directory Domain Controller ($dcMachineName), check details: PRE_VALIDATION_FAILED" + } + Disconnect-SsoAdminServer -Server $vcfVcenterDetails.fqdn -WarningAction SilentlyContinue } else { - Write-Error "Unable to connect to vCenter Server ($($ssoServer.fqdn))" + Write-Warning "Adding Identity Source to vCenter Server ($($vcfVcenterDetails.fqdn)) named ($domain), already exists: SKIPPED" } } - else { - Write-Error "Adding Identity Source to vCenter Server ($($ssoServer.fqdn)) named ($domain): FAILED" - } - Disconnect-VIServer -Server $ssoServer.fqdn -Confirm:$false -WarningAction SilentlyContinue | Out-Null - } - else { - Write-Error "Unable to communicate with Active Directory Domain Controller ($dcMachineName), check details" } } - Disconnect-SsoAdminServer -Server $ssoServer.fqdn -WarningAction SilentlyContinue - } - else { - Write-Error "Unable to connect to vCenter Server ($($ssoServer.fqdn))" } } - else { - Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials" - } } Catch { Debug-ExceptionWriter -object $_ @@ -220,33 +215,86 @@ Function Add-IdentitySource { } Export-ModuleMember -Function Add-IdentitySource +Function Undo-IdentitySource { + <# + .SYNOPSIS + Removes Active Directory over LDAP/LDAPS as an Identity Provider from vCenter Server + + .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 + - Removes the Active Directory Domain as an Identity Provider if its present + + .EXAMPLE + Undo-IdentitySource -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo.rainpole.io + This example removes the sfo.rainpole.io domain as an Identity Provider from 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 + ) + + 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-SSOConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-SSOAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + if (Get-IdentitySource -Server $ssoConnectionDetail | Where-Object { $_.Name -eq $domain }) { + Get-IdentitySource -Server $ssoConnectionDetail | Where-Object { $_.Name -eq $domain } | Remove-IdentitySource | Out-Null + if (!(Get-IdentitySource -Server $ssoConnectionDetail | Where-Object { $_.Name -eq $domain })) { + Write-Output "Removing Identity Source from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($domain): SUCCESSFUL" + } + else { + Write-Error "Removing Identity Source from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($domain): POST_VALIDATION_FAILED" + } + Disconnect-SsoAdminServer -Server $vcfVcenterDetails.fqdn -WarningAction SilentlyContinue + } + else { + Write-Warning "Removing Identity Source from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($domain), does not exist: SKIPPED" + } + } + } + } + } + } + } + Catch { + Debug-ExceptionWriter -object $_ + } +} +Export-ModuleMember -Function Undo-IdentitySource + Function Add-SddcManagerRole { <# .SYNOPSIS - Assign SDDC Manager roles to a user/group + Assign SDDC Manager roles to a user/group - .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 to retrive the Management Domain vCenter Server - details from from the SDDC Manager inventory and then: + .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 - 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 - .EXAMPLE - Add-SddcManagerRole -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo.rainpole.io -domainBindUser svc-vsphere-ad -domainBindPass VMw@re1! -principal gg-vcf-admins -role ADMIN -type group - This example assigns the group gg-vcf-admins from domain sfo.rainpole.io the SDDC Manager role ADMIN - .EXAMPLE - Add-SddcManagerRole -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo.rainpole.io -domainBindUser svc-vsphere-ad -domainBindPass VMw@re1! -principal gg-vcf-operators -role OPERATOR -type group - This example assigns the group gg-vcf-operators from domain sfo.rainpole.io the SDDC Manager role OPERATOR + Add-SddcManagerRole -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo.rainpole.io -domainBindUser svc-vsphere-ad -domainBindPass VMw@re1! -principal gg-vcf-admins -role ADMIN -type group + This example assigns the group gg-vcf-admins from domain sfo.rainpole.io the SDDC Manager role ADMIN .EXAMPLE - Add-SddcManagerRole -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo.rainpole.io -domainBindUser svc-vsphere-ad -domainBindPass VMw@re1! -principal gg-vcf-viewers -role VIEWER -type group - This example assigns the group gg-vcf-viewers from domain sfo.rainpole.io the SDDC Manager role VIEWER - #> + Add-SddcManagerRole -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo.rainpole.io -domainBindUser svc-vsphere-ad -domainBindPass VMw@re1! -principal compliance -role OPERATOR -type user + This example assigns the user compliance from domain sfo.rainpole.io the SDDC Manager role OPERATOR + #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, @@ -265,66 +313,63 @@ Function Add-SddcManagerRole { if ($checkAdAuthentication[1] -match "Authentication Successful") { $securePass = ConvertTo-SecureString -String $domainBindPass -AsPlainText -Force $domainCreds = New-Object System.Management.Automation.PSCredential ($domainBindUser, $securePass) - Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null - if ($accessToken) { - $ssoServer = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT - $ssoConnection = Connect-SsoAdminServer -Server $ssoServer.fqdn -User $ssoServer.ssoAdmin -Password $ssoServer.ssoAdminPass - if ($DefaultSsoAdminServers.Name -eq $($ssoServer.fqdn)) { - if (Get-IdentitySource -Server $ssoConnection | Where-Object { $_.Name -eq $domain }) { - 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 ($type -eq "group") { - $vcfCheck = Get-VCFUser | Where-Object { $_.name -eq $($domain.ToUpper() + "\" + $principal) } - if ($vcfCheck.name -eq $($domain.ToUpper() + "\" + $principal)) { - Write-Warning "Assigning the role ($role) in SDDC Manager ($server) to Active Directory $type ($principal), already assigned: SKIPPED" - } - else { - New-VCFGroup -group $principal -domain $domain -role $role | Out-Null - $vcfCheck = Get-VCFUser | Where-Object { $_.name -eq $($domain.ToUpper() + "\" + $principal) } - if ($vcfCheck.name -eq $($domain.ToUpper() + "\" + $principal)) { - Write-Output "Assigning the role ($role) in SDDC Manager ($server) to Active Directory $type ($principal): SUCCESSFUL" + 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-SSOConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-SSOAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + 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 }) } + elseif ($type -eq "user") { $adObjectCheck = (Get-ADUser -Server $domain -Credential $domainCreds -Filter { SamAccountName -eq $principal }) } + if ($adObjectCheck) { + if ($type -eq "group") { + $vcfCheck = Get-VCFUser | Where-Object { $_.name -eq $($domain.ToUpper() + "\" + $principal) } + if ($vcfCheck.name -eq $($domain.ToUpper() + "\" + $principal)) { + Write-Warning "Assigning the role ($role) in SDDC Manager ($server) to Active Directory $type ($principal), already assigned: SKIPPED" + } + else { + New-VCFGroup -group $principal -domain $domain -role $role | Out-Null + $vcfCheck = Get-VCFUser | Where-Object { $_.name -eq $($domain.ToUpper() + "\" + $principal) } + if ($vcfCheck.name -eq $($domain.ToUpper() + "\" + $principal)) { + Write-Output "Assigning the role ($role) in SDDC Manager ($server) to Active Directory $type ($principal): SUCCESSFUL" + } + else { + Write-Error "Assigning the role ($role) in SDDC Manager ($server) to Active Directory $type ($principal): POST_VALIDATION_FAILED" + } + } + } + elseif ($type -eq "user") { + $vcfCheck = Get-VCFUser | Where-Object { $_.name -eq $($principal + "@" + $domain.ToUpper()) } + if ($vcfCheck.name -eq $($principal + "@" + $domain.ToUpper())) { + Write-Warning "Assigning the role ($role) in SDDC Manager ($server) to Active Directory $type ($principal), already assigned: SKIPPED" + } + else { + New-VCFUser -user ($principal + "@" + $domain.ToUpper()) -role $role | Out-Null + $vcfCheck = Get-VCFUser | Where-Object { $_.name -eq $($principal + "@" + $domain.ToUpper()) } + if ($vcfCheck.name -eq $($principal + "@" + $domain.ToUpper())) { + Write-Output "Assigning the role ($role) in SDDC Manager ($server) to Active Directory $type ($principal): SUCCESSFUL" + } + else { + Write-Error "Assigning the role ($role) in SDDC Manager ($server) to Active Directory $type ($principal): POST_VALIDATION_FAILED" + } + } + } } else { - Write-Error "Assigning the role ($role) in SDDC Manager ($server) to Active Directory $type ($principal): FAILED" + Write-Error "Unable to find $type ($principal) in the Active Directory Domain: PRE_VALIDATION_FAILED" } } - } - elseif ($type -eq "user") { - $vcfCheck = Get-VCFUser | Where-Object { $_.name -eq $($principal + "@" + $domain.ToUpper()) } - if ($vcfCheck.name -eq $($principal + "@" + $domain.ToUpper())) { - Write-Warning "Assigning the role ($role) in SDDC Manager ($server) to Active Directory $type ($principal), already assigned: SKIPPED" - } else { - New-VCFUser -user ($principal + "@" + $domain.ToUpper()) -role $role | Out-Null - $vcfCheck = Get-VCFUser | Where-Object { $_.name -eq $($principal + "@" + $domain.ToUpper()) } - if ($vcfCheck.name -eq $($principal + "@" + $domain.ToUpper())) { - Write-Output "Assigning the role ($role) in SDDC Manager ($server) to Active Directory $type ($principal): SUCCESSFUL" - } - else { - Write-Error "Assigning the role ($role) in SDDC Manager ($server) to Active Directory $type ($principal): FAILED" - } + Write-Error "Unable to find Identity Source in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($domain): PRE_VALIDATION_FAILED" } } } - else { - Write-Error "Active Directory $type ($principal) not found in the Active Directory Domain, create and retry" - } - } - else { - Write-Error "Unable to find Identity Source in vCenter Server ($($ssoServer.fqdn)) named ($domain)" } } - else { - Write-Error "Unable to connect to vCenter Server ($($ssoServer.fqdn))" - } - } - else { - Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials" } } else { - Write-Error "Unable to authenticate to Active Directory with user ($domainBindUser) and password ($domainBindPass), check details" + Write-Error "Unable to authenticate to Active Directory with user ($domainBindUser) and password ($domainBindPass), check details: PRE_VALIDATION_FAILED" } } Catch { @@ -333,21 +378,73 @@ Function Add-SddcManagerRole { } Export-ModuleMember -Function Add-SddcManagerRole +Function Undo-SddcManagerRole { + <# + .SYNOPSIS + Remove access for a user/group in SDDC Manager + + .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 + + .EXAMPLE + Undo-SddcManagerRole -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -principal gg-vcf-admins -type GROUP + This example removes access for the group gg-vcf-admins from 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]$principal, + [Parameter (Mandatory = $true)] [ValidateSet("GROUP","USER")] [String]$type + ) + + Try { + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (Get-VCFUser -type $type | Where-Object {$_.name -match $principal}) { + Remove-VCFUser -id (Get-VCFUser -type $type | Where-Object {$_.name -match $principal}).id + if (!(Get-VCFUser -type $type | Where-Object {$_.name -match $principal})) { + Write-Output "Removing $type from SDDC Manager ($server) named ($principal): SUCCESSFUL" + } + else { + Write-Error "Removing $type from SDDC Manager ($server) named ($principal): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Removing $type from SDDC Manager ($server) named ($principal), not assigned: SKIPPED" + } + } + } + } + Catch { + Debug-ExceptionWriter -object $_ + } +} +Export-ModuleMember -Function Undo-SddcManagerRole + Function Set-vCenterPasswordExpiration { <# .SYNOPSIS Set the password expiration for the root account - .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 to retrive the - Management Domain vCenter Server details from from the SDDC Manager inventory and then: - - Connects to the vCenter Server instance + .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 - 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 - .EXAMPLE - Set-vCenterPasswordExpiration -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -passwordExpires $true -email "admin@rainpole.io" -maxDaysBetweenPasswordChange 80 + .EXAMPLE + Set-vCenterPasswordExpiration -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -passwordExpires $true -email "administrator@rainpole.io" -maxDaysBetweenPasswordChange 999 This example configures the password expiration settings for the vCenter Server root account to expire after 80 days with email for warning set to "admin@rainpole.io" .EXAMPLE @@ -367,34 +464,33 @@ Function Set-vCenterPasswordExpiration { ) Try { - Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null - if ($accessToken) { - $vcenter = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain - Connect-VIServer -Server $vcenter.fqdn -User $vcenter.ssoAdmin -pass $vcenter.ssoAdminPass | Out-Null - Request-vSphereApiToken -Fqdn $vcenter.fqdn -Username $vcenter.ssoadmin -Password $vcenter.ssoAdminPass -admin | Out-Null - if ($DefaultVIServer.Name -eq $($vcenter.fqdn)) { - $pwdExpirySettings = Get-VCPasswordExpiry - if ($passwordExpires) { - Set-VCPasswordExpiry -passwordExpires $passwordExpires -email $email -maxDaysBetweenPasswordChange $maxDaysBetweenPasswordChange | Out-Null - } - else { - Set-VCPasswordExpiry -passwordExpires $passwordExpires | Out-Null - } - $pwdExpirySettings = Get-VCPasswordExpiry - if ($pwdExpirySettings.max_days_between_password_change -eq -1) { - Write-Output "Configured Password Expiry on vCenter Server Appliance ($($vcenter.fqdn)) to (Never Expire): 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)) { + Request-vSphereApiToken -Fqdn $vcfVcenterDetails.fqdn -Username $vcfVcenterDetails.ssoadmin -Password $vcfVcenterDetails.ssoAdminPass -admin | Out-Null + $pwdExpirySettings = Get-VCPasswordExpiry + if ($passwordExpires) { + Set-VCPasswordExpiry -passwordExpires $passwordExpires -email $email -maxDaysBetweenPasswordChange $maxDaysBetweenPasswordChange | Out-Null + } + else { + Set-VCPasswordExpiry -passwordExpires $passwordExpires | Out-Null + } + $pwdExpirySettings = Get-VCPasswordExpiry + if ($pwdExpirySettings.max_days_between_password_change -eq -1) { + Write-Output "Configured Password Expiry on vCenter Server Appliance ($($vcfVcenterDetails.fqdn)) to (Never Expire): SUCCESSFUL" + } + else { + Write-Output "Configured Password Expiry on vCenter Server Appliance ($($vcfVcenterDetails.fqdn)) to ($($pwdExpirySettings.max_days_between_password_change) days) and Email Notification to ($($pwdExpirySettings.email)): SUCCESSFUL" + } + } + } } else { - Write-Output "Configured Password Expiry on vCenter Server Appliance ($($vcenter.fqdn)) to ($($pwdExpirySettings.max_days_between_password_change) days) and Email Notification to ($($pwdExpirySettings.email)): SUCCESSFUL" + Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" } } - else { - Write-Error "Unable to connect to vCenter Server ($($vcenter.fqdn))" - } - Disconnect-VIServer $vcenter.fqdn -Confirm:$false -WarningAction SilentlyContinue - } - else { - Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials" } } Catch { @@ -406,21 +502,26 @@ Export-ModuleMember -Function Set-vCenterPasswordExpiration Function Set-EsxiPasswordPolicy { <# .SYNOPSIS - Set ESXi password polciies + Set ESXi password polciies - .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 and then: + .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 the workload domain exists in the SDDC Manager inventory - Gathers the ESXi hosts for the cluster specificed - Configured all ESXi hosts in he provided cluster - .EXAMPLE - Set-EsxiPasswordPolicy -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -cluster sfo-m01-cl01 -policy "retry=5 min=disabled,disabled,disabled,disabled,15" + EXAMPLE + Set-EsxiPasswordPolicy -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -cluster sfo-m01-cl01 -policy "retry=5 min=disabled,disabled,disabled,disabled,15" This example configures all ESXi hosts within the cluster named sfo-m01-cl01 of the workload domain sfo-m01 - #> + #> - Param ( + Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, @@ -431,46 +532,46 @@ Function Set-EsxiPasswordPolicy { ) Try { - Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null - if ($accessToken) { - $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)) { - $checkCluster = Get-Cluster | Where-Object {$_.Name -eq $cluster} - if ($checkCluster) { - $esxiHosts = Get-Cluster $cluster | Get-VMHost - $count = 0 - Foreach ($esxiHost in $esxiHosts) { - $advancedSetting = Get-VMHost | Where-Object { $_.ConnectionState -eq "Connected" } | Get-AdvancedSetting | Where-Object { $_.Name -eq "Security.PasswordQualityControl" } - if ($advancedSetting) { - Set-AdvancedSetting -AdvancedSetting $advancedSetting -Value $policy -Confirm:$false | Out-Null - $checkSetting = Get-VMHost | Where-Object { $_.ConnectionState -eq "Connected" } | Get-AdvancedSetting | Where-Object { $_.Name -eq "Security.PasswordQualityControl" } - if ($checkSetting -match $policy) { - if ($detail -eq "true") { - Write-Output "Updating Advanced System Setting (Security.PasswordQualityControl) on ESXi Host ($esxiHost): 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-Cluster | Where-Object {$_.Name -eq $cluster}) { + $esxiHosts = Get-Cluster $cluster | Get-VMHost + $count = 0 + Foreach ($esxiHost in $esxiHosts) { + if (($advancedSetting = Get-VMHost | Where-Object { $_.ConnectionState -eq "Connected" } | Get-AdvancedSetting | Where-Object { $_.Name -eq "Security.PasswordQualityControl" })) { + Set-AdvancedSetting -AdvancedSetting $advancedSetting -Value $policy -Confirm:$false | Out-Null + $checkSetting = Get-VMHost | Where-Object { $_.ConnectionState -eq "Connected" } | Get-AdvancedSetting | Where-Object { $_.Name -eq "Security.PasswordQualityControl" } + if ($checkSetting -match $policy) { + if ($detail -eq "true") { + Write-Output "Updating Advanced System Setting (Security.PasswordQualityControl) on ESXi Host ($esxiHost): SUCCESSFUL" + } + } + else { + Write-Error "Updating Advanced System Setting (Security.PasswordQualityControl) on ESXi Host ($esxiHost): POST_VALIDATION_FAILED" + } + } + $count = $count + 1 + } + if ($detail -eq "false") { + Write-Output "Updating Advanced System Setting (Security.PasswordQualityControl) on all ESXi Hosts for Workload Domain ($domain): SUCCESSFUL" + } } - } - else { - Write-Error "Updating Advanced System Setting (Security.PasswordQualityControl) on ESXi Host ($esxiHost): FAILED" + else { + Write-Error "Unable to find Cluster ($cluster) in vCenter Server ($($vcfVcenterDetails.fqdn)), check details and retry: PRE_VALIDATION_FOUND" + } + Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue } } - $count = $count + 1 - } - if ($detail -eq "false") { - Write-Output "Updating Advanced System Setting (Security.PasswordQualityControl) on all ESXi Hosts for Workload Domain ($domain): SUCCESSFUL" - } + } } else { - Write-Error "Unable to find Cluster ($cluster) in vCenter Server ($($vcenter.fqdn)), check details and retry" + Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" } } - else { - Write-Error "Unable to connect to vCenter Server ($($vcenter.fqdn))" - } - Disconnect-VIServer $vcenter.fqdn -Confirm:$false -WarningAction SilentlyContinue - } - else { - Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials" } } Catch { @@ -482,21 +583,23 @@ Export-ModuleMember -Function Set-EsxiPasswordPolicy Function Install-WorkspaceOne { <# .SYNOPSIS - Deploy Workspace ONE Access Virtual Appliance + Deploy Workspace ONE Access Virtual Appliance - .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 to retrive the - Management Domain vCenter Server details from from the SDDC Manager inventory and then: - - Connects to the Management Domain vCenter Server + .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 - Gathers DNS and NTP configuration from SDDC Manager - Deploys the Workspace ONE Access Virtual Appliance to the Management Domain vCenter Server - .EXAMPLE - Install-WorkspaceOne -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -wsaFqdn sfo-wsa01.sfo.rainpole.io -wsaIpAddress 192.168.31.60 -wsaGateway 192.168.31.1 -wsaSubnetMask 255.255.255.0 -wsaOvaPath F:\identity-manager.ova -wsaFolder sfo-m01-fd-wsa + .EXAMPLE + Install-WorkspaceOne -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -wsaFqdn sfo-wsa01.sfo.rainpole.io -wsaIpAddress 192.168.31.60 -wsaGateway 192.168.31.1 -wsaSubnetMask 255.255.255.0 -wsaOvaPath F:\identity-manager.ova -wsaFolder sfo-m01-fd-wsa This example deploys the Workspace ONE Access Virtual Appliance named sfo-wsa01.sfo.rainpole.io into the sfo-m01-fd-wsa folder of the management domain - #> + #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, @@ -520,99 +623,92 @@ Function Install-WorkspaceOne { Break } } - - Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null - if ($accessToken) { - $vcenter = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT - Connect-VIServer -Server $vcenter.fqdn -User $vcenter.ssoAdmin -pass $vcenter.ssoAdminPass | Out-Null - $wsaHostname = $wsaFqdn.Split(".")[0] - if ($DefaultVIServer.Name -eq $($vcenter.fqdn)) { - $wsaExists = Get-VM -Name $wsaHostname -ErrorAction Ignore - if ($wsaExists) { - Write-Warning "Deploying a virtual machine in vCenter Server ($($vcenter.fqdn)) named ($wsaHostname), already exists: SKIPPED" - } - else { - $dnsServer1 = (Get-VCFConfigurationDNS | Where-Object { $_.isPrimary -Match "True" }).ipAddress - $dnsServer2 = (Get-VCFConfigurationDNS | Where-Object { $_.isPrimary -Match "False" }).ipAddress - $cluster = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.type -eq "MANAGEMENT" }).clusters.id) }).Name - $datastore = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.type -eq "MANAGEMENT" }).clusters.id) }).primaryDatastoreName - $datacenter = (Get-Datacenter -Cluster $cluster).Name - $avnCheck = (Get-VCFApplicationVirtualNetwork | Where-Object { $_.regionType -eq "REGION_A" }).name - if ($avnCheck) { - $regionaPortgroup = (Get-VCFApplicationVirtualNetwork | Where-Object { $_.regionType -eq "REGION_A" }).name - $domain = (Get-VCFApplicationVirtualNetwork | Where-Object { $_.regionType -eq "REGION_A" }).domainName - - $command = '"C:\Program Files\VMware\VMware OVF Tool\ovftool.exe" --noSSLVerify --acceptAllEulas --allowAllExtraConfig --diskMode=thin --powerOn --name=' + $wsaHostname + ' --ipProtocol="IPv4" --ipAllocationPolicy="fixedAllocatedPolicy" --vmFolder=' + $wsaFolder + ' --net:"Network 1"=' + $regionaPortgroup + ' --datastore=' + $datastore + ' --X:injectOvfEnv --prop:vamitimezone=' + $timezone + ' --prop:vami.ip0.IdentityManager=' + $wsaIpAddress + ' --prop:vami.netmask0.IdentityManager=' + $wsaSubnetMask + ' --prop:vami.hostname=' + $wsaFqdn + ' --prop:vami.gateway.IdentityManager=' + $wsaGateway + ' --prop:vami.domain.IdentityManager=' + $domain + ' --prop:vami.searchpath.IdentityManager=' + $domain + ' --prop:vami.DNS.IdentityManager=' + $dnsServer1 + ',' + $dnsServer2 + ' "' + $wsaOvaPath + '" "vi://' + $vcenter.ssoAdmin + ':' + $vcenter.ssoAdminPass + '@' + $vcenter.fqdn + '/' + $datacenter + '/host/' + $cluster + '/"' - Invoke-Expression "& $command" -ErrorAction Ignore - $wsaExists = Get-VM -Name $wsaHostname -ErrorAction Ignore - if ($wsaExists) { - $Timeout = 900 ## seconds - $CheckEvery = 15 ## seconds - Try { - $timer = [Diagnostics.Stopwatch]::StartNew() ## Start the timer - Write-Output "Waiting for $wsaIpAddress to become pingable." - While (-not (Test-Connection -ComputerName $wsaIpAddress -Quiet -Count 1)) { - ## If the timer has waited greater than or equal to the timeout, throw an exception exiting the loop - if ($timer.Elapsed.TotalSeconds -ge $Timeout) { - Throw "Timeout Exceeded. Giving up on ping availability to $wsaIpAddress" - } - Start-Sleep -Seconds $CheckEvery ## Stop the loop every $CheckEvery seconds - } - } - Catch { - Write-Error "Failed to get a Response from Workspace ONE Access Instance ($wsaFqdn)" - } - Finally { - $timer.Stop() ## Stop the timer - } - $Timeout = 900 ## seconds - $CheckEvery = 5 ## seconds - Try { - $timer = [Diagnostics.Stopwatch]::StartNew() ## Start the timer - $uri = "https://" + $wsaFqdn + "/SAAS/jersey/manager/api/system/health" - Write-Output "Initial connection made, waiting for ($wsaFqdn) to fully boot and services to start. Be warned, this takes a long time." - While ($timer.Elapsed.TotalSeconds -lt $Timeout) { - ## If the timer has waited greater than or equal to the timeout, throw an exception exiting the loop - Try { - $response = Invoke-RestMethod $uri -Method 'GET' -SessionVariable webSession -ErrorAction Ignore - if ($response.AllOk -eq "true") { - Write-Output "Deploying Workspace ONE Access Instance ($wsaFqdn) using ($wsaOvaPath): SUCCESSFUL" - break + 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) { + $wsaHostname = $wsaFqdn.Split(".")[0] + if (Get-VM -Name $wsaHostname -ErrorAction Ignore) { + Write-Warning "Deploying a virtual machine in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($wsaHostname), already exists: SKIPPED" + } + else { + $dnsServer1 = (Get-VCFConfigurationDNS | Where-Object { $_.isPrimary -Match "True" }).ipAddress + $dnsServer2 = (Get-VCFConfigurationDNS | Where-Object { $_.isPrimary -Match "False" }).ipAddress + $cluster = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.type -eq "MANAGEMENT" }).clusters.id) }).Name + $datastore = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.type -eq "MANAGEMENT" }).clusters.id) }).primaryDatastoreName + $datacenter = (Get-Datacenter -Cluster $cluster).Name + $avnCheck = (Get-VCFApplicationVirtualNetwork | Where-Object { $_.regionType -eq "REGION_A" }).name + if ($avnCheck) { + $regionaPortgroup = (Get-VCFApplicationVirtualNetwork | Where-Object { $_.regionType -eq "REGION_A" }).name + $domain = (Get-VCFApplicationVirtualNetwork | Where-Object { $_.regionType -eq "REGION_A" }).domainName + $command = '"C:\Program Files\VMware\VMware OVF Tool\ovftool.exe" --noSSLVerify --acceptAllEulas --allowAllExtraConfig --diskMode=thin --powerOn --name=' + $wsaHostname + ' --ipProtocol="IPv4" --ipAllocationPolicy="fixedAllocatedPolicy" --vmFolder=' + $wsaFolder + ' --net:"Network 1"=' + $regionaPortgroup + ' --datastore=' + $datastore + ' --X:injectOvfEnv --prop:vamitimezone=' + $timezone + ' --prop:vami.ip0.IdentityManager=' + $wsaIpAddress + ' --prop:vami.netmask0.IdentityManager=' + $wsaSubnetMask + ' --prop:vami.hostname=' + $wsaFqdn + ' --prop:vami.gateway.IdentityManager=' + $wsaGateway + ' --prop:vami.domain.IdentityManager=' + $domain + ' --prop:vami.searchpath.IdentityManager=' + $domain + ' --prop:vami.DNS.IdentityManager=' + $dnsServer1 + ',' + $dnsServer2 + ' "' + $wsaOvaPath + '" "vi://' + $vcfVcenterDetails.ssoAdmin + ':' + $vcfVcenterDetails.ssoAdminPass + '@' + $vcfVcenterDetails.fqdn + '/' + $datacenter + '/host/' + $cluster + '/"' + Invoke-Expression "& $command" -ErrorAction Ignore + if (Get-VM -Name $wsaHostname -ErrorAction Ignore) { + $Timeout = 900 ## seconds + $CheckEvery = 15 ## seconds + Try { + $timer = [Diagnostics.Stopwatch]::StartNew() ## Start the timer + Write-Output "Waiting for $wsaIpAddress to become pingable." + While (-not (Test-Connection -ComputerName $wsaIpAddress -Quiet -Count 1)) { + ## If the timer has waited greater than or equal to the timeout, throw an exception exiting the loop + if ($timer.Elapsed.TotalSeconds -ge $Timeout) { + Throw "Timeout Exceeded. Giving up on ping availability to $wsaIpAddress" + } + Start-Sleep -Seconds $CheckEvery ## Stop the loop every $CheckEvery seconds + } + } + Catch { + Write-Error "Failed to get a Response from Workspace ONE Access Instance ($wsaFqdn): POST_VALIDATION_FAILURE" + } + Finally { + $timer.Stop() ## Stop the timer + } + $Timeout = 900 ## seconds + $CheckEvery = 5 ## seconds + Try { + $timer = [Diagnostics.Stopwatch]::StartNew() ## Start the timer + $uri = "https://" + $wsaFqdn + "/SAAS/jersey/manager/api/system/health" + Write-Output "Initial connection made, waiting for ($wsaFqdn) to fully boot and services to start. Be warned, this takes a long time." + While ($timer.Elapsed.TotalSeconds -lt $Timeout) { + ## If the timer has waited greater than or equal to the timeout, throw an exception exiting the loop + Try { + $response = Invoke-RestMethod $uri -Method 'GET' -SessionVariable webSession -ErrorAction Ignore + if ($response.AllOk -eq "true") { + Write-Output "Deploying Workspace ONE Access Instance ($wsaFqdn) using ($wsaOvaPath): SUCCESSFUL" + break + } + } + Catch { + Write-Output "Waiting for ($wsaFqdn) to fully boot up. Checking every $CheckEvery seconds" + } + Start-Sleep -Seconds $CheckEvery ## Stop the loop every $CheckEvery seconds + } + if ($timer.Elapsed.TotalSeconds -ge $Timeout) { + Write-Error "Workspace ONE Access Instance ($wsaFqdn) failed to initialize properly. Please delete the VM from vCenter Server ($($vcfVcenterDetails.fqdn)) and retry: POST_VAIDATION_FAILED" + } + } + Catch { + Debug-ExceptionWriter -object $_ + } + Finally { + $timer.Stop() ## Stop the timer } } - Catch { - Write-Output "Waiting for ($wsaFqdn) to fully boot up. Checking every $CheckEvery seconds" + else { + Write-Error "Deployment of Workspace ONE Access Instance ($wsaFqdn): POST_VALIDATION_FAILED" } - Start-Sleep -Seconds $CheckEvery ## Stop the loop every $CheckEvery seconds } - if ($timer.Elapsed.TotalSeconds -ge $Timeout) { - Write-Error "Workspace ONE Access Instance ($wsaFqdn) failed to initialize properly. Please delete the VM from vCenter Server ($($vcenter.fqdn)) and retry" + else { + Write-Error "Application Virtual Networks have not been configured in SDDC Manager ($server), unable to find REGION_A details. Deploy and try again: PRE_VALIDATION_FAILED" } } - Catch { - Debug-ExceptionWriter -object $_ - } - Finally { - $timer.Stop() ## Stop the timer - } - } - else { - Write-Error "Deployment of Workspace ONE Access Instance ($wsaFqdn): FAILED" + Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue } } - else { - Write-Error "Application Virtual Networks have not been configured in SDDC Manager ($server), unable to find REGION_A details. Deploy and try again" - } } - Disconnect-VIServer $vcenter.fqdn -Confirm:$false -WarningAction SilentlyContinue - } - else { - Write-Error "Unable to connect to vCenter Server ($($vcenter.fqdn))" } } - else { - Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials" - } } Catch { Debug-ExceptionWriter -object $_ @@ -623,20 +719,21 @@ Export-ModuleMember -Function Install-WorkspaceOne Function Initialize-WorkspaceOne { <# .SYNOPSIS - Initalize Workspace ONE Access Virtual Appliance + Initalize Workspace ONE Access Virtual Appliance - .DESCRIPTION - The Initialize-WorkspaceOne cmdlet performs the initial configuration of Workspace ONE Access Virtual Appliance. + .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 - Sets the default password for the admin, root and SSH Users - Initializes the internal PostgrsSQL database - Activates the default connector - .EXAMPLE - Initialize-WorkspaceOne -wsaFqdn sfo-wsa01.sfo.rainpole.io -adminPass VMw@re1! -rootPass VMw@re1! -sshUserPass VMw@re1! + .EXAMPLE + Initialize-WorkspaceOne -wsaFqdn sfo-wsa01.sfo.rainpole.io -adminPass VMw@re1! -rootPass VMw@re1! -sshUserPass VMw@re1! This example initialzes the Workspace ONE Access Virtual Appliance sfo-wsa01.sfo.rainpole.io and sets the default passwords for admin, root and SSH User - #> + #> - Param ( + Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaFqdn, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$adminPass, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$rootPass, @@ -644,36 +741,38 @@ Function Initialize-WorkspaceOne { ) Try { - $baseUri = "https://" + $wsaFqdn + ":8443" - $uri = $baseUri + "/login" - $response = Invoke-RestMethod $uri -Method 'GET' -SessionVariable webSession - $response | Out-File wsaResponse.txt - $tokenSource = (Select-String -Path wsaResponse.txt -Pattern 'window.ec_wiz.vk =') - $token = ($tokenSource -Split ("'"))[1] - Remove-Item wsaResponse.txt - if ($token) { - $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" - $headers.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8") - $headers.Add("X-Vk", "$token") - $headers.Add("Accept", "application/json") - # Set the Admin Password - $body = "password=" + $adminPass + "&confpassword=" + $adminPass - $uri = $baseUri + "/cfg/changePassword" - Invoke-RestMethod $uri -Method 'POST' -Headers $headers -Body $body -WebSession $webSession | Out-Null - # Set the Root & SSHUser Passwords - $body = "rootPassword=" + $rootPass + "&sshuserPassword=" + $sshUserPass - $uri = $baseUri + "/cfg/system" - Invoke-RestMethod $uri -Method 'POST' -Headers $headers -Body $body -WebSession $webSession | Out-Null - # Initalize the Internal Database - $uri = $baseUri + "/cfg/setup/initialize" - Invoke-RestMethod $uri -Method 'POST' -Headers $headers -WebSession $webSession | Out-Null - # Activate the default connector - $uri = $baseUri + "/cfg/setup/activateConnector" - Invoke-RestMethod $uri -Method 'POST' -Headers $headers -WebSession $webSession | Out-Null - Write-Output "Initial Configuration of Workspace ONE Access Instance ($wsaFqdn): SUCCESSFUL" - } - else { - Write-Warning "Initial Configuration of Workspace ONE Access Instance ($wsaFqdn), already performed: SKIPPED" + if (Test-WSAConnection -server $wsaFqdn) { + $baseUri = "https://" + $wsaFqdn + ":8443" + $uri = $baseUri + "/login" + $response = Invoke-RestMethod $uri -Method 'GET' -SessionVariable webSession + $response | Out-File wsaResponse.txt + $tokenSource = (Select-String -Path wsaResponse.txt -Pattern 'window.ec_wiz.vk =') + $token = ($tokenSource -Split ("'"))[1] + Remove-Item wsaResponse.txt + if ($token) { + $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" + $headers.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8") + $headers.Add("X-Vk", "$token") + $headers.Add("Accept", "application/json") + # Set the Admin Password + $body = "password=" + $adminPass + "&confpassword=" + $adminPass + $uri = $baseUri + "/cfg/changePassword" + Invoke-RestMethod $uri -Method 'POST' -Headers $headers -Body $body -WebSession $webSession | Out-Null + # Set the Root & SSHUser Passwords + $body = "rootPassword=" + $rootPass + "&sshuserPassword=" + $sshUserPass + $uri = $baseUri + "/cfg/system" + Invoke-RestMethod $uri -Method 'POST' -Headers $headers -Body $body -WebSession $webSession | Out-Null + # Initalize the Internal Database + $uri = $baseUri + "/cfg/setup/initialize" + Invoke-RestMethod $uri -Method 'POST' -Headers $headers -WebSession $webSession | Out-Null + # Activate the default connector + $uri = $baseUri + "/cfg/setup/activateConnector" + Invoke-RestMethod $uri -Method 'POST' -Headers $headers -WebSession $webSession | Out-Null + Write-Output "Initial Configuration of Workspace ONE Access Instance ($wsaFqdn): SUCCESSFUL" + } + else { + Write-Warning "Initial Configuration of Workspace ONE Access Instance ($wsaFqdn), already performed: SKIPPED" + } } } Catch { @@ -685,16 +784,24 @@ Export-ModuleMember -Function Initialize-WorkspaceOne Function Set-WorkspaceOneNtpConfig { <# .SYNOPSIS - Configure NTP Server on Workspace ONE Access Appliance + Configure NTP Server on Workspace ONE Access Appliance - .DESCRIPTION - The Set-WorkspaceOneNtpConfig cmdlet configures the NTP Server details of the Workspace ONE Access Appliance - using the same NTP Server configuration as SDDC Manager + .DESCRIPTION + 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 + - 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! + .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 - #> + #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, @@ -705,48 +812,42 @@ Function Set-WorkspaceOneNtpConfig { ) Try { - Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null - if ($accessToken) { - $vcenter = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT - if (Test-Connection -ComputerName ($wsaFqdn) -Quiet -Count 1) { - Connect-VIServer -Server $vcenter.fqdn -User $vcenter.ssoAdmin -pass $vcenter.ssoAdminPass | Out-Null - if ($DefaultVIServer.Name -eq $($vcenter.fqdn)) { - $ntpServer = (Get-VCFConfigurationNTP).ipAddress - $vmName = $wsaFqdn.Split(".")[0] - if ($checkVm = (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 $vcenter.fqdn - if (($output.ScriptOutput).Contains($ntpServer)) { - Write-Warning "Configuring NTP on Workspace ONE Access Instance ($vmName) to NTP Server ($ntpServer), already performed: SKIPPED" - } - else { - $scriptCommand = '/usr/local/horizon/scripts/ntpServer.hzn --set ' + $ntpServer - $output = Invoke-VMScript -VM $vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $rootPass -Server $vcenter.fqdn - $scriptCommand = '/usr/local/horizon/scripts/ntpServer.hzn --get' - $output = Invoke-VMScript -VM $vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $rootPass -Server $vcenter.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): FAILED" + 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) { + $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 { + $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" + } + } + } + else { + Write-Error "Unable to local a virtual machine named ($vmName) in vCenter Server ($($vcfVcenterDetails.fqdn)) inventory: PRE_VALIDATION_FAILED" + } + Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue } } } - else { - Write-Error "A virtual machine with name ($vmName) not found in vCenter Server ($($vcenter.fqdn))" - } - Disconnect-VIServer $vcenter.fqdn -Confirm:$false -WarningAction SilentlyContinue - } - else { - Write-Error "Unable to connect to vCenter Server ($($vcenter.fqdn))" } } - else { - Write-Error "Unable to communicate with Workspace ONE Access Instance ($wsaFqdn), check fqdn/ip address" - } - } - else { - Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials" } } Catch { @@ -758,15 +859,22 @@ Export-ModuleMember -Function Set-WorkspaceOneNtpConfig Function Install-WorkspaceOneCertificate { <# .SYNOPSIS - Install a Signed Certificate on Workspace ONE Access Appliance + Install a Signed Certificate on Workspace ONE Access Appliance - .DESCRIPTION - The Install-WorkspaceOneCertificate cmdlet replaces the certificate on the Workspace ONE Access + .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 + - Copies over the certificate files to the Workspace ONE Access appliance and installs the certificate - .EXAMPLE - Install-WorkspaceOneCertificate -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -wsaFqdn sfo-wsa01.sfo.rainpole.io -rootPass VMw@re1! -sshUserPass VMw@re1! + .EXAMPLE + Install-WorkspaceOneCertificate -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -wsaFqdn sfo-wsa01.sfo.rainpole.io -rootPass VMw@re1! -sshUserPass VMw@re1! This example install the Workspace ONE Access Virtual Appliance sfo-wsa01.sfo.rainpole.io with a the signed certificate provided - #> + #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, @@ -812,28 +920,26 @@ Function Install-WorkspaceOneCertificate { } } - Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null - if ($accessToken) { - $vcenter = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT - Connect-VIServer -Server $vcenter.fqdn -User $vcenter.ssoAdmin -pass $vcenter.ssoAdminPass | Out-Null - if ($DefaultVIServer.Name -eq $($vcenter.fqdn)) { - $vmName = $wsaFqdn.Split(".")[0] - Get-Item $rootCa | Copy-VMGuestFile -Destination '/tmp' -VM $vmName -LocalToGuest -GuestUser root -GuestPassword $rootPass -Force - Get-Item $wsaCertKey | Copy-VMGuestFile -Destination '/tmp' -VM $vmName -LocalToGuest -GuestUser root -GuestPassword $rootPass -Force - Get-Item $wsaCert | Copy-VMGuestFile -Destination '/tmp' -VM $vmName -LocalToGuest -GuestUser root -GuestPassword $rootPass -Force - - $scriptCommand = 'echo "yes" | /usr/local/horizon/scripts/installExternalCertificate.hzn --ca /tmp/' + (Split-Path -Leaf $rootCa) + ' --cert /tmp/' + (Split-Path -Leaf $wsaCert) + ' --key /tmp/' + (Split-Path -Leaf $wsaCertKey) - $output = Invoke-VMScript -VM $vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $rootPass -Server $vcenter.fqdn - Write-Output "Installing Signed Certifcate on Workspace ONE Access Instance ($wsaFqdn) using ($wsaCert): SUCCESSFUL" - Disconnect-VIServer $vcenter.fqdn -Confirm:$false -WarningAction SilentlyContinue - } - else { - Write-Error "Unable to connect to vCenter Server ($($vcenter.fqdn))" + 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) { + $vmName = $wsaFqdn.Split(".")[0] + Get-Item $rootCa | Copy-VMGuestFile -Destination '/tmp' -VM $vmName -LocalToGuest -GuestUser root -GuestPassword $rootPass -Force + Get-Item $wsaCertKey | Copy-VMGuestFile -Destination '/tmp' -VM $vmName -LocalToGuest -GuestUser root -GuestPassword $rootPass -Force + Get-Item $wsaCert | Copy-VMGuestFile -Destination '/tmp' -VM $vmName -LocalToGuest -GuestUser root -GuestPassword $rootPass -Force + $scriptCommand = 'echo "yes" | /usr/local/horizon/scripts/installExternalCertificate.hzn --ca /tmp/' + (Split-Path -Leaf $rootCa) + ' --cert /tmp/' + (Split-Path -Leaf $wsaCert) + ' --key /tmp/' + (Split-Path -Leaf $wsaCertKey) + $output = Invoke-VMScript -VM $vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $rootPass -Server $vcenter.fqdn + Write-Output "Installing Signed Certifcate on Workspace ONE Access Instance ($wsaFqdn) using ($wsaCert): SUCCESSFUL" + Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue + } + } + } + } } } - else { - Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials" - } } Catch { Debug-ExceptionWriter -object $_ @@ -844,15 +950,19 @@ Export-ModuleMember -Function Install-WorkspaceOneCertificate Function Set-WorkspaceOneSmtpConfig { <# .SYNOPSIS - Configure SMTP Server on Workspace ONE Access Appliance - - .DESCRIPTION - The Set-WorkspaceOneSmtpConfig cmdlet configures the SMTP Server details of the Workspace ONE Access Appliance + Configure SMTP Server on Workspace ONE Access Appliance + + .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 + - Configures the SMTP Server settings - .EXAMPLE - Set-WorkspaceOneSmtpConfig -server sfo-wsa01.sfo.rainpole.io -user admin -pass VMw@re1! -smtpFqdn smtp.sfo.rainpole.io -smtpPort 25 -smtpEmail sfo-wsa@rainpole.io + .EXAMPLE + Set-WorkspaceOneSmtpConfig -server sfo-wsa01.sfo.rainpole.io -user admin -pass VMw@re1! -smtpFqdn smtp.sfo.rainpole.io -smtpPort 25 -smtpEmail sfo-wsa@rainpole.io This example configures the Workspace ONE Access Virtual Appliance sfo-wsa01.sfo.rainpole.io with the SMTP Server details - #> + #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, @@ -861,32 +971,30 @@ Function Set-WorkspaceOneSmtpConfig { [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$smtpFqdn, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$smtpPort, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$smtpEmail, - [Parameter (Mandatory = $false)] [String]$smtpEmailPassword + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$smtpEmailPassword ) Try { - Request-WSAToken -fqdn $server -user $user -pass $pass | Out-Null - if ($sessionToken) { - if (!(Get-WSASmtpConfiguration | Where-Object {$_.host -eq $smtpFqdn})) { - if (-not $PsBoundParameters.ContainsKey("smtpEmailPassword")) { - Set-WSASmtpConfiguration -fqdn $smtpFqdn -port $smtpPort -user $smtpEmail | Out-Null - } - if ($PsBoundParameters.ContainsKey("smtpEmailPassword")) { - Set-WSASmtpConfiguration -fqdn $smtpFqdn -port $smtpPort -user $smtpEmail -pass $smtpEmailPassword | Out-Null - } + if (Test-WSAConnection -server $server) { + if (Test-WSAAuthentication -server $server -user $user -pass $pass) { if (!(Get-WSASmtpConfiguration | Where-Object {$_.host -eq $smtpFqdn})) { - Write-Output "Configuring SMTP Server for Workspace ONE Access Instance ($server) with SMTP Server ($smtpFqdn): SUCCESSFUL" + if (-not $PsBoundParameters.ContainsKey("smtpEmailPassword")) { + Set-WSASmtpConfiguration -fqdn $smtpFqdn -port $smtpPort -user $smtpEmail | Out-Null + } + if ($PsBoundParameters.ContainsKey("smtpEmailPassword")) { + Set-WSASmtpConfiguration -fqdn $smtpFqdn -port $smtpPort -user $smtpEmail -pass $smtpEmailPassword | Out-Null + } + if (Get-WSASmtpConfiguration | Where-Object {$_.host -eq $smtpFqdn}) { + Write-Output "Configuring SMTP Server for Workspace ONE Access Instance ($server) with SMTP Server ($smtpFqdn): SUCCESSFUL" + } + else { + Write-Error "Configuring SMTP Server for Workspace ONE Access Instance ($server) with SMTP Server ($smtpFqdn): POST_VALIDATION_FAILED" + } } else { - Write-Error "Configuring SMTP Server for Workspace ONE Access Instance ($server) with SMTP Server ($smtpFqdn): FAILED" + Write-Warning "Configuring SMTP Server for Workspace ONE Access Instance ($server) with SMTP Server ($smtpFqdn), already exists: SKIPPED" } } - else { - Write-Warning "Configuring SMTP Server for Workspace ONE Access Instance ($server) with SMTP Server ($smtpFqdn), already exists: SKIPPED" - } - } - else { - Write-Error "Unable to obtain access token for Workspace ONE Access Instance ($wsaFqdn), check credentials" } } Catch { @@ -898,17 +1006,22 @@ Export-ModuleMember -Function Set-WorkspaceOneSmtpConfig Function Add-WorkspaceOneDirectory { <# .SYNOPSIS - Configure Active Directory LDAP Directory in Workspace ONE Access Appliance + Configure Active Directory LDAP Directory in Workspace ONE Access Appliance - .DESCRIPTION - The Add-WorkspaceOneDirectory cmdlet configures Active Directory LDAP Directory in Workspace ONE Access Appliance + .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 the bind user can authenticate to the domain + - Creates an identity provider within Workspace ONE Access - .EXAMPLE - Add-WorkspaceOneDirectory -server sfo-wsa01.sfo.rainpole.io -user admin -pass VMw@re1! -domain sfo.rainpole.io -baseDnUser "OU=Security Users,DC=sfo,DC=rainpole,DC=io" -baseDnGroup "OU=Security Groups,DC=sfo,DC=rainpole,DC=io" -bindUserDn "CN=svc-wsa-ad,OU=Security Users,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" + .EXAMPLE + Add-WorkspaceOneDirectory -server sfo-wsa01.sfo.rainpole.io -user admin -pass VMw@re1! -domain sfo.rainpole.io -baseDnUser "OU=Security Users,DC=sfo,DC=rainpole,DC=io" -baseDnGroup "OU=Security Groups,DC=sfo,DC=rainpole,DC=io" -bindUserDn "CN=svc-wsa-ad,OU=Security Users,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 configures the domain sfo.rainpole.io as a directory source in Workspace ONE Access Virtual Appliance and syncronises the groups provided - #> + #> - Param ( + Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, @@ -933,76 +1046,70 @@ Function Add-WorkspaceOneDirectory { } Try { - Request-WSAToken -fqdn $server -user $user -pass $pass | Out-Null - if ($sessionToken) { - $checkAdAuthentication = Test-ADAuthentication -user ($bindUserDn.Split(",")[0]).Split("=")[1] -pass $bindUserPass -server $domain -domain $domain - if ($checkAdAuthentication -contains "2") { - $checkDirectoryExist = Get-WSADirectory | Where-Object { ($_.name -eq $domain) } - if (!$checkDirectoryExist) { - if ($protocol -eq "ldaps") { - $directory = Add-WSALdapDirectory -domainName $domain -baseDn $baseDnUser -bindDn $bindUserDn -certificate $certificate - } - else{ - $directory = Add-WSALdapDirectory -domainName $domain -baseDn $baseDnUser -bindDn $bindUserDn - } - $connector = Get-WSAConnector | Where-Object {$_.host -eq $wsaFqdn} - Set-WSABindPassword -directoryId $directory.directoryConfigId -connectorId $connector.instanceId -pass $bindUserPass | Out-Null - $adUserJson = '{ "identityUserInfo": { "' + $bindUserDn + '": { "selected": true }, "' + $baseDnUser + '": { "selected": true }}}' - $mappedGroupObject = @() - foreach ($group in $adGroups) { - $adGroupDetails = Get-ADPrincipalGuid -domain $domain -user ($bindUserDn.Split(',')[0]).Split('=')[1] -pass $bindUserPass -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 + if (Test-WSAConnection -server $server) { + if (Test-WSAAuthentication -server $server -user $user -pass $pass) { + $checkAdAuthentication = Test-ADAuthentication -user ($bindUserDn.Split(",")[0]).Split("=")[1] -pass $bindUserPass -server $domain -domain $domain -ErrorAction SilentlyContinue + if ($checkAdAuthentication[1] -match "Authentication Successful") { + if (!(Get-WSADirectory | Where-Object { ($_.name -eq $domain) })) { + if ($protocol -eq "ldaps") { + $directory = Add-WSALdapDirectory -domainName $domain -baseDn $baseDnUser -bindDn $bindUserDn -certificate $certificate + } + else{ + $directory = Add-WSALdapDirectory -domainName $domain -baseDn $baseDnUser -bindDn $bindUserDn + } + $connector = Get-WSAConnector | Where-Object {$_.host -eq $server} + Set-WSABindPassword -directoryId $directory.directoryConfigId -connectorId $connector.instanceId -pass $bindUserPass | Out-Null + $adUserJson = '{ "identityUserInfo": { "' + $bindUserDn + '": { "selected": true }, "' + $baseDnUser + '": { "selected": true }}}' + $mappedGroupObject = @() + foreach ($group in $adGroups) { + $adGroupDetails = Get-ADPrincipalGuid -domain $domain -user ($bindUserDn.Split(',')[0]).Split('=')[1] -pass $bindUserPass -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: PRE_VALIDATION_FAILED" } } - else { - Write-Error "Group $group is not available in Active Directory Domain" + $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 + Set-WSADirectoryUser -directoryId $directory.directoryConfigId -json $adUserJson | Out-Null + Set-WSADirectoryGroup -directoryId $directory.directoryConfigId -json $adGroupJson | Out-Null + Set-WSASyncSetting -directoryId $directory.directoryConfigId | Out-Null + Start-WSADirectorySync -directoryId $directory.directoryConfigId | Out-Null + Write-Output "Creating Active Directory ($($protocol.ToUpper())) Directory in Workspace ONE Access Instance ($server) named ($domain): SUCCESSFUL" } - $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 + else { + Write-Warning "Creating Active Directory ($($protocol.ToUpper())) Directory in Workspace ONE Access Instance ($server) named ($domain), already exists: SKIPPED" } - $adGroupJson = $adGroupObject | ConvertTo-Json -Depth 10 - - #$adUserJson - #$adGroupJson - Set-WSADirectoryUser -directoryId $directory.directoryConfigId -json $adUserJson | Out-Null - Set-WSADirectoryGroup -directoryId $directory.directoryConfigId -json $adGroupJson | Out-Null - Set-WSASyncSetting -directoryId $directory.directoryConfigId | Out-Null - Start-WSADirectorySync -directoryId $directory.directoryConfigId | Out-Null - Write-Output "Creating Active Directory ($($protocol.ToUpper())) Directory in Workspace ONE Access Instance ($server) named ($domain): SUCCESSFUL" } else { - Write-Warning "Creating Active Directory ($($protocol.ToUpper())) Directory in Workspace ONE Access Instance ($server) named ($domain), already exists: SKIPPED" + Write-Error "Authenticating as Active Directory Domain User ($(($bindUserDn.Split(",")[0]).Split("=")[1])): PRE_VALIDATION_FAILED" } } - else { - Write-Error "Authenticating as Active Directory Domain User ($domainJoinUser): FAILED" - } - } - else { - Write-Error "Unable to obtain access token for Workspace ONE Access Instance ($wsaFqdn), check credentials" } } Catch { @@ -1014,21 +1121,25 @@ Export-ModuleMember -Function Add-WorkspaceOneDirectory Function Set-WorkspaceOneNsxtIntegration { <# .SYNOPSIS - Integrate NSX Manager with Workspace ONE Access + Integrate NSX Manager with Workspace ONE Access - .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 to retrive the NSX Manager - details from the SDDC Manager inventory and then: - - Connects to the NSX Manager instance - - Connects to the Workspace ONE Access intance + .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 - Enables the integration between NSX Manager and Workspace ONE Access - .EXAMPLE - Set-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! + .EXAMPLE + Set-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 integrates the Management Domain NSX Manager instance with Workspace ONE Access - #> + #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, @@ -1041,57 +1152,54 @@ Function Set-WorkspaceOneNsxtIntegration { ) Try { - Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null - if ($accessToken) { - $nsxtManagerDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain - Request-NsxToken -fqdn $nsxtManagerDetails.fqdn -username $nsxtManagerDetails.adminUser -password $nsxtManagerDetails.AdminPass | Out-Null - if ($nsxtHeaders.Authorization) { - $clientId = $nsxtManagerDetails.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 - } - Request-WSAToken -fqdn $wsaFqdn -user $wsaUser -pass $wsaPass | Out-Null - if ($sessionToken) { - $sharedSecret = (Get-WSAOAuthToken).message - $clientExists = Get-WSAClient | Where-Object { $_.clientId -eq $clientId } - if (!$clientExists) { - Add-WSAClient -clientId $clientId -sharedSecret $sharedSecret | Out-Null - $clientExists = Get-WSAClient | Where-Object { $_.clientId -eq $clientId } - if ($clientExists) { - Write-Output "Creating Service Client in Workspace ONE Access Instance ($wsaFqdn) named ($clientId): SUCCESSFUL" - } - else { - Write-Error "Creating Service Client in Workspace ONE Access Instance ($wsaFqdn) named ($clientId): FAILED" - Break + 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) { + $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-WSAClient | Where-Object { $_.clientId -eq $clientId })) { + Add-WSAClient -clientId $clientId -sharedSecret $sharedSecret | Out-Null + if (Get-WSAClient | Where-Object { $_.clientId -eq $clientId }) { + Write-Output "Creating Service Client in Workspace ONE Access Instance ($wsaFqdn) named ($clientId): SUCCESSFUL" + } + else { + Write-Error "Creating Service Client in Workspace ONE Access Instance ($wsaFqdn) named ($clientId): POST_VALIDATION_FAILED" + Break + } + } + else { + Write-Warning "Creating Service Client in Workspace ONE Access Instance ($wsaFqdn) named ($clientId), already exists: SKIPPED" + } + if (Get-NsxtVidm) { + $clientIdSecret = (Get-WSAClient -clientId $clientId).secret + Set-NsxtVidm -wsaHostname $wsaFqdn -thumbprint $wsaThumbprint -clientId $clientId -sharedSecret $clientIdSecret -nsxHostname $vcfNsxDetails.fqdn | Out-Null + Write-Output "Updating integration between NSX Manager ($($vcfNsxDetails.fqdn)) and Workspace ONE Acccess Instance ($wsaFqdn): SUCCESSFUL" + } + else { + Set-NsxtVidm -wsaHostname $wsaFqdn -thumbprint $wsaThumbprint -clientId $clientId -sharedSecret $sharedSecret -nsxHostname $vcfNsxDetails.fqdn | Out-Null + Write-Output "Creating integration between NSX Manager ($($vcfNsxDetails.fqdn)) and Workspace ONE Acccess Instance ($wsaFqdn): SUCCESSFUL" + } + } + } + } } } - else { - Write-Warning "Creating Service Client in Workspace ONE Access Instance ($wsaFqdn) named ($clientId), already exists: SKIPPED" - } - $vidmExists = Get-NsxtVidm - if ($vidmExists) { - $clientIdSecret = (Get-WSAClient -clientId $clientId).secret - Set-NsxtVidm -wsaHostname $wsaFqdn -thumbprint $wsaThumbprint -clientId $clientId -sharedSecret $clientIdSecret -nsxHostname $nsxtManagerDetails.fqdn | Out-Null - Write-Output "Updating integration between NSX Manager ($($nsxtManagerDetails.fqdn)) and Workspace ONE Acccess Instance ($wsaFqdn): SUCCESSFUL" - } - else { - Set-NsxtVidm -wsaHostname $wsaFqdn -thumbprint $wsaThumbprint -clientId $clientId -sharedSecret $sharedSecret -nsxHostname $nsxtManagerDetails.fqdn | Out-Null - Write-Output "Creating integration between NSX Manager ($($nsxtManagerDetails.fqdn)) and Workspace ONE Acccess Instance ($wsaFqdn): SUCCESSFUL" - } } else { - Write-Error "Unable to obtain access token from Workspace ONE Access Instance ($wsaFqdn), check credentials" + 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 NSX Manager ($($nsxtManagerDetails.fqdn)), check credentials" - } - } - else { - Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials" } } Catch { @@ -1100,66 +1208,77 @@ Function Set-WorkspaceOneNsxtIntegration { } Export-ModuleMember -Function Set-WorkspaceOneNsxtIntegration -Function Add-NsxtVidmGroupRole { +Function Add-NsxtVidmRole { <# - .SYNOPSIS - Configure Role-Based Access Control for NSX Manager + .SYNOPSIS + Configure Role-Based Access Control for NSX Manager - .DESCRIPTION - The Add-NsxtVidmGroupRole cmdlet configures role assignments in NSX Manager. The cmdlet connects to SDDC - Manager using the -server, -user, and -password values to retrive the NSX Manager details from the SDDC Manager - inventory and then: - - Connects to the NSX Manager instance - - Assigns Active Directory groups to NSX Manager roles + .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 + - Assigns Active Directory users or groups to NSX Manager roles based on the -type, -principal, and -role values. - .EXAMPLE - Add-NsxtVidmGroupRole -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -group "gg-nsx-enterprise-admins@sfo.rainpole.io" -role enterprise_admin - This example assigns the gg-nsx-enterprise-admins@sfo.rainpole.io group with the enterprise_admin role in NSX Manager - #> + .EXAMPLE + Add-NsxtVidmRole -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -type group -principal "gg-nsx-enterprise-admins@sfo.rainpole.io" -role enterprise_admin + This example assigns the group gg-nsx-enterprise-admins@sfo.rainpole.io with the enterprise_admin role in NSX Manager + .EXAMPLE + 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, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$group, - [Parameter (Mandatory = $true)] [ValidateSet("lb_admin", "security_engineer", "vpn_admin", "network_op", "netx_partner_admin", "gi_partner_admin", "security_op", "network_engineer", "lb_auditor", "auditor", "enterprise_admin")] [string]$role + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$principal, + [Parameter (Mandatory = $true)] [ValidateSet("group", "user")] [String]$type, + [Parameter (Mandatory = $true)] [ValidateSet("auditor", "enterprise_admin", "gi_partner_admin", "lb_admin", "lb_auditor", "network_engineer", "network_op", "netx_partner_admin", "security_engineer", "security_op", "vpn_admin")] [string]$role ) - Try { - Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null - if ($accessToken) { - $nsxtManagerDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain - Request-NsxToken -fqdn $nsxtManagerDetails.fqdn -username $nsxtManagerDetails.adminUser -password $nsxtManagerDetails.AdminPass | Out-Null - if ($nsxtHeaders.Authorization) { - $groupExists = Get-NsxtUser | Where-Object { $_.name -eq $group } - if (!$groupExists) { - Set-NsxtRole -principal $group -type remote_group -role $role -identitySource VIDM | Out-Null - $groupExists = Get-NsxtUser | Where-Object { $_.name -eq $group } - if ($groupExists) { - Write-Output "Assigning group ($group) the role ($role) in NSX-T Data Center for Workload Domain ($domain): SUCCESSFUL" - } - else { - Write-Error "Assigning group ($group) the role ($role) in NSX-T Data Center for Workload Domain ($domain): FAILED" + 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 ((Invoke-Expression "Get-NsxtVidm$type -searchString $principal" | Where-Object { $_.name -eq $principal })) { + if (!(Get-NsxtUser | Where-Object { $_.name -eq $principal })) { + Invoke-Expression "Set-NsxtRole -principal $principal -type remote_$type -role $role -identitySource VIDM | Out-Null" + if (Get-NsxtUser | Where-Object { $_.name -eq $principal }) { + Write-Output "Assigning $type ($principal) the role ($role) in NSX-T Data Center for Workload Domain ($domain): SUCCESSFUL" + } + else { + Write-Error "Assigning $type ($principal) the role ($role) in NSX-T Data Center for Workload Domain ($domain): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Assigning $type ($principal) the role ($role) in NSX-T Data Center for Workload Domain ($domain), already exists: SKIPPED" + } + } + else { + Write-Error "Unable to find $type ($principal) in Workspace ONE Access for NSX-T Data Center, check $type synchronization: PRE_VALIDATION_FAILED" + } + } + } } } else { - Write-Warning "Assigning group ($group) the role ($role) in NSX-T Data Center for Workload Domain ($domain), already exists: SKIPPED" + 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 NSX Manager ($($nsxtManagerDetails.fqdn)), check credentials" - } - } - else { - Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials" } } Catch { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-NsxtVidmGroupRole +Export-ModuleMember -Function Add-NsxtVidmRole Function Add-WorkspaceOneRole { <# @@ -1168,7 +1287,13 @@ Function Add-WorkspaceOneRole { .DESCRIPTION The Add-WorkspaceOneRole cmdlet assigns roles to Active Directory groups provided to manage administrative - access to the Workspace ONE Access instance. + 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 the role exists in Workspace ONE Access + - Validates the group exists in Workspace ONE Access + - Assign the role to the group .EXAMPLE Add-WorkspaceOneRole -server sfo-wsa01.sfo.rainpole.io -user admin -pass VMw@re1! -group "gg-wsa-admins" -role "Super Admin" @@ -1176,60 +1301,57 @@ Function Add-WorkspaceOneRole { #> Param ( - [Parameter (Mandatory = $true)] [String]$server, - [Parameter (Mandatory = $true)] [String]$user, - [Parameter (Mandatory = $true)] [String]$pass, - [Parameter (Mandatory = $true)] [String]$group, - [Parameter (Mandatory = $true)] [ValidateSet("Super Admin", "Directory Admin", "ReadOnly Admin")] [String]$role + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$group, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [ValidateSet("Super Admin", "Directory Admin", "ReadOnly Admin")] [String]$role ) Try { - Request-WSAToken -fqdn $server -user $user -pass $pass | Out-Null - if ($sessionToken) { - $roleId = Get-WSARoleId -role $role - if (!$roleId) { - Write-Error "Unable to find role id ($roleId) for role ($role) in Workspace ONE Access Instance ($server)" - } - else { - $groupDetails = Get-WSAActiveDirectoryGroupDetail -group $group - $groupId = $groupDetails.Resources.id - if (!$groupId) { - Write-Error "Unable to find the group ($group) in Workspace ONE Access Instance ($server)" + if (Test-WSAConnection -server $server) { + if (Test-WSAAuthentication -server $server -user $user -pass $pass) { + $roleId = Get-WSARoleId -role $role + if (!$roleId) { + Write-Error "Unable to find role id ($roleId) for role ($role) in Workspace ONE Access Instance ($server): PRE_VALIDATION_FAILED" } else { - $associations = Get-WSARoleAssociation -roleId $roleId - $assign = $true - if ($associations.groups) { - if ($associations.groups -contains $groupId) { - Write-Warning "Assigning group ($group) to role ($role) in Workspace ONE Access Instance ($server), already exists: SKIPPED" - $assign = $false - } + $groupDetails = Get-WSAActiveDirectoryGroupDetail -group $group + $groupId = $groupDetails.Resources.id + if (!$groupId) { + Write-Error "Unable to find the group ($group) in Workspace ONE Access Instance ($server): PRE_VALIDATION_FAILED" } - - if ($assign) { - if ($role -ne "ReadOnly Admin") { - Write-Output "Update the Administrator Role Member with ($group) group" - $administratorRole = Get-WsaRole | Where-Object { $_.displayName -eq "Administrator" } - $adminId = $administratorRole.id - Set-WSARoleMember -groupId $groupId -id $adminId - } - $response = Add-WSARoleAssociation -roleId $roleId -groupId $groupId - if ($response.operations.code -eq "200") { - Write-Output "Assigning group ($group) to role ($role) in Workspace ONE Access Instance ($server): SUCCESSFUL" - } - elseif ($response.operations.code -eq "409") { - Write-Warning "$($response.operations.reason)" + else { + $associations = Get-WSARoleAssociation -roleId $roleId + $assign = $true + if ($associations.groups) { + if ($associations.groups -contains $groupId) { + Write-Warning "Assigning group ($group) to role ($role) in Workspace ONE Access Instance ($server), already exists: SKIPPED" + $assign = $false + } } - else { - Write-Error "$($response.operations.reason)" + if ($assign) { + if ($role -ne "ReadOnly Admin") { + Write-Output "Update the Administrator Role Member with ($group) group" + $administratorRole = Get-WsaRole | Where-Object { $_.displayName -eq "Administrator" } + $adminId = $administratorRole.id + Set-WSARoleMember -groupId $groupId -id $adminId + } + $response = Add-WSARoleAssociation -roleId $roleId -groupId $groupId + if ($response.operations.code -eq "200") { + Write-Output "Assigning group ($group) to role ($role) in Workspace ONE Access Instance ($server): SUCCESSFUL" + } + elseif ($response.operations.code -eq "409") { + Write-Warning "$($response.operations.reason)" + } + else { + Write-Error "$($response.operations.reason)" + } } } } } } - else { - Write-Error "Unable to obtain access token from Workspace ONE Access Instance ($wsaFqdn), check credentials" - } } Catch { Debug-ExceptionWriter -object $_ @@ -1240,10 +1362,10 @@ Export-ModuleMember -Function Add-WorkspaceOneRole Function Get-NsxtManagerAuthenticationPolicy { <# .SYNOPSIS - Retrieve the current Authentication Policy from NSX Manager Nodes + Retrieve the current Authentication Policy from NSX Manager Nodes - .DESCRIPTION - The Get-NsxtManagerAuthenticationPolicy cmdlet retrieves the current Authentication policy from each NSX + .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: - Output the following Authentication policy on each NSX manager node. @@ -1253,11 +1375,11 @@ Function Get-NsxtManagerAuthenticationPolicy { d) cli_failed_auth_lockout_period (in sec) e) cli_max_auth_failures (in attempt) f) minimum_password_length (in characters) - - .EXAMPLE - Get-NsxtManagerAuthenticationPolicy -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 + + .EXAMPLE + Get-NsxtManagerAuthenticationPolicy -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 This example retrieves the current Authentication policy from NSX manager nodes in sfo-m01 workload domain - #> + #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, @@ -1267,23 +1389,22 @@ Function Get-NsxtManagerAuthenticationPolicy { ) Try { - Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null - if ($accessToken) { - $nsxtManagerDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain -listNodes - foreach ($nsxtManagerNode in $nsxtManagerDetails.nodes) { - Request-NsxToken -fqdn $nsxtManagerNode.fqdn -username $nsxtManagerDetails.adminUser -password $nsxtManagerDetails.AdminPass | Out-Null - if ($nsxtHeaders.Authorization) { - $response = Get-NsxtManagerAuthPolicy -nsxtManagerNode $nsxtManagerNode.fqdn - Write-Output "Showing $($nsxtManagerNode.fqdn), results: $response" - } - else { - Write-Error "Unable to obtain access token from NSX Manager ($($nsxtManagerDetails.fqdn)), check credentials" + 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 -listNodes)) { + foreach ($nsxtManagerNode in $vcfNsxDetails.nodes) { + if (Test-NSXTConnection -server $nsxtManagerNode.fqdn) { + if (Test-NSXTAuthentication -server $nsxtManagerNode.fqdn -user $vcfNsxDetails.adminUser -pass $vcfNsxDetails.adminPass) { + $response = Get-NsxtManagerAuthPolicy -nsxtManagerNode $nsxtManagerNode.fqdn + Write-Output "Showing $($nsxtManagerNode.fqdn), results: $response" + } + } + } + } } } } - else { - Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials" - } } Catch { Debug-ExceptionWriter -object $_ @@ -1294,12 +1415,16 @@ Export-ModuleMember -Function Get-NsxtManagerAuthenticationPolicy Function Set-NsxtManagerAuthenticationPolicy { <# .SYNOPSIS - Configure Authentication Password Policy NSX Manager Nodes + Configure Authentication Password Policy NSX Manager Nodes - .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 to - retrive the NSX-T Data Center details from its inventory and then: + .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 - 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) @@ -1308,10 +1433,10 @@ Function Set-NsxtManagerAuthenticationPolicy { e) cli_max_auth_failures (in attempt) f) minimum_password_length (in characters) - .EXAMPLE - Set-NsxtManagerAuthenticationPolicy -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -apiLockoutPeriod 900 -apiResetPeriod 120 -apiMaxAttempt 5 -cliLockoutPeriod 900 -cliMaxAttempt 5 -minPasswdLength 15 + .EXAMPLE + Set-NsxtManagerAuthenticationPolicy -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -apiLockoutPeriod 900 -apiResetPeriod 120 -apiMaxAttempt 5 -cliLockoutPeriod 900 -cliMaxAttempt 5 -minPasswdLength 15 This example configures the Authentication password policy in NSX manager nodes in sfo-m01 workload domain - #> + #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, @@ -1328,46 +1453,50 @@ Function Set-NsxtManagerAuthenticationPolicy { ) Try { - Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null - if ($accessToken) { - $nsxtManagerDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain -listNodes - foreach ($nsxtManagerNode in $nsxtManagerDetails.nodes) { - Request-NsxToken -fqdn $nsxtManagerNode.fqdn -username $nsxtManagerDetails.adminUser -password $nsxtManagerDetails.AdminPass | Out-Null - if ($nsxtHeaders.Authorization) { - $response = Get-NsxtManagerAuthPolicy -nsxtManagerNode $nsxtManagerNode.fqdn - if (!$PsBoundParameters.ContainsKey("apiLockoutPeriod")){ - $apiLockoutPeriod = [int]$response.api_failed_auth_lockout_period - } - if (!$PsBoundParameters.ContainsKey("apiResetPeriod")){ - $apiResetPeriod = [int]$response.api_failed_auth_reset_period - } - if (!$PsBoundParameters.ContainsKey("apiMaxAttempt")){ - $apiMaxAttempt = [int]$response.api_max_auth_failures - } - if (!$PsBoundParameters.ContainsKey("cliLockoutPeriod")){ - $cliLockoutPeriod = [int]$response.cli_failed_auth_lockout_period - } - if (!$PsBoundParameters.ContainsKey("cliMaxAttempt")){ - $cliMaxAttempt = [int]$response.cli_max_auth_failures - } - if (!$PsBoundParameters.ContainsKey("minPasswdLength")){ - $minPasswdLength = [int]$response.minimum_password_length - } - $response = Set-NsxtManagerAuthPolicy -nsxtManagerNode $nsxtManagerNode.fqdn -api_lockout_period $apiLockoutPeriod -api_reset_period $apiResetPeriod -api_max_attempt $apiMaxAttempt -cli_lockout_period $cliLockoutPeriod -cli_max_attempt $cliMaxAttempt -min_passwd_length $minPasswdLength - if ($detail -eq "true") { - Write-Output "Configuring Authentication Policy on NSX Manager ($($nsxtManagerNode.fqdn)) for Workload Domain ($domain): SUCCESSFUL" + 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 -listNodes)) { + if (Test-NSXTConnection -server $vcfNsxDetails.fqdn) { + if (Test-NSXTAuthentication -server $vcfNsxDetails.fqdn -user $vcfNsxDetails.adminUser -pass $vcfNsxDetails.adminPass) { + foreach ($nsxtManagerNode in $vcfNsxDetails.nodes) { + if (Test-NSXTAuthentication -server $vcfNsxDetails.fqdn -user $vcfNsxDetails.adminUser -pass $vcfNsxDetails.AdminPass) { + $response = Get-NsxtManagerAuthPolicy -nsxtManagerNode $nsxtManagerNode.fqdn + if (!$PsBoundParameters.ContainsKey("apiLockoutPeriod")){ + $apiLockoutPeriod = [int]$response.api_failed_auth_lockout_period + } + if (!$PsBoundParameters.ContainsKey("apiResetPeriod")){ + $apiResetPeriod = [int]$response.api_failed_auth_reset_period + } + if (!$PsBoundParameters.ContainsKey("apiMaxAttempt")){ + $apiMaxAttempt = [int]$response.api_max_auth_failures + } + if (!$PsBoundParameters.ContainsKey("cliLockoutPeriod")){ + $cliLockoutPeriod = [int]$response.cli_failed_auth_lockout_period + } + if (!$PsBoundParameters.ContainsKey("cliMaxAttempt")){ + $cliMaxAttempt = [int]$response.cli_max_auth_failures + } + if (!$PsBoundParameters.ContainsKey("minPasswdLength")){ + $minPasswdLength = [int]$response.minimum_password_length + } + $response = Set-NsxtManagerAuthPolicy -nsxtManagerNode $nsxtManagerNode.fqdn -api_lockout_period $apiLockoutPeriod -api_reset_period $apiResetPeriod -api_max_attempt $apiMaxAttempt -cli_lockout_period $cliLockoutPeriod -cli_max_attempt $cliMaxAttempt -min_passwd_length $minPasswdLength + if ($detail -eq "true") { + Write-Output "Configuring Authentication Policy on NSX Manager ($($nsxtManagerNode.fqdn)) for Workload Domain ($domain): SUCCESSFUL" + } + } + } + if ($detail -eq "false") { + Write-Output "Configuring Authentication Password Policy for all NSX Manager Nodes in Workload Domain ($domain): SUCCESSFUL" + } + } + } } } else { - Write-Error "Unable to obtain access token from NSX Manager ($($nsxtManagerDetails.fqdn)), check credentials" + Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" } } - if ($detail -eq "false") { - Write-Output "Configuring Authentication Password Policy for all NSX Manager Nodes in Workload Domain ($domain): SUCCESSFUL" - } - } - else { - Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials" } } Catch { @@ -1379,10 +1508,10 @@ Export-ModuleMember -Function Set-NsxtManagerAuthenticationPolicy Function Get-NsxtEdgeNodeAuthenticationPolicy { <# .SYNOPSIS - Retrieve Authentication Policy from NSX Edge Nodes + Retrieve Authentication Policy from NSX Edge Nodes - .DESCRIPTION - The Get-NsxtEdgeNodeAuthenticationPolicy cmdlet retrieves the current Authentication policy from NSX Edge + .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. @@ -1390,10 +1519,10 @@ Function Get-NsxtEdgeNodeAuthenticationPolicy { b) cli_max_auth_failures (in attempt) c) minimum_password_length (in characters) - .EXAMPLE - Get-NsxtEdgeNodeAuthenticationPolicy -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 + .EXAMPLE + Get-NsxtEdgeNodeAuthenticationPolicy -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 This example retrieving the Authentication policy for NSX Edge nodes in sfo-m01 workload domain - #> + #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, @@ -1403,24 +1532,23 @@ Function Get-NsxtEdgeNodeAuthenticationPolicy { ) Try { - Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null - if ($accessToken) { - $nsxtManagerDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain -listNodes - Request-NsxToken -fqdn $nsxtManagerDetails.fqdn -username $nsxtManagerDetails.adminUser -password $nsxtManagerDetails.AdminPass | Out-Null - $nsxtEdgeNodes = (Get-NsxtEdgeCluster | Where-Object {$_.member_node_type -eq "EDGE_NODE"}) - if ($nsxtHeaders.Authorization) { - foreach ($nsxtEdgeNode in $nsxtEdgeNodes.members) { - $response = Get-NsxtEdgeNodeAuthPolicy -nsxtManager $nsxtManagerDetails.fqdn -nsxtEdgeNodeID $nsxtEdgeNode.transport_node_id - Write-Output "Retrieving $($nsxtEdgeNode.transport_node_id), results: $response" + 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 -listNodes)) { + if (Test-NSXTConnection -server $vcfNsxDetails.fqdn) { + if (Test-NSXTAuthentication -server $vcfNsxDetails.fqdn -user $vcfNsxDetails.adminUser -pass $vcfNsxDetails.adminPass) { + $nsxtEdgeNodes = (Get-NsxtEdgeCluster | Where-Object {$_.member_node_type -eq "EDGE_NODE"}) + foreach ($nsxtEdgeNode in $nsxtEdgeNodes.members) { + $response = Get-NsxtEdgeNodeAuthPolicy -nsxtManager $vcfNsxDetails.fqdn -nsxtEdgeNodeID $nsxtEdgeNode.transport_node_id + Write-Output "Retrieving $($nsxtEdgeNode.transport_node_id), results: $response" + } + } + } + } } } - else { - Write-Error "Unable to obtain access token from NSX Manager ($($nsxtManagerDetails.fqdn)), check credentials" - } - } - else { - Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials" - } + } } Catch { Debug-ExceptionWriter -object $_ @@ -1431,21 +1559,25 @@ Export-ModuleMember -Function Get-NsxtEdgeNodeAuthenticationPolicy Function Set-NsxtEdgeNodeAuthenticationPolicy { <# .SYNOPSIS - Configure Authentication Policy NSX Edge Nodes + Configure Authentication Policy NSX Edge Nodes - .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 to retrive the NSX-T - Data Center details from its inventory and then: + .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 - 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) c) minimum_password_length (in characters) - .EXAMPLE - Set-NsxtEdgeNodeAuthenticationPolicy -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -cliLockoutPeriod 900 -cliMaxAttempt 5 -minPasswdLength 15 + .EXAMPLE + Set-NsxtEdgeNodeAuthenticationPolicy -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -cliLockoutPeriod 900 -cliMaxAttempt 5 -minPasswdLength 15 This example configures the Authentication policy of the NSX Edges nodes in sfo-m01 workload domain - #> + #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, @@ -1459,38 +1591,40 @@ Function Set-NsxtEdgeNodeAuthenticationPolicy { ) Try { - Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null - if ($accessToken) { - $nsxtManagerDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain -listNodes - Request-NsxToken -fqdn $nsxtManagerDetails.fqdn -username $nsxtManagerDetails.adminUser -password $nsxtManagerDetails.AdminPass | Out-Null - $nsxtEdgeNodes = (Get-NsxtEdgeCluster | Where-Object {$_.member_node_type -eq "EDGE_NODE"}) - if ($nsxtHeaders.Authorization) { - foreach ($nsxtEdgeNode in $nsxtEdgeNodes.members) { - $response = Get-NsxtEdgeNodeAuthPolicy -nsxtManager $nsxtManagerDetails.fqdn -nsxtEdgeNodeID $nsxtEdgeNode.transport_node_id - if (!$PsBoundParameters.ContainsKey("cliLockoutPeriod")){ - $cliLockoutPeriod = [int]$response.cli_failed_auth_lockout_period - } - if (!$PsBoundParameters.ContainsKey("cliMaxAttempt")){ - $cliMaxAttempt = [int]$response.cli_max_auth_failures - } - if (!$PsBoundParameters.ContainsKey("minPasswdLength")){ - $minPasswdLength = [int]$response.minimum_password_length - } - $response = Set-NsxtEdgeNodeAuthPolicy -nsxtManager $nsxtManagerDetails.fqdn -nsxtEdgeNodeID $nsxtEdgeNode.transport_node_id -cli_lockout_period $cliLockoutPeriod -cli_max_attempt $cliMaxAttempt -min_passwd_length $minPasswdLength - if ($detail -eq "true") { - Write-Output "Configuring Authentication Policy on NSX Edge Node ($nsxtEdgeNode) for Workload Domain ($domain): SUCCESSFUL" + 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 -listNodes)) { + if (Test-NSXTConnection -server $vcfNsxDetails.fqdn) { + if (Test-NSXTAuthentication -server $vcfNsxDetails.fqdn -user $vcfNsxDetails.adminUser -pass $vcfNsxDetails.adminPass) { + $nsxtEdgeNodes = (Get-NsxtEdgeCluster | Where-Object {$_.member_node_type -eq "EDGE_NODE"}) + foreach ($nsxtEdgeNode in $nsxtEdgeNodes.members) { + $response = Get-NsxtEdgeNodeAuthPolicy -nsxtManager $vcfNsxDetails.fqdn -nsxtEdgeNodeID $nsxtEdgeNode.transport_node_id + if (!$PsBoundParameters.ContainsKey("cliLockoutPeriod")){ + $cliLockoutPeriod = [int]$response.cli_failed_auth_lockout_period + } + if (!$PsBoundParameters.ContainsKey("cliMaxAttempt")){ + $cliMaxAttempt = [int]$response.cli_max_auth_failures + } + if (!$PsBoundParameters.ContainsKey("minPasswdLength")){ + $minPasswdLength = [int]$response.minimum_password_length + } + $response = Set-NsxtEdgeNodeAuthPolicy -nsxtManager $vcfNsxDetails.fqdn -nsxtEdgeNodeID $nsxtEdgeNode.transport_node_id -cli_lockout_period $cliLockoutPeriod -cli_max_attempt $cliMaxAttempt -min_passwd_length $minPasswdLength + if ($detail -eq "true") { + Write-Output "Configuring Authentication Policy on NSX Edge Node ($nsxtEdgeNode) for Workload Domain ($domain): SUCCESSFUL" + } + } + if ($detail -eq "false") { + Write-Output "Configuring Authentication Password Policy on all NSX Edge Nodes for Workload Domain ($domain): SUCCESSFUL" + } + } + } } } + 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 NSX Manager ($($nsxtManagerDetails.fqdn)), check credentials" - } - if ($detail -eq "false") { - Write-Output "Configuring Authentication Password Policy on all NSX Edge Nodes for Workload Domain ($domain): SUCCESSFUL" - } - } - else { - Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials" } } Catch { @@ -1566,7 +1700,7 @@ Function Install-SiteRecoveryManager { $cluster = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }).clusters.id) }).Name $datastore = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }).clusters.id) }).primaryDatastoreName $datacenter = (Get-Datacenter -Cluster $cluster).Name - $mgmtPortgroup = ((get-vmhost)[0] | Get-VMHostNetwork | Select Hostname, VMkernelGateway -ExpandProperty VirtualNic | where-object {$_.DeviceName -eq "vmk0"}).PortGroupName + $mgmtPortgroup = ((get-vmhost)[0] | Get-VMHostNetwork | Select-Object Hostname, VMkernelGateway -ExpandProperty VirtualNic | where-object {$_.DeviceName -eq "vmk0"}).PortGroupName $ntpServer = (Get-VCFConfigurationNTP).ipAddress $netMode = "static" $command = '"C:\Program Files\VMware\VMware OVF Tool\ovftool.exe" --noSSLVerify --acceptAllEulas --allowAllExtraConfig --diskMode=thin --powerOn --name=' + $srmHostname + ' --ipProtocol="IPv4" --ipAllocationPolicy="fixedAllocatedPolicy" --vmFolder=' + $srmFolder + ' --net:"Network 1"=' + $mgmtPortgroup + ' --datastore=' + $datastore + ' --deploymentOption=' + $deploymentOption + ' --prop:varoot-password=' + $srmVaRootPassword + ' --prop:vaadmin-password=' + $srmVaAdminPassword +' --prop:dbpassword=' + $srmDbPassword + ' --prop:network.netmode.VMware_Site_Recovery_Manager_Appliance=' + $netMode + ' --prop:network.ip0.VMware_Site_Recovery_Manager_Appliance=' + $srmIpAddress + ' --prop:network.netprefix0.VMware_Site_Recovery_Manager_Appliance=' + $srmNetPrefix + ' --prop:vami.hostname=' + $srmFqdn + ' --prop:network.domain.VMware_Site_Recovery_Manager_Appliance=' + $srmDomain + ' --prop:network.searchpath.VMware_Site_Recovery_Manager_Appliance=' + $srmNetworkSearchPath + ' --prop:ntpserver=' + $ntpServer +' --prop:network.gateway.VMware_Site_Recovery_Manager_Appliance=' + $srmGateway + ' --prop:network.DNS.VMware_Site_Recovery_Manager_Appliance=' + $dnsServer1 + ',' + $dnsServer2 + ' --prop:enableFileIntegrity= ' + $enableFileIntegrity +' ' + $srmOvfPath + ' "vi://' + $vcenter.ssoAdmin + ':' + $vcenter.ssoAdminPass + '@' + $vcenter.fqdn + '/' + $datacenter + '/host/' + $cluster + '/"' @@ -1578,7 +1712,7 @@ Function Install-SiteRecoveryManager { Try { $timer = [Diagnostics.Stopwatch]::StartNew() ## Start the timer Write-Output "Waiting for $srmIpAddress to become pingable." - While (!(Test-NetConnection $srmIpAddress -Port 5480 -WarningAction silentlyContinue | ? { $_.TcpTestSucceeded -eq $True })) { + While (!(Test-NetConnection $srmIpAddress -Port 5480 -WarningAction silentlyContinue | Where-Object { $_.TcpTestSucceeded -eq $True })) { ## If the timer has waited greater than or equal to the timeout, throw an exception exiting the loop if ($timer.Elapsed.TotalSeconds -ge $Timeout) { Throw "Timeout Exceeded. Giving up on ping availability to $srmIpAddress" @@ -1663,7 +1797,7 @@ Function Install-vSphereReplicationManager { $cluster = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }).clusters.id) }).Name $datastore = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }).clusters.id) }).primaryDatastoreName $datacenter = (Get-Datacenter -Cluster $cluster).Name - $mgmtPortgroup = ((get-vmhost)[0] | Get-VMHostNetwork | Select Hostname, VMkernelGateway -ExpandProperty VirtualNic | where-object {$_.DeviceName -eq "vmk0"}).PortGroupName + $mgmtPortgroup = ((get-vmhost)[0] | Get-VMHostNetwork | Select-Object Hostname, VMkernelGateway -ExpandProperty VirtualNic | where-object {$_.DeviceName -eq "vmk0"}).PortGroupName $ntpServer = (Get-VCFConfigurationNTP).ipAddress $netMode = "static" $command = '"C:\Program Files\VMware\VMware OVF Tool\ovftool.exe" --noSSLVerify --acceptAllEulas --allowAllExtraConfig --diskMode=thin --powerOn --name=' + $vrmsHostname + ' --ipProtocol="IPv4" --ipAllocationPolicy="fixedAllocatedPolicy" --vmFolder=' + $vrmsFolder + ' --net:"Network 1"=' + $mgmtPortgroup + ' --datastore=' + $datastore + ' --prop:varoot-password=' + $vrmsVaRootPassword + ' --prop:vaadmin-password=' + $vrmsVaAdminPassword +' --prop:network.netmode.vSphere_Replication_Appliance=' + $netMode + ' --prop:network.ip0.vSphere_Replication_Appliance=' + $vrmsIpAddress + ' --prop:network.netprefix0.vSphere_Replication_Appliance=' + $vrmsNetPrefix + ' --prop:vami.hostname=' + $vrmsFqdn + ' --prop:network.domain.vSphere_Replication_Appliance=' + $vrmsDomain + ' --prop:network.searchpath.vSphere_Replication_Appliance=' + $vrmsNetworkSearchPath + ' --prop:ntpserver=' + $ntpServer +' --prop:network.gateway.vSphere_Replication_Appliance=' + $vrmsGateway + ' --prop:network.DNS.vSphere_Replication_Appliance=' + $dnsServer1 + ',' + $dnsServer2 + ' --prop:enableFileIntegrity= ' + $enableFileIntegrity +' --vService:installation=com.vmware.vim.vsm:extension_vservice ' + $vrmsOvfPath + ' "vi://' + $vcenter.ssoAdmin + ':' + $vcenter.ssoAdminPass + '@' + $vcenter.fqdn + '/' + $datacenter + '/host/' + $cluster + '/"' @@ -1675,7 +1809,7 @@ Function Install-vSphereReplicationManager { Try { $timer = [Diagnostics.Stopwatch]::StartNew() ## Start the timer Write-Output "Waiting for $vrmsIpAddress to become pingable." - While (!(Test-NetConnection $vrmsIpAddress -Port 5480 -WarningAction silentlyContinue | ? { $_.TcpTestSucceeded -eq $True })) { + While (!(Test-NetConnection $vrmsIpAddress -Port 5480 -WarningAction silentlyContinue | Where-Object { $_.TcpTestSucceeded -eq $True })) { ## If the timer has waited greater than or equal to the timeout, throw an exception exiting the loop if ($timer.Elapsed.TotalSeconds -ge $Timeout) { Throw "Timeout Exceeded. Giving up on ping availability to $vrmsIpAddress" @@ -1745,7 +1879,7 @@ Function Connect-DRSolutionTovCenter { # Retireve the vCenter SSL Thumbprint $vcenterFQDN = $vcenter.fqdn $command = 'openssl s_client -connect ' + $vcenterFQDN + ':443 2>&1 | openssl x509 -sha256 -fingerprint -noout' - $thumbprint = (iex "& $command").Split("=")[1] + $thumbprint = (Invoke-Expression "& $command").Split("=")[1] $vCenterInstanceUuid = Connect-VIServer -Server $vcenter.fqdn -User $vcenter.ssoAdmin -pass $vcenter.ssoAdminPass | Select-Object InstanceUuid $vCenterInstanceUuid = $vCenterInstanceUuid.InstanceUuid Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue @@ -1769,15 +1903,15 @@ Export-ModuleMember -Function Connect-DRSolutionTovCenter Function Install-VAMICertificate { <# .SYNOPSIS - Install a Signed Certificate Using VAMI Appliance interface + Install a Signed Certificate Using VAMI Appliance interface - .DESCRIPTION - The Install-VAMICertificate cmdlet replaces the certificate on the Site Recovery Manager appliance + .DESCRIPTION + The Install-VAMICertificate cmdlet replaces the certificate on the Site Recovery Manager appliance - .EXAMPLE - Install-VAMICertificate -fqdn sfo-m01-srm01.sfo.rainpole.io -username admin -password VMw@re1! -certFile C:\Certs\sfo-m01-srm01.4.p12 -certPassword VMw@re1! + .EXAMPLE + Install-VAMICertificate -fqdn sfo-m01-srm01.sfo.rainpole.io -username admin -password VMw@re1! -certFile C:\Certs\sfo-m01-srm01.4.p12 -certPassword VMw@re1! This example configures the Site Recovery Manager Virtual Appliance with the with a signed cert - #> + #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$fqdn, @@ -1802,7 +1936,7 @@ Function Install-VAMICertificate { $body = '{ "certificateContent": "'+$base64string+'", "certificatePassword": "'+$certPassword+'" - }' + }' $sessionId = Request-VAMISessionId -fqdn $fqdn -username $username -password $password $VAMIAuthHeaders = createVAMIAuthHeader($sessionId) $uri = "https://"+$fqdn+":5480/configure/requestHandlers/installPkcs12Certificate" @@ -2782,35 +2916,36 @@ Function Enable-SupervisorCluster { .EXAMPLE $wmClusterInput = @{ - Server = sfo-vcf01.sfo.rainpole.io - User = administrator@vsphere.local - Pass = 'VMw@re1!' - Domain = sfo-m01 - SizeHint = Tiny - ManagementVirtualNetwork = Get-VirtualNetwork -Name sfo-w01-kub-seg01 - ManagementNetworkMode = StaticRange - ManagementNetworkStartIpAddress = 192.168.20.10 - ManagementNetworkAddressRangeSize = 5 - ManagementNetworkGateway = 192.168.20.1 - ManagementNetworkSubnetMask = 255.255.255.0 - MasterNtpServer = @(172.16.11.253, 172.16.12.253) - Cluster = sfo-w01-cl01 - ContentLibrary = Kubernetes - EphemeralStoragePolicy = Get-SpbmStoragePolicy -Name vsphere-with-tanzu-policy - ImageStoragePolicy = Get-SpbmStoragePolicy -Name vsphere-with-tanzu-policy - MasterStoragePolicy = Get-SpbmStoragePolicy -Name vsphere-with-tanzu-policy - NsxEdgeClusterId = (Get-NsxtEdgeCluster -Name sfo-w01-ec01).Id - 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 - WorkerDnsServer = @(172.16.11.4, 172.16.11.5) - MasterDnsServerIpAddress = @(172.16.11.4, 172.16.11.5) - MasterDnsSearchDomain = sfo.rainpole.io - } - - Enable-SupervisorCluster @wmClusterInput + server = sfo-vcf01.sfo.rainpole.io + user = administrator@vsphere.local + pass = 'VMw@re1!' + domain = sfo-m01 + 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 + } + + Enable-SupervisorCluster @wmClusterInput -RunAsync:$true This example enables Workload Management on a vSphere Cluster in workload domain sfo-w01 #> @@ -2820,17 +2955,16 @@ Function Enable-SupervisorCluster { [Parameter (Mandatory = $true)] [String]$pass, [Parameter (Mandatory = $true)] [String]$domain, [Parameter (Mandatory = $true)] [String]$cluster, - [Parameter (Mandatory = $true)] [String]$sizeHint, - [Parameter (Mandatory = $true)] [String]$managementNetworkMode, + [Parameter (Mandatory = $true)] [ValidateSet("Tiny", "Small", "Medium", "Large")] [String]$sizeHint, + [Parameter (Mandatory = $true)] [ValidateSet("DHCP", "StaticRange")][String]$managementNetworkMode, [Parameter (Mandatory = $true)] [String]$managementVirtualNetwork, [Parameter (Mandatory = $true)] [String]$managementNetworkStartIpAddress, [Parameter (Mandatory = $true)] [String]$managementNetworkAddressRangeSize, [Parameter (Mandatory = $true)] [String]$managementNetworkGateway, [Parameter (Mandatory = $true)] [String]$managementNetworkSubnetMask, - [Parameter (Mandatory = $true)] [String]$ntpServer1IpAddress, - [Parameter (Mandatory = $false)] [String]$ntpServer2IpAddress, - [Parameter (Mandatory = $true)] [String]$dnsServer1IpAddress, - [Parameter (Mandatory = $false)] [String]$dnsServer2IpAddress, + [Parameter (Mandatory = $true)] [string]$masterDnsName, + [Parameter (Mandatory = $true)] [Array]$masterNtpServers, + [Parameter (Mandatory = $true)] [Array]$masterDnsServers, [Parameter (Mandatory = $true)] [String]$contentLibrary, [Parameter (Mandatory = $true)] [String]$ephemeralStoragePolicy, [Parameter (Mandatory = $true)] [String]$imageStoragePolicy, @@ -2842,67 +2976,583 @@ Function Enable-SupervisorCluster { [Parameter (Mandatory = $true)] [String]$externalIngressCIDRs, [Parameter (Mandatory = $true)] [String]$externalEgressCIDRs, [Parameter (Mandatory = $true)] [String]$masterDnsSearchDomain, - [Parameter (Mandatory = $true)] [ValidateSet("true", "false")] [String]$async + [Parameter (Mandatory = $true)] [Array]$workerDnsServers, + [Parameter (Mandatory = $false)] [ValidateSet("true", "false")] [bool]$RunAsync, + [Parameter (Mandatory = $false)] [ValidateSet("true", "false")] [bool]$SkipValidation, + [Parameter (Mandatory = $false)] [ValidateSet("true", "false")] [bool]$ValidateOnly ) Try { $vcenter = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain Connect-VIServer -Server $vcenter.fqdn -User $vcenter.ssoAdmin -Password $vcenter.ssoAdminPass -Force | Out-Null + Request-VCToken -fqdn $vcenter.fqdn -username $vcenter.ssoAdmin -password $vcenter.ssoAdminPass | Out-Null + if ($DefaultVIServer.Name -eq $($vcenter.fqdn)) { $nsxtManagerDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain Request-NsxToken -fqdn $nsxtManagerDetails.fqdn -username $nsxtManagerDetails.adminUser -password $nsxtManagerDetails.adminPass | Out-Null + if (!($getWMCluster = Get-WMCluster -Cluster $cluster -ErrorAction SilentlyContinue)) { - if ($NtpServer2IpAddress) { - $ntpServers = @($NtpServer1IpAddress, $NtpServer2IpAddress) - } - else { - $ntpServers = @($NtpServer1IpAddress) + #Check SkipValidation parameter + if ($SkipValidation -eq $false -or !$SkipValidation) { + + #Validate management network inputs + #Valid Starting IP Address is an actual IPv4 address + do { + try { + $checkManagementNetworkStartIpAddress = [IPAddress]$managementNetworkStartIpAddress + } catch {} + + 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) + } + + try { + $checkManagementNetworkSubnetMask = [IPAddress] $managementNetworkSubnetMask + } catch {} + + 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 { + try { + $checkManagementNetworkGateway = [IPAddress]$managementNetworkGateway + } catch {} + + 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 + try { + $checkManagementNetworkGatewayInSubnet = Test-IpAddress -IpAddress $managementNetworkGateway -Subnet "$managementNetworkStartIpAddress/$managementNetworkCidr" + } catch {} + + 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" + try { + $checkAlteredManagementNetworkGatewayFormat = [IPAddress]$managementNetworkGateway + } catch {} + } until ($managementNetworkGateway -ne [String]::Empty -and $checkAlteredManagementNetworkGatewayFormat.IpAddressToString -eq $managementNetworkGateway) + } + } until ($checkManagementNetworkGatewayInSubnet.Validated -eq $True) + + #Validate Management Virtual Network (dvPortGroup) exists + do { + try { + $checkManagementVirtualNetwork = Get-VirtualNetwork -Name $ManagementVirtualNetwork -ErrorAction SilentlyContinue + } catch {} + + 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 + try { + $checkEphemeralStoragePolicy = Get-SpbmStoragePolicy -Name $EphemeralStoragePolicy -ErrorAction SilentlyContinue + } catch {} + + 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 + try { + $checkImageStoragePolicy = Get-SpbmStoragePolicy -Name $ImageStoragePolicy -ErrorAction SilentlyContinue + } catch {} + + 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 + try { + $checkMasterStoragePolicy = Get-SpbmStoragePolicy -Name $MasterStoragePolicy -ErrorAction SilentlyContinue + } catch {} + + 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 + try { + $checkNsxEdgeCluster = Get-NsxEdgeCluster -Name $nsxEdgeCluster -ErrorAction SilentlyContinue + $nsxEdgeClusterId = $checkNsxEdgeCluster.Id + } catch { + } + + 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 + + try { + $checkAlteredMasterNtpServer = Get-NtpServer -server $masterNtpServers[$i] + } catch {} + + } 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]) { + try { + $checkMasterDnsServerFormat = [IPAddress]$masterDnsServers[$i] + } catch {} + + 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 + + try { + $checkAlteredMasterDnsServerFormat = [IPAddress]$masterDnsServerFormatPrompt + } catch {} + + } 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" + + try { + $checkAlteredMasterDnsServer = [IPAddress]$masterDnsServerPrompt + } catch {} + + $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]) { + try { + $checkWorkerDnsServerFormat = [IPAddress]$workerDnsServers[$i] + } catch {} + + 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 + + try { + $checkAlteredWorkerDnsServerFormat = [IPAddress]$workerDnsServerFormatPrompt + } catch {} + + } 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 { + try { + $checkWorkerDnsServer = Invoke-Expression 'nslookup -type=A vmware.com ""$workerDnsServers[$i]""' + } catch {} + + 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" + try { + $checkAlteredWorkerDnsServer = [IPAddress]$workerDnsServerPrompt + } catch {} + $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 + #Full validation (checking type, subscription, etc.) is TBD + 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 { + try { + $checkMasterDnsName = Invoke-Expression "nslookup -type=A $masterDnsName" + } catch {} + 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 { + try { + $checkMasterDnsSearchDomain = Invoke-Expression "nslookup -type=A $masterDnsSearchDomain" + } catch {} + 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 { + try { + $checkCluster = Get-Cluster -Name $cluster -ErrorAction SilentlyContinue + } catch {} + + 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 ($DnsServer2IpAddress) { - $dnsServers = @($DnsServer1IpAddress, $DnsServer2IpAddress) + 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 + } } - else { - $dnsServers = @($DnsServer1IpAddress) - } - - $internalWMClusterInput = @{ - SizeHint = $SizeHint - ManagementVirtualNetwork = Get-VirtualNetwork -Name $ManagementVirtualNetwork - ManagementNetworkMode = $managementNetworkMode - ManagementNetworkStartIpAddress = $managementNetworkStartIpAddress - ManagementNetworkAddressRangeSize = $managementNetworkAddressRangeSize - ManagementNetworkGateway = $managementNetworkGateway - ManagementNetworkSubnetMask = $managementNetworkSubnetMask - MasterNtpServer = $ntpServers - Cluster = $cluster - ContentLibrary = $contentLibrary - EphemeralStoragePolicy = Get-SpbmStoragePolicy -Name $ephemeralStoragePolicy - ImageStoragePolicy = Get-SpbmStoragePolicy -Name $imageStoragePolicy - MasterStoragePolicy = Get-SpbmStoragePolicy -Name $masterStoragePolicy - NsxEdgeClusterId = (Get-NsxtEdgeCluster -Name $nsxEdgeCluster).Id - DistributedSwitch = $distributedSwitch - PodCIDRs = $podCIDRs - ServiceCIDR = $serviceCIDR - ExternalIngressCIDRs = $externalIngressCIDRs - ExternalEgressCIDRs = $externalEgressCIDRs - WorkerDnsServer = $dnsServers - MasterDnsServerIpAddress = $dnsServers - MasterDnsSearchDomain = $dnsSearchDomain - } - - if ($async -eq "true") { - Enable-WMCluster @internalWMClusterInput -RunAsync | Out-Null - Write-Output "Submitted Creation of Supervisor Cluster $cluster in vCenter Server $($vcenter.fqdn), this takes a while" - } - if ($async -eq "false") { - Enable-WMCluster @internalWMClusterInput | Out-Null - if ($getWMCluster = Get-WMCluster -Cluster $cluster -ErrorAction SilentlyContinue) { - Write-Output "Created Supervisor Cluster $cluster in vCenter Server $($vcenter.fqdn) Successfully" + + + if ($ValidateOnly -eq $true) { + Write-Output "Validation complete" + } elseif (!$ValidateOnly -or $ValidateOnly -eq $false) { + if ($runAsync -eq $true) { + Enable-WMCluster @internalWMClusterInput -RunAsync | Out-Null + Write-Output "Submitted Creation of Supervisor Cluster $cluster in vCenter Server $($vcenter.fqdn). This may take a while to complete." } - else { - Write-Error "Creating Supervisor Cluster $cluster in vCenter Server $($vcenter.fqdn) Failed" + if ($runAsync -eq $false) { + Enable-WMCluster @internalWMClusterInput | Out-Null + if ($getWMCluster = Get-WMCluster -Cluster $cluster -ErrorAction SilentlyContinue) { + Write-Output "Started Supervisor Cluster $cluster instantiation in vCenter Server $($vcenter.fqdn) Successfully" + } + else { + Write-Error "Starting Supervisor Cluster $cluster instantiation in vCenter Server $($vcenter.fqdn) Failed" + } } } } @@ -3341,7 +3991,7 @@ Function Add-SupervisorClusterCertificate { if ($isMacOS -eq $true -or $isLinux -eq $true) { $certificateFormatted = $Certificate -Replace "`n","\n" - } elseif ($isWindows -eq $true) { + } elseif ($isWindows -eq $true -or $PSEdition -eq "Desktop") { $certificateFormatted = $Certificate -Replace "`r`n","\n" } else { Write-Error -Message "Unsupported operating system. Exiting." @@ -3807,16 +4457,16 @@ Function Connect-SupervisorCluster { The Connect-SupervisorCluster cmdlet logs the user in to a Supervisor Cluster .EXAMPLE - Connect-WMCluster -Cluster sfo-w01-cl01 -User administrator@vsphere.local -Pass VMw@re1! - This example logs the vSphere SSO user administrator@vsphere.local into Supervisor Cluster sfo-w01-cl01 + Connect-SupervisorCluster -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -cluster sfo-w01-cl01 + This example logs in with the vSphere SSO user administrator@vsphere.local to the Supervisor Cluster sfo-w01-cl01 #> 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]$Cluster + [Parameter (Mandatory = $true)][string]$server, + [Parameter (Mandatory = $true)][string]$user, + [Parameter (Mandatory = $true)][string]$pass, + [Parameter (Mandatory = $true)][string]$domain, + [Parameter (Mandatory = $true)][string]$cluster ) if ($accessToken) { @@ -3842,12 +4492,8 @@ Function Connect-SupervisorCluster { } Try { - Start-AwaitSession | Out-Null - Send-AwaitCommand "kubectl vsphere login --server $kubIpAddress --vsphere-username $User --insecure-skip-tls-verify" | Out-Null - Wait-AwaitResponse "Password:" | Out-Null - Send-AwaitCommand "$Pass" - Stop-AwaitSession - Start-Sleep -seconds 3 | Out-Null + $env:KUBECTL_VSPHERE_PASSWORD = $pass + Invoke-Expression "kubectl vsphere login --server $kubIpAddress --vsphere-username $user --insecure-skip-tls-verify" | Out-Null } Catch { Write-Error "Something went wrong." @@ -3859,7 +4505,7 @@ Function Connect-SupervisorCluster { Write-Output "Connection successful." } } -Export-ModuleMember -Function Connect-Supervisor +Export-ModuleMember -Function Connect-SupervisorCluster Function Add-TanzuKubernetesCluster { <# @@ -3925,14 +4571,36 @@ Export-ModuleMember -Function Add-TanzuKubernetesCluster ####################################################################################################################### -######################################################################################################################### -################## 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 ################# +####################################################################################################################### +################# 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]$username, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$password, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$workbook ) @@ -3951,168 +4619,173 @@ Function Export-vRLIJsonSpec { $pnpWorkbook = Open-ExcelPackage -Path $workbook ### Obtain Configuration Information from vRealize Suite Lifecycle Manager - Request-vRSLCMToken -fqdn $server -username $username -password $password | Out-Null - if (($vrslcmHealth = Get-vRSLCMHealth).'vrlcm-server' -eq "UP") { - 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) { - $vrliCertificate = Get-vRSLCMLockerCertificate | Where-Object {$_.alias -eq $pnpWorkbook.Workbook.Names["region_vrli_virtual_hostname"].Value} - if ($vrliCertificate.alias) { - $vrliPassword = Get-vRSLCMLockerPassword | Where-Object {$_.alias -eq $pnpWorkbook.Workbook.Names["region_vrli_admin_password_alias"].Value} - if ($vrliPassword.alias) { - $vcCredentials = Get-vRSLCMLockerPassword | Where-Object {$_.alias -eq (($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 - $productsObject = @() - $productsObject += [pscustomobject]@{ - 'id' = "vrli" - 'version' = "8.4.0" - '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 + 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 | Where-Object {$_.alias -eq $pnpWorkbook.Workbook.Names["region_vrli_admin_password_alias"].Value}) { + $vcCredentials = Get-vRSLCMLockerPassword | Where-Object {$_.alias -eq (($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"} + $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" + } } - - $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 "Admin Password with alias ($($region_vrli_admin_password_alias)) not found in the vRealize Suite Lifecycle Manager Locker, add and retry" } } - else { - Write-Error "Certificate with alias ($($region_vrli_virtual_hostname)) not found in the vRealize Suite Lifecycle Manager Locker, add and retry" - } - } - else { - Write-Error "License key ($($vrliLicense.key)) not found in the vRealize Suite Lifecycle Manager Locker, add and retry" } } - else { - Write-Error "Unable to obtain access token from vRealize Suite Lifecycle Manager ($server), check credentials" - } } Catch { Debug-ExceptionWriter -object $_ @@ -4123,18 +4796,21 @@ Export-ModuleMember -Function Export-vRLIJsonSpec Function New-vRLIDeployment { <# .SYNOPSIS - Deploy vRealize Log Inisght Cluster to vRealize Suite Lifecycle Manager + 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 to retrive the vRSLCM details from its - inventory and then: - - Verifies that the environment does not already exist - - Requests a new deployment of vRealize Log Insight + 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 using the Planning and Preparation Workbook + This example starts a deployment of vRealize Log Inisght via vRealize Suite Lifecycle Manager using the Planning and Preparation Workbook data #> Param ( @@ -4157,55 +4833,52 @@ Function New-vRLIDeployment { } } - Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null - if ($accessToken) { - $vrslcm = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass - Request-vRSLCMToken -fqdn $vrslcm.fqdn -username $vrslcm.adminUser -password $vrslcm.adminPass | Out-Null - if (($vrslcmHealth = Get-vRSLCMHealth).'vrlcm-server' -eq "UP") { - Export-vRLIJsonSpec -server $vrslcm.fqdn -username $vrslcm.adminUser -password $vrslcm.adminPass -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 | Where-Object {$_.alias -Match $($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) + 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 | Where-Object {$_.alias -Match $($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-Output "Deployment Request for vRealize Log Insight Submitted Successfully (Request Ref: $($newRequest.requestId))" + Write-Error "Certificate with alias ($($jsonSpec.products.properties.certificate.Split(":")[3])) does not exist in the locker: PRE_VALIDATION_FAILED" } } else { - Write-Error "Request to deploy vRealize Log Insight failed, check the vRealize Suite Lifecycle Manager UI" + Write-Error "Password with alias ($($jsonSpec.products.properties.productPassword.Split(":")[3])) does not exist in the locker: PRE_VALIDATION_FAILED" } } else { - Write-Error "License with alias ($($jsonSpec.products.properties.licenseRef.Split(":")[3])) does not exist in the locker" + 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 "Certificate with alias ($($jsonSpec.products.properties.certificate.Split(":")[3])) does not exist in the locker" - } } - else { - Write-Error "Password with alias ($($jsonSpec.products.properties.productPassword.Split(":")[3])) does not exist in the locker" - } - } - else { - Write-Warning "Environment with name ($($jsonSpec.environmentName)) already exists in vRealize Suite Lifecyle Manager ($($vrslcm.fqdn)) with a status of ($($environmentExists.environmentStatus)): SKIPPED" - } - } - else { - Write-Error "Unable to obtain access token from vRealize Suite Lifecycle Manager ($server), check credentials" + } } } - else { - Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials" - } } Catch { Debug-ExceptionWriter -object $_ @@ -4213,21 +4886,24 @@ Function New-vRLIDeployment { } Export-ModuleMember -Function New-vRLIDeployment -Function Add-vRLISmtpConfiguation { +Function Add-vRLISmtpConfiguration { <# .SYNOPSIS - Configure SMTP settings in vRealize Log Insight + Configure SMTP settings in vRealize Log Insight - .DESCRIPTION - The Add-vRLISmtpConfiguation cmdlet configures the SMTP sever settings in vRealize Log Insight. The cmdlet - connects to SDDC Manager using the -server, -user, and -password values to retrive the vRealize Log Insight - details from its inventory and then: - - Configures SMTP server settings on 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-vRLISmtpConfiguation -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 Suite Lifecycle Manager - #> + .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, @@ -4241,57 +4917,58 @@ Function Add-vRLISmtpConfiguation { ) Try { - Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null - if ($accessToken) { - $vrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass - Request-vRLIToken -fqdn $vrliDetails.fqdn -username $vrliDetails.adminUser -password $vrliDetails.adminPass | Out-Null - if (Test-Connection -ComputerName $smtpServer -Quiet -Count 1) { - if ($vrliResponse.sessionId) { - 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 ($($vrliDetails.fqdn)) with SMTP server ($smtpServer): SUCCESSFUL" - } - else { - Write-Warning "Configuring SMTP Server in vRealize Log Insight ($($vrliDetails.fqdn)) with SMTP server ($smtpServer): FAILED" + 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" + } } } - else { - Write-Warning "Configuring SMTP Server in vRealize Log Insight ($($vrliDetails.fqdn)) with SMTP server ($smtpServer), already exists: SKIPPED" - } - } - else { - Write-Error "Unable to obtain access token from vRealize Log ($($vrliDetails.fqdn)), check credentials" } } - else { - Write-Error "Unable to communicate with SMTP Server ($smtpServer), check details" - } - } - else { - Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials" } } Catch { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-vRLISmtpConfiguation +Export-ModuleMember -Function Add-vRLISmtpConfiguration Function Add-vRLIAuthenticationWSA { <# .SYNOPSIS - Configure vRealize Log Insight Intergration with Workspace ONE Access + 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 to retrive the NSX Manager details from its inventory and then: - - Configures Workspace ONE Access Intergration on vRealize Log Insight + .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 assigns enables Workspace ONE Access integration on vRealize Suite Lifecycle Manager - #> + .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, @@ -4303,30 +4980,33 @@ Function Add-vRLIAuthenticationWSA { ) Try { - $vrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass - Request-vRLIToken -fqdn $vrliDetails.fqdn -username $vrliDetails.adminUser -password $vrliDetails.adminPass | Out-Null - if (Test-Connection -ComputerName $wsaFqdn -Quiet -Count 1) { - if ($vrliResponse.sessionId) { - if (($configurationStatus = Get-vRLIAuthenticationWSA).enabled -eq $false) { - Set-vRLIAuthenticationWSA -hostname $wsaFqdn -port 443 -redirectUrl $vrliDetails.fqdn -username $wsaUser -password $wsaPass - if (($configurationStatus = Get-vRLIAuthenticationWSA).enabled -eq $true) { - Write-Output "Configuring Workspace ONE Access Integration in vRealize Log Insight ($($vrliDetails.fqdn)) with ($wsaFqdn): SUCCESSFUL" - } - else { - Write-Error "Configuring Workspace ONE Access Integration in vRealize Log Insight ($($vrliDetails.fqdn)) with ($wsaFqdn): FAILED" - } - } - else { - Write-Warning "Configuring Workspace ONE Access Integration in vRealize Log Insight ($($vrliDetails.fqdn)) with ($wsaFqdn), already exists: SKIPPED" + 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" + } + } + } } } - else { - Write-Error "Unable to obtain access token from vRealize Log ($($vrliDetails.fqdn)), check credentials" - } - } - else { - Write-Error "Unable to communicate with Workspace ONE Access Instance ($wsaFqdn), check details" - } + } } Catch { Debug-ExceptionWriter -object $_ @@ -4337,20 +5017,23 @@ Export-ModuleMember -Function Add-vRLIAuthenticationWSA Function Install-vRLIPhotonAgent { <# .SYNOPSIS - Install vRealize Log Insight Photon Agent + Install vRealize Log Insight Photon Agent in a Virtual Machine - .DESCRIPTION - The Install-vRLIPhotonAgent cmdlet installs and configures the vRealize Log Insight Photon Agent. The cmdlet connects - to SDDC Manager using the -server, -user, and -password values to retrive the vRealize Log Insight and vCenter Server - details from its inventory and then: - - Authenticates to the vCenter Server + .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 - - Configured the liagent.ini File to communicate with the vRealize Log Insight Cluster + - 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 a virtual machine named sfo-wsa01 - #> + .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, @@ -4361,63 +5044,66 @@ Function Install-vRLIPhotonAgent { ) Try { - $vcenter = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT - $vrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass - if ($vrliDetails) { - Connect-VIServer -Server $vcenter.fqdn -User $vcenter.ssoAdmin -pass $vcenter.ssoAdminPass | Out-Null - if ($DefaultVIServer.Name -eq $($vcenter.fqdn)) { - if (Get-VM -Name $vmName -Server $vcenter.fqdn -ErrorAction SilentlyContinue) { - $output = Invoke-VMScript -VM $vmName -ScriptText "systemctl status liagentd" -GuestUser root -GuestPassword $vmRootPass -Server $vcenter.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 $vcenter.fqdn | Out-Null - $installAgent = @( - "curl -k -o /tmp/liagent.rpm https://$($vrliDetails.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 $vcenter.fqdn | Out-Null - } - $output = Invoke-VMScript -VM $vmName -ScriptText "chmod 777 /tmp/installAgent.sh && /tmp/installAgent.sh" -GuestUser root -GuestPassword $vmRootPass -Server $vcenter.fqdn - if ($output.ScriptOutput.Contains("/lib/systemd/system/liagentd.service; enabled")) { - $configureAgent = @( - "sed -i 's/;hostname=LOGINSIGHT/hostname=$($vrliDetails.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 $vcenter.fqdn | Out-Null - } - $output = Invoke-VMScript -VM $vmName -ScriptText "chmod 777 /tmp/configureAgent.sh && /tmp/configureAgent.sh" -GuestUser root -GuestPassword $vmRootPass -Server $vcenter.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): FAILED" + 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" + } + } + } } } - else { - Write-Error "Enabling vRealize Log Insight Agent Installed and Configured on ($vmName): FAILED" - } } } - else { - Write-Error "Virtual Machine ($vmName), not Found in vCenter Server ($($vcenter.fqdn)) Inventory, check details and try again" - } - } - else { - Write-Error "Unable to connect to vCenter Server ($($vcenter.fqdn))" } } - else { - Write-Error "vRealize Log Insight Not Found in SDDC Manager ($server) Inventory, must be Deployed in VMware Cloud Foundation Aware-Mode" - } } Catch { Debug-ExceptionWriter -object $_ @@ -4428,18 +5114,24 @@ Export-ModuleMember -Function Install-vRLIPhotonAgent Function Add-vRLIAgentGroup { <# .SYNOPSIS - Creates an agent group + Creates an agent group in vRealize Log Insight - .DESCRIPTION - The Add-vRLIAgentGroup cmdlet creates new agent groups in vRealize Log Insight. The cmdlet connects to SDDC - Manager using the -server, -user, and -password values to retrive the vRealize Log Insight details from its - inventory and then: - - Creates an agent group + .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 -criteria sfo-wsa01.sfo.rainpole.io - This example assigns enables Workspace ONE Access integration on vRealize Suite Lifecycle Manager - #> + .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 + + .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 + #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, @@ -4450,30 +5142,34 @@ Function Add-vRLIAgentGroup { ) Try { - $vrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass - Request-vRLIToken -fqdn $vrliDetails.fqdn -username $vrliDetails.adminUser -password $vrliDetails.adminPass | Out-Null - if ($agentGroupType -eq "wsa") { - $agentName = "Workspace ONE Access - Appliance Agent Group" - } - elseif ($agentGroupType -eq "photon") { - $agentName = "Photon OS - Appliance Agent Group" - } - if ($vrliResponse.sessionId) { - 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 ($($vrliDetails.fqdn)) for ($agentName): SUCCESSFUL" - } - else { - Write-Error "Creating Agent Group in vRealize Log Insight ($($vrliDetails.fqdn)) for ($agentName): FAILED" + 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" + } + else { + Write-Error "Creating Agent Group in vRealize Log Insight ($($vcfVrliDetails.fqdn)) for ($agentName): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Creating Agent Group in vRealize Log Insight ($($vcfVrliDetails.fqdn)) for ($agentName), already exists: SKIPPED" + } + } + } } } - else { - Write-Warning "Creating Agent Group in vRealize Log Insight ($($vrliDetails.fqdn)) for ($agentName), already exists: SKIPPED" - } - } - else { - Write-Error "Unable to obtain access token from vRealize Log ($($vrliDetails.fqdn)), check credentials" } } Catch { @@ -4485,22 +5181,25 @@ Export-ModuleMember -Function Add-vRLIAgentGroup Function Register-vRLIWorkloadDomain { <# .SYNOPSIS - Connect a Workload Domain to vRealize Log Insight + 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 and then: - - Obtains the Workload Domain ID - - Connects the Workload Domain with 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 + .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 + 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, @@ -4511,33 +5210,36 @@ Function Register-vRLIWorkloadDomain { ) Try { - Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null - if ($accessToken) { - $vrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass - 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 ($($vrliDetails.fqdn)) for Workload Domain ($domain): SUCCESSFUL" - } - else { - Write-Error "Workload Domain Intergration in vRealize Log Insight ($($vrliDetails.fqdn)) for Workload Domain ($domain): FAILED" + 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" + } + } } } - else { - Write-Warning "Workload Domain Intergration in vRealize Log Insight ($($vrliDetails.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)" } } - else { - Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials" - } } Catch { Debug-ExceptionWriter -object $_ @@ -4548,18 +5250,22 @@ Export-ModuleMember -Function Register-vRLIWorkloadDomain Function Set-vRLISyslogEdgeCluster { <# .SYNOPSIS - Configure Syslog settings on NSX Edge Cluster + 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 and then: - - Gathers the Edge Node details - - Configures the Syslog settings + .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 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 - .EXAMPLE - Set-vRLISyslogEdgeCluster -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -exportname SFO-VRLI - This example ENABLES the Workload Domain in vRealize Log Insight - #> + .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, @@ -4570,39 +5276,36 @@ Function Set-vRLISyslogEdgeCluster { ) Try { - Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null - if ($accessToken) { - $vrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass - $nsxtManagerDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain -listNodes - Request-NsxToken -fqdn $nsxtManagerDetails.fqdn -username $nsxtManagerDetails.adminUser -password $nsxtManagerDetails.AdminPass | Out-Null - if ($accessToken) { - [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 $vrliDetails.fqdn})) { - Set-NsxtSyslogExporter -transport -id $nodeId -exporterName $exportName -logLevel INFO -port 514 -protocol TCP -server $vrliDetails.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): FAILED" + 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" + } + 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" + } } } - else { - Write-Warning "Configuring Syslog Server ($($vrliDetails.fqdn)) on Edge Node ($nodeId), already exists: SKIPPED" - } - } - else { - Write-Warning "Configuring Syslog Exporter ($exportName) on Edge Node ($nodeId), already exists: SKIPPED" } - } + } } - else { - Write-Error "Unable to obtain access token from NSX Manager ($($nsxtManagerDetails.fqdn)), check credentials" - } - } - else { - Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials" } } Catch { @@ -4614,20 +5317,22 @@ Export-ModuleMember -Function Set-vRLISyslogEdgeCluster Function Add-vRLILogArchive { <# .SYNOPSIS - Configure log archiving + 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 to retrive the vRealize Log Insight details from its - inventory and then: - - Configure an email address to send notifications - - Configure the log retention threshold - - Configure log archive location + .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 assigns enables Workspace ONE Access integration on vRealize Suite Lifecycle Manager - #> + .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, @@ -4641,17 +5346,20 @@ Function Add-vRLILogArchive { ) Try { - $vrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass - Request-vRLIToken -fqdn $vrliDetails.fqdn -username $vrliDetails.adminUser -password $vrliDetails.adminPass | Out-Null - if ($vrliResponse.sessionId) { - 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" - } - else { - Write-Error "Unable to obtain access token from vRealize Log ($($vrliDetails.fqdn)), check credentials" + 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 { @@ -4663,20 +5371,22 @@ Export-ModuleMember -Function Add-vRLILogArchive Function Add-vRLIAuthenticationGroup { <# .SYNOPSIS - Adds a group from the authentication provider + 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 to retrive the vRealize Log Insight - details from the SDDC Manager inventory and then: - - Connects to vRealize Log Insight - - Verifies that the group has not already been assigned access to vRealize Log Insight - - Adds the group to the access control assigning the role provided + .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' + .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, @@ -4688,30 +5398,33 @@ Function Add-vRLIAuthenticationGroup { ) Try { - $vrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass - Request-vRLIToken -fqdn $vrliDetails.fqdn -username $vrliDetails.adminUser -password $vrliDetails.adminPass | Out-Null - if ($vrliResponse.sessionId) { - 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 ($($vrliDetails.fqdn)), named ($group): SUCCESSFUL" - } - else { - Write-Warning "Adding Group to vRealize Log Insight ($($vrliDetails.fqdn)), named ($group): FAILED" + 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" + } + } } } - else { - Write-Warning "Adding Group to vRealize Log Insight ($($vrliDetails.fqdn)), named ($group), already exists: SKIPPED" - } - } - else { - Write-Error "Workspace ONE Integration on vRealize Log Insight ($($vrliDetails.fqdn)), not enabled: FAILED" } } - else { - Write-Error "Unable to obtain access token from vRealize Log ($($vrliDetails.fqdn)), check credentials" - } } Catch { Debug-ExceptionWriter -object $_ @@ -4719,1484 +5432,1292 @@ Function Add-vRLIAuthenticationGroup { } Export-ModuleMember -Function Add-vRLIAuthenticationGroup -########################################### E N D O F F U N C T I O N S ########################################## -######################################################################################################################## +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 -######################################################################################################################## -############### I N T E L L I G E N T O P E R A T I O N S M A N A G E M E N T F U N C T I O N S ################ + .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 + #> -Function Export-vROPsJsonSpec { Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$username, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$password, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$workbook + [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 ) - 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 + $adapter = "VMWARE" # Defines the vRealize Operations Manager Adapter type + $resource = "Datacenter" # Defines the vRealize Operations Manager Resource type associated with the Adapter - ### Obtain Configuration Information from vRealize Suite Lifecycle Manager - Request-vRSLCMToken -fqdn $server -username $username -password $password | Out-Null - if (($vrslcmHealth = Get-vRSLCMHealth).'vrlcm-server' -eq "UP") { - if ($pnpWorkbook.Workbook.Names["vrops_license"].Value) { - $licenseKey = $pnpWorkbook.Workbook.Names["vrops_license"].Value - } - else { - $licenseKey = $pnpWorkbook.Workbook.Names["vrs_license"].Value - } - $vropsLicense = Get-vRSLCMLockerLicense | Where-Object {$_.key -eq $licenseKey} - if ($vropsLicense.key -eq $licenseKey) { - $vropsCertificate = Get-vRSLCMLockerCertificate | Where-Object {$_.alias -eq $pnpWorkbook.Workbook.Names["xreg_vrops_virtual_hostname"].Value} - if ($vropsCertificate.alias) { - $defaultPassword = Get-vRSLCMLockerPassword | Where-Object {$_.alias -eq $pnpWorkbook.Workbook.Names["vrslcm_xreg_env_password_alias"].Value} - if ($defaultPassword.alias) { - $vropsPassword = Get-vRSLCMLockerPassword | Where-Object {$_.alias -eq $pnpWorkbook.Workbook.Names["xreg_vrops_root_password_alias"].Value} - if ($vropsPassword.alias) { - $vcCredentials = Get-vRSLCMLockerPassword | Where-Object {$_.alias -eq (($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["vrslcm_xreg_dc"].Value} - if ($datacenterName) { - $xintEnvironment = Get-vRSLCMEnvironment | Where-Object {$_.environmentName -eq $pnpWorkbook.Workbook.Names["vrslcm_xreg_env"].Value} - $pnpWorkbook.Workbook.Names["xint-m01-fd-vrops"].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:" + $($defaultPassword.vmid) + ":" + $($defaultPassword.alias)) - 'certificate' = ("locker:certificate:" + $($vropsCertificate.vmid) + ":" + $($vropsCertificate.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 - '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:" + $($vropsCertificate.vmid) + ":" + $($vropsCertificate.alias)) - 'productPassword' = ("locker:password:" + $($vropsPassword.vmid) + ":" + $($vropsPassword.alias)) - 'licenseRef' = ("locker:license:" + $($vropsLicense.vmid) + ":" + $($vropsLicense.alias)) - 'disableTls' = "TLSv1,TLSv1.1" - 'fipsMode' = "false" - 'timeSyncMode' = "ntp" - 'masterVidmEnabled' = $true - 'ntp' = $pnpWorkbook.Workbook.Names["region_ntp1_server"].Value - 'affinityRule' = $false - 'configureAffinitySeparateAll' = "true" - 'deployOption' = $pnpWorkbook.Workbook.Names["xreg_vrops_appliance_size"].Value.ToLower() - 'isCaEnabled' = "false" - } - - #### Generate vRealize Log Insight Cluster Details - $clusterVipProperties = @() - $clusterVipProperties += [pscustomobject]@{ - 'hostName' = $pnpWorkbook.Workbook.Names["xreg_vrops_virtual_fqdn"].Value - } - - $clusterVipsObject = @() - $clusterVipsObject += [pscustomobject]@{ - 'type' = "vrops-cluster" - 'properties' = ($clusterVipProperties | Select-Object -Skip 0) - } - - $clusterObject = @() - $clusterObject += [pscustomobject]@{ - 'clusterVips' = $clusterVipsObject - } - - #### Generate vRealize Log Insight Node Details - $masterProperties = @() - $masterProperties += [pscustomobject]@{ - 'vmName' = $pnpWorkbook.Workbook.Names["xreg_vrops_nodea_hostname"].Value - 'hostName' = $pnpWorkbook.Workbook.Names["xreg_vrops_nodea_fqdn"].Value - 'ip' = $pnpWorkbook.Workbook.Names["xreg_vrops_nodea_ip"].Value - 'gateway' = $pnpWorkbook.Workbook.Names["xreg_seg01_gateway_ip"].Value - 'domain' = $pnpWorkbook.Workbook.Names["region_ad_parent_fqdn"].Value - 'searchpath' = $pnpWorkbook.Workbook.Names["parent_dns_zone"].Value - 'dns' = ($pnpWorkbook.Workbook.Names["region_dns1_ip"].Value + "," + $pnpWorkbook.Workbook.Names["region_dns2_ip"].Value) - 'netmask' = $pnpWorkbook.Workbook.Names["xreg_seg01_mask"].Value - 'timeZone' = "UTC" - 'vCenterHost' = $pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value - 'cluster' = ($pnpWorkbook.Workbook.Names["mgmt_datacenter"].Value + "#" + $pnpWorkbook.Workbook.Names["mgmt_cluster"].Value) - 'network' = $pnpWorkbook.Workbook.Names["xreg_seg01_name"].Value - 'storage' = $pnpWorkbook.Workbook.Names["mgmt_vsan_datastore"].Value - 'diskMode' = "thin" - 'vCenterName' = ($pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value).Split(".")[0] - 'vcUsername' = $vcCredentials.userName - 'vcPassword' = ("locker:password:" + $($vcCredentials.vmid) + ":" + $($vcCredentials.alias)) - 'ntp' = $pnpWorkbook.Workbook.Names["xregion_ntp1_server"].Value - } - - $replicaProperties = @() - $replicaProperties += [pscustomobject]@{ - 'vmName' = $pnpWorkbook.Workbook.Names["xreg_vrops_nodeb_hostname"].Value - 'hostName' = $pnpWorkbook.Workbook.Names["xreg_vrops_nodeb_fqdn"].Value - 'ip' = $pnpWorkbook.Workbook.Names["xreg_vrops_nodeb_ip"].Value - } - - $dataProperties = @() - $dataProperties += [pscustomobject]@{ - 'vmName' = $pnpWorkbook.Workbook.Names["xreg_vrops_nodec_hostname"].Value - 'hostName' = $pnpWorkbook.Workbook.Names["xreg_vrops_nodec_fqdn"].Value - 'ip' = $pnpWorkbook.Workbook.Names["xreg_vrops_nodec_ip"].Value - } - - $remoteCollector1Properties = @() - $remoteCollector1Properties += [pscustomobject]@{ - 'vmName' = $pnpWorkbook.Workbook.Names["region_vropsca_hostname"].Value - 'hostName' = $pnpWorkbook.Workbook.Names["region_vropsca_fqdn"].Value - 'ip' = $pnpWorkbook.Workbook.Names["region_vropsca_ip"].Value - 'deployOption' = "smallrc" - 'gateway' = $pnpWorkbook.Workbook.Names["reg_seg01_gateway_ip"].Value - 'domain' = $pnpWorkbook.Workbook.Names["region_ad_parent_fqdn"].Value - 'searchpath' = $pnpWorkbook.Workbook.Names["region_ad_child_fqdn"].Value - 'dns' = ($pnpWorkbook.Workbook.Names["region_dns1_ip"].Value + "," + $pnpWorkbook.Workbook.Names["region_dns2_ip"].Value) - 'netmask' = $pnpWorkbook.Workbook.Names["reg_seg01_mask_overlay_backed"].Value - 'timeZone' = "UTC" - 'vCenterHost' = $pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value - 'cluster' = ($pnpWorkbook.Workbook.Names["mgmt_datacenter"].Value + "#" + $pnpWorkbook.Workbook.Names["mgmt_cluster"].Value) - 'network' = $pnpWorkbook.Workbook.Names["reg_seg01_name"].Value - 'storage' = $pnpWorkbook.Workbook.Names["mgmt_vsan_datastore"].Value - 'diskMode' = "thin" - 'vCenterName' = ($pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value).Split(".")[0] - 'vcUsername' = $vcCredentials.userName - 'vcPassword' = ("locker:password:" + $($vcCredentials.vmid) + ":" + $($vcCredentials.alias)) - 'ntp' = $pnpWorkbook.Workbook.Names["xregion_ntp1_server"].Value - } - - $remoteCollector2Properties = @() - $remoteCollector2Properties += [pscustomobject]@{ - 'vmName' = $pnpWorkbook.Workbook.Names["region_vropscb_hostname"].Value - 'hostName' = $pnpWorkbook.Workbook.Names["region_vropscb_fqdn"].Value - 'ip' = $pnpWorkbook.Workbook.Names["region_vropscb_ip"].Value - 'deployOption' = "smallrc" - 'gateway' = $pnpWorkbook.Workbook.Names["reg_seg01_gateway_ip"].Value - 'domain' = $pnpWorkbook.Workbook.Names["region_ad_parent_fqdn"].Value - 'searchpath' = $pnpWorkbook.Workbook.Names["region_ad_child_fqdn"].Value - 'dns' = ($pnpWorkbook.Workbook.Names["region_dns1_ip"].Value + "," + $pnpWorkbook.Workbook.Names["region_dns2_ip"].Value) - 'netmask' = $pnpWorkbook.Workbook.Names["reg_seg01_mask_overlay_backed"].Value - 'timeZone' = "UTC" - 'vCenterHost' = $pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value - 'cluster' = ($pnpWorkbook.Workbook.Names["mgmt_datacenter"].Value + "#" + $pnpWorkbook.Workbook.Names["mgmt_cluster"].Value) - 'network' = $pnpWorkbook.Workbook.Names["reg_seg01_name"].Value - 'storage' = $pnpWorkbook.Workbook.Names["mgmt_vsan_datastore"].Value - 'diskMode' = "thin" - 'vCenterName' = ($pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value).Split(".")[0] - 'vcUsername' = $vcCredentials.userName - 'vcPassword' = ("locker:password:" + $($vcCredentials.vmid) + ":" + $($vcCredentials.alias)) - 'ntp' = $pnpWorkbook.Workbook.Names["xregion_ntp1_server"].Value - } - - $nodesObject = @() - $nodesobject += [pscustomobject]@{ - 'type' = "master" - 'properties' = ($masterProperties | Select-Object -Skip 0) - } - $nodesobject += [pscustomobject]@{ - 'type' = "replica" - 'properties' = ($replicaProperties | Select-Object -Skip 0) - } - $nodesobject += [pscustomobject]@{ - 'type' = "data" - 'properties' = ($dataProperties | Select-Object -Skip 0) - } - $nodesobject += [pscustomobject]@{ - 'type' = "remotecollector" - 'properties' = ($remoteCollector1Properties | Select-Object -Skip 0) - } - $nodesobject += [pscustomobject]@{ - 'type' = "remotecollector" - 'properties' = ($remoteCollector2Properties | Select-Object -Skip 0) - } - - #### Generate the vRealize Log Insight Properties Section - $productsObject = @() - $productsObject += [pscustomobject]@{ - 'id' = "vrops" - 'version' = "8.4.0" - 'properties' = ($productPropertiesObject | Select-Object -Skip 0) - 'clusterVIP' = ($clusterObject | Select-Object -Skip 0) - 'nodes' = $nodesObject - } - - if (!($xintEnvironment)) { - $vropsDeploymentObject = @() - $vropsDeploymentObject += [pscustomobject]@{ - 'environmentName' = $pnpWorkbook.Workbook.Names["vrslcm_xreg_env"].Value - 'infrastructure' = ($infrastructureObject | Select-Object -Skip 0) - 'products' = $productsObject - } - } - else { - $vropsDeploymentObject = @() - $vropsDeploymentObject += [pscustomobject]@{ - 'environmentId' = $xintEnvironment.environmentId - 'environmentName' = $pnpWorkbook.Workbook.Names["vrslcm_xreg_env"].Value - 'infrastructure' = ($infrastructureObject | Select-Object -Skip 0) - 'products' = $productsObject + 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 (($vcfVropsDetails = Get-vROPSServerDetail -fqdn $server -username $user -password $pass)) { + 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) { + if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) { + if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.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" + } + } } } - - $vropsDeploymentObject | ConvertTo-Json -Depth 12 | Out-File -Encoding UTF8 -FilePath "vropsDeploymentSpec.json" - - Write-Output "Creation of Deployment JSON Specification file for vRealize Operations Manager: 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["xreg_vrops_root_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["vrslcm_xreg_env_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_vrops_virtual_hostname"].Value)' not found in the vRealize Suite Lifecycle Manager Locker, add and retry" + } } } - else { - Write-Error "License with alias '$licenseKey' not found in the vRealize Suite Lifecycle Manager Locker, add and retry" - } } else { - Write-Error "Unable to obtain access token from vRealize Suite Lifecycle Manager ($server), check credentials" + Write-Error "Unable to find template Alert JSON ($alertTemplate): PRE_VALIDATION_FAILED" } - Close-ExcelPackage $pnpWorkbook -NoSave -ErrorAction SilentlyContinue } Catch { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Export-vROPsJsonSpec +Export-ModuleMember -Function Add-vRLIAlertDatacenter -Function New-vROPSDeployment { +Function Add-vRLIAlertVirtualMachine { <# - .SYNOPSIS - Deploy vRealize Operations Manager to vRealize Suite Lifecycle Manager + .SYNOPSIS + Adds virtual machine based alerts in vRealize Log Insight .DESCRIPTION - The New-vROPSDeployment cmdlet deploys vRealize Operations Manager via vRealize Suite Lifecycle Manager. The cmdlet - connects to SDDC Manager using the -server, -user, and -password values to retrive the vRSLCM details from its - inventory and then: - - Verifies that the environment does not already exist - - Requests a new deployment of vRealize Operations Manager + 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 + - 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 Virtual Machine object provided is valid in the vCenter Server inventory + - Creates the alert in vRealize Log Insight for the Virtual Machine object if not already configured + - Integrates with vRealize Operations Manager if the -vropsIntegration switch is provided .EXAMPLE - New-vROPSDeployment -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -workbook .\pnp-workbook.xlsx - This example starts a deployment of vRealize Operations Manager using the Planning and Preparation Workbook + Add-vRLIAlertVirtualMachine -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -sddcDomainName sfo-m01 -vmName xint-vrslcm01 -email administrator@rainpole.io -alertTemplate ".\SampleNotifications\vrli-vcf-vmVrslcm.json" -vropsIntegration + This example adds the alerts provided in the JSON file for the vRealize Suite Lifecycle Manager Virtual Machine #> 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]$sddcDomainName, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vmName, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$email, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$alertTemplate, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$vropsIntegration ) - 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 - } - } + $adapter = "VMWARE" # Defines the vRealize Operations Manager Adapter type + $resource = "VirtualMachine" # Defines the vRealize Operations Manager Resource type associated with the Adapter Try { - $vrslcm = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass - Request-vRSLCMToken -fqdn $vrslcm.fqdn -username $vrslcm.adminUser -password $vrslcm.adminPass | Out-Null - if (($vrslcmHealth = Get-vRSLCMHealth).'vrlcm-server' -eq "UP") { - Export-vROPSJsonSpec -workbook $workbook -server $vrslcm.fqdn -username $vrslcm.adminUser -password $vrslcm.adminPass | Out-Null - $json = (Get-Content -Raw .\vropsDeploymentSpec.json) - $jsonSpec = $json | ConvertFrom-Json - if (!($checkProducts = (Get-vRSLCMEnvironment | Where-Object {$_.environmentName -eq $jsonSpec.environmentName}).products.id -contains $jsonSpec.products.id)) { - if (Get-vRSLCMLockerPassword | Where-Object {$_.alias -Match $($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])}) { - if ($jsonSpec.environmentId) { - $newRequest = Add-vRSLCMEnvironment -json $json -environmentId $jsonSpec.environmentId -addProduct -WarningAction SilentlyContinue -ErrorAction SilentlyContinue - } - else { - $newRequest = Add-vRSLCMEnvironment -json $json -WarningAction SilentlyContinue -ErrorAction SilentlyContinue - } - if ($newRequest) { - if ($PsBoundParameters.ContainsKey("monitor")) { - Start-Sleep 10 - Watch-vRSLCMRequest -vmid $($newRequest.requestId) - } - else { - Write-Output "Deployment Rquest for vRealize Operations Manager Submitted Successfully (Request Ref: $($newRequest.requestId))" + 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 (($vcfVropsDetails = Get-vROPSServerDetail -fqdn $server -username $user -password $pass)) { + 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-VM $vmName -ErrorAction Ignore ) { + if (Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass) { + if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) { + if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass) { + $templateAlerts = (Get-Content -path $alertTemplate -Raw) + $templateAlerts = $templateAlerts -replace '!!vmName!!',$vmName + $templateAlerts = $templateAlerts -replace '!!email!!',$email + [Array]$allAlerts = $templateAlerts | ConvertFrom-Json + foreach ($alert in $allAlerts) { + $json = $alert | ConvertTo-Json + if ($PsBoundParameters.ContainsKey("vropsIntegration")) { + $VMEntityInstanceUUID =(Get-vROPSResourceDetail -adapter $adapter -resource $resource -objectname $vmName | Where-Object {$_.identifierType.name -eq "VMEntityInstanceUUID"}).value + $VMEntityObjectID =(Get-vROPSResourceDetail -adapter $adapter -resource $resource -objectname $vmName | Where-Object {$_.identifierType.name -eq "VMEntityObjectID"}).value + $VMEntityVCID =(Get-vROPSResourceDetail -adapter $adapter -resource $resource -objectname $vmName | Where-Object {$_.identifierType.name -eq "VMEntityVCID"}).value + $VMServiceMonitoringEnabled =(Get-vROPSResourceDetail -adapter $adapter -resource $resource -objectname $vmName | Where-Object {$_.identifierType.name -eq "VMServiceMonitoringEnabled"}).value + $isPingEnabled =(Get-vROPSResourceDetail -adapter $adapter -resource $resource -objectname $vmName | Where-Object {$_.identifierType.name -eq "isPingEnabled"}).value + $vcopsResourceKindKey = '"vcopsResourceKindKey": "' + 'resourceName='+ $vmName +'&adapterKindKey='+ $adapter+ '&resourceKindKey='+ $resource +'&identifiers=VMEntityInstanceUUID::'+ $VMEntityInstanceUUID +'$$$VMEntityName::'+ $vmName + '$$$VMEntityObjectID::'+ $VMEntityObjectID +'$$$VMEntityVCID::'+ $VMEntityVCID +'$$$VMServiceMonitoringEnabled::'+ $VMServiceMonitoringEnabled +'$$$isPingEnabled::'+ $isPingEnabled +'"' + $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 Virtual Machine Alerts in vRealize Log Insight ($($vcfVrliDetails.fqdn)) using template Alert JSON ($alertTemplate) for Workload Domain ($sddcDomainName): SUCCESSFUL" + } + } + } + } + else { + Write-Error "Unable to find Virtual Machine ($vmName) in vCenter Server ($($vcfVcenterDetails.fqdn)): PRE_VALIDATION_FAILED" + } + } + } } } - else { - Write-Error "Request to deploy vRealize Operations Manager failed, check the vRealize Suite Lifecycle Manager UI" - } - } - else { - Write-Error "License in vRealize Suite Lifecycle Manager ($($vrslcm.fqdn)) Locker with alias ($($jsonSpec.products.properties.licenseRef.Split(":")[3])), does not exist: FAILED" } - } - else { - Write-Error "Certificate in vRealize Suite Lifecycle Manager ($($vrslcm.fqdn)) Locker with alias ($($jsonSpec.products.properties.certificate.Split(":")[3])), does not exist: FAILED" - } + } } - else { - Write-Error "Password in vRealize Suite Lifecycle Manager ($($vrslcm.fqdn)) Locker with alias ($($jsonSpec.products.properties.productPassword.Split(":")[3])), does not exist: FAILED" - } - } - else { - Write-Warning "vRealize Operations Manager in environment ($($jsonSpec.environmentName)) on vRealize Suite Lifecycle Manager ($($vrslcm.fqdn)), already exists: SKIPPED" } } else { - Write-Error "Unable to obtain access token from vRealize Suite Lifecycle Manager ($server), check credentials" + Write-Error "Unable to find template Alert JSON ($alertTemplate): PRE_VALIDATION_FAILED" } } Catch { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function New-vROPSDeployment +Export-ModuleMember -Function Add-vRLIAlertVirtualMachine -Function Register-vROPSWorkloadDomain { +Function Undo-vRLIAlert { <# .SYNOPSIS - Connect a Workload Domain to vRealize Operations Manager + Removes alerts from vRealize Log Insight - .DESCRIPTION - The Register-vROPSWorkloadDomain cmdlet connects a Workload Domain to vRealize Operations Manager. - The cmdlet connects to SDDC Manager using the -server, -user, and -password values and then: - - Obtains the Workload Domain ID - - Connects the Workload Domain with vRealize Opertations Manager - - .EXAMPLE - Register-vROPSWorkloadDomain -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 Opertations Manager + .DESCRIPTION + The Undo-vRLIAlert cmdlet removes datacenter based alerts from 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 + - Deletes all alerts with the name provided in the title .EXAMPLE - Register-vROPSWorkloadDomain -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 Opertations Manager - #> + Undo-vRLIAlert -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -name sfo-m01-dc01 + This example removes all alerts that contain the name 'sfo-m01-dc01' + #> 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 + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$name ) Try { - Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null - if ($accessToken) { - $vropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass - if (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}) { - if ((Get-VCFvROPSConnection | Where-Object {$_.domainId -eq (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}).id}).status -ne $status) { - Set-VCFvROPSConnection -domainId (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}).id -status $status | Out-Null - Start-Sleep 10 - Do { - $configStatus = (Get-VCFvROPSConnection | Where-Object {$_.domainId -eq (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}).id}).status - } Until ($configStatus -ne "IN_PROGRESS") - if ((Get-VCFvROPSConnection | Where-Object {$_.domainId -eq (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}).id}).status -eq $status) { - Write-Output "Enabling Workload Domain Intergation with vRealize Opertations Manager ($($vropsDetails.loadBalancerFqdn)) for domain ($domain): SUCCESSFUL" - } - else { - Write-Error "Enabling Workload Domain Intergation with vRealize Opertations Manager ($($vropsDetails.loadBalancerFqdn)) for domain ($domain): FAILED" + 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 ($allAlerts = Get-vRLIAlert | Where-Object {$_.name -match $name} | Select-Object name, id) { + Foreach ($alert in $allAlerts) { + Remove-vRLIAlert -alertId $alert.id | Out-Null + } + Write-Output "Removing Alerts in vRealize Log Insight ($($vcfVrliDetails.fqdn)) with name ($name): SUCCESSFUL" + } + else { + Write-Warning "Removing Alerts in vRealize Log Insight ($($vcfVrliDetails.fqdn)) for name ($name), none exist: SKIPPED" + } + } } - } - else { - Write-Warning "Enabling Workload Domain Intergation with vRealize Opertations Manager ($($vropsDetails.loadBalancerFqdn)) for domain ($domain), already enabled: SKIPPED" - } - } - else { - 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" - } } Catch { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Register-vROPSWorkloadDomain +Export-ModuleMember -Function Undo-vRLIAlert -Function Update-vROPSAdapterVcenter { +########################################### 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 O P E R A T I O N S M A N A G E M E N T F U N C T I O N S ############### + +Function Export-vROPsJsonSpec { <# - .SYNOPSIS - Reconfigures assigned Remove Collector Group for vCenter Adapter + .SYNOPSIS + Create vRealize Operations Manager Deployment JSON specification - .DESCRIPTION - The Update-vROPSAdapterVcenter cmdlet reconfigures the assigned Remove Collector Group for vCenter Adapter in vRealize Operations Manager. - The cmdlet connects to SDDC Manager using the -server, -user, and -password values and then: - - Obtains the vRealize Opertaions Manager details - - Obtains the Remote Collector details - - Obtains the vCenter Adapter details from vRelize Operations Manager - - Reconfigures the assigned Remote Collector Group + .DESCRIPTION + The Export-vROPsJsonSpec cmdlet creates the JSON specification file using the Planning and Preparation workbook + to deploy vRealize Operations Manager 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 'vropsDeploymentSpec.json' - .EXAMPLE - Update-vROPSAdapterVcenter -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -collectorGroupName "sfo-remote-collectors" - This example reconfigures all vCenter Adapters to use the provided remote collector group - #> + .EXAMPLE + Export-vROPsJsonSpec -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 Operations 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 = $true)] [ValidateNotNullOrEmpty()] [String]$collectorGroupName + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$workbook ) Try { - Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null - if ($accessToken) { - $vropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass - Request-vROPSToken -fqdn $vropsDetails.loadBalancerFqdn -username $vropsDetails.adminUser -password $vropsDetails.adminPass | Out-Null - if ($vropsHeaders.Authorization) { - if (Get-vROPSCollectorGroup | Where-Object {$_.name -eq $collectorGroupName}) { - $collectorGroupId = (Get-vROPSCollectorGroup | Where-Object {$_.name -eq $collectorGroupName}).id - $adapters = Get-vROPSAdapter | Where-Object {$_.resourceKey.adapterKindKey -eq "VMWARE"} - Foreach ($adapter in $adapters) { - $vcurl = ((Get-vROPSAdapter -id $adapter.id).resourceKey.resourceIdentifiers | Where-Object {$_.identifierType.name -eq "VCURL"}).value - $json = '{ - "resourceKey" : { - "name" : "'+ $($adapter.resourceKey.name) +'", - "adapterKindKey" : "NSXTAdapter", - "resourceKindKey" : "VMwareAdapter Instance", - "resourceIdentifiers" : [ { - "identifierType" : { - "name" : "AUTODISCOVERY", - "dataType" : "STRING", - "isPartOfUniqueness" : true - }, - "value" : "true" - }, { - "identifierType" : { - "name" : "PROCESSCHANGEEVENTS", - "dataType" : "STRING", - "isPartOfUniqueness" : true - }, - "value" : "true" - }, { - "identifierType" : { - "name" : "VCURL", - "dataType" : "STRING", - "isPartOfUniqueness" : true - }, - "value" : "'+ $vcurl +'" - } ] - }, - "description" : "'+ $($adapter.description) +'", - "id" : "'+ $($adapter.id) +'", - "collectorGroupId": "'+ $($collectorGroupId) +'" - }' - - $json | Out-File .\updateAdapter.json - if (!($($adapter.collectorGroupId) -eq $collectorGroupId)) { - Set-vROPSAdapter -json .\updateAdapter.json | Out-Null - Write-Output "Assigned vCenter Adapter in vRealize Operations Manager in ($($vropsDetails.loadBalancerFqdn)) to Remote Collector Group ($collectorGroupName): SUCCESSFUL" - } - else { - Write-Warning "vCenter Adapter: $($adapter.resourceKey.name) already assigned to $collectorGroupName in '$($vropsDetails.loadBalancerFqdn), skipping configuration" + + 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["vrops_license"].Value) { + $licenseKey = $pnpWorkbook.Workbook.Names["vrops_license"].Value + } + else { + $licenseKey = $pnpWorkbook.Workbook.Names["vrs_license"].Value + } + $vropsLicense = Get-vRSLCMLockerLicense | Where-Object {$_.key -eq $licenseKey} + if ($vropsLicense.key -eq $licenseKey) { + if ($vropsCertificate = Get-vRSLCMLockerCertificate | Where-Object {$_.alias -eq $pnpWorkbook.Workbook.Names["xreg_vrops_virtual_hostname"].Value}) { + if ($defaultPassword = Get-vRSLCMLockerPassword | Where-Object {$_.alias -eq $pnpWorkbook.Workbook.Names["vrslcm_xreg_env_password_alias"].Value}) { + if ($vropsPassword = Get-vRSLCMLockerPassword | Where-Object {$_.alias -eq $pnpWorkbook.Workbook.Names["xreg_vrops_root_password_alias"].Value}) { + $vcCredentials = Get-vRSLCMLockerPassword | Where-Object {$_.alias -eq (($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["vrslcm_xreg_dc"].Value} + if ($datacenterName) { + $xintEnvironment = Get-vRSLCMEnvironment | Where-Object {$_.environmentName -eq $pnpWorkbook.Workbook.Names["vrslcm_xreg_env"].Value} + $pnpWorkbook.Workbook.Names["xint-m01-fd-vrops"].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:" + $($defaultPassword.vmid) + ":" + $($defaultPassword.alias)) + 'certificate' = ("locker:certificate:" + $($vropsCertificate.vmid) + ":" + $($vropsCertificate.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 + '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:" + $($vropsCertificate.vmid) + ":" + $($vropsCertificate.alias)) + 'productPassword' = ("locker:password:" + $($vropsPassword.vmid) + ":" + $($vropsPassword.alias)) + 'licenseRef' = ("locker:license:" + $($vropsLicense.vmid) + ":" + $($vropsLicense.alias)) + 'disableTls' = "TLSv1,TLSv1.1" + 'fipsMode' = "false" + 'timeSyncMode' = "ntp" + 'masterVidmEnabled' = $true + 'ntp' = $pnpWorkbook.Workbook.Names["region_ntp1_server"].Value + 'affinityRule' = $false + 'configureAffinitySeparateAll' = "true" + 'deployOption' = $pnpWorkbook.Workbook.Names["xreg_vrops_appliance_size"].Value.ToLower() + 'isCaEnabled' = "false" + } + + #### Generate vRealize Log Insight Cluster Details + $clusterVipProperties = @() + $clusterVipProperties += [pscustomobject]@{ + 'hostName' = $pnpWorkbook.Workbook.Names["xreg_vrops_virtual_fqdn"].Value + } + + $clusterVipsObject = @() + $clusterVipsObject += [pscustomobject]@{ + 'type' = "vrops-cluster" + 'properties' = ($clusterVipProperties | Select-Object -Skip 0) + } + + $clusterObject = @() + $clusterObject += [pscustomobject]@{ + 'clusterVips' = $clusterVipsObject + } + + #### Generate vRealize Log Insight Node Details + $masterProperties = @() + $masterProperties += [pscustomobject]@{ + 'vmName' = $pnpWorkbook.Workbook.Names["xreg_vrops_nodea_hostname"].Value + 'hostName' = $pnpWorkbook.Workbook.Names["xreg_vrops_nodea_fqdn"].Value + 'ip' = $pnpWorkbook.Workbook.Names["xreg_vrops_nodea_ip"].Value + 'gateway' = $pnpWorkbook.Workbook.Names["xreg_seg01_gateway_ip"].Value + 'domain' = $pnpWorkbook.Workbook.Names["region_ad_parent_fqdn"].Value + 'searchpath' = $pnpWorkbook.Workbook.Names["parent_dns_zone"].Value + 'dns' = ($pnpWorkbook.Workbook.Names["region_dns1_ip"].Value + "," + $pnpWorkbook.Workbook.Names["region_dns2_ip"].Value) + 'netmask' = $pnpWorkbook.Workbook.Names["xreg_seg01_mask"].Value + 'timeZone' = "UTC" + 'vCenterHost' = $pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value + 'cluster' = ($pnpWorkbook.Workbook.Names["mgmt_datacenter"].Value + "#" + $pnpWorkbook.Workbook.Names["mgmt_cluster"].Value) + 'network' = $pnpWorkbook.Workbook.Names["xreg_seg01_name"].Value + 'storage' = $pnpWorkbook.Workbook.Names["mgmt_vsan_datastore"].Value + 'diskMode' = "thin" + 'vCenterName' = ($pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value).Split(".")[0] + 'vcUsername' = $vcCredentials.userName + 'vcPassword' = ("locker:password:" + $($vcCredentials.vmid) + ":" + $($vcCredentials.alias)) + 'ntp' = $pnpWorkbook.Workbook.Names["xregion_ntp1_server"].Value + } + + $replicaProperties = @() + $replicaProperties += [pscustomobject]@{ + 'vmName' = $pnpWorkbook.Workbook.Names["xreg_vrops_nodeb_hostname"].Value + 'hostName' = $pnpWorkbook.Workbook.Names["xreg_vrops_nodeb_fqdn"].Value + 'ip' = $pnpWorkbook.Workbook.Names["xreg_vrops_nodeb_ip"].Value + } + + $dataProperties = @() + $dataProperties += [pscustomobject]@{ + 'vmName' = $pnpWorkbook.Workbook.Names["xreg_vrops_nodec_hostname"].Value + 'hostName' = $pnpWorkbook.Workbook.Names["xreg_vrops_nodec_fqdn"].Value + 'ip' = $pnpWorkbook.Workbook.Names["xreg_vrops_nodec_ip"].Value + } + + $remoteCollector1Properties = @() + $remoteCollector1Properties += [pscustomobject]@{ + 'vmName' = $pnpWorkbook.Workbook.Names["region_vropsca_hostname"].Value + 'hostName' = $pnpWorkbook.Workbook.Names["region_vropsca_fqdn"].Value + 'ip' = $pnpWorkbook.Workbook.Names["region_vropsca_ip"].Value + 'deployOption' = "smallrc" + 'gateway' = $pnpWorkbook.Workbook.Names["reg_seg01_gateway_ip"].Value + 'domain' = $pnpWorkbook.Workbook.Names["region_ad_parent_fqdn"].Value + 'searchpath' = $pnpWorkbook.Workbook.Names["region_ad_child_fqdn"].Value + 'dns' = ($pnpWorkbook.Workbook.Names["region_dns1_ip"].Value + "," + $pnpWorkbook.Workbook.Names["region_dns2_ip"].Value) + 'netmask' = $pnpWorkbook.Workbook.Names["reg_seg01_mask_overlay_backed"].Value + 'timeZone' = "UTC" + 'vCenterHost' = $pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value + 'cluster' = ($pnpWorkbook.Workbook.Names["mgmt_datacenter"].Value + "#" + $pnpWorkbook.Workbook.Names["mgmt_cluster"].Value) + 'network' = $pnpWorkbook.Workbook.Names["reg_seg01_name"].Value + 'storage' = $pnpWorkbook.Workbook.Names["mgmt_vsan_datastore"].Value + 'diskMode' = "thin" + 'vCenterName' = ($pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value).Split(".")[0] + 'vcUsername' = $vcCredentials.userName + 'vcPassword' = ("locker:password:" + $($vcCredentials.vmid) + ":" + $($vcCredentials.alias)) + 'ntp' = $pnpWorkbook.Workbook.Names["xregion_ntp1_server"].Value + } + + $remoteCollector2Properties = @() + $remoteCollector2Properties += [pscustomobject]@{ + 'vmName' = $pnpWorkbook.Workbook.Names["region_vropscb_hostname"].Value + 'hostName' = $pnpWorkbook.Workbook.Names["region_vropscb_fqdn"].Value + 'ip' = $pnpWorkbook.Workbook.Names["region_vropscb_ip"].Value + 'deployOption' = "smallrc" + 'gateway' = $pnpWorkbook.Workbook.Names["reg_seg01_gateway_ip"].Value + 'domain' = $pnpWorkbook.Workbook.Names["region_ad_parent_fqdn"].Value + 'searchpath' = $pnpWorkbook.Workbook.Names["region_ad_child_fqdn"].Value + 'dns' = ($pnpWorkbook.Workbook.Names["region_dns1_ip"].Value + "," + $pnpWorkbook.Workbook.Names["region_dns2_ip"].Value) + 'netmask' = $pnpWorkbook.Workbook.Names["reg_seg01_mask_overlay_backed"].Value + 'timeZone' = "UTC" + 'vCenterHost' = $pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value + 'cluster' = ($pnpWorkbook.Workbook.Names["mgmt_datacenter"].Value + "#" + $pnpWorkbook.Workbook.Names["mgmt_cluster"].Value) + 'network' = $pnpWorkbook.Workbook.Names["reg_seg01_name"].Value + 'storage' = $pnpWorkbook.Workbook.Names["mgmt_vsan_datastore"].Value + 'diskMode' = "thin" + 'vCenterName' = ($pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value).Split(".")[0] + 'vcUsername' = $vcCredentials.userName + 'vcPassword' = ("locker:password:" + $($vcCredentials.vmid) + ":" + $($vcCredentials.alias)) + 'ntp' = $pnpWorkbook.Workbook.Names["xregion_ntp1_server"].Value + } + + $nodesObject = @() + $nodesobject += [pscustomobject]@{ + 'type' = "master" + 'properties' = ($masterProperties | Select-Object -Skip 0) + } + $nodesobject += [pscustomobject]@{ + 'type' = "replica" + 'properties' = ($replicaProperties | Select-Object -Skip 0) + } + $nodesobject += [pscustomobject]@{ + 'type' = "data" + 'properties' = ($dataProperties | Select-Object -Skip 0) + } + $nodesobject += [pscustomobject]@{ + 'type' = "remotecollector" + 'properties' = ($remoteCollector1Properties | Select-Object -Skip 0) + } + $nodesobject += [pscustomobject]@{ + 'type' = "remotecollector" + 'properties' = ($remoteCollector2Properties | 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") { $vropsVersion = "8.4.0"} + if ($vcfVersion -eq "4.3.1") { $vropsVersion = "8.5.0"} + $productsObject = @() + $productsObject += [pscustomobject]@{ + 'id' = "vrops" + 'version' = $vropsVersion + 'properties' = ($productPropertiesObject | Select-Object -Skip 0) + 'clusterVIP' = ($clusterObject | Select-Object -Skip 0) + 'nodes' = $nodesObject + } + + if (!($xintEnvironment)) { + $vropsDeploymentObject = @() + $vropsDeploymentObject += [pscustomobject]@{ + 'environmentName' = $pnpWorkbook.Workbook.Names["vrslcm_xreg_env"].Value + 'infrastructure' = ($infrastructureObject | Select-Object -Skip 0) + 'products' = $productsObject + } + } + else { + $vropsDeploymentObject = @() + $vropsDeploymentObject += [pscustomobject]@{ + 'environmentId' = $xintEnvironment.environmentId + 'environmentName' = $pnpWorkbook.Workbook.Names["vrslcm_xreg_env"].Value + 'infrastructure' = ($infrastructureObject | Select-Object -Skip 0) + 'products' = $productsObject + } + } + + $vropsDeploymentObject | ConvertTo-Json -Depth 12 | Out-File -Encoding UTF8 -FilePath "vropsDeploymentSpec.json" + + Write-Output "Creation of Deployment JSON Specification file for vRealize Operations Manager: SUCCESSFUL" + } + else { + Write-Error "Datacenter Provided in the Planning and Preparation Workbook '$($pnpWorkbook.Workbook.Names["vrslcm_xreg_dc"].Value)' does not exist: PRE_VALIDATION_FAILED" + } + } + else { + Write-Error "Root Password with alias '$($pnpWorkbook.Workbook.Names["xreg_vrops_root_password_alias"].Value)' not found in the vRealize Suite Lifecycle Manager Locker: PRE_VALIDATION_FAILED" + } + } + else { + Write-Error "Admin Password with alias '$($pnpWorkbook.Workbook.Names["vrslcm_xreg_env_password_alias"].Value)' not found in the vRealize Suite Lifecycle Manager Locker: PRE_VALIDATION_FAILED" + } + } + else { + Write-Error "Certificate with alias '$($pnpWorkbook.Workbook.Names["xreg_vrops_virtual_hostname"].Value)' not found in the vRealize Suite Lifecycle Manager Locker: PRE_VALIDATION_FAILED" + } + } + else { + Write-Error "License with alias '$licenseKey' not found in the vRealize Suite Lifecycle Manager Locker: PRE_VALIDATION_FAILED" + } } - Remove-Item .\updateAdapter.json -Force -Confirm:$false } - } - else { - Write-Error "Remote Collector Group in vRealize Operations Manager ($($vropsDetails.loadBalancerFqdn)) named ($collectorGroupName) not found: FAILED" - } + } } - else { - Write-Error "Unable to obtain access token from vRealize Operations Manager ($($vropsDetails.loadBalancerFqdn)), check credentials" - } - } - else { - Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials" } + Close-ExcelPackage $pnpWorkbook -NoSave -ErrorAction SilentlyContinue } Catch { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Update-vROPSAdapterVcenter +Export-ModuleMember -Function Export-vROPsJsonSpec -Function Add-vROPSGroupRemoteCollectors { +Function New-vROPSDeployment { <# - .SYNOPSIS - Groups the Remote Collectors into a group + .SYNOPSIS + Deploy vRealize Operations Manager to vRealize Suite Lifecycle Manager - .DESCRIPTION - The Add-vROPSGroupRemoteCollectors cmdlet groups the remote collectors in vRealize Operations Manager. - The cmdlet connects to SDDC Manager using the -server, -user, and -password values and then: - - Obtains the vRealize Opertaions Manager details - - Obtains the Remote Collector details - - Creates a new Remote Collector Group and assigns the deployed Remote Collectors + .DESCRIPTION + The New-vROPSDeployment cmdlet deploys vRealize Operations Manager via 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 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 Operations Manager via vRealize Suite Lifecycle Manager - .EXAMPLE - Add-vROPSGroupRemoteCollectors -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -collectorGroupName "sfo-remote-collectors" - This example configures the currency to USD in vRealize Opertations Manager - #> + .EXAMPLE + New-vROPSDeployment -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -workbook .\pnp-workbook.xlsx + This example starts a deployment of vRealize Operations Manager 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 = $true)] [ValidateNotNullOrEmpty()] [String]$collectorGroupName + [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 { - Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null - if ($accessToken) { - $vropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass - Request-vROPSToken -fqdn $vropsDetails.loadBalancerFqdn -username $vropsDetails.adminUser -password $vropsDetails.adminPass | Out-Null - if ($vropsHeaders.Authorization) { - if (!(Get-vROPSCollectorGroup | Where-Object {$_.name -eq $collectorGroupName})) { - $collectors = (Get-vROPSCollector | Where-Object {$_.type -eq "REMOTE"} | Select-Object id).id - $collectorIds = $collectors -join "," - Add-vROPSCollectorGroup -name $collectorGroupName -collectorIds $collectorIds - if (Get-vROPSCollectorGroup | Where-Object {$_.name -eq $collectorGroupName}) { - Write-Output "Creating Remote Collector Group in ($($vropsDetails.loadBalancerFqdn)) named ($collectorGroupName): SUCCESSFUL" - } - else { - Write-Error "Creating Remote Collector Group in ($($vropsDetails.loadBalancerFqdn)) named ($collectorGroupName): FAILED" + 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-vROPSJsonSpec -workbook $workbook -server $server -user $user -pass $pass | Out-Null + $json = (Get-Content -Raw .\vropsDeploymentSpec.json) + $jsonSpec = $json | ConvertFrom-Json + if (!($checkProducts = (Get-vRSLCMEnvironment | Where-Object {$_.environmentName -eq $jsonSpec.environmentName}).products.id -contains $jsonSpec.products.id)) { + if (Get-vRSLCMLockerPassword | Where-Object {$_.alias -Match $($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])}) { + if ($jsonSpec.environmentId) { + $newRequest = Add-vRSLCMEnvironment -json $json -environmentId $jsonSpec.environmentId -addProduct -WarningAction SilentlyContinue -ErrorAction SilentlyContinue + } + else { + $newRequest = Add-vRSLCMEnvironment -json $json -WarningAction SilentlyContinue -ErrorAction SilentlyContinue + } + if ($newRequest) { + if ($PsBoundParameters.ContainsKey("monitor")) { + Start-Sleep 10 + Watch-vRSLCMRequest -vmid $($newRequest.requestId) + } + else { + Write-Output "Deployment Rquest for vRealize Operations Manager Submitted Successfully (Request Ref: $($newRequest.requestId))" + } + } + else { + Write-Error "Request to deploy vRealize Operations Manager failed, check the vRealize Suite Lifecycle Manager UI: POST_VALIDATION_FAILED" + } + } + else { + Write-Error "License in vRealize Suite Lifecycle Manager ($($vrvcfVrslcmDetailsslcm.fqdn)) Locker with alias ($($jsonSpec.products.properties.licenseRef.Split(":")[3])), does not exist: PRE_VALIDATION_FAILED" + } + } + else { + Write-Error "Certificate in vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($($jsonSpec.products.properties.certificate.Split(":")[3])), does not exist: PRE_VALIDATION_FAILED" + } + } + else { + Write-Error "Password in vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($($jsonSpec.products.properties.productPassword.Split(":")[3])), does not exist: PRE_VALIDATION_FAILED" + } + } + else { + Write-Warning "vRealize Operations Manager in environment ($($jsonSpec.environmentName)) on vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)), already exists: SKIPPED" + } + } } - } - else { - Write-Warning "Creating Remote Collector Group in ($($vropsDetails.loadBalancerFqdn)) named ($collectorGroupName), already exists: SKIPPED" - } - } - else { - Write-Error "Unable to obtain access token from vRealize Operations Manager ($($vropsDetails.loadBalancerFqdn)), check credentials" + } } } - else { - Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials" - } } Catch { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-vROPSGroupRemoteCollectors +Export-ModuleMember -Function New-vROPSDeployment -Function Add-vROPSCurrency { +Function Import-vROPSUserGroup { <# - .SYNOPSIS - Connect a Workload Domain to vRealize Operations Manager + .SYNOPSIS + Import a Group from Workspace ONE Access and assign access in vRealize Operations Manager - .DESCRIPTION - The Add-vROPSCurrency cmdlet connects a Workload Domain to vRealize Operations Manager. - The cmdlet connects to SDDC Manager using the -server, -user, and -password values and then: - - Obtains the vRealize Opertaions Manager details - - Connects to vRealize Opertations Manager - - Configures the currency value + .DESCRIPTION + The Import-vROPSUserGroup cmdlet imports a Group from Workspace ONE Access and assigns access in vRealize + Operations 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 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 Workspace ONE Access has been configured as an authentication source + - Validates the user group provided can be found in vRealize Operations Manager + - Validated the role exists within vRealize Operations Manager + - Imports the group and assigns the vRealize Operations Manager role - .EXAMPLE - Add-vROPSCurrency -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -currency USD - This example configures the currency to USD in vRealize Opertations Manager - #> + .EXAMPLE + Import-vROPSUserGroup -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo.rainpole.io -groupName gg-vrops-admins -role Administrator + This example imports a group into vRealize Operations Manager and assigns the role + #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$currency + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$groupName, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$role ) Try { - Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null - if ($accessToken) { - $vropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass - Request-vROPSToken -fqdn $vropsDetails.loadBalancerFqdn -username $vropsDetails.adminUser -password $vropsDetails.adminPass | Out-Null - if ($vropsHeaders.Authorization) { - if ((Get-vROPSCurrency -eq $null)) { - Set-vROPSCurrency -currency $currency | Out-Null - if (Get-vROPSCurrency -eq $currency) { - Write-Output "Configuring currency in vRealize Operations Manager ($($vropsDetails.loadBalancerFqdn)) to ($currency): SUCCESSFUL" - } - else { - Write-Error "Configuring currency in vRealize Operations Manager ($($vropsDetails.loadBalancerFqdn)) to ($currency): FAILED" + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) { + if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass) { + if (!(Get-vROPSUserGroup -name ($groupName + '@' + $domain))) { + if (Get-vROPSAuthSource | Where-Object {$_.name -eq "vIDMAuthSource"}) { + if (Search-vROPSUserGroup -sourceId (Get-vROPSAuthSource | Where-Object {$_.name -eq "vIDMAuthSource"}).id -domain $domain -groupName ($groupName + '@' + $domain)) { + if (Get-vROPSAuthRole -name $role -ErrorAction SilentlyContinue) { + Add-vROPSUserGroup -sourceId (Get-vROPSAuthSource | Where-Object {$_.name -eq "vIDMAuthSource"}).id -userGroup ($groupName + '@' + $domain) -role $role | Out-Null + if (Get-vROPSUserGroup -name ($groupName + '@' + $domain)) { + Write-Output "Importing User Group into vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($($groupName + '@' + $domain)): SUCCESSFUL" + } + else { + Write-Error "Importing User Group into vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($($groupName + '@' + $domain)): POST_VALIDATION_FAILED" + } + } + else { + Write-Error "Unable to locate Role in vealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($role): PRE_VALIDATION_FAILED" + } + } + else { + Write-Error "Unable to locate User Group in vealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($groupName): PRE_VALIDATION_FAILED" + } + } + else { + Write-Error "Unable to locate Authentication Source in vealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) type (vIDMAuthSource): PRE_VALIDATION_FAILED" + } + } + else { + Write-Warning "Importing User Group into vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($($groupName + '@' + $domain)), already performed: SKIPPED" + } + } } } - else { - Write-Warning "Configuring currency in vRealize Operations Manager ($($vropsDetails.loadBalancerFqdn)) to ($currency), already exists: SKIPPED" - } } - else { - Write-Error "Unable to obtain access token from vRealize Operations Manager ($($vropsDetails.loadBalancerFqdn)), check credentials" - } - } - else { - Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials" } } Catch { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-vROPSCurrency +Export-ModuleMember -Function Import-vROPSUserGroup -Function Add-vROPSCredentialNsxt { +Function Register-vROPSWorkloadDomain { <# .SYNOPSIS - Adds an NSX credential to vRealize Operations Manager + Connect a Workload Domain to vRealize Operations Manager - .DESCRIPTION - The Add-vROPSCredentialNsxt cmdlet adds a credential for a Workload Domains NSX Manager to vRealize Operations Manager. - The cmdlet connects to SDDC Manager using the -server, -user, and -password values and then: - - Obtains the vRealize Opertaions Manager details - - Obtains the NSX Management Cluster details for the Workload Domain - - Creates a new credential for the Workload Domain in vRealize Operations Manager using credentials from SDDC Manager inventory + .DESCRIPTION + The Register-vROPSWorkloadDomain cmdlet connects a Workload Domain to vRealize Operations 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 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 if the Workload Domain is already connected to vRealize Operations Manager + - Enables/Disables connecting the Workload Domain to vRealize Operations Manager - .EXAMPLE - Add-vROPSCredentialNsxt -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 - This example creates an NSX credential for the Workload Domain named 'sfo-w01' in vRealize Opertations Manager - #> + .EXAMPLE + Register-vROPSWorkloadDomain -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 Opertations Manager + + .EXAMPLE + Register-vROPSWorkloadDomain -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 Opertations 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]$domain, + [Parameter (Mandatory = $true)] [ValidateSet("ENABLED", "DISABLED")] [String]$status ) Try { - Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null - if ($accessToken) { - $vropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass - $nsxDetails = Get-NsxtServerDetail -fqdn $server -user $user -pass $pass -domain $domain - Request-vROPSToken -fqdn $vropsDetails.loadBalancerFqdn -username $vropsDetails.adminUser -password $vropsDetails.adminPass | Out-Null - if (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}) { - if (!(Get-vROPSCredential | Where-Object {$_.name -eq $nsxDetails.fqdn})) { - $json = '{ "name": "'+ $nsxDetails.fqdn +'", "adapterKindKey": "NSXTAdapter", "credentialKindKey": "NSXTCREDENTIAL", "fields": [ { "name": "USERNAME", "value": "'+ $nsxDetails.adminUser +'" }, { "name": "PASSWORD", "value": "'+ $nsxDetails.adminPass +'" } ]}' - $json | Out-File .\addCredential.json - Add-vROPSCredential -json .\addCredential.json | Out-Null - if (Get-vROPSCredential | Where-Object {$_.name -eq $nsxDetails.fqdn}) { - Write-Output "Creating Credential in vRealize Operations Manager ($($vropsDetails.loadBalancerFqdn)) named ($($nsxDetails.fqdn)): SUCCESSFUL" + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) { + if (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}) { + if ((Get-VCFvROPSConnection | Where-Object {$_.domainId -eq (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}).id}).status -ne $status) { + Set-VCFvROPSConnection -domainId (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}).id -status $status | Out-Null + Start-Sleep 10 + Do { + $configStatus = (Get-VCFvROPSConnection | Where-Object {$_.domainId -eq (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}).id}).status + } Until ($configStatus -ne "IN_PROGRESS") + if ((Get-VCFvROPSConnection | Where-Object {$_.domainId -eq (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}).id}).status -eq $status) { + Write-Output "Enabling Workload Domain Intergation with vRealize Opertations Manager ($($vcfVropsDetails.loadBalancerFqdn)) for domain ($domain): SUCCESSFUL" + } + else { + Write-Error "Enabling Workload Domain Intergation with vRealize Opertations Manager ($($vcfVropsDetails.loadBalancerFqdn)) for domain ($domain): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Enabling Workload Domain Intergation with vRealize Opertations Manager ($($vcfVropsDetails.loadBalancerFqdn)) for domain ($domain), already enabled: SKIPPED" + } } else { - Write-Error "Creating Credential in vRealize Operations Manager ($($vropsDetails.loadBalancerFqdn)) named ($($nsxDetails.fqdn)): FAILED" + Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" } - Remove-Item .\addCredential.json -Force -Confirm:$false - } - else { - Write-Warning "Creating Credential in vRealize Operations Manager ($($vropsDetails.loadBalancerFqdn)) named ($($nsxDetails.fqdn)), already exists: SKIPPED" } } - else { - 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" } } Catch { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-vROPSCredentialNsxt +Export-ModuleMember -Function Register-vROPSWorkloadDomain -Function Add-vROPSAdapterNsxt { +Function Add-vROPSGroupRemoteCollectors { <# .SYNOPSIS - Adds an NSX Adapter to vRealize Operations Manager + Creates a Remote Collectors Group and assigns nodes in vRealize Operations Manager - .DESCRIPTION - The Add-vROPSAdapterNsxt cmdlet adds an adapter for a Workload Domains NSX Manager to vRealize Operations Manager. - The cmdlet connects to SDDC Manager using the -server, -user, and -password values and then: - - Obtains the vRealize Opertaions Manager details - - Checks the Workload Domain is valid and then obtains the NSX Management Cluster details - - Checks the Remote Collector Group exits in vRealize Operations Manager - - Creates a new adapter including credentials for the Workload Domain in vRealize Operations Manager using credentials from SDDC Manager inventory + .DESCRIPTION + The Add-vROPSGroupRemoteCollectors cmdlet creates a Remote Collector Group in vRealize Operations Manager and + assigns the remote collector nodes. 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 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 + - Gathers the Remote Collector node details + - Creates a new Remote Collector Group in vRealize Operations Manager + - Assigns the deployed Remote Collector nodes to the Remote Collector Group in vRealize Operations Manager - .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 Workload Domain named 'sfo-w01' in vRealize Opertations Manager - #> + .EXAMPLE + Add-vROPSGroupRemoteCollectors -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -collectorGroupName "sfo-remote-collectors" + This example creats a Remote Collector Group called 'sfo-remote-collectors' and assigns the Remove Collector Nodes in vRealize Opertations 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]$collectorGroupName ) Try { - Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null - if ($accessToken) { - $vropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass - $nsxDetails = Get-NsxtServerDetail -fqdn $server -user $user -pass $pass -domain $domain - Request-vROPSToken -fqdn $vropsDetails.loadBalancerFqdn -username $vropsDetails.adminUser -password $vropsDetails.adminPass | Out-Null - if (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}) { - if (Get-vROPSCollectorGroup | Where-Object {$_.name -eq $collectorGroupName}) { - if (!(Get-vROPSCredential | Where-Object {$_.name -eq $nsxDetails.fqdn})) { - if (!(Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $nsxDetails.fqdn})) { - $json = '{ - "name": "'+ $nsxDetails.fqdn +'", - "description": "NSX-T Adapter - '+ $nsxDetails.fqdn +'", - "adapterKindKey": "NSXTAdapter", - "monitoringInterval": 5, - "collectorGroupId": "'+ (Get-vROPSCollectorGroup | Where-Object {$_.name -eq $collectorGroupName}).id +'", - "resourceIdentifiers": [ - { - "name": "NSXTHOST", - "value": "'+ $nsxDetails.fqdn +'" - } - ], - "credential": { - "name": "'+ $nsxDetails.fqdn +'", - "adapterKindKey": "NSXTAdapter", - "credentialKindKey": "NSXTCREDENTIAL", - "fields": [{ - "name": "USERNAME", - "value": "'+ $nsxDetails.adminUser +'" - }, - { - "name": "PASSWORD", - "value": "'+ $nsxDetails.adminPass +'" - } - ] + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) { + if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass) { + if (!(Get-vROPSCollectorGroup | Where-Object {$_.name -eq $collectorGroupName})) { + $collectors = (Get-vROPSCollector | Where-Object {$_.type -eq "REMOTE"} | Select-Object id).id + $collectorIds = $collectors -join "," + Add-vROPSCollectorGroup -name $collectorGroupName -collectorIds $collectorIds + if (Get-vROPSCollectorGroup | Where-Object {$_.name -eq $collectorGroupName}) { + Write-Output "Creating Remote Collector Group in ($($vcfVropsDetails.loadBalancerFqdn)) named ($collectorGroupName): SUCCESSFUL" + } + else { + Write-Error "Creating Remote Collector Group in ($($vcfVropsDetails.loadBalancerFqdn)) named ($collectorGroupName): POST_VALIDATION_FAILED" } - }' - $json | Out-File .\addAdapter.json - Add-vROPSAdapter -json .\addAdapter.json | Out-Null - - if (Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $nsxDetails.fqdn}) { - Start-vROPSAdapter -adapterId (Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $nsxDetails.fqdn}).id | Out-Null - Write-Output "Adding NSX Adapter in vRealize Operations Manager ($($vropsDetails.loadBalancerFqdn)) named ($($nsxDetails.fqdn)): SUCCESSFUL" } else { - Write-Error "Adding NSX Adapter in vRealize Operations Manager ($($vropsDetails.loadBalancerFqdn)) named ($($nsxDetails.fqdn)): FAILED" + Write-Warning "Creating Remote Collector Group in ($($vcfVropsDetails.loadBalancerFqdn)) named ($collectorGroupName), already exists: SKIPPED" } - Remove-Item .\addAdapter.json -Force -Confirm:$false - } - else { - Write-Warning "Adding NSX Adapter in vRealize Operations Manager ($($vropsDetails.loadBalancerFqdn)) named ($($nsxDetails.fqdn)), already exists: SKIPPED" } } - else { - Write-Warning "Credential in vRealize Operations Manager ($($vropsDetails.loadBalancerFqdn)) named ($($nsxDetails.fqdn)), already exists: SKIPPED" - } - } - else { - Write-Error "Remote Collector Group in vRealize Operations Manager ($($vropsDetails.loadBalancerFqdn)) named ($collectorGroupName), does not exist: FAILED" } } - else { - 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" } } Catch { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-vROPSAdapterNsxt +Export-ModuleMember -Function Add-vROPSGroupRemoteCollectors -########################################### E N D O F F U N C T I O N S ########################################## -######################################################################################################################## +Function Update-vROPSAdapterVcenter { + <# + .SYNOPSIS + Updates the assigned Remote Collector Group for vCenter Adapter + .DESCRIPTION + The Update-vROPSAdapterVcenter cmdlet updates the assigned Remote Collector Group for all vCenter Adapters in + vRealize Operations 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 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 Remote Collector Group exits in vRealize Operations Manager + - Gathers the unique ID of the Remote Collector Group + - Gathers the vCenter Adapter details from vRelize Operations Manager + - Updates the assigned Remote Collector Group for the vCenter Adapter in vRelize Operations Manager -######################################################################################################################## -######################## P R I V A T E C L O U D A U T O M A T I O N F U N C T I O N S ######################### + .EXAMPLE + Update-vROPSAdapterVcenter -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -collectorGroupName "sfo-remote-collectors" + This example updates all vCenter Adapters to use the Remote Collector Group named 'sfo-remote-collectors' + #> -Function Export-vRAJsonSpec { Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$username, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$password, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$workbook + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$collectorGroupName ) 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 - Request-vRSLCMToken -fqdn $server -username $username -password $password | Out-Null - if (($vrslcmHealth = Get-vRSLCMHealth).'vrlcm-server' -eq "UP") { - if ($pnpWorkbook.Workbook.Names["vra_license"].Value) { - $licenseKey = $pnpWorkbook.Workbook.Names["vra_license"].Value - } - else { - $licenseKey = $pnpWorkbook.Workbook.Names["vrs_license"].Value - } - $vraLicense = Get-vRSLCMLockerLicense | Where-Object {$_.key -eq $licenseKey} - if ($vraLicense.key -eq $licenseKey) { - $vraCertificate = Get-vRSLCMLockerCertificate | Where-Object {$_.alias -eq $pnpWorkbook.Workbook.Names["xreg_vra_virtual_hostname"].Value} - if ($vraCertificate.alias) { - $defaultPassword = Get-vRSLCMLockerPassword | Where-Object {$_.alias -eq $pnpWorkbook.Workbook.Names["vrslcm_xreg_env_password_alias"].Value} - if ($defaultPassword.alias) { - $vraPassword = Get-vRSLCMLockerPassword | Where-Object {$_.alias -eq $pnpWorkbook.Workbook.Names["xreg_vra_root_password_alias"].Value} - if ($vraPassword.alias) { - $vcCredentials = Get-vRSLCMLockerPassword | Where-Object {$_.alias -eq (($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["vrslcm_xreg_dc"].Value} - if ($datacenterName) { - $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:" + $($vraCertificate.vmid) + ":" + $($vraCertificate.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]@{ - 'certificate' = ("locker:certificate:" + $($vraCertificate.vmid) + ":" + $($vraCertificate.alias)) - 'productPassword' = ("locker:password:" + $($vraPassword.vmid) + ":" + $($vraPassword.alias)) - 'licenseRef' = ("locker:license:" + $($vraLicense.vmid) + ":" + $($vraLicense.alias)) - 'fipsMode' = "false" - 'timeSyncMode' = "ntp" - 'ntp' = $pnpWorkbook.Workbook.Names["region_ntp1_server"].Value - 'affinityRule' = $false - 'configureAffinitySeparateAll' = "true" - 'nodeSize' = $pnpWorkbook.Workbook.Names["xreg_vra_appliance_size"].Value.ToLower() - 'vraK8ServiceCidr' = $pnpWorkbook.Workbook.Names["xreg_vra_k8s_cluster_cidr"].Value - 'vraK8ClusterCidr' = $pnpWorkbook.Workbook.Names["xreg_vra_k8s_service_cidr"].Value - 'clusterFqdn' = $pnpWorkbook.Workbook.Names["xreg_vra_virtual_fqdn"].Value - } - - #### Generate vRealize Log Insight Cluster Details - $clusterVipProperties = @() - $clusterVipProperties += [pscustomobject]@{ - 'hostName' = $pnpWorkbook.Workbook.Names["xreg_vra_virtual_fqdn"].Value - } - - $clusterVipsObject = @() - $clusterVipsObject += [pscustomobject]@{ - 'type' = "vra-va" - 'properties' = ($clusterVipProperties | Select-Object -Skip 0) - } - - $clusterObject = @() - $clusterObject += [pscustomobject]@{ - 'clusterVips' = $clusterVipsObject - } - - #### Generate vRealize Log Insight Node Details - $vraPrimaryProperties = @() - $vraPrimaryProperties += [pscustomobject]@{ - 'hostName' = $pnpWorkbook.Workbook.Names["xreg_vra_nodea_fqdn"].Value - 'vmName' = $pnpWorkbook.Workbook.Names["xreg_vra_nodea_hostname"].Value - 'ip' = $pnpWorkbook.Workbook.Names["xreg_vra_nodea_ip"].Value - } - - $vraSecondary1Properties = @() - $vraSecondary1Properties += [pscustomobject]@{ - 'hostName' = $pnpWorkbook.Workbook.Names["xreg_vra_nodeb_fqdn"].Value - 'vmName' = $pnpWorkbook.Workbook.Names["xreg_vra_nodeb_hostname"].Value - 'ip' = $pnpWorkbook.Workbook.Names["xreg_vra_nodeb_ip"].Value - } - - $vraSecondary2Properties = @() - $vraSecondary2Properties += [pscustomobject]@{ - 'hostName' = $pnpWorkbook.Workbook.Names["xreg_vra_nodec_fqdn"].Value - 'vmName' = $pnpWorkbook.Workbook.Names["xreg_vra_nodec_hostname"].Value - 'ip' = $pnpWorkbook.Workbook.Names["xreg_vra_nodec_ip"].Value - } - - $nodesObject = @() - $nodesobject += [pscustomobject]@{ - 'type' = "vrava-primary" - 'properties' = ($vraPrimaryProperties | Select-Object -Skip 0) - } - $nodesobject += [pscustomobject]@{ - 'type' = "vrava-secondary" - 'properties' = ($vraSecondary1Properties | Select-Object -Skip 0) - } - $nodesobject += [pscustomobject]@{ - 'type' = "vrava-secondary" - 'properties' = ($vraSecondary2Properties | Select-Object -Skip 0) - } - - #### Generate the vRealize Log Insight Properties Section - $productsObject = @() - $productsObject += [pscustomobject]@{ - 'id' = "vra" - 'version' = "8.4.1" - 'properties' = ($productPropertiesObject | Select-Object -Skip 0) - 'clusterVIP' = ($clusterObject | Select-Object -Skip 0) - 'nodes' = $nodesObject - } - - if (!($xintEnvironment)) { - $vraDeploymentObject = @() - $vraDeploymentObject += [pscustomobject]@{ - 'environmentName' = $pnpWorkbook.Workbook.Names["vrslcm_xreg_env"].Value - 'infrastructure' = ($infrastructureObject | Select-Object -Skip 0) - 'products' = $productsObject + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) { + if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass) { + if ($collectorGroupId = (Get-vROPSCollectorGroup | Where-Object {$_.name -eq $collectorGroupName}).id) { + $adapters = Get-vROPSAdapter | Where-Object {$_.resourceKey.adapterKindKey -eq "VMWARE"} + Foreach ($adapter in $adapters) { + $vcurl = ((Get-vROPSAdapter -id $adapter.id).resourceKey.resourceIdentifiers | Where-Object {$_.identifierType.name -eq "VCURL"}).value + $json = '{ + "resourceKey" : { + "name" : "'+ $($adapter.resourceKey.name) +'", + "adapterKindKey" : "VMWARE", + "resourceKindKey" : "VMwareAdapter Instance", + "resourceIdentifiers" : [ { + "identifierType" : { + "name" : "AUTODISCOVERY", + "dataType" : "STRING", + "isPartOfUniqueness" : true + }, + "value" : "true" + }, { + "identifierType" : { + "name" : "PROCESSCHANGEEVENTS", + "dataType" : "STRING", + "isPartOfUniqueness" : true + }, + "value" : "true" + }, { + "identifierType" : { + "name" : "VCURL", + "dataType" : "STRING", + "isPartOfUniqueness" : true + }, + "value" : "'+ $vcurl +'" + } ] + }, + "description" : "'+ $($adapter.description) +'", + "id" : "'+ $($adapter.id) +'", + "collectorGroupId": "'+ $($collectorGroupId) +'" + }' + + $json | Out-File .\updateAdapter.json + if (!($($adapter.collectorGroupId) -eq $collectorGroupId)) { + Set-vROPSAdapter -json .\updateAdapter.json | Out-Null + Write-Output "Assiging vCenter Adapter ($($adapter.resourceKey.name)) to Remote Collector Group ($collectorGroupName): SUCCESSFUL" } - } - else { - $vraDeploymentObject = @() - $vraDeploymentObject += [pscustomobject]@{ - 'environmentId' = $xintEnvironment.environmentId - 'environmentName' = $pnpWorkbook.Workbook.Names["vrslcm_xreg_env"].Value - 'infrastructure' = ($infrastructureObject | Select-Object -Skip 0) - 'products' = $productsObject + else { + Write-Warning "Assiging vCenter Adapter ($($adapter.resourceKey.name)) to Remote Collector Group ($collectorGroupName), already assigned: SKIPPED" } + Remove-Item .\updateAdapter.json -Force -Confirm:$false } - - $vraDeploymentObject | ConvertTo-Json -Depth 12 | Out-File -Encoding UTF8 -FilePath "vraDeploymentSpec.json" - - Write-Output "Creation of Deployment JSON Specification file for vRealize Automation: 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" + Write-Error "Remote Collector Group in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($collectorGroupName), does not exist: PRE_VALIDATION_FAILED" } } - else { - Write-Error "Root Password with alias '$($pnpWorkbook.Workbook.Names["xreg_vra_root_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["vrslcm_xreg_env_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_vra_virtual_hostname"].Value)' not found in the vRealize Suite Lifecycle Manager Locker, add and retry" - } - } - else { - Write-Error "License with alias '$licenseKey' not found in the vRealize Suite Lifecycle Manager Locker, add and retry" } } - else { - Write-Error "Unable to obtain access token from vRealize Suite Lifecycle Manager ($server), check credentials" - } - Close-ExcelPackage $pnpWorkbook -NoSave -ErrorAction SilentlyContinue } Catch { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Export-vRAJsonSpec +Export-ModuleMember -Function Update-vROPSAdapterVcenter -Function New-vRADeployment { +Function Add-vROPSCurrency { <# - .SYNOPSIS - Deploy vRealize Automation to vRealize Suite Lifecycle Manager + .SYNOPSIS + Configures the currency in vRealize Operations Manager .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 to retrive the vRSLCM details from its - inventory and then: - - Verifies that the environment does not already exist - - Requests a new deployment of vRealize Automation + The Add-vROPSCurrency cmdlet configures the currency in vRealize Operations 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 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 if a currency value has been configured + - Configures the currency value based on the value provided .EXAMPLE - New-vRADeployment -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -workbook .\pnp-workbook.xlsx - This example starts a deployment of vRealize Automation using the Planning and Preparation Workbook + Add-vROPSCurrency -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -currency USD + This example configures the currency to USD in vRealize Opertations 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]$currency ) - 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 { - $vrslcm = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass - Request-vRSLCMToken -fqdn $vrslcm.fqdn -username $vrslcm.adminUser -password $vrslcm.adminPass | Out-Null - if (($vrslcmHealth = Get-vRSLCMHealth).'vrlcm-server' -eq "UP") { - Export-vRAJsonSpec -server $vrslcm.fqdn -username $vrslcm.adminUser -password $vrslcm.adminPass -workbook $workbook | Out-Null - $json = (Get-Content -Raw .\vraDeploymentSpec.json) - $jsonSpec = $json | ConvertFrom-Json - if (!($checkProducts = (Get-vRSLCMEnvironment | Where-Object {$_.environmentName -eq $jsonSpec.environmentName}).products.id -contains $jsonSpec.products.id)) { - if (Get-vRSLCMLockerPassword | Where-Object {$_.alias -Match $($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])}) { - if ($jsonSpec.environmentId) { - $newRequest = Add-vRSLCMEnvironment -json $json -environmentId $jsonSpec.environmentId -addProduct - } - else { - $newRequest = Add-vRSLCMEnvironment -json $json - } - if ($newRequest) { - if ($PsBoundParameters.ContainsKey("monitor")) { - Start-Sleep 10 - Watch-vRSLCMRequest -vmid $($newRequest.requestId) + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) { + if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass) { + if (-not (($currentCurrency = Get-vROPSCurrency | Select-Object code)).code) { + Set-vROPSCurrency -currency $currency | Out-Null + if (((Get-vROPSCurrency | Select-Object code)).code -eq $currency) { + Write-Output "Configuring currency in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) to ($currency): SUCCESSFUL" } else { - Write-Output "Deployment Rquest for vRealize Automation Submitted Successfully (Request Ref: $($newRequest.requestId))" + Write-Error "Configuring currency in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) to ($currency): POST_VALIDATION_FAILED" } } else { - Write-Error "Request to deploy vRealize Automation failed, check the vRealize Suite Lifecycle Manager UI" + Write-Warning "Configuring currency in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) to ($currency), ($($currentCurrency.code)) already set: SKIPPED" } } - else { - Write-Error "License in vRealize Suite Lifecycle Manager ($($vrslcm.fqdn)) Locker with alias ($($jsonSpec.products.properties.licenseRef.Split(":")[3])), does not exist: FAILED" - } } - else { - Write-Error "Certificate in vRealize Suite Lifecycle Manager ($($vrslcm.fqdn)) Locker with alias ($($jsonSpec.products.properties.certificate.Split(":")[3])), does not exist: FAILED" - } - } - else { - Write-Error "Password in vRealize Suite Lifecycle Manager ($($vrslcm.fqdn)) Locker with alias ($($jsonSpec.products.properties.productPassword.Split(":")[3])), does not exist: FAILED" } } - else { - Write-Warning "vRealize Automation in environment ($($jsonSpec.environmentName)) on vRealize Suite Lifecycle Manager ($($vrslcm.fqdn)), already exists: SKIPPED" - } - } - else { - Write-Error "Unable to obtain access token from vRealize Suite Lifecycle Manager ($server), check credentials" } } Catch { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function New-vRADeployment - - -########################################### E N D O F F U N C T I O N S ########################################## -######################################################################################################################## - - -####################################################################################################################### -################# S H A R E D P O W E R V A L I D A T E D S O L U T I O N F U N C T I O N S ################ +Export-ModuleMember -Function Add-vROPSCurrency -Function Add-vCenterGlobalPermission { +Function Enable-vROPSManagementPack { <# .SYNOPSIS - Adds a Global Permission to user/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 to retrive the management domain - vCenter Server details from its inventory and then: - - Verifies that the bind credentials are valid - - 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 Global Permission - - If -localDomain is selected, then AD authentication check is skipped and user/group is checked for in the local directory + Install a Management Pack in vRealize Operations Manager - .EXAMPLE - Add-vCenterGlobalPermission -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo.rainpole.io -domainBindUser svc-vsphere-ad -domainBindPass VMw@re1! -principal gg-vc-admins -role Admin -propagate true -type group - This example adds the group gg-vc-admins from domain sfo.rainpole.io the Administrator Global Permission + .DESCRIPTION + The Enable-vROPSManagementPack cmdlet uploads and installs a management pack in vRealize Operations Manager. + The cmdlet connects to SDDC Manager using the -server, -user, and -password values. + - Validates the path to the Management Pack (.pak) file + - Validates that network connectivity and authentication is possible to SDDC Manager + - 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 the Management Pack does not exist in vRealize Operations Manager + - Uploads the Management Pack file to vRealize Operations Manager + - Installs the Management Pack to vRealize Operations Manager .EXAMPLE - Add-vCenterGlobalPermission -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain vsphere.local -domainBindUser administrator -domainBindPass VMw@re1! -principal svc-sfo-m01-nsx01-sfo-m01-vc01 -role "NSX-T Data Center to vSphere Integration" -propagate true -type user -localdomain - This example adds the "NSX-T Data Center to vSphere Integration" Global Permission to the user svc-sfo-m01-nsx01-sfo-m01-vc01 from domain vsphere.local - #> + Enable-vROPSManagementPack -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -packType "SDDC Health" -pakfile .\management.pak + This example installs the SDDC Health Management Pack in vRealize Operations 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]$domainBindUser, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domainBindPass, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$principal, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$role, - [Parameter (Mandatory = $true)] [ValidateSet("true", "false")] [String]$propagate, - [Parameter (Mandatory = $true)] [ValidateSet("group", "user")] [String]$type, - [Parameter (Mandatory = $false)] [Switch]$localDomain = $false + [Parameter (Mandatory = $true)] [ValidateSet("SDDC Health")] [ValidateNotNullOrEmpty()] [String]$packType, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$pakFile ) - Try { - if (!$localDomain){ - $checkAdAuthentication = Test-ADAuthentication -user $domainBindUser -pass $domainBindPass -server $domain -domain $domain -ErrorAction SilentlyContinue - if (!($checkAdAuthentication[1] -match "Authentication Successful")) { - Write-Error "Unable to authenticate to Active Directory with user ($domainBindUser) and password ($domainBindPass), check details" - Return - } - } + if (!$pakFile) { + $pakFile = Get-ExternalFileName -title "Select the Management Pack file (.pak)" -fileType "pak" -location "default" + } + else { + if (!(Test-Path -Path $pakFile)) { + Write-Error "Management Pack file (pak) '$pakFile' File Not Found" + Break + } + } - $securePass = ConvertTo-SecureString -String $domainBindPass -AsPlainText -Force - $domainCreds = New-Object System.Management.Automation.PSCredential ($domainBindUser, $securePass) - Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null - if ($accessToken) { - $vcenter = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT - Connect-VIServer -Server $vcenter.fqdn -User $vcenter.ssoAdmin -Pass $vcenter.ssoAdminPass | Out-Null - if ($DefaultVIServer.Name -eq $($vcenter.fqdn)) { - Connect-SsoAdminServer -Server $vcenter.fqdn -User $vcenter.ssoAdmin -Password $vcenter.ssoAdminPass | Out-Null - if ($DefaultSsoAdminServers.Name -eq $($vcenter.fqdn)) { - if (!(Get-IdentitySource | Where-Object { $_.Name -eq $domain })) { - Write-Error "Unable to find Identity Source in vCenter Server ($($vcenter.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 }) - } - } - 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 vsphere.local | Where-Object { $_.Name -eq $principal }) - } - } - if ($objectCheck) { - $roleId = (Get-VIRole -Name $role | Select-Object -ExpandProperty Id) - Add-GlobalPermission -vcServer $vcenter.fqdn -vcUsername $vcenter.ssoAdmin -vcPassword $vcenter.ssoAdminPass -roleId $roleId -user $principal -propagate $propagate -type $type - Write-Output "Adding Global Permission with Role ($role) in vCenter Server ($($vcenter.vmName)) to $type ($principal): SUCCESSFUL" - } - else { - if ($localDomain) { - Write-Error "Unable to find $type ($principal) in Local Domain, create and retry" + Try { + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) { + if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass) { + if (!(Get-vROPSSolution | Where-Object {$_.id -eq $packType})) { + $uploadPak = Import-vROPSManagementPack -server $vcfVropsDetails.loadBalancerFqdn -username $vcfVropsDetails.adminUser -password $vcfVropsDetails.adminPass -pak $pakFile + if ($uploadPak) { + $pakId = ($uploadPak | ConvertFrom-JSon).pak_id + $installPak = Install-vROPSManagementPack -server $vcfVropsDetails.loadBalancerFqdn -username $vcfVropsDetails.adminUser -password $vcfVropsDetails.adminPass -pakId $pakId + Do { + $status = Get-vROPSManagementPackStatus -server $vcfVropsDetails.loadBalancerFqdn -username $vcfVropsDetails.adminUser -password $vcfVropsDetails.adminPass -pakId $pakId + } Until ( $status.cluster_pak_install_status -ne "CANDIDATE" ) + if ($status.cluster_pak_install_status -eq "COMPLETED") { + Write-Output "Installing '$pakFile' Management Pack to vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)): SUCCESSFUL" + } + else { + Write-Error "Installing '$pakFile' Management Pack to vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)): POST_VALIDATION_FAILED" + } + } + else { + Write-Error "Uploading '$pakFile' Management Pack to vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)): POST_VALIDATION_FAILED" + } } else { - Write-Error "Unable to find $type ($principal) in Active Directory Domain ($domain), create and retry" + Write-Warning "Installing '$pakFile' Management Pack to vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)), already exists: SKIPPED" } } } } - else { - Write-Error "Unable to connect to vCenter Single-Sign On ($($vcenter.fqdn))" - } } - else { - Write-Error "Unable to connect to vCenter Server ($($vcenter.fqdn))" - } - Disconnect-SsoAdminServer $vcenter.fqdn -WarningAction SilentlyContinue - Disconnect-VIServer $vcenter.fqdn -Confirm:$false -WarningAction SilentlyContinue - } - else { - Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials" } } Catch { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-vCenterGlobalPermission +Export-ModuleMember -Function Enable-vROPSManagementPack -Function Set-vCenterPermission { - <# +Function Register-vROPSManagementPack { + <# .SYNOPSIS - Sets Permission for user or group in the vCenter server. This overrides any existing Global permissions for the user or group in the vCenter server + Enable / Disable a Management Pack - .DESCRIPTION - The Set-vCenterPermission cmdlet assigns the Permission/Role to existing user or group in the vCenter server. - The user/group must exist in the domain prior to running this cmdlet + .DESCRIPTION + The Register-vROPSManagementPack cmdlet activates or deactivates a management pack in vRealize Operations + 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 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 if the Management Pack is activated or deactivated in vRealize Operations Manager + - Activates or deactivates the Management Pack - .EXAMPLE - Set-vCenterPermission -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain vsphere.local -workloadDomain sfo-m01 -principal svc-sfo-w01-nsx01-sfo-w01-vc01 -role "NoAccess" - This example assigns NoAccess permission to the user svc-sfo-w01-nsx01-sfo-w01-vc01 from domain vsphere.local + .EXAMPLE + Register-vROPSManagementPack -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -state enable -packType Ping + This example activates the Ping management pack in vRealize Operations Manager .EXAMPLE - Set-vCenterPermission -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo -workloadDomain sfo-m01 -principal gg-vc-admins -role "Admin" - This example assigns Admin permission to the group gg-vc-admins from domain sfo - #> + Register-vROPSManagementPack -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -state disable -packType Ping + This example deactivates the Ping management pack in vRealize Operations 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]$workloadDomain, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$principal, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$role - ) + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateSet("enable","disable")] [ValidateNotNullOrEmpty()] [String]$state, + [Parameter (Mandatory = $true)] [ValidateSet("Ping","PCI","ISO","FISMA","HIPAA","CIS","DISA")] [ValidateNotNullOrEmpty()] [String]$packType + ) - Try { - Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null - if ($accessToken) { - $vcenter = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $workloadDomain - Connect-VIServer -Server $vcenter.fqdn -User $vcenter.ssoAdmin -pass $vcenter.ssoAdminPass | Out-Null - if ($DefaultVIServer.Name -eq $($vcenter.fqdn)) { - $principal = $domain.ToUpper() + "\" + $principal - $objectCheck = Get-VIPermission -Server $vcenter.fqdn | Where-Object { $_.Principal -eq $principal } - if ($objectCheck) { - if (!($objectCheck.Role -eq $role)) { - New-VIPermission -Server $vcenter.fqdn -Role $role -Principal $principal -Entity (Get-Folder "Datacenters" -Type Datacenter | Where-Object {$_.Uid -like "*"+$vcenter.fqdn+"*"}) | Out-Null - $objectCheck = Get-VIPermission -Server $vcenter.fqdn | Where-Object { $_.Principal -eq $principal } - if ($objectCheck.Role -eq $role) { - Write-Output "Assigning role ($role) in vCenter Server ($($vcenter.vmName)) to ($principal): SUCCESSFUL" - } - else { - Write-Error "Assigning role ($role) in vCenter Server ($($vcenter.vmName)) to ($principal): FAILED" + Try { + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) { + if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass) { + # Connect to vRealize Operations Manager and extract the Management Pack Details + $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $($vcfVropsDetails.adminUser), $($vcfVropsDetails.adminPass)))) # Create Basic Authentication Encoded Credentials + $vropsBasicHeaders = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" + $vropsBasicHeaders.Add("Authorization", "Basic $base64AuthInfo") + $vropsBasicHeaders.Add("Content-Type", "application/json") + $uri = ((Get-vROPSManagementPack -server $vcfVropsDetails.loadBalancerFqdn -username $vcfVropsDetails.adminUser -password $vcfVropsDetails.adminPass | Where-Object {$_.links -match $packType}).links | Where-Object {$_.rel -eq "pak_information"}).href + $adapterDetails = Invoke-RestMethod -Method GET -Uri $uri -Headers $vropsBasicHeaders + $uri = ((Get-vROPSManagementPack -server $vcfVropsDetails.loadBalancerFqdn -username $vcfVropsDetails.adminUser -password $vcfVropsDetails.adminPass | Where-Object {$_.links -match $packType}).links | Where-Object {$_.rel -eq "pak_cluster_status"}).href + if ($state -eq "enable") { + if (!(Get-vROPSSolution | Where-Object {$_.id -match $packType})) { + Set-vROPSManagementPack -server $vcfVropsDetails.loadBalancerFqdn -username $vcfVropsDetails.adminUser -password $vcfVropsDetails.adminPass -pakId ((($adapterDetails.pak_id) -Split ("-"))[0]) -version $adapterDetails.version -status enable | Out-Null + Do { + $status = Invoke-RestMethod -Method GET -Uri $uri -Headers $vropsBasicHeaders + } Until ( $status.cluster_pak_install_status -ne "CANDIDATE" ) + if ($status.cluster_pak_install_status -eq "COMPLETED") { + Write-Output "Activating ($packType) Management Pack on vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)): SUCCESSFUL" + } + else { + Write-Error "Activating ($packType) Management Pack on vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Activating ($packType) Management Pack on vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)), already exists: SKIPPED" + } + } + elseif ($state -eq "disable") { + if (Get-vROPSSolution | Where-Object {$_.id -match $packType}) { + Set-vROPSManagementPack -server $vcfVropsDetails.loadBalancerFqdn -username $vcfVropsDetails.adminUser -password $vcfVropsDetails.adminPass -pakId ((($adapterDetails.pak_id) -Split ("-"))[0]) -version $adapterDetails.version -status disable | Out-Null + Do { + $status = Get-vROPSManagementPackActivity -server $vcfVropsDetails.loadBalancerFqdn -username $vcfVropsDetails.adminUser -password $vcfVropsDetails.adminPass + } Until ( $($status.current_pak_activity.pak_id) -ne $adapterDetails.pak_id ) + if (!(Get-vROPSSolution | Where-Object {$_.id -match $packType})) { + Write-Output "Deactivating ($packType) Management Pack on vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)): SUCCESSFUL" + } + else { + Write-Error "Deactivating ($packType) Management Pack on vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Deactivating ($packType) Management Pack on vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)), already exists: SKIPPED" + } + } } } - else { - Write-Warning "Assigning role ($role) in vCenter Server ($($vcenter.vmName)) to ($principal), already assigned: SKIPPED" - } - } - else { - Write-Error "Unable to find ($principal) in vCenter Server ($($vcenter.vmName))" } - Disconnect-VIServer $vcenter.fqdn -Confirm:$false -WarningAction SilentlyContinue - } - else { - Write-Error "Unable to connect to vCenter Server ($($vcenter.fqdn))" } } - else { - Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials" - } - } + } Catch { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Set-vCenterPermission +Export-ModuleMember -Function Register-vROPSManagementPack -Function Add-SsoPermission { +Function Add-vROPSAdapterNsxt { <# .SYNOPSIS - Assign vCenter Single Sign-On Group to user/group + Adds an NSX Adapter to vRealize Operations Manager - .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 to retrive the management domain - vCenter Server details from its inventory and then: - - Verifies that the bind credetials are valid - - 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 vCenter Single Sign-On Role + .DESCRIPTION + The Add-vROPSAdapterNsxt cmdlet adds an NSX Adapter for a Workload Domains NSX Management Cluster to vRealize + Operations 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 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 Workload Domain is valid and then obtains the NSX Management Cluster details + - Validates that the Remote Collector Group exits in vRealize Operations Manager + - Validates that the NSX Adapter and Credentials do not already exist in vRealize Operations Manager + - Validates that the credentials do not already exist in vRealize Operations Manager + - Creates a new NSX Adapter for the Workload Domain using credentials from SDDC Manager inventory in vRealize Operations Manager + - Starts the collection of the NSX Adapter in vRealize Operations Manager - .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-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 .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 - #> + 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 + #> 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 + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$collectorGroupName ) 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) - Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null - if ($accessToken) { - $ssoServer = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $sddcDomain - $ssoConnection = Connect-SsoAdminServer -Server $ssoServer.fqdn -User $ssoServer.ssoAdmin -Password $ssoServer.ssoAdminPass - if ($DefaultSsoAdminServers.Name -eq $($ssoServer.fqdn)) { - $targetGroup = Get-SsoGroup -Domain vsphere.local -Name $ssoGroup -Server $ssoConnection - if (Get-IdentitySource -Server $ssoConnection | 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 $ssoConnection - $ldapGroup | Add-GroupToSsoGroup -TargetGroup $targetGroup -ErrorAction SilentlyContinue - if (Get-SsoGroup -Group $targetGroup -Name $principal) { - Write-Output "Assigning SSO Group ($ssoGroup) in vCenter Server ($($ssoServer.vmName)) to $type ($principal) for domain ($domain): SUCCESSFUL" - } - else { Write-Error "Assigning SSO Group ($ssoGroup) in vCenter Server ($($ssoServer.vmName)) to $type ($principal) for domain ($domain): FAILED" - } - } - else { - Write-Warning "Assigning SSO Group ($ssoGroup) in vCenter Server ($($ssoServer.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" - } - } - 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 $ssoConnection - $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 ($($ssoServer.vmName)) to $type ($principal) for domain ($domain): SUCCESSFUL" + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + $vcfNsxDetails = Get-NsxtServerDetail -fqdn $server -user $user -pass $pass -domain $domain + if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) { + if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass) { + if (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}) { + 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 +'" + } + ] + } + }' + $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 } - else { Write-Error "Assigning SSO Group ($ssoGroup) in vCenter Server ($($ssoServer.vmName)) to$type ($principal) for domain ($domain): FAILED" + else { + Write-Error "Credential in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($($vcfNsxDetails.fqdn)), already exists: PRE_VALIDATION_FAILED" } } else { - Write-Warning "Assigning SSO Group ($ssoGroup) in vCenter Server ($($ssoServer.vmName)) to $type ($principal) for domain ($domain). already exists: SKIPPED" - } + Write-Warning "Adding NSX Adapter in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($($vcfNsxDetails.fqdn)), already exists: SKIPPED" + } } - else { - Write-Error "Unable to find $type ($principal) in Active Directory Domain ($domain), create and retry" + else { + Write-Error "Remote Collector Group in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($collectorGroupName), does not exist: 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 find Identity Source in vCenter Server ($($vcenter.fqdn)) named ($domain)" - } - Disconnect-SsoAdminServer -Server $ssoServer.fqdn - } - else { - Write-Error "Unable to connect to vCenter Single-Sign On ($($ssoServer.fqdn))" } } - else { - Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials" - } - } - else { - Write-Error "Unable to authenticate to Active Directory with user ($domainBindUser) and password ($domainBindPass), check details" - } - } - elseif ($source -eq "local") { - Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null - if ($accessToken) { - $ssoServer = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $sddcDomain - $ssoConnection = Connect-SsoAdminServer -Server $ssoServer.fqdn -User $ssoServer.ssoAdmin -Password $ssoServer.ssoAdminPass - if ($DefaultSsoAdminServers.Name -eq $($ssoServer.fqdn)) { - $targetGroup = Get-SsoGroup -Domain vsphere.local -Name $ssoGroup -Server $ssoConnection - if (Get-IdentitySource | Where-Object { $_.Name -eq $domain }) { - if ($type -eq "group") { - if (!(Get-SsoGroup -Group $targetGroup -Name $principal -Server $ssoConnection)) { - $ldapGroup = Get-SsoGroup -Domain $domain -Name $principal -Server $ssoConnection - $ldapGroup | Add-GroupToSsoGroup -TargetGroup $targetGroup -ErrorAction SilentlyContinue - if (Get-SsoGroup -Group $targetGroup -Name $principal -Server $ssoConnection) { - Write-Output "Assigning SSO Group ($ssoGroup) in vCenter Server ($($ssoServer.vmName)) to $type ($principal) for domain ($domain): SUCCESSFUL" - } - else { - Write-Error "Assigning SSO On Group ($ssoGroup) in vCenter Server ($($ssoServer.vmName)) to $type ($principal) for domain ($domain): FAILED" - } - } - else { - Write-Warning "Assigning SSO Group ($ssoGroup) in vCenter Server ($($ssoServer.vmName)) to $type ($principal) for domain ($domain).already exists: SKIPPED" - } - } - elseif ($type -eq "user") { - if (!(Get-SsoPersonUser -Group $targetGroup -Server $ssoConnection | Where-Object {$_.Name -eq $principal})) { - $ldapUser = Get-SsoPersonUser -Domain $domain -Name $principal -Server $ssoConnection - $ldapUser | Add-UserToSsoGroup -TargetGroup $targetGroup -ErrorAction SilentlyContinue - if (Get-SsoPersonUser -Group $targetGroup -Server $ssoConnection| Where-Object {$_.Name -eq $principal}) { - Write-Output "Assigning SSO Group ($ssoGroup) in vCenter Server ($($ssoServer.vmName)) to $type ($principal) for domain ($domain): SUCCESSFUL" - } - else { - Write-Error "Assigning SSO Group ($ssoGroup) in vCenter Server ($($ssoServer.vmName)) to $type ($principal) for domain ($domain): FAILED" - } - } - else { - Write-Warning "Assigning SSO Group ($ssoGroup) in vCenter Server ($($ssoServer.vmName)) to $type ($principal) for domain ($domain), already exists: SKIPPED" - } - } - } - else { - Write-Error "Unable to find Identity Source in vCenter Server ($($vcenter.fqdn)) named ($domain)" - } - Disconnect-SsoAdminServer -Server $ssoServer.fqdn - } - else { - Write-Error "Unable to connect to vCenter Single-Sign On ($($ssoServer.fqdn))" - } - } - else { - Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials" } } } @@ -6204,5053 +6725,8014 @@ Function Add-SsoPermission { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-SsoPermission +Export-ModuleMember -Function Add-vROPSAdapterNsxt -Function Add-vSphereRole { +Function Add-vROPSAdapterPing { <# - .SYNOPSIS - Add a vSphere role + .SYNOPSIS + Adds a Ping Adapter to vRealize Operations Manager .DESCRIPTION - The Add-vSphereRole cmdlet creates a role in vCenter Server. 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: - - Verifies if the role already exists and if not creates it - - Assigns permissions to the role based on the template file provided + The Add-vROPSAdapterPing cmdlet adds a Ping adapter to vRealize Operations 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 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 Remote Collector Group exits in vRealize Operations Manager + - Validates that the Ping Adapter does not already exist in vRealize Operations Manager + - Creates a new Ping adapter in vRealize Operations Manager .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 + 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' #> 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, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$template + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$addressList, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$adapterName, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$collectorGroupName ) Try { - if (!$PsBoundParameters.ContainsKey("template")) { - $template = Get-ExternalFileName -title "Select the vSphere role template (.role)" -fileType "role" -location "C:\Program Files\WindowsPowerShell\Modules\PowerValidatedSolutions\vSphereRoles" - } - else { - if (!(Test-Path -Path $template)) { - Write-Error "vSphere Role Template '$template' File Not Found" - Break - } - } - - $vcenter = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT - Connect-VIServer -Server $vcenter.fqdn -User $vcenter.ssoAdmin -pass $vcenter.ssoAdminPass | Out-Null - if ($DefaultVIServer.Name -eq $($vcenter.fqdn)) { - $roleContent = Get-Content -Path $template - $checkRole = Get-VIRole -Server $vcenter.fqdn | Where-Object { $_.Name -eq $roleName } - if (!$checkRole ) { - New-VIRole -Name $roleName -Server $vcenter.fqdn | Out-Null - $checkRole = Get-VIRole -Server $vcenter.fqdn | Where-Object { $_.Name -eq $roleName } - if ($checkRole ) { - Foreach ($privilege in $roleContent) { - if (-not ($privilege -eq $null -or $privilege -eq "")) { - Set-VIRole -Server $vcenter.fqdn -Role $roleName -AddPrivilege (Get-VIPrivilege -ID $privilege) -Confirm:$False -ErrorAction SilentlyContinue | Out-Null + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) { + if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass) { + if (Get-vROPSCollectorGroup | Where-Object {$_.name -eq $collectorGroupName}) { + if (Get-vROPSSolution | Where-Object {$_.id -match "Ping"}) { + if (!(Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $adapterName})) { + $json = '{ + "name": "'+ $adapterName +'", + "description": "Ping Adapter - '+ $adapterName +'", + "adapterKindKey": "PingAdapter", + "monitoringInterval": 5, + "collectorGroupId": "'+ (Get-vROPSCollectorGroup | Where-Object {$_.name -eq $collectorGroupName}).id +'", + "resourceIdentifiers": [ + { + "name": "unique_name", + "value": "'+ $adapterName +'" + }, + { + "name": "address_list", + "value": "'+ $addressList +'" + }, + { + "name": "batch_circle_interval", + "value": "0" + }, + { + "name": "count", + "value": "20" + }, + { + "name": "dns_resolving_interval", + "value": "30" + }, + { + "name": "dont_fragment", + "value": "false" + }, + { + "name": "generate_fqdn_children", + "value": "false" + }, + { + "name": "packet_size", + "value": "56" + }, + { + "name": "period", + "value": "2000" + } + ] + }' + + $json | Out-File .\addAdapter.json + Add-vROPSAdapter -json .\addAdapter.json | Out-Null + + if (Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $adapterName}) { + Start-vROPSAdapter -adapterId (Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $adapterName}).id | Out-Null + Write-Output "Adding Ping Adapter in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($adapterName): SUCCESSFUL" + } + else { + Write-Error "Adding Ping Adapter in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($adapterName)): POST_VALDATION_FAILED" + } + Remove-Item .\addAdapter.json -Force -Confirm:$false + } + else { + Write-Warning "Adding Ping Adapter in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($adapterName), already exists: SKIPPED" + } + } + else { + Write-Error "The Ping Management Pack in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)), not activated: PRE_VALIDATION_FAILED" + } + } + else { + Write-Error "Remote Collector Group in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($collectorGroupName), does not exist: PRE_VALIDATION_FAILED" + } } } - Write-Output "Creating a new role in vCenter Server ($($vcenter.fqdn)) named ($roleName): SUCCESSFUL" } - else { - Write-Error "Creating a new role in vCenter Server ($($vcenter.fqdn)) named ($roleName): FAILED" - } - } - else { - Write-Warning "Creating a new role in vCenter Server ($($vcenter.fqdn)) named ($roleName), already exists: SKIPPED" } - Disconnect-VIServer $vcenter.fqdn -Confirm:$false -WarningAction SilentlyContinue - } - else { - Write-Error "Unable to connect to vCenter Server ($($vcenter.fqdn))" } } Catch { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-vSphereRole +Export-ModuleMember -Function Add-vROPSAdapterPing -Function Add-VMFolder { +Function Update-vROPSAdapterSddcHealth { <# - .SYNOPSIS - Create a VM Folder + .SYNOPSIS + Updates the SDDC Health Adapters names in vRealize Operations Manager - .DESCRIPTION - The Add-VMFolder cmdlet creates a VM and Template folder. The cmdlet connects to SDDC Manager using the -server, -user, and -password values - to retrive the vCenter Server details from its inventory and then: - - Verifies that the folder has not already been created - - Creates the folder + .DESCRIPTION + The Update-vROPSAdapterSddcHealth cmdlet updates the names of the SDDC Health Adapters in vRealize Operations + 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 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 SDDC Health Adapters exits in vRealize Operations Manager + - Gathers the unique ID of the Remote Collectors + - Gathers the details of the SDDC Health Adapters + - Updates the name of the SDDC Health Adapters - .EXAMPLE - Add-VMFolder -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -foldername "myFolder" - This example shows how to create the folder myFolder within the VMware Cloud Foundation domain sfo-m01 - #> + .EXAMPLE + Update-vROPSAdapterSddcHealth -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! + This example updates all the name of all SDDC Health Adapters + #> 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]$folderName + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass ) Try { - Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null - if ($accessToken) { - $vcenter = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain -ErrorAction SilentlyContinue - if ($vcenter) { - 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 - $datacenter = (Get-Datacenter -Cluster $cluster -Server $vcenter.fqdn).Name - $folderExists = (Get-Folder -Name $folderName -Server $vcenter.fqdn -WarningAction SilentlyContinue -ErrorAction Ignore) - if ($folderExists) { - Write-Warning "Adding VM and Template Folder to vCenter Server ($($vcenter.fqdn)) named ($folderName), already exists: SKIPPED" - } - else { - $folder = (Get-View -Server $vcenter.fqdn (Get-View -Server $vcenter.fqdn -viewtype datacenter -filter @{"name" = [String]$datacenter }).vmfolder).CreateFolder($folderName) - $folderExists = (Get-Folder -Name $folderName -Server $vcenter.fqdn -WarningAction SilentlyContinue -ErrorAction Ignore) - if ($folderExists) { - Write-Output "Adding VM and Template Folder to vCenter Server ($($vcenter.fqdn)) named ($folderName): SUCCESSFUL" - } - else { - Write-Error "Adding VM and Template Folder to vCenter Server ($($vcenter.fqdn)) named ($folderName): FAILED" + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) { + if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass) { + if ($adapters = Get-vROPSAdapter | Where-Object {$_.resourceKey.adapterKindKey -eq "SDDCHealthAdapter"}) { + Foreach ($adapter in $adapters) { + $collectorDetails = Get-vROPSCollector | Where-Object {$_.id -eq $adapter.collectorId} + $adapterName = (($adapter.resourceKey.name).Split("-"))[0] + "-" + ($collectorDetails.name -Split ("vRealize Operations Manager Collector-")) + $json = '{ + "resourceKey": { + "name": "'+ $adapterName +'", + "adapterKindKey": "SDDCHealthAdapter", + "resourceKindKey": "SDDCHealth Instance" + }, + "description": "SDDC Health Adapter for'+ ($collectorDetails.name -Split ("vRealize Operations Manager Collector-")) +'", + "collectorId": '+ $($collectorDetails.id) +', + "monitoringInterval": 5, + "id": "'+ $($adapter.id) +'" + }' + + $json | Out-File .\updateAdapter.json + if (!($adapter.resourceKey.name -eq $adapterName)) { + Set-vROPSAdapter -json .\updateAdapter.json | Out-Null + Write-Output "Renaming Adapter ($($adapter.resourceKey.name)) to ($adapterName): SUCCESSFUL" + Remove-Item .\updateAdapter.json -Force -Confirm:$false + } + else { + Write-Warning "Renaming Adapter ($($adapter.resourceKey.name)) to ($adapterName), already performed: SKIPPED" + } + } + } + else { + Write-Error "Unable to locate Adapters of type (SDDCHealthAdapter) in vealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)): PRE_VALIDATION_FAILED" + } } } - Disconnect-VIServer $vcenter.fqdn -Confirm:$false -WarningAction SilentlyContinue - } - else { - Write-Error "Unable to connect to vCenter Server ($($vcenter.fqdn))" } } - else { - 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" } } Catch { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-VMFolder - -Function Undo-VMFolder { +Export-ModuleMember -Function Update-vROPSAdapterSddcHealth + +Function Add-vROPSAdapterSddcHealth { <# - .SYNOPSIS - Remove a VM Folder + .SYNOPSIS + Adds an SDDC Health Adapters for Remote Collectors - .DESCRIPTION - The Undo-VMFolder cmdlet removes a VM and Template folder. 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 instance - - Verifies that the folder is present in vCenter Server - - Removes the VM and Template folder from the vCenter Server Inventory - .EXAMPLE - Undo-VMFolder -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -foldername "myFolder" - This example shows how to remove the folder myFolder within the VMware Cloud Foundation domain sfo-m01 - #> + .DESCRIPTION + The Add-vROPSAdapterSddcHealth cmdlet adds SDDC Health Adapters for the Remove Collectors in vRealize + Operations 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 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 SDDC Health Adapters do not exist in vRealize Operations Manager + - Gathers the Remote Collector details from vRealize Operations Manager + - Creates a new SDDC Health Adapter for each Remote Collector in vRealize Operations Manager + + .EXAMPLE + Add-vROPSAdapterSddcHealth -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! + This example creates an SDDC Health Adapter for each Remote Collector Node found in vRealize Operations 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]$folderName, - [Parameter (Mandatory = $true)] [ValidateSet("Datacenter", "VM", "Network", "HostAndCluster", "Datastore")] [String]$folderType + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass ) Try { - Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null - if ($accessToken) { - $vcenter = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain -ErrorAction SilentlyContinue - if ($vcenter) { - Connect-VIServer -Server $vcenter.fqdn -User $vcenter.ssoAdmin -pass $vcenter.ssoAdminPass | Out-Null - if ($DefaultVIServer.Name -eq $($vcenter.fqdn)) { - $folderExists = (Get-Folder -Name $folderName -Type $folderType -Server $vcenter.fqdn -ErrorAction Ignore) - if (!$folderExists) { - Write-Warning "Removing Folder Type ($folderType) from vCenter Server ($($vcenter.fqdn)) with name ($folderName), folder does not exist: SKIPPED" - } - else { - Get-Folder -Name $folderName -Type $folderType -Server $vcenter.fqdn | Remove-Folder -Confirm:$false -ErrorAction Ignore - $folderExists = (Get-Folder -Name $folderName -Type $folderType -Server $vcenter.fqdn -ErrorAction Ignore) - if (!$folderExists) { - Write-Output "Removing Folder Type ($folderType) from vCenter Server ($($vcenter.fqdn)) with name ($folderName): SUCCESSFUL" - } - else { - Write-Error "Removing Folder Type ($folderType) from vCenter Server ($($vcenter.fqdn)) with name ($folderName): FAILED" + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) { + if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass) { + if ($remoteCollectors = (Get-vROPSCollector | Where-Object {$_.type -eq "REMOTE"})) { + Foreach ($collector in $remoteCollectors) { + $adapterName = "SDDC Health Adapter Instance -" + ($collector.name -Split ("vRealize Operations Manager Collector-")) + $json = '{ + "resourceKey": { + "name": "'+ $adapterName +'", + "adapterKindKey": "SDDCHealthAdapter", + "resourceKindKey": "SDDCHealth Instance" + }, + "description": "SDDC Health Adapter for'+ ($collector.name -Split ("vRealize Operations Manager Collector-")) +'", + "collectorId": '+ $($collector.id) +', + "monitoringInterval": 5 + }' + + $json | Out-File .\addAdapter.json + if (!(Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $adapterName})) { + Add-vROPSAdapter -json .\addAdapter.json | Out-Null + if (Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $adapterName}) { + Start-vROPSAdapter -adapterId (Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $adapterName}) | Out-Null + Write-Output "Adding Adapter ($adapterName) to vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)): SUCCESSFUL" + } + else { + Write-Error "Adding Adapter ($adapterName) to vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Adding Adapter ($adapterName) to vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)), already performed: SKIPPED" + } + Remove-Item .\addAdapter.json -Force -Confirm:$false + } + } + else { + Write-Error "Unable to locate Remote Collectors in vealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)): PRE_VALIDATION_FAILED" + } } } - Disconnect-VIServer $vcenter.fqdn -Confirm:$false -WarningAction SilentlyContinue - } - else { - Write-Error "Unable to connect to vCenter Server ($($vcenter.fqdn))" } } - else { - 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" } } Catch { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Undo-VMFolder +Export-ModuleMember -Function Add-vROPSAdapterSddcHealth -Function Add-AntiAffinityRule { +Function Add-vROPSAlertPluginEmail { <# - .SYNOPSIS - Creates a vSphere Anti-Affinity rule + .SYNOPSIS + Adds an Email based Alert Plugin - .DESCRIPTION - The Add-AntiAffinityRule cmdlet creates a vSphere Anti-Affinity rule. The cmdlet connects to SDDC Manager using the -server, -user, and -password values - to retrive the vCenter Server details from its inventory and then: - - Verifies that the anti-affinity rule has not already been created - - Creates the anti-affinity rule + .DESCRIPTION + The Add-vROPSAlertPluginEmail cmdlet adds an Email based Alert Plugin in vRealize Operations 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 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 Email Alert Plugin does not exist in vRealize Operations Manager + - Creates a new Email Alert Plugin and enables it in vRealize Operations Manager - .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 - #> + .EXAMPLE + Add-vROPSAlertPluginEmail -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -pluginName "Email-Alert-Plugin" -smtpServer smtp.rainpole.io -smtpPort 25 -senderAddress "vrops-alerts@rainpole.io" -secureConnection true -protocol TLS -authentication false + This example creates and enables an Email Alert Plugin in vRealize Operations Manager without authentication + + .EXAMPLE + Add-vROPSAlertPluginEmail -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -pluginName "Email-Alert-Plugin" -smtpServer smtp.rainpole.io -smtpPort 25 -senderAddress "vrops-alerts@rainpole.io" -secureConnection true -protocol TLS -authentication true -authUser administrator -authPass VMw@re1! + This example creates and enables an Email Alert Plugin in vRealize Operations Manager with authentication + #> 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 + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pluginName, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$smtpServer, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$smtpPort, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$senderAddress, + [Parameter (Mandatory = $true)] [ValidateSet("true","false")] [ValidateNotNullOrEmpty()] [String]$secureConnection, + [Parameter (Mandatory = $false)] [ValidateSet("SSL","TLS")] [ValidateNotNullOrEmpty()] [String]$protocol, + [Parameter (Mandatory = $true)] [ValidateSet("true","false")] [ValidateNotNullOrEmpty()] [String]$authentication, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$authUser, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$authPass ) Try { - Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null - if ($accessToken) { - $vcenter = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain -ErrorAction SilentlyContinue - if ($vcenter) { - 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 - $antiAffinityRuleExists = (Get-Cluster -Name $cluster | Get-DrsRule | Where-Object {$_.Name -eq $ruleName}) - if ($antiAffinityRuleExists) { - 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 - $antiAffinityRuleExists = (Get-Cluster -Name $cluster | Get-DrsRule | Where-Object {$_.Name -eq $ruleName}) - if ($antiAffinityRuleExists) { - 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): FAILED" + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) { + if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass) { + if (!(Get-vROPSAlertPlugin | Where-Object {$_.name -eq $pluginName})) { + if ($authentication -eq "true") { + $json = '{ + "pluginTypeId" : "StandardEmailPlugin", + "name" : "'+ $pluginName +'", + "description" : "", + "configValues" : [ { + "name" : "IS_SECURE_CONNECTION", + "value" : "'+ $secureConnection +'" + }, { + "name" : "SECURE_CONNECTION_TYPE", + "value" : "'+ $protocol +'" + }, { + "name" : "IS_REQUIRES_AUTHETICATION", + "value" : "'+ $authentication +'" + }, { + "name" : "USERNAME", + "value" : "'+ $authUser +'" + }, { + "name" : "PASSWORD", + "value" : "'+ $authPass +'" + },{ + "name" : "SMTP_HOST", + "value" : "'+ $smtpServer +'" + }, { + "name" : "SMTP_PORT", + "value" : "'+ $smtpPort +'" + }, { + "name" : "senderEmailAddress", + "value" : "'+ $senderAddress +'" + }, { + "name" : "senderName", + "value" : "'+ ($senderAddress -split("@"))[0] +'" + } ] + }' + } + else { + $json = '{ + "pluginTypeId" : "StandardEmailPlugin", + "name" : "'+ $pluginName +'", + "description" : "", + "configValues" : [ { + "name" : "IS_SECURE_CONNECTION", + "value" : "'+ $secureConnection +'" + }, { + "name" : "SECURE_CONNECTION_TYPE", + "value" : "'+ $protocol +'" + }, { + "name" : "SMTP_HOST", + "value" : "'+ $smtpServer +'" + }, { + "name" : "SMTP_PORT", + "value" : "'+ $smtpPort +'" + }, { + "name" : "senderEmailAddress", + "value" : "'+ $senderAddress +'" + }, { + "name" : "senderName", + "value" : "'+ ($senderAddress -split("@"))[0] +'" + } ] + }' + } + $json | Out-File .\addAlertPlugin.json + Add-vROPSAlertPlugin -json .\addAlertPlugin.json | Out-Null + if (Get-vROPSAlertPlugin | Where-Object {$_.name -eq $pluginName}) { + Set-vROPSAlertPluginStatus -pluginId (Get-vROPSAlertPlugin | Where-Object {$_.name -eq $pluginName}).pluginId -status true + Write-Output "Adding Alert Plugin to vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($pluginName): SUCCESSFUL" + } + else { + Write-Error "Adding Alert Plugin to vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($pluginName): POST_VALIDATION_FAILED" + } + Remove-Item .\addAlertPlugin.json -Force -Confirm:$false + } + else { + Write-Warning "Adding Alert Plugin to vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($pluginName), already exists: SKIPPED" + } } } - Disconnect-VIServer $vcenter.fqdn -Confirm:$false -WarningAction SilentlyContinue - } - else { - Write-Error "Unable to connect to vCenter Server ($($vcenter.fqdn))" } } - else { - 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" } } Catch { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-AntiAffinityRule +Export-ModuleMember -Function Add-vROPSAlertPluginEmail -Function Add-ClusterGroup { +Function Import-vROPSNotification { <# - .SYNOPSIS - Creates a vSphere DRS Cluster Group + .SYNOPSIS + Adds notifications - .DESCRIPTION - The Add-ClusterGroup cmdlet creates a vSphere DRS Cluster Group. The cmdlet connects to SDDC Manager using the -server, -user, and -password values - to retrive the vCenter Server details from its inventory and then: - - Verifies that that the vSphere DRS Cluster Group does not already exist - - Creates the vSphere DRS Cluster Group + .DESCRIPTION + The Import-vROPSNotification cmdlet adds notifications in vRealize Operations 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 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 .csv provided exists + - Adds notifications based on a .csv file into vRealize Operations Manager - .EXAMPLE - Add-ClusterGroup -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -drsGroupName "Clustered Workspace ONE Access Appliances" -drsGroupVMs "xreg-wsa01a,xreg-wsa01b,xreg-wsa01c" - This example shows how to create a vSphere DRS Cluster group in the vCenter Server of the sfo-m01 workload domain - #> + .EXAMPLE + Import-vROPSNotification -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -csvPath .\SampleNotifications\vrops-vcf-notifications.csv + This example adds notifications based on the comma seperated value file provided + #> 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]$drsGroupName, - [Parameter (Mandatory = $true)] [String]$drsGroupVMs + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$csvPath ) - Try { - Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null - if ($accessToken) { - $vcenter = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain -ErrorAction SilentlyContinue - if ($vcenter) { - 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 (!$PsBoundParameters.ContainsKey("csvPath")) { + $csvPath = Get-ExternalFileName -title "Select the Comma Seperated Value (.csv) File" -fileType "csv" -location "default" + } + if (!(Test-Path -Path $csvPath)) { + Write-Error "Comma Seperated Value (.csv) File ($csvPath) File Not Found" + Break + } - $drsGroupExists = (Get-Cluster -Name $cluster | Get-DrsClusterGroup | Where-Object {$_.Name -eq $drsGroupName}) - if ($drsGroupExists) { - Write-Warning "Adding vSphere DRS Group to vCenter Server ($($vcenter.fqdn)) named ($drsGroupName), already exists: SKIPPED" - } - else { - $vmNames = $drsGroupVMs.split(",") - $vms = foreach ($name in $vmNames) { Get-VM -name $name -ErrorAction SilentlyContinue } - New-DrsClusterGroup -Cluster $cluster -VM $vms -Name $drsGroupName | Out-Null - $drsGroupExists = (Get-Cluster -Name $cluster | Get-DrsClusterGroup | Where-Object {$_.Name -eq $drsGroupName}) - if ($drsGroupExists) { - Write-Output "Adding vSphere DRS Group to vCenter Server ($($vcenter.fqdn)) named ($drsGroupName): SUCCESSFUL" - } - else { - Write-Error "Adding vSphere DRS Group to vCenter Server ($($vcenter.fqdn)) named ($drsGroupName): FAILED" + Try { + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) { + if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass) { + New-vROPSNotification $csvPath | Out-Null + Write-Output "Adding Notifications to vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) using Comma Seperated Value File ($csvPath): SUCCESSFUL" } } - Disconnect-VIServer $vcenter.fqdn -Confirm:$false -WarningAction SilentlyContinue - } - else { - Write-Error "Unable to connect to vCenter Server ($($vcenter.fqdn))" } } - else { - 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" } } Catch { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-ClusterGroup +Export-ModuleMember -Function Import-vROPSNotification -Function Add-VmStartupRule { + +########################################### E N D O F F U N C T I O N S ######################################### +####################################################################################################################### + + +####################################################################################################################### +######################## P R I V A T E C L O U D A U T O M A T I O N F U N C T I O N S ######################## + +Function Export-vRAJsonSpec { <# - .SYNOPSIS - Creates a VM to VM DRS rule + .SYNOPSIS + Create vRealize Automation Deployment JSON specification - .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 to retrive the vCenter Server details from its inventory and then: - - Verifies that that the Virtual Machine to Virtual Machine startup rule does not already exist - - Creates the vSphere DRS Virtual Machine to Virtual Machine startup rule + .DESCRIPTION + The Export-vRAJsonSpec cmdlet creates the JSON specification file using the Planning and Preparation workbook + to deploy vRealize Automation 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 - 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 + Export-vRAJsonSpec -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 vRealize Automation using the Planning and Preparation Workbook + #> 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]$vmGroup, - [Parameter (Mandatory = $true)] [String]$dependOnVmGroup - ) + [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 { - Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null - if ($accessToken) { - $vcenter = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain -ErrorAction SilentlyContinue - if ($vcenter) { - 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 - $vmGroupExists = (Get-Cluster -Name $cluster | Get-DrsClusterGroup | Where-Object {$_.Name -eq $vmGroup}) - if ($vmGroupExists) { - $dependOnVmGroupExists = (Get-Cluster -Name $cluster | Get-DrsClusterGroup | Where-Object {$_.Name -eq $dependOnVmGroup}) - if ($dependOnVmGroupExists) { - $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 (!$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["vra_license"].Value) { + $licenseKey = $pnpWorkbook.Workbook.Names["vra_license"].Value } else { - Add-DrsVmToVmGroup -name $ruleName -vmGroup $vmGroup -dependOnVmGroup $dependOnVmGroup -Enabled -cluster $cluster | Out-Null - Start-Sleep 5 - $ruleNameExists = Get-DrsVmToVmGroup -Cluster $cluster -Name $ruleName - if ($ruleNameExists) { - Write-Output "Adding vSphere DRS Virtual Machine to Virtual Machine Group to vCenter Server ($($vcenter.fqdn)) named ($ruleName): SUCCESSFUL" + $licenseKey = $pnpWorkbook.Workbook.Names["vrs_license"].Value + } + $vraLicense = Get-vRSLCMLockerLicense | Where-Object {$_.key -eq $licenseKey} + if ($vraLicense.key -eq $licenseKey) { + $vraCertificate = Get-vRSLCMLockerCertificate | Where-Object {$_.alias -eq $pnpWorkbook.Workbook.Names["xreg_vra_virtual_hostname"].Value} + if ($vraCertificate.alias) { + $defaultPassword = Get-vRSLCMLockerPassword | Where-Object {$_.alias -eq $pnpWorkbook.Workbook.Names["vrslcm_xreg_env_password_alias"].Value} + if ($defaultPassword.alias) { + $vraPassword = Get-vRSLCMLockerPassword | Where-Object {$_.alias -eq $pnpWorkbook.Workbook.Names["xreg_vra_root_password_alias"].Value} + if ($vraPassword.alias) { + $vcCredentials = Get-vRSLCMLockerPassword | Where-Object {$_.alias -eq (($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["vrslcm_xreg_dc"].Value} + if ($datacenterName) { + $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:" + $($vraCertificate.vmid) + ":" + $($vraCertificate.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]@{ + 'certificate' = ("locker:certificate:" + $($vraCertificate.vmid) + ":" + $($vraCertificate.alias)) + 'productPassword' = ("locker:password:" + $($vraPassword.vmid) + ":" + $($vraPassword.alias)) + 'licenseRef' = ("locker:license:" + $($vraLicense.vmid) + ":" + $($vraLicense.alias)) + 'fipsMode' = "false" + 'timeSyncMode' = "ntp" + 'ntp' = $pnpWorkbook.Workbook.Names["region_ntp1_server"].Value + 'affinityRule' = $false + 'configureAffinitySeparateAll' = "true" + 'nodeSize' = $pnpWorkbook.Workbook.Names["xreg_vra_appliance_size"].Value.ToLower() + 'vraK8ServiceCidr' = $pnpWorkbook.Workbook.Names["xreg_vra_k8s_cluster_cidr"].Value + 'vraK8ClusterCidr' = $pnpWorkbook.Workbook.Names["xreg_vra_k8s_service_cidr"].Value + 'clusterFqdn' = $pnpWorkbook.Workbook.Names["xreg_vra_virtual_fqdn"].Value + } + + #### Generate vRealize Log Insight Cluster Details + $clusterVipProperties = @() + $clusterVipProperties += [pscustomobject]@{ + 'hostName' = $pnpWorkbook.Workbook.Names["xreg_vra_virtual_fqdn"].Value + } + + $clusterVipsObject = @() + $clusterVipsObject += [pscustomobject]@{ + 'type' = "vra-va" + 'properties' = ($clusterVipProperties | Select-Object -Skip 0) + } + + $clusterObject = @() + $clusterObject += [pscustomobject]@{ + 'clusterVips' = $clusterVipsObject + } + + #### Generate vRealize Log Insight Node Details + $vraPrimaryProperties = @() + $vraPrimaryProperties += [pscustomobject]@{ + 'hostName' = $pnpWorkbook.Workbook.Names["xreg_vra_nodea_fqdn"].Value + 'vmName' = $pnpWorkbook.Workbook.Names["xreg_vra_nodea_hostname"].Value + 'ip' = $pnpWorkbook.Workbook.Names["xreg_vra_nodea_ip"].Value + } + + $vraSecondary1Properties = @() + $vraSecondary1Properties += [pscustomobject]@{ + 'hostName' = $pnpWorkbook.Workbook.Names["xreg_vra_nodeb_fqdn"].Value + 'vmName' = $pnpWorkbook.Workbook.Names["xreg_vra_nodeb_hostname"].Value + 'ip' = $pnpWorkbook.Workbook.Names["xreg_vra_nodeb_ip"].Value + } + + $vraSecondary2Properties = @() + $vraSecondary2Properties += [pscustomobject]@{ + 'hostName' = $pnpWorkbook.Workbook.Names["xreg_vra_nodec_fqdn"].Value + 'vmName' = $pnpWorkbook.Workbook.Names["xreg_vra_nodec_hostname"].Value + 'ip' = $pnpWorkbook.Workbook.Names["xreg_vra_nodec_ip"].Value + } + + $nodesObject = @() + $nodesobject += [pscustomobject]@{ + 'type' = "vrava-primary" + 'properties' = ($vraPrimaryProperties | Select-Object -Skip 0) + } + $nodesobject += [pscustomobject]@{ + 'type' = "vrava-secondary" + 'properties' = ($vraSecondary1Properties | Select-Object -Skip 0) + } + $nodesobject += [pscustomobject]@{ + 'type' = "vrava-secondary" + 'properties' = ($vraSecondary2Properties | 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") { $vraVersion = "8.4.1"} + if ($vcfVersion -eq "4.3.1") { $vraVersion = "8.5.0"} + $productsObject = @() + $productsObject += [pscustomobject]@{ + 'id' = "vra" + 'version' = $vraVersion + 'properties' = ($productPropertiesObject | Select-Object -Skip 0) + 'clusterVIP' = ($clusterObject | Select-Object -Skip 0) + 'nodes' = $nodesObject + } + + if (!($xintEnvironment)) { + $vraDeploymentObject = @() + $vraDeploymentObject += [pscustomobject]@{ + 'environmentName' = $pnpWorkbook.Workbook.Names["vrslcm_xreg_env"].Value + 'infrastructure' = ($infrastructureObject | Select-Object -Skip 0) + 'products' = $productsObject + } + } + else { + $vraDeploymentObject = @() + $vraDeploymentObject += [pscustomobject]@{ + 'environmentId' = $xintEnvironment.environmentId + 'environmentName' = $pnpWorkbook.Workbook.Names["vrslcm_xreg_env"].Value + 'infrastructure' = ($infrastructureObject | Select-Object -Skip 0) + 'products' = $productsObject + } + } + + $vraDeploymentObject | ConvertTo-Json -Depth 12 | Out-File -Encoding UTF8 -FilePath "vraDeploymentSpec.json" + + Write-Output "Creation of Deployment JSON Specification file for vRealize Automation: 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["xreg_vra_root_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["vrslcm_xreg_env_password_alias"].Value)' not found in the vRealize Suite Lifecycle Manager Locker, add and retry" + } } else { - Write-Error "Adding vSphere DRS Virtual Machine to Virtual Machine Group to vCenter Server ($($vcenter.fqdn)) named ($ruleName): FAILED" + Write-Error "Certificate with alias '$($pnpWorkbook.Workbook.Names["xreg_vra_virtual_hostname"].Value)' not found in the vRealize Suite Lifecycle Manager Locker, add and retry" } } + else { + Write-Error "License with alias '$licenseKey' not found in the vRealize Suite Lifecycle Manager Locker, add and retry" + } } - else { - Write-Error "vSphere DRS Group (VM Group to start after dependency) in vCenter Server ($($vcenter.fqdn)) named ($dependOnVmGroup), does not exist: FAILED" - } - } - else { - Write-Error "vSphere DRS Group (VM Group to start first) in vCenter Server ($($vcenter.fqdn)) named ($vmGroup), does not exist: FAILED" } - Disconnect-VIServer $vcenter.fqdn -Confirm:$false -WarningAction SilentlyContinue - } - else { - Write-Error "Unable to connect to vCenter Server ($($vcenter.fqdn))" } } - else { - 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" } + Close-ExcelPackage $pnpWorkbook -NoSave -ErrorAction SilentlyContinue } Catch { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-VmStartupRule +Export-ModuleMember -Function Export-vRAJsonSpec -Function Move-VMtoFolder { +Function New-vRADeployment { <# - .SYNOPSIS - Moves VMs to a folder + .SYNOPSIS + Deploy vRealize Automation to vRealize Suite Lifecycle Manager - .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 - to retrive the vCenter Server details from its inventory and then: - - Verifies that the folder provided exists in the vCenter Server inventory - - Verified the virtual machine exists - - Moves the virtual machines provided in the -vmlist parameter + .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 vRealize Automation has not been deployed in VMware Cloud Foundation aware mode and retrives its details + - Requests a new deployment of vRealize Automation - .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 + New-vRADeployment -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -workbook .\pnp-workbook.xlsx + This example starts a deployment of vRealize Automation using the Planning and Preparation Workbook + #> 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]$vmList, - [Parameter (Mandatory = $true)] [String]$folder + [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 { - Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null - if ($accessToken) { - $vcenter = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain -ErrorAction SilentlyContinue - if ($vcenter) { - Connect-VIServer -Server $vcenter.fqdn -User $vcenter.ssoAdmin -pass $vcenter.ssoAdminPass | Out-Null - if ($DefaultVIServer.Name -eq $($vcenter.fqdn)) { - if (Get-Folder | Where-Object {$_.Name -eq $folder}) { - $vmNames = $vmList.split(",") - foreach ($vm in $vmNames) { - $checkVm = Get-VM -Name $vm -ErrorAction SilentlyContinue - if ($checkVm) { - Get-VM -Name $vm | Move-VM -InventoryLocation (Get-Folder | Where-Object {$_.Name -eq $folder}) | Out-Null - Write-Output "Relocating Virtual Machine in vCenter Server ($($vcenter.fqdn)) named ($vm) to folder ($folder): SUCCESSFUL" + 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-vRAJsonSpec -server $server -user $user -pass $pass -workbook $workbook | Out-Null + $json = (Get-Content -Raw .\vraDeploymentSpec.json) + $jsonSpec = $json | ConvertFrom-Json + if (!($checkProducts = (Get-vRSLCMEnvironment | Where-Object {$_.environmentName -eq $jsonSpec.environmentName}).products.id -contains $jsonSpec.products.id)) { + if (Get-vRSLCMLockerPassword | Where-Object {$_.alias -Match $($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])}) { + if ($jsonSpec.environmentId) { + $newRequest = Add-vRSLCMEnvironment -json $json -environmentId $jsonSpec.environmentId -addProduct + } + else { + $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 vRealize Automation Submitted Successfully (Request Ref: $($newRequest.requestId))" + } + } + else { + Write-Error "Request to deploy vRealize Automation failed, check the vRealize Suite Lifecycle Manager UI" + } + } + else { + Write-Error "License in vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($($jsonSpec.products.properties.licenseRef.Split(":")[3])), does not exist: FAILED" + } + } + 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.productPassword.Split(":")[3])), does not exist: FAILED" + } } else { - Write-Warning "Relocating Virtual Machine in vCenter Server ($($vcenter.fqdn)) named ($vm) to folder ($folder), Vitual Machine not found: SKIPPED" + Write-Warning "vRealize Automation in environment ($($jsonSpec.environmentName)) on vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)), already exists: SKIPPED" } } } - else { - Write-Error "Relocating Virtual Machine in vCenter Server ($($vcenter.fqdn)) named ($vm) to folder ($folder), Folder not found: FAILED" - } - Disconnect-VIServer $vcenter.fqdn -Confirm:$false -WarningAction SilentlyContinue - } - else { - Write-Error "Unable to connect to vCenter Server ($($vcenter.fqdn))" - } + } } - else { - 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" } } Catch { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Move-VMtoFolder +Export-ModuleMember -Function New-vRADeployment -Function Import-vRSLCMLockerCertificate { +Function Update-vRAOrganizationDisplayName { <# .SYNOPSIS - Add a certificate to the vRealize Suite Lifecycle Manager Locker + Configures the organization name .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 - - 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 + 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 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 + - Verifies if the organization name is already configured based on the input + - Configures the organization name .EXAMPLE - Import-vRSLCMLockerCertificate -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -certificateAlias "xint-vrops01" -certificatePassphrase "VMw@re1!" - This example gets the details of a certificate based on the vmid + Update-vRAOrganizationDisplayName -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -displayName "Rainpole" -vraUser configadmin -vraPass VMw@re1! + This example configures the organization display name as 'Rainpole' #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$certificateAlias, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$certificatePassphrase, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$certChainPath + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$displayName, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vraUser, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vraPass ) Try { - if (!$PsBoundParameters.ContainsKey("certChainPath")) { - $certChainPath = Get-ExternalFileName -title "Select the Certificate Chain PEM File (.pem)" -fileType "pem" -location "default" - } - else { - if (!(Test-Path -Path $certChainPath)) { - Write-Error "Certificate Chain '$certChainPath' File Not Found" - Break - } - } - $vrslcm = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass - Request-vRSLCMToken -fqdn $vrslcm.fqdn -username $vrslcm.adminUser -password $vrslcm.adminPass | Out-Null - if (($vrslcmHealth = Get-vRSLCMHealth).'vrlcm-server' -eq "UP") { - if (!(Get-vRSLCMLockerCertificate | Where-Object {$_.alias -eq $certificateAlias})) { - if ($PsBoundParameters.ContainsKey("certificatePassphrase")) { - $lockerCert = Add-vRSLCMLockerCertificate -vrslcmFQDN $vrslcm.fqdn -certificateAlias $certificateAlias -certificatePassphrase $certificatePassphrase -certChainPath $certChainPath - } - else { - $lockerCert = Add-vRSLCMLockerCertificate -vrslcmFQDN $vrslcm.fqdn -certificateAlias $certificateAlias -certChainPath $certChainPath - } - if ((Get-vRSLCMLockerCertificate | Where-Object {$_.alias -eq $certificateAlias})) { - Write-Output "Importing Certificate to the vRealize Suite Lifecycle Manager ($($vrslcm.fqdn)) Locker with alias ($certificateAlias): SUCCESSFUL" - } - else { - Write-Error "Importing Certificate to the vRealize Suite Lifecycle Manager ($($vrslcm.fqdn)) Locker with alias ($certificateAlias): FAILED" + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVraDetails = Get-vRAServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-vRAConnection -server $vcfVraDetails.loadBalancerFqdn) { + if (Test-vRAAuthentication -server $vcfVraDetails.loadBalancerFqdn -user $vraUser -pass $vraPass) { + $orgId = (Get-vRAOrganizationId).Split("orgs/")[-1] + if (!((Get-vRAOrganizationDisplayName -orgId $orgId).displayname -eq $displayName)) { + Set-vRAOrganizationDisplayName -orgId $orgId -displayName $displayName | Out-Null + if ((Get-vRAOrganizationDisplayName -orgId $orgId).displayname -eq $displayName) { + Write-Output "Updating Organization Display Name in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)): SUCCESSFUL" + } + else { + Write-Error "Updating Organization Display Name in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)): FAILED" + } + } + else { + Write-Warning "Updating Organization Display Name in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)), already defined: SKIPPED" + } + } + } } } - else { - Write-Warning "Importing Certificate to the vRealize Suite Lifecycle Manager ($($vrslcm.fqdn)) Locker with alias ($certificateAlias), already exist: SKIPPED" - } - } - else { - Write-Error "Unable to obtain access token from vRealize Suite Lifecycle Manager ($server), check credentials" } } Catch { - Write-Error $_.Exception.Message + Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Import-vRSLCMLockerCertificate +Export-ModuleMember -Function Update-vRAOrganizationDisplayName -Function Undo-vRSLCMLockerCertificate { +Function New-vRACloudAccount { <# .SYNOPSIS - Remove a certificate from the vRealize Suite Lifecycle Manager Locker + Creates vSphere and NSX-T Cloud Accounts .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 - - Verifies that the certificate is present in the vRealize Suite Lifecycle Manager Locker - - Removes the certificate from vRealize Suite Lifecycle Manager Locker + 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 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 + - Retrives details from SDDC Manager for the vCenter Server and NSX Management Cluster + - Adds a Cloud Account for vCenter Server and NSX Management Cluster .EXAMPLE - Undo-vRSLCMLockerCertificate -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -certificateAlias "xint-vrops01" - This example removes a certificate with an alias of 'xint-vrops01' from the vRealize Suite Lifecycle Manager Locker + New-vRACloudAccount -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -vraUser configadmin -vraPass VMw@re1! -capabilityTab private + This example creates vSphere and NSX-T Cloud Accounts in vRealize Automation #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$certificateAlias + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$domain, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vraUser, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vraPass, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$capabilityTab ) Try { - - $vrslcm = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass - Request-vRSLCMToken -fqdn $vrslcm.fqdn -username $vrslcm.adminUser -password $vrslcm.adminPass | Out-Null - if (($vrslcmHealth = Get-vRSLCMHealth).'vrlcm-server' -eq "UP") { - if (Get-vRSLCMLockerCertificate | Where-Object {$_.alias -eq $certificateAlias}) { - Remove-vRSLCMLockerCertificate -vmid (Get-vRSLCMLockerCertificate | Where-Object {$_.alias -eq $certificateAlias}).vmid | Out-Null - if ((Get-vRSLCMLockerCertificate | Where-Object {$_.alias -eq $certificateAlias})) { - Write-Error "Removing Certificate from the vRealize Suite Lifecycle Manager ($($vrslcm.fqdn)) Locker with alias ($certificateAlias): FAILED" - } - else { - Write-Output "Removing Certificate from the vRealize Suite Lifecycle Manager ($($vrslcm.fqdn)) Locker with alias ($certificateAlias): SUCCESSFUL" + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVraDetails = Get-vRAServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-vRAConnection -server $vcfVraDetails.loadBalancerFqdn) { + if (Test-vRAAuthentication -server $vcfVraDetails.loadBalancerFqdn -user $vraUser -pass $vraPass) { + if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) { + $vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain + $vcfNsxtDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain + if (!(Get-vRACloudAccount -type vsphere | Where-object {$_.name -eq $($vcfVcenterDetails.vmName)})) { + Connect-VIServer -Server $vcfVcenterDetails.fqdn -User $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass | Out-Null + if ($DefaultVIServer.Name -eq $($vcfVcenterDetails.fqdn)) { + $dataCenterMoref = (Get-View -Server $($vcfVcenterDetails.fqdn) -viewtype Datacenter).MoRef + $vcenterCloudAccount = '{ + "hostName": "' + $($vcfVcenterDetails.fqdn) + '", + "acceptSelfSignedCertificate": true, + "username": "' + $($vcfVcenterDetails.ssoAdmin) + '", + "password": "' + $($vcfVcenterDetails.ssoAdminPass) + '", + "dcId": "onprem", + "createDefaultZones": true, + "name": "' + $($vcfVcenterDetails.vmName) + '", + "regionIds": [ "' + $($dataCenterMoref.type) + ":" + $($dataCenterMoref.value) +'" ], + "tags": [ { "key": "' + $capabilityTag + '", "value": "" } ] + }' + Add-vRACloudAccount -type vsphere -json $vcenterCloudAccount | Out-Null + if (Get-vRACloudAccount -type vsphere | Where-object {$_.name -eq $($vcfVcenterDetails.vmName)}) { + Write-Output "Creating vSphere Cloud Account in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)) named ($($vcfVcenterDetails.fqdn)): SUCCESSFUL" + } + else { + Write-Error "Creating vSphere Cloud Account in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)) named ($($vcfVcenterDetails.fqdn)): POST_VALIDATION_FAILED" + } + } + else { + Write-Error "Unable to connect to vCenter Server ($($vcfVcenterDetails.fqdn)): PRE_VALIDATION_FAILED" + } + Disconnect-VIServer $($vcfVcenterDetails.fqdn) -Confirm:$false -WarningAction SilentlyContinue + } + else { + Write-Warning "Creating vSphere Cloud Account in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)) named ($($vcfVcenterDetails.fqdn)), already exists: SKIPPED" + } + if (!(Get-vRACloudAccount -type nsx-t | Where-object {$_.name -eq ($vcfNsxtDetails.fqdn).Split(".")[0]})) { + $nsxtCloudAccount = '{ + "hostName": "' + $($vcfNsxtDetails.fqdn) + '", + "acceptSelfSignedCertificate": true, + "password": "' + $($vcfNsxtDetails.adminPass) + '", + "name": "' + ($vcfNsxtDetails.fqdn).Split(".")[0] + '", + "username": "' + $($vcfNsxtDetails.adminUser) + '", + "associatedCloudAccountIds": [ "' + (Get-vRACloudAccount -type vsphere | Where-Object {$_.name -eq $vcfVcenterDetails.vmName}).id + '" ], + "tags": [ { "key": "' + $capabilityTag + '", "value": "" } ] + }' + Add-vRACloudAccount -type nsx-t -json $nsxtCloudAccount | Out-Null + if (Get-vRACloudAccount -type nsx-t | Where-object {$_.name -eq ($vcfNsxtDetails.fqdn).Split(".")[0]}) { + Write-Output "Creating NSX-T Cloud Account in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)) named ($(($vcfNsxtDetails.fqdn).Split(".")[0])): SUCCESSFUL" + } + else { + Write-Error "Creating NSX-T Cloud Account in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)) named ($(($vcfNsxtDetails.fqdn).Split(".")[0])): POST_VALIDATED_FAILED" + } + } + else { + Write-Warning "Creating NSX-T Cloud Account in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)) named ($(($vcfNsxtDetails.fqdn).Split(".")[0])), already exists: SKIPPED" + } + } + else { + Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" + } + } + } } } - else { - Write-Warning "Removing Certificate from the vRealize Suite Lifecycle Manager ($($vrslcm.fqdn)) Locker with alias ($certificateAlias), does not exist: SKIPPED" - } - } - else { - Write-Error "Unable to obtain access token from vRealize Suite Lifecycle Manager ($server), check credentials" } } Catch { - Write-Error $_.Exception.Message + Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Undo-vRSLCMLockerCertificate +Export-ModuleMember -Function New-vRACloudAccount -Function New-vRSLCMLockerPassword { +Function Undo-vRACloudAccount { <# .SYNOPSIS - Add a password to the vRealize Suite Lifecycle Manager Locker Locker + Removes the vSphere and NSX-T Cloud Accounts .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 - - Verifies that the password is not present in the vRealize Suite Lifecycle Manager Locker - - Adds the password to the vRealize Suite Lifecycle Manager Locker + 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 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 + - Retrives details from SDDC Manager for the vCenter Server and NSX Management Cluster + - Removes the Cloud Accounts for vCenter Server and NSX Management Cluster .EXAMPLE - New-vRSLCMLockerPassword -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -alias xint-vrops01-admin -password VMw@re1! -description "vRealize Operations Admin" -userName xint-vrops01-admin - This example adds a password with an alias of 'xint-vrops01-admin' to the vRealize Suite Lifecycle Manager Locker + Undo-vRACloudAccount -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -vraUser configadmin -vraPass VMw@re1! + This example creates vSphere and NSX-T Cloud Accounts in vRealize Automation #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$alias, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$password, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$description, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$userName + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$domain, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vraUser, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vraPass ) Try { - $vrslcm = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass - Request-vRSLCMToken -fqdn $vrslcm.fqdn -username $vrslcm.adminUser -password $vrslcm.adminPass | Out-Null - if (($vrslcmHealth = Get-vRSLCMHealth).'vrlcm-server' -eq "UP") { - if (!(Get-vRSLCMLockerPassword | Where-Object {$_.alias -eq $alias})) { - if ($PsBoundParameters.ContainsKey("description")) { - $lockerPassword = Add-vRSLCMLockerPassword -alias $alias -password $password -description $description -userName $userName - } - else { - $lockerPassword = Add-vRSLCMLockerPassword -alias $alias -password $password -userName $userName - } - if ((Get-vRSLCMLockerPassword | Where-Object {$_.alias -eq $alias})) { - Write-Output "Adding Password to the vRealize Suite Lifecycle Manager ($($vrslcm.fqdn)) Locker with alias ($alias): SUCCESSFUL" - } - else { - Write-Error "Adding Password to the vRealize Suite Lifecycle Manager ($($vrslcm.fqdn)) Locker with alias ($alias): FAILED" + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVraDetails = Get-vRAServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-vRAConnection -server $vcfVraDetails.loadBalancerFqdn) { + if (Test-vRAAuthentication -server $vcfVraDetails.loadBalancerFqdn -user $vraUser -pass $vraPass) { + if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) { + $vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain + $vcfNsxtDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain + if (Get-vRACloudAccount -type nsx-t | Where-object {$_.name -eq ($vcfNsxtDetails.fqdn).Split(".")[0]}) { + Remove-vRACloudAccount -id (Get-vRACloudAccount -type nsx-t | Where-object {$_.name -eq ($vcfNsxtDetails.fqdn).Split(".")[0]}).id | Out-Null + if (!(Get-vRACloudAccount -type nsx-t | Where-object {$_.name -eq ($vcfNsxtDetails.fqdn).Split(".")[0]})) { + Write-Output "Removing NSX-T Cloud Account in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)) named ($(($vcfNsxtDetails.fqdn).Split(".")[0])): SUCCESSFUL" + } + else { + Write-Error "Removing NSX-T Cloud Account in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)) named ($(($vcfNsxtDetails.fqdn).Split(".")[0])): POST_VALIDATED_FAILED" + } + } + else { + Write-Warning "Removing NSX-T Cloud Account in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)) named ($(($vcfNsxtDetails.fqdn).Split(".")[0])), does not exist: SKIPPED" + } + if (Get-vRACloudAccount -type vsphere | Where-object {$_.name -eq $($vcfVcenterDetails.vmName)}) { + Remove-vRACloudAccount -id (Get-vRACloudAccount -type vsphere | Where-object {$_.name -eq $($vcfVcenterDetails.vmName)}).id | Out-Null + if (!(Get-vRACloudAccount -type vsphere | Where-object {$_.name -eq $($vcfVcenterDetails.vmName)})) { + Write-Output "Removing vSphere Cloud Account in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)) named ($($vcfVcenterDetails.fqdn)): SUCCESSFUL" + } + else { + Write-Error "Removing vSphere Cloud Account in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)) named ($($vcfVcenterDetails.fqdn)): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Removing vSphere Cloud Account in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)) named ($($vcfVcenterDetails.fqdn)), does not exist: SKIPPED" + } + } + else { + Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" + } + } + } } } - else { - Write-Warning "Adding Password to the vRealize Suite Lifecycle Manager ($($vrslcm.fqdn)) Locker with alias ($alias), already exists: SKIPPED" - } - } - else { - Write-Error "Unable to obtain access token from vRealize Suite Lifecycle Manager ($server), check credentials" } } Catch { - Write-Error $_.Exception.Message + Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function New-vRSLCMLockerPassword +Export-ModuleMember -Function Undo-vRACloudAccount -Function Undo-vRSLCMLockerPassword { +Function Update-vRACloudAccountZone { <# .SYNOPSIS - Remove a password from the vRealize Suite Lifecycle Manager Locker + Update Cloud Zone Configuration .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 - - Verifies that the password is present in the vRealize Suite Lifecycle Manager Locker - - Removes the password from the vRealize Suite Lifecycle Manager Locker + 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 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 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 + - Adds the folder to the Cloud Account Zone as a target + - Adds a dynamic filter to use the defined tags .EXAMPLE - Undo-vRSLCMLockerPassword -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -alias xint-vrops01-admin - This example removes a password with an alias of 'xint-vrops01-admin' from the vRealize Suite Lifecycle Manager Locker + Update-vRACloudAccountZone -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -vraUser configadmin -vraPass VMw@re1! -tagKey enabled -tagValue true -folder "sfo-w01-fd-workload" -resourcePool "sfo-w01-cl01-rp-workload" + This example updates the Cloud Zone for the Workload Domain with a default folder and adds tags to the resource pool for dynamic provisioning in vRealize Automation #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$alias + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraUser, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraPass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tagKey, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tagValue, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$folder, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$resourcePool ) Try { - $vrslcm = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass - Request-vRSLCMToken -fqdn $vrslcm.fqdn -username $vrslcm.adminUser -password $vrslcm.adminPass | Out-Null - if (($vrslcmHealth = Get-vRSLCMHealth).'vrlcm-server' -eq "UP") { - if (Get-vRSLCMLockerPassword | Where-Object {$_.alias -eq $alias}) { - Remove-vRSLCMLockerPassword -vmid (Get-vRSLCMLockerPassword | Where-Object {$_.alias -eq $alias}).vmid | Out-Null - if ((Get-vRSLCMLockerPassword | Where-Object {$_.alias -eq $alias})) { - Write-Error "Removing Password from the vRealize Suite Lifecycle Manager ($($vrslcm.fqdn)) Locker with alias ($alias): FAILED" - } - else { - Write-Output "Removing Password from the vRealize Suite Lifecycle Manager ($($vrslcm.fqdn)) Locker with alias ($alias): SUCCESSFUL" + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVraDetails = Get-vRAServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-vRAConnection -server $vcfVraDetails.loadBalancerFqdn) { + if (Test-vRAAuthentication -server $vcfVraDetails.loadBalancerFqdn -user $vraUser -pass $vraPass) { + $vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain + if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) { + if (Get-vRACloudAccount -type vsphere | Where-object {$_.name -eq $($vcfVcenterDetails.vmName)}) { + $cluster = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }).clusters.id) }).Name + if (Get-vRAResourceCompute | Where-Object {$_.name -eq ($cluster + " / " + $resourcePool)}) { + $cloudZoneDetails = Get-vRACloudZone | Where-Object {$_.cloudAccountId -eq (Get-vRACloudAccount -type vsphere | Where-object {$_.name -eq $($vcfVcenterDetails.vmName)}).id } + Add-vRAResourceComputeTag -id (Get-vRAResourceCompute | Where-Object {$_.name -eq ($cluster + " / " + $resourcePool)}).id -tagKey $tagKey -tagValue $tagValue | Out-Null + Update-VRACloudZone -id $cloudZoneDetails.id -folder $folder | Out-Null + Update-VRACloudZone -id $cloudZoneDetails.id -tagKey $tagKey -tagValue $tagValue | Out-Null + Write-Output "Updating Cloud Zone Configuration in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)) named ($($cluster + " / " + $resourcePool)): SUCCESSFUL" + } + else { + Write-Error "Unable to find Resource Pool in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn) named ($resourcePool) : PRE_VALIDATION_FAILED" + } + } + else { + Write-Error "Unable to find vSphere Cloud Account in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn) named ($($vcfVcenterDetails.vmName)) : 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-Warning "Removing Password from the vRealize Suite Lifecycle Manager ($($vrslcm.fqdn)) Locker with alias ($alias), does not exist: SKIPPED" - } - } - else { - Write-Error "Unable to obtain access token from vRealize Suite Lifecycle Manager ($server), check credentials" } } Catch { - Write-Error $_.Exception.Message + Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Undo-vRSLCMLockerPassword +Export-ModuleMember -Function Update-vRACloudAccountZone -Function New-vRSLCMLockerLicense { +Function Add-vROvCenterServer { <# .SYNOPSIS - Add a license to the vRealize Suite Lifecycle Manager Locker + Adds a vCenter Server instance to an embedded vRealize Orchestrator. .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 - - Verifies that the license is not present in the vRealize Suite Lifecycle Manager Locker - - Adds the license to the vRealize Suite Lifecycle Manager Locker + The Add-vROvCenterServer cmdlet invokes the workflow in vRealize Orchestrator to add a vCenter Server. + The cmdlet connects to SDDC Manager using the -server, -user, -password, and -domain values + to return the workload domain vCenter Server details from its inventory and then: + - Makes a connection to the embedded vRealize Orchestrator using the -vraUser and -vraPass values. + - Verifies the workflow exists. + - Verifies that the vCenter Server instance exists in the vRealize Orchestrator catalog. + - Adds the vCenter Server instance using the -vcUser and -vcPass values. .EXAMPLE - New-vRSLCMLockerLicense -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -alias "vRealize Automation" -license "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX" - This example adds a license with an alias of 'vRealize Automation' to the vRealize Suite Lifecycle Manager Locker + Add-vROvCenterServer -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -vraUser configadmin -vraPass VMw@re1! -vcUser administrator@vsphere.local -vcPass VMw@re1! + This example adds the vCenter Server instance from the "sfo-w01" workload domain from the embedded vRealize Orchestrator catalog. #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$alias, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$license + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraUser, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraPass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vcUser, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vcPass ) + $workflowName = "Add a vCenter Server instance" + Try { - $vrslcm = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass - Request-vRSLCMToken -fqdn $vrslcm.fqdn -username $vrslcm.adminUser -password $vrslcm.adminPass | Out-Null - if (($vrslcmHealth = Get-vRSLCMHealth).'vrlcm-server' -eq "UP") { - if (!(Get-vRSLCMLockerLicense | Where-Object {$_.key -eq $license})) { - if (!(Get-vRSLCMLockerLicense | Where-Object {$_.alias -eq $alias})) { - $lockerLicense = Add-vRSLCMLockerLicense -alias $alias -license $license - Start-Sleep 2 - if ((Get-vRSLCMLockerLicense | Where-Object {$_.key -eq $license})) { - Write-Output "Adding License to the vRealize Suite Lifecycle Manager ($($vrslcm.fqdn)) Locker with alias ($alias): SUCCESSFUL" - } - else { - Write-Error "Adding License to the vRealize Suite Lifecycle Manager ($($vrslcm.fqdn)) Locker with alias ($alias): FAILED" - } + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVraDetails = Get-vRAServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-vRAConnection -server $vcfVraDetails.loadBalancerFqdn) { + if (Test-vRAAuthentication -server $vcfVraDetails.loadBalancerFqdn -user $vraUser -pass $vraPass) { + if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) { + $vcenter = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain + $checkExists = (Invoke-RestMethod -Method 'GET' -URI "https://$($vcfVraDetails.loadBalancerFqdn)/vco/api/catalog/VC" -headers $vraHeaders) + if ((($checkExists.relations.link.attributes | Where-Object { $_.name -eq "id" }).value) -ne "$($vcenter.fqdn)") { + if ($workflow = Get-vROWorkflow -name $workflowName) { + $parameters = + @" +{"parameters": + [ + { + "value": { + "boolean": { + "value": true } - else { - Write-Warning "Adding License to the vRealize Suite Lifecycle Manager ($($vrslcm.fqdn)) Locker with alias ($alias), already exists: SKIPPED" + }, + "type": "boolean", + "name": "enabled", + "scope": "local" + }, + { + "value": { + "string": { + "value": "$($vcenter.fqdn)" } - } - else { - Write-Warning "Adding License to the vRealize Suite Lifecycle Manager ($($vrslcm.fqdn)) Locker with alias ($alias), already exists: SKIPPED" - } + }, + "type": "string", + "name": "host", + "scope": "local" + }, + { + "value": { + "number": { + "value": 443 + } + }, + "type": "number", + "name": "port", + "scope": "local" + }, + { + "value": { + "string": { + "value": "/sdk" + } + }, + "type": "string", + "name": "path", + "scope": "local" + }, + { + "value": { + "boolean": { + "value": false + } + }, + "type": "boolean", + "name": "sessionPerUser", + "scope": "local" + }, + { + "value": { + "string": { + "value": "$vcUser" + } + }, + "type": "string", + "name": "userName", + "scope": "local" + }, + { + "value": { + "string": { + "value": "$vcPass" + } + }, + "type": "string", + "name": "password", + "scope": "local" + }, + { + "value": { + "boolean": { + "value": true + } + }, + "type": "boolean", + "name": "ignoreCertificateWarnings", + "scope": "local" + }, + { + "value": { + "number": { + "value": 443 + } + }, + "type": "number", + "name": "httpPort", + "scope": "local" + }, + { + "value": { + "string": { + "value": "https://$($vcenter.fqdn):443/pbm" + } + }, + "type": "string", + "name": "pbmUrl", + "scope": "local" + }, + { + "value": { + "string": { + "value": "https://$($vcenter.fqdn):443/sms/sdk" + } + }, + "type": "string", + "name": "smsUrl", + "scope": "local" } - else { - Write-Error "Unable to obtain access token from vRealize Suite Lifecycle Manager ($server), check credentials" + ] +} +"@ + $response = Invoke-vROWorkflow -id $($workflow.ID) -parameters ($parameters | ConvertFrom-Json).parameters + if (Get-vROWorkflowExecutionState -executionStateRef $response.Execution | Where-Object {$_.Execution -ne "failed"}) { + Do { + $workflowStatus = (Get-vROWorkflowExecutionState -executionStateRef $response.Execution).Execution + } + Until ($workflowStatus -ne "running") + if (Get-vROWorkflowExecutionState -executionStateRef $response.Execution | Where-Object {$_.Execution -eq "completed"}) { + Write-Output "Adding vCenter Server ($($vcenter.fqdn)) to embedded vRealize Orchestrator ($($vcfVraDetails.loadBalancerFqdn)) for Workload Domain ($domain): SUCCESSFUL" + } + else { + Write-Error "Adding vCenter Server ($($vcenter.fqdn)) to embedded vRealize Orchestrator ($($vcfVraDetails.loadBalancerFqdn)) for Workload Domain ($domain), check credentials: POST_VALIDATION_FAILED" + } + } + else { + Write-Error "Adding vCenter Server ($($vcenter.fqdn)) to embedded vRealize Orchestrator ($($vcfVraDetails.loadBalancerFqdn)) for Workload Domain ($domain): FAILED" + } + } + else { + Write-Error "Unable to find the workflow named ($workflowName) to embedded vRealize Orcherator ($($vcfVraDetails.loadBalancerFqdn)): PRE_VALIDATION_FAILED" + } + } + else { + Write-Warning "Adding vCenter Server ($($vcenter.fqdn)) to embedded vRealize Orchestrator ($($vcfVraDetails.loadBalancerFqdn)) 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 { - Write-Error $_.Exception.Message + Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function New-vRSLCMLockerLicense +Export-ModuleMember -Function Add-vROvCenterServer -Function Undo-vRSLCMLockerLicense { +Function Remove-vROvCenterServer { <# .SYNOPSIS - Remove a license to the vRealize Suite Lifecycle Manager Locker + Removes a vCenter Server instance from an embedded vRealize Orchestrator. .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 - - Verifies that the license is present in the vRealize Suite Lifecycle Manager Locker - - Removes the license to the vRealize Suite Lifecycle Manager Locker + The Remove-vROvCenterServer cmdlet invokes the workflow in vRealize Orchestrator to remove a vCenter Server. + The cmdlet connects to SDDC Manager using the -server, -user, -password, and -domain values + to return the workload domain vCenter Server details from its inventory and then: + - Makes a connection to the embedded vRealize Orchestrator using the -vraUser and -vraPass values. + - Verifies the workflow exists. + - Verifies that the vCenter Server instance exists in the vRealize Orchestrator catalog. + - Removes the vCenter Server instance. .EXAMPLE - Undo-vRSLCMLockerLicense -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -alias "vRealize Automation" - This example removes a license with an alias of 'vRealize Automation' from the vRealize Suite Lifecycle Manager Locker + Remove-vROvCenterServer -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -vraUser configadmin -vraPass VMw@re1! + This example removes the vCenter Server instance from the "sfo-w01" workload domain from the embedded vRealize Orchestrator catalog. #> Param ( [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$alias + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraUser, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraPass ) + $workflowName = "Remove a vCenter Server instance" + Try { - $vrslcm = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass - Request-vRSLCMToken -fqdn $vrslcm.fqdn -username $vrslcm.adminUser -password $vrslcm.adminPass | Out-Null - if (($vrslcmHealth = Get-vRSLCMHealth).'vrlcm-server' -eq "UP") { - if (Get-vRSLCMLockerLicense | Where-Object {$_.alias -eq $alias}) { - Remove-vRSLCMLockerLicense -vmid (Get-vRSLCMLockerLicense | Where-Object {$_.alias -eq $alias}).vmid | Out-Null - if (Get-vRSLCMLockerLicense | Where-Object {$_.key -eq $license}) { - Write-Error "Removing License from the vRealize Suite Lifecycle Manager ($($vrslcm.fqdn)) Locker with alias ($alias): FAILED" + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVraDetails = Get-vRAServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-vRAConnection -server $vcfVraDetails.loadBalancerFqdn) { + if (Test-vRAAuthentication -server $vcfVraDetails.loadBalancerFqdn -user $vraUser -pass $vraPass) { + if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) { + $vcenter = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain + $checkExists = (Invoke-RestMethod -Method 'GET' -URI "https://$($vcfVraDetails.loadBalancerFqdn)/vco/api/catalog/VC" -headers $vraHeaders) + if ((($checkExists.relations.link.attributes | Where-Object { $_.name -eq "id" }).value) -eq "$($vcenter.fqdn)") { + if ($workflow = Get-vROWorkflow -name $workflowName) { + $parameters = + @" +{"parameters": + [ + { + "value": { + "string": { + "value": "https://$($vcenter.fqdn):443/sdk" } - else { - Write-Output "Removing License from the vRealize Suite Lifecycle Manager ($($vrslcm.fqdn)) Locker with alias ($alias): SUCCESSFUL" + }, + "type": "string", + "name": "host", + "scope": "local" + } + ] +} +"@ + $response = Invoke-vROWorkflow -id $($workflow.ID) -parameters ($parameters | ConvertFrom-Json).parameters + if (Get-vROWorkflowExecutionState -executionStateRef $response.Execution | Where-Object {$_.Execution -ne "failed"}) { + Do { + $workflowStatus = (Get-vROWorkflowExecutionState -executionStateRef $response.Execution).Execution + } + Until ($workflowStatus -ne "running") + if (Get-vROWorkflowExecutionState -executionStateRef $response.Execution | Where-Object {$_.Execution -eq "completed"}) { + Write-Output "Removing vCenter Server ($($vcenter.fqdn)) from embedded vRealize Orchestrator ($($vcfVraDetails.loadBalancerFqdn)) for Workload Domain ($domain): SUCCESSFUL" + } + else { + Write-Error "Removing vCenter Server ($($vcenter.fqdn)) from embedded vRealize Orchestrator ($($vcfVraDetails.loadBalancerFqdn)) for Workload Domain ($domain): POST_VALIDATION_FAILED" + } + } + else { + Write-Error "Removing vCenter Server ($($vcenter.fqdn)) from embedded vRealize Orchestrator ($($vcfVraDetails.loadBalancerFqdn)) for Workload Domain ($domain): FAILED" + } + } + else { + Write-Error "Unable to find the workflow named ($workflowName) in embedded vRealize Orcherator ($($vcfVraDetails.loadBalancerFqdn)): PRE_VALIDATION_FAILED" + } + } + else { + Write-Warning "Removing vCenter Server ($($vcenter.fqdn)) from embedded vRealize Orchestrator ($($vcfVraDetails.loadBalancerFqdn)) for Workload Domain ($domain), does not exist: SKIPPED" + } + } + else { + Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" + } + } + } } } - else { - Write-Warning "Removing License from the vRealize Suite Lifecycle Manager ($($vrslcm.fqdn)) Locker with alias ($alias), does not exist: SKIPPED" - } - } - else { - Write-Error "Unable to obtain access token from vRealize Suite Lifecycle Manager ($server), check credentials" } } Catch { - Write-Error $_.Exception.Message + Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Undo-vRSLCMLockerLicense +Export-ModuleMember -Function Remove-vROvCenterServer -Function Add-VmGroup { +Function Add-vROTrustedCertificate { <# - .SYNOPSIS - Add a VM Group + .SYNOPSIS + Adds a trusted certificate to an embedded vRealize Orchestrator. - .DESCRIPTION - The Add-VmGroup cmdlet adds a Virtual Machine to an existing VM Group. + .DESCRIPTION + The Add-vROTrustedCertificate cmdlet invokes a workflow in vRealize Orchestrator to add trusted certificate. The cmdlet connects to SDDC Manager using the -server, -user, and -password values and then: - - Verifies a connection has been made to the vCenter Server - - Verifies 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 + - Makes a connection to the embedded vRealize Orchestrator using the -vraUser and -vraPass values. + - Verifies the workflow exists. + - Adds the trusted certificate using the -certFile value. .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" - This example adds the vRealize Automation cluster VMs to the VM Group called primary_az_vmgroup - #> + Add-vROTrustedCertificate -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -vraUser configadmin -vraPass VMw@re1! -certFile "C:\Root64.pem" + This example adds a trusted certificate in PEM-encoded format to the embedded vRealize Orchestrator. + #> 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]$name, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vmList + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraUser, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraPass, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$certFile ) + $workflowName = "Import a trusted certificate from a file" + + if (!$PsBoundParameters.ContainsKey("certFile")) { + $certFile = Get-ExternalFileName -title "Select the trusted certificate file (.cer)" -fileType "cer" -location "default" + } + elseif ($PsBoundParameters.ContainsKey("certFile")) { + if (!(Test-Path -Path $certFile)) { + Write-Error "Selecting the trusted certificate file ($certFile), file not found: PRE_VALIDATION_FAILED" + Break + } + } + Try { - Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null - if ($accessToken) { - $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 - 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: FAILED" + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVraDetails = Get-vRAServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-vRAConnection -server $vcfVraDetails.loadBalancerFqdn) { + if (Test-vRAAuthentication -server $vcfVraDetails.loadBalancerFqdn -user $vraUser -pass $vraPass) { + if ($workflow = Get-vROWorkflow -name $workflowName) { + $certName = Split-Path -Path "$certFile" -Leaf + $certContent = [Convert]::ToBase64String([IO.File]::ReadAllBytes("$certFile")) + $parameters = + @" +{"parameters": + [ + {"value": { + "mime-attachment": { + "name":"$certName", + "content": "$certContent", + "mime-type": "application/x-x509-ca-cert"} + }, + "type": "MimeAttachment", + "name": "cer", + "scope": "local" + } + ] +} +"@ + $response = Invoke-vROWorkflow -id $($workflow.ID) -parameters ($parameters | ConvertFrom-Json).parameters + if (Get-vROWorkflowExecutionState -executionStateRef $response.Execution | Where-Object { $_.Execution -ne "failed" }) { + Do { + $workflowStatus = (Get-vROWorkflowExecutionState -executionStateRef $response.Execution).Execution + } + Until ($workflowStatus -ne "running") + if (Get-vROWorkflowExecutionState -executionStateRef $response.Execution | Where-Object { $_.Execution -eq "completed" }) { + Write-Output "Adding trusted certificate ($certFile) to the embedded vRealize Orchestrator ($($vcfVraDetails.loadBalancerFqdn)): SUCCESSFUL" + } + else { + Write-Error "Adding trusted certificate ($certFile) to the embedded vRealize Orchestrator ($($vcfVraDetails.loadBalancerFqdn)), check certificate format: POST_VALIDATION_FAILED" + } + } + else { + Write-Error "Adding trusted certificate ($certFile) to the embedded vRealize Orchestrator ($($vcfVraDetails.loadBalancerFqdn)): FAILED" + } + } + } + } } } - else { - Write-Error "Unable to connect to vCenter Server ($($vcenter.fqdn))" - } - } - else { - Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials" } } Catch { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-VmGroup +Export-ModuleMember -Function Add-vROTrustedCertificate -Function Add-WorkspaceOneDirectoryGroup { +Function Add-vRANotification { <# - .SYNOPSIS - Adds Active Directory Group to sync in Workspace ONE Access Appliance + .SYNOPSIS + Adds notification settings in vRealize Automation. - .DESCRIPTION - The Add-WorkspaceOneDirectoryGroup cmdlet adds an Active Directory Group to sync in Workspace ONE Access Appliance + .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 vRealize Automation has been deployed in VMware Cloud Foundation aware mode and retrives its details + - Makes a connection to the vRealize Automation Cluster + - Adds notifications settings to vRealize Automation - .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 + Add-vRANotification -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -vraUser configadmin -vraPass VMw@re1! -smtpServer smtp.raipole.io -emailAddress vra-no-reply@rainpole.io -sender "Rainpole Cloud" -connection NONE + This example adds notifications settings for vRealize Automation. + #> - Param ( + 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 + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraUser, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraPass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$smtpServer, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$emailAddress, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sender, + [Parameter (Mandatory = $true)] [ValidateSet("SSL","STARTTLS","NONE")] [ValidateNotNullOrEmpty()] [String]$connection ) Try { - Request-WSAToken -fqdn $server -user $user -pass $pass | Out-Null - if ($sessionToken) { - $checkAdAuthentication = Test-ADAuthentication -user $bindUser -pass $bindPass -server $domain -domain $domain - if ($checkAdAuthentication -contains "2") { - $checkDirectoryExist = Get-WSADirectory | Where-Object { ($_.name -eq $domain) } - if ($checkDirectoryExist) { - - $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 + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVraDetails = Get-vRAServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-vRAConnection -server $vcfVraDetails.loadBalancerFqdn) { + if (Test-vRAAuthentication -server $vcfVraDetails.loadBalancerFqdn -user $vraUser -pass $vraPass) { + New-vRANotification -name $smtpServer -serverName $smtpServer -emailAddress $emailAddress -sender $sender -trustCert true -connection $connection -authentication false | Out-Null + if (Get-vRANotification | Where-Object {$_.name -eq $smtpServer}) { + Write-Output "Configuring Notification settings in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)) named ($smtpServer): SUCCESSFUL" + } + else { + Write-Output "Configuring Notification settings in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)) named ($smtpServer): POST_VALIDATION_FAILED" } } - else { - Write-Error "Group $group is not available in Active Directory Domain" - } - } - $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 $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" } - else { - Write-Warning "Active Directory Directory Domain ($domain) does not exist, check details and try again" - } - } - else { - Write-Error "Domain User ($bindUser) Authentication Failed" } } - else { - Write-Error "Unable to obtain access token from Workspace ONE Access Instance ($wsaFqdn), check credentials" - } } Catch { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-WorkspaceOneDirectoryGroup - -########################################## E N D O F F U N C T I O N S ########################################## -####################################################################################################################### - - -####################################################################################################################### -##################################### S U P P O R T I N G F U N C T I O N S ###################################### - -############################################################## -############# Begin Active Directory Functions ############# +Export-ModuleMember -Function Add-vRANotification -Function Test-ADAuthentication { +Function Add-vRAUser { <# .SYNOPSIS - Test authetication against Active Directory + Adds user access in an organization. .DESCRIPTION - The Test-ADAuthentication cmdlet tests the credentials provided against Active Directory domain + 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 vRealize Automation has been deployed in VMware Cloud Foundation aware mode and retrives its details + - Makes a connection to the vRealize Automation Cluster + - Adds the user to both an organization role and a service role .EXAMPLE - Test-ADAuthentication -user svc-vsphere-ad -pass VMw@re1! -server sfo.rainpole.io -domain sfo.rainpole.io - This example check that the svc-vsphere-ad user can authenticate to the sfo.rainpole.io domain + Add-vRAUser -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -vraUser configadmin -vraPass VMw@re1! -email jdoe@rainpole.io -orgRole org_member -serviceRole automationservice:cloud_admin + This example adds user access in vRealize Automation by userId and orgId along with the required orgRole and serviceRole. + + Note: This cmdlet currently only supports a single serviceRole. #> Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, - [Parameter (Mandatory = $false)] [String]$server, - [Parameter (Mandatory = $false)] [String]$domain = $env:USERDOMAIN + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraUser, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraPass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$email, + [Parameter (Mandatory = $true)] [ValidateSet("org_owner","org_member")] [ValidateNotNullOrEmpty()] [String]$orgRole, + [Parameter (Mandatory = $true)] [ValidateSet('automationservice:cloud_admin', 'automationservice:user', 'automationservice:viewer', 'catalog:admin', 'catalog:user', 'catalog:viewer', 'CodeStream:administrator', 'CodeStream:developer', 'CodeStream:executor', 'CodeStream:user', 'CodeStream:viewer', 'migration:admin', 'migration:viewer', 'orchestration:admin', 'orchestration:designer', 'orchestration:viewer', 'saltstack:admin')] [ValidateNotNullOrEmpty()] [String]$serviceRole ) Try { - Add-Type -AssemblyName System.DirectoryServices.AccountManagement - $contextType = [System.DirectoryServices.AccountManagement.ContextType]::Domain - $argumentList = New-Object -TypeName "System.Collections.ArrayList" - $null = $argumentList.Add($contextType) - $null = $argumentList.Add($domain) - if ($null -ne $server) { - $argumentList.Add($server) - } - $principalContext = New-Object System.DirectoryServices.AccountManagement.PrincipalContext -ArgumentList $argumentList -ErrorAction SilentlyContinue - if ($null -eq $principalContext) { - Write-Error "$domain\$user - AD Authentication Failed" - } - if ($principalContext.ValidateCredentials($user, $pass)) { - Write-Output "$domain\$user - AD Authentication Successful" - } - else { - Write-Error "$domain\$user - AD Authentication Failed" + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVraDetails = Get-vRAServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-vRAConnection -server $vcfVraDetails.loadBalancerFqdn) { + if (Test-vRAAuthentication -server $vcfVraDetails.loadBalancerFqdn -user $vraUser -pass $vraPass) { + $orgId = (Get-vRAOrganizationId).Split("orgs/")[-1] + if (Get-vRAUser -orgId $orgId -email $email | Where-Object { $_.user.email -eq $email }) { + $userId = (Get-vRAUser -orgId $orgId -email $email).user.userId + $services = (Get-vRAServices -orgId $orgId) + $serviceDefinitionId = (($services.serviceRoles | Where-Object {$_.name -eq $serviceRole -and $_.displayName -ne $serviceRole}).serviceDefinitionLink -Split("external/"))[-1] + if (!(Get-vRAUserRoles -userId $userId -orgId $orgId | Where-Object { $_.organizationRoles.name -eq $orgRole -and $_.serviceRoles.serviceRoles.name -eq $serviceRole -and $_.serviceRoles.serviceDefinitionId -eq $serviceDefinitionId})) { + New-vRAUser -userId $userId -orgId $orgId -orgRole $orgRole -serviceRole $serviceRole -serviceDefinitionId $serviceDefinitionId | Out-Null + if (Get-vRAUserRoles -userId $userId -orgId $orgId | Where-Object { $_.organizationRoles.name -eq $orgRole -and $_.serviceRoles.serviceRoles.name -eq $serviceRole -and $_.serviceRoles.serviceDefinitionId -eq $serviceDefinitionId}) { + Write-Output "Assigning user email ($email) the organization role ($orgRole) and service role ($serviceRole) in vRealize Automation: SUCCESSFUL" + } + else { + Write-Error "Assigning user email ($email) the organization role ($orgRole) and service role ($serviceRole) in vRealize Automation: POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Assigning user email ($email) the organization role ($orgRole) and service role ($serviceRole) in vRealize Automation, already exists: SKIPPED" + } + } + else { + Write-Error "Unable to find user email ($email) in Workspace ONE Access for vRealize Automation, check user synchronization or email: PRE_VALIDATION_FAILED" + } + } + } + } + } } } Catch { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Test-ADAuthentication +Export-ModuleMember -Function Add-vRAUser -Function Get-ADPrincipalGuid { +Function Undo-vRAUser { <# .SYNOPSIS - Get principal GUID details + Removes user access from an organization. .DESCRIPTION - The Get-ADPrincipalGuid cmdlet retrieves the GUID details for an active directory user or group Active Directory domain + 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 vRealize Automation has been deployed in VMware Cloud Foundation aware mode and retrives its details + - Makes a connection to the vRealize Automation Cluster + - Removes the user from an organization role and all service roles .EXAMPLE - Get-ADPrincipalGuid -domain sfo.rainple.io -user svc-vsphere-ad -pass VMw@re1! -principal gg-sso-admin - This example retrives the details for th gg-sso-admin domain + Undo-vRAUser -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -vraUser configadmin -vraPass VMw@re1! -email jdoe@rainpole.io + This example removes user access from vRealize Automation by email. #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$principal + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraUser, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraPass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$email ) Try { - $checkAdAuthentication = Test-ADAuthentication -user $user -pass $pass -server $domain -domain $domain - if ($checkAdAuthentication -contains "2") { - $securePassword = ConvertTo-SecureString -String $pass -AsPlainText -Force - $creds = New-Object System.Management.Automation.PSCredential ($user, $securePassword) - $nsxAdminGroupObject = (Get-ADGroup -Server $domain -Credential $creds -Filter { SamAccountName -eq $principal }) - $nsxAdminGroupObject - } - else { - Write-Error "Domain User $user Authentication Failed" - } - } - Catch { - Debug-ExceptionWriter -object $_ - } -} -Export-ModuleMember -Function Get-ADPrincipalGuid + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVraDetails = Get-vRAServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-vRAConnection -server $vcfVraDetails.loadBalancerFqdn) { + if (Test-vRAAuthentication -server $vcfVraDetails.loadBalancerFqdn -user $vraUser -pass $vraPass) { + $orgId = (Get-vRAOrganizationId).Split("orgs/")[-1] + if (Get-vRAUser -orgId $orgId -email $email | Where-Object { $_.user.email -eq $email -and $_.organizationRoles.name -ne $null -and $_.serviceRoles.serviceDefinitionId -ne $null}) { + + if ($objectCheck = Get-vRAUser -orgId $orgId -email $email | Where-Object { $_.user.email -eq $email }) { + if ($orgRole = ($objectCheck.organizationRoles.name)) { + Remove-vRAUserOrgRole -userId $userId -orgId $orgId -orgRole $orgRole + } -############## End Active Directory Functions ############## -############################################################## + if ($serviceRoles = ($objectCheck.serviceRoles.serviceRoles.name)) { + $services = (Get-vRAServices -orgId $orgId) + Foreach ($serviceRole in $serviceRoles) { + $serviceDefinitionId = (($services.serviceRoles | Where-Object {$_.name -eq $serviceRole -and $_.displayName -ne $serviceRole}).serviceDefinitionLink -Split("external/"))[-1] + Remove-vRAUserServiceRole -userId $userId -orgId $orgId -serviceDefinitionId $serviceDefinitionId -serviceRole $serviceRole + } + } + if ($orgRole -eq $null) { + $orgRole = "none" + } -############################################################## -############# Begin Cloud Foundation Functions ############# + if ($serviceRoles -eq $null) { + $serviceRole = "none" + } + else { + $serviceRole = $serviceRoles -join ', ' + } -Function Get-vCenterServerDetail { - Param ( - [Parameter (Mandatory = $false)] [String]$server, - [Parameter (Mandatory = $false)] [String]$user, - [Parameter (Mandatory = $false)] [String]$pass, - [Parameter (Mandatory = $false)] [ValidateSet("MANAGEMENT", "VI")][String]$domainType, - [Parameter (Mandatory = $false)] [String]$domain - ) + if (Get-vRAUser -orgId $orgId -email $email | Where-Object { $_.organizationRoles.name -eq $null -and $_.serviceRoles.serviceRoles.name -eq $null -and $_.serviceRoles.serviceDefinitionId -eq $null}) { + Write-Output "Removing user email ($email) from organization role ($orgRole) and service roles(s) ($serviceRole) in vRealize Automation: SUCCESSFUL" + } + else { + Write-Warning "Removing user email ($email) from organization role ($orgRole) and service roles(s) ($serviceRole) in vRealize Automation: POST_VALIDATION_FAILED" + } + } + else { + Write-Error "Unable to find user email ($email) in Workspace ONE Access for vRealize Automation, check email variable: PRE_VALIDATION_FAILED" + } + } + elseif (Get-vRAUser -orgId $orgId -email $email | Where-Object { $_.user.email -eq $email -and $_.organizationRoles.name -ne $null -or $_.serviceRoles.serviceDefinitionId -ne $null}) { + if ($objectCheck = Get-vRAUser -orgId $orgId -email $email | Where-Object { $_.user.email -eq $email }) { + if ($orgRole = ($objectCheck.organizationRoles.name)) { + Remove-vRAUserOrgRole -userId $userId -orgId $orgId -orgRole $orgRole + } - Try { - if (!$PsBoundParameters.ContainsKey("user") -or (!$PsBoundParameters.ContainsKey("pass"))) { - # Request Credentials - $creds = Get-Credential - $user = $creds.UserName.ToString() - $pass = $creds.GetNetworkCredential().password - } - if (!$PsBoundParameters.ContainsKey("server")) { - $server = Read-Host "SDDC Manager access token not found. Please enter the SDDC Manager FQDN, e.g., sfo-vcf01.sfo.rainpole.io" - } - Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null + if ($serviceRoles = ($objectCheck.serviceRoles.serviceRoles.name)) { + $services = (Get-vRAServices -orgId $orgId) + Foreach ($serviceRole in $serviceRoles) { + $serviceDefinitionId = (($services.serviceRoles | Where-Object {$_.name -eq $serviceRole -and $_.displayName -ne $serviceRole}).serviceDefinitionLink -Split("external/"))[-1] + Remove-vRAUserServiceRole -userId $userId -orgId $orgId -serviceDefinitionId $serviceDefinitionId -serviceRole $serviceRole + } + } - if ($accessToken) { - if ($PsBoundParameters.ContainsKey("domainType")) { - # Dynamically build vCenter Server details based on Cloud Foundation domain type - $vcfWorkloadDomainDetails = Get-VCFWorkloadDomain | Where-Object { $_.type -eq $domainType } - } - if ($PsBoundParameters.ContainsKey("domain")) { - # Dynamically build vCenter Server details based on Cloud Foundation domain name - $vcfWorkloadDomainDetails = Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain } - } - if ($vcfWorkloadDomainDetails) { - $vcenterServerDetails = Get-VCFvCenter | Where-Object { $_.id -eq $($vcfWorkloadDomainDetails.vcenters.id) } - $vcenterCredentialDetails = Get-VCFCredential | Where-Object { $_.resource.resourceId -eq $($vcenterServerDetails.id) } - $pscCredentialDetails = Get-VCFCredential | Where-Object { $_.resource.resourceType -eq "PSC" } - $vcenterServer = New-Object -TypeName psobject - $vcenterServer | Add-Member -notepropertyname 'fqdn' -notepropertyvalue $vcenterServerDetails.fqdn - $vcenterServer | Add-Member -notepropertyname 'vmName' -notepropertyvalue $vcenterServerDetails.fqdn.Split(".")[0] - $vcfDetail = Get-VCFManager - if ( ($vcfDetail.version).Split("-")[0] -gt "4.1.0.0") { - $vcenterServer | Add-Member -notepropertyname 'ssoAdmin' -notepropertyvalue ($pscCredentialDetails | Where-Object { ($_.credentialType -eq "SSO" -and $_.accountType -eq "SYSTEM") }).username - $vcenterServer | Add-Member -notepropertyname 'ssoAdminPass' -notepropertyvalue ($pscCredentialDetails | Where-Object { ($_.credentialType -eq "SSO" -and $_.accountType -eq "SYSTEM") }).password - } - else { - $vcenterServer | Add-Member -notepropertyname 'ssoAdmin' -notepropertyvalue ($pscCredentialDetails | Where-Object { ($_.credentialType -eq "SSO" -and $_.accountType -eq "USER") }).username - $vcenterServer | Add-Member -notepropertyname 'ssoAdminPass' -notepropertyvalue ($pscCredentialDetails | Where-Object { ($_.credentialType -eq "SSO" -and $_.accountType -eq "USER") }).password + if ($orgRole -eq $null) { + $orgRole = "none" + } + + if ($serviceRoles -eq $null) { + $serviceRole = "none" + } + else { + $serviceRole = $serviceRoles -join ', ' + } + + if (Get-vRAUser -orgId $orgId -email $email | Where-Object { $_.organizationRoles.name -eq $null -and $_.serviceRoles.serviceRoles.name -eq $null -and $_.serviceRoles.serviceDefinitionId -eq $null}) { + Write-Output "Removing user email ($email) from organization role ($orgRole) and service roles(s) ($serviceRole) in vRealize Automation: SUCCESSFUL" + } + else { + Write-Warning "Removing user email ($email) from organization role ($orgRole) and service roles(s) ($serviceRole) in vRealize Automation: POST_VALIDATION_FAILED" + } + } + else { + Write-Error "Unable to find user email ($email) in Workspace ONE Access for vRealize Automation, check email variable: PRE_VALIDATION_FAILED" + } + } + else { + Write-Warning "Removing user email ($email) from organization role and service roles(s) in vRealize Automation, no roles assigned: PRE_VALIDATION_FAILED" + } + } + } } - $vcenterServer | Add-Member -notepropertyname 'root' -notepropertyvalue ($vcenterCredentialDetails | Where-Object { ($_.credentialType -eq "SSH" -and $_.accountType -eq "USER") }).username - $vcenterServer | Add-Member -notepropertyname 'rootPass' -notepropertyvalue ($vcenterCredentialDetails | Where-Object { ($_.credentialType -eq "SSH" -and $_.accountType -eq "USER") }).password - $vcenterServer - } - else { - Write-Error "Workload domainType or domain name does not exist" - Break } } - else { - Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials" - Break - } } Catch { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Get-vCenterServerDetail +Export-ModuleMember -Function Undo-vRAUser + +Function Add-vRAGroup { + <# + .SYNOPSIS + Adds a group in an organization. + + .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 vRealize Automation has been deployed in VMware Cloud Foundation aware mode and retrives its details + - Makes a connection to the vRealize Automation Cluster + - Adds the group to an organization role and a service role + + .EXAMPLE + Add-vRAGroup -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -vraUser configadmin -vraPass VMw@re1! -displayName gg-vra-org-owners@rainpole.io -orgRole org_owner + This example adds a group to vRealize Automation by groupId and orgId along with the required orgRole. + + .EXAMPLE + Add-vRAGroup -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -vraUser configadmin -vraPass VMw@re1! -displayName gg-vra-cloud-assembly-admins@rainpole.io -orgRole org_member -serviceRole automationservice:cloud_admin + This example adds a group to vRealize Automation by groupId and orgId along with the required orgRole and serviceRole. + + Note: This cmdlet currently only supports a single serviceRole. + #> -Function Get-NsxtServerDetail { Param ( - [Parameter (Mandatory = $false)] [String]$fqdn, - [Parameter (Mandatory = $false)] [String]$username, - [Parameter (Mandatory = $false)] [String]$password, - [Parameter (Mandatory = $false)] [String]$domain, - [Parameter( Mandatory = $false)] [ValidateSet("MANAGEMENT", "VI")] [String]$domainType, - [Parameter (Mandatory = $false)] [switch]$listNodes = $false + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraUser, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraPass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$displayName, + [Parameter (Mandatory = $true)] [ValidateSet("org_owner","org_member")] [ValidateNotNullOrEmpty()] [String]$orgRole, + [Parameter (Mandatory = $false)] [ValidateSet('automationservice:cloud_admin', 'automationservice:user', 'automationservice:viewer', 'catalog:admin', 'catalog:user', 'catalog:viewer', 'CodeStream:administrator', 'CodeStream:developer', 'CodeStream:executor', 'CodeStream:user', 'CodeStream:viewer', 'migration:admin', 'migration:viewer', 'orchestration:admin', 'orchestration:designer', 'orchestration:viewer', 'saltstack:admin')] [ValidateNotNullOrEmpty()] [String]$serviceRole ) Try { - if (!$PsBoundParameters.ContainsKey("username") -or (!$PsBoundParameters.ContainsKey("password"))) { - # Request Credentials - $creds = Get-Credential - $username = $creds.UserName.ToString() - $password = $creds.GetNetworkCredential().password - } - if (!$PsBoundParameters.ContainsKey("fqdn")) { - $fqdn = Read-Host "SDDC Manager access token not found. Please enter the SDDC Manager FQDN, e.g., sfo-vcf01.sfo.rainpole.io" - } - Request-VCFToken -fqdn $fqdn -Username $username -Password $password | Out-Null - - if ($accessToken) { - if ($PsBoundParameters.ContainsKey("domainType")) { - # Dynamically build vCenter Server details based on Cloud Foundation domain type - $vcfWorkloadDomainDetails = Get-VCFWorkloadDomain | Where-Object { $_.type -eq $domainType } - } - if ($PsBoundParameters.ContainsKey("domain")) { - # Dynamically build vCenter Server details based on Cloud Foundation domain name - $vcfWorkloadDomainDetails = Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain } - } - if ($vcfWorkloadDomainDetails) { - $nsxtServerDetails = Get-VCFNsxtcluster | Where-Object { $_.id -eq $($vcfWorkloadDomainDetails.nsxtCluster.id) } - $nsxtCreds = Get-VCFCredential | Where-Object { $_.resource.resourceId -eq $($nsxtServerDetails.id) } - - $nsxtCluster = New-Object -TypeName PSCustomObject - $nsxtCluster | Add-Member -notepropertyname 'fqdn' -notepropertyvalue $nsxtServerDetails.vipFqdn - $nsxtCluster | Add-Member -notepropertyname 'adminUser' -notepropertyvalue ($nsxtCreds | Where-Object { ($_.credentialType -eq "API" -and $_.accountType -eq "SYSTEM") }).username - $nsxtCluster | Add-Member -notepropertyname 'adminPass' -notepropertyvalue ($nsxtCreds | Where-Object { ($_.credentialType -eq "API" -and $_.accountType -eq "SYSTEM") }).password - $nsxtCluster | Add-Member -notepropertyname 'rootUser' -notepropertyvalue ($nsxtCreds | Where-Object { ($_.credentialType -eq "SSH" -and $_.accountType -eq "SYSTEM") }).username - $nsxtCluster | Add-Member -notepropertyname 'rootPass' -notepropertyvalue ($nsxtCreds | Where-Object { ($_.credentialType -eq "SSH" -and $_.accountType -eq "SYSTEM") }).password - if ($listNodes) { - $nsxtCluster | Add-Member -notepropertyname 'nodes' -notepropertyvalue $nsxtServerDetails.nodes - } - $nsxtCluster - } - else { - Write-Error "Workload domainType or domain name does not exist" - Break + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVraDetails = Get-vRAServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-vRAConnection -server $vcfVraDetails.loadBalancerFqdn) { + if (Test-vRAAuthentication -server $vcfVraDetails.loadBalancerFqdn -user $vraUser -pass $vraPass) { + $orgId = (Get-vRAOrganizationId).Split("orgs/")[-1] + if (Get-vRAGroup -orgId $orgId -displayName $displayName | Where-Object { $_.displayName -eq $displayName }) { + $groupId = (Get-vRAGroup -orgId $orgId -displayName $displayName).id + if ($PsBoundParameters.ContainsKey("orgRole") -and ($PsBoundParameters.ContainsKey("serviceRole"))) { + $services = (Get-vRAServices -orgId $orgId) + $serviceDefinitionId = (($services.serviceRoles | Where-Object {$_.name -eq $serviceRole -and $_.displayName -ne $serviceRole}).serviceDefinitionLink -Split("external/"))[-1] + if (!(Get-vRAGroupRoles -groupId $groupId -orgId $orgId | Where-Object { $_.organizationRoles.name -eq $orgRole -and $_.serviceRoles.serviceRoleNames -eq $serviceRole -and $_.serviceRoles.serviceDefinitionId -eq $serviceDefinitionId})) { + New-vRAGroup -groupId $groupId -orgId $orgId -orgRole $orgRole -serviceRole $serviceRole -serviceDefinitionId $serviceDefinitionId | Out-Null + if (Get-vRAGroupRoles -groupId $groupId -orgId $orgId | Where-Object { $_.organizationRoles.name -eq $orgRole -and $_.serviceRoles.serviceRoleNames -eq $serviceRole -and $_.serviceRoles.serviceDefinitionId -eq $serviceDefinitionId}) { + Write-Output "Assigning group ($displayName) the organization role ($orgRole) and service role ($serviceRole) in vRealize Automation: SUCCESSFUL" + } + else { + Write-Error "Assigning group ($displayName) the organization role ($orgRole) and service role ($serviceRole) in vRealize Automation: POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Assigning group ($displayName) the organization role ($orgRole) and service role ($serviceRole) in vRealize Automation, already exists: SKIPPED" + } + } + elseif (!$PsBoundParameters.ContainsKey("serviceRole")) { + if (!(Get-vRAGroupRoles -groupId $groupId -orgId $orgId | Where-Object { $_.organizationRoles.name -eq $orgRole -and $_.serviceRoles.serviceRoleNames -eq $null -and $_.serviceRoles.serviceDefinitionId -eq $null})) { + New-vRAGroup -groupId $groupId -orgId $orgId -orgRole $orgRole | Out-Null + if (Get-vRAGroupRoles -groupId $groupId -orgId $orgId | Where-Object { $_.organizationRoles.name -eq $orgRole -and $_.serviceRoles.serviceRoleNames -eq $null -and $_.serviceRoles.serviceDefinitionId -eq $null}) { + Write-Output "Assigning group ($displayName) the organization role ($orgRole) in vRealize Automation: SUCCESSFUL" + } + else { + Write-Error "Assigning group ($displayName) the organization role ($orgRole) in vRealize Automation: POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Assigning group ($displayName) the organization role ($orgRole) in vRealize Automation, already exists: SKIPPED" + } + } + } + else { + Write-Error "Unable to find group ($displayName) in Workspace ONE Access for vRealize Automation, check group synchronization or displayName: PRE_VALIDATION_FAILED" + } + } + } + } } } - else { - Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials" - Break - } } Catch { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Get-NsxtServerDetail +Export-ModuleMember -Function Add-vRAGroup + +Function Undo-vRAGroup { + <# + .SYNOPSIS + Removes a group in an organization. + + .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 vRealize Automation has been deployed in VMware Cloud Foundation aware mode and retrives its details + - Makes a connection to the vRealize Automation Cluster + - Removes the group from an organization role and all service roles + + .EXAMPLE + Undo-vRAGroup -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -vraUser configadmin -vraPass VMw@re1! -displayName gg-vra-cloud-assembly-admins@rainpole.io + This example removes a group from vRealize Automation by displayName. + #> -Function Get-vRSLCMServerDetail { Param ( - [Parameter (Mandatory = $false)] [String]$fqdn, - [Parameter (Mandatory = $false)] [String]$username, - [Parameter (Mandatory = $false)] [String]$password + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraUser, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraPass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$displayName ) Try { - if (!$PsBoundParameters.ContainsKey("username") -or (!$PsBoundParameters.ContainsKey("password"))) { - # Request Credentials - $creds = Get-Credential - $username = $creds.UserName.ToString() - $password = $creds.GetNetworkCredential().password - } - if (!$PsBoundParameters.ContainsKey("fqdn")) { - $fqdn = Read-Host "SDDC Manager access token not found. Please enter the SDDC Manager FQDN, e.g., sfo-vcf01.sfo.rainpole.io" - } - Request-VCFToken -fqdn $fqdn -Username $username -Password $password | Out-Null - - if ($accessToken) { - # Get vRSLCM Server Details - $vRSLCMFQDN = Get-VCFvRSLCM - $vRSLCMCreds = Get-VCFCredential -resourceName $vRSLCMFQDN.fqdn - $vrslcmDetails = New-Object -TypeName PSCustomObject - $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 + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfVraDetails = Get-vRAServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-vRAConnection -server $vcfVraDetails.loadBalancerFqdn) { + if (Test-vRAAuthentication -server $vcfVraDetails.loadBalancerFqdn -user $vraUser -pass $vraPass) { + $orgId = (Get-vRAOrganizationId).Split("orgs/")[-1] + if (Get-vRAGroup -orgId $orgId -displayName $displayName | Where-Object { $_.displayName -eq $displayName }) { + $groupId = (Get-vRAGroup -orgId $orgId -displayName $displayName).id + if (Get-vRAGroup -orgId $orgId -displayName $displayName | Where-Object { $_.organizationRoles.name -ne $null -or $_.serviceRoles.serviceDefinitionId -ne $null}) { + Remove-vRAGroupRoles -groupId $groupId -orgId $orgId | Out-Null + if (!(Get-vRAGroup -orgId $orgId -displayName $displayName | Where-Object { $_.organizationRoles.name -ne $null -and $_.serviceRoles.serviceRoleNames -ne $null -and $_.serviceRoles.serviceDefinitionId -ne $null})) { + Write-Output "Removing group ($displayName) from vRealize Automation: SUCCESSFUL" + } + else { + Write-Error "Removing group ($displayName) from vRealize Automation:: POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Removing group ($displayName) from vRealize Automation:, does not exist: SKIPPED" + } + } + else { + Write-Error "Unable to find group ($displayName) in Workspace ONE Access for vRealize Automation, check group synchronization or displayName: PRE_VALIDATION_FAILED" + } + } + } + } } - else { - Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials" - Break } } Catch { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Get-vRSLCMServerDetail +Export-ModuleMember -Function Undo-vRAGroup -Function Get-WSAServerDetail { - Param ( - [Parameter (Mandatory = $false)] [String]$fqdn, - [Parameter (Mandatory = $false)] [String]$username, - [Parameter (Mandatory = $false)] [String]$password - ) +########################################### E N D O F F U N C T I O N S ########################################## +######################################################################################################################## - Try { - if (!$PsBoundParameters.ContainsKey("username") -or (!$PsBoundParameters.ContainsKey("password"))) { - # Request Credentials - $creds = Get-Credential - $username = $creds.UserName.ToString() - $password = $creds.GetNetworkCredential().password - } - if (!$PsBoundParameters.ContainsKey("fqdn")) { - $fqdn = Read-Host "SDDC Manager access token not found. Please enter the SDDC Manager FQDN, e.g., sfo-vcf01.sfo.rainpole.io" - } - Request-VCFToken -fqdn $fqdn -Username $username -Password $password | Out-Null + +####################################################################################################################### +################# S H A R E D P O W E R V A L I D A T E D S O L U T I O N F U N C T I O N S ################ + +Function Add-vCenterGlobalPermission { + <# + .SYNOPSIS + Adds a Global Permission to user/group - if ($accessToken) { - # Get WSA Server Details - $wsaFQDN = Get-VCFWSA - #$wsaCreds = Get-VCFCredential -resourceName $wsaFQDN.fqdn - $wsaDetails = New-Object -TypeName PSCustomObject - $wsaDetails | Add-Member -notepropertyname 'fqdn' -notepropertyvalue $wsaFQDN.nodes.fqdn - $wsaDetails | Add-Member -notepropertyname 'loadBalancerIpAddress' -notepropertyvalue $wsaFQDN.loadBalancerIpAddress - $wsaDetails | Add-Member -notepropertyname 'node1IpAddress' -notepropertyvalue $wsaFQDN.nodes.ipAddress[0] - $wsaDetails | Add-Member -notepropertyname 'node2IpAddress' -notepropertyvalue $wsaFQDN.nodes.ipAddress[1] - $wsaDetails | Add-Member -notepropertyname 'node3IpAddress' -notepropertyvalue $wsaFQDN.nodes.ipAddress[2] - $wsaDetails - } - else { - Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials" - } - } - Catch { - Debug-ExceptionWriter -object $_ - } -} -Export-ModuleMember -Function Get-WSAServerDetail + .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 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 + + If -localDomain is selected, then AD authentication check is skipped and user/group is checked for in the local directory + + .EXAMPLE + Add-vCenterGlobalPermission -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo.rainpole.io -domainBindUser svc-vsphere-ad -domainBindPass VMw@re1! -principal gg-vc-admins -role Admin -propagate true -type group + This example adds the group gg-vc-admins from domain sfo.rainpole.io the Administrator Global Permission + + .EXAMPLE + Add-vCenterGlobalPermission -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain vsphere.local -domainBindUser administrator -domainBindPass VMw@re1! -principal svc-sfo-m01-nsx01-sfo-m01-vc01 -role "NSX-T Data Center to vSphere Integration" -propagate true -type user -localdomain + This example adds the "NSX-T Data Center to vSphere Integration" Global Permission to the user svc-sfo-m01-nsx01-sfo-m01-vc01 from domain vsphere.local + #> -Function Get-vRAServerDetail { Param ( - [Parameter (Mandatory = $false)] [String]$fqdn, - [Parameter (Mandatory = $false)] [String]$username, - [Parameter (Mandatory = $false)] [String]$password + [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]$domainBindUser, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domainBindPass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$principal, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$role, + [Parameter (Mandatory = $true)] [ValidateSet("true", "false")] [String]$propagate, + [Parameter (Mandatory = $true)] [ValidateSet("group", "user")] [String]$type, + [Parameter (Mandatory = $false)] [Switch]$localDomain = $false ) Try { - if (!$PsBoundParameters.ContainsKey("username") -or (!$PsBoundParameters.ContainsKey("password"))) { - # Request Credentials - $creds = Get-Credential - $username = $creds.UserName.ToString() - $password = $creds.GetNetworkCredential().password - } - if (!$PsBoundParameters.ContainsKey("fqdn")) { - $fqdn = Read-Host "SDDC Manager access token not found. Please enter the SDDC Manager FQDN, e.g., sfo-vcf01.sfo.rainpole.io" - } - Request-VCFToken -fqdn $fqdn -Username $username -Password $password | Out-Null - - if ($accessToken) { - # Get vRSLCM Server Details - $vraFQDN = Get-VCFvRA - $vraCreds = Get-VCFCredential -resourceName $vraFQDN.loadBalancerFqdn - $vraDetails = New-Object -TypeName PSCustomObject - $vraDetails | Add-Member -notepropertyname 'fqdn' -notepropertyvalue $vraFQDN.nodes.fqdn - $vraDetails | Add-Member -notepropertyname 'loadBalancerIpAddress' -notepropertyvalue $vraFQDN.loadBalancerIpAddress - $vraDetails | Add-Member -notepropertyname 'loadBalancerFqdn' -notepropertyvalue $vraFQDN.loadBalancerFqdn - $vraDetails | Add-Member -notepropertyname 'node1IpAddress' -notepropertyvalue $vraFQDN.nodes.ipAddress[0] - $vraDetails | Add-Member -notepropertyname 'node2IpAddress' -notepropertyvalue $vraFQDN.nodes.ipAddress[1] - $vraDetails | Add-Member -notepropertyname 'node3IpAddress' -notepropertyvalue $vraFQDN.nodes.ipAddress[2] - $vraDetails + if (!$localDomain){ + $checkAdAuthentication = Test-ADAuthentication -user $domainBindUser -pass $domainBindPass -server $domain -domain $domain -ErrorAction SilentlyContinue + if (!($checkAdAuthentication[1] -match "Authentication Successful")) { + Write-Error "Unable to authenticate to Active Directory with user ($domainBindUser) and password ($domainBindPass), check details: PRE_VALIDTION_FAILED" + Return + } + } + + $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 (($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 }) + } + } + 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 vsphere.local | 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.Split("\"))[1])): SUCCESSFUL" + } + else { + 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 $vcfVcenterDetails.fqdn -WarningAction SilentlyContinue + Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue + } + } + } } - else { - Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials" - Break } } Catch { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Get-vRAServerDetail +Export-ModuleMember -Function Add-vCenterGlobalPermission -Function Get-vROPsServerDetail { - Param ( - [Parameter (Mandatory = $false)] [String]$fqdn, - [Parameter (Mandatory = $false)] [String]$username, - [Parameter (Mandatory = $false)] [String]$password - ) +Function Set-vCenterPermission { + <# + .SYNOPSIS + Sets Permission for user or group in the vCenter Server. This overrides any existing Global Permissions for the user or group in the vCenter Server. - Try { - if (!$PsBoundParameters.ContainsKey("username") -or (!$PsBoundParameters.ContainsKey("password"))) { - # Request Credentials - $creds = Get-Credential - $username = $creds.UserName.ToString() - $password = $creds.GetNetworkCredential().password - } - if (!$PsBoundParameters.ContainsKey("fqdn")) { - $fqdn = Read-Host "SDDC Manager access token not found. Please enter the SDDC Manager FQDN, e.g., sfo-vcf01.sfo.rainpole.io" - } - Request-VCFToken -fqdn $fqdn -Username $username -Password $password | Out-Null - - if ($accessToken) { - # Get vRSLCM Server Details - $vropsFQDN = Get-VCFvROPs - $vropsCreds = Get-VCFCredential -resourceName $vropsFQDN.loadBalancerFqdn - $vropsDetails = New-Object -TypeName PSCustomObject - $vropsDetails | Add-Member -notepropertyname 'fqdn' -notepropertyvalue $vropsFQDN.nodes.fqdn - $vropsDetails | Add-Member -notepropertyname 'loadBalancerIpAddress' -notepropertyvalue $vropsFQDN.loadBalancerIp - $vropsDetails | Add-Member -notepropertyname 'loadBalancerFqdn' -notepropertyvalue $vropsFQDN.loadBalancerFqdn - $vropsNode1FQDN = $vropsFQDN.nodes.fqdn[0] - $vropsNode1IP = [System.Net.Dns]::GetHostAddresses("$vropsNode1FQDN").IPAddressToString - $vropsDetails | Add-Member -notepropertyname 'node1IpAddress' -notepropertyvalue $vropsNode1IP - $vropsNode2FQDN = $vropsFQDN.nodes.fqdn[1] - $vropsNode2IP = [System.Net.Dns]::GetHostAddresses("$vropsNode2FQDN").IPAddressToString - $vropsDetails | Add-Member -notepropertyname 'node2IpAddress' -notepropertyvalue $vropsNode2IP - $vropsNode3FQDN = $vropsFQDN.nodes.fqdn[2] - $vropsNode3IP = [System.Net.Dns]::GetHostAddresses("$vropsNode3FQDN").IPAddressToString - $vropsDetails | Add-Member -notepropertyname 'node3IpAddress' -notepropertyvalue $vropsNode3IP - $vropsDetails | Add-Member -notepropertyname 'adminUser' -notepropertyvalue $vropsCreds.username - $vropsDetails | Add-Member -notepropertyname 'adminPass' -notepropertyvalue $vropsCreds.password - - $vropsDetails - } - else { - Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials" - Break + .DESCRIPTION + The Set-vCenterPermission cmdlet assigns the Permission/Role to existing user or group in the vCenter Server. + The user/group must exist in the domain prior to running this cmdlet. + + .EXAMPLE + Set-vCenterPermission -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain vsphere.local -workloadDomain sfo-m01 -principal svc-sfo-w01-nsx01-sfo-w01-vc01 -role "NoAccess" + This example assigns NoAccess role to the user svc-sfo-w01-nsx01-sfo-w01-vc01 from domain vsphere.local. + + .EXAMPLE + Set-vCenterPermission -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo -workloadDomain sfo-m01 -principal gg-vc-admins -role "Admin" + This example assigns the Admin role to the group gg-vc-admins from domain SFO. + + .EXAMPLE + Set-vCenterPermission -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo -workloadDomain sfo-m01 -principal sfo-vra-vsphere -role "NoAccess" -folderName "local" -folderType "Datastore" + This example assigns the NoAccess role to the user svc-vra-vsphere from domain SFO on the datastore folder named "local". + Note: The functionality is limited to non-nested folders in the default datacenter. + #> + + 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]$workloadDomain, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$principal, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$role, + [Parameter (ParameterSetName = 'Folders', Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$folderName, + [Parameter (ParameterSetName = 'Folders', Mandatory = $false)] [ValidateSet("Datacenter", "Datastore", "HostAndCluster", "Network", "VM")] [String]$folderType + ) + + Try { + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $workloadDomain }) { + if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $workloadDomain)) { + 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-SsoPersonUser -Domain $domain -Name $principal -Server $ssoConnectionDetail) { + $principal = $domain.ToUpper() + "\" + $principal + if ($PsBoundParameters.ContainsKey("folderName") -and ($PsBoundParameters.ContainsKey("folderType"))) { + if (($objectCheck = Get-Folder -Name $folderName -Type $folderType -ErrorAction Ignore | Where-Object {$_.Uid -like "*"+$vcfVcenterDetails.fqdn+"*"}).Name) { + if ($objectCheck = Get-VIPermission -Server $vcfVcenterDetails.fqdn -Principal $principal -Entity (Get-Folder -Name $folderName -Type $folderType | Where-Object {$_.Uid -like "*"+$vcfVcenterDetails.fqdn+"*"})) { + if (!($objectCheck.Role -eq $role)) { + New-VIPermission -Server $vcfVcenterDetails.fqdn -Role $role -Principal $principal -Entity (Get-Folder -Name $folderName -Type $folderType | Where-Object {$_.Uid -like "*"+$vcfVcenterDetails.fqdn+"*"}) | Out-Null + $objectCheck = Get-VIPermission -Server $vcfVcenterDetails.fqdn -Principal $principal -Entity (Get-Folder -Name $folderName -Type $folderType | Where-Object {$_.Uid -like "*"+$vcfVcenterDetails.fqdn+"*"}) + if ($objectCheck.Role -eq $role) { + Write-Output "Assigning role ($role) in vCenter Server ($($vcfVcenterDetails.vmName)) to ($principal) on $($folderType.ToLower()) folder ($folderName): SUCCESSFUL" + } + else { + Write-Error "Assigning role ($role) in vCenter Server ($($vcfVcenterDetails.vmName)) to ($principal) on $($folderType.ToLower()) folder ($folderName): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Assigning role ($role) in vCenter Server ($($vcfVcenterDetails.vmName)) to ($principal) on $($folderType.ToLower()) folder ($folderName), already assigned: SKIPPED" + } + } + else { + Write-Error "Assigning role ($role) in vCenter Server ($($vcfVcenterDetails.vmName)) to ($principal) on $($folderType.ToLower()) folder ($folderName), check folderName and folderType: PRE_VALIDATION_FAILED" + } + } + else { + 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 Get-vROPsServerDetail +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 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 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 + #> -Function Get-vRLIServerDetail { Param ( - [Parameter (Mandatory = $false)] [String]$fqdn, - [Parameter (Mandatory = $false)] [String]$username, - [Parameter (Mandatory = $false)] [String]$password + [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 (!$PsBoundParameters.ContainsKey("username") -or (!$PsBoundParameters.ContainsKey("password"))) { - # Request Credentials - $creds = Get-Credential - $username = $creds.UserName.ToString() - $password = $creds.GetNetworkCredential().password - } - if (!$PsBoundParameters.ContainsKey("fqdn")) { - $fqdn = Read-Host "SDDC Manager access token not found. Please enter the SDDC Manager FQDN, e.g., sfo-vcf01.sfo.rainpole.io" + 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 (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" + } + 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" + } } - Request-VCFToken -fqdn $fqdn -Username $username -Password $password | Out-Null - - if ($accessToken) { - # Get vRealize Log Insight Server Details - $vrliVcfDetail = Get-VCFvRLI - $vrliCreds = Get-VCFCredential -resourceName $vrliVcfDetail.loadBalancerFqdn - $vrliDetail = New-Object -TypeName PSCustomObject - $vrliDetail | Add-Member -notepropertyname 'fqdn' -notepropertyvalue $vrliVcfDetail.loadBalancerFqdn - $vrliDetail | Add-Member -notepropertyname 'loadBalancerIpAddress' -notepropertyvalue $vrliVcfDetail.loadBalancerIpAddress - $vrliDetail | Add-Member -notepropertyname 'node1IpAddress' -notepropertyvalue $vrliVcfDetail.nodes.ipAddress[0] - $vrliDetail | Add-Member -notepropertyname 'node2IpAddress' -notepropertyvalue $vrliVcfDetail.nodes.ipAddress[1] - $vrliDetail | Add-Member -notepropertyname 'node3IpAddress' -notepropertyvalue $vrliVcfDetail.nodes.ipAddress[2] - $vrliDetail | Add-Member -notepropertyname 'node1Fqdn' -notepropertyvalue $vrliVcfDetail.nodes.fqdn[0] - $vrliDetail | Add-Member -notepropertyname 'node2Fqdn' -notepropertyvalue $vrliVcfDetail.nodes.fqdn[1] - $vrliDetail | Add-Member -notepropertyname 'node3Fqdn' -notepropertyvalue $vrliVcfDetail.nodes.fqdn[2] - $vrliDetail | Add-Member -notepropertyname 'adminUser' -notepropertyvalue $vrliCreds.username - $vrliDetail | Add-Member -notepropertyname 'adminPass' -notepropertyvalue $vrliCreds.password - $vrliDetail + 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) { + $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 { + 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 { + 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 Identity Source in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($domain): PRE_VALIDATION_FAILED" + } + Disconnect-SsoAdminServer -Server $vcfVcenterDetails.fqdn + } + } + } + } } - else { - Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials" - Break } } Catch { Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Get-vRLIServerDetail - -############## End Cloud Foundation Functions ############## -############################################################## - - -############################################################## -################## Begin vSphere Functions ################# +Export-ModuleMember -Function Add-SsoPermission -Function Request-VCToken { +Function Add-SsoUser { <# - .SYNOPSIS - Connects to the specified vCenter Server API and stores the credentials in a base64 string + .SYNOPSIS + Assign vCenter Single Sign-On Group to user/group .DESCRIPTION - The Request-VCToken cmdlet connects to the specified vCenter Server and stores the credentials - in a base64 string. It is required once per session before running all other cmdlets + 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 the user does not exist + - Adds the user to the vCenter Single Sign-On domain .EXAMPLE - Request-VCToken -fqdn sfo-m01-vc01.sfo.rainpole.io -username administrator@vsphere.local -password VMw@re1! - This example shows how to connect to the vCenter Server API - #> + Add-SsoUser -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -ssoUser svc-vrslcm-vsphere-sfo-m01-vc01 -ssoPass VMw@re1!VMw@re1! + This example adds the user svc-vrslcm-vsphere-sfo-m01-vc01 to the vCenter Single Sign-On domain vsphere.local + #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$fqdn, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$username, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$password + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ssoUser, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ssoPass ) - if ( -not $PsBoundParameters.ContainsKey("username") -or ( -not $PsBoundParameters.ContainsKey("password"))) { - $creds = Get-Credential # Request Credentials - $username = $creds.UserName.ToString() - $password = $creds.GetNetworkCredential().password - } - - $Global:vcenterFqdn = $fqdn - - $vcenterHeader = @{"Authorization" = "Basic "+[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($username+":"+$password))} - $contentType = "application/json" - $uri = "https://$vcenterFqdn/api/session" - Try { - # Checking authentication with vCenter Server API - if ($PSEdition -eq 'Core') { - $Global:vcToken = Invoke-RestMethod -Uri $uri -Headers $vcenterHeader -Method POST -ContentType $contentType -SkipCertificateCheck # PS Core has -SkipCertificateCheck implemented - } - else { - $Global:vcToken = Invoke-RestMethod -Uri $uri -Headers $vcenterHeader -Method POST -ContentType $contentType - } - if ($vcToken) { - Write-Output "Successfully connected to the vCenter Server API: $vcenterFqdn" + 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-SSOConnection -server $($vcfVcenterDetails.fqdn)) { + if (Test-SSOAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { + if (!(Get-SsoPersonUser -Domain vsphere.local -Name $ssoUser -Server $ssoConnectionDetail)) { + New-SsoPersonUser -UserName $ssoUser -Password $ssoPass -Server $ssoConnectionDetail | Out-Null + if (Get-SsoPersonUser -Domain vsphere.local -Name $ssoUser -Server $ssoConnectionDetail) { + Write-Output "Adding New Single Sign-On User to vCenter Server ($($vcfVcenterDetails.vmName)) named ($ssoUser): SUCCESSFUL" + } + else { + Write-Error "Adding New Single Sign-On User to vCenter Server ($($vcfVcenterDetails.vmName)) named ($ssoUser): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Adding New Single Sign-On User to vCenter Server ($($vcfVcenterDetails.vmName)) named ($ssoUser), already exists: SKIPPED" + } + Disconnect-SsoAdminServer $vcfVcenterDetails.fqdn -WarningAction SilentlyContinue + } + } + } + } } + } Catch { - Write-Error $_.Exception.Message + Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Request-VCToken +Export-ModuleMember -Function Add-SsoUser -Function Get-VCVersion { +Function Add-vSphereRole { <# .SYNOPSIS - Get the version + Add a vSphere role .DESCRIPTION - The Get-VCVersion cmdlet gets the version of the vCenter Server + 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 + - Verifies if the role already exists and if not creates it + - Assigns permissions to the role based on the template file provided .EXAMPLE - Get-VCVersion - This example gets the version of the vCenter Server + 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 #> - Try { - $vcenterHeader = @{"vmware-api-session-id" = "$vcToken"} - $uri = "https://$vcenterFqdn/api/appliance/system/version" - - $response = Invoke-RestMethod -Method GET -Uri $uri -Headers $vcenterHeader - $response - } - Catch { - Write-Error $_.Exception.Message - } -} -Export-ModuleMember -Function Get-VCVersion - -Function Get-VCConfigurationNTP { - <# - .SYNOPSIS - Get NTP configuration - - .DESCRIPTION - The Get-VCConfigurationNTP cmdlet gets the NTP configuration of vCenter Server - - .EXAMPLE - Get-VCConfigurationNTP - This example gets the NTP configuration of the 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, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$template + ) Try { - $vcenterHeader = @{"vmware-api-session-id" = "$vcToken"} - $uri = "https://$vcenterFqdn/api/appliance/ntp" + if (!$PsBoundParameters.ContainsKey("template")) { + $template = Get-ExternalFileName -title "Select the vSphere role template (.role)" -fileType "role" -location "C:\Program Files\WindowsPowerShell\Modules\PowerValidatedSolutions\vSphereRoles" + } + else { + if (!(Test-Path -Path $template)) { + Write-Error "vSphere Role Template '$template' File Not Found" + Break + } + } - $response = Invoke-RestMethod -Method GET -Uri $uri -Headers $vcenterHeader - $response + 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) { + $roleContent = Get-Content -Path $template + if (!(Get-VIRole -Server $vcfVcenterDetails.fqdn | Where-Object { $_.Name -eq $roleName })) { + New-VIRole -Name $roleName -Server $vcfVcenterDetails.fqdn | Out-Null + if (Get-VIRole -Server $vcfVcenterDetails.fqdn | Where-Object { $_.Name -eq $roleName }) { + Foreach ($privilege in $roleContent) { + if (-not ($privilege -eq $null -or $privilege -eq "")) { + Set-VIRole -Server $vcfVcenterDetails.fqdn -Role $roleName -AddPrivilege (Get-VIPrivilege -ID $privilege) -Confirm:$False -ErrorAction SilentlyContinue | Out-Null + } + } + Write-Output "Creating a new role in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($roleName): SUCCESSFUL" + } + else { + Write-Error "Creating a new role in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($roleName): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Creating a new role in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($roleName), already exists: SKIPPED" + } + Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue + } + } + } + } + } } Catch { - Write-Error $_.Exception.Message + Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Get-VCConfigurationNTP +Export-ModuleMember -Function Add-vSphereRole -Function Get-VCConfigurationDNS { +Function Add-VMFolder { <# .SYNOPSIS - Get DNS configuration + Create a VM Folder .DESCRIPTION - The Get-VCConfigurationDNS cmdlet gets the DNS configuration of vCenter Server + 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 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 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 .EXAMPLE - Get-VCConfigurationDNS - This example gets the DNS configuration of the vCenter Server + Add-VMFolder -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -foldername "myFolder" + This example shows how to create the folder myFolder within the VMware Cloud Foundation domain sfo-m01 #> - Try { - $vcenterHeader = @{"vmware-api-session-id" = "$vcToken"} - $uri = "https://$vcenterFqdn/api/appliance/networking/dns/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]$folderName + ) - $response = Invoke-RestMethod -Method GET -Uri $uri -Headers $vcenterHeader - $response + 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 + $datacenter = (Get-Datacenter -Cluster $cluster -Server $vcfVcenterDetails.fqdn).Name + if (Get-Folder -Name $folderName -Server $vcfVcenterDetails.fqdn -WarningAction SilentlyContinue -ErrorAction Ignore) { + Write-Warning "Adding VM and Template Folder to vCenter Server ($($vcfVcenterDetails.fqdn)) named ($folderName), already exists: SKIPPED" + } + else { + (Get-View -Server $vcfVcenterDetails.fqdn (Get-View -Server $vcfVcenterDetails.fqdn -viewtype datacenter -filter @{"name" = [String]$datacenter }).vmfolder).CreateFolder($folderName) | Out-Null + if ((Get-Folder -Name $folderName -Server $vcfVcenterDetails.fqdn -WarningAction SilentlyContinue -ErrorAction Ignore)) { + Write-Output "Adding VM and Template Folder to vCenter Server ($($vcfVcenterDetails.fqdn)) named ($folderName): SUCCESSFUL" + } + else { + Write-Error "Adding VM and Template Folder to vCenter Server ($($vcfVcenterDetails.fqdn)) named ($folderName): POST_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 { - Write-Error $_.Exception.Message + Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Get-VCConfigurationDNS +Export-ModuleMember -Function Add-VMFolder -Function Get-VCPasswordPolicy { +Function Undo-VMFolder { <# - .SYNOPSIS - Get the global password policy. + .SYNOPSIS + Remove a VM Folder .DESCRIPTION - The Get-VCPasswordPolicy cmdlet gets global password policy for the vCenter Server + 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 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 the VM and Template folder is present in the vCenter Server inventory + - Removes the VM and Template folder from the vCenter Server inventory .EXAMPLE - Get-VCPasswordPolicy - This example gets the global password policy of the vCenter Server - #> + Undo-VMFolder -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -foldername "myFolder" -folderType VM + This example shows how to remove the folder myFolder within the VMware Cloud Foundation domain sfo-m01 + #> - Try { - $vcenterHeader = @{"vmware-api-session-id" = "$vcToken"} - $uri = "https://$vcenterFqdn/api/appliance/local-accounts/global-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]$folderName, + [Parameter (Mandatory = $true)] [ValidateSet("Datacenter", "VM", "Network", "HostAndCluster", "Datastore")] [String]$folderType + ) - $response = Invoke-RestMethod -Method GET -Uri $uri -Headers $vcenterHeader - $response + 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-Folder -Name $folderName -Type $folderType -Server $vcfVcenterDetails.fqdn -ErrorAction Ignore)) { + Write-Warning "Removing Folder Type ($folderType) from vCenter Server ($($vcfVcenterDetails.fqdn)) with name ($folderName), folder does not exist: SKIPPED" + } + else { + Get-Folder -Name $folderName -Type $folderType -Server $vcfVcenterDetails.fqdn | Remove-Folder -Confirm:$false -ErrorAction Ignore + if (!(Get-Folder -Name $folderName -Type $folderType -Server $vcfVcenterDetails.fqdn -ErrorAction Ignore)) { + Write-Output "Removing Folder Type ($folderType) from vCenter Server ($($vcfVcenterDetails.fqdn)) with name ($folderName): SUCCESSFUL" + } + else { + Write-Error "Removing Folder Type ($folderType) from vCenter Server ($($vcfVcenterDetails.fqdn)) with name ($folderName): POST_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 { - Write-Error $_.Exception.Message + Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Get-VCPasswordPolicy +Export-ModuleMember -Function Undo-VMFolder -Function Set-VCPasswordPolicy { +Function Add-ResourcePool { <# - .SYNOPSIS - Set the global password policy + .SYNOPSIS + Create a resource pool - .DESCRIPTION - The Set-VCPasswordPolicy cmdlet configures the global password policy for the vCenter Server + .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 - Set-VCPasswordPolicy -maxDays 120 -minDays 1 -warnDays 14 - This example configures the global password policy of the vCenter Server - #> + .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]$maxDays, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$minDays, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$warnDays + [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]$resourcePoolName ) Try { - $vcenterHeader = @{"vmware-api-session-id" = "$vcToken"} - $vcenterHeader.Add("Content-Type", "application/json") - $uri = "https://$vcenterFqdn/api/appliance/local-accounts/global-policy" - $body = '{ "max_days": '+$maxDays+', "min_days": '+$minDays+', "warn_days": '+$warnDays+' }' - - $response = Invoke-RestMethod -Method PUT -Uri $uri -Headers $vcenterHeader -Body $body - $response + if (Test-Connection -ComputerName ($server) -Quiet -Count 1) { + Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null + if ($accessToken) { + $vcenter = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain -ErrorAction SilentlyContinue + if ($vcenter) { + 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-ResourcePool -Server $vcenter.fqdn | Where-Object {$_.Name -eq $resourcePoolName})) { + New-ResourcePool -Name $resourcePoolName -Location $cluster -Server $vcenter.fqdn | Out-Null + if (Get-ResourcePool -Server $vcenter.fqdn | Where-Object {$_.Name -eq $resourcePoolName}) { + Write-Output "Adding Resource Pool to vCenter Server ($($vcenter.fqdn)) named ($resourcePoolName): SUCCESSFUL" + } + else { + Write-Error "Adding Resource Pool to vCenter Server ($($vcenter.fqdn)) named ($resourcePoolName): FAILED" + } + } + else { + Write-Warning "Adding Resource Pool to vCenter Server ($($vcenter.fqdn)) named ($resourcePoolName), already exists: SKIPPED" + } + Disconnect-VIServer $vcenter.fqdn -Confirm:$false -WarningAction SilentlyContinue + } + else { + Write-Error "Unable to connect to vCenter Server ($($vcenter.fqdn))" + } + } + else { + 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 { - Write-Error $_.Exception.Message + Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Set-VCPasswordPolicy +Export-ModuleMember -Function Add-ResourcePool -Function Get-VCPasswordExpiry { +Function Undo-ResourcePool { <# - .SYNOPSIS - Get the vcenter password expiry date. + .SYNOPSIS + Remove a resource pool - .DESCRIPTION - The Get-VCPasswordPolicy cmdlet gets password expiration settings for the vCenter Server root account + .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 - Get-VCPasswordExpiry - This example gets the password policy of the vCenter Server - #> + .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, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$resourcePoolName + ) Try { - $uri = "https://$currentvCenterServer"+":5480/rest/appliance/local-accounts/root" - $response = Invoke-RestMethod -Method GET -Uri $uri -Headers $vcAdminHeaders - $response + if (Test-Connection -ComputerName ($server) -Quiet -Count 1) { + Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null + if ($accessToken) { + $vcenter = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain -ErrorAction SilentlyContinue + if ($vcenter) { + 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-ResourcePool -Server $vcenter.fqdn | Where-Object {$_.Name -eq $resourcePoolName}) { + Remove-ResourcePool -ResourcePool $resourcePoolName -Server $vcenter.fqdn -Confirm:$false | Out-Null + if (!(Get-ResourcePool -Server $vcenter.fqdn | Where-Object {$_.Name -eq $resourcePoolName})) { + Write-Output "Removing Resource Pool from vCenter Server ($($vcenter.fqdn)) named ($resourcePoolName): SUCCESSFUL" + } + else { + Write-Error "Removing Resource Pool from vCenter Server ($($vcenter.fqdn)) named ($resourcePoolName): FAILED" + } + } + else { + Write-Warning "Removing Resource Pool from vCenter Server ($($vcenter.fqdn)) named ($resourcePoolName), does not exist: SKIPPED" + } + Disconnect-VIServer $vcenter.fqdn -Confirm:$false -WarningAction SilentlyContinue + } + else { + Write-Error "Unable to connect to vCenter Server ($($vcenter.fqdn))" + } + } + else { + 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 { - Write-Error $_.Exception.Message + Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Get-VCPasswordExpiry +Export-ModuleMember -Function Undo-ResourcePool -Function Set-VCPasswordExpiry { +Function Add-AntiAffinityRule { <# .SYNOPSIS - Set the vcenter password expiry date + Creates a vSphere Anti-Affinity rule .DESCRIPTION - The Set-VCPasswordExpiry cmdlet configures password expiration settings for the vCenter Server root account + 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 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 .EXAMPLE - Set-VCPasswordExpiry -passwordExpires $true -email "admin@rainpole.io" -maxDaysBetweenPasswordChange 91 - This example configures the configures password expiration settings for the vCenter Server root account - - Set-VCPasswordExpiry -passwordExpires $false - This example configures the configures password expiration settings for the vCenter Server root account to never expire + 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 = $false, ParameterSetName = 'neverexpire')] [Parameter (Mandatory = $true, ParameterSetName = 'expire')] [ValidateNotNullOrEmpty()] [Bool]$passwordExpires, - [Parameter (Mandatory = $true, ParameterSetName = 'expire')] [ValidateNotNullOrEmpty()] [String]$email, - [Parameter (Mandatory = $true, ParameterSetName = 'expire')] [ValidateNotNullOrEmpty()] [String]$maxDaysBetweenPasswordChange + [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 { - $uri = "https://$currentvCenterServer"+":5480/rest/appliance/local-accounts/root" - - if ($passwordExpires) { - $body = '{"config":{"password_expires": "'+ $passwordExpires +'", "email": "'+ $email+ '", "max_days_between_password_change": "' + $maxDaysBetweenPasswordChange + '" }}' - } - else { - $body = '{"config":{"password_expires": "'+ $passwordExpires + '"}}' - } - $response = Invoke-RestMethod -Method PATCH -Uri $uri -Headers $vcAdminHeaders -Body $body - $response + 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" + } + } + Disconnect-VIServer $vcenter.fqdn -Confirm:$false -WarningAction SilentlyContinue + } + else { + Write-Error "Unable to connect to vCenter Server ($($vcenter.fqdn)): PRE_VALIDATION_FAILED" + } + } + else { + Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" + } + } + } } Catch { - Write-Error $_.Exception.Message + Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Set-VCPasswordExpiry +Export-ModuleMember -Function Add-AntiAffinityRule -Function Add-GlobalPermission { +Function Add-ClusterGroup { <# - .SYNOPSIS - Script to add vSphere Global Permission - - .DESCRIPTION - The Add-GlobalPermission cmdlet adds a new vSphere Global Permission + .SYNOPSIS + Creates a vSphere DRS Cluster Group - .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 + .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 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 - .EXAMPLE - Add-GlobalPermission -vcServer sfo-m01-vc01.sfo.rainpole.io -username administrator@vsphewre.local -vcPassword VMware1! -user svc-vc-admins - This example shows how to add the Administrator global permission to a user called svc-vc-admins - #> + .EXAMPLE + Add-ClusterGroup -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -drsGroupName "xint-vm-group-wsa" -drsGroupVMs "xreg-wsa01a,xreg-wsa01b,xreg-wsa01c" + 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]$vcServer, - [Parameter (Mandatory = $true)] [String]$vcUsername, - [Parameter (Mandatory = $true)] [String]$vcPassword, + [Parameter (Mandatory = $true)] [String]$server, [Parameter (Mandatory = $true)] [String]$user, - [Parameter (Mandatory = $true)] [String]$roleId, - [Parameter (Mandatory = $true)] [String]$propagate, - [Parameter (Mandatory = $true)] [String]$type + [Parameter (Mandatory = $true)] [String]$pass, + [Parameter (Mandatory = $true)] [String]$domain, + [Parameter (Mandatory = $true)] [String]$drsGroupName, + [Parameter (Mandatory = $true)] [String]$drsGroupVMs ) 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; + 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-DrsClusterGroup | Where-Object {$_.Name -eq $drsGroupName})) { + $vmNames = $drsGroupVMs.split(",") + $vms = foreach ($name in $vmNames) { Get-VM -name $name -ErrorAction SilentlyContinue } + New-DrsClusterGroup -Cluster $cluster -VM $vms -Name $drsGroupName | Out-Null + if (Get-Cluster -Name $cluster | Get-DrsClusterGroup | Where-Object {$_.Name -eq $drsGroupName}) { + Write-Output "Adding vSphere DRS Group to vCenter Server ($($vcfVcenterDetails.fqdn)) named ($drsGroupName): SUCCESSFUL" + } + else { + Write-Error "Adding vSphere DRS Group to vCenter Server ($($vcfVcenterDetails.fqdn)) named ($drsGroupName): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Adding vSphere DRS Group to vCenter Server ($($vcfVcenterDetails.fqdn)) named ($drsGroupName), 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" + } } } -"@ - [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] - } - else { - Write-Error "Failed to login to vSphere MOB" - exit 1 - } - - $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 { + Debug-ExceptionWriter -object $_ } +} +Export-ModuleMember -Function Add-ClusterGroup - $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" +Function Undo-ClusterGroup { + <# + .SYNOPSIS + Creates 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 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 + #> + + 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]$drsGroupName + ) + + 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 | Where-Object {$_.DependsOnVmGroup -eq $drsGroupName})) { + if ((Get-Cluster -Name $cluster | Get-DrsClusterGroup | Where-Object {$_.Name -eq $drsGroupName})) { + Remove-DrsClusterGroup -DrsClusterGroup $drsGroupName -Server $($vcfVcenterDetails.fqdn) -Confirm:$false | Out-Null + if (!(Get-Cluster -Name $cluster | Get-DrsClusterGroup | Where-Object {$_.Name -eq $drsGroupName})) { + Write-Output "Removing vSphere DRS Group from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($drsGroupName): SUCCESSFUL" + } + else { + Write-Error "Removing vSphere DRS Group from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($drsGroupName): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Removing vSphere DRS Group from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($drsGroupName), already exists: SKIPPED" + + } + } + else { + Write-Error "Unable to remove vSphere DRS Group from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($drsGroupName), in use by VM to VM Group: 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" + } + } } - $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 + Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-GlobalPermission +Export-ModuleMember -Function Undo-ClusterGroup -Function Get-SsoPasswordPolicies { +Function Add-VmStartupRule { <# .SYNOPSIS - Get vSphere Single-Sign On password policies + Creates a VM to VM DRS rule .DESCRIPTION - The Get-SsoPasswordPolicies cmdlet gets the vSphere Single-Sign On password policies + 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 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 - Get-SsoPasswordPolicies -ssoAdminPass VMw@re1! -ssoDomain vsphere.local -vmName sfo-m01-vc01 -rootPass VMw@re1! - This example shows how to get vSphere Single-Sign On password policies + 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]$ssoAdminPass, - [Parameter (Mandatory = $true)] [String]$ssoDomain, - [Parameter (Mandatory = $true)] [String]$vmName, - [Parameter (Mandatory = $true)] [String]$rootPass + [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]$vmGroup, + [Parameter (Mandatory = $true)] [String]$dependOnVmGroup ) Try { - $a, $b = $ssoDomain.split(".") - $scriptCommand = "/opt/likewise/bin/ldapsearch -h localhost -w $ssoAdminPass -x -D `"cn=Administrator,cn=Users,dc=$a,dc=$b`" -b `"cn=password and lockout policy,dc=$a,dc=$b`" | grep vmwPassword" - $output = Invoke-VMScript -ScriptText $scriptCommand -vm $vmName -GuestUser "root" -GuestPassword $rootPass - $output.scriptOutput + 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" + } + 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" + } + else { + Write-Error "Adding vSphere DRS Virtual Machine to Virtual Machine Group to vCenter Server ($($vcenter.fqdn)) named ($ruleName): POST_VALIDATION_FAILED" + } + } + } + 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 { + Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" + } + } + } } Catch { - Write-Error $_.Exception.Message + Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Get-SsoPasswordPolicies +Export-ModuleMember -Function Add-VmStartupRule -Function Add-DrsVmToVmGroup { +Function Move-VMtoFolder { <# .SYNOPSIS - Creates a vSphere VM to VM Group + Moves VMs to a folder .DESCRIPTION - The Add-DrsVmToVmGroup cmdlet creates a vSphere VM to VM Group + 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 + - Retrives the details of the vCenter Server for the Workload Domain provided + - Validates that the folder provided exists in the vCenter Server inventory + - Validates the virtual machine exists in the vCenter Server inventory + - Moves the virtual machines provided in the -vmlist parameter .EXAMPLE - Add-DrsVmToVmGroup -name vm-vm-rule-wsa-vra -vmGroup sfo-m01-vm-group-wsa -dependOnVmGroup sfo-m01-vm-group-vra -Enabled -cluster sfo-m01-cl01 - This example shows how to create a vSphere VM to VM group in the vCenter Server + 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]$name, - [Parameter (Mandatory = $true)] [String]$vmGroup, - [Parameter (Mandatory = $true)] [String]$dependOnVmGroup, - [Parameter (Mandatory = $false)] [Switch]$enabled=$true, - [Parameter (Mandatory = $true)] [String]$cluster + [Parameter (Mandatory = $true)] [String]$server, + [Parameter (Mandatory = $true)] [String]$user, + [Parameter (Mandatory = $true)] [String]$pass, + [Parameter (Mandatory = $true)] [String]$domain, + [Parameter (Mandatory = $true)] [String]$vmList, + [Parameter (Mandatory = $true)] [String]$folder ) 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].Operation = 'add' - $spec.RulesSpec[0].Info = New-Object VMware.Vim.ClusterDependencyRuleInfo - $spec.RulesSpec[0].Info.DependsOnVmGroup = $dependOnVmGroup - $spec.RulesSpec[0].Info.VmGroup = $vmGroup - $spec.RulesSpec[0].Info.Name = $name - $spec.RulesSpec[0].Info.UserCreated = $true - $spec.RulesSpec[0].Info.Enabled = $true - - $ClusterToReconfig = Get-View -Id $updateCluster.ExtensionData.MoRef - $ClusterToReconfig.ReconfigureComputeResource_Task($spec, $true) + 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)) { + if (Get-Folder | Where-Object {$_.Name -eq $folder}) { + $vmNames = $vmList.split(",") + foreach ($vm in $vmNames) { + if (Get-VM -Name $vm -ErrorAction SilentlyContinue) { + Get-VM -Name $vm | Move-VM -InventoryLocation (Get-Folder | Where-Object {$_.Name -eq $folder}) | Out-Null + Write-Output "Relocating Virtual Machine in vCenter Server ($($vcenter.fqdn)) named ($vm) to folder ($folder): SUCCESSFUL" + } + else { + Write-Warning "Relocating Virtual Machines in vCenter Server ($($vcenter.fqdn)) named ($vm) to folder ($folder), Vitual Machine not found: SKIPPED" + } + } + } + else { + Write-Error "Relocating Virtual Machine in vCenter Server ($($vcenter.fqdn)) folder ($folder), Folder not found: 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 { + Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" + } + } + } } Catch { - Write-Error $_.Exception.Message + Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Add-DrsVmToVmGroup +Export-ModuleMember -Function Move-VMtoFolder -Function Get-DrsVmToVmGroup { +Function Import-vRSLCMLockerCertificate { <# - .SYNOPSIS - Gets all vSphere VM to VM Group + .SYNOPSIS + Add a certificate to the vRealize Suite Lifecycle Manager Locker - .DESCRIPTION - The Get-DrsVmToVmGroup cmdlet retrieves the vSphere VM to VM Group + .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 + - 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 - .EXAMPLE - Get-DrsVmToVmGroup -name vm-vm-rule-wsa-vra -cluster sfo-m01-cl01 - This example shows how to retrieve a vSphere VM to VM group in the vCenter Server - #> + .EXAMPLE + Import-vRSLCMLockerCertificate -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -certificateAlias "xint-vrops01" -certificatePassphrase "VMw@re1!" + This example gets the details of a certificate based on the vmid + #> Param ( - [Parameter (Mandatory = $false)] [String]$name, - [Parameter (Mandatory = $true)] [String]$cluster + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$certificateAlias, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$certificatePassphrase, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$certChainPath ) Try { - $getCluster = Get-Cluster | Where-Object {$_.Name -eq $cluster} - if ($PsBoundParameters.ContainsKey("name")){ - $getCluster.ExtensionData.Configuration.Rule | Where-Object {$_.Name -eq $name} + if (!$PsBoundParameters.ContainsKey("certChainPath")) { + $certChainPath = Get-ExternalFileName -title "Select the Certificate Chain PEM File (.pem)" -fileType "pem" -location "default" } else { - $getCluster.ExtensionData.Configuration.Rule + if (!(Test-Path -Path $certChainPath)) { + Write-Error "Certificate Chain '$certChainPath' 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) { + if (!(Get-vRSLCMLockerCertificate | Where-Object {$_.alias -eq $certificateAlias})) { + if ($PsBoundParameters.ContainsKey("certificatePassphrase")) { + Add-vRSLCMLockerCertificate -vrslcmFQDN $vcfVrslcmDetails.fqdn -certificateAlias $certificateAlias -certificatePassphrase $certificatePassphrase -certChainPath $certChainPath | Out-Null + } + else { + Add-vRSLCMLockerCertificate -vrslcmFQDN $vcfVrslcmDetails.fqdn -certificateAlias $certificateAlias -certChainPath $certChainPath | Out-Null + } + if ((Get-vRSLCMLockerCertificate | Where-Object {$_.alias -eq $certificateAlias})) { + Write-Output "Importing Certificate to the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($certificateAlias): SUCCESSFUL" + } + else { + Write-Error "Importing Certificate to the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($certificateAlias): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Importing Certificate to the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($certificateAlias), already exist: SKIPPED" + } + } + } + } + } } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-DrsVmToVmGroup - - -################## End vSphere Functions ################### -############################################################## - - -############################################################## -########### Begin Workspace ONE Access Functions ########### +Export-ModuleMember -Function Import-vRSLCMLockerCertificate -Function Request-WSAToken { +Function Undo-vRSLCMLockerCertificate { <# - .SYNOPSIS - Connects to the specified Workspace ONE Access instance to obtain a session token + .SYNOPSIS + Remove a certificate from the vRealize Suite Lifecycle Manager Locker - .DESCRIPTION - The Request-WSAToken cmdlet connects to the specified Workspace ONE Access instance and requests a session token + .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 + - Verifies that the certificate is present in the vRealize Suite Lifecycle Manager Locker + - Removes the certificate from vRealize Suite Lifecycle Manager Locker - .EXAMPLE - Request-WSAToken -fqdn sfo-wsa01.sfo.rainpole.io -user admin -pass VMware1! - This example shows how to connect to a Workspace ONE Access instance and request a session token - #> + .EXAMPLE + Undo-vRSLCMLockerCertificate -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -certificateAlias "xint-vrops01" + This example removes a certificate with an alias of 'xint-vrops01' from the vRealize Suite Lifecycle Manager Locker + #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$fqdn, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$user, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$pass + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$certificateAlias ) - If ( -not $PsBoundParameters.ContainsKey("user") -or ( -not $PsBoundParameters.ContainsKey("pass"))) { - # Request Credentials - $creds = Get-Credential - $user = $creds.UserName.ToString() - $pass = $creds.GetNetworkCredential().password - } - - $Global:workSpaceOne = $fqdn - - # Validate credentials by executing an API call - $wsaHeaders = @{"Content-Type" = "application/json" } - $wsaHeaders.Add("Accept", "application/json; charset=utf-8") - $uri = "https://$workSpaceOne/SAAS/API/1.0/REST/auth/system/login" - $body = '{"username": "' + $user + '", "password": "' + $pass + '", "issueToken": "true"}' - Try { - # Checking against the API - # PS Core has -SkipCertificateCheck implemented, PowerShell 5.x does not - if ($PSEdition -eq 'Core') { - $response = Invoke-RestMethod $uri -Method 'POST' -Headers $wsaHeaders -Body $body -SkipCertificateCheck - $Global:sessionToken = "HZN " + $response.sessionToken - } - else { - $response = Invoke-RestMethod $uri -Method 'POST' -Headers $wsaHeaders -Body $body - $Global:sessionToken = "HZN " + $response.sessionToken - } - if ($response.sessionToken) { - Write-Output "Successfully Requested New Session Token From Workspace ONE Access instance: $fqdn" + + 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-vRSLCMLockerCertificate | Where-Object {$_.alias -eq $certificateAlias}) { + Remove-vRSLCMLockerCertificate -vmid (Get-vRSLCMLockerCertificate | Where-Object {$_.alias -eq $certificateAlias}).vmid | Out-Null + if ((Get-vRSLCMLockerCertificate | Where-Object {$_.alias -eq $certificateAlias})) { + Write-Error "Removing Certificate from the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($certificateAlias): POST_VALIDATION_FAILED" + } + else { + Write-Output "Removing Certificate from the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($certificateAlias): SUCCESSFUL" + } + } + else { + Write-Warning "Removing Certificate from the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($certificateAlias), does not exist: SKIPPED" + } + } + } + } + } } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Request-WSAToken +Export-ModuleMember -Function Undo-vRSLCMLockerCertificate -Function Get-WSAConnector { +Function New-vRSLCMLockerPassword { <# - .SYNOPSIS - Get connectors + .SYNOPSIS + Add a password to the vRealize Suite Lifecycle Manager Locker Locker - .DESCRIPTION - The Get-WSAConnector cmdlets retrieves a list of connectors in Workspace ONE Access + .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 + - Verifies that the password is not present in the vRealize Suite Lifecycle Manager Locker + - Adds the password to the vRealize Suite Lifecycle Manager Locker - .EXAMPLE - Get-WSAConnector - This example retrives a list of connectors in Workspace ONE Access - #> + .EXAMPLE + New-vRSLCMLockerPassword -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -alias xint-vrops01-admin -password VMw@re1! -description "vRealize Operations Admin" -userName xint-vrops01-admin + This example adds a password with an alias of 'xint-vrops01-admin' to the vRealize Suite Lifecycle Manager Locker + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$alias, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$password, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$description, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$userName + ) Try { - $wsaHeaders = @{"Content-Type" = "application/vnd.vmware.horizon.manager.connector.management.connector+json" } - $wsaHeaders.Add("Authorization", "$sessionToken") - $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/connectormanagement/connectorinstances" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders - $response.items + 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-vRSLCMLockerPassword | Where-Object {$_.alias -eq $alias})) { + if ($PsBoundParameters.ContainsKey("description")) { + $lockerPassword = Add-vRSLCMLockerPassword -alias $alias -password $password -description $description -userName $userName + } + else { + $lockerPassword = Add-vRSLCMLockerPassword -alias $alias -password $password -userName $userName + } + if ((Get-vRSLCMLockerPassword | Where-Object {$_.alias -eq $alias})) { + Write-Output "Adding Password to the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($alias): SUCCESSFUL" + } + else { + Write-Error "Adding Password to the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($alias): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Adding Password to the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($alias), already exists: SKIPPED" + } + } + } + } + } + } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-WSAConnector +Export-ModuleMember -Function New-vRSLCMLockerPassword -Function Get-WSADirectory { +Function Undo-vRSLCMLockerPassword { <# - .SYNOPSIS - Get diretories + .SYNOPSIS + Remove a password from the vRealize Suite Lifecycle Manager Locker - .DESCRIPTION - The Get-WSADirectory cmdlets retrieves all directories in Workspace ONE Access + .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 + - Verifies that the password is present in the vRealize Suite Lifecycle Manager Locker + - Removes the password from the vRealize Suite Lifecycle Manager Locker - .EXAMPLE - Get-WSADirectory - This example retrives a list of directories in Workspace ONE Access - #> + .EXAMPLE + Undo-vRSLCMLockerPassword -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -alias xint-vrops01-admin + This example removes a password with an alias of 'xint-vrops01-admin' from the vRealize Suite Lifecycle Manager Locker + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$alias + ) Try { - $wsaHeaders = @{"Content-Type" = "application/vnd.vmware.horizon.manager.connector.management.directory.ad.over.ldap+json" } - $wsaHeaders.Add("Authorization", "$sessionToken") - $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/connectormanagement/directoryconfigs" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders - $response.items + 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-vRSLCMLockerPassword | Where-Object {$_.alias -eq $alias}) { + Remove-vRSLCMLockerPassword -vmid (Get-vRSLCMLockerPassword | Where-Object {$_.alias -eq $alias}).vmid | Out-Null + if ((Get-vRSLCMLockerPassword | Where-Object {$_.alias -eq $alias})) { + Write-Error "Removing Password from the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($alias): POST_VALIDATION_FAILED" + } + else { + Write-Output "Removing Password from the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($alias): SUCCESSFUL" + } + } + else { + Write-Warning "Removing Password from the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($alias), does not exist: SKIPPED" + } + } + } + } + } + } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-WSADirectory +Export-ModuleMember -Function Undo-vRSLCMLockerPassword -Function Get-WSADirectoryDomain { +Function New-vRSLCMLockerLicense { <# - .SYNOPSIS - Get directory domains + .SYNOPSIS + Add a license to the vRealize Suite Lifecycle Manager Locker - .DESCRIPTION - The Get-WSADirectoryDomain cmdlets retrieves a list of directory domains in Workspace ONE Access + .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 + - Verifies that the license is not present in the vRealize Suite Lifecycle Manager Locker + - Adds the license to the vRealize Suite Lifecycle Manager Locker - .EXAMPLE - Get-WSADirectoryDomain -directoryId a1c985d5-0eeb-4a66-bc51-11eda9321aac - This example retrives a list of directory domains in Workspace ONE Access - #> + .EXAMPLE + New-vRSLCMLockerLicense -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -alias "vRealize Automation" -license "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX" + This example adds a license with an alias of 'vRealize Automation' to the vRealize Suite Lifecycle Manager Locker + #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [string]$directoryId + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$alias, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$license ) Try { - $wsaHeaders = @{"Accept" = "application/vnd.vmware.horizon.manager.connector.management.directory.domain.list+json" } - $wsaHeaders.Add("Authorization", "$sessionToken") - $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/connectormanagement/directoryconfigs/$directoryId/domains" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders - $response.items + 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-vRSLCMLockerLicense | Where-Object {$_.key -eq $license})) { + if (!(Get-vRSLCMLockerLicense | Where-Object {$_.alias -eq $alias})) { + $newRequest = Add-vRSLCMLockerLicense -alias $alias -license $license + Start-Sleep 3 + $status = Watch-vRSLCMRequest -vmid $($newRequest.requestId) + if ($status -match "COMPLETED") { + if ((Get-vRSLCMLockerLicense | Where-Object {$_.key -eq $license})) { + Write-Output "Adding License to the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($alias): SUCCESSFUL" + } + else { + Write-Error "Adding License to the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($alias): POST_VALIDATION_FAILED" + } + } + else { + Write-Error "$status" + } + } + else { + Write-Warning "Adding License to the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($alias), already exists: SKIPPED" + } + } + else { + Write-Warning "Adding License to the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with license ($license), already exists: SKIPPED" + } + } + } + } + } + } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-WSADirectoryDomain +Export-ModuleMember -Function New-vRSLCMLockerLicense -Function Add-WSALdapDirectory { +Function Undo-vRSLCMLockerLicense { <# - .SYNOPSIS - Create an LDAP directory + .SYNOPSIS + Remove a license to the vRealize Suite Lifecycle Manager Locker - .DESCRIPTION - The Add-WSALdapDirectory cmdlets creates a new LDAP Active Directory connection in Workspace ONE Access + .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 + - Verifies that the license is present in the vRealize Suite Lifecycle Manager Locker + - Removes the license to the vRealize Suite Lifecycle Manager Locker + + .EXAMPLE + Undo-vRSLCMLockerLicense -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -alias "vRealize Automation" + This example removes a license with an alias of 'vRealize Automation' from the vRealize Suite Lifecycle Manager Locker + #> - .EXAMPLE - Add-WSALdapDirectory -domainName sfo.rainpole.io -baseDn "ou=VVD,dc=sfo,dc=rainpole,dc=io" -bindDn "cn=svc-wsa-ad,ou=VVD,dc=sfo,dc=rainpole,dc=io" - This example creates a new LDAP Active Directory connection in Workspace ONE Access - #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domainName, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$baseDn, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$bindDn, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$certificate + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$alias ) Try { - $wsaHeaders = @{"Content-Type" = "application/vnd.vmware.horizon.manager.connector.management.directory.ad.over.ldap+json" } - $wsaHeaders.Add("Accept", "application/vnd.vmware.horizon.manager.connector.management.directory.ad.over.ldap+json") - $wsaHeaders.Add("Authorization", "$sessionToken") - if ($PsBoundParameters.ContainsKey("certificate")){ - #read certificate file contents as certdata - $certdata = (Get-Content ($certificate)) -join "\n" - $body = '{ - "useSRV":true, - "directoryType":"ACTIVE_DIRECTORY_LDAP", - "directorySearchAttribute":"sAMAccountName", - "directoryConfigId":null, - "useGlobalCatalog":false, - "syncConfigurationEnabled":false, - "useStartTls":true, - "userAttributeMappings":[], - "name":"' + $domainName + '", - "baseDN":"' + $baseDn + '", - "bindDN":"' + $bindDn + '", - "sslCertificate":"' + $certdata + '" - }' - }else{ - $body = '{ - "useSRV":true, - "directoryType":"ACTIVE_DIRECTORY_LDAP", - "directorySearchAttribute":"sAMAccountName", - "directoryConfigId":null, - "useGlobalCatalog":false, - "syncConfigurationEnabled":false, - "useStartTls":false, - "userAttributeMappings":[], - "name":"' + $domainName + '", - "baseDN":"' + $baseDn + '", - "bindDN":"' + $bindDn + '" - }' + 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-vRSLCMLockerLicense | Where-Object {$_.alias -eq $alias}) { + Remove-vRSLCMLockerLicense -vmid (Get-vRSLCMLockerLicense | Where-Object {$_.alias -eq $alias}).vmid | Out-Null + if (Get-vRSLCMLockerLicense | Where-Object {$_.key -eq $license}) { + Write-Error "Removing License from the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($alias): POST_VALIDATION_FAILED" + } + else { + Write-Output "Removing License from the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($alias): SUCCESSFUL" + } + } + else { + Write-Warning "Removing License from the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($alias), does not exist: SKIPPED" + } + } + } + } + } } - $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/connectormanagement/directoryconfigs" - $response = Invoke-RestMethod $uri -Method 'POST' -Headers $wsaHeaders -Body $body - $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Add-WSALdapDirectory +Export-ModuleMember -Function Undo-vRSLCMLockerLicense -Function Set-WSABindPassword { +Function New-vRSLCMDatacenter { <# - .SYNOPSIS - Create an LDAP directory + .SYNOPSIS + Adds a datacenter to vRealize Suite Lifecycle Manager - .DESCRIPTION - The Set-WSABindPassword cmdlets creates a new LDAP Active Directory connection in Workspace ONE Access + .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 the datacenter has not already been created in the inventory + - Creates the datacenter in the inventory - .EXAMPLE - Set-WSABindPassword -directoryId a1c985d5-0eeb-4a66-bc51-11eda9321aac -connectorId 59ee9717-a09e-45b6-9e5f-8d92a55a1825 -password VMw@re1! - This example creates a new LDAP Active Directory connection in Workspace ONE Access - #> + .EXAMPLE + New-vRSLCMDatacenter -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -datacenterName xint-m01-dc01 -location "San Francisco, California, US" + This example adds a datacenter to the vRealize Suite Lifecycle Manager inventory + #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$directoryId, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$connectorId, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$datacenterName, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$location ) Try { - $wsaHeaders = @{"Content-Type" = "application/vnd.vmware.horizon.manager.connector.management.directory.details+json" } - $wsaHeaders.Add("Accept", "application/vnd.vmware.horizon.manager.connector.management.connector+json") - $wsaHeaders.Add("Authorization", "$sessionToken") - $body = '{"directoryId":"' + $directoryId + '","directoryBindPassword":"' + $pass + '","usedForAuthentication":true}' - $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/connectormanagement/connectorinstances/$connectorId/associatedirectory" - $response = Invoke-RestMethod $uri -Method 'POST' -Headers $wsaHeaders -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) { + if (!(Get-vRSLCMDatacenter -datacenterName $datacenterName -ErrorAction SilentlyContinue )) { + Add-vRSLCMDatacenter -datacenterName $datacenterName -location $location | Out-Null + if (Get-vRSLCMDatacenter -datacenterName $datacenterName -ErrorAction SilentlyContinue ) { + Write-Output "Adding Datacenter to the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) inventory name ($datacenterName): SUCCESSFUL" + } + else { + Write-Error "Adding Datacenter to the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) inventory name ($datacenterName): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Adding Datacenter to the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) inventory name ($datacenterName), already exists: SKIPPED" + } + } + } + } + } + } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Set-WSABindPassword +Export-ModuleMember -Function New-vRSLCMDatacenter -Function Set-WSASyncSetting { +Function New-vRSLCMDatacenterVcenter { <# - .SYNOPSIS - Set directory sync schedule + .SYNOPSIS + Adds a vCenter Server to a Datacenter to vRealize Suite Lifecycle Manager - .DESCRIPTION - The Set-WSASyncSetting cmdlets configures the directory sync schedule in Workspace ONE Access + .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 the vCenter Server has not already been added to the Datacenter + - Adds the vCenter Server to the Datacenter - .EXAMPLE - Set-WSASyncSetting -directoryId a1c985d5-0eeb-4a66-bc51-11eda9321aac - This example configures the directory sync schedule in Workspace ONE Access - #> + .EXAMPLE + New-vRSLCMDatacenterVcenter -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -datacenterName xint-m01-dc01 -vcenterFqdn sfo-m01-vc01.sfo.rainpole.io -userLockerAlias sfo-m01-vc01-sfo-m01-dc01 + This example adds a vCenter Server to a Datacenter in vRealize Suite Lifecycle Manager + #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$directoryId + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$datacenterName, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vcenterFqdn, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$userLockerAlias ) Try { - $wsaHeaders = @{"Content-Type" = "application/vnd.vmware.horizon.manager.connector.management.directory.sync.profile.syncschedule+json" } - $wsaHeaders.Add("Accept", "application/vnd.vmware.horizon.manager.connector.management.directory.sync.profile.syncschedule+json") - $wsaHeaders.Add("Authorization", "$sessionToken") - $body = '{"frequency":"fifteenMinutes"}' - $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/connectormanagement/directoryconfigs/$directoryId/syncprofile" - Invoke-RestMethod $uri -Method 'PUT' -Headers $wsaHeaders -Body $body + 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-vRSLCMDatacenter -datacenterName $datacenterName -ErrorAction SilentlyContinue ) { + if (Get-vRSLCMLockerPassword | Where-Object {$_.alias -eq $userLockerAlias}) { + if (!(Get-vRSLCMDatacenterVcenter -datacenterVmid (Get-vRSLCMDatacenter -datacenterName $datacenterName).datacenterVmid -vcenterName ($vcenterFqdn.Split(".")[0]) -ErrorAction SilentlyContinue)) { + Add-vRSLCMDatacenterVcenter -datacenterVmid (Get-vRSLCMDatacenter -datacenterName $datacenterName).datacenterVmid -vcenterFqdn $vcenterFqdn -userLockerAlias $userLockerAlias | Out-Null + Start-Sleep 5 + if (Get-vRSLCMDatacenterVcenter -datacenterVmid (Get-vRSLCMDatacenter -datacenterName $datacenterName).datacenterVmid -vcenterName ($vcenterFqdn.Split(".")[0]) -ErrorAction SilentlyContinue) { + Write-Output "Adding vCenter Server to Datacenter ($datacenterName) in vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) named ($($vcenterFqdn.Split(".")[0])): SUCCESSFUL" + } + else { + Write-Error "Adding vCenter Server to Datacenter ($datacenterName) in vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) named ($($vcenterFqdn.Split(".")[0])): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Adding vCenter Server to Datacenter ($datacenterName) in vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) named ($($vcenterFqdn.Split(".")[0])), already exists: SKIPPED" + } + } + else { + Write-Error "Unable to find Password alias in vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) named ($userLockerAlias): PRE_VALIDATION_FAILED" + } + } + else { + Write-Error "Unable to find Datacenter named ($datacenterName) in vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)): PRE_VALIDATION_FAILED" + } + } + } + } + } + } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Set-WSASyncSetting +Export-ModuleMember -Function New-vRSLCMDatacenterVcenter -Function Start-WSADirectorySync { +Function Undo-vRSLCMDatacenter { <# - .SYNOPSIS - Start an directory sync + .SYNOPSIS + Deletes a datacenter from vRealize Suite Lifecycle Manager - .DESCRIPTION - The Start-WSADirectorySync cmdlets triggers a directory sync in Workspace ONE Access + .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 the datacenter has not already been removed from the inventory + - Deletes the datacenter from the inventory - .EXAMPLE - Start-WSADirectorySync -directoryId a1c985d5-0eeb-4a66-bc51-11eda9321aac - This example starts a directory sync in Workspace ONE Access - #> + .EXAMPLE + Undo-vRSLCMDatacenter -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -datacenterName xint-m01-dc01 + This example deletes a datacenter from the vRealize Suite Lifecycle Manager inventory + #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$directoryId + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$datacenterName ) Try { - $wsaHeaders = @{"Content-Type" = "application/vnd.vmware.horizon.manager.connector.management.directory.sync.profile.sync+json" } - $wsaHeaders.Add("Accept", "application/vnd.vmware.horizon.v1.0+json") - $wsaHeaders.Add("Authorization", "$sessionToken") - $body = '{"ignoreSafeguards":true}' - $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/connectormanagement/directoryconfigs/$directoryId/syncprofile/sync" - Invoke-RestMethod $uri -Method 'POST' -Headers $wsaHeaders -Body $body - } - Catch { - Write-Error $_.Exception.Message - } -} -Export-ModuleMember -Function Start-WSADirectorySync - -Function Set-WSADirectoryUser { + 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-vRSLCMDatacenter -datacenterName $datacenterName -ErrorAction SilentlyContinue ) { + Remove-vRSLCMDatacenter -datacenterVmid ((Get-vRSLCMDatacenter -datacenterName $datacenterName).datacenterVmid) | Out-Null + Start-Sleep 2 + if (!(Get-vRSLCMDatacenter -datacenterName $datacenterName -ErrorAction SilentlyContinue )) { + Write-Output "Removing Datacenter from the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) inventory named ($datacenterName): SUCCESSFUL" + } + else { + Write-Error "Removing Datacenter from the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) inventory named ($datacenterName): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Removing Datacenter from the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) inventory named ($datacenterName), does not exist: SKIPPED" + } + } + } + } + } + } + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Undo-vRSLCMDatacenter + +Function Add-VmGroup { <# .SYNOPSIS - Add users to directory + Add a VM Group .DESCRIPTION - The Set-WSADirectoryUser cmdlets configures the user/ou that should be sycncronised for Workspace ONE Access + 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 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 - Set-WSADirectoryUser -directoryId a1c985d5-0eeb-4a66-bc51-11eda9321aac -json (Get-Content -Raw .\adUsers.json) - This example configures the user/ou that should be sycncronised for Workspace ONE Access + .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" + This example adds the vRealize Automation cluster VMs to the VM Group called primary_az_vmgroup #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$directoryId, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$json + [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]$name, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vmList ) Try { - $wsaHeaders = @{"Content-Type" = "application/vnd.vmware.horizon.manager.connector.management.directory.sync.profile.users+json" } - $wsaHeaders.Add("Accept", "application/vnd.vmware.horizon.manager.connector.management.directory.sync.profile.users+json") - $wsaHeaders.Add("Authorization", "$sessionToken") - $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/connectormanagement/directoryconfigs/$directoryId/syncprofile" - Invoke-RestMethod $uri -Method 'PUT' -Headers $wsaHeaders -Body $json + 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 { - Write-Error $_.Exception.Message + Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Set-WSADirectoryUser +Export-ModuleMember -Function Add-VmGroup -Function Set-WSADirectoryGroup { +Function Add-WorkspaceOneDirectoryGroup { <# .SYNOPSIS - Add groups to directory + Adds Active Directory Group to sync in Workspace ONE Access Appliance .DESCRIPTION - The Set-WSADirectoryGroup cmdlets configures the groups/ou that should be sycncronised for Workspace ONE Access + The Add-WorkspaceOneDirectoryGroup cmdlet adds an Active Directory Group to sync in Workspace ONE Access Appliance .EXAMPLE - Set-WSADirectoryUser -directoryId a1c985d5-0eeb-4a66-bc51-11eda9321aac -json (Get-Content -Raw .\adGroups.json) - This example configures the groups/ou that should be sycncronised for Workspace ONE Access + 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 #> - Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$directoryId, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$json + 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 { - $wsaHeaders = @{"Content-Type" = "application/vnd.vmware.horizon.manager.connector.management.directory.sync.profile.groups+json" } - $wsaHeaders.Add("Accept", "application/vnd.vmware.horizon.manager.connector.management.directory.sync.profile.groups+json") - $wsaHeaders.Add("Authorization", "$sessionToken") - $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/connectormanagement/directoryconfigs/$directoryId/syncprofile" - $response = Invoke-RestMethod $uri -Method 'PUT' -Headers $wsaHeaders -Body $json - $response + 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) { + $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" + } + } + $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 $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" + } + else { + Write-Error "Active Directory 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" + } + } + } } Catch { - Write-Error $_.Exception.Message + Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Set-WSADirectoryGroup +Export-ModuleMember -Function Add-WorkspaceOneDirectoryGroup -Function Get-WSASmtpConfiguration { +Function Add-WorkspaceOneDirectoryConnector { <# .SYNOPSIS - Get SMTP configuration + Adds a connector to the directory in Workspace ONE Access Appliance - .DESCRIPTION - The Get-WSASmtpConfiguration cmdlets retrieves the SMTP configurtion of Workspace ONE Access + .DESCRIPTION + The Add-WorkspaceOneDirectoryConnector cmdlet adds a connector to the directory in Workspace ONE Access Appliance - .EXAMPLE - Get-WSASmtpConfiguration - This example gets the current SMTP configuration of Workspace ONE Access - #> + .EXAMPLE + Add-WorkspaceOneDirectoryConnector -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo.rainpole.io -wsaNode xint-wsa01b.rainpole.io -wsaUser admin -wsaPass VMw@re1! -bindUserPass VMw@re1! + 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]$wsaNode, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaUser, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaPass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$bindUserPass + ) Try { - $wsaHeaders = @{"Accept" = "application/json, text/plain, */*" } - $wsaHeaders.Add("Authorization", "$sessionToken") - $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/system/config/smtp" - $response = Invoke-RestMethod $uri -Headers $wsaHeaders - $response + if (Test-VCFConnection -server $server) { + if (Test-VCFAuthentication -server $server -user $user -pass $pass) { + if (($vcfWsaDetails = Get-WSAServerDetail -fqdn $server -username $user -password $pass)) { + if (Test-WSAConnection -server $vcfWsaDetails.loadBalancerFqdn) { + if (Test-WSAAuthentication -server $vcfWsaDetails.loadBalancerFqdn -user $wsaUser -pass $wsaPass) { + if ($directoryId = (Get-WSADirectory | Where-Object {$_.name -eq $domain}).directoryId) { + if (Get-WSAConnector | Where-Object {$_.host -eq $wsaNode}) { + if (!(Get-WSADirectory -directoryId $directoryId -connector | Where-Object {$_.host -eq $wsaNode})) { + Add-WSAConnector -wsaNode $wsaNode -domain $domain -bindUserPass $bindUserPass | Out-Null + if (Get-WSADirectory -directoryId $directoryId -connector | Where-Object {$_.host -eq $wsaNode}) { + Write-Output "Adding Connector to Directory ($domain) in Workspace ONE Access ($($vcfWsaDetails.loadBalancerFqdn)) named ($wsaNode): SUCCESSFUL" + } + else { + Write-Error "Adding Connector to Directory ($domain) in Workspace ONE Access ($($vcfWsaDetails.loadBalancerFqdn)) named ($wsaNode): POST_VALIDATION_FAILED" + } + } + else { + Write-Warning "Adding Connector to Directory ($domain) in Workspace ONE Access ($($vcfWsaDetails.loadBalancerFqdn)) named ($wsaNode), already exists: SKIPPED" + } + } + else { + Write-Error "Unable to find node in Workspace ONE Access ($($vcfWsaDetails.loadBalancerFqdn)) named ($wsaNode): PRE_VALIDATION_FAILED" + } + } + else { + Write-Error "Unable to find Active Directory domain in Workspace ONE Access ($($vcfWsaDetails.loadBalancerFqdn)) named ($domain): PRE_VALIDATION_FAILED" + } + } + } + } + } + } } Catch { - Write-Error $_.Exception.Message + Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Get-WSASmtpConfiguration +Export-ModuleMember -Function Add-WorkspaceOneDirectoryConnector -Function Set-WSASmtpConfiguration { +########################################## E N D O F F U N C T I O N S ########################################## +####################################################################################################################### + + +####################################################################################################################### +##################################### S U P P O R T I N G F U N C T I O N S ###################################### + +############################################################## +############# Begin Active Directory Functions ############# + +Function Test-ADAuthentication { <# - .SYNOPSIS - Set SMTP configuration + .SYNOPSIS + Test authetication against Active Directory - .DESCRIPTION - The Set-WSASmtpConfiguration cmdlets configures the SMTP configurtion of Workspace ONE Access + .DESCRIPTION + The Test-ADAuthentication cmdlet tests the credentials provided against Active Directory domain - .EXAMPLE - Set-WSASmtpConfiguration - This example sets the SMTP configuration of Workspace ONE Access - #> + .EXAMPLE + Test-ADAuthentication -user svc-vsphere-ad -pass VMw@re1! -server sfo.rainpole.io -domain sfo.rainpole.io + This example check that the svc-vsphere-ad user can authenticate to the sfo.rainpole.io domain + #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$fqdn, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$port, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$pass + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $false)] [String]$server, + [Parameter (Mandatory = $false)] [String]$domain = $env:USERDOMAIN ) Try { - $wsaHeaders = @{"Accept" = "application/json, text/plain, */*" } - $wsaHeaders.Add("Content-Type", "application/vnd.vmware.horizon.manager.system.config.smtp+json") - $wsaHeaders.Add("Authorization", "$sessionToken") - if (-not $PsBoundParameters.ContainsKey("pass")) { - $body = '{ "host": "' + $fqdn + '", "port": ' + $port + ', "user": "' + $user + '", "password": "' + $pass + '"}' + Add-Type -AssemblyName System.DirectoryServices.AccountManagement + $contextType = [System.DirectoryServices.AccountManagement.ContextType]::Domain + $argumentList = New-Object -TypeName "System.Collections.ArrayList" + $null = $argumentList.Add($contextType) + $null = $argumentList.Add($domain) + if ($null -ne $server) { + $argumentList.Add($server) + } + $principalContext = New-Object System.DirectoryServices.AccountManagement.PrincipalContext -ArgumentList $argumentList -ErrorAction SilentlyContinue + if ($null -eq $principalContext) { + Write-Error "$domain\$user - AD Authentication Failed" + } + if ($principalContext.ValidateCredentials($user, $pass)) { + Write-Output "$domain\$user - AD Authentication Successful" } else { - $body = '{ "host": "' + $fqdn + '", "port": ' + $port + ', "user": "' + $user + '" }' + Write-Error "$domain\$user - AD Authentication Failed" } - $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/system/config/smtp" - $response = Invoke-RestMethod $uri -Method 'PUT' -Headers $wsaHeaders -Body $body - $response } Catch { - Write-Error $_.Exception.Message + Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Set-WSASmtpConfiguration +Export-ModuleMember -Function Test-ADAuthentication -Function Set-WSARoleMember { +Function Get-ADPrincipalGuid { <# - .SYNOPSIS - Set WSA Role Member + .SYNOPSIS + Get principal GUID details - .DESCRIPTION - The Set-WSARoleMember cmdlets updates the Role with the given group + .DESCRIPTION + The Get-ADPrincipalGuid cmdlet retrieves the GUID details for an active directory user or group Active Directory domain - .EXAMPLE - Set-WSARoleMember -id 55048dee-fe1b-404a-936d-3e0b86a7209e -groupId fe515568-fdcd-43c7-9971-e834d7246203 - This example updates the Role with the given GroupId in Workspace ONE Access - #> + .EXAMPLE + Get-ADPrincipalGuid -domain sfo.rainple.io -user svc-vsphere-ad -pass VMw@re1! -principal gg-sso-admin + This example retrives the details for th gg-sso-admin domain + #> - Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$groupId + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$principal ) - Try { - $wsaHeaders = @{"Content-Type" = "application/json" } - $wsaHeaders.Add("Authorization", "$sessionToken") - if ($PsBoundParameters.ContainsKey("id")) { - $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/scim/Roles/$id" - - $json = @" - { - "schemas": [ - "urn:scim:schemas:core:1.0" - ], - "members": [ - { - "value": "$groupId", - "type": "Group" - } - ] - } -"@ - $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -body $json -headers $wsaHeaders - $response - } - } + Try { + $checkAdAuthentication = Test-ADAuthentication -user $user -pass $pass -server $domain -domain $domain + if ($checkAdAuthentication -contains "2") { + $securePassword = ConvertTo-SecureString -String $pass -AsPlainText -Force + $creds = New-Object System.Management.Automation.PSCredential ($user, $securePassword) + $nsxAdminGroupObject = (Get-ADGroup -Server $domain -Credential $creds -Filter { SamAccountName -eq $principal }) + $nsxAdminGroupObject + } + else { + Write-Error "Domain User $user Authentication Failed" + } + } Catch { - Write-Error $_.Exception.Message + Debug-ExceptionWriter -object $_ } } +Export-ModuleMember -Function Get-ADPrincipalGuid -Function Get-WSARole { - <# - .SYNOPSIS - Get roles +############## End Active Directory Functions ############## +############################################################## - .DESCRIPTION - The Get-WSARole cmdlets retrieves the roles in Workspace ONE Access - .EXAMPLE - Get-WSARole - This example retrieves the roles in Workspace ONE Access - #> +############################################################## +############# Begin Cloud Foundation Functions ############# +Function Get-vCenterServerDetail { Param ( - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id + [Parameter (Mandatory = $false)] [String]$server, + [Parameter (Mandatory = $false)] [String]$user, + [Parameter (Mandatory = $false)] [String]$pass, + [Parameter (Mandatory = $false)] [ValidateSet("MANAGEMENT", "VI")][String]$domainType, + [Parameter (Mandatory = $false)] [String]$domain ) Try { - $wsaHeaders = @{"Content-Type" = "application/json" } - $wsaHeaders.Add("Authorization", "$sessionToken") - if ($PsBoundParameters.ContainsKey("id")) { - $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/scim/Roles/$id" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders - $response + if (!$PsBoundParameters.ContainsKey("user") -or (!$PsBoundParameters.ContainsKey("pass"))) { + # Request Credentials + $creds = Get-Credential + $user = $creds.UserName.ToString() + $pass = $creds.GetNetworkCredential().password + } + if (!$PsBoundParameters.ContainsKey("server")) { + $server = Read-Host "SDDC Manager access token not found. Please enter the SDDC Manager FQDN, e.g., sfo-vcf01.sfo.rainpole.io" + } + Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null + + if ($accessToken) { + if ($PsBoundParameters.ContainsKey("domainType")) { + # Dynamically build vCenter Server details based on Cloud Foundation domain type + $vcfWorkloadDomainDetails = Get-VCFWorkloadDomain | Where-Object { $_.type -eq $domainType } + } + if ($PsBoundParameters.ContainsKey("domain")) { + # Dynamically build vCenter Server details based on Cloud Foundation domain name + $vcfWorkloadDomainDetails = Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain } + } + if ($vcfWorkloadDomainDetails) { + $vcenterServerDetails = Get-VCFvCenter | Where-Object { $_.id -eq $($vcfWorkloadDomainDetails.vcenters.id) } + $vcenterCredentialDetails = Get-VCFCredential | Where-Object { $_.resource.resourceId -eq $($vcenterServerDetails.id) } + $pscCredentialDetails = Get-VCFCredential | Where-Object { $_.resource.resourceType -eq "PSC" } + $vcenterServer = New-Object -TypeName psobject + $vcenterServer | Add-Member -notepropertyname 'fqdn' -notepropertyvalue $vcenterServerDetails.fqdn + $vcenterServer | Add-Member -notepropertyname 'vmName' -notepropertyvalue $vcenterServerDetails.fqdn.Split(".")[0] + $vcfDetail = Get-VCFManager + if ( ($vcfDetail.version).Split("-")[0] -gt "4.1.0.0") { + $vcenterServer | Add-Member -notepropertyname 'ssoAdmin' -notepropertyvalue ($pscCredentialDetails | Where-Object { ($_.credentialType -eq "SSO" -and $_.accountType -eq "SYSTEM") }).username + $vcenterServer | Add-Member -notepropertyname 'ssoAdminPass' -notepropertyvalue ($pscCredentialDetails | Where-Object { ($_.credentialType -eq "SSO" -and $_.accountType -eq "SYSTEM") }).password + } + else { + $vcenterServer | Add-Member -notepropertyname 'ssoAdmin' -notepropertyvalue ($pscCredentialDetails | Where-Object { ($_.credentialType -eq "SSO" -and $_.accountType -eq "USER") }).username + $vcenterServer | Add-Member -notepropertyname 'ssoAdminPass' -notepropertyvalue ($pscCredentialDetails | Where-Object { ($_.credentialType -eq "SSO" -and $_.accountType -eq "USER") }).password + } + $vcenterServer | Add-Member -notepropertyname 'root' -notepropertyvalue ($vcenterCredentialDetails | Where-Object { ($_.credentialType -eq "SSH" -and $_.accountType -eq "USER") }).username + $vcenterServer | Add-Member -notepropertyname 'rootPass' -notepropertyvalue ($vcenterCredentialDetails | Where-Object { ($_.credentialType -eq "SSH" -and $_.accountType -eq "USER") }).password + $vcenterServer + } + else { + Write-Error "Unable to find Workload Domain type or domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED" + } } else { - $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/scim/Roles" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders - $response.Resources + Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials" } } Catch { - Write-Error $_.Exception.Message + Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Get-WSARole - -Function Get-WSAGroup { - <# - .SYNOPSIS - Get groups - - .DESCRIPTION - The Get-WSAGroup cmdlets retrieves the groups in Workspace ONE Access - - .EXAMPLE - Get-WSAGroup - This example retrieves the groups in Workspace ONE Access - #> +Export-ModuleMember -Function Get-vCenterServerDetail +Function Get-NsxtServerDetail { Param ( - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id + [Parameter (Mandatory = $false)] [String]$fqdn, + [Parameter (Mandatory = $false)] [String]$username, + [Parameter (Mandatory = $false)] [String]$password, + [Parameter (Mandatory = $false)] [String]$domain, + [Parameter( Mandatory = $false)] [ValidateSet("MANAGEMENT", "VI")] [String]$domainType, + [Parameter (Mandatory = $false)] [switch]$listNodes = $false ) Try { - $wsaHeaders = @{"Content-Type" = "application/json" } - $wsaHeaders.Add("Authorization", "$sessionToken") - if ($PsBoundParameters.ContainsKey("id")) { - $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/scim/Groups/$id" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders - $response + if (!$PsBoundParameters.ContainsKey("username") -or (!$PsBoundParameters.ContainsKey("password"))) { + # Request Credentials + $creds = Get-Credential + $username = $creds.UserName.ToString() + $password = $creds.GetNetworkCredential().password + } + if (!$PsBoundParameters.ContainsKey("fqdn")) { + $fqdn = Read-Host "SDDC Manager access token not found. Please enter the SDDC Manager FQDN, e.g., sfo-vcf01.sfo.rainpole.io" + } + Request-VCFToken -fqdn $fqdn -Username $username -Password $password | Out-Null + + if ($accessToken) { + if ($PsBoundParameters.ContainsKey("domainType")) { + # Dynamically build vCenter Server details based on Cloud Foundation domain type + $vcfWorkloadDomainDetails = Get-VCFWorkloadDomain | Where-Object { $_.type -eq $domainType } + } + if ($PsBoundParameters.ContainsKey("domain")) { + # Dynamically build vCenter Server details based on Cloud Foundation domain name + $vcfWorkloadDomainDetails = Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain } + } + if ($vcfWorkloadDomainDetails) { + $nsxtServerDetails = Get-VCFNsxtcluster | Where-Object { $_.id -eq $($vcfWorkloadDomainDetails.nsxtCluster.id) } + $nsxtCreds = Get-VCFCredential | Where-Object { $_.resource.resourceId -eq $($nsxtServerDetails.id) } + + $nsxtCluster = New-Object -TypeName PSCustomObject + $nsxtCluster | Add-Member -notepropertyname 'fqdn' -notepropertyvalue $nsxtServerDetails.vipFqdn + $nsxtCluster | Add-Member -notepropertyname 'adminUser' -notepropertyvalue ($nsxtCreds | Where-Object { ($_.credentialType -eq "API" -and $_.accountType -eq "SYSTEM") }).username + $nsxtCluster | Add-Member -notepropertyname 'adminPass' -notepropertyvalue ($nsxtCreds | Where-Object { ($_.credentialType -eq "API" -and $_.accountType -eq "SYSTEM") }).password + $nsxtCluster | Add-Member -notepropertyname 'rootUser' -notepropertyvalue ($nsxtCreds | Where-Object { ($_.credentialType -eq "SSH" -and $_.accountType -eq "SYSTEM") }).username + $nsxtCluster | Add-Member -notepropertyname 'rootPass' -notepropertyvalue ($nsxtCreds | Where-Object { ($_.credentialType -eq "SSH" -and $_.accountType -eq "SYSTEM") }).password + if ($listNodes) { + $nsxtCluster | Add-Member -notepropertyname 'nodes' -notepropertyvalue $nsxtServerDetails.nodes + } + $nsxtCluster + } + else { + Write-Error "Workload domainType or domain name does not exist" + Break + } } else { - $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/scim/Groups" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders - $response.Resources + Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials" + Break } } Catch { - Write-Error $_.Exception.Message + Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Get-WSAGroup - -Function Get-WSAUser { - <# - .SYNOPSIS - Get users - - .DESCRIPTION - The Get-WSAUser cmdlets retrieves the users in Workspace ONE Access - - .EXAMPLE - Get-WSAUser - This example retrieves the users in Workspace ONE Access - #> +Export-ModuleMember -Function Get-NsxtServerDetail +Function Get-vRSLCMServerDetail { Param ( - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id + [Parameter (Mandatory = $false)] [String]$fqdn, + [Parameter (Mandatory = $false)] [String]$username, + [Parameter (Mandatory = $false)] [String]$password ) Try { - $wsaHeaders = @{"Content-Type" = "application/json" } - $wsaHeaders.Add("Authorization", "$sessionToken") - if ($PsBoundParameters.ContainsKey("id")) { - $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/scim/Users/$id" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders - $response + if (!$PsBoundParameters.ContainsKey("username") -or (!$PsBoundParameters.ContainsKey("password"))) { + # Request Credentials + $creds = Get-Credential + $username = $creds.UserName.ToString() + $password = $creds.GetNetworkCredential().password } - else { - $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/scim/Users" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders - $response.Resources + if (!$PsBoundParameters.ContainsKey("fqdn")) { + $fqdn = Read-Host "SDDC Manager access token not found. Please enter the SDDC Manager FQDN, e.g., sfo-vcf01.sfo.rainpole.io" + } + + if (Test-VCFConnection -server $fqdn) { + if (Test-VCFAuthentication -server $fqdn -user $username -pass $password) { + if (Get-VCFvRSLCM) { + # Get vRSLCM Server Details + $vRSLCMFQDN = Get-VCFvRSLCM + $vRSLCMCreds = Get-VCFCredential -resourceName $vRSLCMFQDN.fqdn + $vrslcmDetails = New-Object -TypeName PSCustomObject + $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 + } + else { + Write-Error "Unable to obtain vRealize Suite Lifecycle Manager details from SDDC Manager ($fqdn), check deployment status: PRE_VALIDATION_FAILED" + } + } } } Catch { - Write-Error $_.Exception.Message + Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Get-WSAUser - -Function Get-WSARuleSet { - <# - .SYNOPSIS - Get rulesets - - .DESCRIPTION - The Get-WSARuleSet cmdlets retrieves the rulesets in Workspace ONE Access +Export-ModuleMember -Function Get-vRSLCMServerDetail - .EXAMPLE - Get-WSARuleSet - This example retrieves the rulesets in Workspace ONE Access - #> +Function Get-WSAServerDetail { + Param ( + [Parameter (Mandatory = $false)] [String]$fqdn, + [Parameter (Mandatory = $false)] [String]$username, + [Parameter (Mandatory = $false)] [String]$password + ) Try { - $wsaHeaders = @{"Accept-Type" = "application/json, text/plain, */*" } - $wsaHeaders.Add("Content-Type", "application/vnd.vmware.vidm.accesscontrol.ruleset.list+json") - $wsaHeaders.Add("Authorization", "$sessionToken") - $uri = "https://$workSpaceOne/acs/rulesets" - $response = Invoke-RestMethod $uri -Headers $wsaHeaders - $response.items + if (!$PsBoundParameters.ContainsKey("username") -or (!$PsBoundParameters.ContainsKey("password"))) { + # Request Credentials + $creds = Get-Credential + $username = $creds.UserName.ToString() + $password = $creds.GetNetworkCredential().password + } + if (!$PsBoundParameters.ContainsKey("fqdn")) { + $fqdn = Read-Host "SDDC Manager access token not found. Please enter the SDDC Manager FQDN, e.g., sfo-vcf01.sfo.rainpole.io" + } + + if (Test-VCFConnection -server $fqdn) { + if (Test-VCFAuthentication -server $fqdn -user $username -pass $password) { + if (Get-VCFvRA) { + $vcfWsaDetails = Get-VCFWSA + #$wsaCreds = Get-VCFCredential -resourceName $vcfWsaDetails.fqdn + $wsaDetails = New-Object -TypeName PSCustomObject + $wsaDetails | Add-Member -notepropertyname 'fqdn' -notepropertyvalue $vcfWsaDetails.nodes.fqdn + $wsaDetails | Add-Member -notepropertyname 'loadBalancerIpAddress' -notepropertyvalue $vcfWsaDetails.loadBalancerIpAddress + $wsaDetails | Add-Member -notepropertyname 'loadBalancerFqdn' -notepropertyvalue $vcfWsaDetails.loadBalancerFqdn + $wsaDetails | Add-Member -notepropertyname 'node1IpAddress' -notepropertyvalue $vcfWsaDetails.nodes.ipAddress[0] + $wsaDetails | Add-Member -notepropertyname 'node2IpAddress' -notepropertyvalue $vcfWsaDetails.nodes.ipAddress[1] + $wsaDetails | Add-Member -notepropertyname 'node3IpAddress' -notepropertyvalue $vcfWsaDetails.nodes.ipAddress[2] + $wsaDetails + } + else { + Write-Error "Unable to obtain Workspace ONE Access details from SDDC Manager ($fqdn), check deployment status: PRE_VALIDATION_FAILED" + } + } + } } Catch { - Write-Error $_.Exception.Message + Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Get-WSARuleSet +Export-ModuleMember -Function Get-WSAServerDetail -Function Get-WSAOAuthToken { +Function Get-vRAServerDetail { + Param ( + [Parameter (Mandatory = $false)] [String]$fqdn, + [Parameter (Mandatory = $false)] [String]$username, + [Parameter (Mandatory = $false)] [String]$password + ) + + Try { + if (!$PsBoundParameters.ContainsKey("username") -or (!$PsBoundParameters.ContainsKey("password"))) { + # Request Credentials + $creds = Get-Credential + $username = $creds.UserName.ToString() + $password = $creds.GetNetworkCredential().password + } + if (!$PsBoundParameters.ContainsKey("fqdn")) { + $fqdn = Read-Host "SDDC Manager access token not found. Please enter the SDDC Manager FQDN, e.g., sfo-vcf01.sfo.rainpole.io" + } + + if (Test-VCFConnection -server $fqdn) { + if (Test-VCFAuthentication -server $fqdn -user $username -pass $password) { + if (Get-VCFvRA) { + $vcfVraDetails = Get-VCFvRA + $vraCreds = Get-VCFCredential -resourceName $vcfVraDetails.loadBalancerFqdn + $vraDetails = New-Object -TypeName PSCustomObject + $vraDetails | Add-Member -notepropertyname 'fqdn' -notepropertyvalue $vcfVraDetails.nodes.fqdn + $vraDetails | Add-Member -notepropertyname 'loadBalancerIpAddress' -notepropertyvalue $vcfVraDetails.loadBalancerIpAddress + $vraDetails | Add-Member -notepropertyname 'loadBalancerFqdn' -notepropertyvalue $vcfVraDetails.loadBalancerFqdn + $vraDetails | Add-Member -notepropertyname 'node1IpAddress' -notepropertyvalue $vcfVraDetails.nodes.ipAddress[0] + $vraDetails | Add-Member -notepropertyname 'node2IpAddress' -notepropertyvalue $vcfVraDetails.nodes.ipAddress[1] + $vraDetails | Add-Member -notepropertyname 'node3IpAddress' -notepropertyvalue $vcfVraDetails.nodes.ipAddress[2] + $vraDetails + } + else { + Write-Error "Unable to obtain vRealize Automation details from SDDC Manager ($fqdn), check deployment status: PRE_VALIDATION_FAILED" + } + } + } + } + Catch { + Debug-ExceptionWriter -object $_ + } +} +Export-ModuleMember -Function Get-vRAServerDetail + +Function Get-vROPsServerDetail { <# .SYNOPSIS - Get AOuth Token + Gather details about vRealize Operations Manager .DESCRIPTION - The Get-WSAOAuthToken cmdlets gets an OAuth token from Workspace ONE Access + The Get-vROPsServerDetail cmdlet connects to SDDC Manager and gathers details about vRealize Operations Manager + from the SDDC Manager inventory. .EXAMPLE - Get-WSAOAuthToken - This example retrieves the am OAuth oken from Workspace ONE Access + Get-vROPsServerDetail -fqdn sfo-vcf01.sfo.rainpole.io -username administrator@vsphere.local -password VMw@re1! + This example gathers details about vRealize Opertations Manager #> + Param ( + [Parameter (Mandatory = $false)] [String]$fqdn, + [Parameter (Mandatory = $false)] [String]$username, + [Parameter (Mandatory = $false)] [String]$password + ) + Try { - $wsaHeaders = @{"Content-Type" = "application/x-www-form-urlencoded; charset=UTF-8" } - $wsaHeaders.Add("Accept", "application/json, text/javascript, */*; q=0.01") - $wsaHeaders.Add("Authorization", "$sessionToken") - $uri = "https://$workSpaceOne/SAAS/admin/settings/OAuthClient/generateRandomOAuthSecret" - $response = Invoke-RestMethod $uri -Method 'POST' -Headers $wsaHeaders - $response + if (!$PsBoundParameters.ContainsKey("username") -or (!$PsBoundParameters.ContainsKey("password"))) { + # Request Credentials + $creds = Get-Credential + $username = $creds.UserName.ToString() + $password = $creds.GetNetworkCredential().password + } + if (!$PsBoundParameters.ContainsKey("fqdn")) { + $fqdn = Read-Host "SDDC Manager access token not found. Please enter the SDDC Manager FQDN, e.g., sfo-vcf01.sfo.rainpole.io" + } + + if (Test-VCFConnection -server $fqdn) { + if (Test-VCFAuthentication -server $fqdn -user $username -pass $password) { + if (Get-VCFvROPS) { + $vcfVropsDetails = Get-VCFvROPs + $vropsCreds = Get-VCFCredential -resourceName $vcfVropsDetails.loadBalancerFqdn + $vropsDetails = New-Object -TypeName PSCustomObject + $vropsDetails | Add-Member -notepropertyname 'fqdn' -notepropertyvalue $vcfVropsDetails.nodes.fqdn + $vropsDetails | Add-Member -notepropertyname 'loadBalancerIpAddress' -notepropertyvalue $vcfVropsDetails.loadBalancerIp + $vropsDetails | Add-Member -notepropertyname 'loadBalancerFqdn' -notepropertyvalue $vcfVropsDetails.loadBalancerFqdn + $vropsNode1FQDN = $vcfVropsDetails.nodes.fqdn[0] + $vropsNode1IP = [System.Net.Dns]::GetHostAddresses("$vropsNode1FQDN").IPAddressToString + $vropsDetails | Add-Member -notepropertyname 'node1IpAddress' -notepropertyvalue $vropsNode1IP + $vropsNode2FQDN = $vcfVropsDetails.nodes.fqdn[1] + $vropsNode2IP = [System.Net.Dns]::GetHostAddresses("$vropsNode2FQDN").IPAddressToString + $vropsDetails | Add-Member -notepropertyname 'node2IpAddress' -notepropertyvalue $vropsNode2IP + $vropsNode3FQDN = $vcfVropsDetails.nodes.fqdn[2] + $vropsNode3IP = [System.Net.Dns]::GetHostAddresses("$vropsNode3FQDN").IPAddressToString + $vropsDetails | Add-Member -notepropertyname 'node3IpAddress' -notepropertyvalue $vropsNode3IP + $vropsDetails | Add-Member -notepropertyname 'adminUser' -notepropertyvalue $vropsCreds.username + $vropsDetails | Add-Member -notepropertyname 'adminPass' -notepropertyvalue $vropsCreds.password + $vropsDetails + } + else { + Write-Error "Unable to obtain vRealize Operations Manager details from SDDC Manager ($fqdn), check deployment status: PRE_VALIDATION_FAILED" + } + } + } } Catch { - Write-Error $_.Exception.Message + Debug-ExceptionWriter -object $_ } } -Export-ModuleMember -Function Get-WSAOAuthToken +Export-ModuleMember -Function Get-vROPsServerDetail -Function Get-WSAClient { +Function Get-vRLIServerDetail { + Param ( + [Parameter (Mandatory = $false)] [String]$fqdn, + [Parameter (Mandatory = $false)] [String]$username, + [Parameter (Mandatory = $false)] [String]$password + ) + + Try { + if (!$PsBoundParameters.ContainsKey("username") -or (!$PsBoundParameters.ContainsKey("password"))) { + # Request Credentials + $creds = Get-Credential + $username = $creds.UserName.ToString() + $password = $creds.GetNetworkCredential().password + } + if (!$PsBoundParameters.ContainsKey("fqdn")) { + $fqdn = Read-Host "SDDC Manager access token not found. Please enter the SDDC Manager FQDN, e.g., sfo-vcf01.sfo.rainpole.io" + } + + if (Test-VCFConnection -server $fqdn) { + if (Test-VCFAuthentication -server $fqdn -user $username -pass $password) { + if (Get-VCFvRLI) { + $vrliVcfDetail = Get-VCFvRLI + $vrliCreds = Get-VCFCredential -resourceName $vrliVcfDetail.loadBalancerFqdn + $vrliDetail = New-Object -TypeName PSCustomObject + $vrliDetail | Add-Member -notepropertyname 'fqdn' -notepropertyvalue $vrliVcfDetail.loadBalancerFqdn + $vrliDetail | Add-Member -notepropertyname 'loadBalancerIpAddress' -notepropertyvalue $vrliVcfDetail.loadBalancerIpAddress + $vrliDetail | Add-Member -notepropertyname 'node1IpAddress' -notepropertyvalue $vrliVcfDetail.nodes.ipAddress[0] + $vrliDetail | Add-Member -notepropertyname 'node2IpAddress' -notepropertyvalue $vrliVcfDetail.nodes.ipAddress[1] + $vrliDetail | Add-Member -notepropertyname 'node3IpAddress' -notepropertyvalue $vrliVcfDetail.nodes.ipAddress[2] + $vrliDetail | Add-Member -notepropertyname 'node1Fqdn' -notepropertyvalue $vrliVcfDetail.nodes.fqdn[0] + $vrliDetail | Add-Member -notepropertyname 'node2Fqdn' -notepropertyvalue $vrliVcfDetail.nodes.fqdn[1] + $vrliDetail | Add-Member -notepropertyname 'node3Fqdn' -notepropertyvalue $vrliVcfDetail.nodes.fqdn[2] + $vrliDetail | Add-Member -notepropertyname 'adminUser' -notepropertyvalue $vrliCreds.username + $vrliDetail | Add-Member -notepropertyname 'adminPass' -notepropertyvalue $vrliCreds.password + $vrliDetail + } + else { + Write-Error "Unable to obtain vRealize Log Insight details from SDDC Manager ($fqdn), check deployment status: PRE_VALIDATION_FAILED" + } + } + } + } + Catch { + Debug-ExceptionWriter -object $_ + } +} +Export-ModuleMember -Function Get-vRLIServerDetail + +############## End Cloud Foundation Functions ############## +############################################################## + + +############################################################## +################## Begin vSphere Functions ################# + +Function Request-VCToken { <# - .SYNOPSIS - Get clients + .SYNOPSIS + Connects to the specified vCenter Server API and stores the credentials in a base64 string - .DESCRIPTION - The Get-WSAClient cmdlets gets a list of clients in Workspace ONE Access + .DESCRIPTION + The Request-VCToken cmdlet connects to the specified vCenter Server and stores the credentials + in a base64 string. It is required once per session before running all other cmdlets - .EXAMPLE - Get-WSAClient - This example retrieves all clients in Workspace ONE Access - #> + .EXAMPLE + Request-VCToken -fqdn sfo-m01-vc01.sfo.rainpole.io -username administrator@vsphere.local -password VMw@re1! + This example shows how to connect to the vCenter Server API + #> Param ( - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$clientId + [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:vcenterFqdn = $fqdn + + $vcenterHeader = @{"Authorization" = "Basic "+[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($username+":"+$password))} + $contentType = "application/json" + $uri = "https://$vcenterFqdn/api/session" + Try { - $wsaHeaders = @{"Content-Type" = "application/vnd.vmware.horizon.manager.oauth2client+json" } - $wsaHeaders.Add("Authorization", "$sessionToken") - if ($PsBoundParameters.ContainsKey("clientId")) { - $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/oauth2clients/$clientId" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders - $response + # Checking authentication with vCenter Server API + if ($PSEdition -eq 'Core') { + $Global:vcToken = Invoke-RestMethod -Uri $uri -Headers $vcenterHeader -Method POST -ContentType $contentType -SkipCertificateCheck # PS Core has -SkipCertificateCheck implemented } else { - $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/oauth2clients" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders - $response.items + $Global:vcToken = Invoke-RestMethod -Uri $uri -Headers $vcenterHeader -Method POST -ContentType $contentType + } + if ($vcToken) { + Write-Output "Successfully connected to the vCenter Server API: $vcenterFqdn" } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-WSAClient +Export-ModuleMember -Function Request-VCToken -Function Add-WSAClient { +Function Get-VCVersion { <# - .SYNOPSIS - Add a client + .SYNOPSIS + Get the version + + .DESCRIPTION + The Get-VCVersion cmdlet gets the version of the vCenter Server + + .EXAMPLE + Get-VCVersion + This example gets the version of the vCenter Server + #> + + Try { + $vcenterHeader = @{"vmware-api-session-id" = "$vcToken"} + $uri = "https://$vcenterFqdn/api/appliance/system/version" + + $response = Invoke-RestMethod -Method GET -Uri $uri -Headers $vcenterHeader + $response + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Get-VCVersion + +Function Get-VCConfigurationNTP { + <# + .SYNOPSIS + Get NTP configuration .DESCRIPTION - The Add-WSAClient cmdlets add a client in Workspace ONE Access + The Get-VCConfigurationNTP cmdlet gets the NTP configuration of vCenter Server .EXAMPLE - Add-WSAClient -json .\SampleJson\nsxClient.json - This example retrieves all clients in Workspace ONE Access + Get-VCConfigurationNTP + This example gets the NTP configuration of the vCenter Server #> - Param ( - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$clientId, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$sharedSecret - ) - Try { - $wsaHeaders = @{"Content-Type" = "application/vnd.vmware.horizon.manager.oauth2client+json" } - $wsaHeaders.Add("Authorization", "$sessionToken") - $body = '{ - "clientId": "' + $clientId + '", - "secret": "' + $sharedSecret + '", - "scope": "admin", - "authGrantTypes": "refresh_token client_credentials", - "redirectUri": "", - "tokenType": "Bearer", - "tokenLength": 32, - "accessTokenTTL": 8, - "refreshTokenTTL": 1440, - "refreshTokenIdleTTL": 4, - "rememberAs": "' + $clientId + '", - "displayUserGrant": false, - "internalSystemClient": false, - "inheritanceAllowed": true - }' - $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/oauth2clients" - Invoke-RestMethod $uri -Method 'POST' -Headers $wsaHeaders -body $body + $vcenterHeader = @{"vmware-api-session-id" = "$vcToken"} + $uri = "https://$vcenterFqdn/api/appliance/ntp" + + $response = Invoke-RestMethod -Method GET -Uri $uri -Headers $vcenterHeader + $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Add-WSAClient +Export-ModuleMember -Function Get-VCConfigurationNTP -Function Add-WSARoleAssociation { +Function Get-VCConfigurationDNS { <# - .SYNOPSIS - Add the AD group to the WSA role + .SYNOPSIS + Get DNS configuration - .DESCRIPTION - Add the AD group to the given WSA role. + .DESCRIPTION + The Get-VCConfigurationDNS cmdlet gets the DNS configuration of vCenter Server - .EXAMPLE - Add-WSARoleAssociation -roleId "1d0b09a1-8744-4f85-8c4f-ac104e586010" -groupId "1e942dc6-94ba-43ef-97ce-9ba34fee1609" - #> + .EXAMPLE + Get-VCConfigurationDNS + This example gets the DNS configuration of the vCenter Server + #> - Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$roleId, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$groupId - ) + Try { + $vcenterHeader = @{"vmware-api-session-id" = "$vcToken"} + $uri = "https://$vcenterFqdn/api/appliance/networking/dns/servers" - Try { - $wsaHeaders = @{"Content-Type" = "application/vnd.vmware.vidm.accesscontrol.ruleset.associations.bulk.request+json" } - $wsaHeaders.Add("Authorization", "$sessionToken") - $uri = "https://$workSpaceOne/acs/associations/rulesets/$roleId" - $body = '{ - "operations": [ - { - "users": [], - "groups": [ - "'+$groupId+'" - ], - "associationMethodTO": "POST" - }, - { - "users": [], - "groups": [], - "associationMethodTO": "DELETE" - } - ] - }' - - $response = Invoke-RestMethod $uri -Method 'POST' -Headers $wsaHeaders -body $body - $response - } - Catch { - Write-Error $_.Exception.Message - } -} -Export-ModuleMember -Function Add-WSARoleAssociation - -Function Get-WSARoleId { - <# - .SYNOPSIS - Get role id for role name - - .DESCRIPTION - Get the role id corresponding to the given role name - - .EXAMPLE - Get-WSARoleId -role "Super Admin" - This retrieves the id for the Super Admin role - #> - - Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$role - ) - - Try { - $wsaHeaders = @{"Content-Type" = "application/json" } - $wsaHeaders.Add("Authorization", "$sessionToken") - $uri = "https://$workSpaceOne/acs/rulesets" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders - $roledetails = $response.items | Where-Object {$_.name -eq $role} - $roleId=$roledetails._links.self.href.split('/')[3] - $roleId - } - Catch { - Write-Error $_.Exception.Message - } -} -Export-ModuleMember -Function Get-WSARoleId - -Function Get-WSAActiveDirectoryGroupDetail { - <# - .SYNOPSIS - Get details of the given Active Directory group - - .DESCRIPTION - Get details from Workspace ONE Access of the given Active Directory group - - .EXAMPLE - Get-WSAActiveDirectoryGroupDetail -group "gg-wsa-admins" - #> - - Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$group - ) - - Try { - $wsaHeaders = @{"Content-Type" = "application/json" } - $wsaHeaders.Add("Authorization", "$sessionToken") - $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/scim/Groups/.search?locale=en" - $body = '{ - "attributes": "id,displayName", - "filter": "(displayName co \"' + $group + '\")" - }' - $response = Invoke-RestMethod $uri -Method 'POST' -Headers $wsaHeaders -body $body - $response - } - Catch { - Write-Error $_.Exception.Message - } -} -Export-ModuleMember -Function Get-WSAActiveDirectoryGroupDetail - -Function Get-WSARoleAssociation { - <# - .SYNOPSIS - Get associations for the given Role Id - - .DESCRIPTION - Get details of associations for the given Role Id. This has details of the groups associated with a role. - - .EXAMPLE - Get-WSARoleAssociation -roleId "1d0b09a1-8744-4f85-8c4f-ac104e586010" - #> - - Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$roleId - ) - - Try { - $wsaHeaders = @{"Content-Type" = "application/json" } - $wsaHeaders.Add("Authorization", "$sessionToken") - $uri = "https://$workSpaceOne/acs/associations/rulesets/$roleId" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders - $response - } - Catch { - Write-Error $_.Exception.Message - } + $response = Invoke-RestMethod -Method GET -Uri $uri -Headers $vcenterHeader + $response + } + Catch { + Write-Error $_.Exception.Message + } } -Export-ModuleMember -Function Get-WSARoleAssociation +Export-ModuleMember -Function Get-VCConfigurationDNS -Function Get-WSAPasswordLockout { +Function Get-VCPasswordPolicy { <# - .SYNOPSIS - Get password lockout policy + .SYNOPSIS + Get the global password policy. .DESCRIPTION - Get details of the password lockout policy for Workspace ONE Access + The Get-VCPasswordPolicy cmdlet gets global password policy for the vCenter Server .EXAMPLE - Get-WSAPasswordLockout + Get-VCPasswordPolicy + This example gets the global password policy of the vCenter Server #> Try { - $wsaHeaders = @{"Accept" = "application/vnd.vmware.horizon.manager.password.lockout+json" } - $wsaHeaders.Add("Authorization", "$sessionToken") - $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/passwordlockoutconfig" - $response = Invoke-RestMethod $uri -Headers $wsaHeaders + $vcenterHeader = @{"vmware-api-session-id" = "$vcToken"} + $uri = "https://$vcenterFqdn/api/appliance/local-accounts/global-policy" + + $response = Invoke-RestMethod -Method GET -Uri $uri -Headers $vcenterHeader $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-WSAPasswordLockout +Export-ModuleMember -Function Get-VCPasswordPolicy -Function Set-WSAPasswordLockout { +Function Set-VCPasswordPolicy { <# .SYNOPSIS - Set password lockout policy + Set the global password policy .DESCRIPTION - Set details of the password lockout policy for Workspace ONE Access + The Set-VCPasswordPolicy cmdlet configures the global password policy for the vCenter Server .EXAMPLE - Set-WSAPasswordLockout + Set-VCPasswordPolicy -maxDays 120 -minDays 1 -warnDays 14 + This example configures the global password policy of the vCenter Server #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$numAttempts, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$attemptInterval, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$unlockInterval + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$maxDays, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$minDays, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$warnDays ) Try { - $wsaHeaders = @{"Accept" = "application/vnd.vmware.horizon.manager.password.lockout+json" } - $wsaHeaders.Add("Authorization", "$sessionToken") - $wsaHeaders.Add("Content-Type", "application/vnd.vmware.horizon.manager.password.lockout+json") - $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/passwordlockoutconfig" - $body = '{"numAttempts":'+$numAttempts+',"attemptInterval":'+$attemptInterval+',"unlockInterval":'+$unlockInterval+'}' - $response = Invoke-RestMethod $uri -Method 'PUT' -Headers $wsaHeaders -Body $body + $vcenterHeader = @{"vmware-api-session-id" = "$vcToken"} + $vcenterHeader.Add("Content-Type", "application/json") + $uri = "https://$vcenterFqdn/api/appliance/local-accounts/global-policy" + $body = '{ "max_days": '+$maxDays+', "min_days": '+$minDays+', "warn_days": '+$warnDays+' }' + + $response = Invoke-RestMethod -Method PUT -Uri $uri -Headers $vcenterHeader -Body $body $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Set-WSAPasswordLockout +Export-ModuleMember -Function Set-VCPasswordPolicy - Function Get-WSAPasswordPolicy { +Function Get-VCPasswordExpiry { <# - .SYNOPSIS - Get password policy + .SYNOPSIS + Get the vcenter password expiry date. .DESCRIPTION - Get details of the password policy for Workspace ONE Access + The Get-VCPasswordPolicy cmdlet gets password expiration settings for the vCenter Server root account .EXAMPLE - Get-WSAPasswordPolicy + Get-VCPasswordExpiry + This example gets the password policy of the vCenter Server #> Try { - $wsaHeaders = @{"Accept" = "application/vnd.vmware.horizon.manager.tenants.tenant.passwordpolicy+json" } - $wsaHeaders.Add("Authorization", "$sessionToken") - $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/tenants/tenant/passwordpolicy" - $response = Invoke-RestMethod $uri -Headers $wsaHeaders + $uri = "https://$currentvCenterServer"+":5480/rest/appliance/local-accounts/root" + $response = Invoke-RestMethod -Method GET -Uri $uri -Headers $vcAdminHeaders $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-WSAPasswordPolicy +Export-ModuleMember -Function Get-VCPasswordExpiry -Function Set-WSAPasswordPolicy { +Function Set-VCPasswordExpiry { <# .SYNOPSIS - Set password lockout policy + Set the vcenter password expiry date .DESCRIPTION - Set details of the password lockout policy for Workspace ONE Access + The Set-VCPasswordExpiry cmdlet configures password expiration settings for the vCenter Server root account .EXAMPLE - Set-WSAPasswordPolicy -minLen 6 -minLower 0 -minUpper 0 -minDigit 0 -minSpecial 0 -history 0 -maxConsecutiveIdenticalCharacters 3 -maxPreviousPasswordCharactersReused 2 -tempPasswordTtlInHrs 167 -passwordTtlInDays 81 -notificationThresholdInDays 16 -notificationIntervalInDays 11 + Set-VCPasswordExpiry -passwordExpires $true -email "admin@rainpole.io" -maxDaysBetweenPasswordChange 91 + This example configures the configures password expiration settings for the vCenter Server root account + + Set-VCPasswordExpiry -passwordExpires $false + This example configures the configures password expiration settings for the vCenter Server root account to never expire #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$minLen, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$minLower, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$minUpper, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$minDigit, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$minSpecial, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$history, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$maxConsecutiveIdenticalCharacters, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$maxPreviousPasswordCharactersReused, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tempPasswordTtlInHrs, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$passwordTtlInDays, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$notificationThresholdInDays, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$notificationIntervalInDays - + [Parameter (Mandatory = $false, ParameterSetName = 'neverexpire')] [Parameter (Mandatory = $true, ParameterSetName = 'expire')] [ValidateNotNullOrEmpty()] [Bool]$passwordExpires, + [Parameter (Mandatory = $true, ParameterSetName = 'expire')] [ValidateNotNullOrEmpty()] [String]$email, + [Parameter (Mandatory = $true, ParameterSetName = 'expire')] [ValidateNotNullOrEmpty()] [String]$maxDaysBetweenPasswordChange ) Try { - $wsaHeaders = @{"Accept" = "application/vnd.vmware.horizon.manager.tenants.tenant.passwordpolicy+json" } - $wsaHeaders.Add("Authorization", "$sessionToken") - $wsaHeaders.Add("Content-Type", "application/vnd.vmware.horizon.manager.tenants.tenant.passwordpolicy+json") - $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/tenants/tenant/passwordpolicy" - $passwordTtlInHours = [int]$passwordTtlInDays * 24 - $notificationThresholdInMilliSec = [int]$notificationThresholdInDays * 24 * 3600 * 1000 - $notificationIntervalInMilliSec = [int]$notificationIntervalInDays * 24 * 3600 * 1000 - $body = '{ - "minLen":'+$minLen+', - "minLower":'+$minLower+', - "minUpper":'+$minUpper+', - "minDigit":'+$minDigit+', - "minSpecial":'+$minSpecial+', - "history":'+$history+', - "maxConsecutiveIdenticalCharacters":'+$maxConsecutiveIdenticalCharacters+', - "maxPreviousPasswordCharactersReused":'+$maxPreviousPasswordCharactersReused+', - "tempPasswordTtl":'+$tempPasswordTtlInHrs+', - "passwordTtlInHours":'+$passwordTtlInHours+', - "notificationThreshold":'+$notificationThresholdInMilliSec+', - "notificationInterval":'+$notificationIntervalInMilliSec+' - }' - Write-OutPut $body - $response = Invoke-RestMethod $uri -Method 'PUT' -Headers $wsaHeaders -Body $body + $uri = "https://$currentvCenterServer"+":5480/rest/appliance/local-accounts/root" + + if ($passwordExpires) { + $body = '{"config":{"password_expires": "'+ $passwordExpires +'", "email": "'+ $email+ '", "max_days_between_password_change": "' + $maxDaysBetweenPasswordChange + '" }}' + } + else { + $body = '{"config":{"password_expires": "'+ $passwordExpires + '"}}' + } + $response = Invoke-RestMethod -Method PATCH -Uri $uri -Headers $vcAdminHeaders -Body $body + $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Set-WSAPasswordPolicy - -############ End Workspace ONE Access Functions ############ -############################################################## - - -############################################################## -############ Begin NSX-T Data Center Functions ############# +Export-ModuleMember -Function Set-VCPasswordExpiry -Function Request-NsxToken { +Function Add-GlobalPermission { <# .SYNOPSIS - Connects to the specified NSX Manager + Script to add vSphere Global Permission .DESCRIPTION - The Request-NsxToken cmdlet connects to the specified NSX Manager with the supplied credentials + The Add-GlobalPermission cmdlet adds a new vSphere Global Permission - .EXAMPLE - Request-NsxToken -fqdn sfo-w01-nsx01.sfo.rainpole.io -username admin -password VMware1!VMw@re1! - This example shows how to connect to NSX Manager + .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-NsxtServerDetail -fqdn sfo-vcf01.sfo.rainpole.io -username admin@local -password VMw@re1!VMw@re1! -domain sfo-w01 | Request-NsxToken - This example shows how to connect to NSX Manager using pipeline input from Get-NsxtServerDetail + Add-GlobalPermission -vcServer sfo-m01-vc01.sfo.rainpole.io -username administrator@vsphewre.local -vcPassword VMware1! -user svc-vc-admins + This example shows how to add the Administrator global permission to a user called svc-vc-admins #> Param ( - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()][String]$fqdn, - [Parameter (Mandatory = $false)] [String]$username, - [Parameter (Mandatory = $false)] [String]$password, - [Parameter (ValueFromPipeline, Mandatory = $false)] [psobject]$inputObject + [Parameter (Mandatory = $true)] [String]$vcServer, + [Parameter (Mandatory = $true)] [String]$vcUsername, + [Parameter (Mandatory = $true)] [String]$vcPassword, + [Parameter (Mandatory = $true)] [String]$user, + [Parameter (Mandatory = $true)] [String]$roleId, + [Parameter (Mandatory = $true)] [String]$propagate, + [Parameter (Mandatory = $true)] [String]$type ) - if ($inputObject) { - $username = $inputObject.adminUser - $password = $inputObject.adminPass - $fqdn = $inputObject.fqdn - $sddcManager = (Get-VCFManager).fqdn - } - else { - if (!$PsBoundParameters.ContainsKey("username") -or (!$PsBoundParameters.ContainsKey("password"))) { - # Request Credentials - $creds = Get-Credential - $username = $creds.UserName.ToString() - $password = $creds.GetNetworkCredential().password - } - if (!$PsBoundParameters.ContainsKey("fqdn")) { - $fqdn = Read-Host "NSX Manager FQDN not found, please enter a value e.g. sfo-m01-nsx01.sfo.rainpole.io" - } - } - - # Validate credentials by executing an API call - $Global:nsxtHeaders = createBasicAuthHeader $username $password - $Global:nsxtmanager = $fqdn - $uri = "https://$nsxtmanager/api/v1/logical-ports" - Try { - # Checking against the NSX Managers API - # PS Core has -SkipCertificateCheck implemented, PowerShell 5.x does not - if ($PSEdition -eq 'Core') { - $response = Invoke-RestMethod -Method GET -Uri $uri -Headers $nsxtHeaders -SkipCertificateCheck + $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] } else { - $response = Invoke-RestMethod -Method GET -Uri $uri -Headers $nsxtHeaders + Write-Error "Failed to login to vSphere MOB" + exit 1 } - if ($response) { - if ($inputObject) { - Write-Output "Successfully Requested New API Token for NSX Manager $nsxtmanager via SDDC Manager $sddcManager" - } - else { - Write-Output "Successfully Requested New API Token for NSX Manager $nsxtmanager" - } + + $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 +"@ + } + + $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" } + $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 Request-NsxToken +Export-ModuleMember -Function Add-GlobalPermission -Function Get-NsxtComputeManager { +Function Get-SsoPasswordPolicies { <# - .SYNOPSIS - Retrieves a list of compute managers from NSX Manager - - .DESCRIPTION - The Get-NsxtComputeManager cmdlet gets compute managers from NSX Manager + .SYNOPSIS + Get vSphere Single-Sign On password policies - .EXAMPLE - Get-NsxtComputeManager - This example gets all compute managers + .DESCRIPTION + The Get-SsoPasswordPolicies cmdlet gets the vSphere Single-Sign On password policies - .EXAMPLE - Get-NsxtComputeManager -vCenterServer "sfo-m01-vc01.sfo.rainpole.io" - This example gets the compute manager named "sfo-m01-vc01.sfo.rainpole.io" - #> + .EXAMPLE + Get-SsoPasswordPolicies -ssoAdminPass VMw@re1! -ssoDomain vsphere.local -vmName sfo-m01-vc01 -rootPass VMw@re1! + This example shows how to get vSphere Single-Sign On password policies + #> Param ( - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vCenterServer + [Parameter (Mandatory = $true)] [String]$ssoAdminPass, + [Parameter (Mandatory = $true)] [String]$ssoDomain, + [Parameter (Mandatory = $true)] [String]$vmName, + [Parameter (Mandatory = $true)] [String]$rootPass ) Try { - if (!$PsBoundParameters.ContainsKey("vCenterServer")) { - $uri = "https://$nsxtManager/api/v1/fabric/compute-managers" - $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders - $response.results - } - elseif ($PsBoundParameters.ContainsKey("vCenterServer")) { - $uri = "https://$nsxtManager/api/v1/fabric/compute-managers" - $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders - $responseChecked = $response.results | Where-Object { $_.server -eq $vCenterServer } - - if (!$responseChecked) { - Write-Output "Compute Manager $vCenterServer was not found." - } - elseif ($responseChecked) { - $responseChecked - } - } + $a, $b = $ssoDomain.split(".") + $scriptCommand = "/opt/likewise/bin/ldapsearch -h localhost -w $ssoAdminPass -x -D `"cn=Administrator,cn=Users,dc=$a,dc=$b`" -b `"cn=password and lockout policy,dc=$a,dc=$b`" | grep vmwPassword" + $output = Invoke-VMScript -ScriptText $scriptCommand -vm $vmName -GuestUser "root" -GuestPassword $rootPass + $output.scriptOutput } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-NsxtComputeManager +Export-ModuleMember -Function Get-SsoPasswordPolicies -Function Set-NsxtComputeManager { +Function Add-DrsVmToVmGroup { <# - .SYNOPSIS - Configure a set of parameters on a compute manager + .SYNOPSIS + Creates a vSphere VM to VM Group - .DESCRIPTION - The Set-NsxtComputeManager cmdlet configures a set of parameters on a compute manager + .DESCRIPTION + The Add-DrsVmToVmGroup cmdlet creates a vSphere VM to VM Group - .EXAMPLE - Get-NsxtComputeManager -vCenterServer sfo-w01-vc01.sfo.rainpole.io | Set-NsxtComputeManager -EnableTrust:$true - This example enables trust (sets OIDC provider to true) for Compute Manager sfo-w01-vc01.sfo.rainpole.io - In this release, it is required to use pipeline input from Get-NsxtComputeManager. - #> + .EXAMPLE + Add-DrsVmToVmGroup -name vm-vm-rule-wsa-vra -vmGroup sfo-m01-vm-group-wsa -dependOnVmGroup sfo-m01-vm-group-vra -Enabled -cluster sfo-m01-cl01 + This example shows how to create a vSphere VM to VM group in the vCenter Server + #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Bool]$EnableTrust, - [Parameter (ValueFromPipeline, Mandatory = $true)] [psObject]$inputObject + [Parameter (Mandatory = $true)] [String]$name, + [Parameter (Mandatory = $true)] [String]$vmGroup, + [Parameter (Mandatory = $true)] [String]$dependOnVmGroup, + [Parameter (Mandatory = $false)] [Switch]$enabled=$true, + [Parameter (Mandatory = $true)] [String]$cluster ) - # Validating pipeline input resource_type - if ($inputObject.resource_type -ne "ComputeManager") { - Write-Error "Invalid pipeline passthrough." - break - } - elseif ($inputObject.resource_type -eq "ComputeManager") { - $computeManagerId = $inputObject.id - $computeManagerRevision = $inputObject._revision - $computeManagerFqdn = $inputObject.server - $computeManagerOriginType = $inputObject.origin_type - $computeManagerSetAsOidcProvider = $inputObject.set_as_oidc_provider - $computeManagerCredentialType = $inputObject.credential.credential_type - $computeManagerCredentialThumbprint = $inputObject.credential.thumbprint - } - - if ($EnableTrust -eq $computeManagerSetAsOidcProvider) { - Write-Error -Message "Compute Manager trust is already set to $EnableTrust." - break - } + Try { + $updateCluster = Get-Cluster | Where-Object {$_.Name -eq $cluster} - $json = @" -{ -"_revision" : $computeManagerRevision, -"server" : "$computeManagerFqdn", -"origin_type" : "$computeManagerOriginType", -"set_as_oidc_provider" : "$EnableTrust", -"credential" : -{ - "credential_type" : "$computeManagerCredentialType", - "thumbprint" : "$computeManagerCredentialThumbprint" -} -} -"@ + $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].Operation = 'add' + $spec.RulesSpec[0].Info = New-Object VMware.Vim.ClusterDependencyRuleInfo + $spec.RulesSpec[0].Info.DependsOnVmGroup = $dependOnVmGroup + $spec.RulesSpec[0].Info.VmGroup = $vmGroup + $spec.RulesSpec[0].Info.Name = $name + $spec.RulesSpec[0].Info.UserCreated = $true + $spec.RulesSpec[0].Info.Enabled = $true - Try { - $uri = "https://$nsxtManager/api/v1/fabric/compute-managers/$computeManagerId" - $response = Invoke-RestMethod -Method PUT -URI $uri -ContentType application/json -body $json -headers $nsxtHeaders - $response + $ClusterToReconfig = Get-View -Id $updateCluster.ExtensionData.MoRef + $ClusterToReconfig.ReconfigureComputeResource_Task($spec, $true) } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Set-NsxtComputeManager +Export-ModuleMember -Function Add-DrsVmToVmGroup -Function Get-NsxtVidm { +Function Get-DrsVmToVmGroup { <# - .SYNOPSIS - Get Identity Manager Configuration + .SYNOPSIS + Gets all vSphere VM to VM Group - .DESCRIPTION - The Get-NsxtVidm cmdlet gets the Identity Manager Configuration + .DESCRIPTION + The Get-DrsVmToVmGroup cmdlet retrieves the vSphere VM to VM Group - .EXAMPLE - Get-NsxtVidm - This example gets the Identity Manager Configuration - #> + .EXAMPLE + Get-DrsVmToVmGroup -name vm-vm-rule-wsa-vra -cluster sfo-m01-cl01 + This example shows how to retrieve a vSphere VM to VM group in the vCenter Server + #> + + Param ( + [Parameter (Mandatory = $false)] [String]$name, + [Parameter (Mandatory = $true)] [String]$cluster + ) Try { - $uri = "https://$nsxtManager/api/v1/node/aaa/providers/vidm" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $nsxtHeaders - $response + $getCluster = Get-Cluster | Where-Object {$_.Name -eq $cluster} + if ($PsBoundParameters.ContainsKey("name")){ + $getCluster.ExtensionData.Configuration.Rule | Where-Object {$_.Name -eq $name} + } + else { + $getCluster.ExtensionData.Configuration.Rule + } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-NsxtVidm +Export-ModuleMember -Function Get-DrsVmToVmGroup -Function Set-NsxtVidm { + +################## End vSphere Functions ################### +############################################################## + + +############################################################## +########### Begin Workspace ONE Access Functions ########### + +Function Request-WSAToken { <# - .SYNOPSIS - Set Identity Manager Configuration + .SYNOPSIS + Connects to the specified Workspace ONE Access instance to obtain a session token - .DESCRIPTION - The Set-NsxtVidm cmdlet configures Identity Manager in NSX-T Manager + .DESCRIPTION + The Request-WSAToken cmdlet connects to the specified Workspace ONE Access instance and requests a session token - .EXAMPLE - Set-NsxtVidm - This example configures the Identity Manager in NSX-T Manager - #> + .EXAMPLE + Request-WSAToken -fqdn sfo-wsa01.sfo.rainpole.io -user admin -pass VMware1! + This example shows how to connect to a Workspace ONE Access instance and request a session token + #> 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]$fqdn, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$pass ) + If ( -not $PsBoundParameters.ContainsKey("user") -or ( -not $PsBoundParameters.ContainsKey("pass"))) { + # Request Credentials + $creds = Get-Credential + $user = $creds.UserName.ToString() + $pass = $creds.GetNetworkCredential().password + } + + $Global:workSpaceOne = $fqdn + + # Validate credentials by executing an API call + $wsaHeaders = @{"Content-Type" = "application/json" } + $wsaHeaders.Add("Accept", "application/json; charset=utf-8") + $uri = "https://$workSpaceOne/SAAS/API/1.0/REST/auth/system/login" + $body = '{"username": "' + $user + '", "password": "' + $pass + '", "issueToken": "true"}' + Try { - $uri = "https://$nsxtManager/api/v1/node/aaa/providers/vidm" - $body = '{ - "lb_enable": false, - "vidm_enable": true, - "host_name": "' + $wsaHostname + '", - "thumbprint": "' + $thumbprint + '", - "client_id": "' + $clientId + '", - "client_secret": "' + $sharedSecret + '", - "node_host_name": "' + $nsxHostname + '" - }' - $response = Invoke-RestMethod $uri -Method 'PUT' -Headers $nsxtHeaders -body $body - $response + # Checking against the API + # PS Core has -SkipCertificateCheck implemented, PowerShell 5.x does not + if ($PSEdition -eq 'Core') { + $response = Invoke-RestMethod $uri -Method 'POST' -Headers $wsaHeaders -Body $body -SkipCertificateCheck + $Global:sessionToken = "HZN " + $response.sessionToken + } + else { + $response = Invoke-RestMethod $uri -Method 'POST' -Headers $wsaHeaders -Body $body + $Global:sessionToken = "HZN " + $response.sessionToken + } + if ($response.sessionToken) { + Write-Output "Successfully Requested New Session Token From Workspace ONE Access instance: $fqdn" + } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Set-NsxtVidm +Export-ModuleMember -Function Request-WSAToken -Function Get-NsxtRole { +Function Get-WSAIdentityProvider { <# - .SYNOPSIS - Gets NSX-T Manager roles + .SYNOPSIS + Get identity providers .DESCRIPTION - The Get-NsxtRole cmdlet gets the roles in NSX-T Manager + The Get-WSAIdentityProvider cmdlets retrieves a list of identity providers in Workspace ONE Access .EXAMPLE - Get-NsxtRole - This example gets all roles in NSX-T Manager + Get-WSAIdentityProvider + This example retrives a list of identity providers in Workspace ONE Access #> Try { - $uri = "https://$nsxtManager/api/v1/aaa/roles" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $nsxtHeaders - $response.results + $wsaHeaders = @{"Accept" = "application/vnd.vmware.horizon.manager.identityprovider.summary.list+json" } + $wsaHeaders.Add("Authorization", "$sessionToken") + $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/identityProviders?onlyEnabledAdapters=true" + $response = Invoke-RestMethod -Uri $uri -Method 'GET' -Headers $wsaHeaders + $response.items } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-NsxtRole +Export-ModuleMember -Function Get-WSAIdentityProvider -Function Set-NsxtRole { +Function Get-WSAConnector { <# - .SYNOPSIS - Adds a role to a user/group + .SYNOPSIS + Get connectors .DESCRIPTION - The Set-NsxtRole cmdlet assigns users/groups to roles + The Get-WSAConnector cmdlets retrieves a list of connectors in Workspace ONE Access .EXAMPLE - Set-NsxtRole -principle "gg-nsx-enterprise-admins@lax.rainpole.io" - This example assigned the provided group the Enterprise Admin role + Get-WSAConnector + This example retrives a list of connectors in Workspace ONE Access #> - Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$principal, - [Parameter (Mandatory = $true)] [ValidateSet("remote_group", "remote_user")] [String]$type, - [Parameter (Mandatory = $true)] [ValidateSet("lb_admin", "security_engineer", "vpn_admin", "network_op", "netx_partner_admin", "gi_partner_admin", "security_op", "network_engineer", "lb_auditor", "auditor", "enterprise_admin")] [String]$role, - [Parameter (Mandatory = $true)] [ValidateSet("LDAP", "VIDM", "OIDC")] [String]$identitySource - ) - Try { - $uri = "https://$nsxtManager/api/v1/aaa/role-bindings" - $body = '{ - "name": "' + $principal + '", - "type": "' + $type + '", - "identity_source_type": "' + $identitySource + '", - "roles": [ - { - "role": "' + $role + '" - } - ] - }' - $response = Invoke-RestMethod $uri -Method 'POST' -Headers $nsxtHeaders -Body $body - $response + $wsaHeaders = @{"Content-Type" = "application/vnd.vmware.horizon.manager.connector.management.connector+json" } + $wsaHeaders.Add("Authorization", "$sessionToken") + $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/connectormanagement/connectorinstances" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders + $response.items } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Set-NsxtRole +Export-ModuleMember -Function Get-WSAConnector -Function Remove-NsxtRole { +Function Add-WSAConnector { <# - .SYNOPSIS - Delete a user/group role assignment + .SYNOPSIS + Add connector to identity providor .DESCRIPTION - The Remove-NsxtRole cmdlet removes a user/group role in NSX-T Manager + The Add-WSAConnector cmdlets adds a connector to an identity providoer in Workspace ONE Access .EXAMPLE - Remove-NsxtRole -id - This example removes the role for the user/group based on the id + Add-WSAConnector -wsaFqdn xint-wsa01b.rainpole.io -domain sfo.rainpole.io -bindUserPass VMw@re1! + This example adds a connector to an identity providoer in Workspace ONE Access #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaNode, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$bindUserPass ) Try { - $uri = "https://$nsxtManager/api/v1/aaa/role-bindings/$id" - $response = Invoke-RestMethod $uri -Method 'DELETE' -Headers $nsxtHeaders + $identityProviderId = (Get-WSAIdentityProvider | Where-Object {$_.directoryConfigurations.name -eq $domain}).id + $directoryId = (Get-WSADirectory | Where-Object {$_.name -eq $domain}).directoryId + $connectorId = (Get-WSAConnector | Where-Object {$_.host -eq $wsaNode}).instanceId + + $wsaHeaders = @{"Accept" = "application/vnd.vmware.horizon.manager.connector.management.connector+json"} + $wsaHeaders.Add("Content-Type", "application/vnd.vmware.horizon.manager.connector.management.directory.bindDetails+json") + $wsaHeaders.Add("Authorization", "$sessionToken") + $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/connectormanagement/connectorinstances/$connectorId/associatedirectory?idp=$identityProviderId" + $body = '{"directoryId": "' + $directoryId + '", "directoryBindPassword":"' + $bindUserPass + '", "usedForAuthentication":true, "bindToAD":true}' + $response = Invoke-RestMethod -Uri $uri -Method 'POST' -Headers $wsaHeaders -Body $body $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Remove-NsxtRole +Export-ModuleMember -Function Add-WSAConnector -Function Get-NsxtUser { +Function Get-WSADirectory { <# - .SYNOPSIS - Gets all users and groups + .SYNOPSIS + Get diretories .DESCRIPTION - The Get-NsxtUser cmdlet gets all users and groups in NSX-T Manager + The Get-WSADirectory cmdlets retrieves all directories in Workspace ONE Access .EXAMPLE - Get-NsxtUser - This example gets all users and grops in NSX-T Manager - #> - - Try { - $uri = "https://$nsxtManager/api/v1/aaa/role-bindings" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $nsxtHeaders - $response.results - } - Catch { - Write-Error $_.Exception.Message - } -} -Export-ModuleMember -Function Get-NsxtUser - -Function Get-NsxtVidmUser { - <# - .SYNOPSIS - Gets vIDM users - - .DESCRIPTION - The Get-NsxtVidmUser cmdlet gets all vIDM users from NSX-T Manager + Get-WSADirectory + This example retrives a list of directories in Workspace ONE Access .EXAMPLE - Get-NsxtVidmUser -searchString svc - This example gets all vIDM users starting with 'svc' from NSX-T Manager + Get-WSADirectory -connector + This example retrives a list of connectors for a directory in Workspace ONE Access #> Param ( - [Parameter (Mandatory = $true)] [ValidateLength(3, 255)] [String]$searchString + [Parameter (ParameterSetName = "connector", Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$directoryId, + [Parameter (ParameterSetName = "connector",Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$connector ) + Try { - $uri = "https://$nsxtManager/api/v1/aaa/vidm/users?search_string=$searchString" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $nsxtHeaders - $response.results + if ($PsBoundParameters.ContainsKey("connector")){ + $wsaHeaders = @{"Accept" = ""} + $wsaHeaders.Add("Authorization", "$sessionToken") + $uri = "https://xint-wsa01.rainpole.io/SAAS/jersey/manager/api/connectormanagement/directoryconfigs/$directoryId/connectors" + $response = Invoke-RestMethod -Uri $uri -Method 'GET' -Headers $wsaHeaders + $response.items + } + else { + $wsaHeaders = @{"Content-Type" = "application/vnd.vmware.horizon.manager.connector.management.directory.ad.over.ldap+json" } + $wsaHeaders.Add("Authorization", "$sessionToken") + $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/connectormanagement/directoryconfigs" + $response = Invoke-RestMethod -Uri $uri -Method 'GET' -Headers $wsaHeaders + $response.items + } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-NsxtVidmUser +Export-ModuleMember -Function Get-WSADirectory -Function Get-NsxtVidmGroup { +Function Get-WSADirectoryDomain { <# - .SYNOPSIS - Gets vIDM groups + .SYNOPSIS + Get directory domains - .DESCRIPTION - The Get-NsxtVidmGroup cmdlet gets all vIDM groups from NSX-T Manager + .DESCRIPTION + The Get-WSADirectoryDomain cmdlets retrieves a list of directory domains in Workspace ONE Access - .EXAMPLE - Get-NsxtVidmGroup -searchString gg- - This example gets all vIDM groups starting with gg- from NSX-T Manager - #> + .EXAMPLE + Get-WSADirectoryDomain -directoryId a1c985d5-0eeb-4a66-bc51-11eda9321aac + This example retrives a list of directory domains in Workspace ONE Access + #> Param ( - [Parameter (Mandatory = $true)] [ValidateLength(3, 255)] [String]$searchString + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [string]$directoryId ) Try { - $uri = "https://$nsxtManager/api/v1/aaa/vidm/groups?search_string=$searchString" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $nsxtHeaders - $response.results + $wsaHeaders = @{"Accept" = "application/vnd.vmware.horizon.manager.connector.management.directory.domain.list+json" } + $wsaHeaders.Add("Authorization", "$sessionToken") + $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/connectormanagement/directoryconfigs/$directoryId/domains" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders + $response.items } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-NsxtVidmGroup +Export-ModuleMember -Function Get-WSADirectoryDomain -Function Get-NsxEdgeCluster { +Function Add-WSALdapDirectory { <# - .SYNOPSIS - Retrieves NSX-T Edge Cluster(s) - - .DESCRIPTION - The Get-NsxtEdgeCluster cmdlet retrieves NSX-T Edge Cluster(s) - - .EXAMPLE - Get-NsxtEdgeCluster - This example returns any NSX-T Edge Clusters + .SYNOPSIS + Create an LDAP directory - .EXAMPLE - Get-NsxtEdgeCluster -Name "sfo-w01-ec01" - This example returns any NSX-T Edge Clusters - #> + .DESCRIPTION + The Add-WSALdapDirectory cmdlets creates a new LDAP Active Directory connection in Workspace ONE Access - Param ( - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$Name + .EXAMPLE + Add-WSALdapDirectory -domainName sfo.rainpole.io -baseDn "ou=VVD,dc=sfo,dc=rainpole,dc=io" -bindDn "cn=svc-wsa-ad,ou=VVD,dc=sfo,dc=rainpole,dc=io" + This example creates a new LDAP Active Directory connection in Workspace ONE Access + #> + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domainName, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$baseDn, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$bindDn, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$certificate ) Try { - if (!$PsBoundParameters.ContainsKey("Name")) { - $uri = "https://$nsxtmanager/api/v1/edge-clusters" - $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders - $response.results - } - elseif ($PsBoundParameters.ContainsKey("Name")) { - $uri = "https://$nsxtmanager/api/v1/edge-clusters" - $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders - $responseChecked = $response.results | Where-Object { $_.display_name -eq $Name } - - if (!$responseChecked) { - Write-Output "NSX-T Edge Cluster $Name was not found." - } - elseif ($responseChecked) { - $responseChecked - } + $wsaHeaders = @{"Content-Type" = "application/vnd.vmware.horizon.manager.connector.management.directory.ad.over.ldap+json" } + $wsaHeaders.Add("Accept", "application/vnd.vmware.horizon.manager.connector.management.directory.ad.over.ldap+json") + $wsaHeaders.Add("Authorization", "$sessionToken") + if ($PsBoundParameters.ContainsKey("certificate")){ + #read certificate file contents as certdata + $certdata = (Get-Content ($certificate)) -join "\n" + $body = '{ + "useSRV":true, + "directoryType":"ACTIVE_DIRECTORY_LDAP", + "directorySearchAttribute":"sAMAccountName", + "directoryConfigId":null, + "useGlobalCatalog":false, + "syncConfigurationEnabled":false, + "useStartTls":true, + "userAttributeMappings":[], + "name":"' + $domainName + '", + "baseDN":"' + $baseDn + '", + "bindDN":"' + $bindDn + '", + "sslCertificate":"' + $certdata + '" + }' + }else{ + $body = '{ + "useSRV":true, + "directoryType":"ACTIVE_DIRECTORY_LDAP", + "directorySearchAttribute":"sAMAccountName", + "directoryConfigId":null, + "useGlobalCatalog":false, + "syncConfigurationEnabled":false, + "useStartTls":false, + "userAttributeMappings":[], + "name":"' + $domainName + '", + "baseDN":"' + $baseDn + '", + "bindDN":"' + $bindDn + '" + }' } + $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/connectormanagement/directoryconfigs" + $response = Invoke-RestMethod $uri -Method 'POST' -Headers $wsaHeaders -Body $body + $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-NsxEdgeCluster +Export-ModuleMember -Function Add-WSALdapDirectory -Function Get-NsxtTransportZone { +Function Set-WSABindPassword { <# - .SYNOPSIS - Get a list of Transport Zones - - .DESCRIPTION - The Get-NsxtTransportZone cmdlet retrieves a list of Transport Zones + .SYNOPSIS + Create an LDAP directory - .EXAMPLE - Get-NsxtTransportZone - This example gets all Transport Zones + .DESCRIPTION + The Set-WSABindPassword cmdlets creates a new LDAP Active Directory connection in Workspace ONE Access - .EXAMPLE - Get-NsxtTransportZone -Name overlay-tz-sfo-w01-nsx01.sfo.rainpole.io - This example gets the Transport Zone with the name "overlay-tz-sfo-w01-nsx01.sfo.rainpole.io" - #> + .EXAMPLE + Set-WSABindPassword -directoryId a1c985d5-0eeb-4a66-bc51-11eda9321aac -connectorId 59ee9717-a09e-45b6-9e5f-8d92a55a1825 -password VMw@re1! + This example creates a new LDAP Active Directory connection in Workspace ONE Access + #> Param ( - [Parameter (Mandatory = $false)] [String]$Name + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$directoryId, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$connectorId, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass ) Try { - if (!$PsBoundParameters.ContainsKey("Name")) { - $uri = "https://$nsxtManager/api/v1/transport-zones" - $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders - $response.results | Sort-Object display_name - } - elseif ($PsBoundParameters.ContainsKey("Name")) { - $uri = "https://$nsxtManager/api/v1/transport-zones" - $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders - $responseChecked = $response.results | Where-Object { $_.display_name -eq $Name } - - if (!$responseChecked) { - Write-Output "NSX Transport Zone $Name was not found" - } - elseif ($responseChecked) { - $responseChecked - } - } + $wsaHeaders = @{"Content-Type" = "application/vnd.vmware.horizon.manager.connector.management.directory.details+json" } + $wsaHeaders.Add("Accept", "application/vnd.vmware.horizon.manager.connector.management.connector+json") + $wsaHeaders.Add("Authorization", "$sessionToken") + $body = '{"directoryId":"' + $directoryId + '","directoryBindPassword":"' + $pass + '","usedForAuthentication":true}' + $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/connectormanagement/connectorinstances/$connectorId/associatedirectory" + $response = Invoke-RestMethod $uri -Method 'POST' -Headers $wsaHeaders -Body $body + $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-NsxtTransportZone +Export-ModuleMember -Function Set-WSABindPassword -Function New-NsxtSegment { +Function Set-WSASyncSetting { <# - .SYNOPSIS - Create a new NSX-T Segment + .SYNOPSIS + Set directory sync schedule - .DESCRIPTION - The New-NsxtSegment cmdlet creates NSX-T Segments + .DESCRIPTION + The Set-WSASyncSetting cmdlets configures the directory sync schedule in Workspace ONE Access - .EXAMPLE - New-NsxtSegment -Name "sfo-w01-xreg-seg01" -GatewayType "Tier1" -ConnectedGateway "sfo-w01-ec01-t1-gw01" -Cidr "192.168.31.1/24" -TransportZone "overlay-tz-sfo-w01-nsx01.sfo.rainpole.io" - This example creates an NSX-T Overlay Segment with the name "sfo-w01-xreg-seg01", connected to Tier-1 gateway "sfo-w01-ec01-t1-gw01", Transport Zone "overlay-tz-sfo-w01-nsx01.sfo.rainpole.io", and CIDR address of "192.168.31.1/24" - #> + .EXAMPLE + Set-WSASyncSetting -directoryId a1c985d5-0eeb-4a66-bc51-11eda9321aac + This example configures the directory sync schedule in Workspace ONE Access + #> Param ( - [Parameter (Mandatory = $true)] [String]$Name, - [Parameter (Mandatory = $false)] [String]$ConnectedGateway, - [Parameter (Mandatory = $false)] [String]$Cidr, - [Parameter (Mandatory = $true)] [String]$TransportZone, - [Parameter (Mandatory = $false)] [ValidateSet("Tier0", "Tier1")] [String]$GatewayType, - [Parameter (Mandatory = $true)] [ValidateSet("Overlay", "VLAN")] [String]$SegmentType, - [Parameter (Mandatory = $false)] [String]$VlanId + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$directoryId ) - if ($GatewayType -eq "Tier0") { - $connectivityPath = (Get-NsxtTier0Gateway -Name $ConnectedGateway).path - } - elseif ($GatewayType -eq "Tier1") { - $connectivityPath = (Get-NsxtTier1Gateway -Name $ConnectedGateway).path - } - elseif (!$GatewayType -and $VlanId) { - Write-Output "Valid VLAN segment configuration" + Try { + $wsaHeaders = @{"Content-Type" = "application/vnd.vmware.horizon.manager.connector.management.directory.sync.profile.syncschedule+json" } + $wsaHeaders.Add("Accept", "application/vnd.vmware.horizon.manager.connector.management.directory.sync.profile.syncschedule+json") + $wsaHeaders.Add("Authorization", "$sessionToken") + $body = '{"frequency":"fifteenMinutes"}' + $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/connectormanagement/directoryconfigs/$directoryId/syncprofile" + Invoke-RestMethod $uri -Method 'PUT' -Headers $wsaHeaders -Body $body } - else { - Write-Error "Gateway type not defined" + Catch { + Write-Error $_.Exception.Message } - - $transportZoneId = (Get-NsxtTransportZone -Name $TransportZone).id - - if ($SegmentType -match "overlay") { - - $json = @" -{ -"display_name" : "$Name", -"subnets" : [{ "gateway_address" : "$Cidr" }], -"connectivity_path" : "$connectivityPath", -"transport_zone_path" : "/infra/sites/default/enforcement-points/default/transport-zones/$transportZoneId" } -"@ +Export-ModuleMember -Function Set-WSASyncSetting - } - elseif ($SegmentType -match "vlan") { +Function Start-WSADirectorySync { + <# + .SYNOPSIS + Start an directory sync - $json = @" -{ -"display_name" : "$Name", -"vlan_ids" : [ "$VlanId" ], -"transport_zone_path" : "/infra/sites/default/enforcement-points/default/transport-zones/$transportZoneId" -} -"@ + .DESCRIPTION + The Start-WSADirectorySync cmdlets triggers a directory sync in Workspace ONE Access - } - else { - Write-Error "SegmentType $SegmentType is invalid." - } + .EXAMPLE + Start-WSADirectorySync -directoryId a1c985d5-0eeb-4a66-bc51-11eda9321aac + This example starts a directory sync in Workspace ONE Access + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$directoryId + ) Try { - $uri = "https://$nsxtManager/policy/api/v1/infra/segments/$Name" - $response = Invoke-RestMethod -Method PUT -URI $uri -ContentType application/json -Body $json -headers $nsxtHeaders - $response + $wsaHeaders = @{"Content-Type" = "application/vnd.vmware.horizon.manager.connector.management.directory.sync.profile.sync+json" } + $wsaHeaders.Add("Accept", "application/vnd.vmware.horizon.v1.0+json") + $wsaHeaders.Add("Authorization", "$sessionToken") + $body = '{"ignoreSafeguards":true}' + $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/connectormanagement/directoryconfigs/$directoryId/syncprofile/sync" + Invoke-RestMethod $uri -Method 'POST' -Headers $wsaHeaders -Body $body } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function New-NsxtSegment +Export-ModuleMember -Function Start-WSADirectorySync -Function Get-NsxtSegment { +Function Set-WSADirectoryUser { <# - .SYNOPSIS - Get a list of Segments - - .DESCRIPTION - The Get-NsxtSegment cmdlet retrieves a list of Segments + .SYNOPSIS + Add users to directory - .EXAMPLE - Get-NsxtSegment - This example gets all Segments + .DESCRIPTION + The Set-WSADirectoryUser cmdlets configures the user/ou that should be sycncronised for Workspace ONE Access - .EXAMPLE - Get-NsxtSegment -name sfo-w01-kub-seg01 - This example gets the segment with the name sfo-w01-kub-seg01 - #> + .EXAMPLE + Set-WSADirectoryUser -directoryId a1c985d5-0eeb-4a66-bc51-11eda9321aac -json (Get-Content -Raw .\adUsers.json) + This example configures the user/ou that should be sycncronised for Workspace ONE Access + #> Param ( - [Parameter (Mandatory = $false)] [String]$name + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$directoryId, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$json ) Try { - if (!$PsBoundParameters.ContainsKey("name")) { - $uri = "https://$nsxtManager/policy/api/v1/infra/segments/" - $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders - $response.results | Sort-Object display_name - } - elseif ($PsBoundParameters.ContainsKey("name")) { - $uri = "https://$nsxtManager/policy/api/v1/infra/segments/" - $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders - $response.results | Where-Object { $_.display_name -eq $name } - } + $wsaHeaders = @{"Content-Type" = "application/vnd.vmware.horizon.manager.connector.management.directory.sync.profile.users+json" } + $wsaHeaders.Add("Accept", "application/vnd.vmware.horizon.manager.connector.management.directory.sync.profile.users+json") + $wsaHeaders.Add("Authorization", "$sessionToken") + $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/connectormanagement/directoryconfigs/$directoryId/syncprofile" + Invoke-RestMethod $uri -Method 'PUT' -Headers $wsaHeaders -Body $json } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-NsxtSegment +Export-ModuleMember -Function Set-WSADirectoryUser -Function Remove-NsxtSegment { +Function Set-WSADirectoryGroup { <# - .SYNOPSIS - Removes a named Segment + .SYNOPSIS + Add groups to directory - .DESCRIPTION - The Remove-NsxtSegment cmdlet removes a named segment. + .DESCRIPTION + The Set-WSADirectoryGroup cmdlets configures the groups/ou that should be sycncronised for Workspace ONE Access - .EXAMPLE - Remove-NsxtSegment -name sfo-w01-kub-seg01 - This example removes the segment with the name sfo-w01-kub-seg01 - #> + .EXAMPLE + Set-WSADirectoryUser -directoryId a1c985d5-0eeb-4a66-bc51-11eda9321aac -json (Get-Content -Raw .\adGroups.json) + This example configures the groups/ou that should be sycncronised for Workspace ONE Access + #> Param ( - [Parameter (Mandatory = $false)] [String]$Name + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$directoryId, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$json ) Try { - $preCheckSegment = Get-NsxtSegment -Name $name -ErrorAction SilentlyContinue + $wsaHeaders = @{"Content-Type" = "application/vnd.vmware.horizon.manager.connector.management.directory.sync.profile.groups+json" } + $wsaHeaders.Add("Accept", "application/vnd.vmware.horizon.manager.connector.management.directory.sync.profile.groups+json") + $wsaHeaders.Add("Authorization", "$sessionToken") + $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/connectormanagement/directoryconfigs/$directoryId/syncprofile" + $response = Invoke-RestMethod $uri -Method 'PUT' -Headers $wsaHeaders -Body $json + $response } Catch { Write-Error $_.Exception.Message } +} +Export-ModuleMember -Function Set-WSADirectoryGroup - if ($preCheckSegment -eq "NSX segment $Name was not found") { - Write-Error $preCheckSegment - Break - } +Function Get-WSASmtpConfiguration { + <# + .SYNOPSIS + Get SMTP configuration + + .DESCRIPTION + The Get-WSASmtpConfiguration cmdlets retrieves the SMTP configurtion of Workspace ONE Access + + .EXAMPLE + Get-WSASmtpConfiguration + This example gets the current SMTP configuration of Workspace ONE Access + #> Try { - $uri = "https://$nsxtManager/policy/api/v1/infra/segments/$Name" - $response = Invoke-RestMethod -Method DELETE -URI $uri -ContentType application/json -headers $nsxtHeaders + $wsaHeaders = @{"Accept" = "application/json, text/plain, */*" } + $wsaHeaders.Add("Authorization", "$sessionToken") + $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/system/config/smtp" + $response = Invoke-RestMethod $uri -Headers $wsaHeaders $response } Catch { Write-Error $_.Exception.Message } +} +Export-ModuleMember -Function Get-WSASmtpConfiguration + +Function Set-WSASmtpConfiguration { + <# + .SYNOPSIS + Set SMTP configuration + + .DESCRIPTION + The Set-WSASmtpConfiguration cmdlets configures the SMTP configurtion of Workspace ONE Access + + .EXAMPLE + Set-WSASmtpConfiguration + This example sets the SMTP configuration of Workspace ONE Access + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$fqdn, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$port, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$pass + ) - # Validation Try { - $checkSegment = Get-NsxtSegment -Name $Name -ErrorAction SilentlyContinue + $wsaHeaders = @{"Accept" = "application/json, text/plain, */*" } + $wsaHeaders.Add("Content-Type", "application/vnd.vmware.horizon.manager.system.config.smtp+json") + $wsaHeaders.Add("Authorization", "$sessionToken") + if (-not $PsBoundParameters.ContainsKey("pass")) { + $body = '{ "host": "' + $fqdn + '", "port": ' + $port + ', "user": "' + $user + '", "password": "' + $pass + '"}' + } + else { + $body = '{ "host": "' + $fqdn + '", "port": ' + $port + ', "user": "' + $user + '" }' + } + $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/system/config/smtp" + $response = Invoke-RestMethod $uri -Method 'PUT' -Headers $wsaHeaders -Body $body + $response } Catch { Write-Error $_.Exception.Message } - - if ($checkSegment -eq "NSX segment $Name was not found") { - Write-Output "NSX-T Segment $Name has been successfully deleted." - } - else { - Write-Error -Message "NSX-T Segment $Name was not deleted. Please check the logs." - } } -Export-ModuleMember -Function Remove-NsxtSegment +Export-ModuleMember -Function Set-WSASmtpConfiguration -Function Get-NsxtTier0Gateway { +Function Set-WSARoleMember { <# - .SYNOPSIS - Get a list of Tier 0 Gateways + .SYNOPSIS + Set WSA Role Member - .DESCRIPTION - The Get-NsxtTier0 cmdlet retrieves a list of Tier 0 Gateways + .DESCRIPTION + The Set-WSARoleMember cmdlets updates the Role with the given group - .EXAMPLE - Get-NsxtTier0Gateway - This example returns all Tier 0 Gateways + .EXAMPLE + Set-WSARoleMember -id 55048dee-fe1b-404a-936d-3e0b86a7209e -groupId fe515568-fdcd-43c7-9971-e834d7246203 + This example updates the Role with the given GroupId in Workspace ONE Access + #> - .EXAMPLE - Get-NsxtTier0Gateway -name sfo-w01-ec01-t0-gw01 - This example returns the Tier 0 Gateway named sfo-w01-ec01-t0-gw01 + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$groupId + ) - .EXAMPLE - Get-NsxtTier0Gateway -id 84a6c7a5-9fe8-4446-8684-814663399584 - This example returns the Tier 0 Gateway based on its id - #> + Try { + $wsaHeaders = @{"Content-Type" = "application/json" } + $wsaHeaders.Add("Authorization", "$sessionToken") + if ($PsBoundParameters.ContainsKey("id")) { + $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/scim/Roles/$id" + + $json = @" + { + "schemas": [ + "urn:scim:schemas:core:1.0" + ], + "members": [ + { + "value": "$groupId", + "type": "Group" + } + ] + } +"@ + $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -body $json -headers $wsaHeaders + $response + } + } + Catch { + Write-Error $_.Exception.Message + } +} + +Function Get-WSARole { + <# + .SYNOPSIS + Get roles + + .DESCRIPTION + The Get-WSARole cmdlets retrieves the roles in Workspace ONE Access + + .EXAMPLE + Get-WSARole + This example retrieves the roles in Workspace ONE Access + #> Param ( - [Parameter (Mandatory = $false)] [String]$name, - [Parameter (Mandatory = $false)] [String]$id + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id ) Try { - if (!$PsBoundParameters.ContainsKey("name") -and !$PsBoundParameters.ContainsKey("id")) { - $uri = "https://$nsxtmanager/policy/api/v1/infra/tier-0s" - $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders - $response.results - } - elseif ($PsBoundParameters.ContainsKey("id")) { - $uri = "https://$nsxtmanager/policy/api/v1/infra/tier-0s/$id" - $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders + $wsaHeaders = @{"Content-Type" = "application/json" } + $wsaHeaders.Add("Authorization", "$sessionToken") + if ($PsBoundParameters.ContainsKey("id")) { + $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/scim/Roles/$id" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders $response } - elseif ($PsBoundParameters.ContainsKey("name")) { - $uri = "https://$nsxtmanager/policy/api/v1/infra/tier-0s" - $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders - $response.results | Where-Object { $_.display_name -eq $name } + else { + $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/scim/Roles" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders + $response.Resources } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-NsxtTier0Gateway +Export-ModuleMember -Function Get-WSARole -Function Get-NsxtTier1Gateway { +Function Get-WSAGroup { <# - .SYNOPSIS - Get a list of Tier 1 Gateways - - .DESCRIPTION - The Get-NsxtTier1Gateway cmdlet retrieves a list of Tier 1 Gateways - - .EXAMPLE - Get-NsxtTier1Gateway - This example returns all Tier 1 Gateways + .SYNOPSIS + Get groups - .EXAMPLE - Get-NsxtTier1Gateway -name sfo-w01-ec01-t1-gw01 - This example returns the Tier 1 Gateway named sfo-w01-ec01-t1-gw01 + .DESCRIPTION + The Get-WSAGroup cmdlets retrieves the groups in Workspace ONE Access - .EXAMPLE - Get-NsxtTier1Gateway -id 84a6c7a5-9fe8-4446-8684-814663399584 - This example returns the Tier 1 Gateway based on its id - #> + .EXAMPLE + Get-WSAGroup + This example retrieves the groups in Workspace ONE Access + #> Param ( - [Parameter (Mandatory = $false)] [String]$name, - [Parameter (Mandatory = $false)] [String]$id + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id ) Try { - if ( -not $PsBoundParameters.ContainsKey("name")) { - $uri = "https://$nsxtmanager/policy/api/v1/infra/tier-1s" - $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders - $response.results - } - elseif ($PsBoundParameters.ContainsKey("id")) { - $uri = "https://$nsxtmanager/policy/api/v1/infra/tier-1s/$id" - $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders + $wsaHeaders = @{"Content-Type" = "application/json" } + $wsaHeaders.Add("Authorization", "$sessionToken") + if ($PsBoundParameters.ContainsKey("id")) { + $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/scim/Groups/$id" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders $response } - elseif ($PsBoundParameters.ContainsKey("name")) { - $uri = "https://$nsxtmanager/policy/api/v1/infra/tier-1s" - $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders - $response.results | Where-Object { $_.display_name -eq $name } + else { + $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/scim/Groups" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders + $response.Resources } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-NsxtTier1Gateway +Export-ModuleMember -Function Get-WSAGroup -Function Get-NsxtPrefixList { +Function Get-WSAUser { <# - .SYNOPSIS - Get Tier-0 Gateway IP Prefix Lists - - .DESCRIPTION - The Get-NsxtTier0PrefixList cmdlet retrieves the IP Prefix Lists assigned to a Tier-0 Gateway + .SYNOPSIS + Get users - .EXAMPLE - Get-NsxtPrefixList -tier0Gateway sfo-w01-ec01-t0-gw01 - This example returns all IP Prefix Lists + .DESCRIPTION + The Get-WSAUser cmdlets retrieves the users in Workspace ONE Access - .EXAMPLE - Get-NsxtPrefixList -name sfo-w01-cl01-prefix-list -tier0Gateway sfo-w01-ec01-t0-gw01 - This example returns the IP Prefix List based on the prefix name provided - - .EXAMPLE - Get-NsxtTier0Gateway -name sfo-w01-ec01-t0-gw01 | Get-NsxtPrefixList -name sfo-w01-cl01-prefix-list - This example returns the IP Prefix List based on the prefix name provided - #> + .EXAMPLE + Get-WSAUser + This example retrieves the users in Workspace ONE Access + #> Param ( - [Parameter (Mandatory = $false)] [String]$tier0Gateway, - [Parameter (Mandatory = $false)] [String]$name, - [Parameter (ValueFromPipeline, Mandatory = $false)] [psObject]$inputObject + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id ) - # Validating pipeline input resource_type - if ($inputObject -and $inputObject.resource_type -eq "Tier0") { - $tier0Gateway = $inputObject.display_name - $uriPath = $inputObject.path - } - elseif ($inputObject -and $inputObject.resource_type -ne "Tier0") { - Write-Error "Invalid pipeline passthrough. Exiting." - Break - } - elseif (!$inputObject -and $Tier0Gateway) { - $uriPath = (Get-NsxtTier0Gateway -Name $Tier0Gateway).path - } - else { - if (!$tier0Gateway) { - $tier0Gateway = Read-Host -Prompt "Tier-0 Gateway not defined. Type in the name of your Tier-0 Gateway, then press Enter" - } - } - Try { - if (!$name) { - $uri = "https://$nsxtmanager/policy/api/v1"+$uriPath+"/prefix-lists" - $response = Invoke-RestMethod -Method GET -URI $uri -headers $nsxtHeaders -ErrorAction SilentlyContinue - $response.results + $wsaHeaders = @{"Content-Type" = "application/json" } + $wsaHeaders.Add("Authorization", "$sessionToken") + if ($PsBoundParameters.ContainsKey("id")) { + $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/scim/Users/$id" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders + $response } - elseif ($name) { - $uri = "https://$nsxtmanager/policy/api/v1"+$uriPath+"/prefix-lists" - $response = Invoke-RestMethod -Method GET -URI $uri -headers $nsxtHeaders -ErrorAction SilentlyContinue - $response.results | Where-Object { $_.display_name -eq $name } + else { + $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/scim/Users" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders + $response.Resources } } Catch { - if ($_.Exception -match "400" -or $_.Exception -match "Bad Request") { - Write-Output $uri - Write-Error "The NSX Tier-0 Gateway was not properly defined" - - } + Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-NsxtPrefixList +Export-ModuleMember -Function Get-WSAUser -Function New-NsxtPrefixList { +Function Get-WSARuleSet { <# - .SYNOPSIS - Creates a Tier-0 Gateway IP Prefix List - - .DESCRIPTION - The New-NsxtPrefixList cmdlet creates a Prefix List on a specified Tier-0 Gateway - - .EXAMPLE - New-NsxtPrefixList -Name sfo-w01-cl01-prefix-list -Tier0Gateway sfo-w01-ec01-t0-gw01 - This example creates a new IP Prefix List on a Tier 0 Gateway - #> - - Param ( - [Parameter (Mandatory = $false)] [String]$Name, - [Parameter (Mandatory = $false)] [String]$Tier0Gateway, - [Parameter (Mandatory = $false)] [String]$SubnetCIDR, - [Parameter (Mandatory = $false)] [String]$GE, - [Parameter (Mandatory = $false)] [String]$LE, - [Parameter (Mandatory = $false)] [ValidateSet("PERMIT", "DENY")] [String]$Action, - [Parameter (Mandatory = $false)] [String]$Json, - [Parameter (ValueFromPipeline, Mandatory = $false)] [psObject]$inputObject - ) + .SYNOPSIS + Get rulesets - # Validating pipeline input resource_type - if ($inputObject -and $inputObject.resource_type -eq "Tier0") { - $uriPath = $inputObject.path - $Tier0Gateway = $inputObject.display_name - } - elseif ($inputObject -and $inputObject.resource_type -ne "Tier0") { - Write-Error "Invalid pipeline passthrough. Exiting." - Break - } - elseif (!$inputObject) { - if (!$Tier0Gateway) { - $Tier0Gateway = Read-Host -Prompt "Tier-0 Gateway not defined. Type in the name of your Tier-0 Gateway, then press Enter" - $uriPath = (Get-NsxtTier0Gateway -Name $Tier0Gateway).path - } - } + .DESCRIPTION + The Get-WSARuleSet cmdlets retrieves the rulesets in Workspace ONE Access - if (!$json) { - if (!$GE -or !$LE) { - $Json = @" -{ - "display_name" : "$Name", - "prefixes" : - [ - { - "network" : "$SubnetCIDR", - "action" : "$Action" - } - ] -} -"@ - } - elseif ($GE -and $LE) { - $Json = @" -{ - "display_name" : "$Name", - "prefixes" : - [ - { - "network" : "$SubnetCIDR", - "action" : "$Action", - "ge" : "$GE", - "le" : "$LE" - } - ] -} -"@ - } - else { - Write-Error "Invalid subnet configuration." - } - } + .EXAMPLE + Get-WSARuleSet + This example retrieves the rulesets in Workspace ONE Access + #> Try { - $global:uri = "https://$nsxtmanager/policy/api/v1"+$uriPath+"/prefix-lists/$Name" - $global:response = Invoke-RestMethod -Method PUT -URI $uri -ContentType application/json -body $json -headers $nsxtHeaders - $response + $wsaHeaders = @{"Accept-Type" = "application/json, text/plain, */*" } + $wsaHeaders.Add("Content-Type", "application/vnd.vmware.vidm.accesscontrol.ruleset.list+json") + $wsaHeaders.Add("Authorization", "$sessionToken") + $uri = "https://$workSpaceOne/acs/rulesets" + $response = Invoke-RestMethod $uri -Headers $wsaHeaders + $response.items } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function New-NsxtPrefixList +Export-ModuleMember -Function Get-WSARuleSet -Function Remove-NsxtPrefixList { +Function Get-WSAOAuthToken { <# - .SYNOPSIS - Remove an IP Prefix List from a Tier-0 Gateway - - .DESCRIPTION - The Remove-NsxtPrefixList cmdlet removes a IP Prefix List from a specified Tier-0 Gateway - - .EXAMPLE - Remove-NsxtPrefixList -Name sfo-w01-cl01-prefix-list -Tier0Gateway sfo-w01-ec01-t0-gw01 - This example removes a Prefix List on a Tier 0 Gateway - #> + .SYNOPSIS + Get AOuth Token - Param ( - [Parameter (Mandatory = $false)] [String]$Name, - [Parameter (Mandatory = $false)] [String]$Tier0Gateway, - [Parameter (ValueFromPipeline, Mandatory = $false)] [psObject]$inputObject - ) + .DESCRIPTION + The Get-WSAOAuthToken cmdlets gets an OAuth token from Workspace ONE Access - # Validating pipeline input resource_type - if ($inputObject -and $inputObject.resource_type -eq "Tier0") { - $uriPath = $inputObject.path - } - elseif ($inputObject -and $inputObject.resource_type -ne "Tier0") { - Write-Error "Invalid pipeline passthrough. Exiting." - Break - } elseif (!$inputObject) { - if (!$Tier0Gateway) { - $Tier0Gateway = Read-Host -Prompt "Tier-0 Gateway not defined. Type in the name of your Tier-0 Gateway, then press Enter" - } - $uriPath = (Get-NsxtTier0Gateway -Name $Tier0Gateway).path - } + .EXAMPLE + Get-WSAOAuthToken + This example retrieves the am OAuth oken from Workspace ONE Access + #> Try { - $preCheckPrefixList = Get-NsxtPrefixList -Name $Name -Tier0Gateway $Tier0Gateway -ErrorAction SilentlyContinue + $wsaHeaders = @{"Content-Type" = "application/x-www-form-urlencoded; charset=UTF-8" } + $wsaHeaders.Add("Accept", "application/json, text/javascript, */*; q=0.01") + $wsaHeaders.Add("Authorization", "$sessionToken") + $uri = "https://$workSpaceOne/SAAS/admin/settings/OAuthClient/generateRandomOAuthSecret" + $response = Invoke-RestMethod $uri -Method 'POST' -Headers $wsaHeaders + $response } Catch { Write-Error $_.Exception.Message } +} +Export-ModuleMember -Function Get-WSAOAuthToken - if ($preCheckPrefixList -eq "NSX IP Prefix List $Name was not found") { - Write-Error $preCheckPrefixList - Break - } +Function Get-WSAClient { + <# + .SYNOPSIS + Get clients - Try { - $uri = "https://$nsxtmanager/policy/api/v1"+$uriPath+"/prefix-lists/$Name" - $response = Invoke-RestMethod -Method DELETE -URI $uri -headers $nsxtHeaders -ContentType application/json - $response - } - Catch { - Write-Error $_.Exception.Message - } + .DESCRIPTION + The Get-WSAClient cmdlets gets a list of clients in Workspace ONE Access + + .EXAMPLE + Get-WSAClient + This example retrieves all clients in Workspace ONE Access + #> + + Param ( + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$clientId + ) - # Validation Try { - $checkPrefixList = Get-NsxtPrefixList -Name $Name -Tier0Gateway $Tier0Gateway -ErrorAction SilentlyContinue + $wsaHeaders = @{"Content-Type" = "application/vnd.vmware.horizon.manager.oauth2client+json" } + $wsaHeaders.Add("Authorization", "$sessionToken") + if ($PsBoundParameters.ContainsKey("clientId")) { + $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/oauth2clients/$clientId" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders + $response + } + else { + $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/oauth2clients" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders + $response.items + } } Catch { Write-Error $_.Exception.Message } - - if ($checkPrefixList -eq "NSX IP Prefix List $Name was not found") { - Write-Output "NSX-T PrefixList $Name has been successfully deleted." - } - else { - Write-Error -Message "NSX-T PrefixList $Name was not deleted. Please check the logs." - } } -Export-ModuleMember -Function Remove-NsxtPrefixList +Export-ModuleMember -Function Get-WSAClient -Function Add-NsxtPrefix { +Function Add-WSAClient { <# - .SYNOPSIS - Add a single entry to an existing NSX IP Prefix List + .SYNOPSIS + Add a client - .DESCRIPTION - The Add-NsxtPrefix cmdlet adds a single entry to an existing NSX IP Prefix List + .DESCRIPTION + The Add-WSAClient cmdlets add a client in Workspace ONE Access - .EXAMPLE - Get-NsxtPrefixList -name sfo-w01-cl01-prefix-list | Add-NsxtPrefix -subnetCIDR 192.168.21.0/24 -LE 32 -GE 28 -action PERMIT - This example adds an IP Prefix entry on an existing IP Prefix List - #> + .EXAMPLE + Add-WSAClient -json .\SampleJson\nsxClient.json + This example retrieves all clients in Workspace ONE Access + #> Param ( - [Parameter (Mandatory = $false)] [String]$prefixListName, - [Parameter (Mandatory = $false)] [String]$tier0Gateway, - [Parameter (Mandatory = $false)] [String]$subnetCIDR, - [Parameter (Mandatory = $false)] [String]$GE, - [Parameter (Mandatory = $false)] [String]$LE, - [Parameter (Mandatory = $false)] [String]$action, - [Parameter (ValueFromPipeline, Mandatory = $false)] [psObject]$inputObject + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$clientId, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$sharedSecret ) - if (!$inputObject -and $tier0Gateway -and $prefixListName) { - $uriPath = (Get-NsxtTier0Gateway -Name $tier0Gateway).path - $existingPrefixes = (Get-NsxtPrefixList -Name $prefixListName -Tier0Gateway $tier0Gateway).prefixes + Try { + $wsaHeaders = @{"Content-Type" = "application/vnd.vmware.horizon.manager.oauth2client+json" } + $wsaHeaders.Add("Authorization", "$sessionToken") + $body = '{ + "clientId": "' + $clientId + '", + "secret": "' + $sharedSecret + '", + "scope": "admin", + "authGrantTypes": "refresh_token client_credentials", + "redirectUri": "", + "tokenType": "Bearer", + "tokenLength": 32, + "accessTokenTTL": 8, + "refreshTokenTTL": 1440, + "refreshTokenIdleTTL": 4, + "rememberAs": "' + $clientId + '", + "displayUserGrant": false, + "internalSystemClient": false, + "inheritanceAllowed": true + }' + $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/oauth2clients" + Invoke-RestMethod $uri -Method 'POST' -Headers $wsaHeaders -body $body + } + Catch { + Write-Error $_.Exception.Message } +} +Export-ModuleMember -Function Add-WSAClient - if ($inputObject -and $inputObject.resource_type -eq "PrefixList") { - $uriPath = $inputObject.parent_path - $Tier0GatewayId = $inputObject.parent_path.Split('/')[3] - $PrefixListName = $inputObject.display_name - $existingPrefixes = $inputObject.prefixes +Function Add-WSARoleAssociation { + <# + .SYNOPSIS + Add the AD group to the WSA role - $getTier0Gateway = Get-NsxtTier0Gateway -name $tier0GatewayId -ErrorAction SilentlyContinue + .DESCRIPTION + Add the AD group to the given WSA role. - if ($getTier0Gateway -eq "NSX Tier-0 Gateway $tier0GatewayId was not found") { - $tier0Gateway = (Get-NsxtTier0Gateway -Id $tier0GatewayId).display_name - } - else { - $Tier0Gateway = $Tier0GatewayId - } + .EXAMPLE + Add-WSARoleAssociation -roleId "1d0b09a1-8744-4f85-8c4f-ac104e586010" -groupId "1e942dc6-94ba-43ef-97ce-9ba34fee1609" + #> - } - elseif ($inputObject -and $inputObject.resource_type -ne "PrefixList") { - Write-Error "Invalid pipeline passthrough" - Break - } + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$roleId, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$groupId + ) - $prefixes = @() + Try { + $wsaHeaders = @{"Content-Type" = "application/vnd.vmware.vidm.accesscontrol.ruleset.associations.bulk.request+json" } + $wsaHeaders.Add("Authorization", "$sessionToken") + $uri = "https://$workSpaceOne/acs/associations/rulesets/$roleId" + $body = '{ + "operations": [ + { + "users": [], + "groups": [ + "'+$groupId+'" + ], + "associationMethodTO": "POST" + }, + { + "users": [], + "groups": [], + "associationMethodTO": "DELETE" + } + ] + }' - $prefixes += $existingPrefixes + $response = Invoke-RestMethod $uri -Method 'POST' -Headers $wsaHeaders -body $body + $response + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Add-WSARoleAssociation - if (!$GE -or !$LE) { - $newPrefix = @{ - network = $subnetCIDR - action = $action - } - } - elseif ($GE -and $LE) { - $newPrefix = @{ - network = $subnetCIDR - action = $action - ge = $GE - le = $LE - } - } - else { - Write-Error "Invalid subnet configuration" - } +Function Get-WSARoleId { + <# + .SYNOPSIS + Get role id for role name - $prefixes += $newPrefix - $prefixesJson = $prefixes | ConvertTo-Json + .DESCRIPTION + Get the role id corresponding to the given role name - $json = @" - { - "display_name": "$PrefixListName", - "prefixes": $prefixesJson - } -"@ + .EXAMPLE + Get-WSARoleId -role "Super Admin" + This retrieves the id for the Super Admin role + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$role + ) + + Try { + $wsaHeaders = @{"Content-Type" = "application/json" } + $wsaHeaders.Add("Authorization", "$sessionToken") + $uri = "https://$workSpaceOne/acs/rulesets" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders + $roledetails = $response.items | Where-Object {$_.name -eq $role} + $roleId=$roledetails._links.self.href.split('/')[3] + $roleId + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Get-WSARoleId + +Function Get-WSAActiveDirectoryGroupDetail { + <# + .SYNOPSIS + Get details of the given Active Directory group + + .DESCRIPTION + Get details from Workspace ONE Access of the given Active Directory group + + .EXAMPLE + Get-WSAActiveDirectoryGroupDetail -group "gg-wsa-admins" + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$group + ) + + Try { + $wsaHeaders = @{"Content-Type" = "application/json" } + $wsaHeaders.Add("Authorization", "$sessionToken") + $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/scim/Groups/.search?locale=en" + $body = '{ + "attributes": "id,displayName", + "filter": "(displayName co \"' + $group + '\")" + }' + $response = Invoke-RestMethod $uri -Method 'POST' -Headers $wsaHeaders -body $body + $response + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Get-WSAActiveDirectoryGroupDetail + +Function Get-WSARoleAssociation { + <# + .SYNOPSIS + Get associations for the given Role Id + + .DESCRIPTION + Get details of associations for the given Role Id. This has details of the groups associated with a role. + + .EXAMPLE + Get-WSARoleAssociation -roleId "1d0b09a1-8744-4f85-8c4f-ac104e586010" + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$roleId + ) + + Try { + $wsaHeaders = @{"Content-Type" = "application/json" } + $wsaHeaders.Add("Authorization", "$sessionToken") + $uri = "https://$workSpaceOne/acs/associations/rulesets/$roleId" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders + $response + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Get-WSARoleAssociation + +Function Get-WSAPasswordLockout { + <# + .SYNOPSIS + Get password lockout policy + + .DESCRIPTION + Get details of the password lockout policy for Workspace ONE Access + + .EXAMPLE + Get-WSAPasswordLockout + #> Try { - $uri = "https://$nsxtmanager/policy/api/v1"+$uriPath+"/prefix-lists/$PrefixListName" - $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -body $json -headers $nsxtHeaders + $wsaHeaders = @{"Accept" = "application/vnd.vmware.horizon.manager.password.lockout+json" } + $wsaHeaders.Add("Authorization", "$sessionToken") + $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/passwordlockoutconfig" + $response = Invoke-RestMethod $uri -Headers $wsaHeaders $response - - if (!$response) { - $output = Get-NsxtPrefixList -Name $PrefixListName -Tier0Gateway $Tier0Gateway - $output - } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Add-NsxtPrefix +Export-ModuleMember -Function Get-WSAPasswordLockout -Function Add-NsxtPrefixList { +Function Set-WSAPasswordLockout { <# .SYNOPSIS - Add an IP Prefix List to a Route Map + Set password lockout policy .DESCRIPTION - The Add-NsxtPrefixList cmdlet adds an IP Prefix List to a Route Map + Set details of the password lockout policy for Workspace ONE Access .EXAMPLE - Get-NsxtPrefixList -Name sfo-w01-cl01-prefix-list | Add-NsxtPrefixList -RouteMap sfo-w01-ec01-route-map -Action PERMIT - This example adds an IP Prefix List to a specific Route Map + Set-WSAPasswordLockout #> Param ( - [Parameter (Mandatory = $false)] [String]$Name, - [Parameter (Mandatory = $false)] [String]$Tier0Gateway, - [Parameter (Mandatory = $false)] [String]$RouteMap, - [Parameter (Mandatory = $false)] [String]$Action, - [Parameter (ValueFromPipeline, Mandatory = $false)] [psObject]$inputObject + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$numAttempts, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$attemptInterval, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$unlockInterval ) - if ($inputObject) { - $Tier0GatewayId = $inputObject.parent_path.Split('/')[3] - $Tier0Gateway = (Get-NsxtTier0Gateway -Id $Tier0GatewayId).display_name - - if ($inputObject.resource_type -eq "Tier0RouteMap") { - $RouteMap = $inputObject.display_name - $existingEntries = $inputObject.entries - $uriPath = $inputObject.parent_path - } - elseif ($inputObject.resource_type -eq "PrefixList" -and $RouteMap) { - $routeMapInput = Get-NsxtTier0Gateway -Name $Tier0Gateway | Get-NsxtRouteMap -Name $RouteMap - $existingEntries = $routeMapInput.entries - $uriPath = $routeMapInput.parent_path - } - else { - Write-Error "Invalid pipeline passthrough. Exiting." - Break - } - } - - $prefixListPath = (Get-NsxtTier0Gateway -Name $Tier0Gateway | Get-NsxtPrefixList -Name $Name).path - $prefixListPathArray = @() - $prefixListPathArray += $prefixListPath - - $existingEntriesPrefixListMatches = $existingEntries.prefix_list_matches - $existingPrefixListPathArray = @() - $existingPrefixListPathArray += $existingEntriesPrefixListMatches - - $existingEntriesAction = $existingEntries.action - - - $existingEntry = @{ - prefix_list_matches = $existingPrefixListPathArray - action = $existingEntriesAction - } - - $newEntry = @{ - prefix_list_matches = $prefixListPathArray - action = $Action - } - - $entries = @() - $entries += $existingEntry - $entries += $newEntry - - $entriesJson = $entries | ConvertTo-Json - - $json = @" - { - "entries": $entriesJson - } -"@ - Try { - $uri = "https://$nsxtmanager/policy/api/v1/"+$uriPath+"/route-maps/$RouteMap" - $response = Invoke-RestMethod -Method PUT -URI $uri -ContentType application/json -body $json -headers $nsxtHeaders + $wsaHeaders = @{"Accept" = "application/vnd.vmware.horizon.manager.password.lockout+json" } + $wsaHeaders.Add("Authorization", "$sessionToken") + $wsaHeaders.Add("Content-Type", "application/vnd.vmware.horizon.manager.password.lockout+json") + $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/passwordlockoutconfig" + $body = '{"numAttempts":'+$numAttempts+',"attemptInterval":'+$attemptInterval+',"unlockInterval":'+$unlockInterval+'}' + $response = Invoke-RestMethod $uri -Method 'PUT' -Headers $wsaHeaders -Body $body $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Add-NsxtPrefixList +Export-ModuleMember -Function Set-WSAPasswordLockout -Function Get-NsxtRouteMap { +Function Get-WSAPasswordPolicy { <# .SYNOPSIS - Get Tier-0 Gateway Route Maps + Get password policy .DESCRIPTION - The Get-NsxtRouteMap cmdlet retrieves the Route Maps assigned to a specified Tier-0 Gateway - - .EXAMPLE - Get-NsxtRouteMap -tier0Gateway sfo-w01-ec01-t0-gw01 - This example gets all Route Maps on the Tier-0 Gateway + Get details of the password policy for Workspace ONE Access .EXAMPLE - Get-NsxtRouteMap -tier0Gateway sfo-w01-ec01-t0-gw01 -name sfo-w01-ec01-t0-gw01-routemap - This example gets a specific route map by name from the Tier-0 Gateway + Get-WSAPasswordPolicy #> - Param ( - [Parameter (Mandatory = $true)] [String]$tier0Gateway, - [Parameter (Mandatory = $false)] [String]$name, - [Parameter (ValueFromPipeline, Mandatory = $false)] [psObject]$inputObject - ) - - # Validating pipeline input resource_type - if ($inputObject -and $inputObject.resource_type -eq "Tier0") { - $tier0Gateway = $inputObject.display_name - $uriPath = $inputObject.path - } - elseif ($inputObject -and $inputObject.resource_type -ne "Tier0") { - Write-Error "Invalid pipeline passthrough. Exiting." - Break - } - elseif (!$inputObject) { - if (!$tier0Gateway) { - Write-Output "Tier 0 Gateway: $Tier0Gateway" - $Tier0Gateway = Read-Host -Prompt "Tier-0 Gateway not defined. Type in the name of your Tier-0 Gateway, then press Enter" - } - $uriPath = (Get-NsxtTier0Gateway -Name $tier0Gateway).path - } - Try { - if (!$PsBoundParameters.ContainsKey("Name")) { - $uri = "https://$nsxtmanager/policy/api/v1"+$uriPath+"/route-maps" - $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders - $response.results - } - elseif ($PsBoundParameters.ContainsKey("Name")) { - $uri = "https://$nsxtmanager/policy/api/v1"+$uriPath+"/route-maps" - $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders - $response.results | Where-Object { $_.display_name -eq $Name } - } + $wsaHeaders = @{"Accept" = "application/vnd.vmware.horizon.manager.tenants.tenant.passwordpolicy+json" } + $wsaHeaders.Add("Authorization", "$sessionToken") + $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/tenants/tenant/passwordpolicy" + $response = Invoke-RestMethod $uri -Headers $wsaHeaders + $response } Catch { - if ($_.Exception -match "400" -or $_.Exception -match "Bad Request") { - Write-Error "The NSX Tier-0 Gateway was not properly defined." - } + Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-NsxtRouteMap +Export-ModuleMember -Function Get-WSAPasswordPolicy -Function New-NsxtRouteMap { +Function Set-WSAPasswordPolicy { <# .SYNOPSIS - Creates a Route Map on a specified Tier-0 Gateway + Set password lockout policy .DESCRIPTION - The New-NsxtRouteMap cmdlet creates a Route Map on a specified Tier-0 Gateway - - .EXAMPLE - New-NsxtRouteMap -Name sfo-w01-cl01-route-map -Tier0Gateway sfo-w01-ec01-t0-gw01 -PrefixList sfo-w01-ec01-prefix-list - This example creates a new Route Map on a Tier-0 Gateway + Set details of the password lockout policy for Workspace ONE Access .EXAMPLE - Net-NsxtTier0Gateway sfo-w01-ec01-t0-gw01 | Get-NsxtPrefixList -Name sfo-w01-ec01-prefix-list | New-NsxtRouteMap -Name sfo-w01-cl01-route-map - This example creates a new Route Map on a Tier-0 Gateway + Set-WSAPasswordPolicy -minLen 6 -minLower 0 -minUpper 0 -minDigit 0 -minSpecial 0 -history 0 -maxConsecutiveIdenticalCharacters 3 -maxPreviousPasswordCharactersReused 2 -tempPasswordTtlInHrs 167 -passwordTtlInDays 81 -notificationThresholdInDays 16 -notificationIntervalInDays 11 #> Param ( - [Parameter (Mandatory = $false)] [String]$Name, - [Parameter (Mandatory = $false)] [String]$Tier0Gateway, - [Parameter (Mandatory = $false)] [String]$PrefixList, - [Parameter (Mandatory = $false)] [String]$Action, - [Parameter (Mandatory = $false)] [String]$Json, - [Parameter (ValueFromPipeline, Mandatory = $false)] [psObject]$inputObject - ) - - if ($inputObject) { - if ($inputObject.resource_type -eq "Tier0") { - $Tier0Gateway = $inputObject.display_name - $Tier0GatewayId = $inputObject.id - $uriPath = $inputObject.path - } - elseif ($inputObject.resource_type -eq "PrefixList") { - $Tier0GatewayId = $inputObject.parent_path.Split('/')[3] - $PrefixListPath = $inputObject.path - $Tier0Gateway = (Get-NsxtTier0Gateway -Id $Tier0GatewayId).display_name - $uriPath = $inputObject.parent_path - } - else { - Write-Error "Invalid pipeline passthrough. Exiting." - Break - } - } elseif (!$inputObject){ - $uriPath = (Get-NsxtTier0Gateway -Name $Tier0Gateway).path - } - - if (!$PrefixListPath) { - $PrefixListPath = $uriPath+"/prefix-lists/"+$PrefixList - } + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$minLen, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$minLower, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$minUpper, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$minDigit, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$minSpecial, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$history, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$maxConsecutiveIdenticalCharacters, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$maxPreviousPasswordCharactersReused, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tempPasswordTtlInHrs, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$passwordTtlInDays, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$notificationThresholdInDays, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$notificationIntervalInDays - $json = @" -{ - "display_name" : "$Name", - "entries" : - [ - { - "action" : "$Action", - "prefix_list_matches" : [ "$prefixListPath" ] - } - ] -} -"@ + ) Try { - $uri = "https://$nsxtmanager/policy/api/v1"+$uriPath+"/route-maps/$Name" - $response = Invoke-RestMethod -Method PUT -URI $uri -ContentType application/json -body $json -headers $nsxtHeaders - $response + $wsaHeaders = @{"Accept" = "application/vnd.vmware.horizon.manager.tenants.tenant.passwordpolicy+json" } + $wsaHeaders.Add("Authorization", "$sessionToken") + $wsaHeaders.Add("Content-Type", "application/vnd.vmware.horizon.manager.tenants.tenant.passwordpolicy+json") + $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/tenants/tenant/passwordpolicy" + $passwordTtlInHours = [int]$passwordTtlInDays * 24 + $notificationThresholdInMilliSec = [int]$notificationThresholdInDays * 24 * 3600 * 1000 + $notificationIntervalInMilliSec = [int]$notificationIntervalInDays * 24 * 3600 * 1000 + $body = '{ + "minLen":'+$minLen+', + "minLower":'+$minLower+', + "minUpper":'+$minUpper+', + "minDigit":'+$minDigit+', + "minSpecial":'+$minSpecial+', + "history":'+$history+', + "maxConsecutiveIdenticalCharacters":'+$maxConsecutiveIdenticalCharacters+', + "maxPreviousPasswordCharactersReused":'+$maxPreviousPasswordCharactersReused+', + "tempPasswordTtl":'+$tempPasswordTtlInHrs+', + "passwordTtlInHours":'+$passwordTtlInHours+', + "notificationThreshold":'+$notificationThresholdInMilliSec+', + "notificationInterval":'+$notificationIntervalInMilliSec+' + }' + Write-OutPut $body + $response = Invoke-RestMethod $uri -Method 'PUT' -Headers $wsaHeaders -Body $body } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function New-NsxtRouteMap +Export-ModuleMember -Function Set-WSAPasswordPolicy -Function Remove-NsxtRouteMap { +############ End Workspace ONE Access Functions ############ +############################################################## + + +############################################################## +############ Begin NSX-T Data Center Functions ############# + +Function Request-NsxToken { <# .SYNOPSIS - Remove a Route Map from a specified Tier-0 Gateway + Connects to the specified NSX Manager .DESCRIPTION - The Remove-NsxtRouteMap cmdlet removes a Route Map attached to a specified Tier-0 Gateway + The Request-NsxToken cmdlet connects to the specified NSX Manager with the supplied credentials .EXAMPLE - Remove-NsxtRouteMap -name sfo-w01-ec01-t0-gw01-routemap -tier0Gateway sfo-w01-ec01-t0-gw01 - This example removes the Route Map sfo-w01-ec01-t0-gw01-routemap from Tier-0 Gateway sfo-w01-ec01-t0-gw01 + Request-NsxToken -fqdn sfo-w01-nsx01.sfo.rainpole.io -username admin -password VMware1!VMw@re1! + This example shows how to connect to NSX Manager + + .EXAMPLE + Get-NsxtServerDetail -fqdn sfo-vcf01.sfo.rainpole.io -username admin@local -password VMw@re1!VMw@re1! -domain sfo-w01 | Request-NsxToken + This example shows how to connect to NSX Manager using pipeline input from Get-NsxtServerDetail #> Param ( - [Parameter (Mandatory = $false)] [String]$name, - [Parameter (Mandatory = $false)] [String]$tier0Gateway, - [Parameter (ValueFromPipeline, Mandatory = $false)] [psObject]$inputObject + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()][String]$fqdn, + [Parameter (Mandatory = $false)] [String]$username, + [Parameter (Mandatory = $false)] [String]$password, + [Parameter (ValueFromPipeline, Mandatory = $false)] [psobject]$inputObject ) if ($inputObject) { - if ($inputObject.resource_type -eq "Tier0RouteMap") { - $Name = $inputObject.display_name - $Tier0GatewayId = $inputObject.parent_path.Split('/')[3] - $Tier0Gateway = (Get-NsxtTier0Gateway -Id $Tier0GatewayId).display_name - $uriPath = $inputObject.parent_path - } - elseif ($inputObject.resource_type -eq "Tier0" -and $Name -and !$Tier0Gateway) { - $Tier0GatewayId = $inputObject.id - $Tier0Gateway = $inputObject.display_name - $uriPath = $inputObject.path - } - else { - Write-output $inputObject.resource_type - Write-Error "Invalid pipeline passthrough. Exiting." - Break - } + $username = $inputObject.adminUser + $password = $inputObject.adminPass + $fqdn = $inputObject.fqdn + $sddcManager = (Get-VCFManager).fqdn } - elseif (!$inputObject) { - if (!$tier0Gateway) { - $tier0Gateway = Read-Host -Prompt "Tier-0 Gateway not defined. Type in the name of your Tier-0 Gateway, then press Enter" + else { + if (!$PsBoundParameters.ContainsKey("username") -or (!$PsBoundParameters.ContainsKey("password"))) { + # Request Credentials + $creds = Get-Credential + $username = $creds.UserName.ToString() + $password = $creds.GetNetworkCredential().password + } + if (!$PsBoundParameters.ContainsKey("fqdn")) { + $fqdn = Read-Host "NSX Manager FQDN not found, please enter a value e.g. sfo-m01-nsx01.sfo.rainpole.io" } - $uriPath = (Get-NsxtTier0Gateway -Name $Tier0Gateway).path } + # Validate credentials by executing an API call + $Global:nsxtHeaders = createBasicAuthHeader $username $password + $Global:nsxtmanager = $fqdn + $uri = "https://$nsxtmanager/api/v1/logical-ports" + Try { - $preCheckRouteMap = Get-NsxtRouteMap -name $Name -tier0Gateway $Tier0Gateway -ErrorAction SilentlyContinue + # Checking against the NSX Managers API + # PS Core has -SkipCertificateCheck implemented, PowerShell 5.x does not + if ($PSEdition -eq 'Core') { + $response = Invoke-RestMethod -Method GET -Uri $uri -Headers $nsxtHeaders -SkipCertificateCheck + } + else { + $response = Invoke-RestMethod -Method GET -Uri $uri -Headers $nsxtHeaders + } + if ($response) { + if ($inputObject) { + Write-Output "Successfully Requested New API Token for NSX Manager $nsxtmanager via SDDC Manager $sddcManager" + } + else { + Write-Output "Successfully Requested New API Token for NSX Manager $nsxtmanager" + } + } } Catch { Write-Error $_.Exception.Message } +} +Export-ModuleMember -Function Request-NsxToken - if ($preCheckRouteMap -eq "NSX-T RouteMap $Name was not found.") { - Write-Error $preCheckRouteMap - Break - } +Function Get-NsxtComputeManager { + <# + .SYNOPSIS + Retrieves a list of compute managers from NSX Manager + + .DESCRIPTION + The Get-NsxtComputeManager cmdlet gets compute managers from NSX Manager + + .EXAMPLE + Get-NsxtComputeManager + This example gets all compute managers + + .EXAMPLE + Get-NsxtComputeManager -vCenterServer "sfo-m01-vc01.sfo.rainpole.io" + This example gets the compute manager named "sfo-m01-vc01.sfo.rainpole.io" + #> + + Param ( + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vCenterServer + ) - # Check if the route map is applied to the route redistribution configuration Try { - $getRouteRedistribution = Get-NsxtRouteRedistributionPolicy -tier0Gateway $tier0Gateway - if ($getRouteRedistribution.route_redistribution_config.redistribution_rules.route_map_path -eq $preCheckRouteMap.path) { - $getRouteRedistribution | Set-NsxtRouteRedistributionPolicy -tier0Gateway $tier0Gateway -RemoveRouteMap:$True | Out-Null + if (!$PsBoundParameters.ContainsKey("vCenterServer")) { + $uri = "https://$nsxtManager/api/v1/fabric/compute-managers" + $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders + $response.results + } + elseif ($PsBoundParameters.ContainsKey("vCenterServer")) { + $uri = "https://$nsxtManager/api/v1/fabric/compute-managers" + $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders + $responseChecked = $response.results | Where-Object { $_.server -eq $vCenterServer } + + if (!$responseChecked) { + Write-Output "Compute Manager $vCenterServer was not found." + } + elseif ($responseChecked) { + $responseChecked + } } } Catch { Write-Error $_.Exception.Message } +} +Export-ModuleMember -Function Get-NsxtComputeManager + +Function Set-NsxtComputeManager { + <# + .SYNOPSIS + Configure a set of parameters on a compute manager + + .DESCRIPTION + The Set-NsxtComputeManager cmdlet configures a set of parameters on a compute manager + + .EXAMPLE + Get-NsxtComputeManager -vCenterServer sfo-w01-vc01.sfo.rainpole.io | Set-NsxtComputeManager -EnableTrust:$true + This example enables trust (sets OIDC provider to true) for Compute Manager sfo-w01-vc01.sfo.rainpole.io + In this release, it is required to use pipeline input from Get-NsxtComputeManager. + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Bool]$EnableTrust, + [Parameter (ValueFromPipeline, Mandatory = $true)] [psObject]$inputObject + ) + + # Validating pipeline input resource_type + if ($inputObject.resource_type -ne "ComputeManager") { + Write-Error "Invalid pipeline passthrough." + break + } + elseif ($inputObject.resource_type -eq "ComputeManager") { + $computeManagerId = $inputObject.id + $computeManagerRevision = $inputObject._revision + $computeManagerFqdn = $inputObject.server + $computeManagerOriginType = $inputObject.origin_type + $computeManagerSetAsOidcProvider = $inputObject.set_as_oidc_provider + $computeManagerCredentialType = $inputObject.credential.credential_type + $computeManagerCredentialThumbprint = $inputObject.credential.thumbprint + } + + if ($EnableTrust -eq $computeManagerSetAsOidcProvider) { + Write-Error -Message "Compute Manager trust is already set to $EnableTrust." + break + } + + $json = @" +{ +"_revision" : $computeManagerRevision, +"server" : "$computeManagerFqdn", +"origin_type" : "$computeManagerOriginType", +"set_as_oidc_provider" : "$EnableTrust", +"credential" : +{ + "credential_type" : "$computeManagerCredentialType", + "thumbprint" : "$computeManagerCredentialThumbprint" +} +} +"@ Try { - $uri = "https://$nsxtmanager/policy/api/v1"+$uriPath+"/route-maps/$name" - $response = Invoke-RestMethod -Method DELETE -URI $uri -headers $nsxtHeaders -ContentType application/json + $uri = "https://$nsxtManager/api/v1/fabric/compute-managers/$computeManagerId" + $response = Invoke-RestMethod -Method PUT -URI $uri -ContentType application/json -body $json -headers $nsxtHeaders $response } Catch { Write-Error $_.Exception.Message - Break } +} +Export-ModuleMember -Function Set-NsxtComputeManager + +Function Get-NsxtVidm { + <# + .SYNOPSIS + Get Identity Manager Configuration + + .DESCRIPTION + The Get-NsxtVidm cmdlet gets the Identity Manager Configuration + + .EXAMPLE + Get-NsxtVidm + This example gets the Identity Manager Configuration + #> - # Validation Try { - $checkRouteMap = Get-NsxtRouteMap -Name $Name -Tier0Gateway $Tier0Gateway -ErrorAction SilentlyContinue + $uri = "https://$nsxtManager/api/v1/node/aaa/providers/vidm" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $nsxtHeaders + $response } Catch { Write-Error $_.Exception.Message } - - if ($checkRouteMap -eq "NSX-T RouteMap $Name was not found.") { - Write-Output "NSX-T RouteMap $Name has been successfully deleted." - } - else { - Write-Error -Message "NSX-T RouteMap $Name was not deleted. Please check the logs." - } } -Export-ModuleMember -Function Remove-NsxtRouteMap +Export-ModuleMember -Function Get-NsxtVidm -Function Get-NsxtRouteRedistributionPolicy { +Function Set-NsxtVidm { <# .SYNOPSIS - Get the route redistribution policy from a Tier-0 Gateway + Set Identity Manager Configuration .DESCRIPTION - The Get-NsxtRouteRedistributionPolicy cmdlet get the route redistribution policy from a Tier-0 Gateway + The Set-NsxtVidm cmdlet configures Identity Manager in NSX-T Manager .EXAMPLE - Get-NsxtRouteRedistributionPolicy -tier0Gateway sfo-w01-ec01-t0-gw01 - This example returns the route redistribution policy for Tier-0 Gateway sfo-w01-ec01-t0-gw01 + Set-NsxtVidm + This example configures the Identity Manager in NSX-T Manager #> Param ( - [Parameter (Mandatory = $false)] [String]$tier0Gateway, - [Parameter (ValueFromPipeline, Mandatory = $false)] [psObject]$inputObject + [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 ) - if ($inputObject -and $inputObject.resource_type -eq "Tier0") { - $Tier0Gateway = $inputObject.display_name - $uriPath = $inputObject.path - } - elseif ($inputObject -and $inputObject.resource_type -ne "Tier0") { - Write-Error "Invalid pipeline passthrough. Exiting." - Break - } - elseif (!$inputObject) { - if (!$Tier0Gateway) { - $Tier0Gateway = Read-Host -Prompt "Tier-0 Gateway not defined. Type in the name of your Tier-0 Gateway, then press Enter" - } - $uriPath = (Get-NsxtTier0Gateway -Name $Tier0Gateway).path - } - Try { - $uri = "https://$nsxtmanager/policy/api/v1"+$uriPath+"/locale-services/default" - $response = Invoke-RestMethod -Method GET -URI $uri -headers $nsxtHeaders -ContentType application/json + $uri = "https://$nsxtManager/api/v1/node/aaa/providers/vidm" + $body = '{ + "lb_enable": false, + "vidm_enable": true, + "host_name": "' + $wsaHostname + '", + "thumbprint": "' + $thumbprint + '", + "client_id": "' + $clientId + '", + "client_secret": "' + $sharedSecret + '", + "node_host_name": "' + $nsxHostname + '" + }' + $response = Invoke-RestMethod $uri -Method 'PUT' -Headers $nsxtHeaders -body $body $response } Catch { Write-Error $_.Exception.Message } - } -Export-ModuleMember Get-NsxtRouteRedistributionPolicy +Export-ModuleMember -Function Set-NsxtVidm -Function Set-NsxtRouteRedistributionPolicy { +Function Get-NsxtRole { <# .SYNOPSIS - Set the route redistriution policy for a Tier 0 Gateway + Gets NSX-T Manager roles .DESCRIPTION - The Set-NsxtRouteRedistributionPolicy cmdlet sets the route redistriution policy for a Tier 0 Gateway + The Get-NsxtRole cmdlet gets the roles in NSX-T Manager .EXAMPLE - Get-NsxtRouteRedistributionPolicy -tier0Gateway "sfo-w01-ec01-t0-gw01" | Set-NsxtRouteRedistributionPolicy -RouteMap "sfo-w01-ec01-t0-gw01-routemap" - This example sets the RouteMap "sfo-w01-ec01-t0-gw01-routemap" on the route redistribution policy for Tier-0 Gateway "sfo-w01-t0-ec01-t0-gw01" + Get-NsxtRole + This example gets all roles in NSX-T Manager #> - Param ( - [Parameter (Mandatory = $false)] [String]$tier0Gateway, - [Parameter (Mandatory = $false)] [String]$routeMap, - [Parameter (Mandatory = $false)] [Bool]$removeRouteMap, - [Parameter (ValueFromPipeline, Mandatory = $true)] [psObject]$inputObject - ) - - if ($inputObject -and $inputObject.resource_type -eq "LocaleServices") { - $Tier0GatewayId = $inputObject.parent_path.Split('/')[3] - $Tier0Gateway = (Get-NsxtTier0Gateway -Id $Tier0GatewayId).display_name - $edgeClusterPath = $inputObject.edge_cluster_path - $bgpEnabled = $inputObject.route_redistribution_config.bgp_enabled - $routeRedistributionName = $inputObject.route_redistribution_config.redistribution_rules.name - $routeRedistributionTypes = $inputObject.route_redistribution_config.redistribution_rules.route_redistribution_types - $uriPath = $inputObject.parent_path - } - elseif ($inputObject -and $inputObject.resource_type -ne "LocaleServices") { - Write-Error "Invalid pipeline passthrough. Exiting." - Break + Try { + $uri = "https://$nsxtManager/api/v1/aaa/roles" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $nsxtHeaders + $response.results } - - if (!$inputObject) { - if (!$Tier0Gateway) { - $Tier0Gateway = Read-Host -Prompt "Tier-0 Gateway not defined. Type in the name of your Tier-0 Gateway, then press Enter" - } - - $getRedistributionPolicy = Get-NsxtTier0Gateway -Name $Tier0Gateway - - $edgeClusterPath = $getRedistributionPolicy.edge_cluster_path - $bgpEnabled = $getRedistributionPolicy.route_redistribution_config.bgp_enabled - $routeRedistributionName = $getRedistributionPolicy.route_redistribution_config.redistribution_rules.name - $routeRedistributionTypes = $getRedistributionPolicy.route_redistribution_config.redistribution_rules.route_redistribution_types - $uriPath = (Get-NsxtTier0Gateway -Name $Tier0Gateway).path + Catch { + Write-Error $_.Exception.Message } +} +Export-ModuleMember -Function Get-NsxtRole - $routeMapPath = "/infra/tier-0s/$Tier0GatewayId/route-maps/$RouteMap" +Function Set-NsxtRole { + <# + .SYNOPSIS + Adds a role to a user/group - foreach ($routeRedistributionType in $routeRedistributionTypes) { - $routeRedistributionTypeString += @" -"$routeRedistributionType", -"@ - } + .DESCRIPTION + The Set-NsxtRole cmdlet assigns users/groups to roles - $routeRedistributionTypeString = $routeRedistributionTypeString.Substring(0, $routeRedistributionTypeString.Length - 1) + .EXAMPLE + Set-NsxtRole -principle "gg-nsx-enterprise-admins@lax.rainpole.io" + This example assigned the provided group the Enterprise Admin role + #> - if ($RemoveRouteMap -eq $true) { - $json = @" -{ - "edge_cluster_path" : "$edgeClusterPath", - "route_redistribution_config" : - { - "bgp_enabled" : "$bgpEnabled", - "redistribution_rules" : - [ - { - "name" : "$routeRedistributionName", - "route_redistribution_types" : [ $routeRedistributionTypeString ] - } - ] - } -} -"@ - } - elseif ($RemoveRouteMap -eq $false -or !$RemoveRouteMap) { - $json = @" -{ - "edge_cluster_path" : "$edgeClusterPath", - "route_redistribution_config" : - { - "bgp_enabled" : "$bgpEnabled", - "redistribution_rules" : - [ - { - "name" : "$routeRedistributionName", - "route_redistribution_types" : [ $routeRedistributionTypeString ], - "route_map_path" : "$routeMapPath" - } - ] - } -} -"@ - } + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$principal, + [Parameter (Mandatory = $true)] [ValidateSet("remote_group", "remote_user")] [String]$type, + [Parameter (Mandatory = $true)] [ValidateSet("lb_admin", "security_engineer", "vpn_admin", "network_op", "netx_partner_admin", "gi_partner_admin", "security_op", "network_engineer", "lb_auditor", "auditor", "enterprise_admin")] [String]$role, + [Parameter (Mandatory = $true)] [ValidateSet("LDAP", "VIDM", "OIDC")] [String]$identitySource + ) Try { - $uri = "https://$nsxtmanager/policy/api/v1"+$uriPath+"/locale-services/default" - $response = Invoke-RestMethod -Method PATCH -URI $uri -headers $nsxtHeaders -ContentType application/json -body $json + $uri = "https://$nsxtManager/api/v1/aaa/role-bindings" + $body = '{ + "name": "' + $principal + '", + "type": "' + $type + '", + "identity_source_type": "' + $identitySource + '", + "roles": [ + { + "role": "' + $role + '" + } + ] + }' + $response = Invoke-RestMethod $uri -Method 'POST' -Headers $nsxtHeaders -Body $body $response - - if (!$response) { - $output = Get-NsxtRouteRedistributionPolicy -Tier0Gateway $Tier0Gateway - $output - } } Catch { Write-Error $_.Exception.Message } - } -Export-ModuleMember Set-NsxtRouteRedistributionPolicy +Export-ModuleMember -Function Set-NsxtRole -Function Get-NsxtManagerAuthPolicy { +Function Remove-NsxtRole { <# .SYNOPSIS - Get the Authentication Policy for NSX Manager Nodes + Delete a user/group role assignment .DESCRIPTION - The Get-NsxtManagerAuthPolicy cmdlet getss the current authentication policy for NSX Manager Node + The Remove-NsxtRole cmdlet removes a user/group role in NSX-T Manager .EXAMPLE - Get-NsxtManagerAuthPolicy -nsxtManagerNode "sfo-m01-nsx01a.sfo.rainpole.io" - This example returns the current Authentication policy in NSX manager node sfo-m01-nsx01a.sfo.rainpole.io + Remove-NsxtRole -id + This example removes the role for the user/group based on the id #> - Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$nsxtManagerNode - ) + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id + ) - Try { - $requestingURL = "https://" + $nsxtManagerNode + "/api/v1/node/aaa/auth-policy" - $response = Invoke-RestMethod -Method GET -URI $requestingURL -ContentType application/json -headers $nsxtHeaders - $response - } - Catch { - Write-Error $_.Exception.Message - } + Try { + $uri = "https://$nsxtManager/api/v1/aaa/role-bindings/$id" + $response = Invoke-RestMethod $uri -Method 'DELETE' -Headers $nsxtHeaders + $response + } + Catch { + Write-Error $_.Exception.Message + } } -Export-ModuleMember Get-NsxtManagerAuthPolicy +Export-ModuleMember -Function Remove-NsxtRole -Function Set-NsxtManagerAuthPolicy { +Function Get-NsxtUser { <# .SYNOPSIS - Set the Authentication Policy for NSX Manager Node + Gets all users and groups .DESCRIPTION - The Set-NsxtManagerAuthPolicy cmdlet configures the authentication policy for NSX Manager Node + The Get-NsxtUser cmdlet gets all users and groups in NSX-T Manager .EXAMPLE - Set-NsxManagerAuthPolicy -nsxtManagerNode "sfo-m01-nsx01a.sfo.rainpole.io" -api_lockout_period 900 -api_reset_period 120 -api_max_attempt 5 -cli_lockout_period 900 -cli_max_attempt 5 -min_passwd_length 15 - This example customized the Authentication policy in NSX manager node sfo-m01-nsx01a.sfo.rainpole.io. + Get-NsxtUser + This example gets all users and grops in NSX-T Manager #> - Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$nsxtManagerNode, - [Parameter (Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int]$api_lockout_period, - [Parameter (Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int]$api_reset_period, - [Parameter (Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int]$api_max_attempt, - [Parameter (Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int]$cli_lockout_period, - [Parameter (Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int]$cli_max_attempt, - [Parameter (Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int]$min_passwd_length - ) - - $authPolicyBody = @{} - if ($PsBoundParameters.ContainsKey("api_lockout_period")) { - $authPolicyBody+= @{api_failed_auth_lockout_period = $api_lockout_period} - } - if ($PsBoundParameters.ContainsKey("api_reset_period")) { - $authPolicyBody += @{api_failed_auth_reset_period = $api_reset_period} - } - if ($PsBoundParameters.ContainsKey("api_max_attempt")) { - $authPolicyBody += @{api_max_auth_failures = $api_max_attempt} - } - if ($PsBoundParameters.ContainsKey("cli_lockout_period")) { - $authPolicyBody += @{cli_failed_auth_lockout_period = $cli_lockout_period} - } - if ($PsBoundParameters.ContainsKey("cli_max_attempt")) { - $authPolicyBody += @{cli_max_auth_failures = $cli_max_attempt} - } - if ($PsBoundParameters.ContainsKey("min_passwd_length")) { - $authPolicyBody += @{minimum_password_length = $min_passwd_length} - } - - Try { - $requestingURL = "https://" + $nsxtManagerNode + "/api/v1/node/aaa/auth-policy" - $response = Invoke-RestMethod -Method PUT -URI $requestingURL -ContentType application/json -headers $nsxtHeaders -Body ($authPolicyBody | ConvertTo-Json) - $response - } - Catch { - Write-Error $_.Exception.Message - } + Try { + $uri = "https://$nsxtManager/api/v1/aaa/role-bindings" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $nsxtHeaders + $response.results + } + Catch { + Write-Error $_.Exception.Message + } } -Export-ModuleMember Set-NsxtManagerAuthPolicy +Export-ModuleMember -Function Get-NsxtUser -Function Get-NsxtEdgeNodeAuthPolicy { +Function Get-NsxtVidmUser { <# .SYNOPSIS - Get the Authentication Policy for NSX Edge Nodes + Gets vIDM users .DESCRIPTION - The Get-NsxtEdgeNodeAuthPolicy cmdlet getss the authentication policy for NSX Edge Nodes + The Get-NsxtVidmUser cmdlet gets all vIDM users from NSX-T Manager .EXAMPLE - Get-NsxtEdgeNodeAuthPolicy -nsxtManagerNode "sfo-m01-nsx01a.sfo.rainpole.io" - This example returns the password policy in NSX manager node sfo-m01-nsx01a.sfo.rainpole.io + Get-NsxtVidmUser -searchString svc + This example gets all vIDM users starting with 'svc' from NSX-T Manager #> - Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$nsxtManager, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$nsxtEdgeNodeID - ) + Param ( + [Parameter (Mandatory = $true)] [ValidateLength(3, 255)] [String]$searchString + ) - Try { - $requestingURL = "https://" + $nsxtManager + "/api/v1/transport-nodes/" + $nsxtEdgeNodeID + "/node/aaa/auth-policy" - $response = Invoke-RestMethod -Method GET -URI $requestingURL -ContentType application/json -headers $nsxtHeaders - $response - } - Catch { - Write-Error $_.Exception.Message - } + Try { + $uri = "https://$nsxtManager/api/v1/aaa/vidm/users?search_string=$searchString" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $nsxtHeaders + $response.results + } + Catch { + Write-Error $_.Exception.Message + } } -Export-ModuleMember Get-NsxtEdgeNodeAuthPolicy +Export-ModuleMember -Function Get-NsxtVidmUser -Function Set-NsxtEdgeNodeAuthPolicy { +Function Get-NsxtVidmGroup { <# .SYNOPSIS - Set the Authentication Policy for NSX Manager Nodes + Gets vIDM groups .DESCRIPTION - The Set-NsxtManagerAuthPolicy cmdlet getss the authentication policy for NSX Manager Nodes + The Get-NsxtVidmGroup cmdlet gets all vIDM groups from NSX-T Manager .EXAMPLE - Set-NsxManagerAuthPolicy -nsxtManagerNode "sfo-m01-nsx01a.sfo.rainpole.io" -api_lockout_period 900 -api_reset_period 120 -api_max_attempt 5 -cli_lockout_period 900 -cli_max_attempt 5 -min_passwd_length 15 - This example customized the password policy in NSX manager node sfo-m01-nsx01a.sfo.rainpole.io. + Get-NsxtVidmGroup -searchString gg- + This example gets all vIDM groups starting with gg- from NSX-T Manager #> - Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$nsxtManager, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$nsxtEdgeNodeID, - [Parameter (Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int]$cli_lockout_period, - [Parameter (Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int]$cli_max_attempt, - [Parameter (Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int]$min_passwd_length - ) - - $authPolicyBody = @{} - if ($PsBoundParameters.ContainsKey("cli_lockout_period")) { - $authPolicyBody += @{cli_failed_auth_lockout_period = $cli_lockout_period} - } - if ($PsBoundParameters.ContainsKey("cli_max_attempt")) { - $authPolicyBody += @{cli_max_auth_failures = $cli_max_attempt} - } - if ($PsBoundParameters.ContainsKey("min_passwd_length")) { - $authPolicyBody += @{minimum_password_length = $min_passwd_length} - } + Param ( + [Parameter (Mandatory = $true)] [ValidateLength(3, 255)] [String]$searchString + ) - Try { - $requestingURL = "https://" + $nsxtManager + "/api/v1/transport-nodes/" + $nsxtEdgeNodeID + "/node/aaa/auth-policy" - $response = Invoke-RestMethod -Method PUT -URI $requestingURL -ContentType application/json -headers $nsxtHeaders -Body ($authPolicyBody | ConvertTo-Json) - $response - } - Catch { - Write-Error $_.Exception.Message - } + Try { + $uri = "https://$nsxtManager/api/v1/aaa/vidm/groups?search_string=$searchString" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $nsxtHeaders + $response.results + } + Catch { + Write-Error $_.Exception.Message + } } -Export-ModuleMember Set-NsxtEdgeNodeAuthPolicy +Export-ModuleMember -Function Get-NsxtVidmGroup -Function Get-NsxtSyslogStatus { +Function Get-NsxEdgeCluster { <# .SYNOPSIS - Gets the status of the Syslog Service + Retrieves NSX-T Edge Cluster(s) .DESCRIPTION - The Get-NsxtSyslogStatus cmdlet gets the status of the Syslog Service for NSX-T Data Center components + The Get-NsxtEdgeCluster cmdlet retrieves NSX-T Edge Cluster(s) .EXAMPLE - Get-NsxtSyslogStatus -type node - This example gets the status of the syslog service for NSX Manager node + Get-NsxtEdgeCluster + This example returns any NSX-T Edge Clusters .EXAMPLE - Get-NsxtSyslogStatus -type transport -id f3bd5bf0-23cd-4c6f-8de5-ab065f74d7fe - This example gets the status of the syslog service for NSX Edge node + Get-NsxtEdgeCluster -Name "sfo-w01-ec01" + This example returns any NSX-T Edge Clusters #> Param ( - [Parameter (ParameterSetName = 'node', Mandatory = $true)] [ValidateNotNullOrEmpty()] [Switch]$node, - [Parameter (ParameterSetName = 'transport', Mandatory = $true)] [ValidateNotNullOrEmpty()] [Switch]$transport, - [Parameter (ParameterSetName = 'transport', Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$Name ) Try { - if ($PsBoundParameters.ContainsKey("node")) { - $uri = "https://$nsxtManager/api/v1/node/services/syslog/status" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $nsxtHeaders - $response + if (!$PsBoundParameters.ContainsKey("Name")) { + $uri = "https://$nsxtmanager/api/v1/edge-clusters" + $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders + $response.results } - if ($PsBoundParameters.ContainsKey("transport")) { - $uri = "https://$nsxtManager/api/v1/transport-nodes/$id/node/services/syslog/status" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $nsxtHeaders - $response + elseif ($PsBoundParameters.ContainsKey("Name")) { + $uri = "https://$nsxtmanager/api/v1/edge-clusters" + $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders + $responseChecked = $response.results | Where-Object { $_.display_name -eq $Name } + + if (!$responseChecked) { + Write-Output "NSX-T Edge Cluster $Name was not found." + } + elseif ($responseChecked) { + $responseChecked + } } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-NsxtSyslogStatus +Export-ModuleMember -Function Get-NsxEdgeCluster -Function Get-NsxtSyslogExporter { +Function Get-NsxtTransportZone { <# .SYNOPSIS - Gets Syslog exporters + Get a list of Transport Zones .DESCRIPTION - The Get-NsxtSyslogExporter cmdlet gets the Syslog exporters configures for NSX-T Data Center components + The Get-NsxtTransportZone cmdlet retrieves a list of Transport Zones .EXAMPLE - Get-NsxtSyslogExporter -node - This example gets the configuration of the syslog exporters for NSX Manager node + Get-NsxtTransportZone + This example gets all Transport Zones .EXAMPLE - Get-NsxtSyslogExporter -transport -id f3bd5bf0-23cd-4c6f-8de5-ab065f74d7fe - This example gets the configuration of the syslog exporters for NSX Edge node + Get-NsxtTransportZone -Name overlay-tz-sfo-w01-nsx01.sfo.rainpole.io + This example gets the Transport Zone with the name "overlay-tz-sfo-w01-nsx01.sfo.rainpole.io" #> Param ( - [Parameter (ParameterSetName = 'node', Mandatory = $true)] [ValidateNotNullOrEmpty()] [Switch]$node, - [Parameter (ParameterSetName = 'transport', Mandatory = $true)] [ValidateNotNullOrEmpty()] [Switch]$transport, - [Parameter (ParameterSetName = 'transport', Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id + [Parameter (Mandatory = $false)] [String]$Name ) Try { - if ($PsBoundParameters.ContainsKey("node")) { - $uri = "https://$nsxtManager/api/v1/node/services/syslog/exporters" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $nsxtHeaders - $response.results + if (!$PsBoundParameters.ContainsKey("Name")) { + $uri = "https://$nsxtManager/api/v1/transport-zones" + $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders + $response.results | Sort-Object display_name } - if ($PsBoundParameters.ContainsKey("transport")) { - $uri = "https://$nsxtManager/api/v1/transport-nodes/$id/node/services/syslog/exporters" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $nsxtHeaders - $response.results + elseif ($PsBoundParameters.ContainsKey("Name")) { + $uri = "https://$nsxtManager/api/v1/transport-zones" + $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders + $responseChecked = $response.results | Where-Object { $_.display_name -eq $Name } + + if (!$responseChecked) { + Write-Output "NSX Transport Zone $Name was not found" + } + elseif ($responseChecked) { + $responseChecked + } } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-NsxtSyslogExporter +Export-ModuleMember -Function Get-NsxtTransportZone -Function Set-NsxtSyslogExporter { +Function New-NsxtSegment { <# .SYNOPSIS - Sets Syslog exporters + Create a new NSX-T Segment .DESCRIPTION - The Set-NsxtSyslogExporter cmdlet Sets the Syslog exporters configures for NSX-T Data Center components - - .EXAMPLE - Set-NsxtSyslogExporter -node -exporterName Syslog1 -logLevel INFO -port 514 -protocol TCP -server sfo-vrli01.sfo.rainpole.io - This example gets the status of the syslog service for NSX Manager node + The New-NsxtSegment cmdlet creates NSX-T Segments .EXAMPLE - Set-NsxtSyslogExporter -transport -id f3bd5bf0-23cd-4c6f-8de5-ab065f74d7fe -exporterName Syslog1 -logLevel INFO -port 514 -protocol TCP -server sfo-vrli01.sfo.rainpole.io - This example gets the status of the syslog service for NSX Edge node + New-NsxtSegment -Name "sfo-w01-xreg-seg01" -GatewayType "Tier1" -ConnectedGateway "sfo-w01-ec01-t1-gw01" -Cidr "192.168.31.1/24" -TransportZone "overlay-tz-sfo-w01-nsx01.sfo.rainpole.io" + This example creates an NSX-T Overlay Segment with the name "sfo-w01-xreg-seg01", connected to Tier-1 gateway "sfo-w01-ec01-t1-gw01", Transport Zone "overlay-tz-sfo-w01-nsx01.sfo.rainpole.io", and CIDR address of "192.168.31.1/24" #> Param ( - [Parameter ( ParameterSetName = 'node', Mandatory = $true)] [ValidateNotNullOrEmpty()] [Switch]$node, - [Parameter ( ParameterSetName = 'transport', Mandatory = $true)] [ValidateNotNullOrEmpty()] [Switch]$transport, - [Parameter ( ParameterSetName = 'transport', Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id, - [Parameter ( Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$exporterName, - [Parameter ( Mandatory = $true)] [ValidateSet("EMERG", "ALERT", "CRIT", "ERR", "WARNING", "NOTICE", "INFO", "DEBUG")] [String]$logLevel, - [Parameter ( Mandatory = $true)] [ValidateNotNullOrEmpty()] [Int]$port, - [Parameter ( Mandatory = $true)] [ValidateSet("TCP", "TLS", "UDP", "LI", "LI-TLS")] [String]$protocol, - [Parameter ( Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server + [Parameter (Mandatory = $true)] [String]$Name, + [Parameter (Mandatory = $false)] [String]$ConnectedGateway, + [Parameter (Mandatory = $false)] [String]$Cidr, + [Parameter (Mandatory = $true)] [String]$TransportZone, + [Parameter (Mandatory = $false)] [ValidateSet("Tier0", "Tier1")] [String]$GatewayType, + [Parameter (Mandatory = $true)] [ValidateSet("Overlay", "VLAN")] [String]$SegmentType, + [Parameter (Mandatory = $false)] [String]$VlanId ) - Try { - $json = '{ - "exporter_name": "' + $exporterName + '", - "level": "' + $logLevel + '", - "port": ' + $port + ', - "protocol": "' + $protocol + '", - "server": "' + $server + '" - }' + if ($GatewayType -eq "Tier0") { + $connectivityPath = (Get-NsxtTier0Gateway -Name $ConnectedGateway).path + } + elseif ($GatewayType -eq "Tier1") { + $connectivityPath = (Get-NsxtTier1Gateway -Name $ConnectedGateway).path + } + elseif (!$GatewayType -and $VlanId) { + Write-Output "Valid VLAN segment configuration" + } + else { + Write-Error "Gateway type not defined" + } - if ($PsBoundParameters.ContainsKey("node")) { - $uri = "https://$nsxtManager/api/v1/node/services/syslog/exporters" - $response = Invoke-RestMethod $uri -Method 'POST' -Headers $nsxtHeaders -ContentType application/json -body $json - $response - } - if ($PsBoundParameters.ContainsKey("transport")) { - $uri = "https://$nsxtManager/api/v1/transport-nodes/$id/node/services/syslog/exporters" - $response = Invoke-RestMethod $uri -Method 'POST' -Headers $nsxtHeaders -ContentType application/json -body $json - $response - } + $transportZoneId = (Get-NsxtTransportZone -Name $TransportZone).id + + if ($SegmentType -match "overlay") { + + $json = @" +{ +"display_name" : "$Name", +"subnets" : [{ "gateway_address" : "$Cidr" }], +"connectivity_path" : "$connectivityPath", +"transport_zone_path" : "/infra/sites/default/enforcement-points/default/transport-zones/$transportZoneId" +} +"@ + + } + elseif ($SegmentType -match "vlan") { + + $json = @" +{ +"display_name" : "$Name", +"vlan_ids" : [ "$VlanId" ], +"transport_zone_path" : "/infra/sites/default/enforcement-points/default/transport-zones/$transportZoneId" +} +"@ + + } + else { + Write-Error "SegmentType $SegmentType is invalid." + } + + Try { + $uri = "https://$nsxtManager/policy/api/v1/infra/segments/$Name" + $response = Invoke-RestMethod -Method PUT -URI $uri -ContentType application/json -Body $json -headers $nsxtHeaders + $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Set-NsxtSyslogExporter +Export-ModuleMember -Function New-NsxtSegment -Function Remove-NsxtSyslogExporter { +Function Get-NsxtSegment { <# .SYNOPSIS - Delete Syslog exporters + Get a list of Segments .DESCRIPTION - The Remove-NsxtSyslogExporter cmdlet deletes the Syslog exporters for NSX-T Data Center components + The Get-NsxtSegment cmdlet retrieves a list of Segments .EXAMPLE - Remove-NsxtSyslogExporter -node -exporterName Syslog1 - This example deletes the syslog exporters for NSX Manager node + Get-NsxtSegment + This example gets all Segments .EXAMPLE - Remove-NsxtSyslogExporter -transport -id f3bd5bf0-23cd-4c6f-8de5-ab065f74d7fe -exporterName Syslog1 - This example deletes the syslog exporters for for NSX Edge node + Get-NsxtSegment -name sfo-w01-kub-seg01 + This example gets the segment with the name sfo-w01-kub-seg01 #> Param ( - [Parameter (ParameterSetName = 'node', Mandatory = $true)] [ValidateNotNullOrEmpty()] [Switch]$node, - [Parameter (ParameterSetName = 'transport', Mandatory = $true)] [ValidateNotNullOrEmpty()] [Switch]$transport, - [Parameter (ParameterSetName = 'transport', Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id, - [Parameter ( Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$exporterName + [Parameter (Mandatory = $false)] [String]$name ) Try { - if ($PsBoundParameters.ContainsKey("node")) { - $uri = "https://$nsxtManager/api/v1/node/services/syslog/exporters/$exporterName" - $response = Invoke-RestMethod $uri -Method 'DELETE' -Headers $nsxtHeaders - $response + if (!$PsBoundParameters.ContainsKey("name")) { + $uri = "https://$nsxtManager/policy/api/v1/infra/segments/" + $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders + $response.results | Sort-Object display_name } - if ($PsBoundParameters.ContainsKey("transport")) { - $uri = "https://$nsxtManager/api/v1/transport-nodes/$id/node/services/syslog/exporters/$exporterName" - $response = Invoke-RestMethod $uri -Method 'DELETE' -Headers $nsxtHeaders - $response + elseif ($PsBoundParameters.ContainsKey("name")) { + $uri = "https://$nsxtManager/policy/api/v1/infra/segments/" + $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders + $response.results | Where-Object { $_.display_name -eq $name } } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Remove-NsxtSyslogExporter +Export-ModuleMember -Function Get-NsxtSegment -Function Copy-vRealizeLoadBalancer -{ +Function Remove-NsxtSegment { <# .SYNOPSIS - Creates a Load Balancer for vRealize component failover + Removes a named Segment .DESCRIPTION - Creates a new loadbalancer in a secondary VMware Cloud Foundation instance by duplicating the settings of the existing load balancer in the instance where the vRealize components are currently running + The Remove-NsxtSegment cmdlet removes a named segment. .EXAMPLE - Copy-vRealizeLoadBalancer -sddcManagerAFQDN sfo-vcf01.sfo.rainpole.io -sddcManagerAUser administrator@vsphere.local -sddcManagerAPassword VMw@re1! -sddcManagerBFQDN lax-vcf01.lax.rainpole.io -sddcManagerBUser administrator@vsphere.local -sddcManagerBPassword VMw@re1! -serviceInterfaceIP 192.168.11.3 -wsaCertName xint-wsa01 - This example copies settings from Load Balancer in SDDC A to a new Load Balancer in SDDC B + Remove-NsxtSegment -name sfo-w01-kub-seg01 + This example removes the segment with the name sfo-w01-kub-seg01 #> - + Param ( - [Parameter (Mandatory = $true)] [String]$sddcManagerAFqdn, - [Parameter (Mandatory = $true)] [String]$sddcManagerAUser, - [Parameter (Mandatory = $true)] [String]$sddcManagerAPassword, - [Parameter (Mandatory = $true)] [String]$sddcManagerBFqdn, - [Parameter (Mandatory = $true)] [String]$sddcManagerBUser, - [Parameter (Mandatory = $true)] [String]$sddcManagerBPassword, - [Parameter (Mandatory = $true)] [String]$serviceInterfaceIp, - [Parameter (Mandatory = $true)] [String]$wsaCertName + [Parameter (Mandatory = $false)] [String]$Name ) Try { - # Setup Parameters - $t1Name = "recovery-t1-gw01" - $siName = "recovery-t1-gw01-si01" - $lbName = "recovery-lb01" - - #Retrieve Edge Cluster Details from SDDC Manager B - Request-VCFToken -fqdn $sddcManagerBFqdn -Username $sddcManagerBUser -Password $sddcManagerBPassword | Out-Null - $mgmtNsxtClusterID = (Get-VCFWorkloadDomain | Where-Object {$_.type -eq "Management"}).nsxtCluster.id - $edgeClusterName = (Get-VCFEdgeCluster | Where-Object {$_.nsxtCluster.id -eq $mgmtNsxtClusterID}).Name - - #Retrieve Segment, WSA, VRA and vROPS Details from SDDC Manager A - Request-VCFToken -fqdn $sddcManagerAFqdn -Username $sddcManagerAUser -Password $sddcManagerAPassword | Out-Null - $xintSegmentDetails = Get-VCFApplicationVirtualNetwork | Where-Object {$_.regionType -eq "X_REGION"} - $wsaDetailsObject = Get-WSAServerDetail -fqdn $sddcManagerAFqdn -username $sddcManagerAUser -password $sddcManagerAPassword - $vraDetailsObject = Get-vRAServerDetail -fqdn $sddcManagerAFqdn -username $sddcManagerAUser -password $sddcManagerAPassword - $vropsDetailsObject = Get-vROPsServerDetail -fqdn $sddcManagerAFqdn -username $sddcManagerAUser -password $sddcManagerAPassword + $preCheckSegment = Get-NsxtSegment -Name $name -ErrorAction SilentlyContinue + } + Catch { + Write-Error $_.Exception.Message + } - #Add Cert to NSX - $nsxManager = Get-NsxtServerDetail -fqdn $sddcManagerBFqdn -user $sddcManagerBUser -pass $sddcManagerBPassword -domainType MANAGEMENT - Request-NsxToken -fqdn $nsxManager.fqdn -username $nsxManager.adminUser -password $nsxManager.adminPass | Out-Null + if ($preCheckSegment -eq "NSX segment $Name was not found") { + Write-Error $preCheckSegment + Break + } - #Get xint segment ID from NSX LM on recovery site - $segmentID = Get-NsxtGlobalSegmentID -segmentName $xintSegmentDetails.name + Try { + $uri = "https://$nsxtManager/policy/api/v1/infra/segments/$Name" + $response = Invoke-RestMethod -Method DELETE -URI $uri -ContentType application/json -headers $nsxtHeaders + $response } Catch { - Debug-ExceptionWriter -object $_ + Write-Error $_.Exception.Message } - - Try { - if ((!$edgeClusterName) -OR (!$xintSegmentDetails) -OR (!$wsaDetailsObject) -OR ((!$vraDetailsObject) -AND (!$vropsDetailsObject))) { - Write-Output "Requirements for Copying Load Balancer not Met". - if (!$wsaDetailsObject) {Write-Output "Clustered Workspace ONE Access was not discovered in the source SDDC Manager instance"} - if ((!$vraDetailsObject) -AND (!$vropsDetailsObject)) {Write-Output "Neither vRealize Automation nor vRealize Operations Manager was discovered in the source SDDC Manager instance"} - if (!$xintSegmentDetails) {Write-Output "Cross-Region Segment was discovered in the target SDDC Manager instance"} - if (!$edgeClusterName) {Write-Output "Management Edge Cluster was not discovered in the target SDDC Manager instance"} - } - else { - #Create a Load Balancer Spec - if (!$vraDetailsObject) { - $lbCustomObject = New-vRealizeLoadBalancerSpec -xintSegmentDetails $xintSegmentDetails -serviceInterfaceIp $serviceInterfaceIp -wsaDetailsObject $wsaDetailsObject -vropsDetailsObject $vropsDetailsObject -wsaCertName $wsaCertName -t1Name $t1Name -lbName $lbName -siName $siName -segmentID $segmentID - } - elseif (!$vropsDetailsObject) { - $lbCustomObject = New-vRealizeLoadBalancerSpec -xintSegmentDetails $xintSegmentDetails -serviceInterfaceIp $serviceInterfaceIp -wsaDetailsObject $wsaDetailsObject -vraDetailsObject $vraDetailsObject -wsaCertName $wsaCertName -t1Name $t1Name -lbName $lbName -siName $siName -segmentID $segmentID - } - else { - $lbCustomObject = New-vRealizeLoadBalancerSpec -xintSegmentDetails $xintSegmentDetails -serviceInterfaceIp $serviceInterfaceIp -wsaDetailsObject $wsaDetailsObject -vraDetailsObject $vraDetailsObject -vropsDetailsObject $vropsDetailsObject -wsaCertName $wsaCertName -t1Name $t1Name -lbName $lbName -siName $siName -segmentID $segmentID - } - $wsaCertPresent = Add-CertToNsxCertificateStore -certName $wsaCertName - - if ($wsaCertPresent -eq $true) { - $ConfigJson = $lbCustomObject.t1_spec.gw | ConvertTo-Json - New-NsxtTier1 -tier1Gateway $t1Name -json $ConfigJson - $edgeClusterID = (Get-NsxtEdgeCluster -name $edgeClusterName).id - $ConfigJson = '{"edge_cluster_path": "/infra/sites/default/enforcement-points/default/edge-clusters/' + $edgeClusterID + '"}' - Set-NsxtTier1 -tier1Gateway $t1name -json $ConfigJson - $ConfigJson = '{ - "segment_path": "'+ $lbCustomObject.t1_spec.service_interface.segment_path + '", - "subnets": [ - { - "ip_addresses": [ "'+ $lbCustomObject.t1_spec.service_interface.subnets.ip_addresses + '" ], - "prefix_len": "'+ $lbCustomObject.t1_spec.service_interface.subnets.prefix_len + '" - } - ] - }' - New-NsxtTier1ServiceInterface -tier1Gateway $t1name -interfaceId $lbCustomObject.t1_spec.service_interface.id -json $ConfigJson - $ConfigJson = '{ - "network": "'+ $lbCustomObject.t1_spec.static_routes.network + '", - "next_hops": [ - { - "ip_address": "'+ $lbCustomObject.t1_spec.static_routes.next_hops.ip_address + '", - "admin_distance": '+ $lbCustomObject.t1_spec.static_routes.next_hops.admin_distance + ', - "scope": [ - "'+ $lbCustomObject.t1_spec.static_routes.next_hops.scope +'" - ] - } - ], - "display_name": "'+ $lbCustomObject.t1_spec.static_routes.display_name + '" - }' - New-NsxtTier1StaticRoute -tier1Gateway $t1name -segment $xintSegmentDetails.name -json $ConfigJson - $ConfigJson = $lbCustomObject.lb_spec.lb_service | ConvertTo-Json - New-NsxtLoadBalancer -lbName $lbName -json $ConfigJson - Foreach ($monitor in $lbCustomObject.lb_spec.service_monitors) { - Try { - $ConfigJson = $monitor | ConvertTo-Json -Depth 10 - New-NsxtLBServiceMonitor -monitorName $monitor.display_name -json $ConfigJson - } - Catch { - Debug-ExceptionWriter -object $_ - } - } - Foreach ($profile in $lbCustomObject.lb_spec.app_profiles) { - Try { - $ConfigJson = $profile | ConvertTo-Json - New-NsxtLBAppProfile -appProfileName $profile.display_name -json $ConfigJson - } - Catch { - Debug-ExceptionWriter -object $_ - } - } - Foreach ($profile in $lbCustomObject.lb_spec.persistence_profiles) { - Try { - $ConfigJson = $profile | ConvertTo-Json - New-NsxtLBPersistenceAppProfile -appProfileName $profile.display_name -json $ConfigJson - } - Catch { - Debug-ExceptionWriter -object $_ - } - } - Foreach ($pool in $lbCustomObject.lb_spec.pools) { - Try { - $ConfigJson = $pool | ConvertTo-Json - New-NsxtLBPool -poolName $pool.display_name -json $ConfigJson - } - Catch { - Debug-ExceptionWriter -object $_ - } - } - Foreach ($virtualServer in $lbCustomObject.lb_spec.virtual_Servers) { - Try { - $ConfigJson = $virtualServer | ConvertTo-Json -Depth 10 - New-NsxtLBVirtualServer -virtualServerName $virtualServer.display_name -json $ConfigJson - } - Catch { - Debug-ExceptionWriter -object $_ - } - } - } - else { - Write-Error "Aborting remainder of NSX-T Load Balancer configuration until certificate files present" - } - } + # Validation + Try { + $checkSegment = Get-NsxtSegment -Name $Name -ErrorAction SilentlyContinue } Catch { - Debug-ExceptionWriter -object $_ + Write-Error $_.Exception.Message + } + + if ($checkSegment -eq "NSX segment $Name was not found") { + Write-Output "NSX-T Segment $Name has been successfully deleted." + } + else { + Write-Error -Message "NSX-T Segment $Name was not deleted. Please check the logs." } } -Export-ModuleMember -Function Copy-vRealizeLoadBalancer +Export-ModuleMember -Function Remove-NsxtSegment -Function New-vRealizeLoadBalancerSpec -{ - Param ( - [Parameter (Mandatory = $true)] [Array]$xintSegmentDetails, - [Parameter (Mandatory = $true)] [Array]$serviceInterfaceIp, - [Parameter (Mandatory = $true)] [Array]$wsaDetailsObject, - [Parameter (Mandatory = $false)] [Array]$vraDetailsObject, - [Parameter (Mandatory = $false)] [Array]$vropsDetailsObject, - [Parameter (Mandatory = $true)] [String]$wsaCertName, - [Parameter (Mandatory = $true)] [String]$t1Name, - [Parameter (Mandatory = $true)] [String]$lbName, - [Parameter (Mandatory = $true)] [String]$siName, - [Parameter (Mandatory = $true)] [String]$segmentID - ) +Function Get-NsxtTier0Gateway { + <# + .SYNOPSIS + Get a list of Tier 0 Gateways - $xintSegmentName = $xintSegmentDetails.name - $xintSegmentServiceInterfacePrefixLength = cidrMaskLookup -source mask -value $xintSegmentDetails.subnetMask - $xintSegmentNextHopIP = $xintSegmentDetails.gateway + .DESCRIPTION + The Get-NsxtTier0 cmdlet retrieves a list of Tier 0 Gateways - $xintWsaVip = $wsaDetailsObject.loadBalancerIpAddress - $xintWsaNode1Ip = $wsaDetailsObject.node1IpAddress - $xintWsaNode2Ip = $wsaDetailsObject.node2IpAddress - $xintWsaNode3Ip = $wsaDetailsObject.node3IpAddress - $xintWsaNode1Name = $wsaDetailsObject.fqdn[0].split(".")[0] - $xintWsaNode2Name = $wsaDetailsObject.fqdn[1].split(".")[0] - $xintWsaNode3Name = $wsaDetailsObject.fqdn[2].split(".")[0] + .EXAMPLE + Get-NsxtTier0Gateway + This example returns all Tier 0 Gateways - If ($vropsDetailsObject) - { - $xintVropsVip = $vropsDetailsObject.loadBalancerIpAddress - $xintVropsNode1Ip = $vropsDetailsObject.node1IpAddress - $xintVropsNode2Ip = $vropsDetailsObject.node2IpAddress - $xintVropsNode3Ip = $vropsDetailsObject.node3IpAddress - $xintVropsNode1Name = $vropsDetailsObject.fqdn[0].split(".")[0] - $xintVropsNode2Name = $vropsDetailsObject.fqdn[1].split(".")[0] - $xintVropsNode3Name = $vropsDetailsObject.fqdn[2].split(".")[0] - } + .EXAMPLE + Get-NsxtTier0Gateway -name sfo-w01-ec01-t0-gw01 + This example returns the Tier 0 Gateway named sfo-w01-ec01-t0-gw01 - If ($vraDetailsObject) - { - $xintVraVip = $vraDetailsObject.loadBalancerIpAddress - $xintVraNode1Ip = $vraDetailsObject.node1IpAddress - $xintVraNode2Ip = $vraDetailsObject.node2IpAddress - $xintVraNode3Ip = $vraDetailsObject.node3IpAddress - $xintVraNode1Name = $vraDetailsObject.fqdn[0].split(".")[0] - $xintVraNode2Name = $vraDetailsObject.fqdn[1].split(".")[0] - $xintVraNode3Name = $vraDetailsObject.fqdn[2].split(".")[0] + .EXAMPLE + Get-NsxtTier0Gateway -id 84a6c7a5-9fe8-4446-8684-814663399584 + This example returns the Tier 0 Gateway based on its id + #> + + Param ( + [Parameter (Mandatory = $false)] [String]$name, + [Parameter (Mandatory = $false)] [String]$id + ) + + Try { + if (!$PsBoundParameters.ContainsKey("name") -and !$PsBoundParameters.ContainsKey("id")) { + $uri = "https://$nsxtmanager/policy/api/v1/infra/tier-0s" + $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders + $response.results + } + elseif ($PsBoundParameters.ContainsKey("id")) { + $uri = "https://$nsxtmanager/policy/api/v1/infra/tier-0s/$id" + $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders + $response + } + elseif ($PsBoundParameters.ContainsKey("name")) { + $uri = "https://$nsxtmanager/policy/api/v1/infra/tier-0s" + $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders + $response.results | Where-Object { $_.display_name -eq $name } + } + } + Catch { + Write-Error $_.Exception.Message } +} +Export-ModuleMember -Function Get-NsxtTier0Gateway - $lbJson += '{' +Function Get-NsxtTier1Gateway { + <# + .SYNOPSIS + Get a list of Tier 1 Gateways + + .DESCRIPTION + The Get-NsxtTier1Gateway cmdlet retrieves a list of Tier 1 Gateways + + .EXAMPLE + Get-NsxtTier1Gateway + This example returns all Tier 1 Gateways + + .EXAMPLE + Get-NsxtTier1Gateway -name sfo-w01-ec01-t1-gw01 + This example returns the Tier 1 Gateway named sfo-w01-ec01-t1-gw01 + + .EXAMPLE + Get-NsxtTier1Gateway -id 84a6c7a5-9fe8-4446-8684-814663399584 + This example returns the Tier 1 Gateway based on its id + #> + + Param ( + [Parameter (Mandatory = $false)] [String]$name, + [Parameter (Mandatory = $false)] [String]$id + ) + + Try { + if ( -not $PsBoundParameters.ContainsKey("name")) { + $uri = "https://$nsxtmanager/policy/api/v1/infra/tier-1s" + $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders + $response.results + } + elseif ($PsBoundParameters.ContainsKey("id")) { + $uri = "https://$nsxtmanager/policy/api/v1/infra/tier-1s/$id" + $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders + $response + } + elseif ($PsBoundParameters.ContainsKey("name")) { + $uri = "https://$nsxtmanager/policy/api/v1/infra/tier-1s" + $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders + $response.results | Where-Object { $_.display_name -eq $name } + } + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Get-NsxtTier1Gateway + +Function Get-NsxtPrefixList { + <# + .SYNOPSIS + Get Tier-0 Gateway IP Prefix Lists + + .DESCRIPTION + The Get-NsxtTier0PrefixList cmdlet retrieves the IP Prefix Lists assigned to a Tier-0 Gateway + + .EXAMPLE + Get-NsxtPrefixList -tier0Gateway sfo-w01-ec01-t0-gw01 + This example returns all IP Prefix Lists + + .EXAMPLE + Get-NsxtPrefixList -name sfo-w01-cl01-prefix-list -tier0Gateway sfo-w01-ec01-t0-gw01 + This example returns the IP Prefix List based on the prefix name provided + + .EXAMPLE + Get-NsxtTier0Gateway -name sfo-w01-ec01-t0-gw01 | Get-NsxtPrefixList -name sfo-w01-cl01-prefix-list + This example returns the IP Prefix List based on the prefix name provided + #> + + Param ( + [Parameter (Mandatory = $false)] [String]$tier0Gateway, + [Parameter (Mandatory = $false)] [String]$name, + [Parameter (ValueFromPipeline, Mandatory = $false)] [psObject]$inputObject + ) + + # Validating pipeline input resource_type + if ($inputObject -and $inputObject.resource_type -eq "Tier0") { + $tier0Gateway = $inputObject.display_name + $uriPath = $inputObject.path + } + elseif ($inputObject -and $inputObject.resource_type -ne "Tier0") { + Write-Error "Invalid pipeline passthrough. Exiting." + Break + } + elseif (!$inputObject -and $Tier0Gateway) { + $uriPath = (Get-NsxtTier0Gateway -Name $Tier0Gateway).path + } + else { + if (!$tier0Gateway) { + $tier0Gateway = Read-Host -Prompt "Tier-0 Gateway not defined. Type in the name of your Tier-0 Gateway, then press Enter" + } + } + + Try { + if (!$name) { + $uri = "https://$nsxtmanager/policy/api/v1"+$uriPath+"/prefix-lists" + $response = Invoke-RestMethod -Method GET -URI $uri -headers $nsxtHeaders -ErrorAction SilentlyContinue + $response.results + } + elseif ($name) { + $uri = "https://$nsxtmanager/policy/api/v1"+$uriPath+"/prefix-lists" + $response = Invoke-RestMethod -Method GET -URI $uri -headers $nsxtHeaders -ErrorAction SilentlyContinue + $response.results | Where-Object { $_.display_name -eq $name } + } + } + Catch { + if ($_.Exception -match "400" -or $_.Exception -match "Bad Request") { + Write-Output $uri + Write-Error "The NSX Tier-0 Gateway was not properly defined" + + } + } +} +Export-ModuleMember -Function Get-NsxtPrefixList + +Function New-NsxtPrefixList { + <# + .SYNOPSIS + Creates a Tier-0 Gateway IP Prefix List + + .DESCRIPTION + The New-NsxtPrefixList cmdlet creates a Prefix List on a specified Tier-0 Gateway + + .EXAMPLE + New-NsxtPrefixList -Name sfo-w01-cl01-prefix-list -Tier0Gateway sfo-w01-ec01-t0-gw01 + This example creates a new IP Prefix List on a Tier 0 Gateway + #> + + Param ( + [Parameter (Mandatory = $false)] [String]$Name, + [Parameter (Mandatory = $false)] [String]$Tier0Gateway, + [Parameter (Mandatory = $false)] [String]$SubnetCIDR, + [Parameter (Mandatory = $false)] [String]$GE, + [Parameter (Mandatory = $false)] [String]$LE, + [Parameter (Mandatory = $false)] [ValidateSet("PERMIT", "DENY")] [String]$Action, + [Parameter (Mandatory = $false)] [String]$Json, + [Parameter (ValueFromPipeline, Mandatory = $false)] [psObject]$inputObject + ) + + # Validating pipeline input resource_type + if ($inputObject -and $inputObject.resource_type -eq "Tier0") { + $uriPath = $inputObject.path + $Tier0Gateway = $inputObject.display_name + } + elseif ($inputObject -and $inputObject.resource_type -ne "Tier0") { + Write-Error "Invalid pipeline passthrough. Exiting." + Break + } + elseif (!$inputObject) { + if (!$Tier0Gateway) { + $Tier0Gateway = Read-Host -Prompt "Tier-0 Gateway not defined. Type in the name of your Tier-0 Gateway, then press Enter" + $uriPath = (Get-NsxtTier0Gateway -Name $Tier0Gateway).path + } + } + + if (!$json) { + if (!$GE -or !$LE) { + $Json = @" +{ + "display_name" : "$Name", + "prefixes" : + [ + { + "network" : "$SubnetCIDR", + "action" : "$Action" + } + ] +} +"@ + } + elseif ($GE -and $LE) { + $Json = @" +{ + "display_name" : "$Name", + "prefixes" : + [ + { + "network" : "$SubnetCIDR", + "action" : "$Action", + "ge" : "$GE", + "le" : "$LE" + } + ] +} +"@ + } + else { + Write-Error "Invalid subnet configuration." + } + } + + Try { + $global:uri = "https://$nsxtmanager/policy/api/v1"+$uriPath+"/prefix-lists/$Name" + $global:response = Invoke-RestMethod -Method PUT -URI $uri -ContentType application/json -body $json -headers $nsxtHeaders + $response + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function New-NsxtPrefixList + +Function Remove-NsxtPrefixList { + <# + .SYNOPSIS + Remove an IP Prefix List from a Tier-0 Gateway + + .DESCRIPTION + The Remove-NsxtPrefixList cmdlet removes a IP Prefix List from a specified Tier-0 Gateway + + .EXAMPLE + Remove-NsxtPrefixList -Name sfo-w01-cl01-prefix-list -Tier0Gateway sfo-w01-ec01-t0-gw01 + This example removes a Prefix List on a Tier 0 Gateway + #> + + Param ( + [Parameter (Mandatory = $false)] [String]$Name, + [Parameter (Mandatory = $false)] [String]$Tier0Gateway, + [Parameter (ValueFromPipeline, Mandatory = $false)] [psObject]$inputObject + ) + + # Validating pipeline input resource_type + if ($inputObject -and $inputObject.resource_type -eq "Tier0") { + $uriPath = $inputObject.path + } + elseif ($inputObject -and $inputObject.resource_type -ne "Tier0") { + Write-Error "Invalid pipeline passthrough. Exiting." + Break + } elseif (!$inputObject) { + if (!$Tier0Gateway) { + $Tier0Gateway = Read-Host -Prompt "Tier-0 Gateway not defined. Type in the name of your Tier-0 Gateway, then press Enter" + } + $uriPath = (Get-NsxtTier0Gateway -Name $Tier0Gateway).path + } + + Try { + $preCheckPrefixList = Get-NsxtPrefixList -Name $Name -Tier0Gateway $Tier0Gateway -ErrorAction SilentlyContinue + } + Catch { + Write-Error $_.Exception.Message + } + + if ($preCheckPrefixList -eq "NSX IP Prefix List $Name was not found") { + Write-Error $preCheckPrefixList + Break + } + + Try { + $uri = "https://$nsxtmanager/policy/api/v1"+$uriPath+"/prefix-lists/$Name" + $response = Invoke-RestMethod -Method DELETE -URI $uri -headers $nsxtHeaders -ContentType application/json + $response + } + Catch { + Write-Error $_.Exception.Message + } + + # Validation + Try { + $checkPrefixList = Get-NsxtPrefixList -Name $Name -Tier0Gateway $Tier0Gateway -ErrorAction SilentlyContinue + } + Catch { + Write-Error $_.Exception.Message + } + + if ($checkPrefixList -eq "NSX IP Prefix List $Name was not found") { + Write-Output "NSX-T PrefixList $Name has been successfully deleted." + } + else { + Write-Error -Message "NSX-T PrefixList $Name was not deleted. Please check the logs." + } +} +Export-ModuleMember -Function Remove-NsxtPrefixList + +Function Add-NsxtPrefix { + <# + .SYNOPSIS + Add a single entry to an existing NSX IP Prefix List + + .DESCRIPTION + The Add-NsxtPrefix cmdlet adds a single entry to an existing NSX IP Prefix List + + .EXAMPLE + Get-NsxtPrefixList -name sfo-w01-cl01-prefix-list | Add-NsxtPrefix -subnetCIDR 192.168.21.0/24 -LE 32 -GE 28 -action PERMIT + This example adds an IP Prefix entry on an existing IP Prefix List + #> + + Param ( + [Parameter (Mandatory = $false)] [String]$prefixListName, + [Parameter (Mandatory = $false)] [String]$tier0Gateway, + [Parameter (Mandatory = $false)] [String]$subnetCIDR, + [Parameter (Mandatory = $false)] [String]$GE, + [Parameter (Mandatory = $false)] [String]$LE, + [Parameter (Mandatory = $false)] [String]$action, + [Parameter (ValueFromPipeline, Mandatory = $false)] [psObject]$inputObject + ) + + if (!$inputObject -and $tier0Gateway -and $prefixListName) { + $uriPath = (Get-NsxtTier0Gateway -Name $tier0Gateway).path + $existingPrefixes = (Get-NsxtPrefixList -Name $prefixListName -Tier0Gateway $tier0Gateway).prefixes + } + + if ($inputObject -and $inputObject.resource_type -eq "PrefixList") { + $uriPath = $inputObject.parent_path + $Tier0GatewayId = $inputObject.parent_path.Split('/')[3] + $PrefixListName = $inputObject.display_name + $existingPrefixes = $inputObject.prefixes + + $getTier0Gateway = Get-NsxtTier0Gateway -name $tier0GatewayId -ErrorAction SilentlyContinue + + if ($getTier0Gateway -eq "NSX Tier-0 Gateway $tier0GatewayId was not found") { + $tier0Gateway = (Get-NsxtTier0Gateway -Id $tier0GatewayId).display_name + } + else { + $Tier0Gateway = $Tier0GatewayId + } + + } + elseif ($inputObject -and $inputObject.resource_type -ne "PrefixList") { + Write-Error "Invalid pipeline passthrough" + Break + } + + $prefixes = @() + + $prefixes += $existingPrefixes + + if (!$GE -or !$LE) { + $newPrefix = @{ + network = $subnetCIDR + action = $action + } + } + elseif ($GE -and $LE) { + $newPrefix = @{ + network = $subnetCIDR + action = $action + ge = $GE + le = $LE + } + } + else { + Write-Error "Invalid subnet configuration" + } + + $prefixes += $newPrefix + $prefixesJson = $prefixes | ConvertTo-Json + + $json = @" + { + "display_name": "$PrefixListName", + "prefixes": $prefixesJson + } +"@ + + Try { + $uri = "https://$nsxtmanager/policy/api/v1"+$uriPath+"/prefix-lists/$PrefixListName" + $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -body $json -headers $nsxtHeaders + $response + + if (!$response) { + $output = Get-NsxtPrefixList -Name $PrefixListName -Tier0Gateway $Tier0Gateway + $output + } + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Add-NsxtPrefix + +Function Add-NsxtPrefixList { + <# + .SYNOPSIS + Add an IP Prefix List to a Route Map + + .DESCRIPTION + The Add-NsxtPrefixList cmdlet adds an IP Prefix List to a Route Map + + .EXAMPLE + Get-NsxtPrefixList -Name sfo-w01-cl01-prefix-list | Add-NsxtPrefixList -RouteMap sfo-w01-ec01-route-map -Action PERMIT + This example adds an IP Prefix List to a specific Route Map + #> + + Param ( + [Parameter (Mandatory = $false)] [String]$Name, + [Parameter (Mandatory = $false)] [String]$Tier0Gateway, + [Parameter (Mandatory = $false)] [String]$RouteMap, + [Parameter (Mandatory = $false)] [String]$Action, + [Parameter (ValueFromPipeline, Mandatory = $false)] [psObject]$inputObject + ) + + if ($inputObject) { + $Tier0GatewayId = $inputObject.parent_path.Split('/')[3] + $Tier0Gateway = (Get-NsxtTier0Gateway -Id $Tier0GatewayId).display_name + + if ($inputObject.resource_type -eq "Tier0RouteMap") { + $RouteMap = $inputObject.display_name + $existingEntries = $inputObject.entries + $uriPath = $inputObject.parent_path + } + elseif ($inputObject.resource_type -eq "PrefixList" -and $RouteMap) { + $routeMapInput = Get-NsxtTier0Gateway -Name $Tier0Gateway | Get-NsxtRouteMap -Name $RouteMap + $existingEntries = $routeMapInput.entries + $uriPath = $routeMapInput.parent_path + } + else { + Write-Error "Invalid pipeline passthrough. Exiting." + Break + } + } + + $prefixListPath = (Get-NsxtTier0Gateway -Name $Tier0Gateway | Get-NsxtPrefixList -Name $Name).path + $prefixListPathArray = @() + $prefixListPathArray += $prefixListPath + + $existingEntriesPrefixListMatches = $existingEntries.prefix_list_matches + $existingPrefixListPathArray = @() + $existingPrefixListPathArray += $existingEntriesPrefixListMatches + + $existingEntriesAction = $existingEntries.action + + + $existingEntry = @{ + prefix_list_matches = $existingPrefixListPathArray + action = $existingEntriesAction + } + + $newEntry = @{ + prefix_list_matches = $prefixListPathArray + action = $Action + } + + $entries = @() + $entries += $existingEntry + $entries += $newEntry + + $entriesJson = $entries | ConvertTo-Json + + $json = @" + { + "entries": $entriesJson + } +"@ + + Try { + $uri = "https://$nsxtmanager/policy/api/v1/"+$uriPath+"/route-maps/$RouteMap" + $response = Invoke-RestMethod -Method PUT -URI $uri -ContentType application/json -body $json -headers $nsxtHeaders + $response + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Add-NsxtPrefixList + +Function Get-NsxtRouteMap { + <# + .SYNOPSIS + Get Tier-0 Gateway Route Maps + + .DESCRIPTION + The Get-NsxtRouteMap cmdlet retrieves the Route Maps assigned to a specified Tier-0 Gateway + + .EXAMPLE + Get-NsxtRouteMap -tier0Gateway sfo-w01-ec01-t0-gw01 + This example gets all Route Maps on the Tier-0 Gateway + + .EXAMPLE + Get-NsxtRouteMap -tier0Gateway sfo-w01-ec01-t0-gw01 -name sfo-w01-ec01-t0-gw01-routemap + This example gets a specific route map by name from the Tier-0 Gateway + #> + + Param ( + [Parameter (Mandatory = $true)] [String]$tier0Gateway, + [Parameter (Mandatory = $false)] [String]$name, + [Parameter (ValueFromPipeline, Mandatory = $false)] [psObject]$inputObject + ) + + # Validating pipeline input resource_type + if ($inputObject -and $inputObject.resource_type -eq "Tier0") { + $tier0Gateway = $inputObject.display_name + $uriPath = $inputObject.path + } + elseif ($inputObject -and $inputObject.resource_type -ne "Tier0") { + Write-Error "Invalid pipeline passthrough. Exiting." + Break + } + elseif (!$inputObject) { + if (!$tier0Gateway) { + Write-Output "Tier 0 Gateway: $Tier0Gateway" + $Tier0Gateway = Read-Host -Prompt "Tier-0 Gateway not defined. Type in the name of your Tier-0 Gateway, then press Enter" + } + $uriPath = (Get-NsxtTier0Gateway -Name $tier0Gateway).path + } + + Try { + if (!$PsBoundParameters.ContainsKey("Name")) { + $uri = "https://$nsxtmanager/policy/api/v1"+$uriPath+"/route-maps" + $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders + $response.results + } + elseif ($PsBoundParameters.ContainsKey("Name")) { + $uri = "https://$nsxtmanager/policy/api/v1"+$uriPath+"/route-maps" + $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders + $response.results | Where-Object { $_.display_name -eq $Name } + } + } + Catch { + if ($_.Exception -match "400" -or $_.Exception -match "Bad Request") { + Write-Error "The NSX Tier-0 Gateway was not properly defined." + } + } +} +Export-ModuleMember -Function Get-NsxtRouteMap + +Function New-NsxtRouteMap { + <# + .SYNOPSIS + Creates a Route Map on a specified Tier-0 Gateway + + .DESCRIPTION + The New-NsxtRouteMap cmdlet creates a Route Map on a specified Tier-0 Gateway + + .EXAMPLE + New-NsxtRouteMap -Name sfo-w01-cl01-route-map -Tier0Gateway sfo-w01-ec01-t0-gw01 -PrefixList sfo-w01-ec01-prefix-list + This example creates a new Route Map on a Tier-0 Gateway + + .EXAMPLE + Net-NsxtTier0Gateway sfo-w01-ec01-t0-gw01 | Get-NsxtPrefixList -Name sfo-w01-ec01-prefix-list | New-NsxtRouteMap -Name sfo-w01-cl01-route-map + This example creates a new Route Map on a Tier-0 Gateway + #> + + Param ( + [Parameter (Mandatory = $false)] [String]$Name, + [Parameter (Mandatory = $false)] [String]$Tier0Gateway, + [Parameter (Mandatory = $false)] [String]$PrefixList, + [Parameter (Mandatory = $false)] [String]$Action, + [Parameter (Mandatory = $false)] [String]$Json, + [Parameter (ValueFromPipeline, Mandatory = $false)] [psObject]$inputObject + ) + + if ($inputObject) { + if ($inputObject.resource_type -eq "Tier0") { + $Tier0Gateway = $inputObject.display_name + $Tier0GatewayId = $inputObject.id + $uriPath = $inputObject.path + } + elseif ($inputObject.resource_type -eq "PrefixList") { + $Tier0GatewayId = $inputObject.parent_path.Split('/')[3] + $PrefixListPath = $inputObject.path + $Tier0Gateway = (Get-NsxtTier0Gateway -Id $Tier0GatewayId).display_name + $uriPath = $inputObject.parent_path + } + else { + Write-Error "Invalid pipeline passthrough. Exiting." + Break + } + } elseif (!$inputObject){ + $uriPath = (Get-NsxtTier0Gateway -Name $Tier0Gateway).path + } + + if (!$PrefixListPath) { + $PrefixListPath = $uriPath+"/prefix-lists/"+$PrefixList + } + + $json = @" +{ + "display_name" : "$Name", + "entries" : + [ + { + "action" : "$Action", + "prefix_list_matches" : [ "$prefixListPath" ] + } + ] +} +"@ + + Try { + $uri = "https://$nsxtmanager/policy/api/v1"+$uriPath+"/route-maps/$Name" + $response = Invoke-RestMethod -Method PUT -URI $uri -ContentType application/json -body $json -headers $nsxtHeaders + $response + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function New-NsxtRouteMap + +Function Remove-NsxtRouteMap { + <# + .SYNOPSIS + Remove a Route Map from a specified Tier-0 Gateway + + .DESCRIPTION + The Remove-NsxtRouteMap cmdlet removes a Route Map attached to a specified Tier-0 Gateway + + .EXAMPLE + Remove-NsxtRouteMap -name sfo-w01-ec01-t0-gw01-routemap -tier0Gateway sfo-w01-ec01-t0-gw01 + This example removes the Route Map sfo-w01-ec01-t0-gw01-routemap from Tier-0 Gateway sfo-w01-ec01-t0-gw01 + #> + + Param ( + [Parameter (Mandatory = $false)] [String]$name, + [Parameter (Mandatory = $false)] [String]$tier0Gateway, + [Parameter (ValueFromPipeline, Mandatory = $false)] [psObject]$inputObject + ) + + if ($inputObject) { + if ($inputObject.resource_type -eq "Tier0RouteMap") { + $Name = $inputObject.display_name + $Tier0GatewayId = $inputObject.parent_path.Split('/')[3] + $Tier0Gateway = (Get-NsxtTier0Gateway -Id $Tier0GatewayId).display_name + $uriPath = $inputObject.parent_path + } + elseif ($inputObject.resource_type -eq "Tier0" -and $Name -and !$Tier0Gateway) { + $Tier0GatewayId = $inputObject.id + $Tier0Gateway = $inputObject.display_name + $uriPath = $inputObject.path + } + else { + Write-output $inputObject.resource_type + Write-Error "Invalid pipeline passthrough. Exiting." + Break + } + } + elseif (!$inputObject) { + if (!$tier0Gateway) { + $tier0Gateway = Read-Host -Prompt "Tier-0 Gateway not defined. Type in the name of your Tier-0 Gateway, then press Enter" + } + $uriPath = (Get-NsxtTier0Gateway -Name $Tier0Gateway).path + } + + Try { + $preCheckRouteMap = Get-NsxtRouteMap -name $Name -tier0Gateway $Tier0Gateway -ErrorAction SilentlyContinue + } + Catch { + Write-Error $_.Exception.Message + } + + if ($preCheckRouteMap -eq "NSX-T RouteMap $Name was not found.") { + Write-Error $preCheckRouteMap + Break + } + + # Check if the route map is applied to the route redistribution configuration + Try { + $getRouteRedistribution = Get-NsxtRouteRedistributionPolicy -tier0Gateway $tier0Gateway + if ($getRouteRedistribution.route_redistribution_config.redistribution_rules.route_map_path -eq $preCheckRouteMap.path) { + $getRouteRedistribution | Set-NsxtRouteRedistributionPolicy -tier0Gateway $tier0Gateway -RemoveRouteMap:$True | Out-Null + } + } + Catch { + Write-Error $_.Exception.Message + } + + Try { + $uri = "https://$nsxtmanager/policy/api/v1"+$uriPath+"/route-maps/$name" + $response = Invoke-RestMethod -Method DELETE -URI $uri -headers $nsxtHeaders -ContentType application/json + $response + } + Catch { + Write-Error $_.Exception.Message + Break + } + + # Validation + Try { + $checkRouteMap = Get-NsxtRouteMap -Name $Name -Tier0Gateway $Tier0Gateway -ErrorAction SilentlyContinue + } + Catch { + Write-Error $_.Exception.Message + } + + if ($checkRouteMap -eq "NSX-T RouteMap $Name was not found.") { + Write-Output "NSX-T RouteMap $Name has been successfully deleted." + } + else { + Write-Error -Message "NSX-T RouteMap $Name was not deleted. Please check the logs." + } +} +Export-ModuleMember -Function Remove-NsxtRouteMap + +Function Get-NsxtRouteRedistributionPolicy { + <# + .SYNOPSIS + Get the route redistribution policy from a Tier-0 Gateway + + .DESCRIPTION + The Get-NsxtRouteRedistributionPolicy cmdlet get the route redistribution policy from a Tier-0 Gateway + + .EXAMPLE + Get-NsxtRouteRedistributionPolicy -tier0Gateway sfo-w01-ec01-t0-gw01 + This example returns the route redistribution policy for Tier-0 Gateway sfo-w01-ec01-t0-gw01 + #> + + Param ( + [Parameter (Mandatory = $false)] [String]$tier0Gateway, + [Parameter (ValueFromPipeline, Mandatory = $false)] [psObject]$inputObject + ) + + if ($inputObject -and $inputObject.resource_type -eq "Tier0") { + $Tier0Gateway = $inputObject.display_name + $uriPath = $inputObject.path + } + elseif ($inputObject -and $inputObject.resource_type -ne "Tier0") { + Write-Error "Invalid pipeline passthrough. Exiting." + Break + } + elseif (!$inputObject) { + if (!$Tier0Gateway) { + $Tier0Gateway = Read-Host -Prompt "Tier-0 Gateway not defined. Type in the name of your Tier-0 Gateway, then press Enter" + } + $uriPath = (Get-NsxtTier0Gateway -Name $Tier0Gateway).path + } + + Try { + $uri = "https://$nsxtmanager/policy/api/v1"+$uriPath+"/locale-services/default" + $response = Invoke-RestMethod -Method GET -URI $uri -headers $nsxtHeaders -ContentType application/json + $response + } + Catch { + Write-Error $_.Exception.Message + } + +} +Export-ModuleMember Get-NsxtRouteRedistributionPolicy + +Function Set-NsxtRouteRedistributionPolicy { + <# + .SYNOPSIS + Set the route redistriution policy for a Tier 0 Gateway + + .DESCRIPTION + The Set-NsxtRouteRedistributionPolicy cmdlet sets the route redistriution policy for a Tier 0 Gateway + + .EXAMPLE + Get-NsxtRouteRedistributionPolicy -tier0Gateway "sfo-w01-ec01-t0-gw01" | Set-NsxtRouteRedistributionPolicy -RouteMap "sfo-w01-ec01-t0-gw01-routemap" + This example sets the RouteMap "sfo-w01-ec01-t0-gw01-routemap" on the route redistribution policy for Tier-0 Gateway "sfo-w01-t0-ec01-t0-gw01" + #> + + Param ( + [Parameter (Mandatory = $false)] [String]$tier0Gateway, + [Parameter (Mandatory = $false)] [String]$routeMap, + [Parameter (Mandatory = $false)] [Bool]$removeRouteMap, + [Parameter (ValueFromPipeline, Mandatory = $true)] [psObject]$inputObject + ) + + if ($inputObject -and $inputObject.resource_type -eq "LocaleServices") { + $Tier0GatewayId = $inputObject.parent_path.Split('/')[3] + $Tier0Gateway = (Get-NsxtTier0Gateway -Id $Tier0GatewayId).display_name + $edgeClusterPath = $inputObject.edge_cluster_path + $bgpEnabled = $inputObject.route_redistribution_config.bgp_enabled + $routeRedistributionName = $inputObject.route_redistribution_config.redistribution_rules.name + $routeRedistributionTypes = $inputObject.route_redistribution_config.redistribution_rules.route_redistribution_types + $uriPath = $inputObject.parent_path + } + elseif ($inputObject -and $inputObject.resource_type -ne "LocaleServices") { + Write-Error "Invalid pipeline passthrough. Exiting." + Break + } + + if (!$inputObject) { + if (!$Tier0Gateway) { + $Tier0Gateway = Read-Host -Prompt "Tier-0 Gateway not defined. Type in the name of your Tier-0 Gateway, then press Enter" + } + + $getRedistributionPolicy = Get-NsxtTier0Gateway -Name $Tier0Gateway + + $edgeClusterPath = $getRedistributionPolicy.edge_cluster_path + $bgpEnabled = $getRedistributionPolicy.route_redistribution_config.bgp_enabled + $routeRedistributionName = $getRedistributionPolicy.route_redistribution_config.redistribution_rules.name + $routeRedistributionTypes = $getRedistributionPolicy.route_redistribution_config.redistribution_rules.route_redistribution_types + $uriPath = (Get-NsxtTier0Gateway -Name $Tier0Gateway).path + } + + $routeMapPath = "/infra/tier-0s/$Tier0GatewayId/route-maps/$RouteMap" + + foreach ($routeRedistributionType in $routeRedistributionTypes) { + $routeRedistributionTypeString += @" +"$routeRedistributionType", +"@ + } + + $routeRedistributionTypeString = $routeRedistributionTypeString.Substring(0, $routeRedistributionTypeString.Length - 1) + + if ($RemoveRouteMap -eq $true) { + $json = @" +{ + "edge_cluster_path" : "$edgeClusterPath", + "route_redistribution_config" : + { + "bgp_enabled" : "$bgpEnabled", + "redistribution_rules" : + [ + { + "name" : "$routeRedistributionName", + "route_redistribution_types" : [ $routeRedistributionTypeString ] + } + ] + } +} +"@ + } + elseif ($RemoveRouteMap -eq $false -or !$RemoveRouteMap) { + $json = @" +{ + "edge_cluster_path" : "$edgeClusterPath", + "route_redistribution_config" : + { + "bgp_enabled" : "$bgpEnabled", + "redistribution_rules" : + [ + { + "name" : "$routeRedistributionName", + "route_redistribution_types" : [ $routeRedistributionTypeString ], + "route_map_path" : "$routeMapPath" + } + ] + } +} +"@ + } + + Try { + $uri = "https://$nsxtmanager/policy/api/v1"+$uriPath+"/locale-services/default" + $response = Invoke-RestMethod -Method PATCH -URI $uri -headers $nsxtHeaders -ContentType application/json -body $json + $response + + if (!$response) { + $output = Get-NsxtRouteRedistributionPolicy -Tier0Gateway $Tier0Gateway + $output + } + } + Catch { + Write-Error $_.Exception.Message + } + +} +Export-ModuleMember Set-NsxtRouteRedistributionPolicy + +Function Get-NsxtManagerAuthPolicy { + <# + .SYNOPSIS + Get the Authentication Policy for NSX Manager Nodes + + .DESCRIPTION + The Get-NsxtManagerAuthPolicy cmdlet getss the current authentication policy for NSX Manager Node + + .EXAMPLE + Get-NsxtManagerAuthPolicy -nsxtManagerNode "sfo-m01-nsx01a.sfo.rainpole.io" + This example returns the current Authentication policy in NSX manager node sfo-m01-nsx01a.sfo.rainpole.io + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$nsxtManagerNode + ) + + Try { + $requestingURL = "https://" + $nsxtManagerNode + "/api/v1/node/aaa/auth-policy" + $response = Invoke-RestMethod -Method GET -URI $requestingURL -ContentType application/json -headers $nsxtHeaders + $response + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember Get-NsxtManagerAuthPolicy + +Function Set-NsxtManagerAuthPolicy { + <# + .SYNOPSIS + Set the Authentication Policy for NSX Manager Node + + .DESCRIPTION + The Set-NsxtManagerAuthPolicy cmdlet configures the authentication policy for NSX Manager Node + + .EXAMPLE + Set-NsxManagerAuthPolicy -nsxtManagerNode "sfo-m01-nsx01a.sfo.rainpole.io" -api_lockout_period 900 -api_reset_period 120 -api_max_attempt 5 -cli_lockout_period 900 -cli_max_attempt 5 -min_passwd_length 15 + This example customized the Authentication policy in NSX manager node sfo-m01-nsx01a.sfo.rainpole.io. + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$nsxtManagerNode, + [Parameter (Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int]$api_lockout_period, + [Parameter (Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int]$api_reset_period, + [Parameter (Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int]$api_max_attempt, + [Parameter (Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int]$cli_lockout_period, + [Parameter (Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int]$cli_max_attempt, + [Parameter (Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int]$min_passwd_length + ) + + $authPolicyBody = @{} + if ($PsBoundParameters.ContainsKey("api_lockout_period")) { + $authPolicyBody+= @{api_failed_auth_lockout_period = $api_lockout_period} + } + if ($PsBoundParameters.ContainsKey("api_reset_period")) { + $authPolicyBody += @{api_failed_auth_reset_period = $api_reset_period} + } + if ($PsBoundParameters.ContainsKey("api_max_attempt")) { + $authPolicyBody += @{api_max_auth_failures = $api_max_attempt} + } + if ($PsBoundParameters.ContainsKey("cli_lockout_period")) { + $authPolicyBody += @{cli_failed_auth_lockout_period = $cli_lockout_period} + } + if ($PsBoundParameters.ContainsKey("cli_max_attempt")) { + $authPolicyBody += @{cli_max_auth_failures = $cli_max_attempt} + } + if ($PsBoundParameters.ContainsKey("min_passwd_length")) { + $authPolicyBody += @{minimum_password_length = $min_passwd_length} + } + + Try { + $requestingURL = "https://" + $nsxtManagerNode + "/api/v1/node/aaa/auth-policy" + $response = Invoke-RestMethod -Method PUT -URI $requestingURL -ContentType application/json -headers $nsxtHeaders -Body ($authPolicyBody | ConvertTo-Json) + $response + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember Set-NsxtManagerAuthPolicy + +Function Get-NsxtEdgeNodeAuthPolicy { + <# + .SYNOPSIS + Get the Authentication Policy for NSX Edge Nodes + + .DESCRIPTION + The Get-NsxtEdgeNodeAuthPolicy cmdlet getss the authentication policy for NSX Edge Nodes + + .EXAMPLE + Get-NsxtEdgeNodeAuthPolicy -nsxtManagerNode "sfo-m01-nsx01a.sfo.rainpole.io" + This example returns the password policy in NSX manager node sfo-m01-nsx01a.sfo.rainpole.io + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$nsxtManager, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$nsxtEdgeNodeID + ) + + Try { + $requestingURL = "https://" + $nsxtManager + "/api/v1/transport-nodes/" + $nsxtEdgeNodeID + "/node/aaa/auth-policy" + $response = Invoke-RestMethod -Method GET -URI $requestingURL -ContentType application/json -headers $nsxtHeaders + $response + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember Get-NsxtEdgeNodeAuthPolicy + +Function Set-NsxtEdgeNodeAuthPolicy { + <# + .SYNOPSIS + Set the Authentication Policy for NSX Manager Nodes + + .DESCRIPTION + The Set-NsxtManagerAuthPolicy cmdlet getss the authentication policy for NSX Manager Nodes + + .EXAMPLE + Set-NsxManagerAuthPolicy -nsxtManagerNode "sfo-m01-nsx01a.sfo.rainpole.io" -api_lockout_period 900 -api_reset_period 120 -api_max_attempt 5 -cli_lockout_period 900 -cli_max_attempt 5 -min_passwd_length 15 + This example customized the password policy in NSX manager node sfo-m01-nsx01a.sfo.rainpole.io. + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$nsxtManager, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$nsxtEdgeNodeID, + [Parameter (Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int]$cli_lockout_period, + [Parameter (Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int]$cli_max_attempt, + [Parameter (Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int]$min_passwd_length + ) + + $authPolicyBody = @{} + if ($PsBoundParameters.ContainsKey("cli_lockout_period")) { + $authPolicyBody += @{cli_failed_auth_lockout_period = $cli_lockout_period} + } + if ($PsBoundParameters.ContainsKey("cli_max_attempt")) { + $authPolicyBody += @{cli_max_auth_failures = $cli_max_attempt} + } + if ($PsBoundParameters.ContainsKey("min_passwd_length")) { + $authPolicyBody += @{minimum_password_length = $min_passwd_length} + } + + Try { + $requestingURL = "https://" + $nsxtManager + "/api/v1/transport-nodes/" + $nsxtEdgeNodeID + "/node/aaa/auth-policy" + $response = Invoke-RestMethod -Method PUT -URI $requestingURL -ContentType application/json -headers $nsxtHeaders -Body ($authPolicyBody | ConvertTo-Json) + $response + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember Set-NsxtEdgeNodeAuthPolicy + +Function Get-NsxtSyslogStatus { + <# + .SYNOPSIS + Gets the status of the Syslog Service + + .DESCRIPTION + The Get-NsxtSyslogStatus cmdlet gets the status of the Syslog Service for NSX-T Data Center components + + .EXAMPLE + Get-NsxtSyslogStatus -type node + This example gets the status of the syslog service for NSX Manager node + + .EXAMPLE + Get-NsxtSyslogStatus -type transport -id f3bd5bf0-23cd-4c6f-8de5-ab065f74d7fe + This example gets the status of the syslog service for NSX Edge node + #> + + Param ( + [Parameter (ParameterSetName = 'node', Mandatory = $true)] [ValidateNotNullOrEmpty()] [Switch]$node, + [Parameter (ParameterSetName = 'transport', Mandatory = $true)] [ValidateNotNullOrEmpty()] [Switch]$transport, + [Parameter (ParameterSetName = 'transport', Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id + ) + + Try { + if ($PsBoundParameters.ContainsKey("node")) { + $uri = "https://$nsxtManager/api/v1/node/services/syslog/status" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $nsxtHeaders + $response + } + if ($PsBoundParameters.ContainsKey("transport")) { + $uri = "https://$nsxtManager/api/v1/transport-nodes/$id/node/services/syslog/status" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $nsxtHeaders + $response + } + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Get-NsxtSyslogStatus + +Function Get-NsxtSyslogExporter { + <# + .SYNOPSIS + Gets Syslog exporters + + .DESCRIPTION + The Get-NsxtSyslogExporter cmdlet gets the Syslog exporters configures for NSX-T Data Center components + + .EXAMPLE + Get-NsxtSyslogExporter -node + This example gets the configuration of the syslog exporters for NSX Manager node + + .EXAMPLE + Get-NsxtSyslogExporter -transport -id f3bd5bf0-23cd-4c6f-8de5-ab065f74d7fe + This example gets the configuration of the syslog exporters for NSX Edge node + #> + + Param ( + [Parameter (ParameterSetName = 'node', Mandatory = $true)] [ValidateNotNullOrEmpty()] [Switch]$node, + [Parameter (ParameterSetName = 'transport', Mandatory = $true)] [ValidateNotNullOrEmpty()] [Switch]$transport, + [Parameter (ParameterSetName = 'transport', Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id + ) + + Try { + if ($PsBoundParameters.ContainsKey("node")) { + $uri = "https://$nsxtManager/api/v1/node/services/syslog/exporters" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $nsxtHeaders + $response.results + } + if ($PsBoundParameters.ContainsKey("transport")) { + $uri = "https://$nsxtManager/api/v1/transport-nodes/$id/node/services/syslog/exporters" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $nsxtHeaders + $response.results + } + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Get-NsxtSyslogExporter + +Function Set-NsxtSyslogExporter { + <# + .SYNOPSIS + Sets Syslog exporters + + .DESCRIPTION + The Set-NsxtSyslogExporter cmdlet Sets the Syslog exporters configures for NSX-T Data Center components + + .EXAMPLE + Set-NsxtSyslogExporter -node -exporterName Syslog1 -logLevel INFO -port 514 -protocol TCP -server sfo-vrli01.sfo.rainpole.io + This example gets the status of the syslog service for NSX Manager node + + .EXAMPLE + Set-NsxtSyslogExporter -transport -id f3bd5bf0-23cd-4c6f-8de5-ab065f74d7fe -exporterName Syslog1 -logLevel INFO -port 514 -protocol TCP -server sfo-vrli01.sfo.rainpole.io + This example gets the status of the syslog service for NSX Edge node + #> + + Param ( + [Parameter ( ParameterSetName = 'node', Mandatory = $true)] [ValidateNotNullOrEmpty()] [Switch]$node, + [Parameter ( ParameterSetName = 'transport', Mandatory = $true)] [ValidateNotNullOrEmpty()] [Switch]$transport, + [Parameter ( ParameterSetName = 'transport', Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id, + [Parameter ( Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$exporterName, + [Parameter ( Mandatory = $true)] [ValidateSet("EMERG", "ALERT", "CRIT", "ERR", "WARNING", "NOTICE", "INFO", "DEBUG")] [String]$logLevel, + [Parameter ( Mandatory = $true)] [ValidateNotNullOrEmpty()] [Int]$port, + [Parameter ( Mandatory = $true)] [ValidateSet("TCP", "TLS", "UDP", "LI", "LI-TLS")] [String]$protocol, + [Parameter ( Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server + ) + + Try { + $json = '{ + "exporter_name": "' + $exporterName + '", + "level": "' + $logLevel + '", + "port": ' + $port + ', + "protocol": "' + $protocol + '", + "server": "' + $server + '" + }' + + if ($PsBoundParameters.ContainsKey("node")) { + $uri = "https://$nsxtManager/api/v1/node/services/syslog/exporters" + $response = Invoke-RestMethod $uri -Method 'POST' -Headers $nsxtHeaders -ContentType application/json -body $json + $response + } + if ($PsBoundParameters.ContainsKey("transport")) { + $uri = "https://$nsxtManager/api/v1/transport-nodes/$id/node/services/syslog/exporters" + $response = Invoke-RestMethod $uri -Method 'POST' -Headers $nsxtHeaders -ContentType application/json -body $json + $response + } + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Set-NsxtSyslogExporter + +Function Remove-NsxtSyslogExporter { + <# + .SYNOPSIS + Delete Syslog exporters + + .DESCRIPTION + The Remove-NsxtSyslogExporter cmdlet deletes the Syslog exporters for NSX-T Data Center components + + .EXAMPLE + Remove-NsxtSyslogExporter -node -exporterName Syslog1 + This example deletes the syslog exporters for NSX Manager node + + .EXAMPLE + Remove-NsxtSyslogExporter -transport -id f3bd5bf0-23cd-4c6f-8de5-ab065f74d7fe -exporterName Syslog1 + This example deletes the syslog exporters for for NSX Edge node + #> + + Param ( + [Parameter (ParameterSetName = 'node', Mandatory = $true)] [ValidateNotNullOrEmpty()] [Switch]$node, + [Parameter (ParameterSetName = 'transport', Mandatory = $true)] [ValidateNotNullOrEmpty()] [Switch]$transport, + [Parameter (ParameterSetName = 'transport', Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id, + [Parameter ( Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$exporterName + ) + + Try { + if ($PsBoundParameters.ContainsKey("node")) { + $uri = "https://$nsxtManager/api/v1/node/services/syslog/exporters/$exporterName" + $response = Invoke-RestMethod $uri -Method 'DELETE' -Headers $nsxtHeaders + $response + } + if ($PsBoundParameters.ContainsKey("transport")) { + $uri = "https://$nsxtManager/api/v1/transport-nodes/$id/node/services/syslog/exporters/$exporterName" + $response = Invoke-RestMethod $uri -Method 'DELETE' -Headers $nsxtHeaders + $response + } + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Remove-NsxtSyslogExporter + +Function Copy-vRealizeLoadBalancer +{ + <# + .SYNOPSIS + Creates a Load Balancer for vRealize component failover + + .DESCRIPTION + Creates a new loadbalancer in a secondary VMware Cloud Foundation instance by duplicating the settings of the existing load balancer in the instance where the vRealize components are currently running + + .EXAMPLE + Copy-vRealizeLoadBalancer -sddcManagerAFQDN sfo-vcf01.sfo.rainpole.io -sddcManagerAUser administrator@vsphere.local -sddcManagerAPassword VMw@re1! -sddcManagerBFQDN lax-vcf01.lax.rainpole.io -sddcManagerBUser administrator@vsphere.local -sddcManagerBPassword VMw@re1! -serviceInterfaceIP 192.168.11.3 -wsaCertName xint-wsa01 + This example copies settings from Load Balancer in SDDC A to a new Load Balancer in SDDC B + #> + + Param ( + [Parameter (Mandatory = $true)] [String]$sddcManagerAFqdn, + [Parameter (Mandatory = $true)] [String]$sddcManagerAUser, + [Parameter (Mandatory = $true)] [String]$sddcManagerAPassword, + [Parameter (Mandatory = $true)] [String]$sddcManagerBFqdn, + [Parameter (Mandatory = $true)] [String]$sddcManagerBUser, + [Parameter (Mandatory = $true)] [String]$sddcManagerBPassword, + [Parameter (Mandatory = $true)] [String]$serviceInterfaceIp, + [Parameter (Mandatory = $true)] [String]$wsaCertName + ) + + Try { + # Setup Parameters + $t1Name = "recovery-t1-gw01" + $siName = "recovery-t1-gw01-si01" + $lbName = "recovery-lb01" + + #Retrieve Edge Cluster Details from SDDC Manager B + Request-VCFToken -fqdn $sddcManagerBFqdn -Username $sddcManagerBUser -Password $sddcManagerBPassword | Out-Null + $mgmtNsxtClusterID = (Get-VCFWorkloadDomain | Where-Object {$_.type -eq "Management"}).nsxtCluster.id + $edgeClusterName = (Get-VCFEdgeCluster | Where-Object {$_.nsxtCluster.id -eq $mgmtNsxtClusterID}).Name + + #Retrieve Segment, WSA, VRA and vROPS Details from SDDC Manager A + Request-VCFToken -fqdn $sddcManagerAFqdn -Username $sddcManagerAUser -Password $sddcManagerAPassword | Out-Null + $xintSegmentDetails = Get-VCFApplicationVirtualNetwork | Where-Object {$_.regionType -eq "X_REGION"} + $wsaDetailsObject = Get-WSAServerDetail -fqdn $sddcManagerAFqdn -username $sddcManagerAUser -password $sddcManagerAPassword + $vraDetailsObject = Get-vRAServerDetail -fqdn $sddcManagerAFqdn -username $sddcManagerAUser -password $sddcManagerAPassword + $vropsDetailsObject = Get-vROPsServerDetail -fqdn $sddcManagerAFqdn -username $sddcManagerAUser -password $sddcManagerAPassword + + #Add Cert to NSX + $nsxManager = Get-NsxtServerDetail -fqdn $sddcManagerBFqdn -user $sddcManagerBUser -pass $sddcManagerBPassword -domainType MANAGEMENT + Request-NsxToken -fqdn $nsxManager.fqdn -username $nsxManager.adminUser -password $nsxManager.adminPass | Out-Null + + #Get xint segment ID from NSX LM on recovery site + $segmentID = Get-NsxtGlobalSegmentID -segmentName $xintSegmentDetails.name + } + Catch { + Debug-ExceptionWriter -object $_ + } + + Try { + if ((!$edgeClusterName) -OR (!$xintSegmentDetails) -OR (!$wsaDetailsObject) -OR ((!$vraDetailsObject) -AND (!$vropsDetailsObject))) { + Write-Output "Requirements for Copying Load Balancer not Met". + if (!$wsaDetailsObject) {Write-Output "Clustered Workspace ONE Access was not discovered in the source SDDC Manager instance"} + if ((!$vraDetailsObject) -AND (!$vropsDetailsObject)) {Write-Output "Neither vRealize Automation nor vRealize Operations Manager was discovered in the source SDDC Manager instance"} + if (!$xintSegmentDetails) {Write-Output "Cross-Region Segment was discovered in the target SDDC Manager instance"} + if (!$edgeClusterName) {Write-Output "Management Edge Cluster was not discovered in the target SDDC Manager instance"} + } + else { + #Create a Load Balancer Spec + if (!$vraDetailsObject) { + $lbCustomObject = New-vRealizeLoadBalancerSpec -xintSegmentDetails $xintSegmentDetails -serviceInterfaceIp $serviceInterfaceIp -wsaDetailsObject $wsaDetailsObject -vropsDetailsObject $vropsDetailsObject -wsaCertName $wsaCertName -t1Name $t1Name -lbName $lbName -siName $siName -segmentID $segmentID + } + elseif (!$vropsDetailsObject) { + $lbCustomObject = New-vRealizeLoadBalancerSpec -xintSegmentDetails $xintSegmentDetails -serviceInterfaceIp $serviceInterfaceIp -wsaDetailsObject $wsaDetailsObject -vraDetailsObject $vraDetailsObject -wsaCertName $wsaCertName -t1Name $t1Name -lbName $lbName -siName $siName -segmentID $segmentID + } + else { + $lbCustomObject = New-vRealizeLoadBalancerSpec -xintSegmentDetails $xintSegmentDetails -serviceInterfaceIp $serviceInterfaceIp -wsaDetailsObject $wsaDetailsObject -vraDetailsObject $vraDetailsObject -vropsDetailsObject $vropsDetailsObject -wsaCertName $wsaCertName -t1Name $t1Name -lbName $lbName -siName $siName -segmentID $segmentID + } + + $wsaCertPresent = Add-CertToNsxCertificateStore -certName $wsaCertName + + if ($wsaCertPresent -eq $true) { + $ConfigJson = $lbCustomObject.t1_spec.gw | ConvertTo-Json + New-NsxtTier1 -tier1Gateway $t1Name -json $ConfigJson + $edgeClusterID = (Get-NsxtEdgeCluster -name $edgeClusterName).id + $ConfigJson = '{"edge_cluster_path": "/infra/sites/default/enforcement-points/default/edge-clusters/' + $edgeClusterID + '"}' + Set-NsxtTier1 -tier1Gateway $t1name -json $ConfigJson + $ConfigJson = '{ + "segment_path": "'+ $lbCustomObject.t1_spec.service_interface.segment_path + '", + "subnets": [ + { + "ip_addresses": [ "'+ $lbCustomObject.t1_spec.service_interface.subnets.ip_addresses + '" ], + "prefix_len": "'+ $lbCustomObject.t1_spec.service_interface.subnets.prefix_len + '" + } + ] + }' + New-NsxtTier1ServiceInterface -tier1Gateway $t1name -interfaceId $lbCustomObject.t1_spec.service_interface.id -json $ConfigJson + $ConfigJson = '{ + "network": "'+ $lbCustomObject.t1_spec.static_routes.network + '", + "next_hops": [ + { + "ip_address": "'+ $lbCustomObject.t1_spec.static_routes.next_hops.ip_address + '", + "admin_distance": '+ $lbCustomObject.t1_spec.static_routes.next_hops.admin_distance + ', + "scope": [ + "'+ $lbCustomObject.t1_spec.static_routes.next_hops.scope +'" + ] + } + ], + "display_name": "'+ $lbCustomObject.t1_spec.static_routes.display_name + '" + }' + New-NsxtTier1StaticRoute -tier1Gateway $t1name -segment $xintSegmentDetails.name -json $ConfigJson + $ConfigJson = $lbCustomObject.lb_spec.lb_service | ConvertTo-Json + New-NsxtLoadBalancer -lbName $lbName -json $ConfigJson + Foreach ($monitor in $lbCustomObject.lb_spec.service_monitors) { + Try { + $ConfigJson = $monitor | ConvertTo-Json -Depth 10 + New-NsxtLBServiceMonitor -monitorName $monitor.display_name -json $ConfigJson + } + Catch { + Debug-ExceptionWriter -object $_ + } + } + Foreach ($profile in $lbCustomObject.lb_spec.app_profiles) { + Try { + $ConfigJson = $profile | ConvertTo-Json + New-NsxtLBAppProfile -appProfileName $profile.display_name -json $ConfigJson + } + Catch { + Debug-ExceptionWriter -object $_ + } + } + Foreach ($profile in $lbCustomObject.lb_spec.persistence_profiles) { + Try { + $ConfigJson = $profile | ConvertTo-Json + New-NsxtLBPersistenceAppProfile -appProfileName $profile.display_name -json $ConfigJson + } + Catch { + Debug-ExceptionWriter -object $_ + } + } + Foreach ($pool in $lbCustomObject.lb_spec.pools) { + Try { + $ConfigJson = $pool | ConvertTo-Json + New-NsxtLBPool -poolName $pool.display_name -json $ConfigJson + } + Catch { + Debug-ExceptionWriter -object $_ + } + } + Foreach ($virtualServer in $lbCustomObject.lb_spec.virtual_Servers) { + Try { + $ConfigJson = $virtualServer | ConvertTo-Json -Depth 10 + New-NsxtLBVirtualServer -virtualServerName $virtualServer.display_name -json $ConfigJson + } + Catch { + Debug-ExceptionWriter -object $_ + } + } + } + else { + Write-Error "Aborting remainder of NSX-T Load Balancer configuration until certificate files present" + } + } + } + Catch { + Debug-ExceptionWriter -object $_ + } +} +Export-ModuleMember -Function Copy-vRealizeLoadBalancer + +Function New-vRealizeLoadBalancerSpec +{ + Param ( + [Parameter (Mandatory = $true)] [Array]$xintSegmentDetails, + [Parameter (Mandatory = $true)] [Array]$serviceInterfaceIp, + [Parameter (Mandatory = $true)] [Array]$wsaDetailsObject, + [Parameter (Mandatory = $false)] [Array]$vraDetailsObject, + [Parameter (Mandatory = $false)] [Array]$vropsDetailsObject, + [Parameter (Mandatory = $true)] [String]$wsaCertName, + [Parameter (Mandatory = $true)] [String]$t1Name, + [Parameter (Mandatory = $true)] [String]$lbName, + [Parameter (Mandatory = $true)] [String]$siName, + [Parameter (Mandatory = $true)] [String]$segmentID + ) + + $xintSegmentName = $xintSegmentDetails.name + $xintSegmentServiceInterfacePrefixLength = cidrMaskLookup -source mask -value $xintSegmentDetails.subnetMask + $xintSegmentNextHopIP = $xintSegmentDetails.gateway + + $xintWsaVip = $wsaDetailsObject.loadBalancerIpAddress + $xintWsaNode1Ip = $wsaDetailsObject.node1IpAddress + $xintWsaNode2Ip = $wsaDetailsObject.node2IpAddress + $xintWsaNode3Ip = $wsaDetailsObject.node3IpAddress + $xintWsaNode1Name = $wsaDetailsObject.fqdn[0].split(".")[0] + $xintWsaNode2Name = $wsaDetailsObject.fqdn[1].split(".")[0] + $xintWsaNode3Name = $wsaDetailsObject.fqdn[2].split(".")[0] + + If ($vropsDetailsObject) + { + $xintVropsVip = $vropsDetailsObject.loadBalancerIpAddress + $xintVropsNode1Ip = $vropsDetailsObject.node1IpAddress + $xintVropsNode2Ip = $vropsDetailsObject.node2IpAddress + $xintVropsNode3Ip = $vropsDetailsObject.node3IpAddress + $xintVropsNode1Name = $vropsDetailsObject.fqdn[0].split(".")[0] + $xintVropsNode2Name = $vropsDetailsObject.fqdn[1].split(".")[0] + $xintVropsNode3Name = $vropsDetailsObject.fqdn[2].split(".")[0] + } + + If ($vraDetailsObject) + { + $xintVraVip = $vraDetailsObject.loadBalancerIpAddress + $xintVraNode1Ip = $vraDetailsObject.node1IpAddress + $xintVraNode2Ip = $vraDetailsObject.node2IpAddress + $xintVraNode3Ip = $vraDetailsObject.node3IpAddress + $xintVraNode1Name = $vraDetailsObject.fqdn[0].split(".")[0] + $xintVraNode2Name = $vraDetailsObject.fqdn[1].split(".")[0] + $xintVraNode3Name = $vraDetailsObject.fqdn[2].split(".")[0] + } + + $lbJson += '{' $lbJson += '"t1_spec":{' $lbJson += '"gw":{' $lbJson += '"resource_type": "Tier1",' @@ -11267,2816 +14749,5549 @@ Function New-vRealizeLoadBalancerSpec $lbJson += '"ip_addresses": [' $lbJson += '""' $lbJson += '],' - $lbJson += '"prefix_len": ' - $lbJson += '}' - $lbJson += ']' - $lbJson += '},' - $lbJson += '"static_routes":{' - $lbJson += '"network": "0.0.0.0/0",' - $lbJson += '"next_hops": [' + $lbJson += '"prefix_len": ' + $lbJson += '}' + $lbJson += ']' + $lbJson += '},' + $lbJson += '"static_routes":{' + $lbJson += '"network": "0.0.0.0/0",' + $lbJson += '"next_hops": [' + $lbJson += '{' + $lbJson += '"ip_address": "",' + $lbJson += '"admin_distance": 1,' + $lbJson += '"scope": [' + $lbJson += '"/infra/tier-1s//locale-services/default/interfaces/"' + $lbJson += '] ' + $lbJson += '}' + $lbJson += '],' + $lbJson += '"display_name": "default"' + $lbJson += '}' + $lbJson += '},' + $lbJson += '"lb_spec": {' + $lbJson += '"lb_service": [' + $lbJson += '{' + $lbJson += '"display_name": "",' + $lbJson += '"resource_type": "LBService",' + $lbJson += '"enabled": true,' + $lbJson += '"size": "SMALL",' + $lbJson += '"connectivity_path":""' + $lbJson += '}' + $lbJson += '],' + $lbJson += '"service_monitors": [' + If ($vropsDetailsObject) + { + $lbJson += '{' + $lbJson += '"display_name": "vrops-https-monitor",' + $lbJson += '"description": "vRealize Operations Manager HTTPS Monitor",' + $lbJson += '"resource_type": "LBHttpsMonitorProfile",' + $lbJson += '"monitor_port": "443",' + $lbJson += '"interval": "5",' + $lbJson += '"fall_count": "3",' + $lbJson += '"rise_count": "3",' + $lbJson += '"timeout": "16",' + $lbJson += '"request_method": "GET",' + $lbJson += '"request_url": "/suite-api/api/deployment/node/status?services=api&services=adminui&services=ui",' + $lbJson += '"request_version": "HTTP_VERSION_1_1",' + $lbJson += '"response_status_codes": [' + $lbJson += '"200","204","301"' + $lbJson += '],' + $lbJson += '"response_body": "ONLINE",' + $lbJson += '"server_ssl_profile_binding": {' + $lbJson += '"ssl_profile_path": "/infra/lb-server-ssl-profiles/default-balanced-server-ssl-profile"' + $lbJson += '}' + $lbJson += '},' + } + If ($vraDetailsObject) + { + $lbJson += '{' + $lbJson += '"display_name": "vra-http-monitor",' + $lbJson += '"description": "vRealize Automation HTTP Monitor",' + $lbJson += '"resource_type": "LBHttpMonitorProfile",' + $lbJson += '"monitor_port": "8008",' + $lbJson += '"interval": "3",' + $lbJson += '"fall_count": "3",' + $lbJson += '"rise_count": "3",' + $lbJson += '"timeout": "10",' + $lbJson += '"request_method": "GET",' + $lbJson += '"request_url": "/health",' + $lbJson += '"request_version": "HTTP_VERSION_1_1",' + $lbJson += '"response_status_codes": [' + $lbJson += '"200"' + $lbJson += '],' + $lbJson += '"response_body": ""' + $lbJson += '},' + } + $lbJson += '{' + $lbJson += '"display_name": "wsa-https-monitor",' + $lbJson += '"description": "Clustered Workspace ONE Access HTTPS Monitor",' + $lbJson += '"resource_type": "LBHttpsMonitorProfile",' + $lbJson += '"monitor_port": "443",' + $lbJson += '"interval": "3",' + $lbJson += '"fall_count": "3",' + $lbJson += '"rise_count": "3",' + $lbJson += '"timeout": "10",' + $lbJson += '"request_method": "GET",' + $lbJson += '"request_url": "/SAAS/API/1.0/REST/system/health/heartbeat",' + $lbJson += '"request_version": "HTTP_VERSION_1_1",' + $lbJson += '"response_status_codes": [' + $lbJson += '"200","201"' + $lbJson += '],' + $lbJson += '"response_body": "ok",' + $lbJson += '"server_ssl_profile_binding": {' + $lbJson += '"client_certificate_path": "/infra/certificates/",' + $lbJson += '"ssl_profile_path": "/infra/lb-server-ssl-profiles/default-balanced-server-ssl-profile"' + $lbJson += '}' + $lbJson += '}' + $lbJson += '],' + $lbJson += '"app_profiles": [' + If ($vropsDetailsObject) + { + $lbJson += '{' + $lbJson += '"display_name": "vrops-http-app-profile-redirect",' + $lbJson += '"description": "Cross-Instance vRealize Operations Manager redirect HTTP to HTTPs",' + $lbJson += '"resource_type": "LBHttpProfile",' + $lbJson += '"idle_timeout": "1800",' + $lbJson += '"request_header_size": "1024",' + $lbJson += '"response_header_size": "4096",' + $lbJson += '"http_redirect_to_https": "True",' + $lbJson += '"response_timeout": "60",' + $lbJson += '"ntlm": "False"' + $lbJson += '},' + $lbJson += '{' + $lbJson += '"display_name": "vrops-tcp-app-profile",' + $lbJson += '"description": "vRealize Operations Manager TCP App Profile",' + $lbJson += '"resource_type": "LBFastTcpProfile",' + $lbJson += '"idle_timeout": "1800",' + $lbJson += '"ha_flow_mirroring_enabled": "False",' + $lbJson += '"close_timeout": "8"' + $lbJson += '},' + } + If ($vraDetailsObject) + { + $lbJson += '{' + $lbJson += '"display_name": "vra-tcp-app-profile",' + $lbJson += '"description": "vRealize Automation TCP App Profile",' + $lbJson += '"resource_type": "LBFastTcpProfile",' + $lbJson += '"idle_timeout": "1800",' + $lbJson += '"ha_flow_mirroring_enabled": "False",' + $lbJson += '"close_timeout": "8"' + $lbJson += '},' + $lbJson += '{' + $lbJson += '"display_name": "vra-http-app-profile-redirect",' + $lbJson += '"description": "vRealize Automation Profile to redirect HTTP to HTTPs",' + $lbJson += '"resource_type": "LBHttpProfile",' + $lbJson += '"idle_timeout": "1800",' + $lbJson += '"request_header_size": "1024",' + $lbJson += '"response_header_size": "4096",' + $lbJson += '"http_redirect_to_https": "True",' + $lbJson += '"response_timeout": "60",' + $lbJson += '"ntlm": "False"' + $lbJson += '},' + } + $lbJson += '{' + $lbJson += '"display_name": "wsa-http-app-profile",' + $lbJson += '"description": "Clustered Workspace ONE Access HTTP Redirect",' + $lbJson += '"resource_type": "LBHttpProfile",' + $lbJson += '"idle_timeout": "3600",' + $lbJson += '"x_forwarded_for": "INSERT",' + $lbJson += '"request_header_size": "1024",' + $lbJson += '"response_header_size": "4096",' + $lbJson += '"http_redirect_to_https": "False",' + $lbJson += '"response_timeout": "60",' + $lbJson += '"ntlm": "False"' + $lbJson += '},' + $lbJson += '{' + $lbJson += '"display_name": "wsa-http-app-profile-redirect",' + $lbJson += '"description": "Clustered Workspace ONE Access redirect HTTP to HTTPs",' + $lbJson += '"resource_type": "LBHttpProfile",' + $lbJson += '"idle_timeout": "3600",' + $lbJson += '"request_header_size": "1024",' + $lbJson += '"response_header_size": "4096",' + $lbJson += '"http_redirect_to_https": "True",' + $lbJson += '"response_timeout": "60",' + $lbJson += '"ntlm": "False"' + $lbJson += '}' + $lbJson += '],' + $lbJson += '"persistence_profiles": [' + If ($vropsDetailsObject) + { + $lbJson += '{' + $lbJson += '"display_name": "vrops-source-ip-persistence-profile",' + $lbJson += '"description": "vRealize Operations Manager Analytics Cluster Source IP Persistence Profile",' + $lbJson += '"resource_type": "LBSourceIpPersistenceProfile",' + $lbJson += '"persistence_shared": "False",' + $lbJson += '"purge": "FULL",' + $lbJson += '"ha_persistence_mirroring_enabled": "False"' + $lbJson += '},' + } + $lbJson += '{' + $lbJson += '"display_name": "wsa-cookie-persistence-profile",' + $lbJson += '"description": "Cookie Persistence Profile",' + $lbJson += '"resource_type": "LBCookiePersistenceProfile",' + $lbJson += '"persistence_shared": "False",' + $lbJson += '"cookie_mode": "REWRITE",' + $lbJson += '"cookie_name": "JSESSIONID",' + $lbJson += '"cookie_fallback": "True",' + $lbJson += '"cookie_garble": "True"' + $lbJson += '}' + $lbJson += '],' + $lbJson += '"pools": [' + If ($vropsDetailsObject) + { + $lbJson += '{' + $lbJson += '"display_name": "vrops-server-pool",' + $lbJson += '"description": "vRealize Operations Manager Analytics Cluster Server Pool",' + $lbJson += '"algorithm": "LEAST_CONNECTION",' + $lbJson += '"active_monitor_paths": [' + $lbJson += '"/infra/lb-monitor-profiles/vrops-https-monitor"' + $lbJson += '],' + $lbJson += '"snat_translation": {' + $lbJson += '"type": "LBSnatAutoMap"' + $lbJson += '},' + $lbJson += '"members": [' + $lbJson += '{' + $lbJson += '"display_name": "",' + $lbJson += '"backup_member": "false",' + $lbJson += '"weight": 1,' + $lbJson += '"admin_state": "ENABLED",' + $lbJson += '"ip_address": "",' + $lbJson += '"port": "443"' + $lbJson += '},' + $lbJson += '{' + $lbJson += '"display_name": "",' + $lbJson += '"backup_member": "false",' + $lbJson += '"weight": 1,' + $lbJson += '"admin_state": "ENABLED",' + $lbJson += '"ip_address": "",' + $lbJson += '"port": "443"' + $lbJson += '},' + $lbJson += '{' + $lbJson += '"display_name": "",' + $lbJson += '"backup_member": "false",' + $lbJson += '"weight": 1,' + $lbJson += '"admin_state": "ENABLED",' + $lbJson += '"ip_address": "",' + $lbJson += '"port": "443"' + $lbJson += '}' + $lbJson += ']' + $lbJson += '},' + } + If ($vraDetailsObject) + { + $lbJson += '{' + $lbJson += '"display_name": "vra-server-pool",' + $lbJson += '"description": "vRealize Automation Cluster Pool",' + $lbJson += '"algorithm": "LEAST_CONNECTION",' + $lbJson += '"active_monitor_paths": [' + $lbJson += '"/infra/lb-monitor-profiles/vra-http-monitor"' + $lbJson += '],' + $lbJson += '"snat_translation": {' + $lbJson += '"type": "LBSnatAutoMap"' + $lbJson += '},' + $lbJson += '"members": [' + $lbJson += '{' + $lbJson += '"display_name": "",' + $lbJson += '"backup_member": "false",' + $lbJson += '"weight": 1,' + $lbJson += '"admin_state": "ENABLED",' + $lbJson += '"ip_address": "",' + $lbJson += '"port": "443"' + $lbJson += '},' + $lbJson += '{' + $lbJson += '"display_name": "",' + $lbJson += '"backup_member": "false",' + $lbJson += '"weight": 1,' + $lbJson += '"admin_state": "ENABLED",' + $lbJson += '"ip_address": "",' + $lbJson += '"port": "443"' + $lbJson += '},' + $lbJson += '{' + $lbJson += '"display_name": "",' + $lbJson += '"backup_member": "false",' + $lbJson += '"weight": 1,' + $lbJson += '"admin_state": "ENABLED",' + $lbJson += '"ip_address": "",' + $lbJson += '"port": "443"' + $lbJson += '}' + $lbJson += ']' + $lbJson += '},' + } + $lbJson += '{' + $lbJson += '"display_name": "wsa-server-pool",' + $lbJson += '"description": "Clustered Workspace ONE Access Server Pool",' + $lbJson += '"algorithm": "LEAST_CONNECTION",' + $lbJson += '"active_monitor_paths": [' + $lbJson += '"/infra/lb-monitor-profiles/wsa-https-monitor"' + $lbJson += '],' + $lbJson += '"snat_translation": {' + $lbJson += '"type": "LBSnatAutoMap"' + $lbJson += '},' + $lbJson += '"members": [' + $lbJson += '{' + $lbJson += '"display_name": "",' + $lbJson += '"backup_member": "false",' + $lbJson += '"weight": 1,' + $lbJson += '"admin_state": "ENABLED",' + $lbJson += '"ip_address": "",' + $lbJson += '"port": "443"' + $lbJson += '},' + $lbJson += '{' + $lbJson += '"display_name": "",' + $lbJson += '"backup_member": "false",' + $lbJson += '"weight": 1,' + $lbJson += '"admin_state": "ENABLED",' + $lbJson += '"ip_address": "",' + $lbJson += '"port": "443"' + $lbJson += '},' + $lbJson += '{' + $lbJson += '"display_name": "",' + $lbJson += '"backup_member": "false",' + $lbJson += '"weight": 1,' + $lbJson += '"admin_state": "ENABLED",' + $lbJson += '"ip_address": "",' + $lbJson += '"port": "443"' + $lbJson += '}' + $lbJson += ']' + $lbJson += '}' + $lbJson += '],' + $lbJson += '"virtual_servers": [' + If ($vropsDetailsObject) + { + $lbJson += '{' + $lbJson += '"display_name": "vrops-https",' + $lbJson += '"description": "vRealize Operations Manager Analytics Cluster UI",' + $lbJson += '"resource_type": "LBVirtualServer",' + $lbJson += '"enabled": "true",' + $lbJson += '"lb_persistence_profile_path": "/infra/lb-persistence-profiles/vrops-source-ip-persistence-profile",' + $lbJson += '"application_profile_path": "/infra/lb-app-profiles/vrops-tcp-app-profile",' + $lbJson += '"pool_path": "/infra/lb-pools/vrops-server-pool",' + $lbJson += '"lb_service_path": "/infra/lb-services/",' + $lbJson += '"ip_address": "",' + $lbJson += '"ports": [' + $lbJson += '"443"' + $lbJson += ']' + $lbJson += '},' + $lbJson += '{' + $lbJson += '"display_name": "vrops-http-redirect",' + $lbJson += '"description": "vRealize Operations Manager Analytics Cluster HTTP to HTTPS Redirect",' + $lbJson += '"resource_type": "LBVirtualServer",' + $lbJson += '"enabled": "true",' + $lbJson += '"application_profile_path": "/infra/lb-app-profiles/vrops-http-app-profile-redirect",' + $lbJson += '"lb_service_path": "/infra/lb-services/",' + $lbJson += '"ip_address": "",' + $lbJson += '"ports": [' + $lbJson += '"80"' + $lbJson += ']' + $lbJson += '},' + } + If ($vraDetailsObject) + { + $lbJson += '{' + $lbJson += '"display_name": "vra-https",' + $lbJson += '"description": "vRealize Automation Cluster UI",' + $lbJson += '"resource_type": "LBVirtualServer",' + $lbJson += '"enabled": "true",' + $lbJson += '"application_profile_path": "/infra/lb-app-profiles/vra-tcp-app-profile",' + $lbJson += '"pool_path": "/infra/lb-pools/vra-server-pool",' + $lbJson += '"lb_service_path": "/infra/lb-services/",' + $lbJson += '"ip_address": "",' + $lbJson += '"ports": [' + $lbJson += '"443"' + $lbJson += ']' + $lbJson += '},' $lbJson += '{' - $lbJson += '"ip_address": "",' - $lbJson += '"admin_distance": 1,' - $lbJson += '"scope": [' - $lbJson += '"/infra/tier-1s//locale-services/default/interfaces/"' - $lbJson += '] ' - $lbJson += '}' - $lbJson += '],' - $lbJson += '"display_name": "default"' - $lbJson += '}' - $lbJson += '},' - $lbJson += '"lb_spec": {' - $lbJson += '"lb_service": [' + $lbJson += '"display_name": "vra-http-redirect",' + $lbJson += '"description": "vRealize Automation HTTP to HTTPS Redirect",' + $lbJson += '"resource_type": "LBVirtualServer",' + $lbJson += '"enabled": "true",' + $lbJson += '"application_profile_path": "/infra/lb-app-profiles/vra-http-app-profile-redirect",' + $lbJson += '"lb_service_path": "/infra/lb-services/",' + $lbJson += '"ip_address": "",' + $lbJson += '"ports": [' + $lbJson += '"80"' + $lbJson += ']' + $lbJson += '},' + } $lbJson += '{' - $lbJson += '"display_name": "",' - $lbJson += '"resource_type": "LBService",' - $lbJson += '"enabled": true,' - $lbJson += '"size": "SMALL",' - $lbJson += '"connectivity_path":""' - $lbJson += '}' - $lbJson += '],' - $lbJson += '"service_monitors": [' - If ($vropsDetailsObject) - { - $lbJson += '{' - $lbJson += '"display_name": "vrops-https-monitor",' - $lbJson += '"description": "vRealize Operations Manager HTTPS Monitor",' - $lbJson += '"resource_type": "LBHttpsMonitorProfile",' - $lbJson += '"monitor_port": "443",' - $lbJson += '"interval": "5",' - $lbJson += '"fall_count": "3",' - $lbJson += '"rise_count": "3",' - $lbJson += '"timeout": "16",' - $lbJson += '"request_method": "GET",' - $lbJson += '"request_url": "/suite-api/api/deployment/node/status?services=api&services=adminui&services=ui",' - $lbJson += '"request_version": "HTTP_VERSION_1_1",' - $lbJson += '"response_status_codes": [' - $lbJson += '"200","204","301"' - $lbJson += '],' - $lbJson += '"response_body": "ONLINE",' - $lbJson += '"server_ssl_profile_binding": {' - $lbJson += '"ssl_profile_path": "/infra/lb-server-ssl-profiles/default-balanced-server-ssl-profile"' - $lbJson += '}' + $lbJson += '"display_name": "wsa-https",' + $lbJson += '"description": "Clustered Workspace ONE Access Cluster UI",' + $lbJson += '"resource_type": "LBVirtualServer",' + $lbJson += '"enabled": "true",' + $lbJson += '"lb_persistence_profile_path": "/infra/lb-persistence-profiles/wsa-cookie-persistence-profile",' + $lbJson += '"application_profile_path": "/infra/lb-app-profiles/wsa-http-app-profile",' + $lbJson += '"pool_path": "/infra/lb-pools/wsa-server-pool",' + $lbJson += '"lb_service_path": "/infra/lb-services/",' + $lbJson += '"ip_address": "",' + $lbJson += '"ports": [' + $lbJson += '"443"' + $lbJson += '],' + $lbJson += '"client_ssl_profile_binding": {' + $lbJson += '"default_certificate_path": "/infra/certificates/",' + $lbJson += '"ssl_profile_path": "/infra/lb-client-ssl-profiles/default-balanced-client-ssl-profile"' + $lbJson += '},' + $lbJson += '"server_ssl_profile_binding": {' + $lbJson += '"client_certificate_path": "/infra/certificates/",' + $lbJson += '"ssl_profile_path": "/infra/lb-server-ssl-profiles/default-balanced-server-ssl-profile"' $lbJson += '},' + $lbJson += '"rules": [' + $lbJson += '{' + $lbJson += '"match_strategy": "ALL",' + $lbJson += '"phase": "HTTP_REQUEST_REWRITE",' + $lbJson += '"actions": [' + $lbJson += '{' + $lbJson += '"type": "LBHttpRequestHeaderRewriteAction",' + $lbJson += '"header_name": "Remoteport",' + $lbJson += '"header_value": "$_remote_port"' + $lbJson += '}' + $lbJson += ']' + $lbJson += '}' + $lbJson += ']' + $lbJson += '},' + $lbJson += '{' + $lbJson += '"display_name": "wsa-http-redirect",' + $lbJson += '"description": "Clustered Workspace ONE Access Cluster HTTP to HTTPS Redirect",' + $lbJson += '"resource_type": "LBVirtualServer",' + $lbJson += '"enabled": "true",' + $lbJson += '"application_profile_path": "/infra/lb-app-profiles/wsa-http-app-profile-redirect",' + $lbJson += '"lb_service_path": "/infra/lb-services/",' + $lbJson += '"ip_address": "",' + $lbJson += '"ports": [' + $lbJson += '"80"' + $lbJson += ']' + $lbJson += '}' + $lbJson += ']' + $lbJson += '}' + $lbJson += '}' + + $lbJson = $lbJson | ForEach-Object { $_ ` + -replace '', $t1Name ` + -replace '', $xintSegmentName ` + -replace '', $segmentID ` + -replace '', $siName ` + -replace '', $serviceInterfaceIp ` + -replace '', $xintionVXLAN ` + -replace '', $xintSegmentNextHopIP ` + -replace '', $xintSegmentServiceInterfacePrefixLength ` + -replace '', $lbName ` + -replace '', $wsaCertName ` + -replace '', $xintWsaNode1Name ` + -replace '', $xintWsaNode2Name ` + -replace '', $xintWsaNode3Name ` + -replace '', $xintWsaNode1IP ` + -replace '', $xintWsaNode2IP ` + -replace '', $xintWsaNode3IP ` + -replace '', $xintVropsNode1Name ` + -replace '', $xintVropsNode2Name ` + -replace '', $xintVropsNode3Name ` + -replace '', $xintVropsNode1Ip ` + -replace '', $xintVropsNode2Ip ` + -replace '', $xintVropsNode3Ip ` + -replace '', $xintVraNode1Name ` + -replace '', $xintVraNode2Name ` + -replace '', $xintVraNode3Name ` + -replace '', $xintVraNode1Ip ` + -replace '', $xintVraNode2Ip ` + -replace '', $xintVraNode3Ip ` + -replace '', $xintWsaVip ` + -replace '', $xintVropsVip ` + -replace '', $xintVraVip ` + } + $lbCustomObject = $lbJson | ConvertFrom-Json + Return $lbCustomObject +} +Export-ModuleMember -Function New-vRealizeLoadBalancerSpec + +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 +{ + <# + .NOTES + =========================================================================== + Created by: Gary Blake + Date: 03/08/2020 + Organization: VMware + =========================================================================== + + .SYNOPSIS + Gets NSX-T Edge Cluster Id + + .DESCRIPTION + The Get-NsxtEdgeCluster cmdlet gets the Edge Cluster Id + + .EXAMPLE + PS C:\> 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 +{ + <# + .NOTES + =========================================================================== + Created by: Gary Blake + Date: 03/08/2020 + Organization: VMware + =========================================================================== + + .SYNOPSIS + Creates a Tier 1 Gateway + + .DESCRIPTION + The New-NsxtTier1 cmdlet creates a Teir 1 Gateway + + .EXAMPLE + PS C:\> 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 + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function New-NsxtTier1 + +Function Set-NsxtTier1 +{ + <# + .NOTES + =========================================================================== + Created by: Gary Blake + Date: 03/08/2020 + Organization: VMware + =========================================================================== + + .SYNOPSIS + Configures Tier 1 Gateway + + .DESCRIPTION + The Set-NsxtTier1 cmdlet configures a Tier 1 Gateway + + .EXAMPLE + PS C:\> Set-NsxtTier1 -tier1Gateway -json + This example sets the configuration on a Tier 1 Gateway + #> + + Param ( + [Parameter (Mandatory=$true)] + [String]$tier1Gateway, + [Parameter (Mandatory=$true)] + [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 + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Set-NsxtTier1 + +Function New-NsxtTier1ServiceInterface +{ + <# + .NOTES + =========================================================================== + Created by: Gary Blake + Date: 03/08/2020 + Organization: VMware + =========================================================================== + + .SYNOPSIS + Creates Service Interface on Tier 1 Gateway + + .DESCRIPTION + The New-NsxtTier1ServiceInterface cmdlet configures a Service Interface on Tier 1 Gateway + + .EXAMPLE + PS C:\> New-NsxtTier1ServiceInterface -tier1Gateway -interfaceId -json + This example configures a Service Interface on a Tier 1 Gateway + #> + + Param ( + [Parameter (Mandatory=$true)] + [String]$tier1Gateway, + [Parameter (Mandatory=$true)] + [String]$interfaceId, + [Parameter (Mandatory=$true)] + [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 + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function New-NsxtTier1ServiceInterface + +Function New-NsxtTier1StaticRoute +{ + <# + .NOTES + =========================================================================== + Created by: Gary Blake + Date: 03/08/2020 + Organization: VMware + =========================================================================== + + .SYNOPSIS + Creates Static Route on Tier 1 Gateway + + .DESCRIPTION + The New-New-NsxtTier1StaticRoute cmdlet creates a static route on Tier 1 Gateway + + .EXAMPLE + PS C:\> New-NsxtTier1StaticRoute -tier1Gateway -segment -json + This example configures a Service Interface on a Tier 1 Gateway + #> + Param ( + [Parameter (Mandatory=$true)] + [String]$tier1Gateway, + [Parameter (Mandatory=$true)] + [String]$segment, + [Parameter (Mandatory=$true)] + [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 + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function New-NsxtTier1StaticRoute + +Function New-NsxtLoadBalancer +{ + <# + .NOTES + =========================================================================== + Created by: Gary Blake + Date: 03/08/2020 + Organization: VMware + =========================================================================== + + .SYNOPSIS + Creates a Load Balancer + + .DESCRIPTION + The New-NsxtLoadBalancer cmdlet creates a load balancer + + .EXAMPLE + PS C:\> New-NsxtLoadBalancer -lbName -json + This example creates a load balancer + #> + Param ( + [Parameter (Mandatory=$true)] + [String]$lbName, + [Parameter (Mandatory=$true)] + [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 + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function New-NsxtLoadBalancer + +Function New-NsxtLBServiceMonitor +{ + <# + .NOTES + =========================================================================== + Created by: Gary Blake + Date: 03/08/2020 + Organization: VMware + =========================================================================== + + .SYNOPSIS + Creates a Load Balancer Service Monitor + + .DESCRIPTION + The New-NsxtLBServiceMonitor cmdlet creates a Load Balancer Service Monitor + + .EXAMPLE + PS C:\> New-NsxtLBServiceMonitor -monitorName -json + This example creates a Load Balancer Serviec Monitor + #> + Param ( + [Parameter (Mandatory=$true)] + [String]$monitorName, + [Parameter (Mandatory=$true)] + [String]$json + ) + + 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 + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function New-NsxtLBServiceMonitor + +Function New-NsxtLBAppProfile +{ + <# + .NOTES + =========================================================================== + Created by: Gary Blake + Date: 03/08/2020 + Organization: VMware + =========================================================================== + + .SYNOPSIS + Creates a Load Balancer Application Profile + + .DESCRIPTION + The New-NsxtLBAppProfile cmdlet creates a Load Balancer Application Profile + + .EXAMPLE + PS C:\> New-NsxtLBAppProfile -appProfileName -json + This example creates a Load Balancer Application Profile + #> + Param ( + [Parameter (Mandatory=$true)] + [String]$appProfileName, + [Parameter (Mandatory=$true)] + [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 + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function New-NsxtLBAppProfile + +Function New-NsxtLBPersistenceAppProfile +{ + <# + .NOTES + =========================================================================== + Created by: Gary Blake + Date: 03/08/2020 + Organization: VMware + =========================================================================== + + .SYNOPSIS + Creates a Load Balancer Persistence Application Profile + + .DESCRIPTION + The New-NsxtLBPersistenceAppProfile cmdlet creates a Load Balancer Persistence Application Profile + + .EXAMPLE + PS C:\> New-NsxtLBPersistenceAppProfile -appProfileName -json + This example creates a Load Balancer Persistence Application Profile + #> + Param ( + [Parameter (Mandatory=$true)] + [String]$appProfileName, + [Parameter (Mandatory=$true)] + [String]$json + ) + + 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 + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function New-NsxtLBPersistenceAppProfile + +Function New-NsxtLBPool +{ + <# + .NOTES + =========================================================================== + Created by: Gary Blake + Date: 03/08/2020 + Organization: VMware + =========================================================================== + + .SYNOPSIS + Creates a Load Balancer Pool + + .DESCRIPTION + The New-NsxtLBPool cmdlet creates a Load Balancer Pool + + .EXAMPLE + PS C:\> New-NsxtLBPool -poolName -json + This example creates a Load Balancer Pool + #> + Param ( + [Parameter (Mandatory=$true)] + [String]$poolName, + [Parameter (Mandatory=$true)] + [String]$json + ) + + 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 + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function New-NsxtLBPool + +Function New-NsxtLBVirtualServer +{ + <# + .NOTES + =========================================================================== + Created by: Gary Blake + Date: 03/08/2020 + Organization: VMware + =========================================================================== + + .SYNOPSIS + Creates a Load Balancer Virtual Server + + .DESCRIPTION + The New-NsxtLBVirtualServer cmdlet creates a Load Balancer Virtual Server + + .EXAMPLE + PS C:\> New-NsxtLBVirtualServer -virtualServerName -json + This example creates a Load Balancer Virtual Server + #> + Param ( + [Parameter (Mandatory=$true)] + [String]$virtualServerName, + [Parameter (Mandatory=$true)] + [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 + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function New-NsxtLBVirtualServer + +Function Get-NsxtCertificate +{ + <# + .NOTES + =========================================================================== + Created by: Gary Blake + Date: 03/08/2020 + Organization: VMware + =========================================================================== + + .SYNOPSIS + Gets NSX-T Certificates + + .DESCRIPTION + The Get-NsxtCertificates cmdlet gets certificates installed in NSX-T + + .EXAMPLE + PS C:\> Get-NsxtCertificates + This example gets the certificates installed in NSX-T + #> + + 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 + } + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Get-NsxtCertificate + +Function Set-NsxtCertificate +{ + <# + .NOTES + =========================================================================== + Created by: Gary Blake + Date: 03/08/2020 + Organization: VMware + =========================================================================== + + .SYNOPSIS + Installs a Certificate in NSX-T + + .DESCRIPTION + The Set-NsxtCertificates cmdlet installs certificates in NSX-T + + .EXAMPLE + PS C:\> Set-NsxtCertificates + This example installs the certificates in NSX-T + #> + + Param ( + [Parameter (Mandatory=$true)] + [ValidateNotNullOrEmpty()] + [string]$certificateName, + [Parameter (Mandatory=$true)] + [String]$json + ) + + Try { + $uri = "https://$nsxtmanager/policy/api/v1/infra/certificates/$($certificateName)" + $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -headers $nsxtHeaders -body $json + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Set-NsxtCertificate + +################## End NSX-T Functions ####################### +############################################################### + + +############################################################### +############ Begin vSphere with Tanzu Functions ############## + +Function Request-vSphereApiToken { + <# + .SYNOPSIS + Request an authentication token for the vSphere REST API + + .DESCRIPTION + The Request-vSphereApiToken cmdlet requests an authentication token for the vSphere REST API + + use -admin to set the Admin token for vCenter Server Management Interface + .EXAMPLE + Request-vSphereApiToken -Fqdn sfo-w01-vc01.sfo.rainpole.io -Username administrator@vsphere.local -Password VMw@re1! + This example requests a vSphere REST API authentication token for user administrator@vsphere.local from vCenter Server sfo-w01-vc01.sfo.rainpole.io + + .EXAMPLE + Get-vCenterServerDetail -Server sfo-vcf01.sfo.rainpole.io -User administrator@vsphere.local -Pass VMw@re1! -Domain sfo-w01 | Request-vSphereApiToken + This example requests a vSphere REST API authentication token for user administrator@vsphere.local from the vCenter Server that manages VI workload domain sfo-w01 + #> + + Param ( + [Parameter (Mandatory = $false)] [String]$Fqdn, + [Parameter (Mandatory = $false)] [String]$Username, + [Parameter (Mandatory = $false)] [String]$Password, + [Parameter (ValueFromPipeline, Mandatory = $false)] [psobject]$inputObject, + [Parameter (Mandatory = $false)] [switch]$admin + ) + + if ($inputObject) { + $username = $inputObject.ssoAdmin + $password = $inputObject.ssoAdminPass + $fqdn = $inputObject.fqdn + $sddcManager = (Get-VCFManager).fqdn + } + else { + if (!$PsBoundParameters.ContainsKey("username") -or (!$PsBoundParameters.ContainsKey("password"))) { + # Request Credentials + $creds = Get-Credential + $username = $creds.UserName.ToString() + $password = $creds.GetNetworkCredential().password + } + if (!$PsBoundParameters.ContainsKey("fqdn")) { + $fqdn = Read-Host "vCenter Server FQDN not found. Please enter a value, e.g., sfo-m01-vc01.sfo.rainpole.io" + } + } + $vcAuthHeaders = createvCenterAuthHeader($username, $password) + + # Perform the vCenter REST API call to authenticate and retrieve the session token + Try { + if ($admin){ + $tmp = $fqdn + $fqdn = $fqdn + ":5480" + $vcAdminSession = (Invoke-WebRequest -Method POST -URI https://$fqdn/rest/com/vmware/cis/session -Headers $vcAuthHeaders | ConvertFrom-Json).Value + $fqdn = $tmp + } + $vcSession = (Invoke-WebRequest -Method POST -URI https://$fqdn/rest/com/vmware/cis/session -Headers $vcAuthHeaders | ConvertFrom-Json).Value + } + Catch { + Write-Error -Message "Something went wrong with vCenter Server authentication." + } + + # Use the session token to build the header used from here on + $Global:vcHeaders = @{"vmware-api-session-id" = $vcSession } + $vcHeaders.Add("Content-Type", "application/json") + + # Use the session token to build the header for admin interface used from here on + if ($admin){ + $Global:vcAdminHeaders = @{"vmware-api-session-id" = $vcAdminSession } + $vcAdminHeaders.Add("Content-Type", "application/json") + } + + # Validate credentials by executing an API call + $Global:currentvCenterServer = $fqdn + + $newUri = "https://$fqdn/api/appliance/system/version" + $oldUri = "https://$fqdn/rest/appliance/system/version" + + Try { + # Checking against the vCenter API + # PS Core has -SkipCertificateCheck implemented, PowerShell 5.x does not + if ($PSEdition -eq 'Core') { + Try { + $response = Invoke-RestMethod -Method GET -Uri $newUri -Headers $vcHeaders -SkipCertificateCheck + if ($response) { + $responseSplit = $response.version.Split(".") + $global:vCenterApi = $responseSplit[0..2] -join "" } - If ($vraDetailsObject) - { - $lbJson += '{' - $lbJson += '"display_name": "vra-http-monitor",' - $lbJson += '"description": "vRealize Automation HTTP Monitor",' - $lbJson += '"resource_type": "LBHttpMonitorProfile",' - $lbJson += '"monitor_port": "8008",' - $lbJson += '"interval": "3",' - $lbJson += '"fall_count": "3",' - $lbJson += '"rise_count": "3",' - $lbJson += '"timeout": "10",' - $lbJson += '"request_method": "GET",' - $lbJson += '"request_url": "/health",' - $lbJson += '"request_version": "HTTP_VERSION_1_1",' - $lbJson += '"response_status_codes": [' - $lbJson += '"200"' - $lbJson += '],' - $lbJson += '"response_body": ""' - $lbJson += '},' + } + Catch { + $errorStatus = $_.Exception.Response.StatusCode + } + if ($errorStatus -eq "NotFound") { + $response = Invoke-RestMethod -Method GET -Uri $oldUri -Headers $vcHeaders -SkipCertificateCheck + $responseSplit = $response.value.version.Split(".") + $global:vCenterApi = $responseSplit[0..2] -join "" + } + } + else { + Try { + $response = Invoke-RestMethod -Method GET -Uri $newUri -Headers $vcHeaders + + if ($response) { + $responseSplit = $response.version.Split(".") + $global:vCenterApi = $responseSplit[0..2] -join "" } - $lbJson += '{' - $lbJson += '"display_name": "wsa-https-monitor",' - $lbJson += '"description": "Clustered Workspace ONE Access HTTPS Monitor",' - $lbJson += '"resource_type": "LBHttpsMonitorProfile",' - $lbJson += '"monitor_port": "443",' - $lbJson += '"interval": "3",' - $lbJson += '"fall_count": "3",' - $lbJson += '"rise_count": "3",' - $lbJson += '"timeout": "10",' - $lbJson += '"request_method": "GET",' - $lbJson += '"request_url": "/SAAS/API/1.0/REST/system/health/heartbeat",' - $lbJson += '"request_version": "HTTP_VERSION_1_1",' - $lbJson += '"response_status_codes": [' - $lbJson += '"200","201"' - $lbJson += '],' - $lbJson += '"response_body": "ok",' - $lbJson += '"server_ssl_profile_binding": {' - $lbJson += '"client_certificate_path": "/infra/certificates/",' - $lbJson += '"ssl_profile_path": "/infra/lb-server-ssl-profiles/default-balanced-server-ssl-profile"' - $lbJson += '}' - $lbJson += '}' - $lbJson += '],' - $lbJson += '"app_profiles": [' - If ($vropsDetailsObject) - { - $lbJson += '{' - $lbJson += '"display_name": "vrops-http-app-profile-redirect",' - $lbJson += '"description": "Cross-Instance vRealize Operations Manager redirect HTTP to HTTPs",' - $lbJson += '"resource_type": "LBHttpProfile",' - $lbJson += '"idle_timeout": "1800",' - $lbJson += '"request_header_size": "1024",' - $lbJson += '"response_header_size": "4096",' - $lbJson += '"http_redirect_to_https": "True",' - $lbJson += '"response_timeout": "60",' - $lbJson += '"ntlm": "False"' - $lbJson += '},' - $lbJson += '{' - $lbJson += '"display_name": "vrops-tcp-app-profile",' - $lbJson += '"description": "vRealize Operations Manager TCP App Profile",' - $lbJson += '"resource_type": "LBFastTcpProfile",' - $lbJson += '"idle_timeout": "1800",' - $lbJson += '"ha_flow_mirroring_enabled": "False",' - $lbJson += '"close_timeout": "8"' - $lbJson += '},' } - If ($vraDetailsObject) - { - $lbJson += '{' - $lbJson += '"display_name": "vra-tcp-app-profile",' - $lbJson += '"description": "vRealize Automation TCP App Profile",' - $lbJson += '"resource_type": "LBFastTcpProfile",' - $lbJson += '"idle_timeout": "1800",' - $lbJson += '"ha_flow_mirroring_enabled": "False",' - $lbJson += '"close_timeout": "8"' - $lbJson += '},' - $lbJson += '{' - $lbJson += '"display_name": "vra-http-app-profile-redirect",' - $lbJson += '"description": "vRealize Automation Profile to redirect HTTP to HTTPs",' - $lbJson += '"resource_type": "LBHttpProfile",' - $lbJson += '"idle_timeout": "1800",' - $lbJson += '"request_header_size": "1024",' - $lbJson += '"response_header_size": "4096",' - $lbJson += '"http_redirect_to_https": "True",' - $lbJson += '"response_timeout": "60",' - $lbJson += '"ntlm": "False"' - $lbJson += '},' + Catch { + $errorStatus = $_.Exception.Response.StatusCode } - $lbJson += '{' - $lbJson += '"display_name": "wsa-http-app-profile",' - $lbJson += '"description": "Clustered Workspace ONE Access HTTP Redirect",' - $lbJson += '"resource_type": "LBHttpProfile",' - $lbJson += '"idle_timeout": "3600",' - $lbJson += '"x_forwarded_for": "INSERT",' - $lbJson += '"request_header_size": "1024",' - $lbJson += '"response_header_size": "4096",' - $lbJson += '"http_redirect_to_https": "False",' - $lbJson += '"response_timeout": "60",' - $lbJson += '"ntlm": "False"' - $lbJson += '},' - $lbJson += '{' - $lbJson += '"display_name": "wsa-http-app-profile-redirect",' - $lbJson += '"description": "Clustered Workspace ONE Access redirect HTTP to HTTPs",' - $lbJson += '"resource_type": "LBHttpProfile",' - $lbJson += '"idle_timeout": "3600",' - $lbJson += '"request_header_size": "1024",' - $lbJson += '"response_header_size": "4096",' - $lbJson += '"http_redirect_to_https": "True",' - $lbJson += '"response_timeout": "60",' - $lbJson += '"ntlm": "False"' - $lbJson += '}' - $lbJson += '],' - $lbJson += '"persistence_profiles": [' - If ($vropsDetailsObject) - { - $lbJson += '{' - $lbJson += '"display_name": "vrops-source-ip-persistence-profile",' - $lbJson += '"description": "vRealize Operations Manager Analytics Cluster Source IP Persistence Profile",' - $lbJson += '"resource_type": "LBSourceIpPersistenceProfile",' - $lbJson += '"persistence_shared": "False",' - $lbJson += '"purge": "FULL",' - $lbJson += '"ha_persistence_mirroring_enabled": "False"' - $lbJson += '},' + + if ($errorStatus -eq "NotFound") { + $response = Invoke-RestMethod -Method GET -Uri $oldUri -Headers $vcHeaders + $responseSplit = $response.value.version.Split(".") + $global:vCenterApi = $responseSplit[0..2] -join "" + } + } + if ($response) { + if ($inputObject) { + Write-Output "Successfully Requested New API Token for vCenter Server $fqdn via SDDC Manager $sddcManager" + } + else { + Write-Output "Successfully Requested New API Token for vCenter Server $fqdn" + } + } + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Request-vSphereApiToken + +Function Enable-WMRegistry { + <# + .SYNOPSIS + Enable the embedded Harbor Registry on a Supervisor Cluster + + .DESCRIPTION + The Enable-WMRegistry cmdlet enables the embedded Harbor Registry on a Supervisor Cluster + + .EXAMPLE + Enable-WMRegistry -Cluster "sfo-w01-cl01" -StoragePolicy "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 = $false)] [String]$Domain, + [Parameter (Mandatory = $false)] [String]$Cluster, + [Parameter (Mandatory = $false)] [String]$StoragePolicy, + [Parameter (ValueFromPipeline, Mandatory = $false)] [psObject]$inputObject + ) + + $vCenterFqdn = $currentvCenterServer + + if ($inputObject) { + $Cluster = $inputObject.Name + } + + Try { + if ($vCenterApi -le 701) { + $getHarborInstalled = (Invoke-RestMethod -Method GET -URI https://$vCenterFqdn/rest/vcenter/content/registries/harbor -Headers $vcHeaders).value + } + elseif ($vCenterApi -ge 702) { + $getHarborInstalled = Invoke-RestMethod -Method GET -URI https://$vCenterFqdn/api/vcenter/content/registries/harbor -Headers $vcHeaders + } + } + Catch { + Write-Error = $_.Exception + } + + if (!$getHarborInstalled) { + Try { + $wmClusterId = (Invoke-RestMethod -Method GET -URI https://$vCenterFqdn/api/vcenter/namespace-management/clusters -Headers $vcHeaders | Where-Object { $_.cluster_name -eq $Cluster }).cluster + } + Catch { + Write-Error $_.Exception.Message + } + + if (!$StoragePolicy) { + Try { + $storagePolicyId = (Invoke-RestMethod -Method GET -URI https://$vCenterFqdn/api/vcenter/namespace-management/clusters/$wmClusterId -Headers $vcHeaders).image_storage.storage_policy + } + Catch { + Write-Error $_.Exception.Message } - $lbJson += '{' - $lbJson += '"display_name": "wsa-cookie-persistence-profile",' - $lbJson += '"description": "Cookie Persistence Profile",' - $lbJson += '"resource_type": "LBCookiePersistenceProfile",' - $lbJson += '"persistence_shared": "False",' - $lbJson += '"cookie_mode": "REWRITE",' - $lbJson += '"cookie_name": "JSESSIONID",' - $lbJson += '"cookie_fallback": "True",' - $lbJson += '"cookie_garble": "True"' - $lbJson += '}' - $lbJson += '],' - $lbJson += '"pools": [' - If ($vropsDetailsObject) + } + elseif ($StoragePolicy) { + Try { + if ($vCenterApi -ge 702) { + $storagePolicyId = ((Invoke-WebRequest -Method GET -URI https://$vCenterFqdn/api/vcenter/storage/policies -Headers $vcHeaders | 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://$vCenterFqdn/rest/vcenter/storage/policies -Headers $vcHeaders | ConvertFrom-Json).value | Where-Object { $_.name -eq $StoragePolicy }).policy + $json = @" +{ + "spec" : + { + "cluster" : "$wmClusterId", + "storage" : + [ { - $lbJson += '{' - $lbJson += '"display_name": "vrops-server-pool",' - $lbJson += '"description": "vRealize Operations Manager Analytics Cluster Server Pool",' - $lbJson += '"algorithm": "LEAST_CONNECTION",' - $lbJson += '"active_monitor_paths": [' - $lbJson += '"/infra/lb-monitor-profiles/vrops-https-monitor"' - $lbJson += '],' - $lbJson += '"snat_translation": {' - $lbJson += '"type": "LBSnatAutoMap"' - $lbJson += '},' - $lbJson += '"members": [' - $lbJson += '{' - $lbJson += '"display_name": "",' - $lbJson += '"backup_member": "false",' - $lbJson += '"weight": 1,' - $lbJson += '"admin_state": "ENABLED",' - $lbJson += '"ip_address": "",' - $lbJson += '"port": "443"' - $lbJson += '},' - $lbJson += '{' - $lbJson += '"display_name": "",' - $lbJson += '"backup_member": "false",' - $lbJson += '"weight": 1,' - $lbJson += '"admin_state": "ENABLED",' - $lbJson += '"ip_address": "",' - $lbJson += '"port": "443"' - $lbJson += '},' - $lbJson += '{' - $lbJson += '"display_name": "",' - $lbJson += '"backup_member": "false",' - $lbJson += '"weight": 1,' - $lbJson += '"admin_state": "ENABLED",' - $lbJson += '"ip_address": "",' - $lbJson += '"port": "443"' - $lbJson += '}' - $lbJson += ']' - $lbJson += '},' + "policy" : "$storagePolicyId" } - If ($vraDetailsObject) - { - $lbJson += '{' - $lbJson += '"display_name": "vra-server-pool",' - $lbJson += '"description": "vRealize Automation Cluster Pool",' - $lbJson += '"algorithm": "LEAST_CONNECTION",' - $lbJson += '"active_monitor_paths": [' - $lbJson += '"/infra/lb-monitor-profiles/vra-http-monitor"' - $lbJson += '],' - $lbJson += '"snat_translation": {' - $lbJson += '"type": "LBSnatAutoMap"' - $lbJson += '},' - $lbJson += '"members": [' - $lbJson += '{' - $lbJson += '"display_name": "",' - $lbJson += '"backup_member": "false",' - $lbJson += '"weight": 1,' - $lbJson += '"admin_state": "ENABLED",' - $lbJson += '"ip_address": "",' - $lbJson += '"port": "443"' - $lbJson += '},' - $lbJson += '{' - $lbJson += '"display_name": "",' - $lbJson += '"backup_member": "false",' - $lbJson += '"weight": 1,' - $lbJson += '"admin_state": "ENABLED",' - $lbJson += '"ip_address": "",' - $lbJson += '"port": "443"' - $lbJson += '},' - $lbJson += '{' - $lbJson += '"display_name": "",' - $lbJson += '"backup_member": "false",' - $lbJson += '"weight": 1,' - $lbJson += '"admin_state": "ENABLED",' - $lbJson += '"ip_address": "",' - $lbJson += '"port": "443"' - $lbJson += '}' - $lbJson += ']' - $lbJson += '},' + ] + } +} +"@ + } } - $lbJson += '{' - $lbJson += '"display_name": "wsa-server-pool",' - $lbJson += '"description": "Clustered Workspace ONE Access Server Pool",' - $lbJson += '"algorithm": "LEAST_CONNECTION",' - $lbJson += '"active_monitor_paths": [' - $lbJson += '"/infra/lb-monitor-profiles/wsa-https-monitor"' - $lbJson += '],' - $lbJson += '"snat_translation": {' - $lbJson += '"type": "LBSnatAutoMap"' - $lbJson += '},' - $lbJson += '"members": [' - $lbJson += '{' - $lbJson += '"display_name": "",' - $lbJson += '"backup_member": "false",' - $lbJson += '"weight": 1,' - $lbJson += '"admin_state": "ENABLED",' - $lbJson += '"ip_address": "",' - $lbJson += '"port": "443"' - $lbJson += '},' - $lbJson += '{' - $lbJson += '"display_name": "",' - $lbJson += '"backup_member": "false",' - $lbJson += '"weight": 1,' - $lbJson += '"admin_state": "ENABLED",' - $lbJson += '"ip_address": "",' - $lbJson += '"port": "443"' - $lbJson += '},' - $lbJson += '{' - $lbJson += '"display_name": "",' - $lbJson += '"backup_member": "false",' - $lbJson += '"weight": 1,' - $lbJson += '"admin_state": "ENABLED",' - $lbJson += '"ip_address": "",' - $lbJson += '"port": "443"' - $lbJson += '}' - $lbJson += ']' - $lbJson += '}' - $lbJson += '],' - $lbJson += '"virtual_servers": [' - If ($vropsDetailsObject) - { - $lbJson += '{' - $lbJson += '"display_name": "vrops-https",' - $lbJson += '"description": "vRealize Operations Manager Analytics Cluster UI",' - $lbJson += '"resource_type": "LBVirtualServer",' - $lbJson += '"enabled": "true",' - $lbJson += '"lb_persistence_profile_path": "/infra/lb-persistence-profiles/vrops-source-ip-persistence-profile",' - $lbJson += '"application_profile_path": "/infra/lb-app-profiles/vrops-tcp-app-profile",' - $lbJson += '"pool_path": "/infra/lb-pools/vrops-server-pool",' - $lbJson += '"lb_service_path": "/infra/lb-services/",' - $lbJson += '"ip_address": "",' - $lbJson += '"ports": [' - $lbJson += '"443"' - $lbJson += ']' - $lbJson += '},' - $lbJson += '{' - $lbJson += '"display_name": "vrops-http-redirect",' - $lbJson += '"description": "vRealize Operations Manager Analytics Cluster HTTP to HTTPS Redirect",' - $lbJson += '"resource_type": "LBVirtualServer",' - $lbJson += '"enabled": "true",' - $lbJson += '"application_profile_path": "/infra/lb-app-profiles/vrops-http-app-profile-redirect",' - $lbJson += '"lb_service_path": "/infra/lb-services/",' - $lbJson += '"ip_address": "",' - $lbJson += '"ports": [' - $lbJson += '"80"' - $lbJson += ']' - $lbJson += '},' + 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://$vCenterFqdn/rest/vcenter/content/registries/harbor -Headers $vcHeaders -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://$vCenterFqdn/api/vcenter/content/registries/harbor -Headers $vcHeaders -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 + Retrieves the embedded Harbor Registry on a Supervisor Cluster + + .DESCRIPTION + The Get-WMRegistry cmdlet retrieves the embedded Harbor Registry on a Supervisor Cluster + + .EXAMPLE + 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 = $false)] [String]$Cluster, + [Parameter (ValueFromPipeline, Mandatory = $false)] [psObject]$inputObject + ) + + $vCenterFqdn = $currentvCenterServer + + if ($inputObject) { + $Cluster = $inputObject.Name + } + + if ($Cluster) { + Try { + $wmClusterId = (Invoke-RestMethod -Method GET -URI https://$vCenterFqdn/api/vcenter/namespace-management/clusters -Headers $vcHeaders | 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://$vCenterFqdn/rest/vcenter/content/registries/harbor -ContentType application/json -headers $vcHeaders + $response.value + } + elseif ($vCenterApi -ge 702) { + $response = Invoke-RestMethod -Method GET -URI https://$vCenterFqdn/api/vcenter/content/registries/harbor -ContentType application/json -headers $vcHeaders + $response + } + } + elseif ($PsBoundParameters.ContainsKey("Cluster")) { + if ($vCenterApi -le 701) { + $response = Invoke-RestMethod -Method GET -URI https://$vCenterFqdn/rest/vcenter/content/registries/harbor -ContentType application/json -headers $vcHeaders + $response.value | Where-Object { $_.cluster -eq $wmClusterId } + } + elseif ($vCenterApi -ge 702) { + $response = Invoke-RestMethod -Method GET -URI https://$vCenterFqdn/api/vcenter/content/registries/harbor -ContentType application/json -headers $vcHeaders + $response | Where-Object { $_.cluster -eq $wmClusterId } + } + } + } + Catch { + Write-Error = $_.Exception + } +} +Export-ModuleMember -Function Get-WMRegistry + +Function Remove-WMRegistry { + <# + .SYNOPSIS + Remove the embedded Harbor Registry on a Supervisor Cluster + + .DESCRIPTION + The Remove-wmRegistry cmdlet removes the embedded Harbor Registry on a Supervisor Cluster + + .EXAMPLE + Get-WMRegistry -Cluster "sfo-w01-cl01" | Remove-WMRegistry + This example enables the embedded Harbor Registry on Supervisor Cluster "sfo-w01-cl01" via pipeline from Get-wmCluster with the default storage policy for the Supervisor Cluster + + .EXAMPLE + Remove-WMRegistry -Cluster "sfo-w01-cl01" + This example enables the embedded Harbor Registry on Supervisor Cluster "sfo-w01-cl01" via pipeline from Get-wmCluster with the default storage policy for the Supervisor Cluster + #> + + Param ( + [Parameter (Mandatory = $false)] [String]$Cluster, + [Parameter (ValueFromPipeline, Mandatory = $false)] [psObject]$inputObject + ) + + $vCenterFqdn = $currentvCenterServer + + if ($inputObject) { + $harborRegistryId = $inputObject.registry + } + else { + Try { + $harborRegistryId = (Get-WMRegistry -Cluster $Cluster).registry + } + Catch { + Write-Error $_.Exception.Message + } + } + + if ($vCenterApi -le 701) { + $uri = "https://$vCenterFqdn/rest/vcenter/content/registries/harbor/$harborRegistryId" + } + elseif ($vCenterApi -ge 702) { + $uri = "https://$vCenterFqdn/api/vcenter/content/registries/harbor/$harborRegistryId" + } + + Try { + $response = Invoke-WebRequest -Method DELETE -URI $uri -ContentType application/json -headers $vcHeaders + if ($response.StatusCode -eq 200 -or $response.StatusCode -eq 204) { + Write-Output "Embedded registry removal successfully started for Supervisor Cluster $Cluster" + } + } + Catch { + Write-Error = $_.Exception + } +} +Export-ModuleMember -Function Remove-WMRegistry + +Function Connect-WMCluster { + <# + .SYNOPSIS + Log in to a Supervisor Cluster + + .DESCRIPTION + The Connect-WMCluster cmdlet adds a refix List to an NSX-T Route Map + + .EXAMPLE + Connect-WMCluster -Cluster sfo-w01-cl01 -User administrator@vsphere.local -Pass VMw@re1! + This example logs the vSphere SSO user administrator@vsphere.local into Supervisor Cluster sfo-w01-cl01 + #> + + Param ( + [Parameter (Mandatory = $false)] [String]$Cluster, + [Parameter (Mandatory = $true)] [String]$User, + [Parameter (Mandatory = $true)] [String]$Pass, + [Parameter (ValueFromPipeline, Mandatory = $false)] [psObject]$inputObject + ) + + if ($inputObject) { + $Server = $inputObject.KubernetesHostname + } + else { + $Server = (Get-WMCluster -Cluster $Cluster).KubernetesHostname + } + + Try { + Start-AwaitSession | Out-Null + Send-AwaitCommand "kubectl vsphere login --server $Server --vsphere-username $Username --insecure-skip-tls-verify" | Out-Null + Wait-AwaitResponse "Password:" | Out-Null + Send-AwaitCommand "$Password" + Stop-AwaitSession + Start-Sleep -seconds 3 | Out-Null + } + Catch { + Write-Error "Something went wrong." + } + + $tryKubectl = Invoke-Expression "kubectl get nodes" + + if ($tryKubectl) { + Write-Output "Connection successful." + } +} +Export-ModuleMember -Function Connect-WMCluster + +Function Disconnect-WMCluster { + <# + .SYNOPSIS + Add a Prefix List to an NSX-T Route Map + + .DESCRIPTION + The Add-NsxtPrefixList cmdlet adds a refix List to an NSX-T Route Map + + .EXAMPLE + Get-NsxtPrefixList -Name sfo-w01-cl01-prefix-list | Add-NsxtPrefixList -RouteMap sfo-w01-ec01-route-map -Action PERMIT + This example creates a new Prefix List on a Tier 0 Gateway + #> + + Try { + Invoke-Expression "kubectl vsphere logout" + } + Catch { + Debug-ExceptionWriter -object $_ + } +} +Export-ModuleMember -Function Disconnect-WMCluster + +Function New-TanzuKubernetesCluster { + <# + .SYNOPSIS + Adds a Tanzu Kubernetes cluster based on the specified YAML file. + + .DESCRIPTION + The New-WMTkgsCluster cmdlet adds a Tanzu Kubernetes cluster based on the specified YAML file. + + .EXAMPLE + New-WMTkgsCluster -YAML c:\kube\yaml\tkgsCluster.yaml + This example creates a new Prefix List on a Tier 0 Gateway + #> + + Param ( + [Parameter (Mandatory = $true)] [String]$YAML + ) + + Try { + Invoke-Expression "kubectl apply -f $YAML" + } + Catch { + Debug-ExceptionWriter -object $_ + } +} +New-Alias -name Set-TanzuKubernetesCluster -Value Mew-TanzuKubernetesCluster +Export-ModuleMember -Alias Set-TanzuKubernetesCluster -Function New-TanzuKubernetesCluster + +Function Get-TanzuKubernetesCluster { + <# + .SYNOPSIS + Retrieves a Tanzu Kubernetes cluster + + .DESCRIPTION + The Get-TanzuKuberntesCluster cmdlet retrieves a Tanzu Kubernetes cluster + + .EXAMPLE + Get-TanzuKubernetesCluster + This example retrieves all TanzuKubernetesCluster objects from all namespaces + + .EXAMPLE + Get-TanzuKubernetesCluster -Name sfo-w01-tkc01 -Namespace sfo-w01-tkc01 + This example retrieves a TanzuKubernetesCluster object named "sfo-w01-tkc01" from the namespace specified "sfo-w01-tkc01" + #> + + Param ( + [Parameter (Mandatory = $false)] [String]$Name, + [Parameter (Mandatory = $false)] [String]$Namespace, + [Parameter (Mandatory = $false)] [Bool]$Detailed + ) + + if ($Detailed -eq $true) { + if (!$Name -and !$Namespace) { + Invoke-Expression "kubectl describe tkc --all-namespaces" + } + elseif (!$Name -and $Namespace) { + Invoke-Expression "kubectl describe tkc -n $Namespace" + } + elseif ($Name -and !$Namespace) { + Write-Error "A resource cannot be retrieved by name across all namespaces" + } + elseif ($Name -and $Namespace) { + Invoke-Expression "kubectl describe tkc $Name -n $Namespace" + } + } + elseif (!$Detailed -or $Detailed -eq $false) { + if (!$Name -and !$Namespace) { + Invoke-Expression "kubectl get tkc --all-namespaces" + } + elseif (!$Name -and $Namespace) { + Invoke-Expression "kubectl get tkc -n $Namespace" + } + elseif ($Name -and !$Namespace) { + Write-Error "A resource cannot be retrieved by name across all namespaces" + } + elseif ($Name -and $Namespace) { + Invoke-Expression "kubectl get tkc $Name -n $Namespace" + } + } +} +Export-ModuleMember -Function Get-TanzuKubernetesCluster + +Function Remove-TanzuKubernetesCluster { + <# + .SYNOPSIS + Adds a Tanzu Kubernetes cluster based on the specified YAML file. + + .DESCRIPTION + The New-WMTkgsCluster cmdlet adds a Tanzu Kubernetes cluster based on the specified YAML file. + + .EXAMPLE + New-WMTkgsCluster -YAML c:\kube\yaml\tkgsCluster.yaml + This example creates a new Prefix List on a Tier 0 Gateway + #> + + Param ( + [Parameter (Mandatory = $true)] [String]$Name, + [Parameter (Mandatory = $true)] [String]$Namespace + ) + + Try { + Invoke-Expression "kubectl delete tkc $Name -n $Namespace" + } + Catch { + Write-Error "Something went wrong." + } +} +Export-ModuleMember -Function Remove-TanzuKubernetesCluster + +############# End vSphere with Tanzu Functions ############### +############################################################### + + +######################################################################################## +################## Start vRealize Suite Lifecycle Manager Functions ################### + +Function Request-vRSLCMToken { + <# + .SYNOPSIS + Connects to the specified vRealize Suite Lifecycle Manager and obtains authorization token + + .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. + + .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 + #> + + Param ( + [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 { + # 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 # PS Core has -SkipCertificateCheck implemented, PowerShell 5.x does not + } + else { + $vrslcmResponse = Invoke-WebRequest -Method GET -Uri $uri -Headers $vrslcmHeaders + } + 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 Request-vRSLCMToken + +Function Get-vRSLCMHealth { + <# + .SYNOPSIS + Check vRealize Suite Lifecycle Manager Health Status + + .DESCRIPTION + The Get-vRSLCMHealth cmdlet checks vRealize Suite Lifecycle Manager Health Status + + .EXAMPLE + Get-vRSLCMHealth + This example checks vRealize Suite Lifecycle Manager Health Status + #> + + Try { + $uri = "https://$vrslcmAppliance/lcm/health/api/v2/status" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders + $response + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Get-vRSLCMHealth + +Function Get-vRSLCMLockerPassword { + <# + .SYNOPSIS + Get paginated list of Passwords available in the Store + + .DESCRIPTION + 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 + #> + + Param ( + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vmid + ) + + Try { + if ($PsBoundParameters.ContainsKey("vmid")) { + $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/passwords/$vmid" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders + $response + } + else { + $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/passwords" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders + $response.passwords + } + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Get-vRSLCMLockerPassword + +Function Add-vRSLCMLockerPassword { + <# + .SYNOPSIS + Creates a new Password in a Locker + + .DESCRIPTION + The Add-vRSLCMLockerPassword cmdlet add as new passwords to the Locker + + .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 + #> + + 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 +'" + }' + } + + $response = Invoke-RestMethod $uri -Method 'POST' -Headers $vrslcmHeaders -Body $body + $response + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Add-vRSLCMLockerPassword + +Function Remove-vRSLCMLockerPassword { + <# + .SYNOPSIS + Delete a Password based on vmid + + .DESCRIPTION + The Remove-vRSLCMLockerPassword cmdlet deletes a password from the Locker + + .EXAMPLE + Remove-vRSLCMLockerPassword -vmid + This example delets the password with the vmid + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vmid + ) + + Try { + $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-vRSLCMLockerPassword + +Function Get-vRSLCMLockerCertificate { + <# + .SYNOPSIS + Get paginated list of Certificates available in the Store + + .DESCRIPTION + The Get-vRSLCMLockerCertificate cmdlet gets a paginated list of certificates available in the Locker + + .EXAMPLE + Get-vRSLCMLockerCertificate + This example gets all certificates in the Locker + + .EXAMPLE + Get-vRSLCMLockerCertificate -vmid 83abd0fd-c92d-4d8f-a5e8-9a1fc4fa6009 + This example gets the details of a certificate based on the vmid + + .EXAMPLE + Get-vRSLCMLockerCertificate -alias xint-vrops01 + This example gets the details of a certificate based on the vmid + #> + + Param ( + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vmid, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$alias + ) + + Try { + 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("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://$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-vRSLCMLockerCertificate + +Function Add-vRSLCMLockerCertificate { + <# + .SYNOPSIS + Add a certificate to the vRSLCM locker + + .DESCRIPTION + The Add-vRSLCMLockerCertificate cmdlet adds a certificate to the vRSLCM locker + + .EXAMPLE + 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 = $true)] [ValidateNotNullOrEmpty()] [String]$vrslcmFQDN, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$certificateAlias, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$certificatePassphrase, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$certChainPath + ) + + 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 { + $body = '{ + "alias": "'+$certificateAlias+'", + "certificateChain": "'+$chain+'", + "certificatePassphrase": "'+$certificatePassphrase+'", + "privateKey": "'+$key+'" + }' + } + + $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-vRSLCMLockerCertificate + +Function Remove-vRSLCMLockerCertificate { + <# + .SYNOPSIS + Delete a certificate based on vmid + + .DESCRIPTION + The Remove-vRSLCMLockerCertificate cmdlet deletes a certificate from the Locker + + .EXAMPLE + Remove-vRSLCMLockerCertificate -vmid + This example delets the certificate with the vmid + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vmid + ) + + Try { + $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 Remove-vRSLCMLockerCertificate + +Function Get-vRSLCMLockerLicense { + <# + .SYNOPSIS + Get paginated list of License available in the Store + + .DESCRIPTION + The Get-vRSLCMLockerPassword cmdlet gets a paginated list of license available in the Locker + + .EXAMPLE + 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 = $false)] [ValidateNotNullOrEmpty()] [String]$vmid, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$alias + ) + + 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 + $response + } + else { + $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/licenses" + $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders + $response + } + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Get-vRSLCMLockerLicense + +Function Add-vRSLCMLockerLicense { + <# + .SYNOPSIS + Creates a new License in a Locker + + .DESCRIPTION + The Add-vRSLCMLockerLicense cmdlet adds as new license to the Locker + + .EXAMPLE + 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]$alias, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$license + ) + + 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 + $response + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Add-vRSLCMLockerLicense + +Function Remove-vRSLCMLockerLicense { + <# + .SYNOPSIS + Delete a License based on vmid + + .DESCRIPTION + The Remove-vRSLCMLockerLicense cmdlet deletes a license from the Locker + + .EXAMPLE + Remove-vRSLCMLockerLicense -vmid + This example delets the license with the vmid + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vmid + ) + + Try { + $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 Remove-vRSLCMLockerLicense + +Function Get-vRSLCMDatacenter { + <# + .SYNOPSIS + Get paginated list of datacenters in vRealize Suite Lifecycle Manager + + .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 + + .EXAMPLE + 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]$datacenterName + ) + + 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 + } + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Get-vRSLCMDatacenter + +Function Add-vRSLCMDatacenter { + <# + .SYNOPSIS + Add a datacenter in vRealize Suite Lifecycle Manager + + .DESCRIPTION + The Add-vRSLCMDatacenter cmdlet adds a datacenter in vRealize Suite Lifecycle Manager + + .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 + #> + + Param ( + [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-vRSLCMDatacenter + +Function Remove-vRSLCMDatacenter { + <# + .SYNOPSIS + Remove a datacenter from vRealize Suite Lifecycle Manager + + .DESCRIPTION + The Remove-vRSLCMDatacenter cmdlet removes a datacenter from vRealize Suite Lifecycle Manager + + .EXAMPLE + Remove-vRSLCMDatacenter -datacenterVmid + This example removes a datacenter from vRealize Suite Lifecycle Manager + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$datacenterVmid + ) + + 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 + + .DESCRIPTION + The Get-vRSLCMDatacenterVcenter cmdlet gets a paginated list of vCenter Servers in vRealize Suite Lifecycle Manager + + .EXAMPLE + Get-vRSLCMDatacenterVcenter -datacenterVmid + This example gets all vCenter Servers for a Datacenter + + .EXAMPLE + Get-vRSLCMDatacenterVcenter -datacenterVmid -vcenterName sfo-m01-vc01 + This example gets a named vCenter Server for a datacenter + + .EXAMPLE + 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 = $true)] [ValidateNotNullOrEmpty()] [String]$datacenterVmid, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vcenterName, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$environments + ) + + 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 + } + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Get-vRSLCMDatacenterVcenter + +Function Add-vRSLCMDatacenterVcenter { + <# + .SYNOPSIS + Add a vCenter Server to a Datacenter in vRealize Suite Lifecycle Manager + + .DESCRIPTION + The Add-vRSLCMDatacenterVcenter cmdlet adds a vCenter Servers to a Datacenter in vRealize Suite Lifecycle Manager + + .EXAMPLE + Add-vRSLCMDatacenterVcenter -datacenterVmid + This example adds a vCenter Server to a Datacenter + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$datacenterVmid, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vcenterFqdn, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$userLockerAlias + ) + + Try { + $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/datacenters/$datacenterVmid/vcenters" + $body = '{ + "vCenterHost": "' + $vcenterFqdn + '", + "vCenterName": "' + ($vcenterFqdn.Split("."))[0] + '", + "vcPassword": "locker:password:' + (Get-vRSLCMLockerPassword | Where-Object {$_.alias -eq $userLockerAlias}).vmid + ':' + $userLockerAlias + '", + "vcUsedAs": "MANAGEMENT", + "vcUsername": "' + (Get-vRSLCMLockerPassword | Where-Object {$_.alias -eq $userLockerAlias}).userName +'" + }' + $response = Invoke-RestMethod $uri -Method 'POST' -Headers $vrslcmHeaders -Body $body + $response + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Add-vRSLCMDatacenterVcenter + +Function Get-vRSLCMEnvironment { + <# + .SYNOPSIS + Get paginated list of environments in vRealize Suite Lifecycle Manager + + .DESCRIPTION + The Get-vRSLCMEnvironment cmdlet gets a paginated list of environments in vRealize Suite Lifecycle Manager + + .EXAMPLE + Get-vRSLCMEnvironment + This example gets all environments in vRealize Suite Lifecycle Manager + #> + + Param ( + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vmid + ) + + Try { + 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 Get-vRSLCMEnvironment + +Function Add-vRSLCMEnvironment { + <# + .SYNOPSIS + Create an environment in 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 + + .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 + #> + + Param ( + [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("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 + } + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Add-vRSLCMEnvironment + +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 Request + + .DESCRIPTION + The Remove-vRSLCMRequest cmdlet removes a request from vRealize Suite Lifecycle Manager + + .EXAMPLE + Remove-vRSLCMRequest -requestId + This example removes a request from vRealize Suite Lifecycle Manager + #> + + Param ( + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$requestId ) + + Try { + + $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-vRSLCMRequest + +Function Watch-vRSLCMRequest { + <# + .SYNOPSIS + Poll request + + .DESCRIPTION + The Watch-vRSLCMRequest cmdlet polls a request in vRealize Suite Lifecycle Manager + + .EXAMPLE + Watch-vRSLCMRequest -vmid + This example polls the request 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" + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Watch-vRSLCMRequest + +Function Resume-vRSLCMRequest { + <# + .SYNOPSIS + Retry a request + + .DESCRIPTION + The Resume-vRSLCMRequest cmdlet reties a request + + .EXAMPLE + 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]$requestId + ) + + Try { + $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 Resume-vRSLCMRequest + +Function Export-WsaJsonSpec { + <# + .SYNOPSIS + Create Clustered Workspace ONE Access JSON specification + + .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 + + .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 + #> + + 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 } - If ($vraDetailsObject) - { - $lbJson += '{' - $lbJson += '"display_name": "vra-https",' - $lbJson += '"description": "vRealize Automation Cluster UI",' - $lbJson += '"resource_type": "LBVirtualServer",' - $lbJson += '"enabled": "true",' - $lbJson += '"application_profile_path": "/infra/lb-app-profiles/vra-tcp-app-profile",' - $lbJson += '"pool_path": "/infra/lb-pools/vra-server-pool",' - $lbJson += '"lb_service_path": "/infra/lb-services/",' - $lbJson += '"ip_address": "",' - $lbJson += '"ports": [' - $lbJson += '"443"' - $lbJson += ']' - $lbJson += '},' - $lbJson += '{' - $lbJson += '"display_name": "vra-http-redirect",' - $lbJson += '"description": "vRealize Automation HTTP to HTTPS Redirect",' - $lbJson += '"resource_type": "LBVirtualServer",' - $lbJson += '"enabled": "true",' - $lbJson += '"application_profile_path": "/infra/lb-app-profiles/vra-http-app-profile-redirect",' - $lbJson += '"lb_service_path": "/infra/lb-services/",' - $lbJson += '"ip_address": "",' - $lbJson += '"ports": [' - $lbJson += '"80"' - $lbJson += ']' - $lbJson += '},' + } + + $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 | Where-Object {$_.alias -eq $pnpWorkbook.Workbook.Names["global_env_admin_password_alias"].Value}) { + if ($configAdminPassword = Get-vRSLCMLockerPassword | Where-Object {$_.alias -eq $pnpWorkbook.Workbook.Names["local_configadmin_password_alias"].Value}) { + if ($wsaPassword = Get-vRSLCMLockerPassword | Where-Object {$_.alias -eq $pnpWorkbook.Workbook.Names["local_admin_password_alias"].Value}) { + $vcCredentials = Get-vRSLCMLockerPassword | Where-Object {$_.alias -eq (($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 + } + + $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) + } + + #### 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"} + $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 + } + + $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" + } + } + } + } } - $lbJson += '{' - $lbJson += '"display_name": "wsa-https",' - $lbJson += '"description": "Clustered Workspace ONE Access Cluster UI",' - $lbJson += '"resource_type": "LBVirtualServer",' - $lbJson += '"enabled": "true",' - $lbJson += '"lb_persistence_profile_path": "/infra/lb-persistence-profiles/wsa-cookie-persistence-profile",' - $lbJson += '"application_profile_path": "/infra/lb-app-profiles/wsa-http-app-profile",' - $lbJson += '"pool_path": "/infra/lb-pools/wsa-server-pool",' - $lbJson += '"lb_service_path": "/infra/lb-services/",' - $lbJson += '"ip_address": "",' - $lbJson += '"ports": [' - $lbJson += '"443"' - $lbJson += '],' - $lbJson += '"client_ssl_profile_binding": {' - $lbJson += '"default_certificate_path": "/infra/certificates/",' - $lbJson += '"ssl_profile_path": "/infra/lb-client-ssl-profiles/default-balanced-client-ssl-profile"' - $lbJson += '},' - $lbJson += '"server_ssl_profile_binding": {' - $lbJson += '"client_certificate_path": "/infra/certificates/",' - $lbJson += '"ssl_profile_path": "/infra/lb-server-ssl-profiles/default-balanced-server-ssl-profile"' - $lbJson += '},' - $lbJson += '"rules": [' - $lbJson += '{' - $lbJson += '"match_strategy": "ALL",' - $lbJson += '"phase": "HTTP_REQUEST_REWRITE",' - $lbJson += '"actions": [' - $lbJson += '{' - $lbJson += '"type": "LBHttpRequestHeaderRewriteAction",' - $lbJson += '"header_name": "Remoteport",' - $lbJson += '"header_value": "$_remote_port"' - $lbJson += '}' - $lbJson += ']' - $lbJson += '}' - $lbJson += ']' - $lbJson += '},' - $lbJson += '{' - $lbJson += '"display_name": "wsa-http-redirect",' - $lbJson += '"description": "Clustered Workspace ONE Access Cluster HTTP to HTTPS Redirect",' - $lbJson += '"resource_type": "LBVirtualServer",' - $lbJson += '"enabled": "true",' - $lbJson += '"application_profile_path": "/infra/lb-app-profiles/wsa-http-app-profile-redirect",' - $lbJson += '"lb_service_path": "/infra/lb-services/",' - $lbJson += '"ip_address": "",' - $lbJson += '"ports": [' - $lbJson += '"80"' - $lbJson += ']' - $lbJson += '}' - $lbJson += ']' - $lbJson += '}' - $lbJson += '}' + } + Close-ExcelPackage $pnpWorkbook -NoSave -ErrorAction SilentlyContinue + } + Catch { + Debug-ExceptionWriter -object $_ + } +} +Export-ModuleMember -Function Export-WsaJsonSpec - $lbJson = $lbJson | ForEach-Object { $_ ` - -replace '', $t1Name ` - -replace '', $xintSegmentName ` - -replace '', $segmentID ` - -replace '', $siName ` - -replace '', $serviceInterfaceIp ` - -replace '', $xintionVXLAN ` - -replace '', $xintSegmentNextHopIP ` - -replace '', $xintSegmentServiceInterfacePrefixLength ` - -replace '', $lbName ` - -replace '', $wsaCertName ` - -replace '', $xintWsaNode1Name ` - -replace '', $xintWsaNode2Name ` - -replace '', $xintWsaNode3Name ` - -replace '', $xintWsaNode1IP ` - -replace '', $xintWsaNode2IP ` - -replace '', $xintWsaNode3IP ` - -replace '', $xintVropsNode1Name ` - -replace '', $xintVropsNode2Name ` - -replace '', $xintVropsNode3Name ` - -replace '', $xintVropsNode1Ip ` - -replace '', $xintVropsNode2Ip ` - -replace '', $xintVropsNode3Ip ` - -replace '', $xintVraNode1Name ` - -replace '', $xintVraNode2Name ` - -replace '', $xintVraNode3Name ` - -replace '', $xintVraNode1Ip ` - -replace '', $xintVraNode2Ip ` - -replace '', $xintVraNode3Ip ` - -replace '', $xintWsaVip ` - -replace '', $xintVropsVip ` - -replace '', $xintVraVip ` +Function New-WSADeployment { + <# + .SYNOPSIS + Deploy Clustered Workspace ONE Access to vRealize Suite Lifecycle Manager + + .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 + + .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 + #> + + 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 + ) + + 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 { + 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 | Where-Object {$_.alias -Match $($jsonSpec.products.properties.vidmAdminPassword.Split(":")[3])}) { + if (Get-vRSLCMLockerPassword | Where-Object {$_.alias -Match $($jsonSpec.products.properties.defaultConfigurationPassword.Split(":")[3])}) { + if (Get-vRSLCMLockerCertificate | Where-Object {$_.alias -Match $($jsonSpec.products.properties.certificate.Split(":")[3])}) { + + #if ($jsonSpec.environmentId) { + # $newRequest = Add-vRSLCMEnvironment -json $json -environmentId $jsonSpec.environmentId -addProduct + #} + #else { + $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 { + Debug-ExceptionWriter -object $_ } - $lbCustomObject = $lbJson | ConvertFrom-Json - Return $lbCustomObject } -Export-ModuleMember -Function New-vRealizeLoadBalancerSpec +Export-ModuleMember -Function New-WSADeployment + +################### End vRealize Suite Lifecycle Manager Functions #################### +######################################################################################## + + +######################################################################################### +######################### Start vRealize Automation Functions ######################### + +Function Request-vRAToken { + <# + .SYNOPSIS + Connects to the specified vRealize Automation and obtains authorization token + + .DESCRIPTION + The Request-vRAToken cmdlet connects to the specified vRealize Automation and obtains an authorization token. + It is required once per session before running all other cmdlets. + + .EXAMPLE + Request-vRAToken -fqdn xreg-vra01.rainpole.io -username configadmin -password VMware1! + This example shows how to connect to the vRealize Automation appliance + + .EXAMPLE + Request-vRAToken -fqdn xreg-vra01.rainpole.io -username configadmin -password VMware1! -displayToken + This example shows how to connect to the vRealize Automation appliance and display the token needed for Terraform + #> -Function Get-NsxtGlobalSegmentID -{ Param ( - [Parameter (Mandatory=$true)] - [String]$segmentName + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$fqdn, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$username, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$password, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$tenant, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$displayToken ) + if ( -not $PsBoundParameters.ContainsKey("username") -or ( -not $PsBoundParameters.ContainsKey("password"))) { + $creds = Get-Credential # Request Credentials + $username = $creds.UserName.ToString() + $password = $creds.GetNetworkCredential().password + } + + $vraBasicHeaders = createBasicAuthHeader $username $password + $Global:vraAppliance = $fqdn + Try { - $uri = "https://$nsxtmanager/policy/api/v1/global-infra/segments/" + # Validate credentials by executing an API call + $uri = "https://$vraAppliance/csp/gateway/am/api/login?access_token" + if ($PsBoundParameters.ContainsKey("tenant")) { + $body = "{ ""username"":""$username"",""password"":""$password"",""domain"":""$tenant""}" + } + else { + $body = "{ ""username"":""$username"",""password"":""$password""}" + } - $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders - $segmentObjectId = ($response.results | where-object {$_.display_name -eq $segmentName}).id + if ($PSEdition -eq 'Core') { + $vraResponse = Invoke-WebRequest -Method POST -Uri $uri -Headers $vraBasicHeaders -Body $body -SkipCertificateCheck # PS Core has -SkipCertificateCheck implemented, PowerShell 5.x does not + } + else { + $vraResponse = Invoke-WebRequest -Method POST -Uri $uri -Headers $vraBasicHeaders -Body $body + } + + if ($vraResponse.StatusCode -eq 200) { + $Global:vraHeaders = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" + $vraHeaders.Add("Accept", "application/json") + $vraHeaders.Add("Content-Type", "application/json") + $vraHeaders.Add("Authorization", "Bearer " + $vraResponse.Headers.'Csp-Auth-Token') + Write-Output "Successfully connected to vRealize Automation: $vraAppliance" + if ($PsBoundParameters.ContainsKey("displayToken")) { + Write-Output "`n---------Refresh Token---------" + ((Select-String -InputObject $vraResponse -Pattern '"refresh_token":') -Split ('"'))[3] + Write-Output "-------------------------------`n" + } + } } Catch { Write-Error $_.Exception.Message } - Return $segmentObjectId } -Export-ModuleMember -Function Get-NsxtGlobalSegmentID +Export-ModuleMember -Function Request-vRAToken -Function Add-CertToNsxCertificateStore -{ - Param ( - [Parameter (Mandatory = $true)] [String]$certName - ) +Function Get-vRAOrganizationId { + <# + .SYNOPSIS + Get the organization ID for the logged in user + + .DESCRIPTION + The Get-vRAOrganizationId cmdlet gets the organization Id for the logged in user + + .EXAMPLE + Get-vRAOrganizationId + This example gets organization Id for the logged in user + #> Try { - $pemFile = Get-ExternalFileName -title "Select the Certificate Chain PEM File for Clustered WSA (.pem)" -fileType "pem" -location "default" + $uri = "https://$vraAppliance/csp/gateway/am/api/loggedin/user/orgs" + $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vraHeaders + $response.refLinks } Catch { Write-Error $_.Exception.Message } +} +Export-ModuleMember -Function Get-vRAOrganizationId + +Function Get-vRAOrganizationDisplayName { + <# + .SYNOPSIS + Get the organization display name + + .DESCRIPTION + The Get-vRAOrganizationDisplayName cmdlet gets the organization display name + + .EXAMPLE + Get-vRAOrganizationDisplayName -orgId + This example gets organization display name for the organization Id provided + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId + ) + Try { - $keyFile = Get-ExternalFileName -title "Select the Key File for Clustered WSA (.key)" -fileType "key" -location "default" + $uri = "https://$vraAppliance/csp/gateway/am/api/orgs/$orgId" + $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vraHeaders + $response } Catch { Write-Error $_.Exception.Message } - - $certAlreadyImported = "" - - #check for existing certificate +} +Export-ModuleMember -Function Get-vRAOrganizationDisplayName + +Function Set-vRAOrganizationDisplayName { + <# + .SYNOPSIS + Configures the organization display name + + .DESCRIPTION + The Set-vRAOrganizationDisplayName cmdlet sets the organization display name + + .EXAMPLE + Set-vRAOrganizationDisplayName -orgId -displayName + This example configures the organization display name for the organization Id provided + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$displayName + ) + Try { - $certAlreadyImported = Get-NsxtCertificate -certificateName $certName -ErrorAction SilentlyContinue + $uri = "https://$vraAppliance/csp/gateway/am/api/orgs/$orgId" + $json = '{ "displayName": "'+ $displayName +'" }' + $response = Invoke-RestMethod -Method 'PATCH' -Uri $uri -Headers $vraHeaders -Body $json + $response.refLink } 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 $_ - } + Write-Error $_.Exception.Message } - Return $wsaCertPresent } -Export-ModuleMember -Function Add-CertToNsxCertificateStore +Export-ModuleMember -Function Set-vRAOrganizationDisplayName -Function Get-NsxtEdgeCluster -{ +Function Get-vRACloudAccount { <# - .NOTES - =========================================================================== - Created by: Gary Blake - Date: 03/08/2020 - Organization: VMware - =========================================================================== - .SYNOPSIS - Gets NSX-T Edge Cluster Id - + Get cloud accounts + .DESCRIPTION - The Get-NsxtEdgeCluster cmdlet gets the Edge Cluster Id - + The Get-vRACloudAccount cmdlet all cloud accounts within the current organization + .EXAMPLE - PS C:\> Get-NsxtEdgeCluster - This example creates a new Route Map on a Tier 0 Gateway + Get-vRACloudAccount + This example gets all cloud accounts within the current organization + + .EXAMPLE + Get-vRACloudAccount -type vsphere + This example gets all vsphere cloud accounts within the current organization, supports vsphere, vmw, gcp, nsx-v, nsx-t, aws and azure #> + Param ( + [Parameter (Mandatory = $false)] [ValidateSet("vsphere","vmc","gcp","nsx-v","nsx-t","aws","azure")] [ValidateNotNullOrEmpty()] [String]$type + ) + 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("type")) { + if ($type -eq "vsphere") {$uri = "https://$vraAppliance/iaas/api/cloud-accounts-vsphere"} + if ($type -eq "vmc") {$uri = "https://$vraAppliance/iaas/api/cloud-accounts-vmc"} + if ($type -eq "gcp") {$uri = "https://$vraAppliance/iaas/api/cloud-accounts-gcp"} + if ($type -eq "nsx-v") {$uri = "https://$vraAppliance/iaas/api/cloud-accounts-nsx-v"} + if ($type -eq "nsx-t") {$uri = "https://$vraAppliance/iaas/api/cloud-accounts-nsx-t"} + if ($type -eq "aws") {$uri = "https://$vraAppliance/iaas/api/cloud-accounts-aws"} + if ($type -eq "azure") {$uri = "https://$vraAppliance/iaas/api/cloud-accounts-azure"} + $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vraHeaders + $response.content + } + else { + $uri = "https://$vraAppliance/iaas/api/cloud-accounts" + $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vraHeaders + $response.content + } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-NsxtEdgeCluster +Export-ModuleMember -Function Get-vRACloudAccount -Function New-NsxtTier1 -{ +Function Add-vRACloudAccount { + <# + .SYNOPSIS + Add a cloud account + + .DESCRIPTION + The Add-vRACloudAccount cmdlet adds a cloud accounts within the current organization + + .EXAMPLE + Add-vRACloudAccount -type vsphere -json (Get-Content -raw .\vsphereCloudAccount.json) + This example adds a vsphere cloud account within the current organization + + .EXAMPLE + Add-vRACloudAccount -type nsx-t -json (Get-Content -raw .\nsxtCloudAccount.json) + This example adds a nsx-t cloud account within the current organization + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateSet("vsphere","vmc","gcp","nsx-v","nsx-t","aws","azure")] [ValidateNotNullOrEmpty()] [String]$type, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$json + ) + + Try { + if ($type -eq "vsphere") {$uri = "https://$vraAppliance/iaas/api/cloud-accounts-vsphere"} + if ($type -eq "vmc") {$uri = "https://$vraAppliance/iaas/api/cloud-accounts-vmc"} + if ($type -eq "gcp") {$uri = "https://$vraAppliance/iaas/api/cloud-accounts-gcp"} + if ($type -eq "nsx-v") {$uri = "https://$vraAppliance/iaas/api/cloud-accounts-nsx-v"} + if ($type -eq "nsx-t") {$uri = "https://$vraAppliance/iaas/api/cloud-accounts-nsx-t"} + if ($type -eq "aws") {$uri = "https://$vraAppliance/iaas/api/cloud-accounts-aws"} + if ($type -eq "azure") {$uri = "https://$vraAppliance/iaas/api/cloud-accounts-azure"} + $response = Invoke-RestMethod -Method 'POST' -Uri $uri -Headers $vraHeaders -Body $json + $response + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Add-vRACloudAccount + +Function Remove-vRACloudAccount { <# - .NOTES - =========================================================================== - Created by: Gary Blake - Date: 03/08/2020 - Organization: VMware - =========================================================================== - .SYNOPSIS - Creates a Tier 1 Gateway - + Remove a cloud account + .DESCRIPTION - The New-NsxtTier1 cmdlet creates a Teir 1 Gateway - + The Remove-vRACloudAccount cmdlet removes a cloud account within the current organization + .EXAMPLE - PS C:\> New-NsxtTier1 -tier1Gateway sfo-w01-ec01-t0-lb01 -json $ConfigJson - This example creates a new Tier 1 Gateway + Remove-vRACloudAccount -id + This example removes the cloud account with the ID within the current organization #> Param ( - [Parameter (Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [string]$tier1Gateway, - [Parameter (Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [string]$json + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id ) 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 + $uri = "https://$vraAppliance/iaas/api/cloud-accounts/$id" + $response = Invoke-RestMethod -Method 'DELETE' -Uri $uri -Headers $vraHeaders + $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function New-NsxtTier1 +Export-ModuleMember -Function Remove-vRACloudAccount -Function Set-NsxtTier1 -{ - <# - .NOTES - =========================================================================== - Created by: Gary Blake - Date: 03/08/2020 - Organization: VMware - =========================================================================== - +Function Get-vRANotification { + <# .SYNOPSIS - Configures Tier 1 Gateway - + Get notification configuration + .DESCRIPTION - The Set-NsxtTier1 cmdlet configures a Tier 1 Gateway - + The Get-vRANotification cmdlet gets the notification configuation from vRealize Automation + .EXAMPLE - PS C:\> Set-NsxtTier1 -tier1Gateway -json - This example sets the configuration on a Tier 1 Gateway + Get-vRANotification + This example gets the current notification configuration from vRealize Automation #> - Param ( - [Parameter (Mandatory=$true)] - [String]$tier1Gateway, - [Parameter (Mandatory=$true)] - [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 + $uri = "https://$vraAppliance/notification/api/email-config" + $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vraHeaders + $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Set-NsxtTier1 +Export-ModuleMember -Function Get-vRANotification -Function New-NsxtTier1ServiceInterface -{ - <# - .NOTES - =========================================================================== - Created by: Gary Blake - Date: 03/08/2020 - Organization: VMware - =========================================================================== - +Function New-vRANotification { + <# .SYNOPSIS - Creates Service Interface on Tier 1 Gateway - + Add notification configuration + .DESCRIPTION - The New-NsxtTier1ServiceInterface cmdlet configures a Service Interface on Tier 1 Gateway - + The New-vRANotification cmdlet adds the notification configuation in vRealize Automation + .EXAMPLE - PS C:\> New-NsxtTier1ServiceInterface -tier1Gateway -interfaceId -json - This example configures a Service Interface on a Tier 1 Gateway + New-vRANotification -name smtp.rainpole.io -serverName smtp.rainpole.io -emailAddress vra-no-reply@rainpole.io -sender administrator -trustCert true -connection NONE -authentication false + This example adds the notification configuration in vRealize Automation without authentication + + .EXAMPLE + New-vRANotification -name smtp.rainpole.io -serverName smtp.rainpole.io -emailAddress vra-no-reply@rainpole.io -sender administrator -trustCert true -connection NONE -authentication true -username administrator -password VMw@re1! + This example adds the notification configuration in vRealize Automation with authentication #> Param ( - [Parameter (Mandatory=$true)] - [String]$tier1Gateway, - [Parameter (Mandatory=$true)] - [String]$interfaceId, - [Parameter (Mandatory=$true)] - [String]$json + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$name, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$serverName, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$emailAddress, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sender, + [Parameter (Mandatory = $true)] [ValidateSet("true","false")] [ValidateNotNullOrEmpty()] [String]$trustCert, + [Parameter (Mandatory = $true)] [ValidateSet("SSL","STARTTLS","NONE")] [ValidateNotNullOrEmpty()] [String]$connection, + [Parameter (Mandatory = $true)] [ValidateSet("true","false")] [ValidateNotNullOrEmpty()] [String]$authentication, + [Parameter (ParameterSetName = "auth", Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$userName, + [Parameter (ParameterSetName = "auth", Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$password + ) 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 + if ($connection -eq "SSL") {$port = "465"} elseif ($connection -eq "STARTTLS") {$port = "587"} else {$port = "25"} + $uri = "https://$vraAppliance/notification/api/email-config" + $body = '{ + "name": "' + $name + '", + "host": "' + $serverName + '", + "port": ' + $port +', + "sender": "' + $emailAddress + '", + "senderName": "' + $sender + '", + "connectionSecurity": "' + $connection + '", + "authenticationRequired": ' + $authentication + ', + "userName": "' + $userName +'", + "password": "' + $password +'", + "trustHost": ' + $trustCert + ' + }' + $response = Invoke-RestMethod -Method 'POST' -Uri $uri -Headers $vraHeaders -Body $body + $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function New-NsxtTier1ServiceInterface +Export-ModuleMember -Function New-vRANotification -Function New-NsxtTier1StaticRoute -{ +Function Remove-vRANotification { <# - .NOTES - =========================================================================== - Created by: Gary Blake - Date: 03/08/2020 - Organization: VMware - =========================================================================== - .SYNOPSIS - Creates Static Route on Tier 1 Gateway - + Remove notification configuration + .DESCRIPTION - The New-New-NsxtTier1StaticRoute cmdlet creates a static route on Tier 1 Gateway - + The Remove-vRANotification cmdlet removes the notification configuation from vRealize Automation + .EXAMPLE - PS C:\> New-NsxtTier1StaticRoute -tier1Gateway -segment -json - This example configures a Service Interface on a Tier 1 Gateway + Remove-vRANotification + This example removes the current notification configuration from vRealize Automation #> - Param ( - [Parameter (Mandatory=$true)] - [String]$tier1Gateway, - [Parameter (Mandatory=$true)] - [String]$segment, - [Parameter (Mandatory=$true)] - [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 + $uri = "https://$vraAppliance/notification/api/email-config" + $response = Invoke-RestMethod -Method 'DELETE' -Uri $uri -Headers $vraHeaders + $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function New-NsxtTier1StaticRoute +Export-ModuleMember -Function Remove-vRANotification -Function New-NsxtLoadBalancer -{ +Function Get-vRAResourceCompute { <# - .NOTES - =========================================================================== - Created by: Gary Blake - Date: 03/08/2020 - Organization: VMware - =========================================================================== - .SYNOPSIS - Creates a Load Balancer - + Get compute resources + .DESCRIPTION - The New-NsxtLoadBalancer cmdlet creates a load balancer - + The Get-vRAResourceCompute cmdlet gets a list of known compute resources from vRealize Automation + .EXAMPLE - PS C:\> New-NsxtLoadBalancer -lbName -json - This example creates a load balancer + Get-vRAResourceCompute + This example gets all known compute resources from vRealize Automation + + .EXAMPLE + Get-vRAResourceCompute -id + This example gets a compute resource from vRealize Automation by id #> + Param ( - [Parameter (Mandatory=$true)] - [String]$lbName, - [Parameter (Mandatory=$true)] - [String]$json + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id ) 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 + if ($PsBoundParameters.ContainsKey("id")) { + $uri = "https://$vraAppliance/iaas/api/fabric-computes/$id" + $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vraHeaders + $response + } + else { + $uri = "https://$vraAppliance/iaas/api/fabric-computes" + $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vraHeaders + $response.content + } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function New-NsxtLoadBalancer +Export-ModuleMember -Function Get-vRAResourceCompute -Function New-NsxtLBServiceMonitor -{ +Function Add-vRAResourceComputeTag { <# - .NOTES - =========================================================================== - Created by: Gary Blake - Date: 03/08/2020 - Organization: VMware - =========================================================================== - .SYNOPSIS - Creates a Load Balancer Service Monitor - + Add a compute resource tag + .DESCRIPTION - The New-NsxtLBServiceMonitor cmdlet creates a Load Balancer Service Monitor - + The Add-vRAResourceComputeTag cmdlet adds a tag to a compute resources in vRealize Automation + .EXAMPLE - PS C:\> New-NsxtLBServiceMonitor -monitorName -json - This example creates a Load Balancer Serviec Monitor + Add-vRAResourceComputeTag -id -tagKey enabled -tagValue true + This example adds a new tag to a compute resourcein vRealize Automation #> + Param ( - [Parameter (Mandatory=$true)] - [String]$monitorName, - [Parameter (Mandatory=$true)] - [String]$json + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$tagKey, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$tagValue ) 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 + $existingTags = (Get-vRAResourceCompute -id $id | Select-Object tags).tags + $tagObject = @() + foreach ($tag in $existingTags) { + if ($tag.key -ne $tagKey) { + $tagObject += [pscustomobject]@{ + 'key'= $tag.key + 'value' = $tag.value + } + } + elseif ($tag.key -eq $tagKey) { + $tagObject += [pscustomobject]@{ + 'key'= $tagkey + 'value' = $tagvalue + } + } + } + if (!($tagObject.key -eq $tagKey)) { + $tagObject += [pscustomobject]@{ + 'key'= $tagkey + 'value' = $tagvalue + } + } + $allTagsObject = @() + $allTagsObject += [pscustomobject]@{ + 'tags' = $tagObject + } + $json = $allTagsObject | ConvertTo-Json -Depth 3 + $uri = "https://$vraAppliance/iaas/api/fabric-computes/$id" + $response = Invoke-RestMethod -Method 'PATCH' -Uri $uri -Headers $vraHeaders -Body $json + $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function New-NsxtLBServiceMonitor +Export-ModuleMember -Function Add-vRAResourceComputeTag -Function New-NsxtLBAppProfile -{ +Function Get-vRACloudZone { <# - .NOTES - =========================================================================== - Created by: Gary Blake - Date: 03/08/2020 - Organization: VMware - =========================================================================== - .SYNOPSIS - Creates a Load Balancer Application Profile - + Get Cloud Zones + .DESCRIPTION - The New-NsxtLBAppProfile cmdlet creates a Load Balancer Application Profile - + The Get-vRACloudZone cmdlet gets a list of known Cloud Zones from vRealize Automation + .EXAMPLE - PS C:\> New-NsxtLBAppProfile -appProfileName -json - This example creates a Load Balancer Application Profile + Get-vRACloudZone + This example gets all known Cloud Zones from vRealize Automation + + .EXAMPLE + Get-vRACloudZone -id + This example gets a Cloud Zone from vRealize Automation by id + + .EXAMPLE + Get-vRACloudZone -id -compute + This example gets a Cloud Zone Compute details from vRealize Automation #> + Param ( - [Parameter (Mandatory=$true)] - [String]$appProfileName, - [Parameter (Mandatory=$true)] - [String]$json + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$compute ) - + 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 + if ($PsBoundParameters.ContainsKey("id") -and $PsBoundParameters.ContainsKey("compute")) { + $uri = "https://$vraAppliance/iaas/api/zones/$id/computes" + $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vraHeaders + $response.content + } + elseif ($PsBoundParameters.ContainsKey("id")) { + $uri = "https://$vraAppliance/iaas/api/zones/$id" + $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vraHeaders + $response + } + else { + $uri = "https://$vraAppliance/iaas/api/zones" + $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vraHeaders + $response.content + } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function New-NsxtLBAppProfile +Export-ModuleMember -Function Get-vRACloudZone -Function New-NsxtLBPersistenceAppProfile -{ +Function Update-vRACloudZone { <# - .NOTES - =========================================================================== - Created by: Gary Blake - Date: 03/08/2020 - Organization: VMware - =========================================================================== - .SYNOPSIS - Creates a Load Balancer Persistence Application Profile - + Update a Cloud Zones + .DESCRIPTION - The New-NsxtLBPersistenceAppProfile cmdlet creates a Load Balancer Persistence Application Profile - + The Update-vRACloudZone cmdlet updates a Cloud Zones in vRealize Automation + .EXAMPLE - PS C:\> New-NsxtLBPersistenceAppProfile -appProfileName -json - This example creates a Load Balancer Persistence Application Profile - #> - Param ( - [Parameter (Mandatory=$true)] - [String]$appProfileName, - [Parameter (Mandatory=$true)] - [String]$json + Update-vRACloudZone -id -folder sfo-w01-fd-workload + This example adds a folder to theCloud Zone in vRealize Automation by id + + .EXAMPLE + Update-vRACloudZone -id -tagKey enabled -tagValue true + This example adds tags that should be used to dynamically obtain resources for a Cloud Zone in vRealize Automation by id + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id, + [Parameter (ParameterSetName = "folder", Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$folder, + [Parameter (ParameterSetName = "tag", Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tagKey, + [Parameter (ParameterSetName = "tag", Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tagValue ) - + 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 + $cloudZoneDetails = Get-VRACloudZone -id $id + if ($PsBoundParameters.ContainsKey("id") -and $PsBoundParameters.ContainsKey("folder")) { + $json = '{ "name": "' + $($cloudZoneDetails.name) + '", "folder": "' + $folder +'" }' + } + if ($PsBoundParameters.ContainsKey("id") -and $PsBoundParameters.ContainsKey("tagKey") -and $PsBoundParameters.ContainsKey("tagValue")) { + $json = '{ "name": "' + $($cloudZoneDetails.name) + '", "tagsToMatch": [ { "key": "' + $tagKey +'", "value": "' + $tagValue +'" } ] }' + } + + $uri = "https://$vraAppliance/iaas/api/zones/$id" + $response = Invoke-RestMethod -Method 'PATCH' -Uri $uri -Headers $vraHeaders -Body $json + $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function New-NsxtLBPersistenceAppProfile +Export-ModuleMember -Function Update-vRACloudZone -Function New-NsxtLBPool -{ +Function Remove-vRACloudZone { <# - .NOTES - =========================================================================== - Created by: Gary Blake - Date: 03/08/2020 - Organization: VMware - =========================================================================== - .SYNOPSIS - Creates a Load Balancer Pool - + Remove Cloud Zones + .DESCRIPTION - The New-NsxtLBPool cmdlet creates a Load Balancer Pool - + The Remove-vRACloudZone cmdlet deletes a Cloud Zones from vRealize Automation + .EXAMPLE - PS C:\> New-NsxtLBPool -poolName -json - This example creates a Load Balancer Pool + Remove-vRACloudZone -id + This example deletes a Cloud Zone from vRealize Automation by id #> + Param ( - [Parameter (Mandatory=$true)] - [String]$poolName, - [Parameter (Mandatory=$true)] - [String]$json + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id ) 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 + $uri = "https://$vraAppliance/iaas/api/zones/$id" + $response = Invoke-RestMethod -Method 'DELETE' -Uri $uri -Headers $vraHeaders + $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function New-NsxtLBPool +Export-ModuleMember -Function Remove-vRACloudZone -Function New-NsxtLBVirtualServer -{ +Function Get-vRAServices { <# - .NOTES - =========================================================================== - Created by: Gary Blake - Date: 03/08/2020 - Organization: VMware - =========================================================================== - .SYNOPSIS - Creates a Load Balancer Virtual Server - + Get the services. + .DESCRIPTION - The New-NsxtLBVirtualServer cmdlet creates a Load Balancer Virtual Server - + The Get-vRAServices cmdlet returns the services information from an organization in vRealize Automation. + .EXAMPLE - PS C:\> New-NsxtLBVirtualServer -virtualServerName -json - This example creates a Load Balancer Virtual Server + Get-vRAServices + This example returns the services information from vRealize Automation by orgId. #> + Param ( - [Parameter (Mandatory=$true)] - [String]$virtualServerName, - [Parameter (Mandatory=$true)] - [String]$json - ) + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId + ) 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 + $uri = "https://$vraAppliance/csp/gateway/slc/api/v2/orgs/$orgId/services" + $response = Invoke-RestMethod -Method GET -Uri $uri -Headers $vraHeaders + $response.results } Catch { Write-Error $_.Exception.Message } + } -Export-ModuleMember -Function New-NsxtLBVirtualServer +Export-ModuleMember -Function Get-vRAServices -Function Get-NsxtCertificate -{ +Function Get-vRAUser { <# - .NOTES - =========================================================================== - Created by: Gary Blake - Date: 03/08/2020 - Organization: VMware - =========================================================================== - .SYNOPSIS - Gets NSX-T Certificates - + Get the user in an organization. + .DESCRIPTION - The Get-NsxtCertificates cmdlet gets certificates installed in NSX-T - + The Get-vRAUser cmdlet returns the user information from an organization in vRealize Automation. + .EXAMPLE - PS C:\> Get-NsxtCertificates - This example gets the certificates installed in NSX-T + Get-vRAUser -orgId $orgId -email jdoe@rainpole.io + This example returns the user information for an organization in vRealize Automation by orgId and email. #> Param ( - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [string]$certificateName + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$email ) 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 - } + $uri = "https://$vraAppliance/csp/gateway/am/api/orgs/$orgId/users/search?userSearchTerm=$email" + $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vraHeaders + $response.results } Catch { Write-Error $_.Exception.Message } + } -Export-ModuleMember -Function Get-NsxtCertificate +Export-ModuleMember -Function Get-vRAUser -Function Set-NsxtCertificate -{ +Function New-vRAUser { <# - .NOTES - =========================================================================== - Created by: Gary Blake - Date: 03/08/2020 - Organization: VMware - =========================================================================== - .SYNOPSIS - Installs a Certificate in NSX-T - + Adds a user in an organization. + .DESCRIPTION - The Set-NsxtCertificates cmdlet installs certificates in NSX-T - + The New-vRAUser cmdlet adds a user in vRealize Automation. + .EXAMPLE - PS C:\> Set-NsxtCertificates - This example installs the certificates in NSX-T + New-vRAUser -userId $userId -orgId $serviceRole -serviceDefinitionId $serviceDefinitionId -orgRole $orgRole> -serviceRole $serviceRole> + This example adds a user to vRealize Automation by userId and orgId and assisgnes the required orgRole and serviceRole. #> Param ( - [Parameter (Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [string]$certificateName, - [Parameter (Mandatory=$true)] - [String]$json + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$userId, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$serviceDefinitionId, + [Parameter (Mandatory = $true)] [ValidateSet("org_owner","org_member")] [ValidateNotNullOrEmpty()] [String]$orgRole, + [Parameter (Mandatory = $false)] [ValidateSet('automationservice:cloud_admin','automationservice:user','automationservice:viewer','catalog:admin','catalog:user','catalog:viewer','CodeStream:administrator','CodeStream:developer','CodeStream:executor','CodeStream:user','CodeStream:viewer','migration:admin','migration:viewer','orchestration:admin','orchestration:designer','orchestration:viewer','saltstack:admin')] [ValidateNotNullOrEmpty()] [String]$serviceRole ) Try { - $uri = "https://$nsxtmanager/policy/api/v1/infra/certificates/$($certificateName)" - $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -headers $nsxtHeaders -body $json + $body = '{ + "organizationRoles": { + "roleNamesToAdd": [ + "' + $orgRole + '" + ], + "roleNamesToRemove": [] + }, + "serviceRoles": [ + { + "serviceDefinitionId": "' + $serviceDefinitionId + '", + "roleNamesToAdd": [ + "' + $serviceRole + '" + ], + "roleNamesToRemove": [] + } + ] + }' + $uri = "https://$vraAppliance/csp/gateway/am/api/v3/users/$userId/orgs/$orgId/roles" + $response = Invoke-RestMethod -Method 'PATCH' -Uri $uri -Headers $vraHeaders -Body $body } Catch { Write-Error $_.Exception.Message } -} -Export-ModuleMember -Function Set-NsxtCertificate -################## End NSX-T Functions ####################### -############################################################### - - -############################################################### -############ Begin vSphere with Tanzu Functions ############## +} +Export-ModuleMember -Function New-vRAUser -Function Request-vSphereApiToken { +Function Get-vRAGroup { <# .SYNOPSIS - Request an authentication token for the vSphere REST API + Get the group in an organization. .DESCRIPTION - The Request-vSphereApiToken cmdlet requests an authentication token for the vSphere REST API - - use -admin to set the Admin token for vCenter Server Management Interface - .EXAMPLE - Request-vSphereApiToken -Fqdn sfo-w01-vc01.sfo.rainpole.io -Username administrator@vsphere.local -Password VMw@re1! - This example requests a vSphere REST API authentication token for user administrator@vsphere.local from vCenter Server sfo-w01-vc01.sfo.rainpole.io + The Get-vRAGroup cmdlet returns the group information from an organization in vRealize Automation. .EXAMPLE - Get-vCenterServerDetail -Server sfo-vcf01.sfo.rainpole.io -User administrator@vsphere.local -Pass VMw@re1! -Domain sfo-w01 | Request-vSphereApiToken - This example requests a vSphere REST API authentication token for user administrator@vsphere.local from the vCenter Server that manages VI workload domain sfo-w01 + Get-vRAGroup -orgId $orgId -displayName gg-vra-cloud-assemhly-admins@rainpole.io + This example returns the group information from vRealize Automation by orgId and displayName. #> Param ( - [Parameter (Mandatory = $false)] [String]$Fqdn, - [Parameter (Mandatory = $false)] [String]$Username, - [Parameter (Mandatory = $false)] [String]$Password, - [Parameter (ValueFromPipeline, Mandatory = $false)] [psobject]$inputObject, - [Parameter (Mandatory = $false)] [switch]$admin + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$displayName ) - if ($inputObject) { - $username = $inputObject.ssoAdmin - $password = $inputObject.ssoAdminPass - $fqdn = $inputObject.fqdn - $sddcManager = (Get-VCFManager).fqdn - } - else { - if (!$PsBoundParameters.ContainsKey("username") -or (!$PsBoundParameters.ContainsKey("password"))) { - # Request Credentials - $creds = Get-Credential - $username = $creds.UserName.ToString() - $password = $creds.GetNetworkCredential().password - } - if (!$PsBoundParameters.ContainsKey("fqdn")) { - $fqdn = Read-Host "vCenter Server FQDN not found. Please enter a value, e.g., sfo-m01-vc01.sfo.rainpole.io" - } - } - $vcAuthHeaders = createvCenterAuthHeader($username, $password) - - # Perform the vCenter REST API call to authenticate and retrieve the session token Try { - if ($admin){ - $tmp = $fqdn - $fqdn = $fqdn + ":5480" - $vcAdminSession = (Invoke-WebRequest -Method POST -URI https://$fqdn/rest/com/vmware/cis/session -Headers $vcAuthHeaders | ConvertFrom-Json).Value - $fqdn = $tmp - } - $vcSession = (Invoke-WebRequest -Method POST -URI https://$fqdn/rest/com/vmware/cis/session -Headers $vcAuthHeaders | ConvertFrom-Json).Value + $uri = "https://$vraAppliance/csp/gateway/am/api/orgs/$orgId/groups-search?groupSearchTerm=$displayName" + $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vraHeaders + $response.results } Catch { - Write-Error -Message "Something went wrong with vCenter Server authentication." + Write-Error $_.Exception.Message } - # Use the session token to build the header used from here on - $Global:vcHeaders = @{"vmware-api-session-id" = $vcSession } - $Global:vcHeaders.Add("Content-Type", "application/json") +} +Export-ModuleMember -Function Get-vRAGroup - # Use the session token to build the header for admin interface used from here on - if ($admin){ - $Global:vcAdminHeaders = @{"vmware-api-session-id" = $vcAdminSession } - $Global:vcAdminHeaders.Add("Content-Type", "application/json") - } +Function New-vRAGroup { + <# + .SYNOPSIS + Adds a group in an organization. - # Validate credentials by executing an API call - $Global:currentvCenterServer = $Fqdn + .DESCRIPTION + The New-vRAGroup cmdlet adds a group in vRealize Automation. - $newUri = "https://$fqdn/api/appliance/system/version" - $oldUri = "https://$fqdn/rest/appliance/system/version" + .EXAMPLE + New-vRAGroup -groupId $groupId -orgId $orgId -serviceDefinitionId $serviceDefinitionId -orgRole $orgRole-serviceRole $serviceRole + This example adds a group in vRealize Automation by groupId and orgId and assisgnes both the required orgRole and serviceRole. - Try { - # Checking against the vCenter API - # PS Core has -SkipCertificateCheck implemented, PowerShell 5.x does not - if ($PSEdition -eq 'Core') { - Try { - $response = Invoke-RestMethod -Method GET -Uri $newUri -Headers $vcHeaders -SkipCertificateCheck - if ($response) { - $responseSplit = $response.version.Split(".") - $global:vCenterApi = $responseSplit[0..2] -join "" - } - } - Catch { - $errorStatus = $_.Exception.Response.StatusCode - } - if ($errorStatus -eq "NotFound") { - $response = Invoke-RestMethod -Method GET -Uri $oldUri -Headers $vcHeaders -SkipCertificateCheck - $responseSplit = $response.value.version.Split(".") - $global:vCenterApi = $responseSplit[0..2] -join "" - } - } - else { - Try { - $response = Invoke-RestMethod -Method GET -Uri $newUri -Headers $vcHeaders + .EXAMPLE + New-vRAGroup -groupId $orgId -orgId $orgId -serviceDefinitionId $serviceDefinitionId -orgRole $orgRole -serviceRole $serviceRole + This example adds a group in vRealize Automation by groupId and orgId and assisgnes the required orgRole only. - if ($response) { - $responseSplit = $response.version.Split(".") - $global:vCenterApi = $responseSplit[0..2] -join "" - } - } - Catch { - $errorStatus = $_.Exception.Response.StatusCode - } + Note: This cmdlet currently only supports a single serviceRole. + #> - if ($errorStatus -eq "NotFound") { - $response = Invoke-RestMethod -Method GET -Uri $oldUri -Headers $vcHeaders - $responseSplit = $response.value.version.Split(".") - $global:vCenterApi = $responseSplit[0..2] -join "" - } - } - if ($response) { - if ($inputObject) { - Write-Output "Successfully Requested New API Token for vCenter Server $fqdn via SDDC Manager $sddcManager" - } - else { - Write-Output "Successfully Requested New API Token for vCenter Server $fqdn" - } + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$groupId, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId, + [Parameter (Mandatory = $true)] [ValidateSet("org_owner","org_member")] [ValidateNotNullOrEmpty()] [String]$orgRole, + [Parameter (ParameterSetName = "serviceRole", Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$serviceDefinitionId, + [Parameter (ParameterSetName = "serviceRole", Mandatory = $false)] [ValidateSet('automationservice:cloud_admin','automationservice:user','automationservice:viewer','catalog:admin','catalog:user','catalog:viewer','CodeStream:administrator','CodeStream:developer','CodeStream:executor','CodeStream:user','CodeStream:viewer','migration:admin','migration:viewer','orchestration:admin','orchestration:designer','orchestration:viewer','saltstack:admin')] [ValidateNotNullOrEmpty()] [String]$serviceRole + ) + + Try { + if ($PsBoundParameters.ContainsKey("serviceRole") -and $PsBoundParameters.ContainsKey("serviceDefinitionId")) { + $body = '{ + "ids":[ + "' + $groupId +'" + ], + "organizationRoleNames":[ + "' + $orgRole +'" + ], + "serviceRoles":[ + { + "serviceDefinitionId":"' + $serviceDefinitionId + '", + "serviceRoleNames":[ + "' + $serviceRole + '" + ] + } + ] + }' + $uri = "https://$vraAppliance/csp/gateway/portal/api/orgs/$orgId/groups" + $response = Invoke-RestMethod -Method 'POST' -Uri $uri -Headers $vraHeaders -Body $body + } + elseif ($PsBoundParameters.ContainsKey("serviceRole") -or $PsBoundParameters.ContainsKey("serviceDefinitionId")) { + Write-Error "Only one of serviceRole and serviceDefinitionId provided." + } + else { + $body = '{ + "ids":[ + "' + $groupId +'" + ], + "organizationRoleNames":[ + "' + $orgRole +'" + ] + }' + $uri = "https://$vraAppliance/csp/gateway/portal/api/orgs/$orgId/groups" + $response = Invoke-RestMethod -Method 'POST' -Uri $uri -Headers $vraHeaders -Body $body } } Catch { Write-Error $_.Exception.Message } + } -Export-ModuleMember -Function Request-vSphereApiToken +Export-ModuleMember -Function New-vRAGroup -Function Enable-WMRegistry { +Function Get-vRAUserRoles { <# .SYNOPSIS - Enable the embedded Harbor Registry on a Supervisor Cluster + Get the user roles. .DESCRIPTION - The Enable-WMRegistry cmdlet enables the embedded Harbor Registry on a Supervisor Cluster + The Get-vRAUser Roles cmdlet returns a user's roles in vRealize Automation. .EXAMPLE - Enable-WMRegistry -Cluster "sfo-w01-cl01" -StoragePolicy "vsphere-with-tanzu-policy" - This example enables the embedded Harbor Registry on Supervisor Cluster "sfo-w01-cl01" + Get-vRAUserRoles -userId $userId -orgId $orgId + This example returns a user's roles from vRealize Automation by userId and orgId. + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$userId, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId + ) + + Try { + $uri = "https://$vraAppliance/csp/gateway/am/api/users/$userid/orgs/$orgId/access" + $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vraHeaders + $response + } + Catch { + Write-Error $_.Exception.Message + } + +} +Export-ModuleMember -Function Get-vRAUserRoles + +Function Get-vRAGroupRoles { + <# + .SYNOPSIS + Get the group roles. + + .DESCRIPTION + The Get-vRAGroupRoles cmdlet returns a group's roles in vRealize Automation. .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 + Get-vRAGroupRoles -groupId $groupId -orgId $orgId + This example returns a group's roles from vRealize Automation by groupId and orgId. #> Param ( - [Parameter (Mandatory = $false)] [String]$Domain, - [Parameter (Mandatory = $false)] [String]$Cluster, - [Parameter (Mandatory = $false)] [String]$StoragePolicy, - [Parameter (ValueFromPipeline, Mandatory = $false)] [psObject]$inputObject + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$groupId, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId ) - $vCenterFqdn = $currentvCenterServer - - if ($inputObject) { - $Cluster = $inputObject.Name + Try { + $uri = "https://$vraAppliance/csp/gateway/portal/api/groups/$groupId/orgs/$orgId/roles" + $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vraHeaders + $response + } + Catch { + Write-Error $_.Exception.Message } +} +Export-ModuleMember -Function Get-vRAGroupRoles + +Function Remove-vRAGroupRoles { + <# + .SYNOPSIS + Remove the group roles. + + .DESCRIPTION + The Remove-vRAGroupRoles cmdlet removes a group's roles in vRealize Automation. + + .EXAMPLE + Remove-vRAGroupRoles -groupId $groupId -orgId $orgId + This example removes a group's roles from vRealize Automation by groupId and orgId. + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$groupId, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId + ) + Try { - if ($vCenterApi -le 701) { - $getHarborInstalled = (Invoke-RestMethod -Method GET -URI https://$vCenterFqdn/rest/vcenter/content/registries/harbor -Headers $vcHeaders).value - } - elseif ($vCenterApi -ge 702) { - $getHarborInstalled = Invoke-RestMethod -Method GET -URI https://$vCenterFqdn/api/vcenter/content/registries/harbor -Headers $vcHeaders - } + $body = '{ + "ids": [ + "' + $groupId + '" + ] + }' + $uri = "https://$vraAppliance/csp/gateway/portal/api/orgs/$orgId/groups" + $response = Invoke-RestMethod -Method 'DELETE' -Uri $uri -Headers $vraHeaders -Body $body } Catch { - Write-Error = $_.Exception + Write-Error $_.Exception.Message } - if (!$getHarborInstalled) { - Try { - $wmClusterId = (Invoke-RestMethod -Method GET -URI https://$vCenterFqdn/api/vcenter/namespace-management/clusters -Headers $vcHeaders | Where-Object { $_.cluster_name -eq $Cluster }).cluster - } - Catch { - Write-Error $_.Exception.Message - } - - if (!$StoragePolicy) { - Try { - $storagePolicyId = (Invoke-RestMethod -Method GET -URI https://$vCenterFqdn/api/vcenter/namespace-management/clusters/$wmClusterId -Headers $vcHeaders).image_storage.storage_policy - } - Catch { - Write-Error $_.Exception.Message - } - } - elseif ($StoragePolicy) { - Try { - if ($vCenterApi -ge 702) { - $storagePolicyId = ((Invoke-WebRequest -Method GET -URI https://$vCenterFqdn/api/vcenter/storage/policies -Headers $vcHeaders | 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://$vCenterFqdn/rest/vcenter/storage/policies -Headers $vcHeaders | ConvertFrom-Json).value | Where-Object { $_.name -eq $StoragePolicy }).policy - $json = @" -{ - "spec" : - { - "cluster" : "$wmClusterId", - "storage" : - [ - { - "policy" : "$storagePolicyId" - } - ] +Export-ModuleMember -Function Remove-vRAGroupRoles + +Function Set-vRAGroupOrgRole { + <# + .SYNOPSIS + Set the group organization role. + + .DESCRIPTION + The Set-vRAGroupOrgRole cmdlet sets a group's organization roles in vRealize Automation. + + .EXAMPLE + Set-vRAGroupOrgRole -groupId $groupId -orgId $orgId -orgRole org_owner + This example sets the group as an organization owner in vRealize Automation by groupId and orgId. + + .EXAMPLE + Set-vRAGroupOrgRole -groupId $groupId -orgId $orgId -orgRole org_member + This example sets the group as an organization member in vRealize Automation by groupId and orgId. + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$groupId, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId, + [Parameter (Mandatory = $true)] [ValidateSet("org_owner","org_member")] [ValidateNotNullOrEmpty()] [String]$orgRole + ) + + Try { + $body = '{ + "organizationRoles": { + "roleNamesToAdd": [ + "' + $orgRole + '" + ], + "roleNamesToRemove": [] + } + }' + $uri = "https://$vraAppliance/csp/gateway/portal/api/groups/$groupId/orgs/$orgId/roles" + $response = Invoke-RestMethod -Method 'PATCH' -Uri $uri -Headers $vraHeaders -Body $body } -} -"@ - } - } - 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://$vCenterFqdn/rest/vcenter/content/registries/harbor -Headers $vcHeaders -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://$vCenterFqdn/api/vcenter/content/registries/harbor -Headers $vcHeaders -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 Set-vRAGroupOrgRole -Function Get-WMRegistry { +Function Remove-vRAGroupOrgRole { <# .SYNOPSIS - Retrieves the embedded Harbor Registry on a Supervisor Cluster + Remove the group organization role. .DESCRIPTION - The Get-WMRegistry cmdlet retrieves the embedded Harbor Registry on a Supervisor Cluster + The Remove-vRAGroupOrgRole cmdlet a removes a group's organization role in vRealize Automation. .EXAMPLE - Get-WMRegistry - This example retrieves all embedded Harbor Registries in vCenter Server inventory + Remove-vRAGroupOrgRole -groupId $groupId -orgId $orgId -orgRole org_owner + This example removes the group as an organization owner in vRealize Automation by groupId and orgId. .EXAMPLE - Get-WMRegistry -Cluster "sfo-w01-cl01" - This example enables the embedded Harbor Registry on Supervisor Cluster "sfo-w01-cl01" + Remove-vRAGroupOrgRole -groupId $groupId -orgId $orgId -orgRole org_member + This example removes the group as an organization member in vRealize Automation by groupId and orgId. + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$groupId, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId, + [Parameter (Mandatory = $true)] [ValidateSet("org_owner","org_member")] [ValidateNotNullOrEmpty()] [String]$orgRole + ) + + Try { + $body = '{ + "organizationRoles": { + "roleNamesToAdd": [], + "roleNamesToRemove": [ + "' + $orgRole + '" + ] + } + }' + $uri = "https://$vraAppliance/csp/gateway/portal/api/groups/$groupId/orgs/$orgId/roles" + $response = Invoke-RestMethod -Method 'PATCH' -Uri $uri -Headers $vraHeaders -Body $body + } + Catch { + Write-Error $_.Exception.Message + } + +} +Export-ModuleMember -Function Remove-vRAGroupOrgRole + +Function Set-vRAGroupServiceRole { + <# + .SYNOPSIS + Set the group service role. + + .DESCRIPTION + The Set-vRAGroupServiceRole cmdlet adds a group's service role in vRealize Automation. .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 + Set-vRAGroupServiceRole -groupId $groupId -orgId $orgId -serviceDefinitionId $serviceDefinitionId -serviceRole $serviceRole + This example adds the group to a service role in vRealize Automation by groupId and orgId. #> Param ( - [Parameter (Mandatory = $false)] [String]$Cluster, - [Parameter (ValueFromPipeline, Mandatory = $false)] [psObject]$inputObject + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$groupId, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$serviceDefinitionId, + [Parameter (Mandatory = $true)] [ValidateSet('automationservice:cloud_admin','automationservice:user','automationservice:viewer','catalog:admin','catalog:user','catalog:viewer','CodeStream:administrator','CodeStream:developer','CodeStream:executor','CodeStream:user','CodeStream:viewer','migration:admin','migration:viewer','orchestration:admin','orchestration:designer','orchestration:viewer','saltstack:admin')] [ValidateNotNullOrEmpty()] [String]$serviceRole ) - $vCenterFqdn = $currentvCenterServer - - if ($inputObject) { - $Cluster = $inputObject.Name + Try { + $body = '{ + "serviceRoles": [ + { + "serviceDefinitionId": "' + $serviceDefinitionId + '", + "roleNamesToAdd": [ + "' + $serviceRole + '" + ], + "roleNamesToRemove": [] + } + ], + "organizationRoles": { + "roleNamesToAdd": [], + "roleNamesToRemove": [] + } + }' + $uri = "https://$vraAppliance/csp/gateway/portal/api/groups/$groupId/orgs/$orgId/roles" + $response = Invoke-RestMethod -Method 'PATCH' -Uri $uri -Headers $vraHeaders -Body $body } - - if ($Cluster) { - Try { - $wmClusterId = (Invoke-RestMethod -Method GET -URI https://$vCenterFqdn/api/vcenter/namespace-management/clusters -Headers $vcHeaders | Where-Object { $_.cluster_name -eq $Cluster }).cluster - } - Catch { - Write-Error $_.Exception.Message - } + Catch { + Write-Error $_.Exception.Message } - Try { - if (!$PsBoundParameters.ContainsKey("Cluster")) { - if ($vCenterApi -le 701) { - $response = Invoke-RestMethod -Method GET -URI https://$vCenterFqdn/rest/vcenter/content/registries/harbor -ContentType application/json -headers $vcHeaders - $response.value - } - elseif ($vCenterApi -ge 702) { - $response = Invoke-RestMethod -Method GET -URI https://$vCenterFqdn/api/vcenter/content/registries/harbor -ContentType application/json -headers $vcHeaders - $response - } - } - elseif ($PsBoundParameters.ContainsKey("Cluster")) { - if ($vCenterApi -le 701) { - $response = Invoke-RestMethod -Method GET -URI https://$vCenterFqdn/rest/vcenter/content/registries/harbor -ContentType application/json -headers $vcHeaders - $response.value | Where-Object { $_.cluster -eq $wmClusterId } - } - elseif ($vCenterApi -ge 702) { - $response = Invoke-RestMethod -Method GET -URI https://$vCenterFqdn/api/vcenter/content/registries/harbor -ContentType application/json -headers $vcHeaders - $response | Where-Object { $_.cluster -eq $wmClusterId } - } - } +} +Export-ModuleMember -Function Set-vRAGroupServiceRole + +Function Remove-vRAGroupServiceRole { + <# + .SYNOPSIS + Remove the group service role. + + .DESCRIPTION + The Remove-vRAGroupServiceRole cmdlet removes a group's service role in vRealize Automation. + + .EXAMPLE + Remove-vRAGroupServiceRole -groupId $groupId -orgId $orgId -serviceDefinitionId $serviceDefinitionId -serviceRole $serviceRole + This example removes the group from a service role in vRealize Automation by groupId and orgId. + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$groupId, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$serviceDefinitionId, + [Parameter (Mandatory = $true)] [ValidateSet('automationservice:cloud_admin','automationservice:user','automationservice:viewer','catalog:admin','catalog:user','catalog:viewer','CodeStream:administrator','CodeStream:developer','CodeStream:executor','CodeStream:user','CodeStream:viewer','migration:admin','migration:viewer','orchestration:admin','orchestration:designer','orchestration:viewer','saltstack:admin')] [ValidateNotNullOrEmpty()] [String]$serviceRole + ) + + Try { + $body = '{ + "serviceRoles": [ + { + "serviceDefinitionId": "' + $serviceDefinitionId + '", + "roleNamesToAdd": [], + "roleNamesToRemove": [ + "' + $serviceRole + '" + ] + } + ], + "organizationRoles": { + "roleNamesToAdd": [], + "roleNamesToRemove": [] + } + }' + $uri = "https://$vraAppliance/csp/gateway/portal/api/groups/$groupId/orgs/$orgId/roles" + $response = Invoke-RestMethod -Method 'PATCH' -Uri $uri -Headers $vraHeaders -Body $body } Catch { - Write-Error = $_.Exception + Write-Error $_.Exception.Message } + } -Export-ModuleMember -Function Get-WMRegistry +Export-ModuleMember -Function Remove-vRAGroupServiceRole -Function Remove-WMRegistry { +Function Set-vRAUserOrgRole { <# .SYNOPSIS - Remove the embedded Harbor Registry on a Supervisor Cluster + Set the user organization role. .DESCRIPTION - The Remove-wmRegistry cmdlet removes the embedded Harbor Registry on a Supervisor Cluster + The Set-vRAUserOrgRole cmdlet sets a user's organization role in vRealize Automation. .EXAMPLE - Get-WMRegistry -Cluster "sfo-w01-cl01" | Remove-WMRegistry - This example enables the embedded Harbor Registry on Supervisor Cluster "sfo-w01-cl01" via pipeline from Get-wmCluster with the default storage policy for the Supervisor Cluster + Set-vRAUserOrgRole -userId $userId -orgId $orgId -orgRole org_owner + This example sets the user as an organization owner in vRealize Automation by userId and orgId. .EXAMPLE - Remove-WMRegistry -Cluster "sfo-w01-cl01" - This example enables the embedded Harbor Registry on Supervisor Cluster "sfo-w01-cl01" via pipeline from Get-wmCluster with the default storage policy for the Supervisor Cluster + Set-vRAUserOrgRole -userId $userId -orgId $orgId -orgRole org_member + This example sets the user as an organization member in vRealize Automation by userId and orgId. #> Param ( - [Parameter (Mandatory = $false)] [String]$Cluster, - [Parameter (ValueFromPipeline, Mandatory = $false)] [psObject]$inputObject + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$userId, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId, + [Parameter (Mandatory = $true)] [ValidateSet("org_owner","org_member")] [ValidateNotNullOrEmpty()] [String]$orgRole ) - $vCenterFqdn = $currentvCenterServer - - if ($inputObject) { - $harborRegistryId = $inputObject.registry - } - else { - Try { - $harborRegistryId = (Get-WMRegistry -Cluster $Cluster).registry - } - Catch { - Write-Error $_.Exception.Message - } - } - - if ($vCenterApi -le 701) { - $uri = "https://$vCenterFqdn/rest/vcenter/content/registries/harbor/$harborRegistryId" - } - elseif ($vCenterApi -ge 702) { - $uri = "https://$vCenterFqdn/api/vcenter/content/registries/harbor/$harborRegistryId" - } - Try { - $response = Invoke-WebRequest -Method DELETE -URI $uri -ContentType application/json -headers $vcHeaders - if ($response.StatusCode -eq 200 -or $response.StatusCode -eq 204) { - Write-Output "Embedded registry removal successfully started for Supervisor Cluster $Cluster" - } + $body = '{ + "organizationRoles": { + "roleNamesToAdd": [ + "' + $orgRole + '" + ], + "roleNamesToRemove": [] + } + }' + $uri = "https://$vraAppliance/csp/gateway/am/api/v3/users/$userId/orgs/$orgId/roles" + $response = Invoke-RestMethod -Method 'PATCH' -Uri $uri -Headers $vraHeaders -Body $body } Catch { - Write-Error = $_.Exception + Write-Error $_.Exception.Message } + } -Export-ModuleMember -Function Remove-WMRegistry +Export-ModuleMember -Function Set-vRAUserOrgRole -Function Connect-WMCluster { +Function Remove-vRAUserOrgRole { <# .SYNOPSIS - Log in to a Supervisor Cluster + Remove the user organization role. .DESCRIPTION - The Connect-WMCluster cmdlet adds a refix List to an NSX-T Route Map + The Remove-vRAUserOrgRole cmdlet a user's organization role in vRealize Automation. .EXAMPLE - Connect-WMCluster -Cluster sfo-w01-cl01 -User administrator@vsphere.local -Pass VMw@re1! - This example logs the vSphere SSO user administrator@vsphere.local into Supervisor Cluster sfo-w01-cl01 + Remove-vRAUserOrgRole -userId $userId -orgId $orgId -orgRole org_owner + This example removes the user as an organization owner in vRealize Automation by userId and orgId. + + .EXAMPLE + Remove-vRAUserOrgRole -userId $userId -orgId $orgId -orgRole org_member + This example removes the user as an organization member in vRealize Automation by userId and orgId. #> Param ( - [Parameter (Mandatory = $false)] [String]$Cluster, - [Parameter (Mandatory = $true)] [String]$User, - [Parameter (Mandatory = $true)] [String]$Pass, - [Parameter (ValueFromPipeline, Mandatory = $false)] [psObject]$inputObject + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$userId, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId, + [Parameter (Mandatory = $true)] [ValidateSet("org_owner","org_member")] [ValidateNotNullOrEmpty()] [String]$orgRole ) - if ($inputObject) { - $Server = $inputObject.KubernetesHostname - } - else { - $Server = (Get-WMCluster -Cluster $Cluster).KubernetesHostname - } - Try { - Start-AwaitSession | Out-Null - Send-AwaitCommand "kubectl vsphere login --server $Server --vsphere-username $Username --insecure-skip-tls-verify" | Out-Null - Wait-AwaitResponse "Password:" | Out-Null - Send-AwaitCommand "$Password" - Stop-AwaitSession - Start-Sleep -seconds 3 | Out-Null + $body = '{ + "organizationRoles": { + "roleNamesToAdd": [], + "roleNamesToRemove": [ + "' + $orgRole + '" + ] + } + }' + $uri = "https://$vraAppliance/csp/gateway/am/api/v3/users/$userId/orgs/$orgId/roles" + $response = Invoke-RestMethod -Method 'PATCH' -Uri $uri -Headers $vraHeaders -Body $body } Catch { - Write-Error "Something went wrong." + Write-Error $_.Exception.Message } - $tryKubectl = Invoke-Expression "kubectl get nodes" - - if ($tryKubectl) { - Write-Output "Connection successful." - } } -Export-ModuleMember -Function Connect-WMCluster +Export-ModuleMember -Function Remove-vRAUserOrgRole -Function Disconnect-WMCluster { +Function Set-vRAUserServiceRole { <# .SYNOPSIS - Add a Prefix List to an NSX-T Route Map + Set the user service role. .DESCRIPTION - The Add-NsxtPrefixList cmdlet adds a refix List to an NSX-T Route Map + The Set-vRAUserServiceRole cmdlet adds a user's service role in vRealize Automation. .EXAMPLE - Get-NsxtPrefixList -Name sfo-w01-cl01-prefix-list | Add-NsxtPrefixList -RouteMap sfo-w01-ec01-route-map -Action PERMIT - This example creates a new Prefix List on a Tier 0 Gateway + Set-vRAUserServiceRole -userId $userId -orgId $orgId -serviceDefinitionId $serviceDefinitionId -serviceRole $serviceRole + This example adds the user to a service role in vRealize Automation by userId and orgId. #> + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$userId, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$serviceDefinitionId, + [Parameter (Mandatory = $true)] [ValidateSet('automationservice:cloud_admin','automationservice:user','automationservice:viewer','catalog:admin','catalog:user','catalog:viewer','CodeStream:administrator','CodeStream:developer','CodeStream:executor','CodeStream:user','CodeStream:viewer','migration:admin','migration:viewer','orchestration:admin','orchestration:designer','orchestration:viewer','saltstack:admin')] [ValidateNotNullOrEmpty()] [String]$serviceRole + ) + Try { - Invoke-Expression "kubectl vsphere logout" + $body = '{ + "serviceRoles": [ + { + "serviceDefinitionId": "' + $serviceDefinitionId + '", + "roleNamesToAdd": [ + "' + $serviceRole + '" + ], + "roleNamesToRemove": [] + } + ] + }' + $uri = "https://$vraAppliance/csp/gateway/am/api/v3/users/$userId/orgs/$orgId/roles" + $response = Invoke-RestMethod -Method 'PATCH' -Uri $uri -Headers $vraHeaders -Body $body } Catch { - Debug-ExceptionWriter -object $_ + Write-Error $_.Exception.Message } + } -Export-ModuleMember -Function Disconnect-WMCluster +Export-ModuleMember -Function Set-vRAUserServiceRole -Function New-TanzuKubernetesCluster { +Function Remove-vRAUserServiceRole { <# .SYNOPSIS - Adds a Tanzu Kubernetes cluster based on the specified YAML file. + Remove the user service role. .DESCRIPTION - The New-WMTkgsCluster cmdlet adds a Tanzu Kubernetes cluster based on the specified YAML file. + The Remove-vRAUserServiceRole cmdlet removes a user's service role in vRealize Automation. .EXAMPLE - New-WMTkgsCluster -YAML c:\kube\yaml\tkgsCluster.yaml - This example creates a new Prefix List on a Tier 0 Gateway + Remove-vRAUserServiceRole -userId $userId -orgId $orgId -serviceDefinitionId $serviceDefinitionId -serviceRole $serviceRole + This example removes the user from a service role in vRealize Automation by userId and orgId. #> Param ( - [Parameter (Mandatory = $true)] [String]$YAML + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$userId, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$serviceDefinitionId, + [Parameter (Mandatory = $true)] [ValidateSet('automationservice:cloud_admin','automationservice:user','automationservice:viewer','catalog:admin','catalog:user','catalog:viewer','CodeStream:administrator','CodeStream:developer','CodeStream:executor','CodeStream:user','CodeStream:viewer','migration:admin','migration:viewer','orchestration:admin','orchestration:designer','orchestration:viewer','saltstack:admin')] [ValidateNotNullOrEmpty()] [String]$serviceRole ) Try { - Invoke-Expression "kubectl apply -f $YAML" + $body = '{ + "serviceRoles": [ + { + "serviceDefinitionId": "' + $serviceDefinitionId + '", + "roleNamesToAdd": [], + "roleNamesToRemove": [ + "' + $serviceRole + '" + ] + } + ] + }' + $uri = "https://$vraAppliance/csp/gateway/am/api/v3/users/$userId/orgs/$orgId/roles" + $response = Invoke-RestMethod -Method 'PATCH' -Uri $uri -Headers $vraHeaders -Body $body } Catch { - Debug-ExceptionWriter -object $_ + Write-Error $_.Exception.Message } + } -New-Alias -name Set-TanzuKubernetesCluster -Value Mew-TanzuKubernetesCluster -Export-ModuleMember -Alias Set-TanzuKubernetesCluster -Function New-TanzuKubernetesCluster +Export-ModuleMember -Function Remove-vRAUserServiceRole -Function Get-TanzuKubernetesCluster { +########################## End vRealize Automation Functions ######################### +######################################################################################## + +######################################################################################## +################### Start vRealize Orchestrator (Embedded) Functions ################# + +Function Invoke-vRORestMethod { <# .SYNOPSIS - Retrieves a Tanzu Kubernetes cluster + A wrapper for Invoke-RestMethod for use with vRealize Orchestrator .DESCRIPTION - The Get-TanzuKuberntesCluster cmdlet retrieves a Tanzu Kubernetes cluster - + The Invoke-RestMethod cmdlet is a wrapper for Invoke-RestMethod use with vRealize Orchestrator + .EXAMPLE - Get-TanzuKubernetesCluster - This example retrieves all TanzuKubernetesCluster objects from all namespaces - + Invoke-vRORestMethod -Method 'GET' -Uri '/vco/api/workflows' + .EXAMPLE - Get-TanzuKubernetesCluster -Name sfo-w01-tkc01 -Namespace sfo-w01-tkc01 - This example retrieves a TanzuKubernetesCluster object named "sfo-w01-tkc01" from the namespace specified "sfo-w01-tkc01" + + $method = "POST" + $uri = "/vco/api/workflows/$($ID)/executions/" + $body = @" + {"parameters": + [ + { + "value": {"string":{ "value": "bar"}}, + "type": "string", + "name": "foo", + "scope": "local" + }, + { + "value": {"number":{ "value": 2022}}, + "type": "number", + "name": "bar", + "scope": "local" + } + ] + } + "@ + Invoke-vRORestMethod -method $method -uri $uri -body $body -webRequest + + .NOTES + Attribution: PowervRO by Jakku Labs (https://github.com/jakkulabs/PowervRO/) #> + [CmdletBinding()][OutputType('System.Management.Automation.PSObject')] + Param ( - [Parameter (Mandatory = $false)] [String]$Name, - [Parameter (Mandatory = $false)] [String]$Namespace, - [Parameter (Mandatory = $false)] [Bool]$Detailed + [Parameter (Mandatory = $true)] [ValidateSet("GET", "POST", "PUT", "DELETE")] [String]$method, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$uri, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] $body, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$outFile, + [Parameter (Mandatory = $false)] [Switch]$webRequest ) - if ($Detailed -eq $true) { - if (!$Name -and !$Namespace) { - Invoke-Expression "kubectl describe tkc --all-namespaces" - } - elseif (!$Name -and $Namespace) { - Invoke-Expression "kubectl describe tkc -n $Namespace" - } - elseif ($Name -and !$Namespace) { - Write-Error "A resource cannot be retrieved by name across all namespaces" - } - elseif ($Name -and $Namespace) { - Invoke-Expression "kubectl describe tkc $Name -n $Namespace" - } + $fullUri = "https://$vraAppliance$uri" + + $Params = @{ + method = $method + headers = $vraHeaders + uri = $fullUri } - elseif (!$Detailed -or $Detailed -eq $false) { - if (!$Name -and !$Namespace) { - Invoke-Expression "kubectl get tkc --all-namespaces" - } - elseif (!$Name -and $Namespace) { - Invoke-Expression "kubectl get tkc -n $Namespace" - } - elseif ($Name -and !$Namespace) { - Write-Error "A resource cannot be retrieved by name across all namespaces" + + if ($PSBoundParameters.ContainsKey("body")) { + $Params.Add("body", $body) + Write-Debug -message $body + } + elseif ($PSBoundParameters.ContainsKey("outFile")) { + $Params.Add("outFile", $outFile) + } + + Try { + if ($PSEdition -eq 'Core') { + if ($PSBoundParameters.ContainsKey("webRequest")) { + Invoke-WebRequest @Params -SkipCertificateCheck + } + else { + Invoke-RestMethod @Params -SkipCertificateCheck + } } - elseif ($Name -and $Namespace) { - Invoke-Expression "kubectl get tkc $Name -n $Namespace" + else { + if ($PSBoundParameters.ContainsKey("webRequest")) { + Invoke-WebRequest @Params + } + else { + Invoke-RestMethod @Params + } } } + Catch { + Write-Error $_.Exception.Message + } } -Export-ModuleMember -Function Get-TanzuKubernetesCluster +Export-ModuleMember -Function Invoke-vRORestMethod -Function Remove-TanzuKubernetesCluster { +function Get-vROVersion { <# .SYNOPSIS - Adds a Tanzu Kubernetes cluster based on the specified YAML file. - + Retrieve the vRealize Orchestrator version information + .DESCRIPTION - The New-WMTkgsCluster cmdlet adds a Tanzu Kubernetes cluster based on the specified YAML file. + The Get-vROVersion cmdlest retrieves the vRealize Orchestrator version information .EXAMPLE - New-WMTkgsCluster -YAML c:\kube\yaml\tkgsCluster.yaml - This example creates a new Prefix List on a Tier 0 Gateway - #> + Get-vROVersion - Param ( - [Parameter (Mandatory = $true)] [String]$Name, - [Parameter (Mandatory = $true)] [String]$Namespace - ) + .NOTES + Attribution: PowervRO by Jakku Labs (https://github.com/jakkulabs/PowervRO/) + #> + [CmdletBinding()][OutputType('System.Management.Automation.PSObject')] + + Param () Try { - Invoke-Expression "kubectl delete tkc $Name -n $Namespace" + $uri = "/vco/api/about" + $response = Invoke-vRORestMethod -method 'GET' -uri $uri + $version = $response.version + [pscustomobject] @{ + Version = $version + BuildNumber = $response."build-number" + BuildDate = $response."build-date" + APIVersion = $response."api-version" + } } Catch { - Write-Error "Something went wrong." + Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Remove-TanzuKubernetesCluster +Export-ModuleMember -Function Get-vROVersion -############# End vSphere with Tanzu Functions ############### -############################################################### - - -######################################################################################## -################## Start vRealize Suite Lifecycle Manager Functions ################### - -Function Request-vRSLCMToken { +function Get-vROWorkflow { <# .SYNOPSIS - Connects to the specified vRealize Suite Lifecycle Manager and obtains authorization token + Get vRealize Orchestrator workflows .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 Get-vROWorkflow cmdlet returns details for vRealize Orchestrator workflows .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 - #> + Get-vROWorkflow - Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$fqdn, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$username, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$password - ) + .EXAMPLE + Get-vROWorkflow -categoryName foo + + .EXAMPLE + Get-vROWorkflow -categoryId 3f23f186158a4869b464b7271fc216ba + + .EXAMPLE + Get-vROWorkflow -id '3f23f186-158a-4869-b464-b7271fc216ba' + + .EXAMPLE + Get-vROWorkflow -name 'foo' + + .EXAMPLE + Get-vROWorkflow -name 'Add' -wildcard + + .EXAMPLE + Get-vROWorkflow -tag 'foo' + + .NOTES + Attribution: PowervRO by Jakku Labs (https://github.com/jakkulabs/PowervRO/) + #> - if ( -not $PsBoundParameters.ContainsKey("username") -or ( -not $PsBoundParameters.ContainsKey("password"))) { - $creds = Get-Credential # Request Credentials - $username = $creds.UserName.ToString() - $password = $creds.GetNetworkCredential().password - } + [CmdletBinding(DefaultParametersetName = "All")][OutputType('System.Management.Automation.PSObject')] - $Global:vrslcmHeaders = createBasicAuthHeader $username $password - $Global:vrslcmAppliance = $fqdn + Param ( + [Parameter (Mandatory = $false, ParameterSetName = "categoryName")] [Alias("Category")] [String]$categoryName, + [Parameter (Mandatory = $false, ParameterSetName = "categoryId")] [String]$categoryId, + [Parameter (Mandatory = $false, ParameterSetName = "id")] [String]$id, + [Parameter (Mandatory = $false, ParameterSetName = "name")] [String]$name, + [Parameter (Mandatory = $false, ParameterSetName = "name")] [Switch]$wildcard, + [Parameter (Mandatory = $false, ParameterSetName = "all")] + [Parameter (Mandatory = $false, ParameterSetName = "categoryName")] + [Parameter (Mandatory = $false, ParameterSetName = "category")] [String[]]$tag + ) 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 # PS Core has -SkipCertificateCheck implemented, PowerShell 5.x does not - } - else { - $vrslcmResponse = Invoke-WebRequest -Method GET -Uri $uri -Headers $vrslcmHeaders + Switch ($PsCmdlet.ParameterSetName) { + "all" { + $uri = "/vco/api/workflows" + break + } + "categoryName" { + $uri = "/vco/api/workflows/?conditions=categoryName=$($categoryName)" + break + } + "categoryId" { + $uri = "/vco/api/catalog/System/WorkflowCategory/$($categoryId)/workflows" + break + } + "id" { + $uri = "/vco/api/workflows/$($id)" + break + } + "name" { + if ($PSBoundParameters.ContainsKey('wildcard')) { + $uri = "/vco/api/workflows/?conditions=name~$($name)" + } + else { + $uri = "/vco/api/workflows/?conditions=name=$($name)" + } + break + } } - if ($vrslcmResponse.StatusCode -eq 200) { - Write-Output "Successfully connected to the vRealize Suite Lifecycle Manager Appliance: $vrslcmAppliance" + # Filter by tag, if needed + if ($PSBoundParameters.ContainsKey('tag')) { + $uri += if ($PSCmdlet.ParameterSetName -eq 'all') { '?' } else { '&' } + $newParams = @() + foreach ($tagAttr in $tag) { + $newParams += "tags=$($tagAttr)" + } + $uri += $newParams -join '&' + } + Switch ($PsCmdlet.ParameterSetName) { + "id" { + $workflow = Invoke-vRORestMethod -method 'GET' -uri $uri -Verbose:$VerbosePreference + [pscustomobject]@{ + Name = $workflow.name + ID = $workflow.id + Description = $workflow.description + ItemHref = $workflow.href + Version = $workflow.version + CategoryName = $null + CategoryHref = $null + CustomIcon = $workflow.'customized-icon' + CanExecute = $null + CanEdit = $null + } + } + "categoryId" { + $workflows = Invoke-vRORestMethod -method 'GET' -uri $uri -Verbose:$VerbosePreference + foreach ($workflow in $workflows.link) { + $returnObject = @{ + Name = ($workflow.attributes | Where-Object { $_.name -eq 'name' }).value + ID = ($workflow.attributes | Where-Object { $_.name -eq 'id' }).value + Description = ($workflow.attributes | Where-Object { $_.name -eq 'description' }).value + ItemHref = $workflow.href + Version = ($workflow.attributes | Where-Object { $_.name -eq 'version' }).value + CategoryName = ($workflow.attributes | Where-Object { $_.name -eq 'categoryName' }).value + CategoryHref = ($workflow.attributes | Where-Object { $_.name -eq 'categoryHref' }).value + CustomIcon = ($workflow.attributes | Where-Object { $_.name -eq 'customIcon' }).value + CanExecute = ($workflow.attributes | Where-Object { $_.name -eq 'canExecute' }).value + CanEdit = ($workflow.attributes | Where-Object { $_.name -eq 'canEdit' }).value + } + # Add tags if needed + $tags = $workflow.attributes | Where-Object { $_.name -eq 'globalTags' } | Select-Object -ExpandProperty 'value' + if ($tags) { + $tagsArray = ($tags -replace ':__SYSTEM_TAG__|.$', '').Split(' ') + $returnObject.Add('tags', $tagsArray) + } + [PSCustomObject]$returnObject + } + } + Default { + $workflows = Invoke-vRORestMethod -method 'GET' -uri $uri -verbose:$VerbosePreference + Foreach ($workflow in $workflows.link) { + $returnObject = @{ + Name = ($workflow.attributes | Where-Object { $_.name -eq 'name' }).value + ID = ($workflow.attributes | Where-Object { $_.name -eq 'id' }).value + Description = ($workflow.attributes | Where-Object { $_.name -eq 'description' }).value + ItemHref = ($workflow.attributes | Where-Object { $_.name -eq 'itemHref' }).value + Version = ($workflow.attributes | Where-Object { $_.name -eq 'version' }).value + CategoryName = ($workflow.attributes | Where-Object { $_.name -eq 'categoryName' }).value + CategoryHref = ($workflow.attributes | Where-Object { $_.name -eq 'categoryHref' }).value + CustomIcon = ($workflow.attributes | Where-Object { $_.name -eq 'customIcon' }).value + CanExecute = ($workflow.attributes | Where-Object { $_.name -eq 'canExecute' }).value + CanEdit = ($workflow.attributes | Where-Object { $_.name -eq 'canEdit' }).value + } + # Add tags, if needed + $tags = $workflow.attributes | Where-Object { $_.name -eq 'globalTags' } | Select-Object -ExpandProperty 'value' + if ($tags) { + $tagsArray = ($tags -replace ':__SYSTEM_TAG__|.$', '').Split(' ') + $returnObject.Add('tags', $tagsArray) + } + [PSCustomObject]$returnObject + } + } } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Request-vRSLCMToken +Export-ModuleMember -Function Get-vROWorkflow -Function Get-vRSLCMHealth { +function Invoke-vROWorkflow { <# .SYNOPSIS - Check vRealize Suite Lifecycle Manager Health Status + Invoke a vRealize Orchestrator workflow .DESCRIPTION - The Get-vRSLCMHealth cmdlet checks vRealize Suite Lifecycle Manager Health Status + The Invoke-vROWorkflow cmdlet starts a vRealize Orchestrator workflow .EXAMPLE - Get-vRSLCMHealth - This example checks vRealize Suite Lifecycle Manager Health Status + Invoke-vROWorkflow -ID 3f23f186-158a-4869-b464-b7271fc216ba + + .EXAMPLE + Invoke-vROWorkflow -ID 3f23f186-158a-4869-b464-b7271fc216ba -parameterName 'text' -parameterValue 'foo' -parameterType 'string' + + .EXAMPLE + $Parameters = @" + {"parameters": + [ + { + "value": {"string":{ "value": "bar"}}, + "type": "string", + "name": "foo", + "scope": "local" + }, + { + "value": {"number":{ "value": 2022}}, + "type": "number", + "name": "year", + "scope": "local" + } + ] + } + "@ + + Invoke-vROWorkflow -id 3f23f186-158a-4869-b464-b7271fc216ba -parameters ($parameters | ConvertFrom-Json).parameters + + .EXAMPLE + $param1 = New-vROParameterDefinition -name 'foo' -value 'bar' -type string -scope LOCAL + Invoke-vROWorkflow -id 3f23f186-158a-4869-b464-b7271fc216ba -parameters $param1 + + .EXAMPLE + Get-vROWorkflow -name 'foo' | Invoke-vROWorkflow -parameterName 'foo' -parameterValue 'bar' -parameterType string + + .NOTES + Attribution: PowervRO by Jakku Labs (https://github.com/jakkulabs/PowervRO/) #> - Try { - $uri = "https://$vrslcmAppliance/lcm/health/api/v2/status" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders - $response - } - Catch { - Write-Error $_.Exception.Message + [CmdletBinding(DefaultParametersetName = "A")][OutputType('System.Management.Automation.PSObject')] + + Param ( + [Parameter (Mandatory = $true, ValueFromPipelinebyPropertyName = $true, ParameterSetName = "A")] + [Parameter (Mandatory = $true, ParameterSetName = "B")] [ValidateNotNullOrEmpty()] [String]$id, + [Parameter (Mandatory = $false, ParameterSetName = "A")] [Parameter (ParameterSetName = "C")] [ValidateNotNullOrEmpty()] [String]$parameterName, + [Parameter (Mandatory = $false, ParameterSetName = "A")] [Parameter (ParameterSetName = "C")] [String]$parameterValue, + [Parameter (Mandatory = $false, ParameterSetName = "A")] [Parameter (ParameterSetName = "C")] [ValidateNotNullOrEmpty()] [String]$parameterType, + [Parameter (Mandatory = $false, ParameterSetName = "B")] [Parameter (ParameterSetName = "D")] [ValidateNotNullOrEmpty()] [PSCustomObject[]]$parameters + ) + + Begin {} + Process { + Try { + if ($PSBoundParameters.ContainsKey('parameterType')) { + $parameterType = $parameterType.ToLower() + $body = @" +{"parameters": + [ + { + "value": {"$($parameterType)":{ "value": "$($parameterValue)"}}, + "type": "$($parameterType)", + "name": "$($parameterName)", + "scope": "local" + } + ] +} +"@ + } + elseif ($PSBoundParameters.ContainsKey('parameters')) { + $object = [PSCustomObject]@{ + parameters = @() + } + foreach ($parameter in $parameters) { + $object.parameters += $parameter + } + $body = $object | ConvertTo-Json -Depth 100 + } + else { + $body = @" +{"parameters": +[ +] +} +"@ + } + $uri = "/vco/api/workflows/$($id)/executions/" + $response = Invoke-vRORestMethod -method 'POST' -uri $uri -body $body -webRequest -verbose:$VerbosePreference + + if ($PSEdition -eq 'Core') { + [pscustomobject]@{ + StatusCode = $response.StatusCode + StatusDescription = $response.StatusDescription + Execution = ([System.Uri]$response.Headers.Location[0]).LocalPath + } + } + else { + [pscustomobject]@{ + StatusCode = $response.StatusCode + StatusDescription = $response.StatusDescription + Execution = ([System.Uri]$response.Headers.Location).LocalPath + } + } + } + Catch { + Write-Error $_.Exception.Message + } } } -Export-ModuleMember -Function Get-vRSLCMHealth +Export-ModuleMember -Function Invoke-vROWorkflow -Function Get-vRSLCMLockerPassword { +function New-vROParameterDefinition { <# .SYNOPSIS - Get paginated list of Passwords available in the Store - + Create a parameter definition for use with a vRealize Orchestrator workflow + .DESCRIPTION - The Get-vRSLCMLockerPassword cmdlet gets a paginated list of passwords available in the Locker + The New-vROParameterDefinition cmdlet create a parameter definition for use with a vRealize Orchestrator workflow .EXAMPLE - Get-vRSLCMLockerPassword - This example gets all passwords in the Locker + $param1 = New-vROParameterDefinition -name 'foo' -value 'bar' -type string -scope LOCAL - .EXAMPLE - Get-vRSLCMLockerPassword -vmid 83abd0fd-c92d-4d8f-a5e8-9a1fc4fa6009 - This example gets the details of a password based on the vmid + Invoke-vROWorkflow -id 697c8755-15c0-44fc-b409-5c562cf2984e -parameters $param1 + + .NOTES + Attribution: PowervRO by Jakku Labs (https://github.com/jakkulabs/PowervRO/) #> + [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = "Low")][OutputType('System.Management.Automation.PSObject')] + Param ( - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vmid - ) + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$name, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$value, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$type, + [Parameter (Mandatory = $false)] [ValidateSet("LOCAL", "TOKEN")] [String]$scope = "LOCAL" + ) - Try { - if ($PsBoundParameters.ContainsKey("vmid")) { - $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/passwords/$vmid" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders - $response + Begin {} + Process { + Try { + if ($PSCmdlet.ShouldProcess("WorkflowParameterDefinition")){ + $parameterDefinition = @" +{ + "name": "$($name)", + "type": "$($type.ToLower())", + "scope": "$($scope.ToLower())", + "value": { + "$($type.ToLower())":{ "value": "$($value)"} + } +} +"@ + $parameterDefinition | ConvertFrom-Json + } } - else { - $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/passwords" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders - $response.passwords + Catch { + Write-Error $_.Exception.Message } } - Catch { - Write-Error $_.Exception.Message + End { } } -Export-ModuleMember -Function Get-vRSLCMLockerPassword +Export-ModuleMember -Function New-vROParameterDefinition -Function Add-vRSLCMLockerPassword { +function Get-vROWorkflowExecution { <# .SYNOPSIS - Creates a new Password in a Locker + Get vRealize orchestrator Wwrkflow executions .DESCRIPTION - The Add-vRSLCMLockerPassword cmdlet add as new passwords to the Locker + The Get-vROWorkflowExecution cmdlet returns the execution runs for a vRealize Orchestrator workflow .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 + Get-vROWorkflowExecution -id 697c8755-15c0-44fc-b409-5c562cf2984e + + .EXAMPLE + Get-vROWorkflowExecution -name 'foo' + + .EXAMPLE + Get-vROWorkflow -name 'foo' | Get-vROWorkflowExecution + + .NOTES + Attribution: PowervRO by Jakku Labs (https://github.com/jakkulabs/PowervRO/) #> - 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 - ) + [CmdletBinding(DefaultParametersetName = "Name")][OutputType('System.Management.Automation.PSObject')] - Try { - $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/passwords" + Param ( + [Parameter (Mandatory = $true, ValueFromPipelinebyPropertyName = $true, ParameterSetName = "id")] [String]$id, + [Parameter (Mandatory = $true, ParameterSetName = "name")] [String]$name + ) - if ($PsBoundParameters.ContainsKey("description")) { - $body = '{ - "alias": "'+ $alias +'", - "password": "'+ $password +'", - "passwordDescription": "'+ $description +'", - "userName": "'+ $userName +'" - }' + Begin {} + Process { + Try { + if ($PSCmdlet.ParameterSetName -eq "name") { + $id = (Get-vROWorkflow -name $name).id + } + $uri = "/vco/api/workflows/$($id)/executions" + $response = Invoke-vRORestMethod -method 'GET' -uri $uri -verbose:$VerbosePreference + $data = $response.relations.link | Where-Object { $_.attributes } + Foreach ($execution in $data) { + [PSCustomObject]@{ + Name = ($execution.attributes | Where-Object { $_.name -eq 'name' }).value + ID = ($execution.attributes | Where-Object { $_.name -eq 'id' }).value + Execution = "$uri/$(($execution.attributes | Where-Object {$_.name -eq 'id'}).value)/" + State = ($execution.attributes | Where-Object { $_.name -eq 'state' }).value + StartedBy = ($execution.attributes | Where-Object { $_.name -eq 'startedBy' }).value + StartDate = ($execution.attributes | Where-Object { $_.name -eq 'StartDate' }).value + EndDate = ($execution.attributes | Where-Object { $_.name -eq 'EndDate' }).value + } + } } - else { - $body = '{ - "alias": "'+ $alias +'", - "password": "'+ $password +'", - "userName": "'+ $userName +'" - }' + Catch { + Write-Error $_.Exception.Message } - - $response = Invoke-RestMethod $uri -Method 'POST' -Headers $vrslcmHeaders -Body $body - $response } - Catch { - Write-Error $_.Exception.Message + End { } } -Export-ModuleMember -Function Add-vRSLCMLockerPassword +Export-ModuleMember -Function Get-vROWorkflowExecution -Function Remove-vRSLCMLockerPassword { +function Get-vROWorkflowExecutionState { <# .SYNOPSIS - Delete a Password based on vmid + Get vRealize Orchestrator workflow execution state .DESCRIPTION - The Remove-vRSLCMLockerPassword cmdlet deletes a password from the Locker + The Get-vROWorkflowExecutionState cmdlet returns the status of vRealize Orchestrator workflow execution runs .EXAMPLE - Remove-vRSLCMLockerPassword -vmid - This example delets the password with the vmid + Get-vROWorkflowExecutionState -executionStateRef '/vco/api/workflows/697c8755-15c0-44fc-b409-5c562cf2984e/executions/cda43353730b4f8ba1815979ef8a932a' + + .EXAMPLE + Get-vROWorkflowExecution -id 697c8755-15c0-44fc-b409-5c562cf2984e | Select-Object -last 1 | Get-vROWorkflowExecutionState + + .NOTES + Attribution: PowervRO by Jakku Labs (https://github.com/jakkulabs/PowervRO/) #> - Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vmid + [CmdletBinding()][OutputType('System.Management.Automation.PSObject')] + + Param ( + [Parameter (Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelinebyPropertyName = $true)] [Alias("execution")] [ValidateNotNullOrEmpty()][String]$executionStateRef ) - Try { - $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/passwords/$vmid" - $response = Invoke-RestMethod $uri -Method 'DELETE' -Headers $vrslcmHeaders - $response + Begin {} + Process { + Try { + Foreach ($reference in $executionStateRef) { + $uri = $reference + "state" + $response = Invoke-vRORestMethod -method 'GET' -uri $uri -webRequest -verbose:$VerbosePreference + [pscustomobject]@{ + ExecutionStateRef = $reference + StatusCode = $response.StatusCode + StatusDescription = $response.StatusDescription + Execution = ($response.Content | ConvertFrom-Json).Value + } + } + } + Catch { + Write-Error $_.Exception.Message + } } - Catch { - Write-Error $_.Exception.Message + End { } } -Export-ModuleMember -Function Remove-vRSLCMLockerPassword +Export-ModuleMember -Function Get-vROWorkflowExecutionState -Function Get-vRSLCMLockerCertificate { +function Get-vROWorkflowExecutionResult { <# .SYNOPSIS - Get paginated list of Certificates available in the Store + Get vRealize Orchestrator workflow execution result .DESCRIPTION - The Get-vRSLCMLockerCertificate cmdlet gets a paginated list of certificates available in the Locker + The Get-vROWorkflowExecutionResult cmdlet returns the results of vRealize Orchestrator workflow execution runs .EXAMPLE - Get-vRSLCMLockerCertificate - This example gets all certificates in the Locker + Get-vROWorkflowExecutionResult -executionRef '/vco/api/workflows/697c8755-15c0-44fc-b409-5c562cf2984e/executions/cda43353730b4f8ba1815979ef8a932a' .EXAMPLE - Get-vRSLCMLockerCertificate -vmid 83abd0fd-c92d-4d8f-a5e8-9a1fc4fa6009 - This example gets the details of a certificate based on the vmid + Get-vROWorkflow -name 'foo' | Get-vROWorkflowExecution | Select-Object -last 1 | Get-vROWorkflowExecutionResult - .EXAMPLE - Get-vRSLCMLockerCertificate -alias xint-vrops01 - This example gets the details of a certificate based on the vmid + .NOTES + Attribution: PowervRO by Jakku Labs (https://github.com/jakkulabs/PowervRO/) #> + [CmdletBinding()][OutputType('System.Management.Automation.PSObject')] + Param ( - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vmid, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$alias + [Parameter (Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelinebyPropertyName = $true)] [Alias("execution")] [ValidateNotNullOrEmpty()] [String]$executionRef ) - Try { - 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("alias")) { - $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/certificates" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders - $response.certificates | Where-Object {$_.alias -eq $alias} + Begin {} + Process { + Try { + Foreach ($reference in $executionRef) { + $response = Invoke-vRORestMethod -method 'GET' -uri $reference -webRequest -verbose:$VerbosePreference + $json = $response.Content | ConvertFrom-Json + Foreach ($outputParameter in $json.'output-parameters') { + $type = $outputParameter.type + [pscustomobject]@{ + ExecutionRef = $reference + Name = $outputParameter.name + Scope = $outputParameter.scope + Type = $outputParameter.type + Value = $outputParameter.value.$type.value + } + } + } } - else { - $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/certificates" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders - $response.certificates + Catch { + Write-Error $_.Exception.Message } } - Catch { - Write-Error $_.Exception.Message + End { } } -Export-ModuleMember -Function Get-vRSLCMLockerCertificate +Export-ModuleMember -Function Get-vROWorkflowExecutionResult -Function Add-vRSLCMLockerCertificate { +#################### End vRealize Orchestrator (Embedded) Functions ################## +######################################################################################## + +######################################################################################## +#################### Start vRealize Operations Manager Functions ##################### + +Function Request-vROPSToken { <# .SYNOPSIS - Add a certificate to the vRSLCM locker + Connects to the specified vRealize Operations Manager and obtains authorization token .DESCRIPTION - The Add-vRSLCMLockerCertificate cmdlet adds a certificate to the vRSLCM locker - - .EXAMPLE - Add-vRSLCMLockerCertificate - This example gets all certificates in the Locker + The Request-vROPSToken cmdlet connects to the specified vRealize Operations Manager and obtains an authorization token. + It is required once per session before running all other cmdlets. - .EXAMPLE - Add-vRSLCMLockerCertificate -vmid 83abd0fd-c92d-4d8f-a5e8-9a1fc4fa6009 - This example gets the details of a certificate based on the vmid - #> + .EXAMPLE + Request-vROPSToken -fqdn xint-vrops01.rainpole.io -username admin -password VMw@re1! + This example shows how to connect to the vRealize Operations Manager appliance + #> 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]$fqdn, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$username, + [Parameter (Mandatory = $true)] [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 + } + Try { - $newPEMString - foreach ($line in Get-Content $certChainPath) { - $stringToAdd = $line + '\n' - $newPEMString += $stringToAdd + $Global:vropsAppliance = $fqdn + $Global:vropsHeaders = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" + $vropsHeaders.Add("Accept", "application/json") + $vropsHeaders.Add("Content-Type", "application/json") + $uri = "https://$vropsAppliance/suite-api/api/auth/token/acquire" + + $body = "{ + `n `"username`" : `"$username`", + `n `"authSource`" : `"LOCAL`", + `n `"password`" : `"$password`" + `n}" + + if ($PSEdition -eq 'Core') { + $vropsResponse = Invoke-RestMethod -Uri $uri -Method 'POST' -Headers $vropsHeaders -Body $body -SkipCertificateCheck # PS Core has -SkipCertificateCheck implemented, PowerShell 5.x does not } - $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+'" - }' + else { + $vropsResponse = Invoke-RestMethod -Uri $uri -Method 'POST' -Headers $vropsHeaders -Body $body } - $uri = "https://$vrslcmFQDN/lcm/locker/api/v2/certificates/import" - $response = Invoke-RestMethod $uri -Method 'POST' -Headers $vrslcmHeaders -ContentType application/json -body $body - $response.certInfo + if ($vropsResponse.token) { + $vropsHeaders.Add("Authorization", "vRealizeOpsToken " + $vropsResponse.token) + Write-Output "Successfully connected to vRealize Operations Manager: $vropsAppliance" + } } Catch { Write-Error $_.Exception.Message } } +Export-ModuleMember -Function Request-vROPSToken -Export-ModuleMember -Function Add-vRSLCMLockerCertificate - -Function Remove-vRSLCMLockerCertificate { +Function Get-vROPSCollector { <# .SYNOPSIS - Delete a certificate based on vmid + Get list of collectors .DESCRIPTION - The Remove-vRSLCMLockerCertificate cmdlet deletes a certificate from the Locker + The Get-vROPSCollector cmdlet gets a list of collectors in vRealize Operations Manager .EXAMPLE - Remove-vRSLCMLockerCertificate -vmid - This example delets the certificate with the vmid + Get-vROPSCollector + This example gets a list of collectors + + .EXAMPLE + Get-vROPSCollector -id + This example gets details of a collector by its ID #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vmid + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id ) Try { - $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/certificates/$vmid" - $response = Invoke-RestMethod $uri -Method 'DELETE' -Headers $vrslcmHeaders - $response + if ($PsBoundParameters.ContainsKey("id")) { + $uri = "https://$vropsAppliance/suite-api/api/collectors/$id/adapters" + $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders + $response.adapterInstancesInfoDto + } + else { + $uri = "https://$vropsAppliance/suite-api/api/collectors" + $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders + $response.collector + } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Remove-vRSLCMLockerCertificate +Export-ModuleMember -Function Get-vROPSCollector -Function Get-vRSLCMLockerLicense { +Function Get-vROPSCollectorGroup { <# .SYNOPSIS - Get paginated list of License available in the Store + Get list of collector groups .DESCRIPTION - The Get-vRSLCMLockerPassword cmdlet gets a paginated list of license available in the Locker - - .EXAMPLE - Get-vRSLCMLockerLicense - This example gets all license in the Locker + The Get-vROPSCollectorGroup cmdlet gets a list of collector groups in vRealize Operations Manager .EXAMPLE - Get-vRSLCMLockerLicense -vmid 2b54b028-9eba-4d2f-b6ee-66428ea2b297 - This example gets the details of a license based on the vmid + Get-vROPSCollectorGroup + This example gets a list of collector groups .EXAMPLE - Get-vRSLCMLockerLicense -alias "vRealize Operations Manager" - This example gets the details of a license based on the alias name + Get-vROPSCollectorGroup -id + This example gets details of a collector by its ID #> Param ( - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vmid, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$alias + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id ) 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("id")) { + $uri = "https://$vropsAppliance/suite-api/api/collectorgroups/$id" + $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders $response } else { - $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/licenses" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders - $response + $uri = "https://$vropsAppliance/suite-api/api/collectorgroups" + $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders + $response.collectorGroups } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-vRSLCMLockerLicense +Export-ModuleMember -Function Get-vROPSCollectorGroup -Function Add-vRSLCMLockerLicense { +Function Add-vROPSCollectorGroup { <# .SYNOPSIS - Creates a new License in a Locker + Add a collector groups .DESCRIPTION - The Add-vRSLCMLockerLicense cmdlet adds as new license to the Locker + The Add-vROPSCollectorGroup cmdlet adds a new collector groups in vRealize Operations Manager .EXAMPLE - Add-vRSLCMLockerLicense -alias "vRealise Operations Manager" -license "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX" - This example adds a license to the Locker + Add-vROPSCollectorGroup -name sfo-remote-collectors -description "Remote Collector Group for SFO" -collectorIds "1,2" + This example gets a list of collector groups #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$alias, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$license + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$name, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$description, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$collectorIds ) Try { - $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/license/validate-and-add" - $body = '{ - "alias": "'+ $alias +'", - "serialKey": "'+ $license +'" - }' + $uri = "https://$vropsAppliance/suite-api/api/collectorgroups" + if ($description) { + $body = '{ "name" : "'+ $name +'", "description" : "'+ $description +'", "collectorId" : ['+ $collectorIds +'], "systemDefined" : false }' + } + else { + $body = '{ "name" : "'+ $name +'", "collectorId" : ['+ $collectorIds +'], "systemDefined" : false }' + } + $response = Invoke-RestMethod -Method 'POST' -Uri $Uri -Headers $vropsHeaders -Body $body - $response = Invoke-RestMethod $uri -Method 'POST' -Headers $vrslcmHeaders -Body $body - $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Add-vRSLCMLockerLicense +Export-ModuleMember -Function Add-vROPSCollectorGroup -Function Remove-vRSLCMLockerLicense { +Function Remove-vROPSCollectorGroup { <# .SYNOPSIS - Delete a License based on vmid + Delete a collector group .DESCRIPTION - The Remove-vRSLCMLockerLicense cmdlet deletes a license from the Locker + The Remove-vROPSCollectorGroup cmdlet deletes a collector group in vRealize Operations Manager .EXAMPLE - Remove-vRSLCMLockerLicense -vmid - This example delets the license with the vmid + Remove-vROPSCollectorGroup -id + This example deletes a gollector group #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vmid + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id ) Try { - $uri = "https://$vrslcmAppliance/lcm/locker/api/licenses/$vmid" - $response = Invoke-RestMethod $uri -Method 'DELETE' -Headers $vrslcmHeaders - $response + $uri = "https://$vropsAppliance/suite-api/api/collectorgroups/$id" + $response = Invoke-RestMethod -Method 'DELETE' -Uri $Uri -Headers $vropsHeaders } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Remove-vRSLCMLockerLicense +Export-ModuleMember -Function Remove-vROPSCollectorGroup -Function Get-vRSLCMDatacenter { +Function Get-vROPSAdapter { <# .SYNOPSIS - Get paginated list of datacenters in vRealize Suite Lifecycle Manager + Get list of adapters .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 + The Get-vROPSAdapter cmdlet gets a list of adapters in vRealize Operations Manager .EXAMPLE - Get-vRSLCMDatacenter -vmid 2b54b028-9eba-4d2f-b6ee-66428ea2b297 - This example gets the details of a datacenter based on the vmid + Get-vROPSAdapter + This example gets a list of all adapters .EXAMPLE - Get-vRSLCMDatacenter -name sfo-m01-dc01 - This example gets the details of a datacenter based on the name + Get-vROPSAdapter -id + This example gets details of an adapter by its ID #> Param ( - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vmid, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$name + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id ) 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("alias")) { - $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/datacenters/$name" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders + if ($PsBoundParameters.ContainsKey("id")) { + $uri = "https://$vropsAppliance/suite-api/api/adapters/$id" + $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders $response } else { - $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/datacenters" - $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders - $response + $uri = "https://$vropsAppliance/suite-api/api/adapters" + $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders + $response.adapterInstancesInfoDto } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-vRSLCMDatacenter +Export-ModuleMember -Function Get-vROPSAdapter -Function Get-vRSLCMEnvironment { +Function Set-vROPSAdapter { <# .SYNOPSIS - Get paginated list of environments in vRealize Suite Lifecycle Manager + Update an adapter .DESCRIPTION - The Get-vRSLCMEnvironment cmdlet gets a paginated list of environments in vRealize Suite Lifecycle Manager + The Set-vROPSAdapter cmdlet updates the adapters configuration in vRealize Operations Manager .EXAMPLE - Get-vRSLCMEnvironment - This example gets all environments in vRealize Suite Lifecycle Manager + Set-vROPSAdapter -json .\adapterJson + This example updates the details of an adapter #> Param ( - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vmid + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$json ) Try { - 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 + 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://$vropsAppliance/suite-api/api/adapters" + $response = Invoke-RestMethod -Method 'PUT' -Uri $Uri -Headers $vropsHeaders -Body $body + $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-vRSLCMEnvironment +Export-ModuleMember -Function Set-vROPSAdapter -Function Add-vRSLCMDatacenter { +Function Add-vROPSAdapter { <# .SYNOPSIS - Add a datacenter in vRealize Suite Lifecycle Manager + Add an adapter .DESCRIPTION - The Add-vRSLCMDatacenter cmdlet adds a datacenter in vRealize Suite Lifecycle Manager + The Add-vROPSAdapter cmdlet adds an adapter to vRealize Operations Manager .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 + Add-vROPSAdapter -json .\adapterJson + This example adds an adapter useing the json specification file #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$datacenterName, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$location + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$json ) Try { - $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/datacenters" - $body = '{ - "dataCenterName": "'+ $datacenterName +'", - "primaryLocation": "'+ $location +'" - }' - $response = Invoke-RestMethod $uri -Method 'POST' -Headers $vrslcmHeaders -Body $body + 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://$vropsAppliance/suite-api/api/adapters" + $response = Invoke-RestMethod -Method 'POST' -Uri $Uri -Headers $vropsHeaders -Body $body $response -} + } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Add-vRSLCMDatacenter +Export-ModuleMember -Function Add-vROPSAdapter -Function Add-vRSLCMEnvironment { +Function Start-vROPSAdapter { <# .SYNOPSIS - Create an environment in vRealize Suite Lifecycle Manager + Starts collection of adapter .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 Start-vROPSAdapter cmdlet starts the collection of an adapter in vRealize Operations 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 + Start-vROPSAdapter -adpaterId + This example starts the adpater by id #> 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]$adapterId ) 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 - } + $uri = "https://$vropsAppliance/suite-api/api/adapters/$adapterId/monitoringstate/start" + $response = Invoke-RestMethod -Method 'PUT' -Uri $Uri -Headers $vropsHeaders + $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Add-vRSLCMEnvironment +Export-ModuleMember -Function Start-vROPSAdapter -Function Get-vRSLCMRequest { +Function Stop-vROPSAdapter { <# .SYNOPSIS - Get all Requests + Stops collection of adapter .DESCRIPTION - The Get-vRSLCMRequest cmdlet gets all requests in vRealize Suite Lifecycle Manager + The Stop-vROPSAdapter cmdlet starts the collection of an adapter in vRealize Operations 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 + Stop-vROPSAdapter -adpaterId + This example starts the adpater by id #> Param ( - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$requestId, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$errorCauses + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$adapterId ) 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 - } + $uri = "https://$vropsAppliance/suite-api/api/adapters/$adapterId/monitoringstate/stop" + $response = Invoke-RestMethod -Method 'PUT' -Uri $Uri -Headers $vropsHeaders + $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-vRSLCMRequest +Export-ModuleMember -Function Stop-vROPSAdapter -Function Remove-vRSLCMRequest { +Function Get-vROPSAdapterKind { <# .SYNOPSIS - Delete a Request + Get list of adapter kinds .DESCRIPTION - The Remove-vRSLCMRequest cmdlet removes a request from vRealize Suite Lifecycle Manager + The Get-vROPSAdapterKind cmdlet gets a list of adapter kinds in vRealize Operations Manager .EXAMPLE - Remove-vRSLCMRequest -requestId - This example removes a request from vRealize Suite Lifecycle Manager + Get-vROPSAdapterKind + This example gets a list of all adapter kinds + + .EXAMPLE + Get-vROPSAdapterKind -kind VMWARE + This example gets details of an resource kinds for the VMWARE adapter kind #> Param ( - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$requestId ) + [Parameter (Mandatory = $false)] [ValidateSet("Container","EP Ops Adapter","Http Post","LogInsight","MicrosoftAzureAdapter","AmazonAWSAdapter","NSXTAdapter","PingAdapter","SDDCHealthAdapter","APPLICATIONDISCOVERY","VMWARE","VmcAdapter","IdentityManagerAdapter","APPOSUCP","VOAAdapter","CASAdapter","LogInsightAdapter","NETWORK_INSIGHT","vCenter Operations Adapter","vRealizeOpsMgrAPI","VirtualAndPhysicalSANAdapter")] [ValidateNotNullOrEmpty()] [String]$adapterKind + ) Try { - - $uri = "https://$vrslcmAppliance/lcm/request/requests/$requestId" - $response = Invoke-RestMethod $uri -Method 'DELETE' -Headers $vrslcmHeaders - $response + if ($PsBoundParameters.ContainsKey("adapterKind")) { + $uri = "https://$vropsAppliance/suite-api/api/adapterkinds/$adapterKind" + $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vropsHeaders + $response.resourceKinds + } + else { + $uri = "https://$vropsAppliance/suite-api/api/adapterkinds" + $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vropsHeaders + $response.'adapter-kind' + } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Remove-vRSLCMRequest +Export-ModuleMember -Function Get-vROPSAdapterKind -Function Watch-vRSLCMRequest { +Function Get-vROPSResourceDetail { <# .SYNOPSIS - Poll request + Get resource detail .DESCRIPTION - The Watch-vRSLCMRequest cmdlet polls a request in vRealize Suite Lifecycle Manager + The Get-vROPSResourceDetail cmdlet gets the details for a resource from vRealize Operations Manager .EXAMPLE - Watch-vRSLCMRequest -vmid - This example polls the request in vRealize Suite Lifecycle Manager + Get-vROPSResourceDetail -adapter VMWARE -resource Datacenter -objectName sfo-m01-dc01 + This example gets the resource details #> Param ( - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vmid + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$adapter, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$resource, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$objectname ) 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://$vropsAppliance/suite-api/api/adapterkinds/$adapter/resourcekinds/$resource/resources?identifiers[VMEntityName]=$objectName" + $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vropsHeaders + $response.resourceList.resourceKey.resourceIdentifiers } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Watch-vRSLCMRequest +Export-ModuleMember -Function Get-vROPSResourceDetail -Function Resume-vRSLCMRequest { +Function Get-vROPSCredential { <# .SYNOPSIS - Retry a request + Get credentials .DESCRIPTION - The Resume-vRSLCMRequest cmdlet reties a request + The Get-vROPSCredential cmdlet gets credentials from vRealize Operations Manager .EXAMPLE - Resume-vRSLCMRequest -requestId 0ee1a4a0-203a-4c87-a40e-65d9a450e398 - This example reties the request based on the request ID provided + Get-vROPSCredential + This example gets all credentials from vRealize Operations Manager #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$requestId + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$credentialId, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$adapter, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$resource ) Try { - $uri = "https://$vrslcmAppliance/lcm/request/api/v2/requests/$requestId/retry" - $response = Invoke-RestMethod $uri -Method 'PATCH' -Headers $vrslcmHeaders - $response + if ($PsBoundParameters.ContainsKey("credentialId") -and (-not $PsBoundParameters.ContainsKey("adapter") -and (-not $PsBoundParameters.ContainsKey("resource")))) { + $uri = "https://$vropsAppliance/suite-api/api/credentials/$credentialId" + $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders + $response + } + elseif ($PsBoundParameters.ContainsKey("credentialId") -and ($PsBoundParameters.ContainsKey("adapter"))) { + $uri = "https://$vropsAppliance/suite-api/api/credentials/$credentialId/adapters" + $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders + $response.adapterInstancesInfoDto + } + elseif ($PsBoundParameters.ContainsKey("credentialId") -and ($PsBoundParameters.ContainsKey("resource"))) { + $uri = "https://$vropsAppliance/suite-api/api/credentials/$credentialId/resources" + $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders + $response + } + else { + $uri = "https://$vropsAppliance/suite-api/api/credentials" + $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders + $response.credentialInstances + } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Resume-vRSLCMRequest - -################### End vRealize Suite Lifecycle Manager Functions #################### -######################################################################################## - - -######################################################################################### -######################### Start vRealize Automation Functions ######################### +Export-ModuleMember -Function Get-vROPSCredential -Function Request-vRAToken { +Function Add-vROPSCredential { <# .SYNOPSIS - Connects to the specified vRealize Automation and obtains authorization token + Add a credential .DESCRIPTION - The Request-vRAToken cmdlet connects to the specified vRealize Automation and obtains an authorization token. - It is required once per session before running all other cmdlets. - - .EXAMPLE - Request-vRAToken -fqdn xreg-vra01.rainpole.io -username configadmin -password VMware1! - This example shows how to connect to the vRealize Automation appliance + The Add-vROPSCredential cmdlet adds a credential to vRealize Operations Manager .EXAMPLE - Request-vRAToken -fqdn xreg-vra01.rainpole.io -username configadmin -password VMware1! -displayToken - This example shows how to connect to the vRealize Automation appliance and display the token needed for Terraform - #> + Add-vROPSCredential -json .\credentialJson + This example adds a new credential + #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$fqdn, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$username, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$password, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$tenant, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$displayToken + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$json ) - if ( -not $PsBoundParameters.ContainsKey("username") -or ( -not $PsBoundParameters.ContainsKey("password"))) { - $creds = Get-Credential # Request Credentials - $username = $creds.UserName.ToString() - $password = $creds.GetNetworkCredential().password - } - - $vraBasicHeaders = createBasicAuthHeader $username $password - $Global:vraAppliance = $fqdn - Try { - # Validate credentials by executing an API call - $uri = "https://$vraAppliance/csp/gateway/am/api/login?access_token" - if ($PsBoundParameters.ContainsKey("tenant")) { - $body = "{ ""username"":""$username"",""password"":""$password"",""domain"":""$tenant""}" - } - else { - $body = "{ ""username"":""$username"",""password"":""$password""}" - } - - if ($PSEdition -eq 'Core') { - $vraResponse = Invoke-WebRequest -Method POST -Uri $uri -Headers $vraBasicHeaders -Body $body -SkipCertificateCheck # PS Core has -SkipCertificateCheck implemented, PowerShell 5.x does not - } - else { - $vraResponse = Invoke-WebRequest -Method POST -Uri $uri -Headers $vraBasicHeaders -Body $body - } - - if ($vraResponse.StatusCode -eq 200) { - $Global:vraHeaders = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" - $vraHeaders.Add("Accept", "application/json") - $vraHeaders.Add("Content-Type", "application/json") - $vraHeaders.Add("Authorization", "Bearer " + $vraResponse.Headers.'Csp-Auth-Token') - Write-Output "Successfully connected to vRealize Automation: $vraAppliance" - if ($PsBoundParameters.ContainsKey("displayToken")) { - Write-Output "`n---------Refresh Token---------" - ((Select-String -InputObject $vraResponse -Pattern '"refresh_token":') -Split ('"'))[3] - Write-Output "-------------------------------`n" + 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://$vropsAppliance/suite-api/api/credentials" + $response = Invoke-RestMethod -Method 'POST' -Uri $Uri -Headers $vropsHeaders -Body $body + $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Request-vRAToken +Export-ModuleMember -Function Add-vROPSCredential -Function Get-vRAOrganizationId { +Function Remove-vROPSCredential { <# .SYNOPSIS - Get the organization ID for the logged in user + Delete a credential .DESCRIPTION - The Get-vRAOrganizationId cmdlet gets the organization Id for the logged in user + The Remove-vROPSCredential cmdlet deletes a credential from vRealize Operations Manager .EXAMPLE - Get-vRAOrganizationId - This example gets organization Id for the logged in user + Remove-vROPSCredential -credentialId + This example deletes a credential #> + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$credentialId + ) + Try { - $uri = "https://$vraAppliance/csp/gateway/am/api/loggedin/user/orgs" - $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vraHeaders - $response.refLinks + $uri = "https://$vropsAppliance/suite-api/api/credentials/$credentialId" + $response = Invoke-RestMethod -Method 'DELETE' -Uri $Uri -Headers $vropsHeaders } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-vRAOrganizationId +Export-ModuleMember -Function Remove-vROPSCredential -Function Get-vRAOrganizationDisplayName { +Function Get-vROPSCurrency { <# .SYNOPSIS - Get the organization display name + Get the currency configuration .DESCRIPTION - The Get-vRAOrganizationDisplayName cmdlet gets the organization display name + The Get-vROPSCurrency cmdlet gets the currency configuration for vRealize Operations Manager .EXAMPLE - Get-vRAOrganizationDisplayName -orgId - This example gets organization display name for the organization Id provided + Get-vROPSCurrency + This example gets the currency configuration for vRealize Operations Manager #> - Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId - ) - Try { - $uri = "https://$vraAppliance/csp/gateway/am/api/orgs/$orgId" - $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vraHeaders + $uri = "https://$vropsAppliance/suite-api/api/costconfig/currency" + $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-vRAOrganizationDisplayName +Export-ModuleMember -Function Get-vROPSCurrency -Function Set-vRAOrganizationDisplayName { +Function Set-vROPSCurrency { <# .SYNOPSIS - Configures the organization display name + Applies the currency configuration .DESCRIPTION - The Set-vRAOrganizationDisplayName cmdlet sets the organization display name + The Set-vROPSCurrency cmdlet applies the currency configuration for vRealize Operations Manager. NOTE: Once + applied for an instance it cannot be changed. .EXAMPLE - Set-vRAOrganizationDisplayName -orgId -displayName - This example configures the organization display name for the organization Id provided + Set-vROPSCurrency + This example gets the currency configuration for vRealize Operations Manager #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$displayName + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$currency ) Try { - $uri = "https://$vraAppliance/csp/gateway/am/api/orgs/$orgId" - $json = '{ "displayName": "'+ $displayName +'" }' - $response = Invoke-RestMethod -Method 'PATCH' -Uri $Uri -Headers $vraHeaders -Body $json - $response.refLink + $uri = "https://$vropsAppliance/suite-api/api/costconfig/currency" + $body = '{ + "code" : "'+ $currency +'" + }' + $response = Invoke-RestMethod -Method 'POST' -Uri $Uri -Headers $vropsHeaders -Body $body + $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Set-vRAOrganizationDisplayName +Export-ModuleMember -Function Set-vROPSCurrency -Function Get-vRACloudAccount { +Function Get-vROPSSolution { <# .SYNOPSIS - Get cloud accounts + Get list of solutions .DESCRIPTION - The Get-vRACloudAccount cmdlet all cloud accounts within the current organization + The Get-vROPSSolution cmdlet gets a list of solutions in vRealize Operations Manager .EXAMPLE - Get-vRACloudAccount - This example gets all cloud accounts within the current organization + Get-vROPSSolution + This example gets a list of all solutions .EXAMPLE - Get-vRACloudAccount -type vsphere - This example gets all vsphere cloud accounts within the current organization, supports vsphere, vmw, gcp, nsx-v, nsx-t, aws and azure + Get-vROPSSolution -solutionId "vSphere" + This example gets a list of all solutions #> Param ( - [Parameter (Mandatory = $false)] [ValidateSet("vsphere","vmc","gcp","nsx-v","nsx-t","aws","azure")] [ValidateNotNullOrEmpty()] [String]$type + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$solutionId, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$adapterKind, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$license ) Try { - if ($PsBoundParameters.ContainsKey("type")) { - if ($type -eq "vsphere") {$uri = "https://$vraAppliance/iaas/api/cloud-accounts-vsphere"} - if ($type -eq "vmc") {$uri = "https://$vraAppliance/iaas/api/cloud-accounts-vmc"} - if ($type -eq "gcp") {$uri = "https://$vraAppliance/iaas/api/cloud-accounts-gcp"} - if ($type -eq "nsx-v") {$uri = "https://$vraAppliance/iaas/api/cloud-accounts-nsx-v"} - if ($type -eq "nsx-t") {$uri = "https://$vraAppliance/iaas/api/cloud-accounts-nsx-t"} - if ($type -eq "aws") {$uri = "https://$vraAppliance/iaas/api/cloud-accounts-aws"} - if ($type -eq "azure") {$uri = "https://$vraAppliance/iaas/api/cloud-accounts-azure"} - $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vraHeaders - $response.content + if ($PsBoundParameters.ContainsKey("solutionId") -and (-not $PsBoundParameters.ContainsKey("adapterKind") -and (-not $PsBoundParameters.ContainsKey("license")))) { + $uri = "https://$vropsAppliance/suite-api/api/solutions/$solutionId" + $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders + $response + } + elseif ($PsBoundParameters.ContainsKey("solutionId") -and ($PsBoundParameters.ContainsKey("adapterKind"))) { + $uri = "https://$vropsAppliance/suite-api/api/solutions/$solutionId/adapterkinds" + $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders + $response.'adapter-kind' + } + elseif ($PsBoundParameters.ContainsKey("solutionId") -and ($PsBoundParameters.ContainsKey("license"))) { + $uri = "https://$vropsAppliance/suite-api/api/solutions/$solutionId/licenses" + $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders + $response.solutionLicenses } else { - $uri = "https://$vraAppliance/iaas/api/cloud-accounts" - $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vraHeaders - $response.content + $uri = "https://$vropsAppliance/suite-api/api/solutions" + $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders + $response.solution } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-vRACloudAccount +Export-ModuleMember -Function Get-vROPSSolution -Function Remove-vRACloudAccount { +Function Import-vROPSManagementPack { <# .SYNOPSIS - Remove a cloud account + Upload a management pack .DESCRIPTION - The Remove-vRACloudAccount cmdlet removes a cloud account within the current organization + The Import-vROPSManagementPack cmdlet uploads a management pack into vRealize Operations Manager .EXAMPLE - Remove-vRACloudAccount -id - This example removes the cloud account with the ID within the current organization + Import-vROPSManagementPack -server xint-vrops01.rainpole.io -username admin -password VMw@re1! -pak .\managementPack.pak + This example uploads the management pack provided to vRealize Operations Manager #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$username, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$password, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pak ) Try { - $uri = "https://$vraAppliance/iaas/api/cloud-accounts/$id" - $response = Invoke-RestMethod -Method 'DELETE' -Uri $Uri -Headers $vraHeaders - $response + if ($PsBoundParameters.ContainsKey("pak")) { + if (!(Test-Path $pak)) { + Throw "Management Pack file $pak not found" + } + } + + $uri = "https://$server/casa/upgrade/cluster/pak/reserved/operation/upload?pak_handling_advice=CLOBBER" + $contentType = "application/octet-stream" + + Add-Type -AssemblyName System.Net.Http + $httpClientHandler = New-Object System.Net.Http.HttpClientHandler + + $networkCredential = New-Object System.Net.NetworkCredential @($userName, $password) + $httpClientHandler.Credentials = $networkCredential + $httpClient = New-Object System.Net.Http.Httpclient $httpClientHandler + + $packageFileStream = New-Object System.IO.FileStream @($pak, [System.IO.FileMode]::Open) + + $fileHeaderValue = New-Object System.Net.Http.Headers.ContentDispositionHeaderValue "form-data" + $fileHeaderValue.Name = "contents" + $fileHeaderValue.FileName = (Split-Path $pak -leaf) + + $streamContent = New-Object System.Net.Http.StreamContent $packageFileStream + $streamContent.Headers.ContentDisposition = $fileHeaderValue + $streamContent.Headers.ContentType = New-Object System.Net.Http.Headers.MediaTypeHeaderValue $contentType + + $content = New-Object System.Net.Http.MultipartFormDataContent + $content.Add($streamContent) + + $response = $httpClient.PostAsync($uri, $content).Result + + if (!$response.IsSuccessStatusCode) { + $responseBody = $response.Content.ReadAsStringAsync().Result + $errorMessage = "Status code {0}. Reason {1}. Server reported the following message: {2}." -f $response.StatusCode, $response.ReasonPhrase, $responseBody + Throw [System.Net.Http.HttpRequestException] $errorMessage + } + Return $response.Content.ReadAsStringAsync().Result } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Remove-vRACloudAccount - -########################## End vRealize Automation Functions ######################### -######################################################################################## - - -######################################################################################## -#################### Start vRealize Operations Manager Functions ##################### +Export-ModuleMember -Function Import-vROPSManagementPack -Function Request-vROPSToken { +Function Install-vROPSManagementPack { <# .SYNOPSIS - Connects to the specified vRealize Operations Manager and obtains authorization token + Install a management pack .DESCRIPTION - The Request-vROPSToken cmdlet connects to the specified vRealize Operations Manager and obtains an authorization token. - It is required once per session before running all other cmdlets. + The Install-vROPSManagementPack cmdlet installs a management pack in vRealize Operations Manager .EXAMPLE - Request-vROPSToken -fqdn xint-vrops01.rainpole.io -username admin -password VMw@re1! - This example shows how to connect to the vRealize Operations Manager appliance - #> + Install-vROPSManagementPack -server xint-vrops01.rainpole.io -username admin -password VMw@re1! -pakId SDDCHealth-8115995854 + This example installs the management pack in vRealize Operations Manager + #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$fqdn, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$username, - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$password + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$password, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pakId ) - if ( -not $PsBoundParameters.ContainsKey("username") -or ( -not $PsBoundParameters.ContainsKey("password"))) { - $creds = Get-Credential # Request Credentials - $username = $creds.UserName.ToString() - $password = $creds.GetNetworkCredential().password - } - Try { - $Global:vropsAppliance = $fqdn - $Global:vropsHeaders = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" - $vropsHeaders.Add("Accept", "application/json") - $vropsHeaders.Add("Content-Type", "application/json") - $uri = "https://$vropsAppliance/suite-api/api/auth/token/acquire" - - $body = "{ - `n `"username`" : `"$username`", - `n `"authSource`" : `"LOCAL`", - `n `"password`" : `"$password`" - `n}" - - if ($PSEdition -eq 'Core') { - $vropsResponse = Invoke-RestMethod -Uri $uri -Method 'POST' -Headers $vropsHeaders -Body $body -SkipCertificateCheck # PS Core has -SkipCertificateCheck implemented, PowerShell 5.x does not - } - else { - $vropsResponse = Invoke-RestMethod -Uri $uri -Method 'POST' -Headers $vropsHeaders -Body $body - } + $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username, $password))) # Create Basic Authentication Encoded Credentials + $vropsBasicHeaders = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" + $vropsBasicHeaders.Add("Authorization", "Basic $base64AuthInfo") + $vropsBasicHeaders.Add("Content-Type", "application/json") - if ($vropsResponse.token) { - $vropsHeaders.Add("Authorization", "vRealizeOpsToken " + $vropsResponse.token) - Write-Output "Successfully connected to vRealize Operations Manager: $vropsAppliance" - } + $response = Invoke-RestMethod "https://$server/casa/upgrade/cluster/pak/$pakId/operation/install" -Method 'POST' -Headers $vropsBasicHeaders + $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Request-vROPSToken +Export-ModuleMember -Function Install-vROPSManagementPack -Function Get-vROPSCollector { +Function Set-vROPSManagementPack { <# .SYNOPSIS - Get list of collectors + Activate / Deactivate a management pack .DESCRIPTION - The Get-vROPSCollector cmdlet gets a list of collectors in vRealize Operations Manager + The Set-vROPSManagementPack cmdlet activates or deactivates a management pack in vRealize Operations Manager .EXAMPLE - Get-vROPSCollector - This example gets a list of collectors + Set-vROPSManagementPack -server xint-vrops01.rainpole.io -username admin -password VMw@re1! -pakId PingAdapter -version "8.4.0.17863953" -status enable + This example activates the Ping management pack in vRealize Operations Manager - .EXAMPLE - Get-vROPSCollector -id - This example gets details of a collector by its ID + Set-vROPSManagementPack -server xint-vrops01.rainpole.io -username admin -password VMw@re1! -pakId PingAdapter -version "8.4.0.17863953" -status disable + This example deactivates the Ping management pack in vRealize Operations Manager #> Param ( - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$username, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$password, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pakId, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$version, + [Parameter (Mandatory = $true)] [ValidateSet("enable","disable")] [ValidateNotNullOrEmpty()] [String]$status ) Try { - if ($PsBoundParameters.ContainsKey("id")) { - $uri = "https://$vropsAppliance/suite-api/api/collectors/$id/adapters" - $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders - $response.adapterInstancesInfoDto - } - else { - $uri = "https://$vropsAppliance/suite-api/api/collectors" - $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders - $response.collector - } + $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username, $password))) # Create Basic Authentication Encoded Credentials + $vropsBasicHeaders = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" + $vropsBasicHeaders.Add("Authorization", "Basic $base64AuthInfo") + $vropsBasicHeaders.Add("Content-Type", "application/json") + + $body = '{ + "pak_id" : "'+ $pakId +'", + "version" : "'+ $version +'", + "force_content_update": true + }' + $response = Invoke-RestMethod "https://$server/casa/upgrade/cluster/pak/operation/$status" -Method 'POST' -Headers $vropsBasicHeaders -Body $body + $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-vROPSCollector +Export-ModuleMember -Function Set-vROPSManagementPack -Function Get-vROPSCollectorGroup { +Function Get-vROPSManagementPack { <# .SYNOPSIS - Get list of collector groups + Get installed management packs .DESCRIPTION - The Get-vROPSCollectorGroup cmdlet gets a list of collector groups in vRealize Operations Manager - - .EXAMPLE - Get-vROPSCollectorGroup - This example gets a list of collector groups + The Get-vROPSManagementPack cmdlet gets a list of installed management packs in vRealize Operations Manager .EXAMPLE - Get-vROPSCollectorGroup -id - This example gets details of a collector by its ID + Get-vROPSManagementPack -server xint-vrops01.rainpole.io -username admin -password VMw@re1! + This example gets a list of all the management packs installed in vRealize Operations Manager #> Param ( - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$username, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$password ) Try { - if ($PsBoundParameters.ContainsKey("id")) { - $uri = "https://$vropsAppliance/suite-api/api/collectorgroups/$id" - $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders - $response - } - else { - $uri = "https://$vropsAppliance/suite-api/api/collectorgroups" - $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders - $response.collectorGroups - } + $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username, $password))) # Create Basic Authentication Encoded Credentials + $vropsBasicHeaders = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" + $vropsBasicHeaders.Add("Authorization", "Basic $base64AuthInfo") + $vropsBasicHeaders.Add("Content-Type", "application/json") + + $response = Invoke-RestMethod "https://$server/casa/upgrade/cluster/pak/reserved/list" -Method 'GET' -Headers $vropsBasicHeaders + $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-vROPSCollectorGroup +Export-ModuleMember -Function Get-vROPSManagementPack -Function Add-vROPSCollectorGroup { +Function Get-vROPSManagementPackStatus { <# .SYNOPSIS - Add a collector groups + Get install status of management pack .DESCRIPTION - The Add-vROPSCollectorGroup cmdlet adds a new collector groups in vRealize Operations Manager + The Get-vROPSManagementPackStatus cmdlet gets the status of the install of a management pack in vRealize Operations Manager .EXAMPLE - Add-vROPSCollectorGroup -name sfo-remote-collectors -description "Remote Collector Group for SFO" -collectorIds "1,2" - This example gets a list of collector groups + Get-vROPSManagementPackStatus -server xint-vrops01.rainpole.io -username admin -password VMw@re1! -pakId SDDCHealth-8115995854 + This example uploads the management pack provided to vRealize Operations Manager #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$name, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$description, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$collectorIds + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$username, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$password, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pakId ) - Try { - $uri = "https://$vropsAppliance/suite-api/api/collectorgroups" - if ($description) { - $body = '{ "name" : "'+ $name +'", "description" : "'+ $description +'", "collectorId" : ['+ $collectorIds +'], "systemDefined" : false }' - } - else { - $body = '{ "name" : "'+ $name +'", "collectorId" : ['+ $collectorIds +'], "systemDefined" : false }' - } - $response = Invoke-RestMethod -Method 'POST' -Uri $Uri -Headers $vropsHeaders -Body $body + Try { + $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username, $password))) # Create Basic Authentication Encoded Credentials + $vropsBasicHeaders = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" + $vropsBasicHeaders.Add("Authorization", "Basic $base64AuthInfo") + $response = Invoke-RestMethod "https://$server/casa/upgrade/cluster/pak/$pakId/status" -Method 'GET' -Headers $vropsBasicHeaders + $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Add-vROPSCollectorGroup +Export-ModuleMember -Function Get-vROPSManagementPackStatus -Function Remove-vROPSCollectorGroup { +Function Get-vROPSManagementPackActivity { <# .SYNOPSIS - Delete a collector group + Get current activity .DESCRIPTION - The Remove-vROPSCollectorGroup cmdlet deletes a collector group in vRealize Operations Manager + The Get-vROPSManagementPackActivity cmdlet gets the current activity for management packs in vRealize Operations Manager .EXAMPLE - Remove-vROPSCollectorGroup -id - This example deletes a gollector group + Get-vROPSManagementPackActivity -server xint-vrops01.rainpole.io -username admin -password VMw@re1! + This example gets the current management pack activity in vRealize Operations Manager #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$username, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$password ) Try { - $uri = "https://$vropsAppliance/suite-api/api/collectorgroups/$id" - $response = Invoke-RestMethod -Method 'DELETE' -Uri $Uri -Headers $vropsHeaders + + $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username, $password))) # Create Basic Authentication Encoded Credentials + $vropsBasicHeaders = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" + $vropsBasicHeaders.Add("Authorization", "Basic $base64AuthInfo") + + $response = Invoke-RestMethod "https://$server/casa/upgrade/cluster/pak/reserved/current_activity" -Method 'GET' -Headers $vropsBasicHeaders + $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Remove-vROPSCollectorGroup +Export-ModuleMember -Function Get-vROPSManagementPackActivity -Function Get-vROPSAdapter { +Function Get-vROPSAlertPlugin { <# .SYNOPSIS - Get list of adapters + Get the alert plugins .DESCRIPTION - The Get-vROPSAdapter cmdlet gets a list of adapters in vRealize Operations Manager - - .EXAMPLE - Get-vROPSAdapter - This example gets a list of all adapters + The Get-vROPSAlertPlugin cmdlet gets the configured alert plugins in vRealize Operations Manager .EXAMPLE - Get-vROPSAdapter -id - This example gets details of an adapter by its ID + Get-vROPSAlertPlugin + This example gets a list of the alert plugins configure in vRealize Operations Manager #> - Param ( - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id - ) - Try { - if ($PsBoundParameters.ContainsKey("id")) { - $uri = "https://$vropsAppliance/suite-api/api/adapters/$id" - $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.adapterInstancesInfoDto - } + $uri = "https://$vropsAppliance/suite-api/api/alertplugins" + $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vropsHeaders + $response.notificationPluginInstances } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-vROPSAdapter +Export-ModuleMember -Function Get-vROPSAlertPlugin -Function Set-vROPSAdapter { +Function Add-vROPSAlertPlugin { <# .SYNOPSIS - Update an adapter + Create an alert plugin .DESCRIPTION - The Set-vROPSAdapter cmdlet updates the adapters configuration in vRealize Operations Manager + The Add-vROPSAlertPlugin cmdlet creates a new alert plugin in vRealize Operations Manager .EXAMPLE - Set-vROPSAdapter -json .\adapterJson - This example updates the details of an adapter + Add-vROPSAlertPlugin -json .\alertPlugin.json + This example adds a new alert plugin based on the JSON provide to vRealize Operations Manager #> Param ( @@ -14092,27 +20307,27 @@ 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 + + $uri = "https://$vropsAppliance/suite-api/api/alertplugins" + $response = Invoke-RestMethod -Method 'POST' -Uri $uri -Headers $vropsHeaders -Body $body } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Set-vROPSAdapter +Export-ModuleMember -Function Add-vROPSAlertPlugin -Function Add-vROPSAdapter { +Function Set-vROPSAlertPlugin { <# .SYNOPSIS - Add an adapter + Updates an alert plugin .DESCRIPTION - The Add-vROPSAdapter cmdlet adds an adapter to vRealize Operations Manager + The Set-vROPSAlertPlugin cmdlet updates an existing alert plugin in vRealize Operations Manager .EXAMPLE - Add-vROPSAdapter -json .\adapterJson - This example adds an adapter useing the json specification file + Set-vROPSAlertPlugin -json .\alertPluginUpdate.json + This example updates the configuration of an existing alert plugin based on the JSON provide to vRealize Operations Manager #> Param ( @@ -14128,289 +20343,439 @@ Function Add-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 'POST' -Uri $Uri -Headers $vropsHeaders -Body $body + + $uri = "https://$vropsAppliance/suite-api/api/alertplugins" + $response = Invoke-RestMethod -Method 'PUT' -Uri $uri -Headers $vropsHeaders -Body $body $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Add-vROPSAdapter +Export-ModuleMember -Function Set-vROPSAlertPlugin -Function Start-vROPSAdapter { +Function Remove-vROPSAlertPlugin { <# .SYNOPSIS - Starts collection of adapter + Delete an alert plugin .DESCRIPTION - The Start-vROPSAdapter cmdlet starts the collection of an adapter in vRealize Operations Manager + The Remove-vROPSAlertPlugin cmdlet deletes an existing alert plugin from vRealize Operations Manager .EXAMPLE - Start-vROPSAdapter -adpaterId - This example starts the adpater by id + Remove-vROPSAlertPlugin -plugId + This example deletes the alert plugin with the plugin ID provide to vRealize Operations Manager #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$adapterId + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pluginId ) Try { - $uri = "https://$vropsAppliance/suite-api/api/adapters/$adapterId/monitoringstate/start" - $response = Invoke-RestMethod -Method 'PUT' -Uri $Uri -Headers $vropsHeaders + $uri = "https://$vropsAppliance/suite-api/api/alertplugins/$pluginId" + $response = Invoke-RestMethod -Method 'DELETE' -Uri $uri -Headers $vropsHeaders $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Start-vROPSAdapter +Export-ModuleMember -Function Remove-vROPSAlertPlugin -Function Stop-vROPSAdapter { +Function Set-vROPSAlertPluginStatus { <# .SYNOPSIS - Stops collection of adapter + Enable/Disable alert plugin .DESCRIPTION - The Stop-vROPSAdapter cmdlet starts the collection of an adapter in vRealize Operations Manager + The Set-vROPSAlertPluginStatus cmdlet Enables/Disables an existing alert plugin from vRealize Operations Manager .EXAMPLE - Stop-vROPSAdapter -adpaterId - This example starts the adpater by id + Set-vROPSAlertPluginStatus -plugId -status true + This example deletes the alert plugin with the plugin ID provide to vRealize Operations Manager #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$adapterId + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pluginId, + [Parameter (Mandatory = $true)] [ValidateSet("false","true")] [ValidateNotNullOrEmpty()] [String]$status ) Try { - $uri = "https://$vropsAppliance/suite-api/api/adapters/$adapterId/monitoringstate/stop" - $response = Invoke-RestMethod -Method 'PUT' -Uri $Uri -Headers $vropsHeaders + $uri = "https://$vropsAppliance/suite-api/api/alertplugins/$pluginId/enable/$status" + $response = Invoke-RestMethod -Method 'PUT' -Uri $uri -Headers $vropsHeaders $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Stop-vROPSAdapter +Export-ModuleMember -Function Set-vROPSAlertPluginStatus -Function Get-vROPSCredential { +Function Get-vROPSAuthSource { <# .SYNOPSIS - Get credentials + Get all the available authentication sources in the system .DESCRIPTION - The Get-vROPSCredential cmdlet gets credentials from vRealize Operations Manager + The Get-vROPSAuthSource cmdlet gets all the available authentication sources in vRealize Operations Manager .EXAMPLE - Get-vROPSCredential - This example gets all credentials from vRealize Operations Manager + Get-vROPSAuthSource + This example gets a list of all available authentication sources + + .EXAMPLE + Get-vROPSAuthSource -sourceId + This example gets detailed information about the provided authentication source #> Param ( - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$credentialId, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$adapter, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$resource + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$sourceId ) Try { - if ($PsBoundParameters.ContainsKey("credentialId") -and (-not $PsBoundParameters.ContainsKey("adapter") -and (-not $PsBoundParameters.ContainsKey("resource")))) { - $uri = "https://$vropsAppliance/suite-api/api/credentials/$credentialId" - $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders + if ($PsBoundParameters.ContainsKey("sourceId")) { + $uri = "https://$vropsAppliance/suite-api/api/auth/sources/$sourceId" + $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vropsHeaders $response } - elseif ($PsBoundParameters.ContainsKey("credentialId") -and ($PsBoundParameters.ContainsKey("adapter"))) { - $uri = "https://$vropsAppliance/suite-api/api/credentials/$credentialId/adapters" - $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders - $response.adapterInstancesInfoDto + else { + $uri = "https://$vropsAppliance/suite-api/api/auth/sources" + $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vropsHeaders + $response.sources } - elseif ($PsBoundParameters.ContainsKey("credentialId") -and ($PsBoundParameters.ContainsKey("resource"))) { - $uri = "https://$vropsAppliance/suite-api/api/credentials/$credentialId/resources" - $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Get-vROPSAuthSource + +Function Get-vROPSAuthRole { + <# + .SYNOPSIS + Get all the roles available in the system + + .DESCRIPTION + The Get-vROPSAuthRole cmdlet gets all the roles available in vRealize Operations Manager + + .EXAMPLE + Get-vROPSAuthRole + This example gets all the roles available + #> + + Param ( + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$name + ) + + Try { + if ($PsBoundParameters.ContainsKey("name")) { + $uri = "https://$vropsAppliance/suite-api/api/auth/roles/$name" + $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vropsHeaders $response } else { - $uri = "https://$vropsAppliance/suite-api/api/credentials" - $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders - $response.credentialInstances + $uri = "https://$vropsAppliance/suite-api/api/auth/roles" + $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vropsHeaders + $response.userRoles } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-vROPSCredential +Export-ModuleMember -Function Get-vROPSAuthRole -Function Add-vROPSCredential { +Function Get-vROPSUserGroup { <# .SYNOPSIS - Add a credential + Get list of local user groups using identifiers or/and names .DESCRIPTION - The Add-vROPSCredential cmdlet adds a credential to vRealize Operations Manager + The Get-vROPSUserGroup cmdlet gets list of local user groups in vRealize Operations Manager .EXAMPLE - Add-vROPSCredential -json .\credentialJson - This example adds a new credential + Get-vROPSUserGroup + This example gets a list of all available authentication sources + + .EXAMPLE + Get-vROPSUserGroup -id + This example gets detailed information about the provided user group using the ID + + .EXAMPLE + Get-vROPSUserGroup -id + This example gets detailed information about the provided user group using the name #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$json + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$name + ) Try { - 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 - } + if ($PsBoundParameters.ContainsKey("id")) { + $uri = "https://$vropsAppliance/suite-api/api/auth/usergroups?id=$id&_no_links=true" + $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders + $response + } + elseif ($PsBoundParameters.ContainsKey("name")) { + $uri = "https://$vropsAppliance/suite-api/api/auth/usergroups?name=$name&_no_links=true" + $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vropsHeaders + $response.userGroups + } + else { + $uri = "https://$vropsAppliance/suite-api/api/auth/usergroups" + $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vropsHeaders + $response.userGroups } - $uri = "https://$vropsAppliance/suite-api/api/credentials" - $response = Invoke-RestMethod -Method 'POST' -Uri $Uri -Headers $vropsHeaders -Body $body - $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Add-vROPSCredential +Export-ModuleMember -Function Get-vROPSUserGroup -Function Remove-vROPSCredential { +Function Add-vROPSUserGroup { <# .SYNOPSIS - Delete a credential + Import user group from an authentication source .DESCRIPTION - The Remove-vROPSCredential cmdlet deletes a credential from vRealize Operations Manager + The Add-vROPSUserGroup cmdlet imports a user group from the authentication source into vRealize Operations + Manager .EXAMPLE - Remove-vROPSCredential -credentialId - This example deletes a credential + Add-vROPSUserGroup -sourceId -userGroup -role + This example imports a user group from the authentication source and assigns the Administrator Role #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$credentialId + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sourceId, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$userGroup, + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$role ) Try { - $uri = "https://$vropsAppliance/suite-api/api/credentials/$credentialId" - $response = Invoke-RestMethod -Method 'DELETE' -Uri $Uri -Headers $vropsHeaders + $uri = "https://$vropsAppliance/suite-api/api/auth/usergroups" + $body = '{ + "authSourceId" : "' + $sourceId + '", + "name" : "' + $userGroup + '", + "role-permissions" : [ { + "roleName" : "' + $role + '", + "allowAllObjects" : true + } ] + }' + $response = Invoke-RestMethod -Method 'POST' -Uri $uri -Headers $vropsHeaders -Body $body + $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Remove-vROPSCredential +Export-ModuleMember -Function Add-vROPSUserGroup -Function Get-vROPSCurrency { +Function Remove-vROPSUserGroup { <# .SYNOPSIS - Get the currency configuration + Deletes a user group .DESCRIPTION - The Get-vROPSCurrency cmdlet gets the currency configuration for vRealize Operations Manager + The Remove-vROPSUserGroup cmdlet deletes a user group from vRealize Operations Manager .EXAMPLE - Get-vROPSCurrency - This example gets the currency configuration for vRealize Operations Manager + Remove-vROPSUserGroup -id + This example deletes a user group from vRealize Operations Manager #> + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id + ) + Try { - $uri = "https://$vropsAppliance/suite-api/api/costconfig/currency" - $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders + $uri = "https://$vropsAppliance/suite-api/api/auth/usergroups/$id" + $response = Invoke-RestMethod -Method 'DELETE' -Uri $uri -Headers $vropsHeaders $response } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-vROPSCurrency +Export-ModuleMember -Function Remove-vROPSUserGroup -Function Set-vROPSCurrency { +Function Search-vROPSUserGroup { <# .SYNOPSIS - Applies the currency configuration + Search for a user group in the source .DESCRIPTION - The Set-vROPSCurrency cmdlet applies the currency configuration for vRealize Operations Manager. NOTE: Once - applied for an instance it cannot be changed. + The Search-vROPSUserGroup cmdlet searches for a user group in the source in vRealize Operations Manager .EXAMPLE - Set-vROPSCurrency - This example gets the currency configuration for vRealize Operations Manager + Search-vROPSUserGroup -sourceId 6d971ad0-a979-4dc1-81af-e77f6c8c158c -domain sfo.rainpole.io -groupName "gg-vrops-read-only@sfo.rainpole.io" + This example searches for a user group in the source defined by source ID #> Param ( - [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$currency + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$sourceId, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$domain, + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$groupName ) Try { - $uri = "https://$vropsAppliance/suite-api/api/costconfig/currency" + $uri = "https://$vropsAppliance/suite-api/api/auth/sources/$sourceId/usergroups/search" $body = '{ - "code" : "'+ $currency +'" - }' - $response = Invoke-RestMethod -Method 'POST' -Uri $Uri -Headers $vropsHeaders -Body $body - $response + "domain": "' + $domain + '", + "name": "' + $groupName + '" + }' + $response = Invoke-RestMethod -Method 'POST' -Uri $uri -Headers $vropsHeaders -Body $body + $response.'usergroup-search-response' } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Set-vROPSCurrency +Export-ModuleMember -Function Search-vROPSUserGroup -Function Get-vROPSSolution { +Function Get-vROPSNotification { <# .SYNOPSIS - Get list of solutions + Get list of all notifications .DESCRIPTION - The Get-vROPSSolution cmdlet gets a list of solutions in vRealize Operations Manager + The Get-vROPSNotification cmdlet gets list of all notifications in vRealize Operations Manager .EXAMPLE - Get-vROPSSolution - This example gets a list of all solutions + Get-vROPSNotification + This example gets a list of all notifications .EXAMPLE - Get-vROPSSolution -solutionId "vSphere" - This example gets a list of all solutions + Get-vROPSNotification -id + This example gets a list of all notifications #> Param ( - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$solutionId, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$adapterKind, - [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$license + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id + ) Try { - if ($PsBoundParameters.ContainsKey("solutionId") -and (-not $PsBoundParameters.ContainsKey("adapterKind") -and (-not $PsBoundParameters.ContainsKey("license")))) { - $uri = "https://$vropsAppliance/suite-api/api/solutions/$solutionId" - $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders + if ($PsBoundParameters.ContainsKey("id")) { + $uri = "https://$vropsAppliance/suite-api/api/notifications/rules/$id" + $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vropsHeaders $response } - elseif ($PsBoundParameters.ContainsKey("solutionId") -and ($PsBoundParameters.ContainsKey("adapterKind"))) { - $uri = "https://$vropsAppliance/suite-api/api/solutions/$solutionId/adapterkinds" - $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders - $response.'adapter-kind' + else { + $uri = "https://$vropsAppliance/suite-api/api/notifications/rules" + $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vropsHeaders + $response.rules } - elseif ($PsBoundParameters.ContainsKey("solutionId") -and ($PsBoundParameters.ContainsKey("license"))) { - $uri = "https://$vropsAppliance/suite-api/api/solutions/$solutionId/licenses" - $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders - $response.solutionLicenses + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Get-vROPSNotification + +Function New-vROPSNotification { + <# + .SYNOPSIS + Creates notifications + + .DESCRIPTION + The New-vROPSNotification cmdlet creates notifications in vRealize Operations Manager + + .EXAMPLE + New-vROPSNotification -csvPath .\SampleNotifications\vropsNotifications-vcf.csv + This example adds all the notifications in the csv file + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$csvPath + ) + + if ($PsBoundParameters.ContainsKey("csvPath")) { + if (!(Test-Path $csvPath)) { + Throw "CSV File Not Found" } else { - $uri = "https://$vropsAppliance/suite-api/api/solutions" - $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders - $response.solution + $alerts = Import-CSV $csvPath | Where-Object -FilterScript { $_.alertName } + } + } + + Try { + Foreach ($alert in $alerts) { + $body = '{ + "name": "'+ $($alert.alertName) +'", + "pluginId": "'+ (Get-vROPSAlertPlugin | Where-Object {$_.name -eq $($alert.alertPluginName)}).pluginId +'", + "resourceKindFilters": [ + { + "resourceKind": "'+ $($alert.resourceKindKey) +'", + "adapterKind": "'+ $($alert.adapterKindKey) +'" + } + ], + "resourceFilters": [ ], + "alertDefinitionIdFilters": { + "values": [ "'+ $($alert.alertDefinition) +'" ] + }, + "properties": [ + { + "name": "maxNotify", + "value": "'+ $($alert.maxNotify) +'" + }, + { + "name": "delay", + "value": "'+ $($alert.delay) +'" + }, + { + "name": "emailaddr", + "value": "'+ $($alert.emailAddress) +'" + }, + { + "name": "resend", + "value": "'+ $($alert.resend) +'" + } + ] + }' + $uri = "https://$vropsAppliance/suite-api/api/notifications/rules" + if (!(Get-vROPSNotification | Where-Object {$_.name -eq $($alert.alertName)})) { + Invoke-RestMethod -Method 'POST' -Uri $uri -Headers $vropsHeaders -Body $body + } } } Catch { Write-Error $_.Exception.Message } } -Export-ModuleMember -Function Get-vROPSSolution +Export-ModuleMember -Function New-vROPSNotification + +Function Remove-vROPSNotification { + <# + .SYNOPSIS + Delete a notification + + .DESCRIPTION + The Remove-vROPSNotification cmdlet deletes a notifications in vRealize Operations Manager + + .EXAMPLE + Remove-vROPSNotification -id + This example deletes a notifications + #> + + Param ( + [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id + + ) + + Try { + $uri = "https://$vropsAppliance/suite-api/api/notifications/rules/$id" + $response = Invoke-RestMethod -Method 'DELETE' -Uri $uri -Headers $vropsHeaders + $response + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Remove-vROPSNotification #################### End vRealize Operations Manager Functions ####################### ######################################################################################## @@ -15053,6 +21418,86 @@ Function Remove-vRLIGroup { } Export-ModuleMember -Function Remove-vRLIGroup +Function Get-vRLIAlert { + <# + .SYNOPSIS + Get list of alerts + + .DESCRIPTION + The Get-vRLIGroup cmdlet gets a list of alerts + + .EXAMPLE + Get-vRLIGroup + This example gets a list alerts from vRealize Log Insight + #> + + Try { + $uri = "https://$vrliAppliance/api/v1/alerts" + $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vrliHeaders + $response + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Get-vRLIAlert + +Function New-vRLIAlert { + <# + .SYNOPSIS + Create an alert + + .DESCRIPTION + The New-vRLIAlert cmdlet creates an alert in vRealize Log Insight + + .EXAMPLE + New-vRLIAlert -json (Get-Content -Raw .\vrliAlert.json) + This example creates an alert in vRealize Log Insight based on the contents of the JSON + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$json + ) + + Try { + $uri = "https://$vrliAppliance/api/v1/alerts" + $response = Invoke-RestMethod -Method 'POST' -Uri $uri -Headers $vrliHeaders -Body $json + $response + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function New-vRLIAlert + +Function Remove-vRLIAlert { + <# + .SYNOPSIS + Delete an alerts + + .DESCRIPTION + The Get-vRLIGroup cmdlet deletes an alerts + + .EXAMPLE + Get-vRLIGroup -alertId + This example deletes an alert from vRealize Log Insight + #> + + Param ( + [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$alertId + ) + + Try { + $uri = "https://$vrliAppliance/api/v1/alerts/$alertId" + $response = Invoke-RestMethod -Method 'DELETE' -Uri $uri -Headers $vrliHeaders + $response + } + Catch { + Write-Error $_.Exception.Message + } +} +Export-ModuleMember -Function Remove-vRLIAlert + ######################### End vRealize Log Insight Functions ######################### ######################################################################################## @@ -15125,10 +21570,10 @@ Function Get-CSPPoxyAppliance { $cloudProxyOva = $PSScriptRoot + "\" + ($response.ovaLink -Split (".com/"))[1] } - if (!($ovaExists = Test-Path $cloudProxyOva)) { + if (!(Test-Path $cloudProxyOva)) { Write-Output "Starting to Download the Cloud Service Proxy OVA to '$cloudProxyOva'" (New-Object System.Net.WebClient).DownloadFile($cloudProxyUrl, $cloudProxyOva) - if ($ovaExists = Test-Path $cloudProxyOva) { + if (Test-Path $cloudProxyOva) { Write-Output "Downloaded the Cloud Service Proxy OVA to '$cloudProxyOva' Successfully" } else { @@ -15249,9 +21694,6 @@ Function cidrMaskLookup { Return $returnValue } -################### End Utility Functions #################### -############################################################### - Function checkVCFToken { if (!$accessToken) { Write-Error "API Access Token Required. Request an Access Token by running Request-VCFToken" @@ -15423,9 +21865,412 @@ Function Request-VAMISessionId Catch { Write-Error $_.Exception.Message } - } +} Export-ModuleMember -Function Request-VAMISessionId +############################ End Utility Functions ############################ +################################################################################# + + +################################################################################# +########################## Start of Test Functions ########################### + +Function Test-VCFConnection { + Param ( + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server + ) + + if (Test-Connection -ComputerName ($server) -Quiet -Count 1) { + $vcfConnection = $True + Return $vcfConnection + } + else { + Write-Error "Unable to communicate with SDDC Manager ($server), check fqdn/ip address: PRE_VALIDATION_FAILED" + $vcfConnection = $False + Return $vcfConnection + } +} +Export-ModuleMember -Function Test-VCFConnection + +Function Test-VCFAuthentication { + Param ( + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$pass + ) + + Remove-Item variable:accessToken -Force -Confirm:$false -ErrorAction Ignore + + Try { + Request-VCFToken -fqdn $server -Username $user -Password $pass -ErrorAction Ignore -ErrorVariable ErrMsg | Out-Null + if ($accessToken) { + $vcfAuthentication = $True + Return $vcfAuthentication + } + else { + Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials: PRE_VALIDATION_FAILED" + $vcfAuthentication = $False + Return $vcfAuthentication + } + } + Catch { + # Do Nothing + } +} +Export-ModuleMember -Function Test-VCFAuthentication + +Function Test-VsphereConnection { + Param ( + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server + ) + + if (Test-Connection -ComputerName ($server) -Quiet -Count 1) { + $vsphereConnection = $True + Return $vsphereConnection + } + else { + Write-Error "Unable to communicate with vCenter Server ($server), check fqdn/ip address: PRE_VALIDATION_FAILED" + $vsphereConnection = $False + Return $vsphereConnection + } +} +Export-ModuleMember -Function Test-VsphereConnection + +Function Test-VsphereAuthentication { + Param ( + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$pass + ) + + Try { + Connect-VIServer -Server $server -User $user -pass $pass | Out-Null + if ($DefaultVIServer.Name -eq $server) { + $vsphereAuthentication = $True + Return $vsphereAuthentication + } + else { + Write-Error "Unable to authenticate to vCenter Server ($server), check credentials: PRE_VALIDATION_FAILED" + $vsphereAuthentication = $False + Return $vsphereAuthentication + } + } + Catch { + # Do Nothing + } +} +Export-ModuleMember -Function Test-VsphereAuthentication + +Function Test-SSOConnection { + Param ( + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server + ) + + if (Test-Connection -ComputerName ($server) -Quiet -Count 1) { + $ssoConnection = $True + Return $ssoConnection + } + else { + Write-Error "Unable to communicate with Single-Sign On Server ($server), check fqdn/ip address: PRE_VALIDATION_FAILED" + $ssoConnection = $False + Return $ssoConnection + } +} +Export-ModuleMember -Function Test-SSOConnection + +Function Test-SSOAuthentication { + Param ( + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$pass + ) + + Try { + $Script:ssoConnectionDetail = Connect-SsoAdminServer -Server $server -User $user -Password $pass + if ($DefaultSsoAdminServers.Name -eq $server) { + $ssoAuthentication = $True + Return $ssoAuthentication + } + else { + Write-Error "Unable to authenticate to Single-Sign-On Server ($server), check credentials: PRE_VALIDATION_FAILED" + $ssoAuthentication = $False + Return $ssoAuthentication + } + } + Catch { + # Do Nothing + } +} +Export-ModuleMember -Function Test-SSOAuthentication + +Function Test-NSXTConnection { + Param ( + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server + ) + + if (Test-Connection -ComputerName ($server) -Quiet -Count 1) { + $nsxtConnection = $True + Return $nsxtConnection + } + else { + Write-Error "Unable to communicate with NSX Manager ($server), check fqdn/ip address: PRE_VALIDATION_FAILED" + $nsxtConnection = $False + Return $nsxtConnection + } +} +Export-ModuleMember -Function Test-NSXTConnection + +Function Test-NSXTAuthentication { + Param ( + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$pass + ) + + Remove-Item variable:nsxtHeaders -Force -Confirm:$false -ErrorAction Ignore + + Try { + $response = Request-NSXToken -fqdn $server -username $user -password $pass + if ($response -match "Successfully Requested") { + $nsxtAuthentication = $True + Return $nsxtAuthentication + } + else { + Write-Error "Unable to obtain access token from NSX Manager ($server), check credentials: PRE_VALIDATION_FAILED" + $nsxtAuthentication = $False + Return $nsxtAuthentication + } + } + Catch { + # Do Nothing + } +} +Export-ModuleMember -Function Test-NSXTAuthentication + +Function Test-vRSLCMConnection { + Param ( + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server + ) + + if (Test-Connection -ComputerName ($server) -Quiet -Count 1) { + $vrslcmConnection = $True + Return $vrslcmConnection + } + else { + Write-Error "Unable to communicate with vRealize Suite Lifecycle Manager ($server), check fqdn/ip address: PRE_VALIDATION_FAILED" + $vrslcmConnection = $False + Return $vrslcmConnection + } +} +Export-ModuleMember -Function Test-vRSLCMConnection + +Function Test-vRSLCMAuthentication { + Param ( + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$pass + ) + + Remove-Item variable:vrslcmHeaders -Force -Confirm:$false -ErrorAction Ignore + + Try { + Request-vRSLCMToken -fqdn $server -username $user -password $pass -ErrorAction Ignore -ErrorVariable ErrMsg | Out-Null + if ((Get-vRSLCMHealth).'vrlcm-server' -eq "UP") { + $vrslcmAuthentication = $True + Return $vrslcmAuthentication + } + else { + Write-Error "Unable to obtain access token from vRealize Suite Lifecycle Manager ($server), check credentials: PRE_VALIDATION_FAILED" + $vrslcmAuthentication = $False + Return $vrslcmAuthentication + } + } + Catch { + # Do Nothing + } +} +Export-ModuleMember -Function Test-vRSLCMAuthentication + +Function Test-vROPSConnection { + Param ( + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server + ) + + if (Test-Connection -ComputerName ($server) -Quiet -Count 1) { + $vropsConnection = $True + Return $vropsConnection + } + else { + Write-Error "Unable to communicate with vRealize Operations Manager ($server), check fqdn/ip address: PRE_VALIDATION_FAILED" + $vropsConnection = $False + Return $vropsConnection + } +} +Export-ModuleMember -Function Test-vROPSConnection + +Function Test-vROPSAuthentication { + Param ( + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$pass + ) + + Remove-Item variable:vropsHeaders -Force -Confirm:$false -ErrorAction Ignore + + Try { + Request-vROPSToken -fqdn $server -username $user -password $pass | Out-Null + if ($vropsHeaders.Authorization) { + $vropsAuthentication = $True + Return $vropsAuthentication + } + else { + Write-Error "Unable to obtain access token from vRealize Operations Manager ($server), check credentials: PRE_VALIDATION_FAILED" + $vropsAuthentication = $False + Return $vropsAuthentication + } + } + Catch { + # Do Nothing + } +} +Export-ModuleMember -Function Test-vROPSAuthentication + +Function Test-vRLIConnection { + Param ( + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server + ) + + if (Test-Connection -ComputerName ($server) -Quiet -Count 1) { + $vrliConnection = $True + Return $vrliConnection + } + else { + Write-Error "Unable to communicate with vRelize Log Insight ($server), check fqdn/ip address: PRE_VALIDATION_FAILED" + $vrliConnection = $False + Return $vrliConnection + } +} +Export-ModuleMember -Function Test-vRLIConnection + +Function Test-vRLIAuthentication { + Param ( + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$pass + ) + + Remove-Item variable:vrliHeaders -Force -Confirm:$false -ErrorAction Ignore + + Try { + Request-vRLIToken -fqdn $server -Username $user -Password $pass -ErrorAction Ignore -ErrorVariable ErrMsg | Out-Null + if ($vrliHeaders.Authorization) { + $vrliAuthentication = $True + Return $vrliAuthentication + } + else { + Write-Error "Unable to obtain access token from vRealize Log Insight ($server), check credentials: PRE_VALIDATION_FAILED" + $vrliAuthentication = $False + Return $vrliAuthentication + } + } + Catch { + # Do Nothing + } +} +Export-ModuleMember -Function Test-vRLIAuthentication + +Function Test-vRAConnection { + Param ( + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server + ) + + if (Test-Connection -ComputerName ($server) -Quiet -Count 1) { + $vraConnection = $True + Return $vraConnection + } + else { + Write-Error "Unable to communicate with vRelize Automation ($server), check fqdn/ip address: PRE_VALIDATION_FAILED" + $vraConnection = $False + Return $vraConnection + } +} +Export-ModuleMember -Function Test-vRAConnection + +Function Test-vRAAuthentication { + Param ( + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$pass + ) + + Remove-Item variable:vraHeaders -Force -Confirm:$false -ErrorAction Ignore + + Try { + Request-vRAToken -fqdn $server -Username $user -Password $pass | Out-Null + if ($vraHeaders.Authorization) { + $vraAuthentication = $True + Return $vraAuthentication + } + else { + Write-Error "Unable to obtain access token from vRealize Automation ($server), check credentials: PRE_VALIDATION_FAILED" + $vraAuthentication = $False + Return $vraAuthentication + } + } + Catch { + # Do Nothing + } +} +Export-ModuleMember -Function Test-vRAAuthentication + +Function Test-WSAConnection { + Param ( + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server + ) + + if (Test-Connection -ComputerName ($server) -Quiet -Count 1) { + $wsaConnection = $True + Return $wsaConnection + } + else { + Write-Error "Unable to communicate with Workspace ONE Access ($server), check fqdn/ip address: PRE_VALIDATION_FAILED" + $wsaConnection = $False + Return $wsaConnection + } +} +Export-ModuleMember -Function Test-WSAConnection + +Function Test-WSAAuthentication { + Param ( + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server, + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$user, + [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$pass + ) + + Remove-Item variable:sessionToken -Force -Confirm:$false -ErrorAction Ignore + + Try { + Request-WSAToken -fqdn $server -user $user -pass $pass | Out-Null + if ($sessionToken) { + $wsaAuthentication = $True + Return $wsaAuthentication + } + else { + Write-Error "Unable to obtain access token from Workspace ONE Access ($server), check credentials: PRE_VALIDATION_FAILED" + $wsaAuthentication = $False + Return $wsaAuthentication + } + } + Catch { + # Do Nothing + } +} +Export-ModuleMember -Function Test-WSAAuthentication + +########################### End of Test Functions ########################### +################################################################################# + + ######################################################################## ##################### Start of Depreicated Functions ###################### diff --git a/README.md b/README.md index 34a52c20..80ed1962 100644 --- a/README.md +++ b/README.md @@ -16,9 +16,9 @@ If you want to use this Microsoft PowerShell module to perform implementation an ```PowerShell Install-Module -Name VMware.PowerCLI -MinimumVersion 12.3.0 -Install-Module -Name VMware.vSphere.SsoAdmin -MinimumVersion 1.3.1 +Install-Module -Name VMware.vSphere.SsoAdmin -MinimumVersion 1.3.7 Install-Module -Name PowerVCF -MinimumVersion 2.1.7 -Install-Module -Name PowerValidatedSolutions -MinimumVersion 1.2.0 +Install-Module -Name PowerValidatedSolutions -MinimumVersion 1.3.0 ``` To verify the modules are installed, run the following command in the PowerShell console.