Skip to content

Commit 9d787e7

Browse files
author
Jim Robinson
committed
Split commands into groups, add cloudfront commands
1 parent d499a37 commit 9d787e7

File tree

5 files changed

+299
-172
lines changed

5 files changed

+299
-172
lines changed

Pipfile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ boto3-stubs = {extras = ["ecs"], version = "*"}
1212
autopep8 = "*"
1313
build = "*"
1414
twine = "*"
15-
boto3-stubs = {extras = ["ecs", "essential", "servicediscovery"], version = "*"}
15+
boto3-stubs = {extras = ["cloudfront", "ecs", "essential", "resourcegroupstaggingapi", "servicediscovery", "sts"], version = "*"}
1616

1717
[requires]
1818
python_version = "3.8"

Pipfile.lock

Lines changed: 44 additions & 23 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

croudtech_ecs_tools/cli.py

Lines changed: 25 additions & 147 deletions
Original file line numberDiff line numberDiff line change
@@ -5,157 +5,23 @@
55
from click.decorators import command
66
from click.termui import prompt
77
import os
8-
from croudtech_ecs_tools.ecs import Ecs, EcsScaler, ServiceInfo
8+
from croudtech_ecs_tools.ecs import Ecs, EcsScaler, ServiceInfo, EcsTools
9+
from croudtech_ecs_tools.cloudfront import Cloudfront
910
import json
1011

1112

12-
13-
class EcsTools:
14-
_services = {}
15-
_tasks = {}
16-
17-
def __init__(self, region):
18-
self.region = region
19-
print(self.region)
20-
self.ecs_client = boto3.client("ecs", config=Boto3Config(
21-
region_name= self.region
22-
))
23-
24-
@property
25-
def clusters(self):
26-
if not hasattr(self, "_clusters"):
27-
paginator = self.ecs_client.get_paginator("list_clusters")
28-
response_iterator = paginator.paginate(
29-
PaginationConfig={
30-
"PageSize": 10,
31-
}
32-
)
33-
self._clusters = []
34-
for page in response_iterator:
35-
for cluster in page["clusterArns"]:
36-
self._clusters.append(cluster.split("/").pop())
37-
38-
return self._clusters
39-
40-
def extractFromArn(self, arn):
41-
arn_parts = arn.split(":")[-1].split("/")[1:]
42-
return arn_parts
43-
44-
def get_services(self, cluster):
45-
if cluster not in self._services:
46-
self._services[cluster] = []
47-
paginator = self.ecs_client.get_paginator("list_services")
48-
49-
response_iterator = paginator.paginate(
50-
cluster=cluster,
51-
PaginationConfig={
52-
"PageSize": 50,
53-
}
54-
)
55-
for page in response_iterator:
56-
for service in page["serviceArns"]:
57-
self._services[cluster].append(service)
58-
return self._services[cluster]
59-
60-
def get_tasks(self, cluster, service):
61-
task_key = cluster+service
62-
if task_key not in self._tasks:
63-
self._tasks[task_key] = []
64-
paginator = self.ecs_client.get_paginator("list_tasks")
65-
response_iterator = paginator.paginate(
66-
cluster=cluster,
67-
serviceName=service,
68-
PaginationConfig={
69-
"PageSize": 50,
70-
}
71-
)
72-
for page in response_iterator:
73-
for task in page["taskArns"]:
74-
self._tasks[task_key].append(task)
75-
return self._tasks[task_key]
76-
77-
def describe_task(self, cluster, task_arn):
78-
response = self.ecs_client.describe_tasks(
79-
cluster=cluster,
80-
tasks=[
81-
task_arn,
82-
],
83-
)
84-
task = response["tasks"].pop()
85-
return task
86-
87-
def execute_command(self,cluster, container, task_arn, command="bash"):
88-
return self.ecs_client.execute_command(
89-
cluster=cluster,
90-
container=container["name"],
91-
command=command,
92-
interactive=True,
93-
task=task_arn
94-
)
95-
96-
def restart_service(self, service_arn, wait=False):
97-
try:
98-
cluster, service = self.extractFromArn(service_arn)
99-
except ValueError as err:
100-
click.echo(f"Invalid service ARN {service_arn}")
101-
return
102-
waiter = self.ecs_client.get_waiter('services_stable')
103-
104-
self.ecs_client.update_service(
105-
cluster=cluster,
106-
service=service,
107-
forceNewDeployment=True
108-
)
109-
if wait:
110-
waiter.wait(
111-
cluster=cluster,
112-
services=[
113-
service,
114-
],
115-
WaiterConfig={
116-
'Delay': 5,
117-
'MaxAttempts': 100
118-
}
119-
)
120-
return True
121-
122-
def get_task_containers(self, cluster, task_arn):
123-
return self.describe_task(cluster, task_arn)["containers"]
124-
125-
def get_service_options(self, cluster):
126-
options = []
127-
for index, option in enumerate(self.get_services(cluster)):
128-
option_name = option.split("/").pop()
129-
options.append(f"{index}: {option_name}")
130-
return "\n".join(options)
131-
132-
def get_task_options(self, cluster, service):
133-
options = []
134-
for index, option in enumerate(self.get_tasks(cluster, service)):
135-
option_name = option.split("/").pop()
136-
options.append(f"{index}: {option_name}")
137-
return "\n".join(options)
138-
139-
def get_task__container_options(self, cluster, task_arn):
140-
options = []
141-
for index, option in enumerate(self.get_task_containers(cluster, task_arn)):
142-
option_name = option["name"]
143-
options.append(f"{index}: {option_name}")
144-
return "\n".join(options)
145-
146-
def get_cluster_options(self):
147-
options = []
148-
for index, option in enumerate(self.clusters):
149-
options.append(f"{index}: {option}")
150-
return "\n".join(options)
151-
15213
@click.group()
15314
@click.version_option()
15415
def cli():
15516
"Tools for managing ECS Services and Tasks"
15617

18+
@cli.group()
19+
@click.version_option()
20+
def ecs():
21+
"Tools for managing ECS Services and Tasks"
22+
15723

158-
@cli.command()
24+
@ecs.command()
15925
@click.option("--region", required=True, default=os.getenv("AWS_DEFAULT_REGION", "eu-west-2"))
16026
@click.option("--command", default="bash")
16127
def ecs_shell(region, command):
@@ -180,7 +46,7 @@ def ecs_shell(region, command):
18046
click.secho(command, fg="cyan")
18147
os.system(command)
18248

183-
@cli.command()
49+
@ecs.command()
18450
@click.option("--region", required=True, default=os.getenv("AWS_DEFAULT_REGION", "eu-west-2"))
18551
@click.option('--wait/--no-wait', default=False, help="Wait for service to become stable before exiting")
18652
@click.argument("service_arn", required=False)
@@ -200,30 +66,42 @@ def restart_service(region, wait, service_arn):
20066
click.echo(f"Service {service_arn} restarted")
20167

20268

203-
@cli.command()
69+
@ecs.command()
20470
@click.option("--cluster", required=True)
20571
def list_service_discovery_endpoints(cluster):
20672
ecs_manager = Ecs(cluster=cluster)
20773
print(json.dumps(ecs_manager.list_ecs_service_endpoints(), indent=2, default=str))
20874

209-
@cli.command()
75+
@ecs.command()
21076
@click.option("--cluster", required=False)
21177
@click.option("--ip-filter", multiple=True)
21278
def show_service_ips(cluster=None, ip_filter=None):
21379
service_info = ServiceInfo()
21480
print(json.dumps(service_info.show_service_ips(cluster, ip_filter), indent=2, default=str))
21581

216-
@cli.command()
82+
@ecs.command()
21783
@click.argument("environment")
21884
def scale_up(environment):
21985
ecs_scaler = EcsScaler(environment)
22086
ecs_scaler.scale_up()
22187

222-
@cli.command()
88+
@ecs.command()
22389
@click.argument("environment")
22490
def scale_down(environment):
22591
ecs_scaler = EcsScaler(environment)
22692
ecs_scaler.scale_down()
22793

94+
@cli.group()
95+
@click.version_option()
96+
def cloudfront():
97+
"Tools for managing Cloudfront Distributions"
98+
99+
@cloudfront.command()
100+
@click.argument("environment")
101+
@click.option("--paths", multiple=True)
102+
def clear_cloudfront_cache(environment, paths):
103+
cloudfront_manager = Cloudfront()
104+
cloudfront_manager.clear_cache(environment, paths)
105+
228106
if __name__ == "__main__":
229107
cli()

0 commit comments

Comments
 (0)