Skip to content

Commit 98c8f31

Browse files
authored
Create compute.py
1 parent ab63f4b commit 98c8f31

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

Infra-with-python/compute.py

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
#First install required library using below pip command
2+
#pip install google-api-python-client
3+
4+
import os
5+
from metadata import *
6+
from var import *
7+
8+
from google.oauth2 import service_account
9+
from googleapiclient.discovery import build
10+
11+
# Create Service account , download keys and add your key file path below
12+
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "key.json"
13+
14+
# I am creating function to create VM instance and this function is being called from main.py
15+
def create_gce_instance(vm_name, zone, subnet_name, machine_type, vm_image):
16+
vm_instance_list = get_vm_instance_list(project, zone)
17+
vm_exists = False
18+
for instance in vm_instance_list.get('items', []):
19+
if instance['name'] == vm_name:
20+
vm_exists = True
21+
break
22+
23+
if not vm_exists:
24+
compute_service = build('compute', 'v1')
25+
subnet_selflink = 'regions/{}/subnetworks/{}'.format(
26+
region, subnet_name)
27+
config = {
28+
'name': vm_name,
29+
'machineType': 'zones/{}/machineTypes/{}'.format(zone, machine_type),
30+
'disks': [{
31+
'boot': True,
32+
'autoDelete': True,
33+
'initializeParams': {
34+
'sourceImage': vm_image
35+
}
36+
}],
37+
'networkInterfaces': [{
38+
'subnetwork': subnet_selflink,
39+
'accessConfigs': [{
40+
'type': 'ONE_TO_ONE_NAT',
41+
'name': 'External NAT'
42+
}]
43+
}]
44+
}
45+
46+
request = compute_service.instances().insert(
47+
project=project, zone=zone, body=config)
48+
response = request.execute()
49+
50+
print('VM instance created:', response['selfLink'])
51+
else:
52+
print(f'VM instance {vm_name} already exist')

0 commit comments

Comments
 (0)