How to generate new self-signed certificate for a bunch of servers in vSphere 8

I just needed to regenerate self-signed certificate on some of my home lab servers

For fowllowing commands It was required to install these module:

Posh-SSH and CredentialManager so first of all I installed these modules :

Install-Module -Name Posh-SSH
Install-Module credentialmanager

Then I stared to write PowerShell script to:

  1. Get all the hosts in Tanzu cluster
  2. Check for each host whether it is in Maintenance mode and then continue the procedure ( if the host is not in maintenance the code will not be executed on that)
  3. Enable the ssh service on each the server
  4. Backup the current certificate and keys
  5. Generate new certificate
  6. Reboot ESXi server ( Please be carefull when the host is rebooted then the old certifications will be removed during the next reboot if you need them please remove reboot from the first line (&& reboot) and then execute the script

After Running the script it ask you about the vCenter server address and credentials then the process will be started

$vcs = Read-Host "Please enter the vCenter Server Address"
Connect-VIServer -Server $vcs
$cluster= Read-Host "Please enter the name of cluster which you want to execute the command"
$cmd = 'mv /etc/vmware/ssl/rui.crt /etc/vmware/ssl/rui.crt.old ; mv /etc/vmware/ssl/rui.key /etc/vmware/ssl/rui.key.old ;  /sbin/generate-certificates && reboot'

$user = 'root'
$pswd = 'VMware1!'

$pswdSec = ConvertTo-SecureString -String $pswd -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user, $pswdSec

get-vmhost| Where-Object {$_.Parent -like $cluster } | ForEach-Object -Process {
if( ((Get-VMhost $_).State ) -eq "Maintenance" ) { 
 Write-host $_ "is alrady in maintenance mode"

      if((Get-VMHostService -VMHost $_).where({$_.Key -eq 'TSM-SSH' }).Running){ 
      Write-Host "ssh was already enabled"
      Write-Host "executing commands"
      $ssh = New-SSHSession -ComputerName $_.Name -Credential $cred -AcceptKey -KeepAliveInterval 5 -Verbose
      Invoke-SSHCommand -SessionId $ssh.SessionId -Command $cmd -TimeOut 30
      Remove-SSHSession -SessionId $ssh.SessionId
    }
      else{
      Get-VMHostService -VMHost $_ | Where-Object {$_.Key -eq "TSM-SSH" } | Start-VMHostService -confirm:$false
      Write-Host "ssh has been enabled"
      Write-Host "executing commands"
      $ssh = New-SSHSession -ComputerName $_.Name -Credential $cred -AcceptKey -KeepAliveInterval 5 -Verbose
      Invoke-SSHCommand -SessionId $ssh.SessionId -Command $cmd -TimeOut 30
      Remove-SSHSession -SessionId $ssh.SessionId
    }


    }
else{

 write-host "The Server"  $_  "is not in maintenance mode so the command has not been executed"
 write-host (Get-VMhost $_).State

    }

}

Leave a Reply

Your email address will not be published. Required fields are marked *

39 + = 40