Skip to content

Instantly share code, notes, and snippets.

@sky-joker
Last active July 18, 2017 16:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sky-joker/abf2bd8664b1654a2bc55f08842edc20 to your computer and use it in GitHub Desktop.
Save sky-joker/abf2bd8664b1654a2bc55f08842edc20 to your computer and use it in GitHub Desktop.
VMwareクローンスクリプト
#!/usr/bin/python3
from pyVim.connect import SmartConnect, Disconnect
from pyVmomi import vim, vmodl
import ssl
import atexit
# 接続先情報
host = 'ESXi or vCenter IP'
username = 'username'
password = 'password'
# クローン情報
clone_target_vm = 'クローン元VM名'
target_host = '展開先ESXiホスト名'
new_vm_name = '新しいVM名'
def get_mob_info(content, mob, target=''):
"""
Management Objectを取得する。
targetが指定されていない場合はContainerView(https://goo.gl/WXMfJK)で返す。
:type content: vim.ServiceInstanceContent
:param content: ServiceContent(https://goo.gl/oMtVFh)
:type mob: Management Object
:param mob: 取得する対象のManagement Objectを指定
:type target: str
:param target: 返すmobの名前を指定
:rtype: Management Object
:return: 指定したManagement Object又はContainerViewを返す
"""
r = content.viewManager.CreateContainerView(content.rootFolder,
[mob],
True)
# 返すmobを名前で指定する場合
if(target):
for i in r.view:
if(i.name == target):
r = i
return r
def main():
# SSL証明書対策
context = None
if hasattr(ssl, '_create_unverified_context'):
context = ssl._create_unverified_context()
# 接続
si = SmartConnect(host = host,
user = username,
pwd = password,
sslContext = context)
# 処理完了時にvCenterから切断
atexit.register(Disconnect, si)
# ServiceContent(Data Object)を取得
content = si.content
# RelocateSpecを作成 https://goo.gl/sJdBRH
relocate_spec = vim.vm.RelocateSpec()
relocate_spec.host = get_mob_info(content, vim.HostSystem, target_host)
# CloneSpec作成 https://goo.gl/7ueuqR
clone_spec = vim.vm.CloneSpec()
clone_spec.location = relocate_spec
clone_spec.powerOn = False
clone_spec.template = False
# Clone実行
target_vm = get_mob_info(content, vim.VirtualMachine, clone_target_vm)
target_vm.CloneVM_Task(folder = target_vm.parent, name = new_vm_name, spec = clone_spec)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment