๋ชฉ์ฐจ
์ ๊ธฐ
CodePipelin ๊ตฌ์ฑ ์,
๋น๋๊ณผ์ ์์ด ECR -> ECS ์ ๋ฐ๋ก ๋ฐฐํฌํ๋ค๋ฉด TaskDefinition ํ์ผ์ ์
๋ฐ์ดํธ ํด์ค์ผ ํ๋ค.
๊ทธ๋ฌ์๊ณ Codebuild๋ฅผ ์ฐ์๋, ํ์ผ ๋ง๋๋๋ฐ ๋ช์ด๋ฉด ๋๋๋๋ฐ, ๋น์ฉ๋ ๋น์ฉ์ด๊ณ codebuild๋ ๋ฌด๊ฒ๋ค ใ (์ด๊ฑฐ ๋๋ฆฌ๋๋ฐ 4๋ถ๊ฑธ๋ฆฐ๋ค..)
lambda๋ก ํ๋ฉด 30์ด๋ฉด ๋๋๋ ์ด๋ ๊ฒ ํด๋ณด๋๊ฒ์ ์ถ์ฒํ๋ค.
===========================================
Source ------> Def-Step ------> ECS (rolling update)
[ECR] [Lambda]
===========================================
import json
import boto3
import zipfile
import tempfile
import os
from subprocess import call
code_pipeline = boto3.client('codepipeline')
s3 = boto3.client('s3')
def lambda_handler(event, context):
job_id = event['CodePipeline.job']['id']
bucketN = event['CodePipeline.job']['data']['inputArtifacts'][0]['location']['s3Location']['bucketName']
objectK = event['CodePipeline.job']['data']['inputArtifacts'][0]['location']['s3Location']['objectKey']
outputN = event['CodePipeline.job']['data']['outputArtifacts'][0]['location']['s3Location']['bucketName']
outputK = event['CodePipeline.job']['data']['outputArtifacts'][0]['location']['s3Location']['objectKey']
tmp_file = tempfile.NamedTemporaryFile()
with tempfile.NamedTemporaryFile() as tmp_file:
s3.download_file(bucketN, objectK, tmp_file.name)
with zipfile.ZipFile(tmp_file.name, 'r') as zip:
json_data = zip.read('imageDetail.json')
obj = json.loads(json_data)
#print(obj)
image_uri = obj['ImageURI'].split('@')[0]
ImageDigest = obj['ImageDigest']
repo_name = obj['RepositoryName']
image = f"{image_uri}@{ImageDigest}"
#print(image)
definition = [{
'name': repo_name,
'imageUri': image
}]
#print(definition)
with open('/tmp/imagedefinitions.json', 'w') as outfile:
json.dump(definition, outfile)
# taskdef ํ์ผ ์ค๋น
for i in ['TaskDef-1', 'TaskDef-2', 'TaskDef-4']:
file_name = '/tmp/imagedefinitions-'+i+'.json'
file_data = [{
'name': "alpha-"+i,
'imageUri': image
}]
with open(file_name, 'w') as outfile:
json.dump(file_data, outfile)
# ์์ถ
file_path = '/tmp/'
zip_file = zipfile.ZipFile('/tmp/imagedefinitions.zip', mode='w')
os.chdir("/tmp/")
for file in os.listdir(file_path):
if file.endswith('.json'):
zip_file.write(file)
zip_file.close()
# jsonํ์ผ ์ ์๊ฒผ๋์ง ํ์ธ
path_dir = '/tmp'
file_list = os.listdir(path_dir)
print(file_list)
# s3์ ์ ์ถ๋ ฅ ์ํฐํํธ๋ก ์
๋ก๋
response = s3.upload_file('/tmp/imagedefinitions.zip', outputN, outputK)
#์ฝ๋ํ์ดํ๋ผ์ธ์ success ์ ๋ฌ
code_pipeline.put_job_success_result(jobId=job_id)
#/tmp๊ฒฝ๋ก clear
call('rm -rf /tmp/*', shell=True)
return True
728x90