Home > Blogs > VMware PowerCLI Blog > Category Archives: General

Category Archives: General

Joining ESXi hosts to a domain and granting permissions with PowerCLI

Recently I was asked by an administrator to help him automate the process of joining ESXi Hosts or as PowerCLI refers to them “VMhosts” to a domain and granting permissions for a domain user with PowerCLI.

In this post I am going to show you how this can be done with a few lines of code and also share my lessons learned throughout this process. Let’s assume that you have list of VMhost IP addresses and all VMhosts have the same local administrator credentials, you want to join them to a domain and grant permissions for a domain user or group account assigning it a specific role. In the script I assume the role exists on the VMHost but later I will show you how to create a custom role.

The Set-VMHostAuthentication cmdlet is used for joining a VMhost to a domain. You should have in mind that the full domain name must be specified on the Domain parameter of the cmdlet.

Get-VMHostAuthentication -VMHost <VMHost>| Set-VMHostAuthentication -Domain <domain fullname> -User <domain user name for authentication> -Password <password for authentication> -JoinDomain -Confirm:$false

The New-VIPermssion cmdlet is used for creating permissions for a specified user. The user is obtained with the Get-VIAccount cmdlet which has the ability to retrieve Domain user or group accounts when the VMHost is joined to a domain. In contrast to Set-VMHostAuthentication the Domain parameter of Get-VIAccount expects the domain alias instead of domain full name.

You should also be aware that if you don’t specify an Id filter to the Get-VIAccount cmdlet it returns the maximum 5000 results and for domains with many accounts this could be a constraint. So it is recommended to use Id filter of the cmdlet itself instead of applying filtering over its results.

To obtain domain user accounts use –User switch.

Get-VIAccount -Domain <domain alias> -User -Id <user name filter>

To obtain domain group accounts use –Group switch.

Get-VIAccount -Domain <domain alias> -Group -Id <group name filter>

To grant permissions you should specify account to Principal parameter returned by the Get-VIAccount cmdlet, role which can be obtained by Get-VIRole or specified by name and entity which in our case will be the VM host.

New-VIPermission -Principal <VIAccount> -Role <VIRole> -Entity <VMHost>

Here is the entire script with a lot of input parameters needed by the used cmdlets in the script but the script itself is not complex:

param (

   [Parameter(Mandatory=$true, HelpMessage="List of VM host IPs")]

   [ValidateNotNull()]

   [string[]]

   $vmHostIPs,

 

   [Parameter(Mandatory=$true, HelpMessage="VM Host User Name")]

   [ValidateNotNull()]

   [string]

   $vmHostUserName,

 

   [Parameter(Mandatory=$true, HelpMessage="VM Host Password")]

   [ValidateNotNull()]

   [string]

   $vmHostPassword,

 

   [Parameter(Mandatory=$true,HelpMessage="Domain full name, required for joining hosts.")]

   [ValidateNotNull()]

   [string]

   $domainlFullName,

  

   [Parameter(Mandatory=$true,HelpMessage="Domain alias, required for retrieving domain accounts.")]

   [ValidateNotNull()]

   [string]

   $domainAlias,

 

   [Parameter(Mandatory=$true, HelpMessage="User name for domain authentication")]

   [ValidateNotNull()]

   [string]

   $domainUser,

 

   [Parameter(Mandatory=$true, HelpMessage="Password for domain authentication")]

   [ValidateNotNull()]

   [string]

   $domainPassword,

  

   [Parameter(Mandatory=$true, HelpMessage="Domain user name for which permissions will be granted")]

   [ValidateNotNull()]

   [string]

   $userNameToGrantPermissions,

  

   [Parameter(Mandatory=$true, HelpMessage="The name of the role you will assign to the user")]

   [ValidateNotNull()]

   [string]

   $roleName

)

 

 

foreach ($vmHostIPin$vmHostIPs) {

    # Establish connection to a VMHost

    $vmHostConnection= Connect-VIServer-Server $vmHostIP -User $vmHostUserName -Password $vmHostPassword

      try {

            # Get VMHost instance

            $vmHost= Get-VMHost -Server $vmHostConnection

     

            # Join the VMHost to a domain

            Get-VMHostAuthentication -VMHost $vmHost | Set-VMHostAuthentication -Domain $domainlFullName -User $domainUser -Password $domainPassword -JoinDomain -Confirm:$false

 

            # Get a domain account

            $viAccount= Get-VIAccount -Domain $domainAlias -User -Id $userNameToGrantPermissions        

            if (-not $viAccount) {

                  throw “VIAccount with Id ‘$userNameToGrantPermissions’ not found in domain ‘$domainAlias’”

            }

 

            # Get role to assign

            $viRole= Get-VIRole -Name $roleName

            if (-not $viRole) {

                  throw “VIRole with name ‘ $viRole’ not found.”

            }

 

            # Add permissions on VMHost

            New-VIPermission -Principal $viAccount -Role $viRole -Entity $vmHost         

      } catch {

            Write-Error (“The following error has occurred for VMHost ‘$vmHost’: `r`n”+$_)

      } finally {

            Disconnect-VIServer $vmHostConnection -Confirm:$false

      }

}

 

As you can see the script opens a connection to each VMhost, joins it to the domain and creates permissions for a specific domain account. It relies on the existing role on the VMHost, but it can be easily modified to create a custom role and assign it to the obtained user.

To create a new custom role the New-VIRole cmdlet needs to be used specifying a name and list of privileges on its input. Here is an example:

New-VIRole -Name MyCustomRole -Privilege ‘Anonymous’, ‘View’, ‘Read’, ‘Power On’, ‘Power Off’

The script is calling the Get-VIAccount with a –User switch parameter which filters on domain user accounts. In order to retrieve a domain group account the –Group switch parameter should be used.

So the script looks pretty simple and straightforward but running it I’ve experienced the following problem. Sometimes Get-VIAccount failed to retrieve the domain user immediately after joining the VMhost to the domain and I received the following error “Error accessing directory: Can’t bind to LDAP server for domain: <DOMAIN>”.

It seems that synchronization with active directory needs some time after a host is joined to the domain and the problem is not 100% reproducible. So I solved it with a simple retry-wait mechanism on retrieving domain users.

# Get a domain account

$viAccount=$null

$retryCount= 5

while ((-not$viAccount) -and ($retryCount-ge 0)) {

      try {

            $viAccount= Get-VIAccount-Domain$domainAlias-User-Id$userNameToGrantPermissions

      } catch {

            Write-Error “Getting VIAccount with Id ‘$userNameToGrantPermissions’ failed with the following error: `r`n $_”

            Write-Host “Next attempt in 5 seconds”

            Start-Sleep -Seconds 5

}

$retryCount

}

Conclusion

In conclusion here are the lessons learned from this task:

  1. Get-VIAccount requires to specify the domain alias to Domain parameter
  2. Get-VIAccount limits the results to 5000
  3. Sometimes Get-VIAccount fails to obtain domain users immediately after a VMhost is joined to a domain.

imageThis post was created by Dimitar Milov…

Dimitar joined VMware and PowerCLI team in the beginning of 2011. He is member of the quality engineering part of the team and his main role is the functional verification of the vSphere, vCloud and License PowerCLI components.

As all members of the team he is working to deliver a good and valuable product. He is also working to improve all processes and tools involved in product development and validation.

PowerCLI Lab Online – Sign up now for the public beta

If you were at VMworld in 2012 you may have attended the Hands on Labs (HOL), this is normally one of the most popular areas at VMworld as it’s a time when people can use the applications they don’t currently have installed in their own environments, they can use a virtual environment to follow instructions and see how the applications really work.

One of the most popular labs at VMworld is always the PowerCLI Lab, this was no exception in 2012, every year the PowerCLI team does a great job of adding new features to the latest version of PowerCLI and this is always a great way to check those features out in a test environment.

There has always been one issue with the HOL though, once you leave VMware you say goodbye to the HOL as access was previously at the event only….. Until Now.

There is now a public beta of the HOL Online, this gives you access to a number of different HOL Online for you to take at your own leisure and sat at the comfort of your own desk.

How do I sign up?

To sign up simply go to http://hol.vmware.com and click on the link as highlighted below:

image

Once you have filled out a few questions you will need to wait for your account to be activated (I have been assured this will be fairly quick).  Once activated you will be able to click on the “VMware Hands-on Labs Online” link as above and access a number of different labs, complete with their own isolated environment and full step by step documentation to run through the lab chosen.

How do I find the PowerCLI Lab?

Once you have gained access to the HOL and signed in use the left hand menu to select “Cloud Infrastructure”

image

Now scroll down the list on the right until you see the PowerCLI Lab, then click Enroll.

image

Once you have done this the selected Lab will be added to “My Enrollments” where you will be able to click the “Start this LAB” button to launch the lab as below:

image

The LAB will now start and you will have access as seen below:

image

PowerScripting Podcast–What’s new in PowerCLI 5.1 R2

If you enjoy podcasts or have a long commute and don’t mind listening to people talk about PowerShell then I can highly recommend the PowerScripting Podcast, they have some great PowerShell information every week and if you have not listened before then you already have 219 podcasts to catch up on!

Recently I had the pleasure of being interviewed on the PowerScripting Podcast by Hal and Jonathan, we talked about what was new with PowerCLI, what was cool in the world of PowerShell and also what I would do on a trip to Mars (I know – Random!).

For more information and ways to download the podcast visit their site here: http://powerscripting.wordpress.com/2013/03/13/episode-219-alan-renouf-from-vmware-on-powercli/

For more information on what’s new in PowerCLI 5.1 R2 make sure you check out this blog post: http://blogs.vmware.com/vipowershell/2013/02/powercli-5-1-release-2-now-available.html

Back to Basics: Connecting to vCenter or a vSphere Host

Following my previous post which took you through the install of PowerCLI I thought it was time to add another back to basics (B2B) post and show how to take the first step in using PowerCLI… Connecting to your vCenter or vSphere host.

Yes, PowerCLI can be used to connect to both vCenter and also the vSphere host independently, of course not all the cmdlets will be relevant if you connect to just the host but still, this can be useful during the initial setup or automated deployments of the complete infrastructure.

How to connect

If you are connecting to either a vCenter server or a vSphere Host the cmdlet is the same, you can use the Connect-VIServer cmdlet to connect to both of these (even at the same time), lets take a look at an example:

C:\PS>Connect-VIServer -Server vcenter01 -User admin -Password pass

In the above example you can see we are connecting to our vCenter server called “vcenter01” with a username and password to gain access to the vCenter server, we did not specify a protocol or port, by default HTTPS and port 443 is assumed which is the same as the vSphere Client or Web Client, unless you specify a –port or –protocol parameter for the cmdlet.

Credentials

In the example above we used the –User and –Password parameters to pass through the credentials but this might not always be what you want to do, especially as PowerShell files are plain text!  There are multiple ways in which we can specify the credentials or store the credentials, its really up to you which you use and which is best suited for your situation.

Continue reading

PowerCLI 5.1 and the future

Recently I have had some questions from people using PowerCLI, these are mainly related to confusion around the 5.1 release of VMware products and the way that PowerCLI works so I wanted to use this blog post to answer some of these questions but also to confirm that the future for PowerCLI is bright.

Q.  “Does PowerCLI work with the vCenter Server Appliance?”image

A. Yes it does, PowerCLI uses the vCenter APIs, in fact the best place to install PowerCLI is the same place that you would use the vSphere Client from, this is normally the vSphere admins workstation or a windows machine used solely for scheduled tasks.  PowerCLI connects to the vCenter APIs and therefore both Windows and the appliance versions of vCenter work with PowerCLI 5.1.

Q. “Does PowerCLI work with the vSphere Web Client?”

A.  A common question and yet in reality you do not need the C# vSphere Client or the vSphere Web Client in order for PowerCLI to work, everything you need is inside the installer for PowerCLI, just install it (instructions here) and your set.

Q. “With VMware releasing more and more Linux related appliances what does this mean for PowerCLI?”

A. PowerCLI is one of VMware’s most successful and well loved automation and troubleshooting tools by vSphere and vCloud Director Admins, as I said in the answer to a previous question, it connects directly to the vSphere APIs, it doesn’t care what is hosting them.

Whilst I can not discuss the roadmap for PowerCLI I can certainly say its as strong as ever and we will continue to wow the users of PowerCLI with the latest features and updates.

Q. “Does Onyx work with vSphere 5.1?”image

A. For those of you who are not aware of what Onyx is, it’s a VMware Fling which sits in-between your vCenter and your vCenter Client, it intercepts the traffic and translates it into PowerShell code, not nicely formatted PowerCLI type cmdlets but still a great place to look if you need to find a way to do something quickly.

You hit play on the Onyx client and the fun begins, anything you do in the vSphere client from then on is captured and represented as code, and not just PowerShell code but also C#, vCO JavaScript and  Raw SOAP messages.

So does it work with 5.1 ?  Yes of course it does, but only when using the C# client, obviously the vSphere Web Client works differently and therefore Onyx is unable to capture the actions you take in the web client and turn them into code, as this is a fling I can not make any promises of if or when this will be updated to work with the web client but obviously the challenges are different.  In the meantime make sure you use the C# client when you want to capture the code.


Hopefully this will help eliminate any questions about PowerCLI and how it works with 5.1 and the future, if you have any further questions please add a comment to this post and we will do our best to answer them.

Meet the PowerCLI Team

I have often been asked who creates PowerCLI and to pass on your appreciation to the people who have saved you so much time and effort.

So after visiting Bulgaria on my way back from VMworld Barcelona I thought it would be nice to show you a recent picture of the PowerCLI Team who are located in Sofia, Bulgaria.

Feel free to leave your comments to them as a comment on this post.

IMG_1999

PowerCLI 5.1 Poster

Following the release of PowerCLI 5.1 there is of course a new PowerCLI Poster, those of you who attended VMworld San Francisco may have been lucky enough to grab one of the few posters we had there, they went very quick and I’m sorry to the people who did not get one.

We plan on having some at VMworld Barcelona (No guarantees) so make sure you attend some of the PowerCLI sessions to get your copy.

In the meantime, for those of you who could not wait and want to print your own copy right now please find below the latest PowerCLI 5.1 poster including a list of all the new cmdlets and the cmdlets in the new PowerCLI for vCloud Tenants snapin.

Download the poster here, this is ideal for printing on large printers or even just keeping on the iPad or as a PDF for reference.

PowerCLI Poster

PowerCLI 5.1 now available

PowerCLI 5.1 is now generally available, as a reminder, in the previous post we gave you an update of what was new.  You can view that post here.

You can view the official PowerCLI release documentation here or the documentation for the Tenant snapin here.

From now on you will see two download links for PowerCLI, one for the updated version of PowerCLI and another for the Cloud Tenants, make sure you choose the correct one as they will not install together.

As you can see from the download page, the updated PowerCLI for vSphere and vCD Administrators is on the left hand side and the PowerCLI for Tenants of vCloud Director is on the right.

Stay tuned for more posts showing exactly what is possible with these new releases soon.Download PowerCLI

Download

Use the following link to be directed to the download page:  http://communities.vmware.com/community/vmtn/server/vsphere/automationtools/powercli?view=overview

PowerCLI 5.1 – What’s New ?

With the announcement of vSphere 5.1 from Steve Herrod at VMworld 2012 – San Francisco I wanted to highlight the new features which will be available as part of VMware vSphere PowerCLI 5.1 Release 1.

Background

image

As with previous releases there have been many enhancements to PowerCLI, as users of PowerCLI will know, as part of the default PowerCLI 5.0.1 install we already had 5 PowerShell Snapin’s available to use, these enabled you to manage the following products and features:

  • vCenter and vSphere (VMware.VimAutomation.Core Snapin)
  • vCenter and vSphere Licensing (VMware.VimAutomation.License Snapin)
  • Image Builder (VMware.ImageBuilder Snapin)
  • Auto Deploy (VMware.DeployAutomation Snapin)
  • vCloud Director (VMware.Vimautomation.Cloud Snapin)

As you will also know, most of the cmdlets for the Cloud snapin were “Get-“ cmdlets, these allowed us to focus on retrieving data from vCloud Director, access to more advanced functions were available via the Get-CIView cmdlet but this was for the advanced PowerCLI users.

What’s New for vSphere Users ?

The PowerCLI Core Snapin introduces a number of improvements and new features, you will of course find many bug fixes and speed enhancements as part of this release, as well as this the following enhancements have been included:

  • You can use Kerberos for pass-through authentication with vCenter Server, ESX/ESXi, and vCenter Virtual Appliance systems.
  • You can create linked clones with New-VM.
  • You can pass datastore clusters to the Datastoreparameters.
  • You can retrieve vSphere objects from vCloud Director objects with the RelatedObjectparameter.
  • You can manage resources more efficiently with Storage DRS (SDRS) support added to a number of cmdlets.
  • You can retrieve, create, modify, and remove VMHost, VM, and SDRS advanced settings with the the Get-AdvancedSetting, New-AdvancedSetting, Set-AdvancedSetting, and Remove-AdvancedSetting cmdlets.

vSphere PowerCLI 5.1 Release 1 also brings a set of improvements that enhance security and customization, these include:

  • You can set the scope of your settings with the Scope parameter of Set-PowerCLIConfiguration.
  • You can initialize custom vSphere PowerCLI scripts automatically by storing them in the Initialize-PowerCLIEnvironment_Custom.ps1 script configuration file.

What’s New for vCloud Admins ?

vCloud Director Admins can take advantage of over 60 cmdlets to manage vCloud Director, these have been enhanced from the “Get-“ cmdlets and now include cmdlets to help you modify and automate your vCloud Directory infrastructure, the following enhancements have been made:

  • You can create, modify, manage, and remove organizations.
  • You can create and manage permissions.
  • You can assign computing and networking resources.
  • You can create, modify, and remove organization networks.
  • You can create, modify, and remove vApp networks.
  • You can create, modify, manage, and remove vApps.
  • You can manage virtual machines and their guest operating systems within vApps.

What’s New for vCloud Tenants ?

With PowerCLI 5.1 Release 1 we now have a new snapin specifically for vCloud Tenants, in fact this is a completely separate installation with its own set of cmdlets which can not be installed on the same machine as vSphere PowerCLI 5.1 Release 1, this is called VMware vSphere PowerCLI Release 1 for Tenants and is designed to aid the vCloud Tenants in performing automated tasks in their hosted vCloud organization.

Why would we do this ?

We wanted to bring the power of automation and the ease of reporting that PowerCLI gives the current vSphere and vCloud Admins to the tenants of the cloud.  All this whilst giving them an easy to use simplified subset of cmdlets specific to the tasks they can do within their vCloud Organization.

What’s available to tenants ?

VMware vSphere PowerCLI 5.1 Release 1 for Tenants consists of two components:

  • vSphere PowerCLI common snapin for providing common PowerCLI configuration and usage based tasks, these cmdlets are part of the VMware.VimAutomation.Commonsnapin.
  • vCloud Director PowerCLI snapin for providing tenant-based reporting and automation, these cmdlets are part of the VMware.VimAutomation.Cloud snapin and can be used with vCloud Director 1.5.1 Tenant tasks.

These components will allow the vCloud Tenants to perform the following tasks:

  • You can list, modify, and manage organizations.
  • You can list, create, and manage permissions.
  • You can list and assign networking resources.
  • You can list organization networks.
  • You can list, create, modify, and remove vApp networks.
  • You can list, create, modify, manage, and remove vApps.
  • You can list and manage virtual machines and their guest operating systems within vApps.

Summary

So where are we now ? What can we actually do with PowerCLI and the different VMware installations of snapins ?

image

As you can see, we have a number of different snapins which enable us to add the products and areas we are interested in using with Windows PowerShell, we have the ability to not only enable our admin users but also our private and public cloud users, with the VMware snapins all users of the VMware products can achieve the level of automation, integration and reporting that PowerShell and PowerCLI gives.

More Information

Keep tuned for more blog posts and information or if you are visiting VMworld Europe in 2012 make sure you add  INF-VSP1252 – What’s New with vSphere 5.1 – ESXCLI & PowerCLI to your session list.