-
Notifications
You must be signed in to change notification settings - Fork 4
/
vmcreation.py
145 lines (128 loc) · 4.9 KB
/
vmcreation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright © 2016 Praveen Kumar <kumarpraveen.nitdgp@gmail.com>
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU General Public License v.2, or (at your option) any later
# version. This program is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY expressed or implied, including the
# implied warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details. You
# should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# vmcreation - Create VM using cloud qcow2 images (fedora, centos)
"""
Reference:
- https://github.com/clauded/virt-tools/blob/master/virt-install-cloud.sh
- https://github.com/kushaldas/tunir
Sample Usage:
$ python vmcreation.py f24
$ python vmcreattion.py centos7
"""
import os
import sys
import subprocess
from argparse import ArgumentParser
from shutil import copy
from random import randint
# Specify vm preferences for your guest
NAME= "dev%d" % randint(1000, 3000)
VROOTDISKSIZE="10G"
VCPUS=1
VMEM=1024
BRIDGE="virbr1"
#sometimes the laptops have virbr0 and so should be set to zero.like
#BRIDGE="virbr0"
NETWORK="bridge=virbr1,model=virtio"
# guest image format
POOL_PATH="/home/vm"
def system(cmd):
"""
Runs a shell command, and returns the output, err, returncode
:param cmd: The command to run.
:return: Tuple with (output, err, returncode).
"""
ret = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
out, err = ret.communicate()
returncode = ret.returncode
return out, err, returncode
def get_meta_data():
meta_data = ("instance-id: id-{0}\n"
"local-hostname: {0}\n").format(NAME)
return meta_data
def get_user_data():
user_data = ("#cloud-config\n"
"password: passw0rd\n"
"chpasswd: { expire: False }\n"
"ssh_pwauth: True\n")
return user_data
def create_required_dir():
if not os.path.isdir(POOL_PATH):
system("mkdir -p %s" % POOL_PATH)
def create_cloud_init_iso():
create_required_dir()
with open('user-data','w') as fh:
fh.write(get_user_data())
with open('meta-data','w') as fh:
fh.write(get_meta_data())
return system(("genisoimage -output %s/%s.configuration.iso "
"-volid cidata -joliet -rock user-data meta-data") % (POOL_PATH, NAME))[1:]
def copy_image_to_libvirt_pool(image_name):
if not os.path.isfile("%s/%s" % (POOL_PATH,image_name)):
copy(image_name, POOL_PATH)
def create_qemu_image(image_name):
copy_image_to_libvirt_pool(image_name)
return system(("qemu-img create -f qcow2 -b {0} {1}/{2}.root.img {3}").format(image_name, POOL_PATH,
NAME, VROOTDISKSIZE))[1:]
def create_vm():
return system(("virt-install --import "
"--name {0} "
"--ram {1} "
"--vcpus={2} "
"--network bridge={3},model=virtio "
"--disk path={4}/{0}.root.img "
"--disk path={4}/{0}.configuration.iso "
"--accelerate "
"--force "
"--graphics none").format(NAME, VMEM, VCPUS, BRIDGE, POOL_PATH))[1:]
if __name__ == "__main__":
parser = ArgumentParser(prog='vmcreation', description='Create virtual machine using KVM')
parser.add_argument("image", help="downloaded qcow2 image name")
args = parser.parse_args()
if os.getuid():
print "Execution Permission Denied (use sudo)"
sys.exit(1)
err, returncode = create_cloud_init_iso()
if returncode:
sys.stderr.write(err)
sys.exit(1)
err, returncode = create_qemu_image(args.image)
if returncode:
sys.stderr.write(err)
sys.exit(1)
err, returncode = create_vm()
if returncode:
sys.stderr.write(err)
sys.exit(1)
print ("======================\n"
"To login to vm guest: "
"sudo virsh console {0}\n"
"Default user for cloud image is:\n"
"Fedora Image: fedora\n"
"Centos Image: centos\n"
"Red Hat Image: cloud-user\n"
"Ubuntu Image: ubuntu\n"
"Debian Image: debian\n"
"======================\n"
"Default password: passw0rd\n"
"======================\n"
"Shutdown vm guest: "
"sudo virsh shutdown {0}\n"
"======================\n"
"Destroy vm guest: "
"sudo virsh destroy {0} && "
"sudo virsh undefine {0}").format(NAME)