Create role and assign global permissions in vCenter or VCSA
This script will help you to create a new role and assign permission to the role.
Please create a JSON file before executing the script as below and then you can execute the script.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
{ "roles": [ { "rolename": "RL_Virtual_Machine_Power", "roleaction": "create", "privileges": [ "System.Anonymous", "System.View", "System.Read", "Global.CancelTask", "Datastore.Browse", "VirtualMachine.Interact.PowerOn", "VirtualMachine.Interact.PowerOff", "VirtualMachine.Interact.Suspend", "VirtualMachine.Interact.Reset", "VirtualMachine.Interact.AnswerQuestion", "VirtualMachine.Interact.ConsoleInteract", "VirtualMachine.Interact.DeviceConnection", "VirtualMachine.Interact.SetCDMedia", "VirtualMachine.Interact.SetFloppyMedia", "VirtualMachine.Interact.ToolsInstall", "VirtualMachine.Interact.GuestControl", "VirtualMachine.Config.Rename", "VirtualMachine.Config.AddExistingDisk", "VirtualMachine.Config.AddNewDisk", "VirtualMachine.Config.RemoveDisk", "VirtualMachine.Config.CPUCount", "VirtualMachine.Config.Memory", "VirtualMachine.Config.AddRemoveDevice", "VirtualMachine.Config.EditDevice", "VirtualMachine.Config.Settings", "VirtualMachine.Config.Resource", "VirtualMachine.Config.UpgradeVirtualHardware", "VirtualMachine.Config.ResetGuestInfo", "VirtualMachine.Config.AdvancedConfig", "VirtualMachine.Config.DiskLease", "VirtualMachine.State.CreateSnapshot", "VirtualMachine.State.RevertToSnapshot", "VirtualMachine.State.RemoveSnapshot", "VirtualMachine.State.RenameSnapshot", "ScheduledTask.Create", "ScheduledTask.Delete", "ScheduledTask.Run", "ScheduledTask.Edit" ], "assignment": [ { "name":"EXAMPLE\\administrator", "type":"user" }, { "name":"EXAMPLE\\administrators", "type":"group" } ] } ] } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 |
<# .SYNOPSIS Configure new role and assign permission into the vCenter .DESCRIPTION This script configure global permissions in to the vCenter. .PARAMETER vCenterName Specify vCenter FQDN or .PARAMETER Username Specify vCenter Username who has access to assign permission .PARAMETER Password Specify vCenter Username Password .PARAMETER JSONFile Specific the path of the JSON file .EXAMPLE ./vCenter-Role-Management.ps1 -vCenterName "vcsa01.example.com" -Username "administrator@vsphere.local" -Password "Password123!" -JSONFile "C:\temp\roles.json" .CREDITS https://www.powershellgallery.com/packages/VIPerms/0.0.6 https://williamlam.com/2017/03/automating-vsphere-global-permissions-with-powercli.html #> [CmdletBinding()] param( [Parameter(Position=0, Mandatory=$true)] [System.String]$vCenterName, [Parameter(Position=1, Mandatory=$true)] [System.String]$Username, [Parameter(Position=2, Mandatory=$true)] [System.String]$Password, [Parameter(Position=3, Mandatory=$true)] [System.String]$JSONFile ) $JSONFile = "D:\Abhishek\Lab\Roles.json"; function Logger { <# .DESCRIPTION This function is created for logging purpose .PARAMETER <paramName> There are two param available to this function $MessageType - Expected value should be I, W, E $Message - This is the message .EXAMPLE Logger -MessageType E -Message "This is error message" Logger -Message "This is info message" Logger -MessageType W -Message "This is warning message" #> param ( [Parameter( Position = 0, Mandatory = $false )] [string] $MessageType, [Parameter( Position = 1, Mandatory = $true )] [string] $Message ) $Message = $(Get-Date -Format "yyyy-MM-dd hh:mm:ss.fff") + " - " + $Message switch ($MessageType) { "W" { Write-Host -ForegroundColor Yellow $Message } "E" { Write-Host -ForegroundColor Red $Message } default { Write-Host -ForegroundColor Green $Message } } } function Connect-VIMobServer { <# .SYNOPSIS Connect to the vSphere Managed Object Browser (MOB). .DESCRIPTION This function will first test the connection to the specified vCenter server MOB. If successful the Uri and PSCredentials object are stored in the global variable $Global:VIPerms for use with other functions in this module. .PARAMETER Server Specify the name of a vCenter server. .PARAMETER Credential Specify the credentials to use to authenticate against the MOB. This is usually administrator@vsphere.local .PARAMETER SkipCertificateCheck Skip certificate verification. .EXAMPLE Connect-VIMobServer -Server "vcenter.example.com" #> param ( [Parameter( Position = 0, Mandatory = $true )] [string] $Server, [Parameter( Position = 1, Mandatory = $true )] [PSCredential] $Credential, [Parameter( Position = 2, Mandatory = $false )] [Switch] $SkipCertificateCheck ) try { $ProPref = $ProgressPreference $ProgressPreference = "SilentlyContinue" if ($SkipCertificateCheck) { Set-CertPolicy -SkipCertificateCheck } $Global:VIPerms = @{ Server = $Server Credential = $Credential SkipCertificateCheck = $true } Invoke-Login -Server $Server -Credential $Credential [PSCustomObject] @{ Server = $Server User = $Credential.GetNetworkCredential().UserName } Invoke-Logoff if ($SkipCertificateCheck) { Set-CertPolicy -ResetToDefault } $ProgressPreference = $ProPref } catch { $Err = $_ throw $Err } } function Invoke-Login { <# .SYNOPSIS Authenticate against vCenter MOB .DESCRIPTION Authenticate against vCenter MOB and grab the vmware-session-nonce. This is then stored in the global VIPerms hashtable along with the session variable from the web request. #> try { $ProPref = $ProgressPreference $ProgressPreference = "SilentlyContinue" if (!($Global:VIPerms.Server) -or ([String]::IsNullOrEmpty($Global:VIPerms.Server)) -or !($Global:VIPerms.Credential) -or ([String]::IsNullOrEmpty($Global:VIPerms.Credential))) { throw "Please authenticate using Connect-VIMobServer first!" } $Uri = ("https://$($Global:VIPerms.Server)/invsvc/mob3/?moid=authorizationService&" + "method=AuthorizationService.GetRoles") # Initial login to vSphere MOB to store session variable $Params = @{ Uri = $Uri SessionVariable = "MobSession" Credential = $Global:VIPerms.Credential Method = "GET" } $Res = Invoke-WebRequest @Params # 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 ($Res.StatusCode -eq 200) { $null = $Res -match 'name="vmware-session-nonce" type="hidden" value="?([^\s^"]+)"' $Global:VIPerms.SessionNonce = $Matches[1] $Global:VIPerms.WebSession = $MobSession } else { throw "Failed to login to vSphere MOB" } $ProgressPreference = $ProPref } catch { $Err = $_ throw $Err } } function Invoke-Logoff { <# .SYNOPSIS Logout of the authenticated vCenter MOB web session and clear up the global variable VIPerms. #> try { $ProPref = $ProgressPreference $ProgressPreference = "SilentlyContinue" $Uri = "https://$($Global:VIPerms.Server)/invsvc/mob3/logout" $Res = Invoke-WebRequest -Uri $Uri -WebSession $Global:VIPerms.WebSession -Method GET $Global:VIPerms.WebSession = $null $Global:VIPerms.SessionNonce = $null $ProgressPreference = $ProPref } catch { $Err = $_ throw $Err } } function Set-CertPolicy { <# .SYNOPSIS Ignore SSL verification. .DESCRIPTION Using a custom .NET type, override SSL verification policies. #> param ( [Switch] $SkipCertificateCheck, [Switch] $ResetToDefault ) try { if ($SkipCertificateCheck) { try { [Net.ServicePointManager]::SecurityProtocol = "Tls12, Tls11, Tls" [Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy } catch { $Err = $_ if ($Err.Exception.Message.StartsWith("Cannot find type [TrustAllCertsPolicy]")) { 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; } } "@ [Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy } else { throw $Err } } } else { [Net.ServicePointManager]::CertificatePolicy = $null } } catch { $Err = $_ throw $Err } } function New-VIGlobalPermission { <# .SYNOPSIS Add a global permission for a user/group. .DESCRIPTION Creates a global permission assigning either a user or group to a specific role. .PARAMETER Name Specify the name of user or group including the domain. .PARAMETER IsGroup Specify whether the target is a group object or not. .PARAMETER RoleId Specify the identifier for the specific role to assign to the global permission. .PARAMETER Propagate Specify whether the permission should propagate to all children objects or not. .PARAMETER SkipCertificateCheck Skip certificate verification. .EXAMPLE New-VIGlobalPermission -Name "VSPHERE.LOCAL\joe-bloggs" -RoleId -1 .EXAMPLE New-VIGlobalPermission -Name "VSPHERE.LOCAL\group-of-users" -IsGroup -RoleId -1 .EXAMPLE New-VIGlobalPermission -Name "VSPHERE.LOCAL\joe-bloggs" -RoleId -1 -Propagate:$false #> param ( [Parameter( Position = 0, Mandatory = $true )] [String] $Name, [Parameter( Position = 1, Mandatory = $false )] [Switch] $IsGroup, [Parameter( Position = 2, Mandatory = $false )] [String] $RoleId, [Parameter( Position = 3, Mandatory = $false )] [Switch] $Propagate = [Switch]::Present, [Parameter( Position = 4, Mandatory = $false )] [Switch] $SkipCertificateCheck ) try { $ProPref = $ProgressPreference $ProgressPreference = "SilentlyContinue" if ($SkipCertificateCheck -or $Global:VIPerms.SkipCertificateCheck) { Set-CertPolicy -SkipCertificateCheck } Invoke-Login $Uri = ("https://$($Global:VIPerms.Server)/invsvc/mob3/?moid=authorizationService&" + "method=AuthorizationService.AddGlobalAccessControlList") $Group = switch ($IsGroup) { $true {"true"} $false {"false"} } $Prop = switch ($Propagate) { $true {"true"} $false {"false"} } $Body = ("vmware-session-nonce=$($Global:VIPerms.SessionNonce)&" + "permissions=%3Cpermissions%3E%0D%0A+++%3Cprincipal%3E%0D%0A++++++" + "%3Cname%3E$([Uri]::EscapeUriString($Name))%3C%2Fname%3E" + "%0D%0A++++++%3Cgroup%3E$Group%3C%2Fgroup%3E%0D%0A+++%3C%2Fprincipal%3E%0D%0A+++" + "%3Croles%3E$RoleId%3C%2Froles%3E%0D%0A+++" + "%3Cpropagate%3E$Prop%3C%2Fpropagate%3E%0D%0A%3C%2Fpermissions%3E") $Params = @{ Uri = $Uri WebSession = $Global:VIPerms.WebSession Method = "POST" Body = $Body } $Res = Invoke-WebRequest @Params Invoke-Logoff if ($SkipCertificateCheck -or $Global:VIPerms.SkipCertificateCheck) { Set-CertPolicy -ResetToDefault } $ProgressPreference = $ProPref Logger -Message "Permission assigned to $Name" } catch { $Err = $_ Logger -MessageType E -Message $Err.Exception.Message } } function New-VCRole { <# .SYNOPSIS Create new role using PowerCLI cmdlet New-VIRole .DESCRIPTION This function will fetch the privileges and then create a new role .PARAMETER Privilege_Ids Specify the privileges ids .PARAMETER RoleName Specify the name of new role .EXAMPLE New-VCRole -Privilege_Ids "System.View","System.Read","Global.CancelTask" -RoleName "New_Role" #> param ( [Parameter( Position = 0, Mandatory = $true )] [string[]] $Privilege_Ids, [Parameter( Position = 1, Mandatory = $true )] [string] $RoleName ) try { $privileges = Get-VIPrivilege -Id $Privilege_Ids; $null = New-VIRole -Name $RoleName -Privilege $privileges -ErrorAction SilentlyContinue if($? -eq $true){ Logger -Message "Role $RoleName has been created" $Global:IsRoleCreated = $true; } elseif ($error[0].Exception.ErrorId -eq "Client20_InventoryServiceImpl_TryValidateUniqueRoleName_DuplicateName" ) { $Global:IsRoleCreated = $true; Logger -MessageType W -Message "Role $RoleName already exists" } else{ $Global:IsRoleCreated = $false; Logger -MessageType E -Message "Role $RoleName unable to create -> $($error[0].Exception.Message)" } } catch { $Global:IsRoleCreated = $false; Logger -MessageType E -Message "Role $RoleName unable to create -> $($_.Exception.Message)" } } if($(Test-Path -Path $JSONFile) -eq $true) { $Roles = $(Get-Content $JSONFile | ConvertFrom-Json).roles } else{ Logger -MessageType E -Message "File path is not valid - $JSONFile" return; } $SecurePassword = ConvertTo-SecureString $Password -AsPlainText -Force $Credential = New-Object System.Management.Automation.PSCredential($Username,$SecurePassword) #Connect vCenter $vCenter_Connection = Connect-VIServer $vCenterName -Force -Credential $Credential if($vCenter_Connection.IsConnected -ne $true) { Logger -MessageType E -Message "$vCenterName - Unable to connect using $Username -> $($error[0].Exception.Message)" return; } Logger -Message "$vCenterName - Connected using $Username" $vCenter_MOB_Connection = Connect-VIMobServer -Server $vCenterName -Credential $Credential -SkipCertificateCheck foreach($role in $Roles) { $roleId = $(Get-VIRole -Name $role.rolename).ExtensionData.RoleId; if($role.roleaction -eq "create") { New-VCRole -Privilege_Ids $role.privileges -RoleName $role.rolename if($Global:IsRoleCreated -eq $false){ continue; } foreach($obj in $role.assignment) { $is_group = $false; if($obj.type -eq "group") { $is_group = $true; } New-VIGlobalPermission -Name $obj.name -IsGroup $is_group -RoleId $roleId } } } if($vCenter_Connection.IsConnected -ne $true){ $null = Disconnect-VIServer * -Force -Confirm:$false } |