Set virtual machine IP with PowerCli

powerclilogo

Ever wondered how you could configure IP’s on a couple of newly created virtual machines using PowerCli. I created a quick script to configure IP addresses on some RHEL 6 virtual machines.
This script has some specific actions that had to be performed to set the hostname. This was done using “SED”.

You could edit it to do other OS’s as well. Just note that this is not supported on Server 2012.  I’ll create a new post on how to do this for Server 2012.

Here are some prerequisites before you can actually execute this script:

  • VMTools needs to be installed and running.
  • Root/Admin credentails.
  • A .csv file containing the info you would like to inject in to the virtual machines. (name,ip, sub,gw,dns)

Copy  this script below.


#Import a csv containing all the info.
$vms = Import-Csv "c:\Users\User\Documents\Script\cloud_vms.csv"

#Start prcoessing each VM per line item.

foreach ($vm in $vms){

$script_block_eth0 = "sed 's/ONBOOT=no/ONBOOT=yes/' -i /etc/sysconfig/network-scripts/ifcfg-eth0"
Invoke-VMScript -ScriptText $script_block_eth0 -VM $vm.name -GuestUser root -GuestPassword "P@ssw0rd" -ToolsWaitSecs 20
Get-VMGuestNetworkInterface -VM $vm.name -Name "eth0" -GuestUser root -GuestPassword "P@ssw0rd" | Set-VMGuestNetworkInterface -Ip $vm.ip -Netmask $vm.mask -Gateway $vm.gateway -Dns $vm.dns1,$vm.dns2 -GuestUser root -GuestPassword "P@ssw0rd" -ToolsWaitSecs 30 -Confirm:$false

$vmname = $vm.name
$script_block_hostname = "sed 's/HOSTNAME=template/HOSTNAME=$vmname/' -i /etc/sysconfig/network"
Invoke-VMScript -ScriptText $script_block_hostname -VM $vm.name -GuestUser root -GuestPassword "P@ssw0rd" -ToolsWaitSecs 20

Invoke-VMScript -ScriptText "service network restart" -VM $vm.name -GuestUser root -GuestPassword "P@ssw0rd" -ToolsWaitSecs 20
}
Share on Facebook0Tweet about this on TwitterShare on LinkedIn0Share on Google+0

Leave a Reply

Your email address will not be published. Required fields are marked *