-
Notifications
You must be signed in to change notification settings - Fork 3
/
create-sn-mi-from-list.py
280 lines (262 loc) · 14.9 KB
/
create-sn-mi-from-list.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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
#!/bin/python3
import csv, random, subprocess, sys, time, os, json
project_id = ""
print(sys.argv[1:])
if sys.argv[1:][0] == 'sn':
filename = sys.argv[1:][1]+".csv"
with open(filename, 'r') as csvfile:
datareader = csv.reader(csvfile)
random_id = random.randint(1000, 9999)
for row in datareader:
session_id = random_id
disk_name = row[0]
disk_zone = row[1]
project_id = row[2]
print(
f"SESSION ID ##{random_id}## DISK NAME : {disk_name} DISK ZONE : {disk_zone} PROJECT ID : {project_id}")
subprocess.Popen(
['/bin/bash', '-c', f'gcloud beta compute snapshots create {disk_name}-adhoc-dontdelete{random_id} --source-disk={disk_name} --source-disk-zone={disk_zone} --project={project_id} --labels=key=adhoc'])
time.sleep(3)
elif sys.argv[1:][0] == 'mi':
print('welcome to machine image')
filename = sys.argv[1:][1]+".csv"
with open(filename, 'r') as csvfile:
datareader = csv.reader(csvfile)
random_id = random.randint(1000, 9999)
for row in datareader:
session_id = random_id
VM_name = row[0]
VM_zone = row[1]
VM_ACTION_NAME = row[2]
project_id = row[3]
print(
f"SESSION ID ##{random_id}## DISK NAME : {VM_name} DISK ZONE : {VM_zone} PROJECT ID : {project_id}")
subprocess.Popen(
['/bin/bash', '-c', f'gcloud beta compute machine-images create {VM_name}-{VM_ACTION_NAME}-{random_id} --source-instance={VM_name} --source-instance-zone={VM_zone} --project={project_id} --description={VM_ACTION_NAME}'])
time.sleep(3)
##############
elif sys.argv[1:][0] == 'delete-mi':
print('welcome to delete machine image')
filename = sys.argv[1:][1]+".csv"
with open(filename, 'r') as csvfile:
datareader = csv.reader(csvfile)
random_id = random.randint(1000, 9999)
for row in datareader:
session_id = random_id
disk_name = row[0]
disk_zone = row[1]
project_id = row[2]
print(
f"SESSION ID ##{random_id}## DISK NAME : {disk_name} DISK ZONE : {disk_zone} PROJECT ID : {project_id}")
subprocess.Popen(
['/bin/bash', '-c', f'gcloud beta compute machine-images delete {disk_name} --project={project_id} -q'])
time.sleep(3)
##############
elif sys.argv[1:][0] == 'delete-sn':
print('welcome to delete machine image')
filename = sys.argv[1:][1]+".csv"
with open(filename, 'r') as csvfile:
datareader = csv.reader(csvfile)
random_id = random.randint(1000, 9999)
for row in datareader:
session_id = random_id
disk_name = row[0]
disk_zone = row[1]
project_id = row[2]
print(
f"SESSION ID ##{random_id}## DISK NAME : {disk_name} DISK ZONE : {disk_zone} PROJECT ID : {project_id}")
subprocess.Popen(
['/bin/bash', '-c', f'gcloud beta compute snapshots delete {disk_name} --project={project_id} -q'])
time.sleep(3)
##############
elif sys.argv[1:][0] == 'list-mi':
subprocess.run(['/bin/bash', '-c', f'mkdir machine-images'])
print('welcome to list machine image')
filename = sys.argv[1:][1]+".csv"
with open(filename, 'r') as csvfile:
datareader = csv.reader(csvfile)
for row in datareader:
project_id = row[0]
subprocess.Popen(['/bin/bash', '-c', f'mkdir {project_id} && gcloud beta compute machine-images list --format="csv[no-heading](NAME)" --project={project_id} > {project_id}/{project_id}-machine-images.csv'])
time.sleep(1)
filename = sys.argv[1:][1]+".csv"
with open(filename, 'r') as csvfile:
datareader = csv.reader(csvfile)
for row in datareader:
project_id = row[0]
filename_tow = f'{project_id}/{project_id}-machine-images.csv'
print(f'{filename_tow}')
with open(filename_tow, 'r') as csvfile_tow:
datareader_tow = csv.reader(csvfile_tow)
for i in datareader_tow:
mi_name = i[0]
subprocess.run(['/bin/bash', '-c', f'gcloud compute machine-images describe {mi_name} --format="csv[no-heading](sourceInstance.scope(sourceInstance),name,creation_timestamp,totalStorageBytes,storageLocations)" --project={project_id} >> machine-images/{project_id}-machine-images.csv'])
time.sleep(1)
filename = sys.argv[1:][1]+".csv"
with open(filename, 'r') as csvfile:
datareader = csv.reader(csvfile)
for row in datareader:
project_id = row[0]
subprocess.run(['/bin/bash', '-c', f'rm -rf {project_id}'])
time.sleep(1)
##############
elif sys.argv[1:][0] == 'add-resource-policies-to-vm':
print('welcome to add add-resource-policies to vm')
filename = sys.argv[1:][1]+".csv"
with open(filename, 'r') as csvfile:
datareader = csv.reader(csvfile)
for row in datareader:
vm_name = row[0]
vm_zone = row[1]
disk_policy = row[2]
project_id = row[3]
subprocess.run(['/bin/bash', '-c', f'gcloud compute disks list --format="csv[no-heading](NAME,users.basename(),zone.basename())" --project={project_id} > {project_id}-disks.csv'])
with open(f'{project_id}-disks.csv', 'r') as csvfile_tow:
datareader_tow = csv.reader(csvfile_tow)
for row in datareader_tow:
DISK_NAME = row[0]
DISK_USER = row[1]
DISK_ZONE = row[2]
subprocess.Popen(['/bin/bash', '-c', f'gcloud compute disks add-resource-policies {DISK_NAME} --resource-policies={disk_policy} --zone={DISK_ZONE} --project={project_id}'])
subprocess.run(['/bin/bash', '-c', f'rm -rf {project_id}-disks.csv'])
##############
elif sys.argv[1:][0] == 'add-resource-policies-to-disks':
print('welcome to add add-resource-policies to vm')
filename = sys.argv[1:][1]+".csv"
with open(filename, 'r') as csvfile_tow:
datareader_tow = csv.reader(csvfile_tow)
for row in datareader_tow:
DISK_NAME = row[0]
Disk_Policy = row[1]
DISK_ZONE = row[2]
project_id = row[3]
subprocess.run(['/bin/bash', '-c', f'gcloud compute disks add-resource-policies {DISK_NAME} --resource-policies={Disk_Policy} --zone={DISK_ZONE} --project={project_id}'])
#####################################################
elif sys.argv[1:][0] == 'remove-resource-policies-to-disks':
print('welcome to remove remove-resource-policies to disks')
filename = sys.argv[1:][1]+".csv"
with open(filename, 'r') as csvfile_tow:
datareader_tow = csv.reader(csvfile_tow)
for row in datareader_tow:
DISK_NAME = row[0]
DISK_ZONE = row[1]
project_id = row[2]
subprocess.Popen(['/bin/bash', '-c', f'OLDBOOT_DISK_LICENSE=$(gcloud beta compute disks describe {DISK_NAME} --zone={DISK_ZONE} --project={project_id} --format="csv[no-heading](resourcePolicies.basename())") && gcloud compute disks remove-resource-policies {DISK_NAME} --resource-policies=$OLDBOOT_DISK_LICENSE --zone={DISK_ZONE} --project={project_id}'])
#####################################################
elif sys.argv[1:][0] == 'remove-sn-schdule-from-disks-and-delete-sn':
print('welcome to remove resource-policies ad snapshots for disks')
filename = sys.argv[1:][1]+".csv"
with open(filename, 'r') as csvfile_tow:
datareader_tow = csv.reader(csvfile_tow)
for row in datareader_tow:
DISK_NAME = row[0]
DISK_ZONE = row[1]
project_id = row[2]
subprocess.run(['/bin/bash', '-c', f'OLDBOOT_DISK_LICENSE=$(gcloud beta compute disks describe {DISK_NAME} --zone={DISK_ZONE} --project={project_id} --format="csv[no-heading](resourcePolicies.basename())") && gcloud compute disks remove-resource-policies {DISK_NAME} --resource-policies=$OLDBOOT_DISK_LICENSE --zone={DISK_ZONE} --project={project_id}'])
cmd = f'gcloud compute snapshots list --filter="sourceDisk={DISK_NAME}" --format="value(name)" --project={project_id}'
output = subprocess.check_output(cmd, shell=True).decode('utf-8')
snapshots = output.split('\n')[:-1] # remove last empty item
print(f'Found {len(snapshots)} snapshots for disk {DISK_NAME}')
print(snapshots)
with open(f'{project_id}-snapshots.csv', 'a', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow([DISK_NAME, len(snapshots)] + snapshots)
for snapshot in snapshots:
cmd2 = f'gcloud compute snapshots delete {snapshot} --quiet --project={project_id}'
subprocess.run(cmd2, shell=True)
print(f'Deleted {len(snapshots)} snapshots for disk {DISK_NAME}')
with open(f'{project_id}-deleted-snapshots.csv', 'a', newline='') as csvfile2:
writer = csv.writer(csvfile2)
writer.writerow([DISK_NAME, len(snapshots)] + snapshots)
#####################################################
elif sys.argv[1:][0] == 'create-mi-to-anther-project':
print('welcome to create mi to anther project')
Source_Project_id = input("Please Enter SORCE PROJECT ID:")
target_project_id = input("Please Enter TARGET PROJECT ID:")
cmd = f'gcloud compute instances list --format="csv[no-heading](NAME,ZONE)" --project={Source_Project_id}'
output = subprocess.check_output(cmd, shell=True).decode('utf-8')
InstancesLIST = output.split('\n')[:-1] # remove last empty item
VMS = csv.reader(InstancesLIST)
for VM in VMS:
VM_NAME = VM[0]
VM_ZONE = VM[1]
MI_NAME = f'{VM_NAME}-moved-from-{Source_Project_id}'
# define the fixed column width
column_width = 30
# format the variables with a fixed width
vm_name_TABLE = '{:<{width}}'.format(VM_NAME, width=column_width)
source_project_id_TABLE = '{:<{width}}'.format(Source_Project_id, width=column_width)
target_project_id_TABLE = '{:<{width}}'.format(target_project_id, width=column_width)
cmd2 = f'gcloud compute machine-images create {MI_NAME} --source-instance="projects/{Source_Project_id}/zones/{VM_ZONE}/instances/{VM_NAME}" --project={target_project_id}'
subprocess.run(cmd2, shell=True)
LOGS = f'| Machine - image create from VM: {vm_name_TABLE} | sorce Project: {source_project_id_TABLE} | in target Project: {target_project_id_TABLE} |'
LOGST = f'Machine - image create from VM: {vm_name_TABLE},sorce Project: {source_project_id_TABLE},in target Project: {target_project_id_TABLE},'
LOGSFILEPATH = f'LOGS-for-Created-MI-IN-{target_project_id}-from-{Source_Project_id}.csv'
print(f'{LOGS}')
# with open(f'{LOGSFILEPATH}', 'a', newline='') as csvfile:
# writer = csv.writer(csvfile)
# writer.writerow(f'{LOGST}')
########################################################################################
elif sys.argv[1:][0] == 'turn-off-all-the-firewall-logs-in-project':
print('welcome to create mi to anther project')
# Set the project ID
project_id = input("Please Enter the PROJECT ID:")
# Run the gcloud command to list all the firewall rules in the project
list_command = f'gcloud compute firewall-rules list --project={project_id} --format=json'
output = subprocess.check_output(list_command.split()).decode('utf-8')
# Parse the JSON output into a list of dictionaries representing each firewall rule
rules = json.loads(output)
# Loop over the list of firewall rules and update each one to turn off logging
for rule in rules:
update_command = f'gcloud compute firewall-rules update {rule["name"]} --no-enable-logging --project={project_id}'
subprocess.Popen(update_command.split())
print(f'Firewall rule {rule["name"]} updated successfully.')
print('All firewall rules updated successfully.')
#####################################################
elif sys.argv[1:][0] == 'add-tags':
print('welcome to add add-tags to vm')
filename = sys.argv[1:][1]+".csv"
with open(filename, 'r') as csvfile:
datareader = csv.reader(csvfile)
for row in datareader:
vm_name = row[0]
vm_zone = row[1]
TAG = row[2]
project_id = row[3]
subprocess.run(['/bin/bash', '-c', f'gcloud compute instances add-tags {vm_name} --zone={vm_zone} --tags={TAG} --project={project_id}'])
print(f'{vm_name} tag {TAG} added' )
##########################################################
elif sys.argv[1:][0] == 'rm-tags':
print('welcome to add rm-tags to vm')
filename = sys.argv[1:][1]+".csv"
with open(filename, 'r') as csvfile:
datareader = csv.reader(csvfile)
for row in datareader:
vm_name = row[0]
vm_zone = row[1]
TAG = row[2]
project_id = row[3]
subprocess.run(['/bin/bash', '-c', f'gcloud compute instances remove-tags {vm_name} --zone={vm_zone} --tags={TAG} --project={project_id}'])
print(f'{vm_name} tag {TAG} removed' )
##########################################################
elif sys.argv[1:][0] == 'move-vms-out-of-sole':
project_id = input("Please Enter the PROJECT ID:")
# Run the gcloud command to list all the firewall rules in the project
list_command = f'gcloud compute instances list --format="csv[no-heading](NAME,ZONE,scheduling.nodeAffinities[values])" --project={project_id}'
output = subprocess.check_output(list_command, shell=True).decode('utf-8')
InstancesLIST = output.split('\n')[:-1] # remove last empty item
VMS = csv.reader(InstancesLIST)
for VM in VMS:
VM_NAME = VM[0]
VM_ZONE = VM[1]
NODE_AFFINITES = VM[2]
if NODE_AFFINITES:
cmd2 = f'gcloud compute instances set-scheduling "{VM_NAME}" --clear-node-affinities --zone={VM_ZONE} --project={project_id}'
subprocess.run(cmd2, shell=True)
print(f'{VM_NAME}-{VM_ZONE}-{project_id}-out - of the sole now')
cmd3 = f'gcloud compute instances start "{VM_NAME}" --zone={VM_ZONE} --project={project_id}'
subprocess.run(cmd3, shell=True)
print(f'{VM_NAME}-{VM_ZONE}-{project_id}-started')
############################################################
else:
print('coming soon')