Repository navigation
Expand file tree
/
Copy pathecr_wrapper.py
More file actions
246 lines (208 loc) · 8.9 KB
/
Copy pathecr_wrapper.py
File metadata and controls
246 lines (208 loc) · 8.9 KB
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
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) with Amazon Elastic Container Registry (Amazon ECR) API to perform
actions.
"""
import logging
import boto3
from boto3 import client
from botocore.exceptions import ClientError
logger = logging.getLogger(__name__)
# snippet-start:[python.example_code.ecr.ECRWrapper.class]
# snippet-start:[python.example_code.ecr.ECRWrapper.decl]
class ECRWrapper:
def __init__(self, ecr_client: client):
self.ecr_client = ecr_client
@classmethod
def from_client(cls) -> "ECRWrapper":
"""
Creates a ECRWrapper instance with a default Amazon ECR client.
:return: An instance of ECRWrapper initialized with the default Amazon ECR client.
"""
ecr_client = boto3.client("ecr")
return cls(ecr_client)
# snippet-end:[python.example_code.ecr.ECRWrapper.decl]
# snippet-start:[python.example_code.ecr.ECRWrapper.CreateRepository]
def create_repository(self, repository_name: str) -> dict[str, any]:
"""
Creates an ECR repository.
:param repository_name: The name of the repository to create.
:return: A dictionary of the created repository.
"""
try:
response = self.ecr_client.create_repository(repositoryName=repository_name)
return response["repository"]
except ClientError as err:
if err.response["Error"]["Code"] == "RepositoryAlreadyExistsException":
print(f"Repository {repository_name} already exists.")
response = self.ecr_client.describe_repositories(
repositoryNames=[repository_name]
)
return self.describe_repositories([repository_name])[0]
else:
logger.error(
"Error creating repository %s. Here's why %s",
repository_name,
err.response["Error"]["Message"],
)
raise
# snippet-end:[python.example_code.ecr.ECRWrapper.CreateRepository]
# snippet-start:[python.example_code.ecr.ECRWrapper.DeleteRepository]
def delete_repository(self, repository_name: str):
"""
Deletes an ECR repository.
:param repository_name: The name of the repository to delete.
"""
try:
self.ecr_client.delete_repository(
repositoryName=repository_name, force=True
)
print(f"Deleted repository {repository_name}.")
except ClientError as err:
logger.error(
"Couldn't delete repository %s.. Here's why %s",
repository_name,
err.response["Error"]["Message"],
)
raise
# snippet-end:[python.example_code.ecr.ECRWrapper.DeleteRepository]
# snippet-start:[python.example_code.ecr.ECRWrapper.SetRepositoryPolicy]
def set_repository_policy(self, repository_name: str, policy_text: str):
"""
Sets the policy for an ECR repository.
:param repository_name: The name of the repository to set the policy for.
:param policy_text: The policy text to set.
"""
try:
self.ecr_client.set_repository_policy(
repositoryName=repository_name, policyText=policy_text
)
print(f"Set repository policy for repository {repository_name}.")
except ClientError as err:
if err.response["Error"]["Code"] == "RepositoryPolicyNotFoundException":
logger.error("Repository does not exist. %s.", repository_name)
raise
else:
logger.error(
"Couldn't set repository policy for repository %s. Here's why %s",
repository_name,
err.response["Error"]["Message"],
)
raise
# snippet-end:[python.example_code.ecr.ECRWrapper.SetRepositoryPolicy]
# snippet-start:[python.example_code.ecr.ECRWrapper.GetRepositoryPolicy]
def get_repository_policy(self, repository_name: str) -> str:
"""
Gets the policy for an ECR repository.
:param repository_name: The name of the repository to get the policy for.
:return: The policy text.
"""
try:
response = self.ecr_client.get_repository_policy(
repositoryName=repository_name
)
return response["policyText"]
except ClientError as err:
if err.response["Error"]["Code"] == "RepositoryPolicyNotFoundException":
logger.error("Repository does not exist. %s.", repository_name)
raise
else:
logger.error(
"Couldn't get repository policy for repository %s. Here's why %s",
repository_name,
err.response["Error"]["Message"],
)
raise
# snippet-end:[python.example_code.ecr.ECRWrapper.GetRepositoryPolicy]
# snippet-start:[python.example_code.ecr.ECRWrapper.GetAuthorizationToken]
def get_authorization_token(self) -> str:
"""
Gets an authorization token for an ECR repository.
:return: The authorization token.
"""
try:
response = self.ecr_client.get_authorization_token()
return response["authorizationData"][0]["authorizationToken"]
except ClientError as err:
logger.error(
"Couldn't get authorization token. Here's why %s",
err.response["Error"]["Message"],
)
raise
# snippet-end:[python.example_code.ecr.ECRWrapper.GetAuthorizationToken]
# snippet-start:[python.example_code.ecr.ECRWrapper.DescribeRepositories]
def describe_repositories(self, repository_names: list[str]) -> list[dict]:
"""
Describes ECR repositories.
:param repository_names: The names of the repositories to describe.
:return: The list of repository descriptions.
"""
try:
response = self.ecr_client.describe_repositories(
repositoryNames=repository_names
)
return response["repositories"]
except ClientError as err:
logger.error(
"Couldn't describe repositories. Here's why %s",
err.response["Error"]["Message"],
)
raise
# snippet-end:[python.example_code.ecr.ECRWrapper.DescribeRepositories]
# snippet-start:[python.example_code.ecr.ECRWrapper.PutLifeCyclePolicy]
def put_lifecycle_policy(self, repository_name: str, lifecycle_policy_text: str):
"""
Puts a lifecycle policy for an ECR repository.
:param repository_name: The name of the repository to put the lifecycle policy for.
:param lifecycle_policy_text: The lifecycle policy text to put.
"""
try:
self.ecr_client.put_lifecycle_policy(
repositoryName=repository_name,
lifecyclePolicyText=lifecycle_policy_text,
)
print(f"Put lifecycle policy for repository {repository_name}.")
except ClientError as err:
logger.error(
"Couldn't put lifecycle policy for repository %s. Here's why %s",
repository_name,
err.response["Error"]["Message"],
)
raise
# snippet-end:[python.example_code.ecr.ECRWrapper.PutLifeCyclePolicy]
# snippet-start:[python.example_code.ecr.ECRWrapper.DescribeImages]
def describe_images(
self, repository_name: str, image_ids: list[str] = None
) -> list[dict]:
"""
Describes ECR images.
:param repository_name: The name of the repository to describe images for.
:param image_ids: The optional IDs of images to describe.
:return: The list of image descriptions.
"""
try:
params = {
"repositoryName": repository_name,
}
if image_ids is not None:
params["imageIds"] = [{"imageTag": tag} for tag in image_ids]
paginator = self.ecr_client.get_paginator("describe_images")
image_descriptions = []
for page in paginator.paginate(**params):
image_descriptions.extend(page["imageDetails"])
return image_descriptions
except ClientError as err:
logger.error(
"Couldn't describe images. Here's why %s",
err.response["Error"]["Message"],
)
raise
# snippet-end:[python.example_code.ecr.ECRWrapper.DescribeImages]
# snippet-end:[python.example_code.ecr.ECRWrapper.class]
if __name__ == "__main__":
try:
ecr_wrapper = ECRWrapper.from_client()
except Exception:
logging.exception("Something went wrong creating a client!")