Skip to content

Commit 9da575f

Browse files
committed
Upading workflow to upload assets
1 parent 967ab18 commit 9da575f

File tree

5 files changed

+1585
-54
lines changed

5 files changed

+1585
-54
lines changed

.github/workflows/publish-template.yml

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ jobs:
2121
with:
2222
python-version: "3.8" # Version range or exact version of a Python version to use, using SemVer's version range syntax
2323
architecture: "x64" # optional x64 or x86. Defaults to x64 if not specified
24-
cache: python
2524

2625
- name: Setup Node
2726
uses: actions/setup-node@v2
@@ -31,8 +30,9 @@ jobs:
3130
cache: npm
3231

3332
- name: Install Requirements
34-
run: npm install -g aws-cdk # Install cdk
35-
run: pip install --requirement requirements.txt
33+
run: |
34+
npm install -g aws-cdk # Install cdk
35+
pip install --requirement requirements.txt
3636
3737
- name: Configure AWS credentials
3838
id: creds
@@ -44,22 +44,24 @@ jobs:
4444
role-duration-seconds: 1200
4545

4646
- name: Synth Template
47-
id: data_prep
4847
env:
4948
BUCKET_NAME: ${{ secrets.BUCKET_NAME }}
5049
BUCKET_PREFIX: ${{ secrets.BUCKET_PREFIX }}
51-
run: rm -Rf cdk.out/
5250
run: cdk synth drift-service-catalog --path-metadata false -c drift:ArtifactBucket=$BUCKET_NAME -c drift:ArtifactBucketPrefix=$BUCKET_PREFIX > drift-service-catalog.yml
5351

54-
- name: Publish Assets
55-
run: # cd cdk.out; for d in asset.*/ ; do base=$(basename "$d") ; cd $base ; zip -r $base.zip * ; mv "${base}.zip" .. ; cd .. ; done; cd ..
56-
run: # aws s3 sync cdk.out/*.zip s3://amazon-sagemaker-safe-deployment-pipeline/drift/ --acl public-read
52+
- name: Publish Assets to S3
53+
env:
54+
BUCKET_NAME: ${{ secrets.BUCKET_NAME }}
55+
BUCKET_PREFIX: ${{ secrets.BUCKET_PREFIX }}
56+
run: python infra/upload_assets.py
57+
58+
- name: Upload Template
59+
uses: actions/upload-artifact@v2
60+
with:
61+
name: cdk-template
62+
path: cdk.out/*.template.json
5763

5864
- name: Print Template
5965
run: cat drift-service-catalog.yml
6066

61-
- name: Upload Template
62-
uses: actions/upload-artifact@v2
63-
with:
64-
name: drift-service-catalog
65-
path: drift-service-catalog.yml
67+

drift-service-catalog.yml

Lines changed: 84 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,8 @@ Resources:
4545
ProvisioningArtifactParameters:
4646
- DisableTemplateValidation: false
4747
Info:
48-
LoadTemplateFromURL: https://amazon-sagemaker-safe-deployment-pipeline.s3.amazonaws.com/drift-pipeline/drift-pipeline-clean.template.json
48+
LoadTemplateFromURL:
49+
Fn::Sub: https://s3.${AWS::Region}.${AWS::URLSuffix}/amazon-sagemaker-safe-deployment-pipeline/drift/995c5412ab943fce18ceaf3ebe66d305f8ab054a4a3f643768722c3fead226a0.json
4950
Name:
5051
Ref: ProductVersion
5152
Description: Amazon SageMaker Project for a build and deployment pipeline that triggers on drift or schedule
@@ -136,15 +137,12 @@ Resources:
136137
- ""
137138
- - "arn:"
138139
- Ref: AWS::Partition
139-
- ":s3:::"
140-
- "amazon-sagemaker-safe-deployment-pipeline"
140+
- :s3:::amazon-sagemaker-safe-deployment-pipeline
141141
- Fn::Join:
142142
- ""
143143
- - "arn:"
144144
- Ref: AWS::Partition
145-
- ":s3:::"
146-
- "amazon-sagemaker-safe-deployment-pipeline"
147-
- /*
145+
- :s3:::amazon-sagemaker-safe-deployment-pipeline/*
148146
- Action:
149147
- ssm:DescribeParameters
150148
- ssm:GetParameters
@@ -196,23 +194,6 @@ Resources:
196194
- Ref: AWS::AccountId
197195
- :parameter
198196
- Ref: CodeCommitDeployKey5E5A6E47
199-
- Action:
200-
- ssm:DescribeParameters
201-
- ssm:GetParameters
202-
- ssm:GetParameter
203-
- ssm:GetParameterHistory
204-
Effect: Allow
205-
Resource:
206-
Fn::Join:
207-
- ""
208-
- - "arn:"
209-
- Ref: AWS::Partition
210-
- ":ssm:"
211-
- Ref: AWS::Region
212-
- ":"
213-
- Ref: AWS::AccountId
214-
- :parameter
215-
- Ref: LambdaKey984A39D9
216197
Version: "2012-10-17"
217198
PolicyName: LaunchRolePolicyA9E2E5B1
218199
Roles:
@@ -256,23 +237,95 @@ Resources:
256237
Type: AWS::SSM::Parameter
257238
Properties:
258239
Type: String
259-
Value: "amazon-sagemaker-safe-deployment-pipeline"
240+
Value: amazon-sagemaker-safe-deployment-pipeline
260241
Name: /drift-pipeline/CodeCommitSeedBucket
261242
CodeCommitBuildKey09FC7134:
262243
Type: AWS::SSM::Parameter
263244
Properties:
264245
Type: String
265-
Value: "drift-pipeline/build.zip"
246+
Value: drift/be4dfed42e0626f2201f8ce29518fb4e31fb640eca88a156fedc5b8d568c6c1c.zip
266247
Name: /drift-pipeline/CodeCommitBuildKey
267248
CodeCommitDeployKey5E5A6E47:
268249
Type: AWS::SSM::Parameter
269250
Properties:
270251
Type: String
271-
Value: "drift-pipeline/deploy.zip"
252+
Value: drift/381262eab49cfaf013c17daf9216232c25761d7f0ec33583681b6b699adf4ecf.zip
272253
Name: /drift-pipeline/CodeCommitDeployKey
273-
LambdaKey984A39D9:
274-
Type: AWS::SSM::Parameter
254+
CDKMetadata:
255+
Type: AWS::CDK::Metadata
275256
Properties:
276-
Type: String
277-
Value: "drift-pipeline/lambda.zip"
278-
Name: /drift-pipeline/LambdaKey
257+
Analytics: v2:deflate64:H4sIAAAAAAAAE3WQwU7EMAxEv2XvaXar5cARthKnPVTlCyzX7Zq2MUoc0Krqv5O0SBQJTvEkk3kal7YsH+zp8ASfocB2OM4onuz8qoCDqTpXg4eJlLx5DoE03ffselOJC+ojqmkoSPRI2byfk6NlZXGLydlzIP/BSAgKo/R2rsVrJyPLSvlT1F7ahEhgQYacZapRYvsiflrlt2HF/fewS2OH/A7jr7zOXSE6vDUy0lYK2OliwrmAXDjYtXfS9hJxIL1AIMMw5QYj431j5Cl9ClNeXQL1P3vbL3FZFlPf9SbueLaPtjwd3gJz4aNTnsg22/kFLKE7OZUBAAA=
258+
Condition: CDKMetadataAvailable
259+
Conditions:
260+
CDKMetadataAvailable:
261+
Fn::Or:
262+
- Fn::Or:
263+
- Fn::Equals:
264+
- Ref: AWS::Region
265+
- af-south-1
266+
- Fn::Equals:
267+
- Ref: AWS::Region
268+
- ap-east-1
269+
- Fn::Equals:
270+
- Ref: AWS::Region
271+
- ap-northeast-1
272+
- Fn::Equals:
273+
- Ref: AWS::Region
274+
- ap-northeast-2
275+
- Fn::Equals:
276+
- Ref: AWS::Region
277+
- ap-south-1
278+
- Fn::Equals:
279+
- Ref: AWS::Region
280+
- ap-southeast-1
281+
- Fn::Equals:
282+
- Ref: AWS::Region
283+
- ap-southeast-2
284+
- Fn::Equals:
285+
- Ref: AWS::Region
286+
- ca-central-1
287+
- Fn::Equals:
288+
- Ref: AWS::Region
289+
- cn-north-1
290+
- Fn::Equals:
291+
- Ref: AWS::Region
292+
- cn-northwest-1
293+
- Fn::Or:
294+
- Fn::Equals:
295+
- Ref: AWS::Region
296+
- eu-central-1
297+
- Fn::Equals:
298+
- Ref: AWS::Region
299+
- eu-north-1
300+
- Fn::Equals:
301+
- Ref: AWS::Region
302+
- eu-south-1
303+
- Fn::Equals:
304+
- Ref: AWS::Region
305+
- eu-west-1
306+
- Fn::Equals:
307+
- Ref: AWS::Region
308+
- eu-west-2
309+
- Fn::Equals:
310+
- Ref: AWS::Region
311+
- eu-west-3
312+
- Fn::Equals:
313+
- Ref: AWS::Region
314+
- me-south-1
315+
- Fn::Equals:
316+
- Ref: AWS::Region
317+
- sa-east-1
318+
- Fn::Equals:
319+
- Ref: AWS::Region
320+
- us-east-1
321+
- Fn::Equals:
322+
- Ref: AWS::Region
323+
- us-east-2
324+
- Fn::Or:
325+
- Fn::Equals:
326+
- Ref: AWS::Region
327+
- us-west-1
328+
- Fn::Equals:
329+
- Ref: AWS::Region
330+
- us-west-2
331+

infra/upload_assets.py

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
import boto3
2+
import glob
3+
import json
4+
import logging
5+
import os
6+
import zipfile
7+
8+
9+
# Get environment variables
10+
LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO").upper()
11+
BUCKET_NAME = os.getenv("BUCKET_NAME")
12+
BUCKET_PREFIX = os.getenv("BUCKET_PREFIX")
13+
BUCKET_ACL = os.getenv("BUCKET_ACL", "public-read")
14+
GITHUB_REF = os.getenv("GITHUB_REF")
15+
GITHUB_SHA = os.getenv("GITHUB_SHA")
16+
17+
# Configure logging
18+
logger = logging.getLogger(__name__)
19+
logger.setLevel(LOG_LEVEL)
20+
21+
# s3 client
22+
s3 = boto3.client("s3")
23+
24+
25+
def upload_file(
26+
file_path: str, bucket_name: str, object_key: str, content_type: str
27+
) -> None:
28+
"""Upload file to s3 setting extra ags for ContentType, ACL, and Metadata for git hash
29+
30+
Args:
31+
file_path (str): Path to local file
32+
bucket_name (str): Name of bucket
33+
object_key (str): Name of object key
34+
content_type (str): Content type
35+
"""
36+
logger.info(f"Uploading asset s3://{bucket_name}/{object_key}")
37+
s3.upload_file(
38+
file_path,
39+
bucket_name,
40+
object_key,
41+
ExtraArgs={
42+
"ContentType": content_type,
43+
"ACL": BUCKET_ACL,
44+
"Metadata": {"git_ref": GITHUB_REF, "git_sha": GITHUB_SHA},
45+
},
46+
)
47+
48+
49+
def zip_filter(filename: str) -> bool:
50+
"""Returns true if file and not in ignore list
51+
52+
Args:
53+
filename (str): file name
54+
55+
Returns:
56+
bool: True if should filter
57+
"""
58+
return os.path.isfile(filename) and filename not in [".DS_Store"]
59+
60+
61+
def make_zipfile(source_dir: str) -> str:
62+
"""Makes a zip file for the sourc directory
63+
64+
Args:
65+
source_dir (str): The source directory to zip
66+
67+
Returns:
68+
str: Returns the zip filename created
69+
"""
70+
output_filename = source_dir + ".zip"
71+
relroot = os.path.abspath(os.path.join(source_dir, os.pardir))
72+
with zipfile.ZipFile(output_filename, "w", zipfile.ZIP_DEFLATED) as zip:
73+
for root, dirs, files in os.walk(source_dir):
74+
# add directory (needed for empty dirs)
75+
zip.write(root, os.path.relpath(root, relroot))
76+
for file in files:
77+
filename = os.path.join(root, file)
78+
if zip_filter(filename):
79+
arcname = os.path.join(os.path.relpath(root, relroot), file)
80+
# print(root, arcname)
81+
zip.write(filename, arcname)
82+
return output_filename
83+
84+
85+
def upload_assets(cdk_dir: str = "cdk.out") -> None:
86+
"""Parses the asset files in cdk directory and uploads resources to S3
87+
88+
Args:
89+
cdk_dir (str): The cdk directory
90+
"""
91+
for asset_path in glob.glob(f"{cdk_dir}/*.assets.json"):
92+
logger.debug(f"Processing asset: {asset_path}")
93+
with open(asset_path, "r") as f:
94+
asset = json.load(f)
95+
for key in asset["files"]:
96+
meta = asset["files"][key]
97+
# Get source info
98+
src = meta["source"]
99+
file_path = os.path.join(cdk_dir, src["path"])
100+
content_type = "application/json"
101+
if src["packaging"] == "zip":
102+
logger.info(f"Packaging zip: {file_path}")
103+
file_path = make_zipfile(file_path)
104+
content_type = "application/zip"
105+
# Get the destination
106+
dest = meta["destinations"]["current_account-current_region"]
107+
bucket_name = dest["bucketName"]
108+
object_key = dest["objectKey"]
109+
# Upload file to s3
110+
upload_file(file_path, bucket_name, object_key, content_type)
111+
112+
113+
if __name__ == "__main__":
114+
ch = logging.StreamHandler()
115+
ch.setFormatter(logging.Formatter("%(levelname)s - %(message)s"))
116+
logger.addHandler(ch)
117+
logger.info(f"Uploading assets for git ref: {GITHUB_REF} sha: {GITHUB_SHA}")
118+
# Upload YAML template
119+
template_name = "drift-service-catalog.yml"
120+
object_key = f"{BUCKET_PREFIX}{template_name}"
121+
upload_file(template_name, BUCKET_NAME, object_key, "application/x-yaml")
122+
# Upload assets
123+
upload_assets("cdk.out")

0 commit comments

Comments
 (0)