ネットワーク上にあるhpサーバのiLO IPアドレスとライセンスを収集するスクリプト

2019/01/09 追記

オリジナルのNachoTech Blogがアクセスできなくなっていたので、「https://github.com/osakanataro/findilos」にオリジナルと後述の改変版をアップロードした。


hpサーバをリモートから制御するために使用するiLO。
稼働させたあとにIPアドレスを確認するのがめんどくさい。
そういう場合に、総当たりでiLOのIPアドレスを確認するスクリプトがあった。

NachoTech Blogの「How to find all the iLO’s on your network」にあるfindilosである。

早速ダウンロードして実行してみる。

[root@adserver ~]# ./findilos 172.17.17.0/24
Scanning...
--------------- ------ -------- ------------ -------------------------
iLO IP Address  iLO HW iLO FW   Server S/N   Server Model
--------------- ------ -------- ------------ -------------------------
172.17.17.xxx   N/A    1.26     CN71xxxMxx   ProLiant DL360 G7
1 iLOs found on network target 172.17.17.0/24
[root@adserver ~]#

iLO HWのモデル名は拾ってくれない。

blogのコメントを確認していくと、元のスクリプトはiLO-2までしか対応しておらず、その後のバージョンについてはコメント欄にある修正を実施すれば良いようだ。

また、iLO Advanceを買っている場合に、そのライセンスコードを表示するための案も提示されていた。

ただ、スクリプト例は汚い実装となっていて、せっかくの元スクリプトを活かしていない形だったので、元スクリプトの実装に従ってライセンスを表示するバージョンを作成した。

その実行例がこちら

[root@adserver ~]# ./findilos 172.17.17.0/24
Scanning...
--------------- ------ -------- ------------ ------------------------- -------------------- -----------------------------
iLO IP Address  iLO HW iLO FW   Server S/N   Server Model              iLO Edition          iLO Licence Key
--------------- ------ -------- ------------ ------------------------- -------------------- -----------------------------
172.17.17.xxx   iLO-3  1.26     CN71xxxMxx   ProLiant DL360 G7         iLO 3 Advanced       xxxxx-xxxxx-xxxxx-xxxxxx-xxxxx
1 iLOs found on network target 172.17.17.0/24
[root@adserver ~]#

スクリプトの修正例は以下

#!/bin/bash
#
# findilos - Search a local network segment for iLOs
#            The iLO is the Integrated Lights-Out management processor
#            used on HP ProLiant and BladeSystem servers
#
scriptversion="1.0"
#
# Author: iggy@nachotech.com
#
# Website: http://blog.nachotech.com
#
# Requires: tr sed expr curl nmap
#
# Tested with: Nmap 4.20, curl 7.17.1, RHEL4
#
# Note: Discovery of an iLO is dependent upon the Virtual Media port
#       being set to the default of 17988.  If this has been changed
#       by the iLO administrator, then this script will NOT find it.
#
#       Also, if the iLO XML Reply Data Return has been Disabled by
#       the iLO administrator, this script will not be able to
#       gather any information about the server.  It will still be
#       discovered, but all you will see is its IP address.
#
# GLOBAL VARIABLES
scriptname="findilos"
iloips="/tmp/tmpilos.$$"
iloxml="/tmp/tmpiloxml.$$"
ilohwvers="/tmp/tmpilohwvers.$$"
declare -i ilosfound=0
# FUNCTIONS
function parseiloxml {
  fgrep "$1" $iloxml > /dev/null 2>&1
  if [ $? -ne 0 ]
  then
    # tag not found in xml output, return empty string
    parsedstring="N/A"
  else
    # tag was found - now we parse it from the output
    tempstring=$( cat $iloxml | tr -d -c [:print:] | sed "s/^.*<$1>//" | sed "s/<.$1.*//")
    # trim off leading and trailing whitespace
    parsedstring=`expr match "$tempstring" '[ \t]*\(.*[^ \t]\)[ \t]*$'`
  fi
}
function is_installed {
  which $1 > /dev/null 2>&1
  if [ $? -ne 0 ]
  then
    printf "\nERROR: %s not installed.\n\n" $1
    exit 255
  fi
}
# MAIN
# check for tools that we depend upon
is_installed tr
is_installed sed
is_installed expr
is_installed curl
is_installed nmap
# check syntax - should have 1 and only 1 parameter on cmdline
if [ $# -ne 1 ]; then
  printf "%s %s ( http://blog.nachotech.com/ )\n" $scriptname $scriptversion
  printf "Usage: %s {target network specification}\n" $scriptname
  printf "TARGET NETWORK SPECIFICATION:\n"
  printf "  Can pass hostnames, IP addresses, networks, etc.\n"
  printf "  Ex: server1.company.com, company.com/24, 192.168.0.1/16, 10.0.0-255.1-254\n"
  printf "EXAMPLE:\n"
  printf "  %s 16.32.64.0/22\n" $scriptname
  exit 255
fi
iprange=$1
# prepare lookup file for iLO hardware versions
cat > $ilohwvers << EOF
iLO-1 shows hw version ASIC:  2
iLO-2 shows hw version ASIC:  7
iLO-3 shows hw version ASIC: 8
iLO-3 shows hw version ASIC: 9
iLO-4 shows hw version ASIC: 12
iLO-4 shows hw version ASIC: 16
i-iLO shows hw version T0
EOF
#
# scan a range of IP addresses looking for an
# open tcp port 17988 (the iLO virtual media port)
#
printf "Scanning..."
nmap -n -P0 -sS -p 17988 -oG - $iprange | fgrep /open/ | awk '{print $2}' > $iloips
printf "\n\n"
#
# open and read the list of IP addresses one at a time
#
exec 3< $iloips
echo "--------------- ------ -------- ------------ ------------------------- -------------------- -----------------------------"
echo "iLO IP Address  iLO HW iLO FW   Server S/N   Server Model              iLO Edition          iLO Licence Key"
echo "--------------- ------ -------- ------------ ------------------------- -------------------- -----------------------------"
while read iloip <&3 ; do
  ilosfound=$ilosfound+1
  #
  # attempt to read the xmldata from iLO, no password required
  #
  curl --proxy "" --fail --silent --max-time 3 http://$iloip/xmldata?item=All > $iloxml
  #
  # parse out the Server model (server product name)
  # from the XML output
  #
  parseiloxml SPN;  servermodel=$parsedstring
  parseiloxml SBSN; sernum=$parsedstring
  parseiloxml PN;   ilotype=$parsedstring
  parseiloxml FWRI; ilofirmware=$parsedstring
  parseiloxml HWRI; ilohardware=$parsedstring
  ilohwver=$(grep "$ilohardware" $ilohwvers|awk '{print $1}')
  if [ "$ilohwver" == "" ]; then
    ilohwver="N/A"
  fi
  if [ "$sernum" == "" ]; then
    sernum="N/A"
  fi
  # add start
  curl --proxy "" --fail --silent --max-time 3 http://$iloip/xmldata?item=CpqKey > $iloxml
  parseiloxml LNAME; ilomodel=$parsedstring
  parseiloxml KEY; ilokey=$parsedstring
  # add end
  printf "%-15s %-6s %-8s %-12s %-25s %-20s %-30s\n" $iloip "$ilohwver" "$ilofirmware" "$sernum" "$servermodel" "$ilomodel" "$ilokey"
done
printf "\n%d iLOs found on network target %s.\n\n" $ilosfound $iprange
rm -f $iloips $iloxml $ilohwvers
exit 0

PowerCLIで対象の仮想マシンを選択してvMotionを実行

VMware vSphere環境で、PowerCLIを使って、仮想マシンのvMotionを行うスクリプトを作成した。

ブラウザを起動し、vSphere Web Clientにログインして、vMotionを実行するまでにかかる時間と
PowerShellを起動して、コマンドを実行する時間を比べると
コマンドを実行したほうがずっと早い、ということで作成した。

というか、vSphere Web Clientは重すぎ!

# 普通のPowerShell/PowerShell ISEからvSphere PowerCLIのコマンドを使うために必要な設定
Add-PSSnapin VMware.VimAutomation.Core
# vCenterサーバに接続
$VC=Connect-VIServer -User "administrator@vsphere.local" -Password "パスワード" "vCenterサーバ"  -WarningAction 0
# 仮想マシンの選択
$VM=Get-VM | Out-GridView -Title "Please select VM" -PassThru

# 選択した仮想マシンが所属しているクラスタのESXiホストリストから選択
$ESX=Get-VMHost -Location  ($VM.ResourcePool).Name | Out-GridView -Title "Please select ESXi host" -PassThru

# 選択したものを表示
Write-Host "VirtualMachine:" $VM.Name
Write-Host "Move from:" $VM.VMHost " to:" $ESX.Name

# vMotionを実行
Move-VM -VM $VM -Destination $ESX

なお、「$VM=Get-VM | Out-GridView -Title “Please select VM” -PassThru」を
「$VM=Get-VM | Select Name,VMHost | Out-GridView -Title “Please select VM” -PassThru」
という風に替えると、選択ウィンドウに表示する内容を変えることができる。

<注意>
WindowsにインストールされているPowerShellのバージョンが低いと「Out-GridView -PassThru」が利用できないため、動作しません。
たしか、PowerShell ver3以降が必要だったような・・・

Azure上の仮想マシンのディスク拡張手法 2016年1月版

Azure上の仮想マシンのディスクがいっぱいになったので拡張する必要があった。

2015年6月にやったときは、「Azure上の仮想ディスクを拡張する」の手順でやろうとしたら、Windows7のPowerShellからではうまくいかずに、WindowsServer2012R2の仮想マシンを別途立て、そこから実行して拡張した。

で・・・今回、Windows7から実行できるようになっていないかを確認しつつ手順を確認していった。

参考資料
・「How to install and configure Azure PowerShell
・「Azure 仮想マシン (IaaS VM) のディスクの拡張について

2016年1月18日時点でのポイント

・最新版のAzure PowerShellは、Githubの「https://github.com/Azure/azure-powershell」で公開されている

・最新版はversion 1.1.0。ただし、PoewrShell 1.0,2.0環境では動かない。

・インストールは「Microsoft Web Platform Installer」による統合的なインストールか、「http://aka.ms/webpi-azps」(今日時点だとWindowsAzurePowershellGet.3f.3f.3fnew.exeがダウンロードされる)による単独インストールにて行う
(古いバージョンは勝手にアンインストールしてくれる)

・ディスク拡張時は、Aazure仮想マシンは停止している必要がある

・「Update-AzureDisk」は、ラベル名も指定しないとエラーになる。
 しかも、ラベル名設定していない場合に「-Label “”」とやってもエラーになる。
 「-Label ” “」とスペースでもいいので指定しなければならない

・現状の仮想ディスクのラベル名情報を確認するには「Get-AzureDisk」で行う

・以前はサブスクリプションの選択とかストレージアカウントの選択など、面倒な処理が必要だったが
 省略できるようになっている。

実際にやった手順の概要

1. Microsoft Azure PowerShellを起動
2. 「Add-AzureAccount」で認証
3. 「Get-AzureVM」でAzure仮想マシン一覧を取得

PS C:\> Get-AzureVM

ServiceName                             Name                                    Status
-----------                             ----                                    ------
service-test                            webserver1                              ReadyRole
service-test                            sqlserver1                              ReadyRole
service-test2                           webserver1                              StoppedVM
service-test2                           sqlserver1                              StoppedVM

PS C:\>

4. 対象仮想マシンの仮想マシン情報を取得
「(Get-AzureVM -ServerName サービス名 -Name 仮想マシン名).VM」を実行する。

PS C:\> (Get-AzureVM -ServiceName servite-test2 -Name sqlserver1).VM

AvailabilitySetName               :
ConfigurationSets                 : {Microsoft.WindowsAzure.Commands.ServiceManagement.Model.NetworkConfigurationSet}
DataVirtualHardDisks              : {servite-test2-sqlserver1-0-201412020519500167, servite-test2-sqlserver1-1-201412020521210099}
Label                             :
OSVirtualHardDisk                 : Microsoft.WindowsAzure.Commands.ServiceManagement.Model.OSVirtualHardDisk
RoleName                          : servite-test2
RoleSize                          : Standard_D2
RoleType                          : PersistentVMRole
WinRMCertificate                  :
X509Certificates                  :
NoExportPrivateKey                : False
NoRDPEndpoint                     : False
NoSSHEndpoint                     : False
DefaultWinRmCertificateThumbprint :
ProvisionGuestAgent               : True
ResourceExtensionReferences       : {BGInfo, IaaSAntimalware}
DataVirtualHardDisksToBeDeleted   :
VMImageInput                      :
PS C:\>

上記出力中の「DataVirtualHardDisks」がディスクの名前。
このAzure仮想マシンには2つのディスクが接続されている。

5. 「Get-AzureDisk -DiskName “ディスクの名前”」でディスク情報の詳細を取得

PS C:\> Get-AzureDisk -DiskName "servite-test2-sqlserver1-0-201412020519500167"

AffinityGroup        :
AttachedTo           : RoleName: sqlserver1
                       DeploymentName: sqlserver1
                       HostedServiceName: service-test2
IsCorrupted          : False
Label                :
Location             : Japan West
DiskSizeInGB         : 200
MediaLink            : https://xxxxxxxxxx.blob.core.windows.net/vhds/sqlserver1-E-drive.vhd
DiskName             : servite-test2-sqlserver1-0-201412020519500167
SourceImageName      :
OS                   :
IOType               : Standard
OperationDescription : Get-AzureDisk
OperationId          : 2905xxxx-xxxx-xxxx-xxxx-1252bc53xxxx
OperationStatus      : Succeeded

PS C:\>

6. 「Update-AzureDisk -DiskName “ディスク名” -ResizedSizeInGB 数値 -Label “ラベル名”」でディスクの容量指定

PS C:\> Update-AzureDisk -DiskName "servite-test2-sqlserver1-0-201412020519500167" -ResizedSizeInGB 250 -Label " "

OperationDescription                    OperationId                             OperationStatus
--------------------                    -----------                             ---------------
Update-AzureDisk                        9154xxxx-xxxx-xxxx-xxxx-f79f842fxxxx    Succeeded
PS C:\>

Get-AzureDiskで確認したときに「Label:」になにもないからといって、-Labelを指定しないと・・・

PS C:\> Update-AzureDisk -DiskName "servite-test2-sqlserver1-0-201412020519500167" -ResizedSizeInGB 250
Update-AzureDisk : 値を Null にすることはできません。
パラメーター名:parameters.Label発生場所 行:1 文字:1
+ Update-AzureDisk -DiskName "servite-test2-sqlserver1-0-201412020519500167" -R ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Update-AzureDisk]、ArgumentNullException
    + FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.ServiceManagement.IaaS.UpdateAzureDiskCommand

PS C:\>

なにも設定されていないから「-Label “”」としても・・・

PS C:\> Update-AzureDisk -DiskName "servite-test2-sqlserver1-0-201412020519500167" -ResizedSizeInGB 250 -label ""
Update-AzureDisk : パラメーター 'Label の引数を確認できません。引数が null または空です。null または空でない引数を指定して、コマンドを再度実行してください。発生場所 行:1 文字:106
+ ... InGB 250 -label ""
+                    ~~
    + CategoryInfo          : InvalidData: (:) [Update-AzureDisk]、ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.WindowsAzure.Commands.ServiceManagement.IaaS.
   UpdateAzureDiskCommand

PS C:\>

と、めんどくさいです。
「-Label ” “」とスペースでもいいので、何か文字列を指定すると、コマンドが実行できます。

7. 仮想マシンの電源ON
8. OS内でファイルシステムの拡張を実行

以上で拡張が完了です。

vSphere PowerCLIの一部コマンドがPowerShell ISEで動作しない

2016/12/15追記

Add-Snappinは、古いPowerShellの場合だけだったようなので、新しいバージョンの場合にも対応したものを下記に記載しています。

vSphere PowerCLIの一部コマンドがPowerShell ISEで動作しない 2016/12/15版


vSphere PowerCLIで変な動作に遭遇した。
vSphere PowerCLIの一部コマンドがPowerShell ISE上だと動作しない、という問題である。
元々、PowerShell ISEの標準設定ではvSphere PowerCLIのコマンドは動かない。
「Add-PSSnapin VMware.VimAutomation.Core」を追加し、モジュールを読み込ませる必要があるのだが、それを行っても動かないものがいくつかあることが分かった。

まずは状況の確認から・・・

現在のvSphere Power CLIのバージョンを確認
Determining the build number for vSphere PowerCLI or VI Toolkit for Windows」より「Get-VIToolkitVersion」を実行。

PowerCLI C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI> Get-VIToolkitVersion

PowerCLI Version
----------------
   VMware vSphere PowerCLI 6.0 Release 1 build 2548067
---------------
Component Versions
---------------
   VMWare AutoDeploy PowerCLI Component 6.0 build 2358282
   VMWare ImageBuilder PowerCLI Component 6.0 build 2358282
   VMware License PowerCLI Component 6.0 build 2315846
   VMware vSphere PowerCLI Component 6.0 build 2548068
   VMware Cloud Infrastructure Suite PowerCLI Component 6.0 build 2548068
   VMware HA PowerCLI Component 6.0 build 2510422
   VMware PowerCLI Component for Storage Management 6.0 build 2522368
   VMware VDS PowerCLI Component 6.0 build 2548068



PowerCLI C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI>

(ちなみに、この記事を書いてる時点では、これより新しいバージョンが出ている)

vCenterサーバに接続

PowerCLI C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI> Connect-VIServer -Server vCenterServer -User root -Password vmware

Name                           Port  User
----                           ----  ----
vCenterServer                  443   root


PowerCLI C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI>

そして、「Get-VdsCommand」を実行してvSphre PowerCLIが提供するvDS関連コマンド一覧を取得。

PowerCLI C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI> Get-VdsCommand

CommandType     Name                                               ModuleName
-----------     ----                                               ----------
Cmdlet          Add-VDSwitchPhysicalNetworkAdapter                 VMware.Vi...
Cmdlet          Add-VDSwitchVMHost                                 VMware.Vi...
Cmdlet          Export-VDPortGroup                                 VMware.Vi...
Cmdlet          Export-VDSwitch                                    VMware.Vi...
Cmdlet          Get-VDBlockedPolicy                                VMware.Vi...
Cmdlet          Get-VDPort                                         VMware.Vi...
Cmdlet          Get-VDPortgroup                                    VMware.Vi...
Cmdlet          Get-VDPortgroupOverridePolicy                      VMware.Vi...
Cmdlet          Get-VDSecurityPolicy                               VMware.Vi...
Cmdlet          Get-VDSwitch                                       VMware.Vi...
Cmdlet          Get-VDSwitchPrivateVlan                            VMware.Vi...
Cmdlet          Get-VDTrafficShapingPolicy                         VMware.Vi...
Cmdlet          Get-VDUplinkLacpPolicy                             VMware.Vi...
Cmdlet          Get-VDUplinkTeamingPolicy                          VMware.Vi...
Cmdlet          New-VDPortgroup                                    VMware.Vi...
Cmdlet          New-VDSwitch                                       VMware.Vi...
Cmdlet          New-VDSwitchPrivateVlan                            VMware.Vi...
Cmdlet          Remove-VDPortGroup                                 VMware.Vi...
Cmdlet          Remove-VDSwitch                                    VMware.Vi...
Cmdlet          Remove-VDSwitchPhysicalNetworkAdapter              VMware.Vi...
Cmdlet          Remove-VDSwitchPrivateVlan                         VMware.Vi...
Cmdlet          Remove-VDSwitchVMHost                              VMware.Vi...
Cmdlet          Set-VDBlockedPolicy                                VMware.Vi...
Cmdlet          Set-VDPort                                         VMware.Vi...
Cmdlet          Set-VDPortgroup                                    VMware.Vi...
Cmdlet          Set-VDPortgroupOverridePolicy                      VMware.Vi...
Cmdlet          Set-VDSecurityPolicy                               VMware.Vi...
Cmdlet          Set-VDSwitch                                       VMware.Vi...
Cmdlet          Set-VDTrafficShapingPolicy                         VMware.Vi...
Cmdlet          Set-VDUplinkLacpPolicy                             VMware.Vi...
Cmdlet          Set-VDUplinkTeamingPolicy                          VMware.Vi...
Cmdlet          Set-VDVlanConfiguration                            VMware.Vi...


PowerCLI C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI> 

ここまでは良い。

PowerShell ISEでの動作が問題。
PowerShell ISE上部の編集画面に下記を入力。

Add-PSSnapin VMware.VimAutomation.Core
Get-VIToolkitVersion
Connect-VIServer -Server vCenterServer -User root -Password vmware
Get-VdsCommand

最初の1行はvSphere PowerCLIのコマンドを実行させるため設定。
これを実行すると・・・

PS C:\Users\osakanataro> Add-PSSnapin VMware.VimAutomation.Core
Get-VIToolkitVersion
Connect-VIServer -Server vCenterServer -User root -Password vmware
Get-VdsCommand

Get-VIToolkitVersion : 用語 'Get-VIToolkitVersion' は、コマンドレット、関数、スクリプト ファイル、または操作可能なプログラムの名前として認識されません。名前が正しく記述されていることを確認し、パスが含まれている場合はそのパスが正しいことを確認してから、
再試行してください。
発生場所 行:2 文字:1
+ Get-VIToolkitVersion
+ ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Get-VIToolkitVersion:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
 

Name                           Port  User                          
----                           ----  ----                          
vCenterServer                  443   root                          
Get-VdsCommand : 用語 'Get-VdsCommand' は、コマンドレット、関数、スクリプト ファイル、または操作可能なプログラムの名前として認識されません。名前が正しく記述されていることを確認し、パスが含まれている場合はそのパスが正しいことを確認してから、再試行してください。
発生場所 行:4 文字:1
+ Get-VdsCommand
+ ~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Get-VdsCommand:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
 



PS C:\Users\osakanataro> 

エラーになる・・・
なぜなのか・・・

まずはPowerShell ISE内で「Get-Module」を実行し、現在使用できるコマンドを確認

PS C:\Users\osakanataro> Get-Module

ModuleType Version    Name                                ExportedCommands                                                                            
---------- -------    ----                                ----------------                                                                            
Script     1.0.0.0    ISE                                 {Get-IseSnippet, Import-IseSnippet, New-IseSnippet}                                         
Manifest   3.1.0.0    Microsoft.PowerShell.Management     {Add-Computer, Add-Content, Checkpoint-Computer, Clear-Content...}                          
Manifest   3.0.0.0    Microsoft.PowerShell.Security       {ConvertFrom-SecureString, ConvertTo-SecureString, Get-Acl, Get-AuthenticodeSignature...}   
Manifest   3.1.0.0    Microsoft.PowerShell.Utility        {Add-Member, Add-Type, Clear-Variable, Compare-Object...}                                   
Manifest   3.0.0.0    Microsoft.WSMan.Management          {Connect-WSMan, Disable-WSManCredSSP, Disconnect-WSMan, Enable-WSManCredSSP...}             



PS C:\Users\osakanataro> 

比較のためvSphere PowerCLIの方でも「Get-Module」を実行してみる

PowerCLI C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI> Get-Module

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Script     0.0        Initialize-VMware_VimAutomation_Cis
Script     0.0        Initialize-VMware_VimAutomation_Vds
Manifest   3.1.0.0    Microsoft.PowerShell.Management     {Add-Computer, Add...
Manifest   3.1.0.0    Microsoft.PowerShell.Utility        {Add-Member, Add-T...
Binary     6.0.0.0    VMware.VimAutomation.Cis.Core       {Connect-CisServer...
Manifest   6.0.0.0    VMware.VimAutomation.Core           {Add-PassthroughDe...
Binary     6.0.0.0    VMware.VimAutomation.HA             Get-DrmInfo
Manifest   6.0.0.0    VMware.VimAutomation.Sdk
Binary     6.0.0.0    VMware.VimAutomation.Storage        {Export-SpbmStorag...
Binary     6.0.0.0    VMware.VimAutomation.Vds            {Add-VDSwitchPhysi...


PowerCLI C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI>

全然違う
「VMware.VimAutomation.Vds」を追加すると実行できそうな雰囲気・・・

しかし、「Add-PSSnapin VMware.VimAutomation.Vds」は下記のエラーとなる。

Add-PSSnapin : Windows PowerShell スナップイン 'VMware.VimAutomation.Vds' がこのコンピューターにインストールされていません。
発生場所 行:2 文字:1
+ Add-PSSnapin VMware.VimAutomation.Vds
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (VMware.VimAutomation.Vds:String) [Add-PSSnapin]、PSArgumentException
    + FullyQualifiedErrorId : AddPSSnapInRead,Microsoft.PowerShell.Commands.AddPSSnapinCommand

ではどうするか?

「Get-Command -Module モジュール名」で指定したモジュールでどんなコマンドが実行できるかを表示すると実行でいるようになるらしい。

そんな馬鹿な、と思いつつ、$DUMMY環境変数に放り込むように変更。

Add-PSSnapin VMware.VimAutomation.Core
$DUMMY=Get-Command -Module VMware.VimAutomation.Vds
Get-VIToolkitVersion
Connect-VIServer -Server vCenterServer -User root -Password vmware
Get-VdsCommand

そして実行

PS C:\Users\osakanataro> Add-PSSnapin VMware.VimAutomation.Core
$DUMMY=Get-Command -Module VMware.VimAutomation.Vds
Get-VIToolkitVersion
Connect-VIServer -Server vCenterServer -User root -Password vmware
Get-VdsCommand


PowerCLI Version
----------------
   VMware vSphere PowerCLI 6.0 Release 1 build 2548067
---------------
Component Versions
---------------
   VMWare AutoDeploy PowerCLI Component 6.0 build 2358282
   VMWare ImageBuilder PowerCLI Component 6.0 build 2358282
   VMware License PowerCLI Component 6.0 build 2315846
   VMware vSphere PowerCLI Component 6.0 build 2548068
   VMware VDS PowerCLI Component 6.0 build 2548068


IsConnected   : True
Id            : /VIServer=root@vCenterServer:443/
ServiceUri    : https://vCenterServer/sdk
SessionSecret : cb8924f9fb4b2cb6cb75a357d8127e2154376d17
Name          : vCenterServer
Port          : 443
SessionId     : cb8924f9fb4b2cb6cb75a357d8127e2154376d17
User          : root
Uid           : /VIServer=root@vCenterServer:443/
Version       : 6.0
Build         : 2776510
ProductLine   : vpx
InstanceUuid  : 1a31cfc8-0931-4752-9573-461f044cc2d4
RefCount      : 6
ExtensionData : VMware.Vim.ServiceInstance
Client        : VMware.VimAutomation.ViCore.Impl.V1.VimClient


Verb                : Add
Noun                : VDSwitchPhysicalNetworkAdapter
HelpFile            : VMware.VimAutomation.Vds.Commands.dll-Help.xml
PSSnapIn            : 
ImplementingType    : VMware.VimAutomation.Vds.Commands.Cmdlets.AddVDSwitchPhysicalNetworkAdapter
Definition          : 
                      Add-VDSwitchPhysicalNetworkAdapter [-VMHostPhysicalNic] <PhysicalNic&#91;&#93;> [-DistributedSwitch] <DistributedSwitch> [-VirtualNicPor
                      tgroup <VDPortgroup&#91;&#93;>] [-VMHostVirtualNic <HostVirtualNic&#91;&#93;>] [-Server <VIServer&#91;&#93;>] [-WhatIf] [-Confirm] [<CommonParameters>]
                      
DefaultParameterSet : 
OutputType          : {System.Void}
Options             : ReadOnly
Name                : Add-VDSwitchPhysicalNetworkAdapter
CommandType         : Cmdlet
Visibility          : Public
ModuleName          : VMware.VimAutomation.Vds
Module              : VMware.VimAutomation.Vds
RemotingCapability  : PowerShell
Parameters          : {[VMHostPhysicalNic, System.Management.Automation.ParameterMetadata], [DistributedSwitch, System.Management.Automation.Parameter
                      Metadata], [VirtualNicPortgroup, System.Management.Automation.ParameterMetadata], [VMHostVirtualNic, System.Management.Automatio
                      n.ParameterMetadata]...}
ParameterSets       : {[-VMHostPhysicalNic] <PhysicalNic&#91;&#93;> [-DistributedSwitch] <DistributedSwitch> [-VirtualNicPortgroup <VDPortgroup&#91;&#93;>] [-VMHostVi
                      rtualNic <HostVirtualNic&#91;&#93;>] [-Server <VIServer&#91;&#93;>] [-WhatIf] [-Confirm] [<CommonParameters>]}
HelpUri             : http://www.vmware.com/support/developer/PowerCLI/PowerCLI60R1/html/Add-VDSwitchPhysicalNetworkAdapter.html
DLL                 : C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\Modules\VMware.VimAutomation.Vds\VMware.VimAutomation.Vds.Commands
                      .dll

<略>

Verb                : Set
Noun                : VDVlanConfiguration
HelpFile            : VMware.VimAutomation.Vds.Commands.dll-Help.xml
PSSnapIn            : 
ImplementingType    : VMware.VimAutomation.Vds.Commands.Cmdlets.Policies.SetVDVlanConfiguration
Definition          : 
                      Set-VDVlanConfiguration -VDPortgroup <VDPortgroup&#91;&#93;> [-DisableVlan] [-VlanId <int>] [-VlanTrunkRange <VlanRangeList>] [-PrivateV
                      lanId <int>] [-WhatIf] [-Confirm] [<CommonParameters>]
                      
                      Set-VDVlanConfiguration -VDSwitch <VDSwitch&#91;&#93;> [-DisableVlan] [-VlanId <int>] [-VlanTrunkRange <VlanRangeList>] [-PrivateVlanId 
                      <int>] [-WhatIf] [-Confirm] [<CommonParameters>]
                      
                      Set-VDVlanConfiguration -VDPort <VDPort&#91;&#93;> [-DisableVlan] [-VlanId <int>] [-VlanTrunkRange <VlanRangeList>] [-PrivateVlanId <int
                      >] [-WhatIf] [-Confirm] [<CommonParameters>]
                      
DefaultParameterSet : 
OutputType          : {VMware.VimAutomation.Vds.Types.V1.VlanConfiguration}
Options             : ReadOnly
Name                : Set-VDVlanConfiguration
CommandType         : Cmdlet
Visibility          : Public
ModuleName          : VMware.VimAutomation.Vds
Module              : VMware.VimAutomation.Vds
RemotingCapability  : PowerShell
Parameters          : {[VDPortgroup, System.Management.Automation.ParameterMetadata], [VDSwitch, System.Management.Automation.ParameterMetadata], [VDP
                      ort, System.Management.Automation.ParameterMetadata], [DisableVlan, System.Management.Automation.ParameterMetadata]...}
ParameterSets       : {-VDPortgroup <VDPortgroup&#91;&#93;> [-DisableVlan] [-VlanId <int>] [-VlanTrunkRange <VlanRangeList>] [-PrivateVlanId <int>] [-WhatIf] 
                      [-Confirm] [<CommonParameters>], -VDSwitch <VDSwitch&#91;&#93;> [-DisableVlan] [-VlanId <int>] [-VlanTrunkRange <VlanRangeList>] [-Priva
                      teVlanId <int>] [-WhatIf] [-Confirm] [<CommonParameters>], -VDPort <VDPort&#91;&#93;> [-DisableVlan] [-VlanId <int>] [-VlanTrunkRange <V
                      lanRangeList>] [-PrivateVlanId <int>] [-WhatIf] [-Confirm] [<CommonParameters>]}
HelpUri             : http://www.vmware.com/support/developer/PowerCLI/PowerCLI60R1/html/Set-VDVlanConfiguration.html
DLL                 : C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\Modules\VMware.VimAutomation.Vds\VMware.VimAutomation.Vds.Commands
                      .dll




PS C:\Users\osakanataro> 

ほんとに実行できたーーー
じゃぁ、この段階での「Get-Module」はどうなってるか確認してみると、ちゃんとVMware.VimAutomation.Vdsが読み込まれてる・・・
謎な動作をしてますね・・・

PS C:\Users\osakanataro> Get-Module

ModuleType Version    Name                                ExportedCommands                                                                            
---------- -------    ----                                ----------------                                                                            
Script     0.0        Initialize-VMware_VimAutomation_Vds                                                                                             
Script     1.0.0.0    ISE                                 {Get-IseSnippet, Import-IseSnippet, New-IseSnippet}                                         
Manifest   3.1.0.0    Microsoft.PowerShell.Management     {Add-Computer, Add-Content, Checkpoint-Computer, Clear-Content...}                          
Manifest   3.0.0.0    Microsoft.PowerShell.Security       {ConvertFrom-SecureString, ConvertTo-SecureString, Get-Acl, Get-AuthenticodeSignature...}   
Manifest   3.1.0.0    Microsoft.PowerShell.Utility        {Add-Member, Add-Type, Clear-Variable, Compare-Object...}                                   
Manifest   3.0.0.0    Microsoft.WSMan.Management          {Connect-WSMan, Disable-WSManCredSSP, Disconnect-WSMan, Enable-WSManCredSSP...}             
Manifest   6.0.0.0    VMware.VimAutomation.Core                                                                                                       
Manifest   6.0.0.0    VMware.VimAutomation.Sdk                                                                                                        
Binary     6.0.0.0    VMware.VimAutomation.Vds            {Add-VDSwitchPhysicalNetworkAdapter, Add-VDSwitchVMHost, Export-VDPortGroup, Export-VDSwi...



PS C:\Users\osakanataro> 

PowerShellを使ってVMwareのテンプレートからデプロイで「既存のカスタマイズ仕様を使用してカスタマイズする」を行う方法

VMware vSphere環境にて、一度、GUI操作でテンプレートのデプロイを行い、その結果をカスタマイズ仕様として保存している、という状態で、VMware Power CLIを使用して、GUIの「既存のカスタマイズ仕様を使用してカスタマイズする」相当の操作を行う場合、どのようにするかを説明する。

手順のポイント

・カスタマイズ仕様は「OSCustomizationSpec」と「OSCustomizationNicMapping」の2つから成り立っている

・既存のカスタマイズ仕様をコピーした一時的なカスタマイズ仕様を作成し、それを編集して使用する

・仮想マシンの電源を1度入れないとカスタマイズされない(カスタマイズ後、再起動される)

・使うcmdletは以下
  カスタマイズ仕様関連
    Get-OSCustomizationSpec, New-OSCustomizationSpec
    Get-OSCustomizationNicMapping, Set-OSCustomizationNicMapping
  テンプレートデプロイ関連
    Get-VMHost
    New-VM
  仮想マシンのハードウェア構成変更
    Get-VM, Set-VM

手順解説

その1 vCenterサーバに接続

vSphere PowerCLIによる操作を行う際、まずは「Connect-VIServer」により、操作対象のvCenterサーバに接続します。

下記はvCenter vApp(VCSA)の初期設定である「root」「vmware」で接続する場合の例です。

PowerCLI C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI> Connect-VIServer -Server IPアドレス -User root -Password vmware

Name                           Port  User
----                           ----  ----
IPアドレス                     443   root


PowerCLI C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI>

その2 既存カスタマイズ仕様をコピーしたカスタマイズ仕様を作成

既存のカスタマイズ仕様を一時的に変更してデプロイする、ということができないため、コピーしたカスタマイズ仕様を変更する、という手順を取る。

ただ、コピーの際に「-Type NonPersistent」というオプションを指定すると、このセッション中のみ使用できる一時的なカスタマイズ仕様として作成することができるため、デプロイ後の削除まで考える必要はない。

PowerCLI C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI> Get-OSCustomizationSpec cent6-dep | New-OSCustomizationSpec -Name cent6-temp -Type NonPersistent

Name                                         Description Type          OSType
----                                         ----------- ----          ------
cent6-temp                                               NonPersistent Linux


PowerCLI C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI>

その3 IPアドレスなど設定

IPアドレスやデフォルトゲートウェイなどネットワークに関する設定は「Get-OSCustomizationNicMapping」にて行う。

NICを増やす場合もここで行う。(ホスト名についてはここでは無い)

PowerCLI C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI> Get-OSCustomizationNicMapping -Spec cent6-temp | Set-OSCustomizationNicMapping -IpMode UseStaticIP -IpAddress 172.17.44.55 -SubnetMask 255.255.0.0 -DefaultGateway 172.17.44.39

Position IPMode           IPAddress       DefaultGateway
-------- ------           ---------       --------------
       1 UseStaticIP      172.17.44.55    172.17.44.39


PowerCLI C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI>

その4 仮想マシンホスト名の命名規則指定

仮想マシンにつけるホスト名をどのようなルールで行うかというのを指定する。

「-NamingScheme vm」は、仮想マシンの登録名とホスト名を同じとする、というものになる。

PowerCLI C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI> Get-OSCustomizationSpec cent6-temp | Set-OSCustomizationSpec -NamingScheme vm

Name                                         Description Type          OSType
----                                         ----------- ----          ------
cent6-temp                                               NonPersistent Linux


PowerCLI C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI>

その5 仮想マシンのデプロイ

今回は「nimblestorage」という名前のDataStoreを指定して、仮想マシンのデプロイを実施するという形で実行している。

先の項目で、仮想マシンの登録名とホスト名を同じとしているので「-Name cent6-ip55」で指定した「cent6-ip55」がホスト名となる。

PowerCLI C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI> New-VM -Name cent6-ip55  -VMHost vmserver21.vmlab.local -Template cent6-deploy -OSCustomizationSpec cent6-temp -Datastore nimblestorage

Name                 PowerState Num CPUs MemoryGB
----                 ---------- -------- --------
cent6-ip55           PoweredOff 1        2.000


PowerCLI C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI>

なお、デプロイ中に強制終了を行うと、それ以後、動作がおかしくなることがあるようだ。

今回遭遇した事例としては、下記の様なエラーがでるが、デプロイ自体は実施されていた。

PowerCLI C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI> New-VM -Name cent6-ip55 -VMHost vmserver21.vmlab.local -Template cent6-deploy -OSCustomizationSpec cent6-temp -Datastore nimblestorage
New-VM : 2015/07/16 18:03:02    New-VM        オブジェクトの現在の状態に問題が
あるため、操作は有効ではありません。
発生場所 行:1 文字:1
+ New-VM -Name cent6-ip55 -VMHost vmserver21.vmlab.local -Template cent6-depl
oy  ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~
    + CategoryInfo          : NotSpecified: (:) [New-VM], VimException
    + FullyQualifiedErrorId : Core_BaseCmdlet_UnknownError,VMware.VimAutomatio
   n.ViCore.Cmdlets.Commands.NewVM

PowerCLI C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI>

その6 CPU/メモリの変更

作成した仮想マシンのCPUとメモリの割り当てを「Set-VM」で変更します。

なお、このSet-VMには「-Name」というオプションがありますが、仮想マシンを指定する際は「-VM 仮想マシン名」という風に指定します。

PowerCLI C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI> Set-VM -VM cent6-ip55 -NumCpu 2 -MemoryMB 4

Confirmation
Proceed to configure the following parameters of the virtual machine with name
'cent6-ip55'?
New MemoryMB: 4MB
New NumCpu: 2
[Y] はい(Y)  [A] すべて続行(A)  [N] いいえ(N)  [L] すべて無視(L)  [S] 中断(S)
[?] ヘルプ(既定値は "Y"): y

Name                 PowerState Num CPUs MemoryGB
----                 ---------- -------- --------
cent6-ip55           PoweredOff 2        0.004


PowerCLI C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI>

上記の出力結果をよく見てみるとわかるのですが、実はメモリ容量はMB単位での指定となっています。このため、現状はなんと4MBしか割り当てられていません。これではMS-DOSぐらいしか起動できません。

「4G」と指定したいところですが、サポートされていないため、「4096」という形で指定します。

PowerCLI C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI> Set-VM -VM cent6-ip55 -NumCpu 2 -MemoryMB 4096

Confirmation
Proceed to configure the following parameters of the virtual machine with name
'cent6-ip55'?
New MemoryMB: 4096MB
New NumCpu: 2
[Y] はい(Y)  [A] すべて続行(A)  [N] いいえ(N)  [L] すべて無視(L)  [S] 中断(S)
[?] ヘルプ(既定値は "Y"): y

Name                 PowerState Num CPUs MemoryGB
----                 ---------- -------- --------
cent6-ip55           PoweredOff 2        4.000


PowerCLI C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI>

その7 仮想マシンの電源ON

デプロイ時の初期設定は仮想マシンの初回起動時に行われるため、まずはPowerShellから電源オンを行うため「Start-VM」を実行します。

PowerCLI C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI> Start-VM -VM cent6-ip55

Name                 PowerState Num CPUs MemoryGB
----                 ---------- -------- --------
cent6-ip55           PoweredOn  2        4.000


PowerCLI C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI>

電源投入後、初回起動時にホスト名/IPアドレスの設定スクリプトが実行されます。また、完了後、自動的に再起動も行われます。

その8 デプロイ完了

再起動が終わったらデプロイが完了です。