VMware ESXI ESXI 6.5, vCenter Server 6.5 User guide

  • Hello! I am an AI chatbot trained to assist you with the VMware ESXI ESXI 6.5 User guide. I’ve already reviewed the document and can help you find the information you need or explain it in simple terms. Just ask your questions, and providing more details will help me assist you more effectively!
vSphere SDK for Perl Programming
Guide
ESXi 6.5
vCenter Server 6.5
This document supports the version of each product listed and
supports all subsequent versions until the document is replaced
by a new edition. To check for more recent editions of this
document, see http://www.vmware.com/support/pubs.
EN-002349-00
VMware, Inc.
3401 Hillview Ave.
Palo Alto, CA 94304
www.vmware.com
2 VMware, Inc.
vSphere SDK for Perl Programming Guide
You can find the most up-to-date technical documentation on the VMware Web site at:
http://www.vmware.com/support/
The VMware Web site also provides the latest product updates.
If you have comments about this documentation, submit your feedback to:
docfeedback@vmware.com
Copyright © 2007–2016 VMware, Inc. All rights reserved. This product is protected by U.S. and international copyright and
intellectual property laws. VMware products are covered by one or more patents listed at
http://www.vmware.com/go/patents.
VMware is a registered trademark or trademark of VMware, Inc. in the United States and/or other jurisdictions. All other marks
and names mentioned herein may be trademarks of their respective companies.
VMware, Inc. 3
Contents
AboutThisBook 7
IntendedAudience 7
1 GettingStartedwithvSphere SDK for Perl 9
vSphereSDKforPerlArchitecture 9
UsingvSphereSDKforPerl 10
GettingStarted 10
CommonvSphereSDKforPerlTasks 11
vSphereSDKforPerlProgrammingConventions 11
vSphereSDKforPerlCommonOptions 12
SpecifyingOptions 12
AuthenticatingThroughvCenterServerandvCenterSingleSignOn 13
Example 13
UsingaSessionFile 13
PassingParametersattheCommandLine 14
SettingEnvironmentVariables 14
Usinga
ConfigurationFile 15
UsingMicrosoftWindowsSecuritySupportProviderInterface(SSPI) 15
CommonOptionsReference 16
HelloHost:RunningYourFirstScript 17
2 WritingvSphereSDKforPerlScripts 19
BasicvSphereSDKforPerlScript 19
Step1:ImportthevSphereSDKforPerlModules 20
Step2:(Optional)DefineScriptSpecificCommandLineOptions 20
Step3:ConnecttotheServer 22
Step4:ObtainViewObjectsofServerSideManagedObjects 22
Step5:ProcessViewsandReportResults 22
Step6:ClosetheServerConnection 23
Understanding
ServerSideObjects 24
UsetheManagedObjectBrowsertoExploreServerSideObjects 24
TypesofManagedObjectsandtheManagedObjectHierarchy 25
ManagedObjectHierarchy 26
ManagedEntitiesintheInventory 26
AccessingServerSideInventoryObjects 27
UnderstandingPerlViewObjects 28
WorkingwithViewObjectPropertyValues 28
AccessingPropertyValues 28
AccessingSimplePropertyValues 29
AccessingEnumerationPropertyValues 29
ModifyingPropertyValues 29
CreatingDataObjectswithProperties 30
UnderstandingOperationsandMethods 30
NonBlockingandBlockingMethods 30
ExamplesofOperations 31
CallingMethods 31
OmittingOptionalArgumentsinMethodCalls 31
vSphere SDK for Perl Programming Guide
4 VMware, Inc.
UpdatingViewObjects 32
3 RefiningvSphereSDKforPerlScripts 33
CreatingandUsingFilters 33
UsingFilterswithVim::find_entity_view()orVim::find_entity_views() 33
FilteringViewsSelectivelyUsingProperties 34
UsingViewSubroutineswithaPropertiesArgument 35
UsingFiltersontheUtilityApplicationCommandLine 35
RetrievingtheServiceInstanceObjectonavSphereHost 36
SavingandUsingSessions 36
SavingSessions 36
LoadingSessions 36
UsingMultipleSessions 37
LearningAboutObjectStructureUsingData::Dumper 38
Specifying
UntypedArgumentsinScheduledTasksandCallbacks 39
UsingAdvancedSubroutines 40
Opts::get_config() 40
4 vSphereSDKforPerlSubroutineReference 41
SubroutinesintheOptsPackage 42
add_options 42
get_option 42
option_is_set 43
parse 43
validate 43
usage 43
SubroutinesintheUtilPackage 43
connect 44
disconnect 44
get_inventory_path 44
trace 44
SubroutinesintheVimPackage 45
clear_session 45
find_entity_view 45
find_entity_views 46
get_service_instance 47
get_service_content 47
get_session_id 48
get_view 48
get_views 48
load_session 48
login 49
logout 49
save_session 49
update_view_data 50
A WebServicesforManagementPerlLibrary 51
WebServicesforManagementOverview 51
RequiredPerlModules 52
SampleScripts 53
SOAPMessageConstructionwithWSMan::WSBasic 53
WSMan::WSBasic>new 54
register_xml_ns 54
register_class_ns 55
Identify 55
VMware, Inc. 5
Contents
Enumerate 55
PullRelease 56
Get 56
WSMan::WSBasicExamples 56
GenericCIMOperationswithWSMan::GenericOps 57
WSMan::GenericOps>new 58
register_xml_ns 58
register_class_ns 58
Identify 59
EnumerateInstances 59
EnumerateInstanceNames 59
EnumerateAssociatedInstances 59
EnumerateAssociatedInstanceNames 60
EnumerateAssociationInstances 60
EnumerateAssociationInstanceNames 60
GetInstance 60
B CredentialStorePerlLibrary 61
CredentialStoreOverview 61
CredentialStoreComponents 62
ManagingtheCredentialStore 62
UsingtheCredentialStore 62
vSphereCredentialStoreSubroutineReference 63
init 63
get_password 63
add_password 64
remove_password 64
clear_passwords 64
get_hosts 64
get_usernames 64
close 65
credstore_admin.plUtilityApplication 65
Index 67
vSphere SDK for Perl Programming Guide
6 VMware, Inc.
VMware, Inc. 7
ThevSphereSDKforPerlProgrammingGuide,providesinformationaboutwritingandrunningVMware
®
vSphereSDKforPerlscriptsonESX/ESXiorvCenterServersystems.
BecauseSDKsubroutinesallowyoutomanagevSpherehostsusingvSphereAPIcalls,abriefdescriptionof
theserversideobjectmodelisincluded.Thisguidefocusesonexplaininghowtoaccessandmodify
serversideobjectsusingthevSphere
SDKforPerlandondiscussingsomeprogrammingtechniques.
Intended Audience
ThisbookisintendedforadministratorswithdifferentlevelsofPerlscriptingexperience:
AlladministratorscanusetheutilityapplicationsandsamplescriptsincludedwiththevSphereSDKfor
PerltomanageandmonitorthehostsinthevSphereenvironment.
ExperiencedPerlprogrammerscanexaminethesourcecodefortheavailablescripts.Theycanthen
modifythosescriptsorwritenewscriptsusingthevSphereSDKforPerlsubroutinestoaccesstheobjects
onthevSpherehostandmanipulatethoseobjectsusingPerl.Thisdocumentincludesadiscussionofthe
vSphere
objectmodelandexplainshowyoucanpreviewandretrievetheobjectsandtheirattributesand
methods.
About This Book
IMPORTANTThisbookdiscussestheSDKforPerlthatallowsyoutoaccessvSpherebyusingthevSphereWeb
ServicesSDK,whichisavailableforallsupportedversionsofvSphere.ThisbookdoesnotdiscussPerl
bindingstovAPI,whichwasreleasedwithvSphere6.0forthefirsttime.
vSphere SDK for Perl Programming Guide
8 VMware, Inc.
VMware, Inc. 9
1
ThevSphereSDKforPerlletsyouautomateawidevarietyofadministrative,provisioning,andmonitoring
tasksinthevSphereenvironment.ThischapterintroducestheSDKarchitecture,explainsthebasicusemodel,
andgetsyoustartedrunningasimplescript.
Thechapterincludesthefollowingtopics:
“vSphereSDKforPerlArchitecture”onpage 9
“UsingvSphereSDKforPerl”onpage 10
“vSphereSDKforPerlCommonOptions”onpage 12
“HelloHost:RunningYourFirstScript”onpage 17
vSphere SDK for Perl Architecture
TheinteractionmodelbetweentheSDKandthevSphereAPIonthehostdirectlyaffectshoweachscriptis
structured,andisthebasisfortroubleshooting.
vSphereSDKforPerlsubroutinesinteractwiththehostandperformvariationsofthesebasictasks:
Connecttoaremotehostusingusersuppliedconnectionparameters,anddisconnect.
Findobjectsontheremotehost(serversideobjects).Forexample,findallvirtualmachinesonahost.
Retrieveormodifyserversideobjects,forexample,managethevirtualmachinelifecycle(start,stop,
suspend,andsoon).
Collectinformationfromserversideobjects.
Managesessions.
MostroutinesretrieveavSphereAPIobjectandmakeitavailableasaPerlobject(calledaviewobject)that
youcanthenmanipulatewithyourscript.
ThevSphereSDKforPerlhasthesecomponents:
vSphereSDKforPerlRuntimeClientsideruntimecomponentsthatinclude:
AcompletePerlbindingofthevSphereAPI,whichmakesallserversideoperationsanddata
structuresavailable.TheSDKhandlesthedatatypemappingbetweenserversideandclientside
objectstransparently.
VMwarePerlmodules(VIRuntime.pmandVILib.pm)thatprovidesubroutinesforbasic
functionality.
vSphereSDKforPerlUtilityApplicationsManagementapplicationsthatyoucanrunwithout
modificationinyourvirtualdatacenter.Youruneachapplicationwithconnectionparametersandother,
applicationspecificparameters.SeethevSphereSDKforPerlUtilityApplicationsReference.
Getting Started with
vSphere SDK for Perl
1
vSphere SDK for Perl Programming Guide
10 VMware, Inc.
SampleScriptsScriptsthatyoucancustomizeforyourneedsandthatillustratethevSphereSDKfor
Perlsfunctionality.YoumustknowPerltocustomizethescripts.Unliketheutilityapplications,sample
scriptsarenotsupportedbyVMware.
AvSphereSDKforPerlinstallationalsoincludesthefollowinglibraries:
WebServicesforManagementPerlLibraryandExamplesTheWSManagementPerlLibraryallows
youtowritescriptsthatretrieveCIMdatafromtheESXihostusingCIMOM,aservicethatprovides
standardCIMmanagementfunctionsoveraWBEM(WebBasedEnterpriseManagement).See“Web
ServicesforManagementPerlLibrary”
onpage 51.
CredentialStoreLibraryandExamplesAllowsvSphereSDKforPerlapplicationstomanagethe
vSpherecredentialstore.ThecredentialstoreallowsvSphereSDKforPerlscriptstoauthenticate
themselvestoESX/ESXiorvCenterServersystems.See“CredentialStorePerlLibrary”onpage 61.
vCLICommands‐SetofhostmanagementcommandsandasetofDCLIcommandsformanaging
vCenterservices.
Using vSphere SDK for Perl
ThissectionexplainshowtogetstartedwithvSphereSDKforPerlbylookingattwotypicalusagescenarios.
ItalsolistscommonvSphereSDKforPerltasksanddiscussesprogrammingconventions.
Getting Started
IfyouwanttousetheSDKtoretrieveperformanceinformationforahost,youmightperformthefollowing
tasks:
1CheckthevSphereSDKforPerlUtilityApplicationsReferenceortheappsdirectoryforascriptthatretrieves
performanceinformation.
Check/usr/lib/vmware-vcli/appsonLinuxand
Program Files\VMware vSphere CLI\Perl\apps
onWindows.Allutilityapplicationsarefullysupported.
Theviperformance.plscriptretrievesperformancecountersfromthehost.
2Runthescriptwiththe--helpoptionorwithoutanyoptionstoseeitsonlinedocumentation.More
detailedinformationisintheUtilityApplicationsReferenceincludedinthevSphereSDKforPerl
documentation
setandavailablefromtheVMwareWebsite.
3Runtheviperformance.plscriptagainstanESXihost.
viperformance.pl --url https://<host>:<port>/sdk/vimService --username nemo --password fi\$h
--host Aquarium --countertype net --interval 30 --samples 3
Escapecharactersmustprecedespecialcharactersinpasswords.SeeTable 13,“OptionsAvailableforAll
SDKforPerlCommands,”onpage 16foracompletelistofconnectionparameters.
IfyouwanttousetheSDKforataskthatnoneoftheutilityapplicationscanperform,youmightperformthe
following
tasks:
1Checkthe/samplesfolderforasamplescriptthatperformsasimilartask.Thescriptsinthesamples
folderareavailableforcustomization.
2Ifascriptthatperformsasimilartaskisavailable,modifythescript.Ifnoneofthescriptsissuitable,write
anewscriptusingthe
vSphereSDKforPerlsubroutines.
Thefollowingmaterialsareavailableformodifyingorwritingscripts:
NOTEIfyoucannotfindautilityapplication,examinethesamplescripts.Youcanusesamplescriptsas
startingpointsforyourapplication.OnLinux,/usr/share/doc/vmware-vcli/samples,onWindows,
Program Files\VMware\VMware vSphere CLI\Perl\samples.Samplescriptsarenotsupported.
VMware, Inc. 11
Chapter 1 Getting Started with vSphere SDK for Perl
3FollowtheseprogrammingconventionswhenyoumodifyorcreatevSphereSDKforPerlscripts:
Useparameternamesfollowedbyparametervalues,asfollows:
Vim::<subroutine>(<parameter_name>=><value>, <parameter_name>=><value> );
Util::<subroutine>(<parameter_name>=><value>, <parameter_name>=><value> );
Opts::<subroutine>(<parameter_name>=><value>, <parameter_name>=><value> );
UsetheoptionsinTable 13,“OptionsAvailableforAllSDKforPerlCommands,onpage 16to
specifyconnectioninformation.
Usethemechanismdiscussedin“Step2:(Optional)DefineScriptSpecificCommandLineOptions”
onpage 20forspecifyingadditionalscriptspecificoptions.
Common vSphere SDK for Perl Tasks
ThevSphereSDKforPerlincludesutilityapplicationsandsamplescriptsforcommonadministrationtasks.
Sometasksrequireadditionalscripting.SeeChapter 2,“WritingvSphereSDKforPerlScripts,”onpage 19.
vSphere SDK for Perl Programming Conventions
SeveralprogrammingconventionsaredifferentthanyoumightexpectbecausetheSDKinteractswithaserver
usingSOAP/WSDL.
BooleandatatypesSDKapplicationssendandreceiveBooleanvaluesasfollows:
Input(sendingfromtheclientapplication):
Source Description
“WritingvSphereSDKforPerlScripts”on
page 19.
Indepthdiscussionofscriptsthatincludesanexample.
Chapter 4,“vSphereSDKforPerl
SubroutineReference,”onpage 41.
ReferencetovSphereSDKforPerlsubroutines.
“WebServicesforManagementPerl
Library”onpage 51.
AllowsyoutowritescriptsthatretrieveCIMdatafromthe
ESX/ESXihostusingCIMOM,aservicethatprovidesstandardCIM
managementfunctionsoveraWBEM(WebBasedEnterprise
Management).
“CredentialStorePerlLibrary”onpage 61. AllowsvSphereSDKforPerlapplicationstomanagethevSphere
credentialstore.
vSphereAPIReferencedocumentation. Referencetotheserversideobjectyourscriptinteractswith.
Table 1-1. Common Administrative Tasks and SDK Utilities
Task Script Location
Discovery(loggingin) connect.pl /apps/general
Performancemonitoring viperformance.pl(retrieves
performancecountersfromhost)
/apps/performance
Virtualmachinepoweroperations vmcontrol.pl /apps/vm
Virtualmachinesnapshotandrestorefunctionality vmsnapshot.pl,snapshotmanager.pl /apps/vm
Virtualmachinemigration vmmigrate.pl /apps/vm
Hostoperations,forexample,addingastandalone
hosttoavCenterServersystem,shuttingdownand
rebootingahost,andsoon
hostops.pl /apps/host
Viewingorchanging
ofCPUormemoryshare
allocationonavirtualmachine
sharesmanager.pl /apps/vm
vSphere SDK for Perl Programming Guide
12 VMware, Inc.
Output(receivingfromtheserver):
TomatchBooleanvaluesinafilter,usethestringstrueandfalse.See“CreatingandUsingFilters”on
page 33.
Date/TimeTheserverreturnsaSOAPdateTimevalue.YoucanusetheDate::ParsePerlmoduleto
processtheseobjects.
ThevSphereSDKforPerlacceptsonlynativeSOAPdateTimevaluesusingstandarddatetimeformat
withorwithoutfractionalseconds,andwithorwithoutGMT(Z)timezone:
YYYY-MM-DDThh:mm:ssTZD,
forexample,1997-07-16T19:20:30+01:00
YYYY-MM-DDThh:mm:ss.sTZD,forexample,1997-07-16T19:20:30.45+01:00
TheSDKalwaysreturnsdateTimevaluesinthestandarddatetimeformat.
SOAPerrormessageMostlikelyindicatesanerrorontheserver,notanerrorwiththecommunication
totheserver.
vSphere SDK for Perl Common Options
AnumberofoptionsareavailableforanyvSphereSDKforPerlscript.Mostoftheseoptionsallowyouto
specifythehostorhoststoconnectto.Mostoptionsrequireanoptionvalue.
perl <app_name>.pl --<option_name> <option_value>
Forexample,topoweronavirtualmachineusingthevmcontrol.plutilityapplication,youmustspecifythe
nameofthevirtualmachinetopoweron,asfollows:
perl vmcontrol.pl --server <myserver> --username <admin> --password <mypassword> --operation
poweron --vmname <virtual_machine_name>
Runanyapplicationorsamplewithoutanyoptionsorwith--helptoseeitsparametersandexecution
examples.Informationaboutcommonandscriptspecificoptionsisincluded.
Specifying Options
Youcanspecifythecommonoptionsinseveralways,discussedinthissection.
WhenyourunavSphereCLIcommand,authenticationhappensinthefollowingorderofprecedence:
false: Use0,ʹ0ʹ,orʹfalseʹ(capitalizationignored)
true: Use1,ʹ1ʹ,orʹtrueʹ(capitalizationignored)
false: Returnvalueis0
true: Returnvalueis1
I
MPORTANTIfthehostyouaretargetingisinlockdownmode,youcannotexecutePerlscriptsagainstthe
host.
Table 1-2. vSphere CLI Authentication Precedence
Authentication Description See
TargetingvCenter
ServerandUsing
vCenterSingle
SignOn
Ifyouareworkinginanenvironmentthatis
managedbyvCenterSingleSignOn,youcan
specifythevCenterSingleSignOnserverand
ausername,password,andtargethost.
“UsingaSessionFile”onpage 13
Commandline Password(--password),
sessionfile
(--sessionfile),orconfigurationfile
(--config) specifiedonthecommandline.
“UsingaSessionFile”onpage 13
Configurationfile Passwordsspecifiedina.visdkrc
configurationfile.
“UsingaConfigurationFile”onpage 15
VMware, Inc. 13
Chapter 1 Getting Started with vSphere SDK for Perl
Thisorderofprecedencealwaysapplies.Thatmeans,forexample,thatyoucannotoverrideanenvironment
variablesettinginaconfigurationfile.
Authenticating Through vCenter Server and vCenter Single Sign-On
ForallESXihoststhat aremanagedbyavCenterServersystemthatisintegratedwithvCenterSingleSignOn
6.0andlater,youcanauthenticatedirectlytothevCenterServersystem,oryoucanauthorizetovCenter
ServerthroughvCenterSingleSignOn.
BestpracticeistoauthenticatethroughvCenter
SingleSignOn.ThevCenterSingleSignOnserviceis
includedinthePlatformServicesController.ThePlatformServicesControllercanbeembeddedinyour
vCenterServerinstallation,oronePlatformServicesControllercanhandleauthentication,certificate
management,andsomeothertasksformultiplevCenterServersystems.
Youusethe
--pscoptionand,optionally,the--server option.
psc‐SpecifiesthePlatformServicesControllerinstanceassociatedwiththevCenterServersystemthat
managesthehost.
server‐SpecifiesthevCenterServersystemthatmanagesthehost.RequiredifthePlatformServices
ControllerinstanceisassociatedwithmorethanonevCenterServersystem.
vihost‐SpecifiestheESXihost,asinearlierversionsofvCLI.
Example
vminfo.pl --server <vc_HOSTNAME_OR_IP> --psc <psc_HOSTNAME_OR_IP> --vihost
<esxi_HOSTNAME_OR_IP>--username root --password vmware --vihost <esxi_host>
IfthespecifieduserisknowntovCenterSingleSignOn,asessioniscreated.Youcansavethesessionwiththe
--savesessionfileargument,andlaterusethatsessionwiththe--sessionfile argument.
UsingasessionfileresultsinlessoverheadandbetterperformancethanconnectingtothePlatformServices
Controller
repeatedly.
Using a Session File
Thesave_session.plscriptintheapps/sessiondirectoryillustrateshowtocreateasessionfile.Youcan
modifythescriptandincludeitinyourownapplication,orcreateasessionfileusingthescriptonthe
commandline,andthenpassinthatsessionfilewhenrunningvSphereSDKforPerl
commands.See“Saving
Sessions”onpage 36.
Thesessionfiledoesnotrevealpasswordinformation.Ifasessionfileisnotusedfor30minutes,thesession
expires.
To create and use a session file
1 Connecttothedirectorywherethescriptislocated,forexample,onWindows:
cd C:\Program Files\VMware\VMware vSphere CLI\Perl\apps\session
Environment
variable
Passwordspecifiedinanenvironment
variable.
“SettingEnvironmentVariables”onpage 14
Credentialstore Passwordretrievedfromthecredentialstore. “CredentialStorePerlLibraryonpage 61
Currentaccount
(ActiveDirectory)
Currentaccountinformationus edtoestablish
anSSPIconnection.Windowsonly.
.“UsingMicrosoftWindowsSecuritySupport
ProviderInterface(SSPI)”onpage 15
Prompttheuserfora
password.
NOTEYoucannotusethisapproachifvCenterServerisintegratedwithvCenterSingleSignOn5.0.
Table 1-2. vSphere CLI Authentication Precedence (Continued)
Authentication Description See
vSphere SDK for Perl Programming Guide
14 VMware, Inc.
2Runsave_session.pl.Youmustsupplyconnectionparametersandthenameofasessionfileinwhich
thescriptcansaveanauthenticationcookie.
perl save_session.pl --savesessionfile <location> --server <esxi_host>
Forexample:
perl save_session.pl --savesessionfile C:\Temp\my_session --server my_server
Ifyouspecifyaserverbutnousernameorpassword,thescriptpromptsyou.
3Youcannowrunscriptsinthe\appsor\samplesdirectoryoryourownscriptsandpassinthesession
fileusingthe--sessionfileparameterasfollows:
<command> --sessionfile <sessionfile_location> <command_options>
Forexample:
perl hostinfo.pl --sessionfile C:\Temp\my_session
Youcanusethecodeinthe\apps\session\save_session.plutilityapplicationinsideyourownvSphere
SDKforPerlapplication.Ifacalltotheserverthrowsanexception,yourapplicationshouldterminatethe
sessiontoavoidsessionleaks.Youcoulddothiswithanerrorhandlerthatrunsdisconnect()orlogout(),
forexample:
eval {
# ... insert program here ...
};
if ($@) {
print "Fatal error: $@";
Util::disconnect();
exit(1);
}
Youcanalsousethe_END_pseudosignalhandlertoperformadisconnect,asfollows:
$SIG{__END__} = sub { Util::disconnect(); }
Passing Parameters at the Command Line
Passparametersatthecommandlineusingoptionnameandoptionvaluepairs(someoptionshavenovalue).
--<optionname> <optionvalue>
Thefollowingexampleconnectstotheserverasusersnow-whitewithpassworddwarf$.Thefirstexample
(Linux)usesanescapecharacterbeforeeachspecialcharacter,theotherexamplesusesinglequotes(Linux)
anddoublequotes(Windows).
Linux
vminfo.pl --server <server> --username snow\-white --password dwarf\$ --vmname <name>
vminfo.pl --server <server> --username ‘snow-white’ --password ‘dwarf$’ --vmname <name>
Windows
vminfo.pl --server <server> --username “snow-white” --password “dwarf$” --vmname <name>
Setting Environment Variables
YoucansetenvironmentvariablesinaLinuxprofile,intheEnvironmentpropertiesdialogboxofthe
MicrosoftWindowsSystemcontrolpanel,or,forthecurrentsession,atthecommandline.Environment
variablesarelistedwhenyourunacommandwith--help.
Thefollowingexampleshowsthecontentsofa
/root/.visdkrc filethatusesenvironmentvariables:
VI_SERVER = <server>
VI_USERNAME = <usr>
VI_PASSWORD = <root_password>
NOTEIfyouuseasessionfile,anyotherconnectionparametersareignored.
VMware, Inc. 15
Chapter 1 Getting Started with vSphere SDK for Perl
VI_PROTOCOL = https
VI_PORTNUMBER = 443
Donotescapespecialcharactersinthefilethatspecifiesenvironmentvariables.
Ifyouhavesetupyoursystemtorunthisfile,youcanrunscriptsonthespecifiedserverafterwards.
Using a Configuration File
Aconfigurationfileisatextfilethatcontainsvariablenamesandsettings.Variablescorrespondingtothe
connectionoptionsareshowninTable 13,“OptionsAvailableforAllSDKforPerlCommands,”onpage 16.
Use--configiftheconfigurationinformationissavedinadifferentfilethan./visdkrc.Ifyou
specify
--config,thesystemignoresthe./visdkrcsettings.
Youcanusethe--configoptiontorunascriptwiththeconfigurationfile,forexample:
connect.pl --config <my_saved_config> --list
Usingaconfigurationfileisusefulforrepeatedlyenteringconnectiondetails.Ifyouhavemultiple
vCenter ServerorESX/ESXisystemsandyouadministereachsystemindividually,youcancreatemultiple
configurationfileswithdifferentnames.Whenyouwanttorunacommandorasetofcommandsonaserver,
youpass
inthe--configoptionwiththeappropriatefilenameatthecommandline.
Using Microsoft Windows Security Support Provider Interface (SSPI)
Youcanusethe--passthroughauthcommandlineargumenttologintoavCenterServersystem(vCenter
Serverversion2.5Update2orlater).Using--passthroughauthpassesthecredentialsoftheexecutinguser
totheserver.Iftheexecutinguserisknownbyboththemachinefromwhichyouaccessthe
vCenterServer
systemandthemachinerunningthevCenterServersystem,noadditionalauthenticationisrequired.
IfSDKcommandsandthevCenterServersystemrunonthesamemachine,alocalaccountfortheexecuting
userworks.Iftheyrunondifferentmachines,thentheexecutingusermusthavean
accountinadomain
trustedbybothmachines.
SSPIsupportsanumberofprotocols.Bydefault,itselectstheNegotiateprotocol,whichindicatesthatclient
andserverattempttofindamutuallysupportedprotocol.Alternatively,youcanuse
--passthroughauthpackagetospecifyanotherprotocolsupportedbySSPI.Kerberos,theWindows
standardfor
domainlevelauthentication,iscommonlychosen.
IfthevCenterServersystemisconfiguredtoacceptonlyaspecificprotocol,specifyingtheprotocoltovSphere
SDKforPerlcommandswith --passthroughauthpackagemightberequiredforsuccessfulauthentication
totheserver.Ifyouuse--passthroughauth,youdonothavetospecifyauthentication
informationinany
otherway.Forexample,torunconnect.plontheserver,youcanusethefollowingcommandatthe
commandline.
<command> <login_params> --passthroughauth
SeetheMicrosoftWebsiteforadetaileddiscussionofSSPI.
ThefollowingexampleconnectstoaserverthathasbeensetuptouseSSPI.Whenyourunthecommand,the
systemcallsvminfo.plwiththe--vmnameoption.Thesystemdoesnotpromptforausernameandpassword
because
thecurrentuserisknowntotheserver.
vminfo.pl --server <vc_server> --passthroughauth --passthroughauthpackage “Kerberos”
--vihost my_esx --vmname <name>
CAUTIONLimitreadaccesstoaconfigurationfile,especiallyifitcontainsusercredentials.
NOTEUsingSSPIissupportedonlywhenyouruncommandsfromWindows,anduseavCenterServer
systemasthetargetserver.
vSphere SDK for Perl Programming Guide
16 VMware, Inc.
Common Options Reference
ThefollowingtablelistsoptionsthatareavailableforallvSphereSDKforPerlscripts.Usetheparameteron
thecommandlineandthevariableortheparameterinconfigurationfiles.
Table 1-3. Options Available for All SDK for Perl Commands
Option and Environment Variable Description
--cacertsfile <certsfile>
-t <certs_file>
VI_CACERTFILE=<cert_file_path>
ESXCLIcommandsonly.
UsedtospecifytheCA(CertificateAuthority)certificatefile,inPEMformat,
toverifytheidentityofthevCenterServersystemorESXisystemtorunthe
commandon.
InvCLI6.0andlater,youcanonlyrunESXCLIcommandsifatrust
relationshipexistsbetween
thehostyouarerunningthecommandonandthe
systemyouaretargetingwiththe--serveroption(ESXihostorvCenter
Serversystem).YoucanestablishthetrustrelationshipbyspecifyingtheCA
certificatefileorbypassinginthethumbprintforeachtargetserver(ESXihost
orvCenterServer
system).
--config <cfg_file_full_path>
VI_CONFIG=<cfg_file_full_path>
Usestheconfigurationfileatthespecified location.
Specifyapaththatisreadablefromthecurrentdirectory.
--credstore <credstore>
VI_CREDSTORE=<credstore>
Nameofacredentialstorefile.Defaultsto
<HOME>/.vmware/credstore/vicredentials.xmlonLinuxand
<APPDATA>/VMware/credstore/vicredentials.xmlonWindows.
CommandsforsettingupthecredentialstoreareincludedinthevSphereSDK
for
Perl,whichisinstalledwithvCLI.ThevSphereSDKforPerlProgramming
Guideexplainshowtomanagethecredentialstore.
--encoding <encoding>
VI_ENCODING=<encoding>
Specifiestheencodingtobeused.Severalencodingsaresupported.
utf8
cp936(SimplifiedChinese)
shftjis(Japanese)
iso-885901(German).
Youcanuse--encodingtospecifytheencodingvCLIshouldmaptowhenit
isrunonaforeignlanguagesystem.
--passthroughauth
VI_PASSTHROUGHAUTH
Ifyouspecifythisoption,thesystemusestheMicrosoftWindowsSecurity
SupportProviderInterface(SSPI)forauthentication.Trustedusersarenot
promptedforausernameand
password.SeetheMicrosoftWebsitefora
detaileddiscussionofSSPI.
ThisoptionissupportedonlyifyouareconnectingtoavCenterServersystem.
--passthroughauthpackage
<package>
VI_PASSTHROUGHAUTHPACKAGE=
<package>
Usethisoptionwith--passthroughauthtospecifyadomainlevel
authenticationprotocoltobeusedbyWindows.Bydefault,SSPIusesthe
Negotiate
protocol,whichmeansthatclientandservertrytonegotiatea
protocolthatbothsupport.
IfthevCenterServersystemtowhichyouareconnectingisconfiguredtouse
aspecificprotocol,youcanspecifythatprotocolusingthisoption.
ThisoptionissupportedonlyifyouarerunningvCLIon
aWindowssystem
andconnectingtoavCenterServersystem.
--password <passwd>
VI_PASSWORD=<passwd>
Usesthespecifiedpassword(usedwith--username)tologintotheserver.
If--serverspecifiesavCenterServersystem,theusernameandpassword
applytothatserver.IfyoucanlogintothevCenterServersystem,you
neednoadditionalauthenticationtoruncommandsontheESXihoststhat
servermanages.
If--serverspecifiesanESXihost,theusernameandpasswordapplyto
thatserver.
Usetheemptystring(' 'onLinuxand“ “onWindows)toindicateno
password.
Ifyoudonotspecifyausernameandpasswordonthecommandline,the
systempromptsyouanddoes
notechoyourinputtothescreen.
--portnumber <number>
VI_PORTNUMBER=<number>
Usesthespecifiedporttoconnecttothesystemspecifiedby--server.Default
is443.
VMware, Inc. 17
Chapter 1 Getting Started with vSphere SDK for Perl
Hello Host: Running Your First Script
Beforeyourunyourfirstscript,youneedthefollowing:
SuccessfulvSphereSDKforPerlinstallation.SeethevSphereSDKforPerlInstallationGuideforinformation.
AccesstooneofthesupportedvSpherehosts.Performaconnectioncheckusingtheprocessdescribedin
“UsetheManagedObjectBrowsertoExploreServerSideObjects”onpage 24.
To run the connect.pl script
1Atacommandprompt,changetothe/apps/generaldirectory.
C:\Program Files\VMware\VMware vSphere CLI\Perl\apps\general
--protocol <HTTP|HTTPS>
VI_PROTOCOL=<HTTP|HTTPS>
Usesthespecifiedprotocoltoconnecttothesystemspecifiedby--server.
DefaultisHTTPS.
--psc <hostname_or_IP>
VI_PSC=<hostname_or_IP>
HostnameorIPaddressofthePlatformServicesControllerinstancethatis
associatedwiththevCenterServersystemthatmanagesthehost.Inmany
cases,thePlatformServicesControllerisembeddedin
thevCenterServer
system,butexternalPlatformServicesControllerinstancesaresupportedas
well.Forthosecases,usethe--serveroptiontospecifythevCenterServer
systemthatmanagesthehost.
Thisoptionimpliesus erauthenticationwithvCenterSingleSignOn.Theuser
youspecifymustbeabletoauthenticateto
vCenterSingleSignOn.
--savesessionfile <file>
VI_SAVESESSIONFILE=<file>
Savesasessiontothespecifiedfile.Thesessionexpiresifithasbeenunused
for30minutes.
--server <server>
VI_SERVER=<server>
UsesthespecifiedESXiorvCenterServersystem.Defaultislocalhost.
If--serverpointstoavCenterServersystem,youcanalsospecifythe--psc
option
tologintothevCenterServersystemwithvCenterSingleSignOn.
Usethe--vihostoptiontospecifytheESXihostthatyouwanttorunthe
commandagainst.SeeAuthenticatingThroughvCenterServerandvCenter
SingleSignOn”onpage 13.
--servicepath <path>
VI_SERVICEPATH=<path>
Usesthespecifiedservicepathtoconnectto
theESXihost.Defaultis
/sdk/webService.
--sessionfile <file>
VI_SESSIONFILE=<file>
Usesthespecifiedsessionfiletoloadapreviouslysavedsession.Thesession
mustbeunexpired.
--thumbprint <thumbprint>
VI_THUMBPRINT=<thumbprint>
ExpectedSHA1hostcertificatethumbprintifnoCAcertificatesfileis
providedinthe--cacertsfile argument.Thethumbprintisreturnedbythe
serverintheerrormessage
ifyouattempttorunacommandwithout
specifyingathumbprintorcertificatefile.
--url <url>
VI_URL=<url>
ConnectstothespecifiedvSphereWebServicesSDKURL.
--username <u_name>
VI_USERNAME=<u_name>
Usesthespecifiedusername.
If--serverspecifiesavCenterServersystem,theusernameand
passwordapplytothatserver.IfyoucanlogintothevCenterServer
system,youneednoadditionalauthenticationtoruncommandsonthe
ESXihoststhatservermanages.
If--serverspecifiesanESXisystem,theusernameandpasswordapply
tothatsystem.
Ifyoudonotspecifyausernameandpasswordonthecommandline,the
systempromptsyouanddoesnotechoyourinputtothescreen.
--vihost <host>
-h <host>
WhenyourunavCLIcommandwiththe
--serveroptionpointingtoa
vCenterServersystem,use--vihosttospecifytheESXihosttorunthe
commandagainst.
N
OTE:Thisoptionisnotsupportedforeachcommand.Ifsupported,the
optionisincludedwhenyourun<cmd> --help.
Table 1-3. Options Available for All SDK for Perl Commands
Option and Environment Variable Description
vSphere SDK for Perl Programming Guide
18 VMware, Inc.
/usr/lib/vmware-vcli/apps
2Runconnect.plasfollows:
connect.pl --url https://<host>:<port>/sdk/vimService --username myuser --password mypassword
Thescriptreturnsaninformationmessageandthehosttime.
Youarenowreadytorunotherscripts,orcreatenewscripts.
N
OTEYoucanrunanyutilityapplicationwith--helptodisplayinformationaboutitsparameters.
VMware, Inc. 19
2
ThischapterusesasimpleexamplescripttoillustratehowtowriteavSphereSDKforPerlscript.Thechapter
alsoexploresthebasicsofthevSphereAPIobjectmodel.
Thechapterincludesthesetopics:
“BasicvSphereSDKforPerlScript”onpage 19
“UnderstandingServerSideObjects”onpage 24
“UnderstandingPerlViewObjects”onpage 28
“WorkingwithViewObjectPropertyValuesonpage 28
“UnderstandingOperationsandMethods”onpage 30
“UpdatingViewObjects”onpage 32
Basic vSphere SDK for Perl Script
vSphereSDKforPerlscriptsretrieveobjects,suchasvirtualmachines,fromtheserverandworkwiththese
objects.vSphereSDKforPerlscriptsfollowthebasicpatternshowninTable 21.
Writing vSphere SDK for Perl Scripts
2
NOTEThischapterdoesnotdiscussPerlbasics.YouareexpectedtoknowPerlandtounderstandits
programmingconventions.WhenyoudevelopavSphereSDKforPerlscript,followPerlstandardsfor
filenames,imports,andgeneralprocessingflow.Usetheappropriatefilenameextensionforthetypeofscript
orapplication
youarecreating(.plonWindowsand.plornosuffixonUNIXlikesystems).
IMPORTANTThesamplescriptdoesnotusefiltersorpropertyfiltersforefficiency.See“RefiningvSphereSDK
forPerlScripts”onpage 33forinformationaboutthosetopics.
Table 2-1. Basic vSphere SDK for Perl Script (simpleclient.pl)
Code element Discussed in
#!/usr/bin/perl
use strict;
use warnings;
use VMware::VIRuntime;
“Step1:ImportthevSphereSDKforPerl
Modulesonpage 20.
vSphere SDK for Perl Programming Guide
20 VMware, Inc.
Step 1: Import the vSphere SDK for Perl Modules
AllvSphereSDKforPerlscriptsmustusetheVMware::VIRuntimemodule:
use VMware::VIRuntime;
Thismodulehandlesallclientsideinfrastructuredetails.Forexample,ittransparentlymapsdatatypesand
provideslocalPerlinterfacestoserversideobjects.Themodulealsoloadssubroutinesthatyoucanuseto
connecttoavCenterServerorESX/ESXisystemandtoretrieveviews.Viewsaretheclientside
Perlobjects
thatencapsulatethepropertiesandoperationsofserversidemanagedobjects.Thesubroutinesareorganized
intodifferentpackages:
TheOptspackagesubroutineshandlebuiltinoptionsandcreatingcustomoptions.
TheUtilpackagesubroutinesfacilitateroutinetasks,suchassettingupandclosingconnectionstothe
server.
TheVimpackagesubroutinesaccessserversidemanagedobjects,instantiatelocalproxyobjects(views),
updateproperties,andrunlocalmethodsthatresultinoperationsonremoteservers.
See“vSphereSDKforPerlSubroutineReference”onpage 41.
Step 2: (Optional) Define Script-Specific Command-Line Options
Whenyourunascriptfromthecommandline,youusuallyspecifyconnectioninformationandmightalso
specifyotherinformationsuchasavirtualmachinethatyouwanttopowerofforahostforwhichyouneed
statusinformation.vSphereSDKforPerlletsyouspecifytheseoptionsina
varietyofways.See“Specifying
Options”onpage 12.
Anumberofcommoncommandlineoptions,mostofthemconnectionoptions,arealreadydefinedforall
utilityapplications(seeTable 13,“OptionsAvailableforAllSDKforPerlCommands,onpage 16).In
addition,mostapplicationshaveapplicationspecificoptionsyoupass
tothescriptatexecutiontime.
my %opts = (
entity => {
type => "=s",
variable => "VI_ENTITY",
help => "ManagedEntity type: HostSystem, etc",
required => 1,
},
);
Opts::add_options(%opts);
Opts::parse();
Opts::validate();
“Step2:(Optional)DefineScriptSpecific
CommandLineOptions”onpage 20.
Util::connect();
“Step3:ConnecttotheServeronpage 22.
# Obtain all inventory objects of the specified type
my $entity_type = Opts::get_option('entity');
my $entity_views = Vim::find_entity_views(
view_type => $entity_type);
“Step4:ObtainViewObjectsofServerSide
ManagedObjects”onpage 22.
# Process the findings and output to the console
foreach my $entity_view (@$entity_views) {
my $entity_name = $entity_view->name;
Util::trace(0, "Found $entity_type:
$entity_name\n");
}
“Step5:ProcessViewsandReportResults”
onpage 22.
# Disconnect from the server
Util::disconnect();
“Step6:ClosetheServerConnection”on
page 23.
Table 2-1. Basic vSphere SDK for Perl Script (simpleclient.pl) (Continued)
Code element Discussed in
/