ecs-deployer-boto3 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,14 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *$py.class
4
+ *.egg-info/
5
+ .venv/
6
+ venv/
7
+ dist/
8
+ build/
9
+ .pytest_cache/
10
+ .ruff_cache/
11
+ .mypy_cache/
12
+ .DS_Store
13
+ .idea/
14
+ .vscode/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ilia Peterov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,93 @@
1
+ Metadata-Version: 2.4
2
+ Name: ecs-deployer-boto3
3
+ Version: 0.1.0
4
+ Summary: Deploy applications to AWS ECS using boto3 and pydantic
5
+ Project-URL: Homepage, https://github.com/ipeterov/ecs-deployer-boto3
6
+ Project-URL: Repository, https://github.com/ipeterov/ecs-deployer-boto3
7
+ Author-email: Ilia Peterov <ipeterov1@gmail.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: Software Development :: Libraries
18
+ Classifier: Topic :: System :: Systems Administration
19
+ Requires-Python: >=3.12
20
+ Requires-Dist: boto3>=1.34
21
+ Requires-Dist: pydantic>=2.0
22
+ Description-Content-Type: text/markdown
23
+
24
+ # ecs-deployer-boto3
25
+
26
+ Deploy applications to AWS ECS using boto3 and pydantic.
27
+
28
+ This library provides a thin, typed wrapper over the AWS ECS deployment API.
29
+ It is decoupled from how you discover or provision your infrastructure
30
+ (CloudFormation, CDK, Terraform, or by hand) — you describe your services as
31
+ pydantic models and the library handles registering task definitions, creating
32
+ or updating services, cleaning up old revisions, and monitoring deployments.
33
+
34
+ Supports both EC2 (with placement strategy / constraints) and Fargate (with
35
+ capacity provider strategy and `awsvpc` network configuration).
36
+
37
+ ## Installation
38
+
39
+ ```bash
40
+ pip install ecs-deployer-boto3
41
+ ```
42
+
43
+ ## Usage
44
+
45
+ ```python
46
+ import boto3
47
+
48
+ from ecs_deployer_boto3 import (
49
+ ApplicationUpdater,
50
+ Container,
51
+ DeploymentMonitor,
52
+ Service,
53
+ Task,
54
+ )
55
+
56
+ services = [
57
+ Service(
58
+ name='web',
59
+ cluster='my-cluster',
60
+ task_definition=Task(
61
+ family='web',
62
+ containers=[
63
+ Container(
64
+ name='web',
65
+ image='123456789.dkr.ecr.us-east-1.amazonaws.com/web:latest',
66
+ port_mappings=[{'container_port': 8000}],
67
+ ),
68
+ ],
69
+ cpu='256',
70
+ memory='512',
71
+ requires_compatibilities=['FARGATE'],
72
+ ),
73
+ launch_type='FARGATE',
74
+ network_configuration={
75
+ 'subnets': ['subnet-abc'],
76
+ 'security_groups': ['sg-abc'],
77
+ 'assign_public_ip': 'ENABLED',
78
+ },
79
+ ),
80
+ ]
81
+
82
+ session = boto3.Session()
83
+
84
+ updater = ApplicationUpdater(services, session)
85
+ updater.update_application(environment={'FOO': 'bar'})
86
+
87
+ monitor = DeploymentMonitor(services, session)
88
+ monitor.monitor(limit_minutes=15)
89
+ ```
90
+
91
+ ## License
92
+
93
+ MIT
@@ -0,0 +1,70 @@
1
+ # ecs-deployer-boto3
2
+
3
+ Deploy applications to AWS ECS using boto3 and pydantic.
4
+
5
+ This library provides a thin, typed wrapper over the AWS ECS deployment API.
6
+ It is decoupled from how you discover or provision your infrastructure
7
+ (CloudFormation, CDK, Terraform, or by hand) — you describe your services as
8
+ pydantic models and the library handles registering task definitions, creating
9
+ or updating services, cleaning up old revisions, and monitoring deployments.
10
+
11
+ Supports both EC2 (with placement strategy / constraints) and Fargate (with
12
+ capacity provider strategy and `awsvpc` network configuration).
13
+
14
+ ## Installation
15
+
16
+ ```bash
17
+ pip install ecs-deployer-boto3
18
+ ```
19
+
20
+ ## Usage
21
+
22
+ ```python
23
+ import boto3
24
+
25
+ from ecs_deployer_boto3 import (
26
+ ApplicationUpdater,
27
+ Container,
28
+ DeploymentMonitor,
29
+ Service,
30
+ Task,
31
+ )
32
+
33
+ services = [
34
+ Service(
35
+ name='web',
36
+ cluster='my-cluster',
37
+ task_definition=Task(
38
+ family='web',
39
+ containers=[
40
+ Container(
41
+ name='web',
42
+ image='123456789.dkr.ecr.us-east-1.amazonaws.com/web:latest',
43
+ port_mappings=[{'container_port': 8000}],
44
+ ),
45
+ ],
46
+ cpu='256',
47
+ memory='512',
48
+ requires_compatibilities=['FARGATE'],
49
+ ),
50
+ launch_type='FARGATE',
51
+ network_configuration={
52
+ 'subnets': ['subnet-abc'],
53
+ 'security_groups': ['sg-abc'],
54
+ 'assign_public_ip': 'ENABLED',
55
+ },
56
+ ),
57
+ ]
58
+
59
+ session = boto3.Session()
60
+
61
+ updater = ApplicationUpdater(services, session)
62
+ updater.update_application(environment={'FOO': 'bar'})
63
+
64
+ monitor = DeploymentMonitor(services, session)
65
+ monitor.monitor(limit_minutes=15)
66
+ ```
67
+
68
+ ## License
69
+
70
+ MIT
@@ -0,0 +1,64 @@
1
+ """Deploy applications to AWS ECS using boto3 and pydantic."""
2
+
3
+ from .application_updater import ApplicationUpdater
4
+ from .deploy_monitor import DeploymentMonitor, ServiceStatus
5
+ from .models import (
6
+ AwsVpcConfiguration,
7
+ BlueGreenConfiguration,
8
+ CapacityProviderStrategyItem,
9
+ Container,
10
+ ContainerDependency,
11
+ DeploymentConfiguration,
12
+ HealthCheck,
13
+ HostVolumeProperties,
14
+ LinuxCapabilities,
15
+ LinuxParameters,
16
+ LoadBalancer,
17
+ LogConfiguration,
18
+ MountPoint,
19
+ NetworkConfiguration,
20
+ PlacementConstraint,
21
+ PlacementStrategy,
22
+ PortMapping,
23
+ RuntimePlatform,
24
+ Secret,
25
+ Service,
26
+ Task,
27
+ Volume,
28
+ VolumeFrom,
29
+ )
30
+ from .utils import chunker, echo
31
+
32
+
33
+ __version__ = '0.1.0'
34
+
35
+ __all__ = [
36
+ 'ApplicationUpdater',
37
+ 'AwsVpcConfiguration',
38
+ 'BlueGreenConfiguration',
39
+ 'CapacityProviderStrategyItem',
40
+ 'Container',
41
+ 'ContainerDependency',
42
+ 'DeploymentConfiguration',
43
+ 'DeploymentMonitor',
44
+ 'HealthCheck',
45
+ 'HostVolumeProperties',
46
+ 'LinuxCapabilities',
47
+ 'LinuxParameters',
48
+ 'LoadBalancer',
49
+ 'LogConfiguration',
50
+ 'MountPoint',
51
+ 'NetworkConfiguration',
52
+ 'PlacementConstraint',
53
+ 'PlacementStrategy',
54
+ 'PortMapping',
55
+ 'RuntimePlatform',
56
+ 'Secret',
57
+ 'Service',
58
+ 'ServiceStatus',
59
+ 'Task',
60
+ 'Volume',
61
+ 'VolumeFrom',
62
+ 'chunker',
63
+ 'echo',
64
+ ]
@@ -0,0 +1,364 @@
1
+ """Deploy ECS services described by ``Service`` models."""
2
+
3
+ import json
4
+ from collections.abc import Callable
5
+ from concurrent.futures import ThreadPoolExecutor
6
+ from typing import TYPE_CHECKING, Any
7
+
8
+ from botocore.exceptions import ClientError
9
+
10
+ from .models import Service
11
+ from .utils import chunker, echo
12
+
13
+
14
+ if TYPE_CHECKING:
15
+ from boto3.session import Session
16
+ from mypy_boto3_ecs import ECSClient
17
+
18
+
19
+ class ApplicationUpdater:
20
+ """Reconcile a list of desired services against what's running in ECS.
21
+
22
+ On ``update_application()``:
23
+
24
+ - For each existing ECS service:
25
+ - If it matches a desired service and can be updated in place, update it.
26
+ - Otherwise, remove it (it was either renamed or removed from the config).
27
+ - For each desired service that doesn't exist yet, create it.
28
+ - Clean up any task definitions that are now INACTIVE.
29
+
30
+ Some service properties can't be changed via ``update_service`` (placement
31
+ strategy / constraints, deployment controller, role, launch type, capacity
32
+ provider). When those change, the service is removed and re-created.
33
+ """
34
+
35
+ def __init__(
36
+ self,
37
+ services: list[Service],
38
+ boto3_session: 'Session',
39
+ dry_run: bool = False,
40
+ ):
41
+ self.ecs: 'ECSClient' = boto3_session.client('ecs')
42
+ self.dry_run = dry_run
43
+
44
+ if len({s.name for s in services}) != len(services):
45
+ raise ValueError('Duplicate service name detected')
46
+
47
+ self.desired_services = {s.name: s for s in services if s.desired_count}
48
+ self.cluster_names = {s.cluster for s in services}
49
+
50
+ # ----- helpers ---------------------------------------------------------
51
+
52
+ def _call(
53
+ self,
54
+ method: Callable,
55
+ params: dict,
56
+ success_message: str | None = None,
57
+ ) -> Any:
58
+ """Call a boto3 method, or print what would be called in dry-run mode."""
59
+ method_name = method.__name__
60
+
61
+ if self.dry_run:
62
+ # Avoid bloating the log with the full environment. The caller
63
+ # already has access to the secrets, so this is about readability,
64
+ # not security.
65
+ params_for_log = params
66
+ if method_name == 'register_task_definition':
67
+ params_for_log = json.loads(json.dumps(params))
68
+ for container in params_for_log.get('containerDefinitions', []):
69
+ container['environment'] = '[OMITTED FROM OUTPUT]'
70
+ formatted = json.dumps(params_for_log, indent=2, sort_keys=True)
71
+ echo(f'Would call `{method_name}` with:\n{formatted}')
72
+ return None
73
+
74
+ result = method(**params)
75
+ if success_message:
76
+ echo(success_message)
77
+ return result
78
+
79
+ @staticmethod
80
+ def _explain_recreate(
81
+ service_name: str,
82
+ attribute: str,
83
+ current: Any,
84
+ desired: Any,
85
+ ) -> None:
86
+ echo(
87
+ f'{service_name}: {attribute} forces re-creation, '
88
+ f'current: {current!r}, desired: {desired!r}',
89
+ )
90
+
91
+ # ----- task definitions -----------------------------------------------
92
+
93
+ def register_task(self, task_definition: dict) -> None:
94
+ family = task_definition.get('family', '')
95
+ echo(f'Registering task definition: {family}')
96
+
97
+ response = self._call(self.ecs.register_task_definition, task_definition)
98
+ if self.dry_run:
99
+ return
100
+
101
+ task_def = response['taskDefinition']
102
+ revision = task_def['revision']
103
+ echo(f'Revision registered: {family}:{revision}')
104
+
105
+ if revision > 1:
106
+ self.deregister_task_definition(f'{family}:{revision - 1}')
107
+
108
+ def deregister_task_definition(self, task_definition: str) -> None:
109
+ try:
110
+ self.ecs.deregister_task_definition(taskDefinition=task_definition)
111
+ echo(f'De-registered task definition {task_definition}')
112
+ except ClientError as err:
113
+ message = str(err)
114
+ if 'in the process of being deleted' in message:
115
+ echo(
116
+ f'Task definition {task_definition} is being deleted, skipping',
117
+ )
118
+ elif 'Unable to describe task definition' in message:
119
+ echo(
120
+ f'Task definition {task_definition} already de-registered, skipping',
121
+ )
122
+ else:
123
+ raise
124
+
125
+ def delete_inactive_ecs_task_definitions(self) -> None:
126
+ response = self.ecs.list_task_definitions(status='INACTIVE')
127
+ inactive = response.get('taskDefinitionArns', [])
128
+ echo(
129
+ f'Cleaning up inactive ECS task definitions. Definitions to delete: {len(inactive)}',
130
+ )
131
+ if not inactive:
132
+ return
133
+
134
+ # AWS allows up to 10 deletions at a time.
135
+ for batch in chunker(inactive, 10):
136
+ self._call(
137
+ self.ecs.delete_task_definitions,
138
+ {'taskDefinitions': batch},
139
+ )
140
+
141
+ # ----- service reconciliation -----------------------------------------
142
+
143
+ def get_existing_services(self, cluster: str):
144
+ response = self.ecs.list_services(cluster=cluster)
145
+ service_arns = response.get('serviceArns', [])
146
+ if not service_arns:
147
+ return
148
+ for batch in chunker(service_arns, 10):
149
+ response = self.ecs.describe_services(
150
+ cluster=cluster,
151
+ services=batch,
152
+ )
153
+ yield from response['services']
154
+
155
+ def match_service_for_update(
156
+ self,
157
+ cluster_name: str,
158
+ details: dict,
159
+ ) -> Service | None:
160
+ """Return the desired service if the existing one can be updated in
161
+ place, otherwise None (caller will remove + re-create)."""
162
+ service_name = details['serviceName']
163
+ match = self.desired_services.get(service_name)
164
+
165
+ if not match:
166
+ echo(f'Service {service_name} not in desired services')
167
+ return None
168
+
169
+ if match.cluster != cluster_name:
170
+ echo(f'Service {service_name} not in cluster {cluster_name}')
171
+ return None
172
+
173
+ # Task family
174
+ task_arn = details['taskDefinition']
175
+ current_family = task_arn.split('/')[-1].split(':')[0]
176
+ if current_family != match.task_definition.family:
177
+ self._explain_recreate(
178
+ service_name,
179
+ 'task family',
180
+ current_family,
181
+ match.task_definition.family,
182
+ )
183
+ return None
184
+
185
+ # Deployment controller
186
+ current_controller = details['deploymentController']['type']
187
+ if current_controller != match.deployment_controller:
188
+ self._explain_recreate(
189
+ service_name,
190
+ 'deployment controller',
191
+ current_controller,
192
+ match.deployment_controller,
193
+ )
194
+ return None
195
+
196
+ # Placement strategy
197
+ current_ps = details.get('placementStrategy', [])
198
+ desired_ps = [p.as_aws_dict() for p in match.placement_strategy]
199
+ if current_ps != desired_ps:
200
+ self._explain_recreate(
201
+ service_name,
202
+ 'placement strategy',
203
+ current_ps,
204
+ desired_ps,
205
+ )
206
+ return None
207
+
208
+ # Placement constraints
209
+ current_pc = details.get('placementConstraints', [])
210
+ desired_pc = [p.as_aws_dict() for p in match.placement_constraints]
211
+ if current_pc != desired_pc:
212
+ self._explain_recreate(
213
+ service_name,
214
+ 'placement constraints',
215
+ current_pc,
216
+ desired_pc,
217
+ )
218
+ return None
219
+
220
+ # Service role (classic EC2 + ELB)
221
+ current_role = details.get('roleArn')
222
+ # AWS returns the role as an ARN; ours may be a name or an ARN. Match
223
+ # by suffix to avoid spurious diffs.
224
+ if match.role_arn and current_role:
225
+ if not (
226
+ current_role == match.role_arn
227
+ or current_role.endswith(f'/{match.role_arn}')
228
+ or match.role_arn.endswith(f'/{current_role}')
229
+ ):
230
+ self._explain_recreate(
231
+ service_name,
232
+ 'role',
233
+ current_role,
234
+ match.role_arn,
235
+ )
236
+ return None
237
+ elif (current_role is None) != (match.role_arn is None):
238
+ self._explain_recreate(
239
+ service_name,
240
+ 'role',
241
+ current_role,
242
+ match.role_arn,
243
+ )
244
+ return None
245
+
246
+ # Launch type / capacity provider strategy. Switching between these
247
+ # two requires a re-create.
248
+ current_launch = details.get('launchType')
249
+ current_cps = details.get('capacityProviderStrategy', [])
250
+ desired_cps = [c.as_aws_dict() for c in match.capacity_provider_strategy]
251
+ if bool(current_cps) != bool(desired_cps):
252
+ self._explain_recreate(
253
+ service_name,
254
+ 'capacity provider strategy presence',
255
+ bool(current_cps),
256
+ bool(desired_cps),
257
+ )
258
+ return None
259
+ if not desired_cps and current_launch != match.launch_type:
260
+ self._explain_recreate(
261
+ service_name,
262
+ 'launch type',
263
+ current_launch,
264
+ match.launch_type,
265
+ )
266
+ return None
267
+
268
+ return match
269
+
270
+ def update_service(self, service_name: str, match: Service) -> None:
271
+ echo(f'Updating service: {service_name}', prefix='\n->> ')
272
+
273
+ if match.deployment_controller != 'ECS':
274
+ raise ValueError(
275
+ f'Unsupported deployment controller for in-place update: '
276
+ f'{match.deployment_controller}',
277
+ )
278
+
279
+ self._call(
280
+ self.ecs.update_service,
281
+ match.as_aws_update_dict(),
282
+ success_message=f'Service updated: {service_name}',
283
+ )
284
+
285
+ def remove_service(self, cluster_name: str, service_name: str) -> None:
286
+ echo(f'Removing service: {service_name}')
287
+
288
+ self._call(
289
+ self.ecs.update_service,
290
+ {'cluster': cluster_name, 'service': service_name, 'desiredCount': 0},
291
+ )
292
+
293
+ response = self._call(
294
+ self.ecs.delete_service,
295
+ {'cluster': cluster_name, 'service': service_name},
296
+ success_message=f'Service removed: {service_name}',
297
+ )
298
+ if self.dry_run:
299
+ return
300
+
301
+ task_arn = response['service']['taskDefinition']
302
+ self.deregister_task_definition(task_arn)
303
+
304
+ echo(f'Waiting for service to terminate: {service_name}')
305
+ waiter = self.ecs.get_waiter('services_inactive')
306
+ waiter.wait(cluster=cluster_name, services=[service_name])
307
+
308
+ def create_service(self, match: Service) -> None:
309
+ echo(f'Creating service: {match.name}')
310
+ self._call(
311
+ self.ecs.create_service,
312
+ match.as_aws_create_dict(),
313
+ success_message=f'Service created: {match.name}',
314
+ )
315
+
316
+ # ----- orchestration --------------------------------------------------
317
+
318
+ def _update_or_remove(
319
+ self,
320
+ environment: dict,
321
+ cluster_name: str,
322
+ ecs_details: dict,
323
+ ) -> str | None:
324
+ service_name = ecs_details['serviceName']
325
+ match = self.match_service_for_update(cluster_name, ecs_details)
326
+ if match is None:
327
+ self.remove_service(cluster_name, service_name)
328
+ return None
329
+
330
+ self.register_task(match.task_definition.as_aws_dict(environment))
331
+ self.update_service(service_name, match)
332
+ return service_name
333
+
334
+ def update_all_services(self, environment: dict) -> None:
335
+ to_process = []
336
+ for cluster_name in sorted(self.cluster_names):
337
+ for ecs_details in self.get_existing_services(cluster_name):
338
+ to_process.append((environment, cluster_name, ecs_details))
339
+ to_process.sort(key=lambda x: x[2]['serviceName'])
340
+
341
+ updated: list[str | None] = []
342
+ if to_process:
343
+ # Sequential in dry-run for readable output.
344
+ threads = 1 if self.dry_run else len(to_process)
345
+ with ThreadPoolExecutor(threads) as pool:
346
+ updated = list(
347
+ pool.map(lambda args: self._update_or_remove(*args), to_process),
348
+ )
349
+
350
+ updated_names = {name for name in updated if name}
351
+
352
+ for service_name, match in sorted(self.desired_services.items()):
353
+ if service_name in updated_names:
354
+ continue
355
+ self.register_task(match.task_definition.as_aws_dict(environment))
356
+ self.create_service(match)
357
+
358
+ def update_application(self, environment: dict) -> None:
359
+ """Reconcile ECS state to match the desired services."""
360
+ if self.dry_run:
361
+ echo('Running in dry run mode')
362
+
363
+ self.update_all_services(environment)
364
+ self.delete_inactive_ecs_task_definitions()