Automating vCloud and AD User Provisioning with Powershell

As part of my Hands-on Lab project, I wanted to automate the creation of user accounts, both for vCloud Director as well as VMware View/Active Directory. I kicked around the idea of using VMware Orchestrator but found that I just don’t know enough about it to make that happen, so instead, I went back to PowerShell and came up with the script below.

 What does it do?

Basically, it takes a file full of people who plan to attend and creates all the stuff I had to do manually the first time I did a lunch and lab event.

Inputs needed:

  • First Name
  • Last Name
  • Email address
  • Location

The location just represents which lunch and lab location the user is attending, this is used multiple places in the script so that all users at a certain event will be groups together in AD as well as in vCloud Director. This will make it much easier to manually delete vCloud Org’s and in active directory it allows me to just delete a particular OU after the event is over. It also makes provisioning VMware View easier too as I can just entitle the OU to a desktop pool and everyone is ready to go. Right now I left View out of this script as I want to manually entitle the OU’s the day of the event, but I will be importing user accounts as we receive RSVP’s.

Expected Results:

  • Create an Active Directory OU if it does not already exist for each “Location”
  • Create an Active Directory User in the proper OU (Location)
  • Generate a password that will be used for AD as well as vCloud login’s
  • Create a vCloud Organization
  • Create a Pay-As-You-Go Virtual Datacenter for the Org
  • Create an Org Admin user with the same credentials as Active Directory
    (Probably could have used LDAP integration but wanted to keep things easier … at least in my mind)
  • Send me as well as the Lab user an email with login details including username, password, VMware View Information, vCloud Director URL

Disclaimer: I am NOT in any way a PowerShell guru, in fact I know very little about it so make sure to check things in a dev environment before using it in production. Also if you know of a better way to do anything in the script please let me know… I’m open to suggestions.

Note: the script is also downloadable in ZIP format HERE.

The Script

###############################################
##                                           ##
## lab_provisioner.ps1 			             ##
##                                           ##
## Author: Justin Paul                       ##
## URL: http://jpaul.me                      ##
## Date:2012-11-23                           ##
## Revision: 1.0                             ##
##                                           ##
## Description:                              ##
## This Script creates an OU for an event as ##
## well as an Active Directory User and      ##
## VMware vCloud Org/Org User for Hands on   ##
## lab purposes.                             ##
##                                           ##
###############################################

### Variables ###
# 1 = True, 0 = False
$Debug = 0

## vCloud Director Info
$CIServer = "your.vcloud.director.com"
$CIUser = "vcloud admin"
$CIPassword = "vcloud password"
$Provider = "your_Provider_VDC"
$NetPool = "Your_Network_Pool_Name"
$NetMax = 10
$MemoryPct = 1
$CPUMhz = 2000

## Active Directory Server
# Force PW Change at Next Logon ? 
# 0 = false 1 = true
$DomainController = "Your-DC-Name-Or-IP"
$PWChange = 0

## SMTP Information
$EmailFrom = <a href="mailto:[email protected]">[email protected]</a>
$SMTPServer = "smtp.gmail.com"
$SMTPUser = "your gmail account"
$SMTPPassword = "your password"
# 587 for GMail, 25 for normal servers
$SMTPPort = 587

### Base OU ... this doesnt change and group/event OU's are created below this one ####
$baseOU = "OU=LabUsers,DC=vcloudlab,DC=local"

## file that contains our new users in the following format
## FirstName,LastName,Email,Location &lt;-- this needs to be the first line of CSV File
## If nothing was passed to the script use default csv file
if ($args.count -eq 0)  {
    $path = "c:\newusers.csv"
} else { $path = $args[0] }

#####################
##                 ##
## Start of Script ##
##                 ##
#####################

######## Import Modules ########
if (-not (Get-Module ActiveDirectory)){            
  Import-Module ActiveDirectory            
} 

######## Declare Functions ######

function Generate-Password () {
    param ()
    PROCESS {
	    if($debug)
	    {
		Write-Host "Generating Password..."
	    }
            if ($args.count -eq 0)  {
                do {
                   $length = Read-Host "How many characters long should the password be?"
                } until ($length -ne $null)
            } else { $length = $args[0] }

    #load Assembly
    [Reflection.Assembly]::LoadWithPartialName("System.Web") &gt; $null
    $password = [System.Web.Security.Membership]::GeneratePassword($length,0)
    if ($debug)
    {
	    Write-Host "Generation Complete"
    }
    return $password
    }
}

### Function to check if OU exists ###
Function CheckOUExist
{
    param($OU)
    if($debug)
    {
        Write-Host "Checking to See if OU Exists..."
    }
    [string] $Path = $OU
    $Result = [adsi]::Exists("LDAP://$Path")
    if ($debug)
    {
        Write-Host "OU Exists? " $Result
    }
    return $Result
}

#### Function to create vCloud Org User ####
Function New-CIUser {
    Param (
        $Name,
        $Pasword,
        $FullName,
        [Switch]$Enabled,
        $Org,
        $Role
    )
    Process {
        if($debug)
        {
            Write-Host "Creating vCloud Objects"
        }
        $OrgED = (Get-Org $Org).ExtensionData
        $orgAdminUser = New-Object VMware.VimAutomation.Cloud.Views.User
        $orgAdminUser.Name = $Name
        $orgAdminUser.FullName = $FullName
        $orgAdminUser.Password = $Pasword
        $orgAdminUser.IsEnabled = $Enabled

        $vcloud = $DefaultCIServers[0].ExtensionData

        $orgAdminRole = $vcloud.RoleReferences.RoleReference | where {$_.Name -eq $Role}
        $orgAdminUser.Role = $orgAdminRole

        $user = $orgED.CreateUser($orgAdminUser)
        Get-CIUser -Org $Org -Name $Name
        if ($debug)
        {
            Write-Host "Done"
        }
    }
} 

###Read users from CSV File
$csv = Import-csv -path $path 

foreach($line in $csv)
{ 
  if ($debug)
  {
      Write-Host "Read 1 Line from CSV file"
  }
  ##reset OU back to baseOU setting
  $OU = $baseOU
  ### Get User Info from CSV File ###
  $UserFirstName = $line.FirstName
  $UserLastName = $line.LastName

  ### send all emails to me while testing
  $UserEmail = $line.Email

  $Group = $line.Location

  ### Add Group Name to OU ###
  $OU = "OU="+$Group+","+$OU
  if ($debug)
  {
      Write-Host "Information in Record"
      Write-Host $UserFirstName  $UserLastName $UserEmail $Group
      Write-Host "User will be created in " $OU
  }

  ### Call OU Check Script
  $OUStatus = CheckOUExist ($OU)
  if (!$OUStatus)
  {
    ### if OU doesnt exist, create OU
    if ($debug)
    {
        Write-Host "OU was not found...Creating it"
    }
    New-ADOrganizationalUnit -Path $baseOU -name $Group
    ### Turn off delete protection
    Set-ADOrganizationalUnit $OU -ProtectedFromAccidentalDeletion:$false
  }

  ### Generate some Variables ###
  $FullName = $UserFirstName+' '+$UserLastName+' '+$Group
  $UserName = $UserFirstname.substring(0,1)+$UserLastName
  $UserName = $UserName.ToLower()
  $myOrg = $Group+'_'+$UserName.ToLower()
  $UserVdc = $UserName+'_vdc'

  ###Generate User Password###
  $UserPassword = Generate-Password(8)

if ($Debug)
{
  Write-Host "User Variables"
  Write-Host "Full Name: " $FullName
  Write-Host "Username: " $UserName
  Write-Host "UserPassword: " $UserPassword
  Write-Host "User Org Name: " $myOrg
  Write-Host "vDC Name: " $UserVdc
}

  ###### Create New AD User ########
  New-ADUser -server $DomainController -SamAccountName $Username -Name $Username -GivenName $UserFirstName -Surname $UserLastName -DisplayName $FullName -Path $OU -changepasswordatlogon $PWChange
  if ($debug)
  {
    Write-Host "AD User Created"
   }
  ##### Generate vCloud Objects ########

  if ($debug)
  {
      Write-Host "Connecting to vCloud Director"
  }
  Connect-CIServer -Server $CIServer -User $CIUser -Password $CIPassword
  if ($debug)
  {
      Write-Host "Creating Org"
  }
  New-Org -Name $myOrg -FullName $FullName
  if ($debug)
  {
      Write-Host "Creating Org Virtual Datacenter"
  }
  $myPVdc = Get-ProviderVdc -Name $Provider
  New-OrgVdc -AllocationModelPayAsYouGo -Name $UserVdc -Org $myOrg -ProviderVdc $myPVdc -VMCPUCoreMHz $CPUMhz
  Get-OrgVdc -Name $UserVdc | Set-OrgVdc -ThinProvisioned $true -UseFastProvisioning $true -NetworkPool $NetPool -NetworkMaxCount $NetMax -MemoryGuaranteedPercent $MemoryPct

  ######## Create New Org User ##########
  if ($debug)
  {
      Write-Host "Creating Org User"
  }
  New-CIUser -Enabled -Name $UserName -FullName $FullName -Pasword $UserPassword -Org $myOrg -Role "Organization Administrator"

  ######## Send Information Email to user #############

  $Subject = "Welcome to the Hands On Labs!"
  $Body = "Welcome to the Hands on Labs!" + "`r`n`r`n

Your account information follows below:

VMware View and vCloud Director Username: $UserName`r`n
Password: $UserPassword`r`n

To Login to VMware View, first download the View Client from http://desktops.vcloudlab.net. After installing the client use desktops.vcloudlab.net as the Server address. After logging into your VMware View Desktop launch internet explorer and enter your vCloud Director URL:`r`n

https://www.vcloudlab.net/cloud/org/$myOrg/ `r`n

Your vCloud Director Username and password are the same as your VMware View credentials.`r`n

For lab manuals please go to http://jpaul.me/ and click the Hands on Labs section at the top of the page.

If you have any questions, or have trouble logging in please email [email protected] (or [email protected]) or see a lab proctor.`r`n"

  $ToEmail = $UserEmail+','+$EmailFrom

  $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, $SmtpPort) 
  $SMTPClient.EnableSsl = $true 
  $SMTPClient.Credentials = New-Object System.Net.NetworkCredential($SMTPUser, $SMTPPassword); 
  $SMTPClient.Send($EmailFrom, $ToEmail, $Subject, $Body)
  if ($debug)
  {
      Write-Host "New User Email Sent to " + $ToEmail
      Write-Host "End of Loop"
  }

}

 

Share This Post

6 Responses to "Automating vCloud and AD User Provisioning with Powershell"

  1. This is awesome – can it be used to provision user accounts for a “Trial Run” of a vCloud service? does it work with vCD 5.1?

    also FYI the download link is broken!

  2. Silly question, how would this procedure be different if one were to import the users via LDAP as opposed to creating local vCD accounts for the Orgs?

  3. It isnt any different really, but for my use case it made more sense to do it with PS.

    so for each lunch and lab day i did, i built an OU and inserted the users that would be there that day into it.
    Then i created each User there own VDC … this is what would have made the other way a PITA

    If i had relied on importing from AD directly i would have had to create and OU for each User, then tell VCD to import those OU’s into the proper VDC (which would have basically been a 1:1 mapping)

    The AD import works good if you have a few or a bunch of AD users that will be using the same Org VDC (so like “College of Business Org VDC” and “College of Education Org VDC” and each one had say 10 admins.

    but for a 1:1 mapping i just felt it easier to let powershell do the provisioning of the VDC user.

  4. Hi Justin,
    I tried using this code but it will be executed on machine having AD installed.Is there any way that we can use activedirectory module on other non-AD windows machine ?
    I mean on machine where we can integrate AD Users with vCloud Director

Leave a Reply