Skip to content

Commit 0102fd1

Browse files
committed
commit everything
1 parent 839c813 commit 0102fd1

18 files changed

+727
-0
lines changed
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
# Delete Sandboxes / Blueprints
2+
3+
Scripts to delete ALL sandboxes / blueprints, or a subset based on criteria (such as belonging to target users)
4+
5+
## Dependencies
6+
- Python version 3.7
7+
- package requirements:
8+
- cloudshell-automation-api
9+
10+
## Delete ALL sandboxes
11+
Deletes all historical sandboxes. Time range can be passed in. Default range is set to 2015 - 2025.
12+
13+
`python delete_ALL_sandboxes.py --help`
14+
```
15+
usage: Delete ALL sandboxes [-h] -s SERVER -u USER -p PASSWORD [--from FROM]
16+
[--until UNTIL]
17+
18+
Automation API script to delete sandboxes
19+
20+
optional arguments:
21+
-h, --help show this help message and exit
22+
-s SERVER, --server SERVER
23+
Cloudshell Server User
24+
-u USER, --user USER Cloudshell Server Password
25+
-p PASSWORD, --password PASSWORD
26+
Cloudshell Server IP or DNS name
27+
--from FROM start range. format MM/DD/YYYY HH:MM, ex. 01/01/2015
28+
00:00
29+
--until UNTIL end range. format MM/DD/YYYY HH:MM, ex. 01/01/2025
30+
00:00
31+
```
32+
Sample commands:
33+
`python delete_ALL_sandboxes.py -s localhost -u admin -p admin`
34+
`python delete_ALL_sandboxes.py -s localhost -u admin -p admin --from 01/01/2020 --until 01/01/2021`
35+
36+
## Delete ALL Blueprints
37+
Deletes all "Regular" type blueprints. Blueprint Templates ignored.
38+
39+
`python delete_ALL_blueprints.py --help`
40+
```
41+
usage: Delete ALL blueprints [-h] -s SERVER -u USER -p PASSWORD
42+
43+
Automation API script to delete blueprints
44+
45+
optional arguments:
46+
-h, --help show this help message and exit
47+
-s SERVER, --server SERVER
48+
Cloudshell Server User
49+
-u USER, --user USER Cloudshell Server Password
50+
-p PASSWORD, --password PASSWORD
51+
Cloudshell Server IP or DNS name
52+
53+
```
54+
55+
Sample command:
56+
`python delete_ALL_blueprints.py -s localhost -u admin -p admin`
57+
58+
## Delete Sandboxes with Target Users
59+
Accepts a list of cloudshell users. Deletes sandboxes owned by one of target users, OR has a target user as permitted user
60+
61+
`python delete_sandboxes_with_target_users.py --help`
62+
63+
```
64+
usage: Delete sandboxes for target users [-h] -s SERVER -u USER -p PASSWORD
65+
[--from FROM] [--until UNTIL] --users
66+
USERS
67+
68+
Automation API script to delete sandboxes
69+
70+
optional arguments:
71+
-h, --help show this help message and exit
72+
-s SERVER, --server SERVER
73+
Cloudshell Server User
74+
-u USER, --user USER Cloudshell Server Password
75+
-p PASSWORD, --password PASSWORD
76+
Cloudshell Server IP or DNS name
77+
--from FROM start range. format MM/DD/YYYY HH:MM, ex. 01/01/2015
78+
00:00
79+
--until UNTIL end range. format MM/DD/YYYY HH:MM, ex. 01/01/2025
80+
00:00
81+
--users USERS list of space separated cloudshell users. Example:
82+
user1 user2 user3.
83+
84+
```
85+
86+
Sample commands:
87+
`python delete_sandboxes_with_target_users.py -s localhost -u admin -p admin --users user1 user2 user3`
88+
`python delete_sandboxes_with_target_users.py -s localhost -u admin -p admin --users user1 user2 user3 --from 01/01/2020 --until 01/01/2021`
89+
90+
## Delete Blueprints with Target Users
91+
Accepts list of cloudshell users. Deletes blueprints owned by one of specified users.
92+
93+
`python delete_blueprints_owned_by_users.py --help`
94+
95+
```
96+
usage: Delete ALL blueprints [-h] -s SERVER -u USER -p PASSWORD --users USERS
97+
98+
Automation API script to delete blueprints
99+
100+
optional arguments:
101+
-h, --help show this help message and exit
102+
-s SERVER, --server SERVER
103+
Cloudshell Server User
104+
-u USER, --user USER Cloudshell Server Password
105+
-p PASSWORD, --password PASSWORD
106+
Cloudshell Server IP or DNS name
107+
--users USERS list of space separated cloudshell users. Example:
108+
user1 user2 user3.
109+
```
110+
111+
sample command:
112+
`python delete_blueprints_owned_by_users.py -s localhost -u admin -p admin --users user1 user2 user3`

automation_api_scripts/delete-sandboxes-and-blueprints/__init__.py

Whitespace-only changes.
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
import json
2+
from typing import List
3+
4+
from argparse import ArgumentParser
5+
import sys
6+
from cloudshell.api.cloudshell_api import CloudShellAPISession, ReservationShortInfo, TopologyInfo
7+
8+
import constants as const
9+
10+
11+
def add_cs_server_args(parser: ArgumentParser):
12+
parser.add_argument('-s', f'--{const.SERVER_KEY}', required=True, help="Cloudshell Server User")
13+
parser.add_argument('-u', f'--{const.USER_KEY}', required=True, help="Cloudshell Server Password")
14+
parser.add_argument('-p', f'--{const.PASSWORD_KEY}', required=True, help="Cloudshell Server IP or DNS name")
15+
16+
17+
def add_time_range_args(parser: ArgumentParser):
18+
parser.add_argument(f'--{const.FROM_KEY}', help="start range. format MM/DD/YYYY HH:MM, ex. 01/01/2015 00:00",
19+
default="01/01/2015 00:00")
20+
parser.add_argument(f'--{const.UNTIL_KEY}', help="end range. format MM/DD/YYYY HH:MM, ex. 01/01/2025 00:00",
21+
default="01/01/2025 00:00")
22+
23+
24+
def add_target_user_arg(parser: ArgumentParser):
25+
parser.add_argument(f'--{const.TARGET_USERS_KEY}',
26+
help="list of space separated cloudshell users. Example: user1 user2 user3.",
27+
required=True)
28+
29+
30+
def _prompt_to_delete(prompt_text):
31+
# raw_input returns the empty string for "enter"
32+
yes = {'yes', 'y', 'ye', ''}
33+
no = {'no', 'n'}
34+
35+
choice = input(prompt_text).lower()
36+
37+
if choice in yes:
38+
print("Starting script..")
39+
return
40+
elif choice in no:
41+
print("Ending script")
42+
sys.exit(0)
43+
else:
44+
print("Please respond with 'yes' or 'no'")
45+
sys.exit(0)
46+
47+
48+
def all_sandbox_delete_prompt(from_time, until_time):
49+
prompt = f"Are you sure you want to delete ALL sandboxes in time range {from_time} - {until_time}? [y/n]"
50+
_prompt_to_delete(prompt)
51+
52+
53+
def all_blueprint_delete_prompt():
54+
prompt = "Are you sure you want to delete ALL blueprints? [y/n]"
55+
_prompt_to_delete(prompt)
56+
57+
58+
def get_cloudshell_api(server, user, password) -> CloudShellAPISession:
59+
try:
60+
api = CloudShellAPISession(host=server, username=user, password=password, domain="Global")
61+
except Exception as e:
62+
print(f"Issue getting cloudshell API session. {type(e).__name__}: {str(e)}")
63+
raise
64+
return api
65+
66+
67+
def get_all_historical_sandboxes(api: CloudShellAPISession, from_time: str, until_time: str) -> List[
68+
ReservationShortInfo]:
69+
try:
70+
all_sandboxes = api.GetScheduledReservations(fromTime=from_time, untilTime=until_time).Reservations
71+
except Exception as e:
72+
print(f"Issue getting sandboxes. {type(e).__name__}: {str(e)}")
73+
raise
74+
historical_sandboxes = [x for x in all_sandboxes if x.Status == "Completed"]
75+
return historical_sandboxes
76+
77+
78+
def get_all_regular_blueprints(api: CloudShellAPISession) -> List[TopologyInfo]:
79+
all_blueprints = api.GetTopologiesByCategory().Topologies
80+
results = []
81+
for curr_bp in all_blueprints:
82+
details = api.GetTopologyDetails(topologyFullPath=curr_bp)
83+
if details.Type == "Regular":
84+
results.append(details)
85+
return results
86+
87+
88+
def get_regular_blueprints_owned_by_users(api: CloudShellAPISession, owners: List[str]) -> List[TopologyInfo]:
89+
all_blueprints = api.GetTopologiesByCategory().Topologies
90+
results = []
91+
for curr_bp in all_blueprints:
92+
details = api.GetTopologyDetails(topologyFullPath=curr_bp)
93+
if details.Type == "Regular":
94+
for curr_owner in owners:
95+
if curr_owner == details.Owner:
96+
results.append(details)
97+
return results
98+
99+
100+
def validate_cloudshell_users(api: CloudShellAPISession, users: List[str]):
101+
failed = []
102+
for curr_user in users:
103+
try:
104+
api.GetUserDetails(curr_user)
105+
except Exception as e:
106+
failed.append(curr_user)
107+
if failed:
108+
raise Exception(f"Invalid cloudshell users passed:\n{json.dumps(failed, indent=4)}")
109+
110+
if __name__ == "__main__":
111+
api = CloudShellAPISession("localhost", "admin", "admin", "Global")
112+
get_all_historical_sandboxes(api, "01/01/2018 00:00", "01/01/2022 00:00")
113+
pass
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
SERVER_KEY = "server"
2+
USER_KEY = "user"
3+
PASSWORD_KEY = "password"
4+
5+
FROM_KEY = "from"
6+
UNTIL_KEY = "until"
7+
8+
TARGET_USERS_KEY = "users"
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import json
2+
3+
import sys
4+
from argparse import ArgumentParser
5+
from common import add_cs_server_args, get_cloudshell_api, all_blueprint_delete_prompt, get_all_regular_blueprints
6+
import constants as const
7+
8+
parser = ArgumentParser(prog="Delete ALL blueprints",
9+
description="Automation API script to delete blueprints")
10+
add_cs_server_args(parser)
11+
12+
# unpack args
13+
args_dict = vars(parser.parse_args())
14+
server = args_dict[const.SERVER_KEY]
15+
user = args_dict[const.USER_KEY]
16+
password = args_dict[const.PASSWORD_KEY]
17+
18+
all_blueprint_delete_prompt()
19+
api = get_cloudshell_api(server, user, password)
20+
all_blueprints = get_all_regular_blueprints(api)
21+
22+
if not all_blueprints:
23+
print("No blueprints found. Stopping.")
24+
sys.exit(0)
25+
26+
print("Deleting ALL blueprints...")
27+
failed = []
28+
for curr_bp in all_blueprints:
29+
print(f"Deleting blueprint '{curr_bp.Name}'")
30+
try:
31+
api.DeleteTopology(topologyFullPath=curr_bp.Name)
32+
except Exception as e:
33+
print(f"Error deleting blueprint '{curr_bp.Name}'. Exception - \n{type(e).__name__}: {str(e)}")
34+
print("===============")
35+
failed.append(curr_bp.Name)
36+
37+
if failed:
38+
raise Exception(f"Failed blueprint deletions:\n{json.dumps(failed, indent=4)}")
39+
40+
print("Delete blueprints script done.")
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import json
2+
3+
import sys
4+
from argparse import ArgumentParser
5+
from common import add_cs_server_args, add_time_range_args, get_cloudshell_api, get_all_historical_sandboxes, \
6+
all_sandbox_delete_prompt
7+
import constants as const
8+
9+
parser = ArgumentParser(prog="Delete ALL sandboxes",
10+
description="Automation API script to delete sandboxes")
11+
add_cs_server_args(parser)
12+
add_time_range_args(parser)
13+
14+
# unpack args
15+
args_dict = vars(parser.parse_args())
16+
server = args_dict[const.SERVER_KEY]
17+
user = args_dict[const.USER_KEY]
18+
password = args_dict[const.PASSWORD_KEY]
19+
from_time = args_dict[const.FROM_KEY]
20+
until_time = args_dict[const.UNTIL_KEY]
21+
22+
all_sandbox_delete_prompt(from_time, until_time)
23+
api = get_cloudshell_api(server, user, password)
24+
all_historical_sandboxes = get_all_historical_sandboxes(api, from_time, until_time)
25+
26+
if not all_historical_sandboxes:
27+
print("No historical sandboxes found. Stopping.")
28+
sys.exit(0)
29+
30+
print("Deleting ALL historical Sandboxes...")
31+
failed = []
32+
for sandbox in all_historical_sandboxes:
33+
print(f"Deleting sandbox '{sandbox.Id}'")
34+
try:
35+
api.DeleteReservation(sandbox.Id)
36+
except Exception as e:
37+
print(f"Error deleting sandbox '{sandbox.Id}'. Exception - \n{type(e).__name__}: {str(e)}")
38+
print("===============")
39+
failed.append(sandbox.Id)
40+
41+
42+
if failed:
43+
raise Exception(f"Failed sandbox deletions:\n{json.dumps(failed, indent=4)}")
44+
45+
print("Delete sandboxes script done.")
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import json
2+
3+
import sys
4+
from argparse import ArgumentParser
5+
from common import add_cs_server_args, get_cloudshell_api, get_regular_blueprints_owned_by_users, add_target_user_arg, \
6+
validate_cloudshell_users
7+
import constants as const
8+
9+
parser = ArgumentParser(prog="Delete ALL blueprints",
10+
description="Automation API script to delete blueprints")
11+
add_cs_server_args(parser)
12+
add_target_user_arg(parser)
13+
14+
# unpack args
15+
args_dict = vars(parser.parse_args())
16+
server = args_dict[const.SERVER_KEY]
17+
user = args_dict[const.USER_KEY]
18+
password = args_dict[const.PASSWORD_KEY]
19+
target_users = args_dict[const.TARGET_USERS_KEY]
20+
21+
api = get_cloudshell_api(server, user, password)
22+
validate_cloudshell_users(api, target_users)
23+
target_blueprints = get_regular_blueprints_owned_by_users(api, target_users)
24+
25+
if not target_blueprints:
26+
print("No blueprints found. Stopping.")
27+
sys.exit(0)
28+
29+
print("Deleting ALL blueprints owned by target users...")
30+
failed = []
31+
for curr_bp in target_blueprints:
32+
print(f"Deleting blueprint '{curr_bp.Name}'")
33+
try:
34+
api.DeleteTopology(topologyFullPath=curr_bp.Name)
35+
except Exception as e:
36+
print(f"Error deleting blueprint '{curr_bp.Name}'. Exception - \n{type(e).__name__}: {str(e)}")
37+
print("===============")
38+
failed.append(curr_bp.Name)
39+
40+
41+
if failed:
42+
raise Exception(f"Failed blueprint deletions:\n{json.dumps(failed, indent=4)}")
43+
44+
print("Delete blueprints for target users script done.")

0 commit comments

Comments
 (0)