CodeCommit
** CodeCommit은 2024년 7월 25일을 기준으로 서비스가 종료되었다.
기존에 CodeCommit을 사용하던 사람들만 저장소가 보관된 상태이고, GitHub 등으로 마이그레이션 해야 한다.
How to migrate your AWS CodeCommit repository to another Git provider | Amazon Web Services
After careful consideration, we have made the decision to close new customer access to AWS CodeCommit, effective July 25, 2024. AWS CodeCommit existing customers can continue to use the service as normal. AWS continues to invest in security, availability,
aws.amazon.com
VPC를 내가 만든 VPC로 설정하고, 나머지는 다 디폴트값으로 설정한 뒤, 완료한다.
인스턴스가 생성되어 있다.
IAM에 접근권한을 준다.
새 파일 - New File 해서 python 파일 만든다.
새로운 파이썬 파일 만든뒤 간단한 연산을 하도록 코드를 짜고, run 해본다.
파이썬 AWS SDK (Boto3) 활용 S3 다루기
curl -O https://bootstrap.pypa.io/get-pip.py
python get-pip.py
python -m pip --version
rm get-pip.py
python -m pip install boto3
python -m pip show boto3
파일을 다운로드 받는다.
파이썬을 설치하면 pip가 설치된다.
s3.py 파일을 만든다.
import sys
import boto3
from botocore.exceptions import ClientError
def get_s3(region=None):
"""
Get a Boto 3 Amazon S3 resource with a specific AWS Region or with your
default AWS Region.
"""
return boto3.resource('s3', region_name=region) if region else boto3.resource('s3')
def list_my_buckets(s3):
print('Buckets:\n\t', *[b.name for b in s3.buckets.all()], sep="\n\t")
def create_and_delete_my_bucket(bucket_name, region, keep_bucket):
s3 = get_s3(region)
list_my_buckets(s3)
try:
print('\nCreating new bucket:', bucket_name)
bucket = s3.create_bucket(
Bucket=bucket_name,
CreateBucketConfiguration={
'LocationConstraint': region
}
)
except ClientError as e:
print(e)
sys.exit('Exiting the script because bucket creation failed.')
bucket.wait_until_exists()
list_my_buckets(s3)
if not keep_bucket:
print('\nDeleting bucket:', bucket.name)
bucket.delete()
bucket.wait_until_not_exists()
list_my_buckets(s3)
else:
print('\nKeeping bucket:', bucket.name)
def main():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('bucket_name', help='The name of the bucket to create.')
parser.add_argument('region', help='The region in which to create your bucket.')
parser.add_argument('--keep_bucket', help='Keeps the created bucket. When not '
'specified, the bucket is deleted '
'at the end of the demo.',
action='store_true')
args = parser.parse_args()
create_and_delete_my_bucket(args.bucket_name, args.region, args.keep_bucket)
if __name__ == '__main__':
main()
소스코드를 만들고-지우고 반복하게 된다.
Run - Run Configuration - New Run Configuration
위 Command에 이 옵션을 넣으면 코드를 삭제하지 않게 된다.
쓴 후 엔터하면
S3에 생성된다.
코드커밋
IAM에서 코드커밋을 만들 사용자를 만들 수 있는데, 나는 기존에 있던 Group에 policy를 추가했다.
fullaccess를 추가한다.
그룹 사용자 중 하나에 들어가서, Security credentials - SSH keys for AWS CodeCommit 에서 자격증명 생성한다.
Codecommit으로 간다. - Create Repository
만든다.
Clone HTTPS를 클릭한 뒤, 다시 Cloud9으로 간다.
aws, git 설치가 되어 있다.
repo를 clone 할 수 있다.
CodeCommit으로 github에 있는 저장소 클론하기.
HTTPS를 카피한다.
github repo에 있는 내용이 git-migration 폴더로 복사된다.
push 한다.
잘 migration 되었다.
CodeBuild용 repo를 새로 만든다.
vue와 vue-cli를 설치한다.
clone 한다.
webpack을 통해서 소스코드를 다운로드받고 그것을 codebuild-repo에 올릴 것이다.
git add .
git commit -m "uploading new file"
git push origin master
푸쉬한 후, CodeCommit의 CodeBuild로 가본다.
이 산출물들을 S3로 보내 보자. -> 정적 웹사이트 기능
아까 전에 만들었던 S3.도메인 으로 들어간다.
맨 밑에 Static website hosting - Edit 클릭
Enable한 후 index.html 입력한다.
Permission 클릭해 보면 public Access Block이 꺼져 있다.
이는 초반에 python파일에서 퍼블릭 엑세스에 대한 허용을 했기 때문이다.
하단의 Bucket policy - Edit 클릭
Policy generator 클릭
Action - GetObject
ARN에 내 도메인의 arn을 입력하고 Add Statements 클릭한다.
generate policy 클릭하면 이런 JSON 파일이 생성된다.
붙여 넣는다.
Resources는 도메인 바로 다음에 /*를 붙여야 한다.
Build projects 클릭한다.
그리고 create build project 를 클릭한다.
새로운 파일에서 yml파일을 만든다.
커밋한다.
build 클릭한다.
완료되었다.
CodeBuild
CodeDeploy를 선택한다.
방금 만든 role에서 - [Trust relationships] 클릭
-[Edit trust policy] 클릭
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": [
"codedeploy.us-east-2.amazonaws.com",
"codedeploy.us-east-1.amazonaws.com",
"codedeploy.us-west-1.amazonaws.com",
"codedeploy.us-west-2.amazonaws.com",
"codedeploy.eu-west-3.amazonaws.com",
"codedeploy.ca-central-1.amazonaws.com",
"codedeploy.eu-west-1.amazonaws.com",
"codedeploy.eu-west-2.amazonaws.com",
"codedeploy.eu-central-1.amazonaws.com",
"codedeploy.ap-east-1.amazonaws.com",
"codedeploy.ap-northeast-1.amazonaws.com",
"codedeploy.ap-northeast-2.amazonaws.com",
"codedeploy.ap-southeast-1.amazonaws.com",
"codedeploy.ap-southeast-2.amazonaws.com",
"codedeploy.ap-south-1.amazonaws.com",
"codedeploy.sa-east-1.amazonaws.com"
]
},
"Action": "sts:AssumeRole"
}
]
}
기존 데이터를 지우고 위 코드로 교체한다.
policy를 새로 만든다.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:Get*",
"s3:List*"
],
"Resource": [
"arn:aws:s3:::replace-with-your-s3-bucket-name/*",
"arn:aws:s3:::aws-codedeploy-us-east-2/*",
"arn:aws:s3:::aws-codedeploy-us-east-1/*",
"arn:aws:s3:::aws-codedeploy-us-west-1/*",
"arn:aws:s3:::aws-codedeploy-us-west-2/*",
"arn:aws:s3:::aws-codedeploy-ca-central-1/*",
"arn:aws:s3:::aws-codedeploy-eu-west-1/*",
"arn:aws:s3:::aws-codedeploy-eu-west-2/*",
"arn:aws:s3:::aws-codedeploy-eu-west-3/*",
"arn:aws:s3:::aws-codedeploy-eu-central-1/*",
"arn:aws:s3:::aws-codedeploy-ap-east-1/*",
"arn:aws:s3:::aws-codedeploy-ap-northeast-1/*",
"arn:aws:s3:::aws-codedeploy-ap-northeast-2/*",
"arn:aws:s3:::aws-codedeploy-ap-southeast-1/*",
"arn:aws:s3:::aws-codedeploy-ap-southeast-2/*",
"arn:aws:s3:::aws-codedeploy-ap-south-1/*",
"arn:aws:s3:::aws-codedeploy-sa-east-1/*"
]
}
]
}
위 json을 붙여넣는다.
역할을 새로 만든다.
이 역할에 아까 만든 정책을 집어 넣을 것이다.
2개의 퍼미션을 추가한다.
ASG를 이용하여 배포하기
시작 구성 -
ami-01711d925a1e4cc3a
#!/bin/bash
yum update -y
yum install -y ruby
curl -O https://aws-codedeploy-ap-northeast-2.s3.amazonaws.com/latest/install
chmod +x ./install
sudo ./install auto
시작구성을 생성한다.
ASG를 만든다.
시작 구성으로 전환 후, 아까 만든 시작 구성을 선택한다.
타겟 그룹을 만든다.
cloud9에서 새 폴더 > index.html 만든다.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sample Deployment</title>
<style>
body {
color: #ffffff;
background-color: #0188cc;
font-family: Arial, sans-serif;
font-size: 14px;
}
h1 {
font-size: 500%;
font-weight: normal;
margin-bottom: 0;
}
h2 {
font-size: 200%;
font-weight: normal;
margin-bottom: 0;
}
</style>
</head>
<body>
<div align="center">
<h1>Congratulations</h1>
<h2>This application was deployed using AWS CodeDeploy.</h2>
<p>For next steps, read the <a href="http://aws.amazon.com/documentation/codedeploy">AWS CodeDeploy Documentation</a>.</p>
</div>
</body>
</html>
GUI에서 파일을 만들게 되면 인코딩의 문제 때문에 오류가 발생하게 된다. 터미널에서 파일을 만든다.
mkdir scripts
cd scripts
vi install_dependencies
#!/bin/bash
yum install -y httpd
vi start_server
#!/bin/bash
systemctl start httpd
vi stop_server
#!/bin/bash
isExistApp = `pgrep httpd`
if [[ -n $isExistApp ]]; then
systemctl stop httpd
fi
3개의 파일을 만든다.
세 개의 파일을 압축한다.
이 zip파일을 s3에 보낸다.
CodeDeploy 하기
배포 그룹을 만든다.
deploy후 asg의 링크로 들어가면 파란색사이트가 보인다(안보임..)
appspec.yml
version: 0.0
os: linux
files:
- source: /index.html
destination: /var/www/html/
hooks:
BeforeInstall:
- location: scripts/install_dependencies
timeout: 300
runas: root
- location: scripts/start_server
timeout: 300
runas: root
ApplicationStop:
- location: scripts/stop_server
timeout: 300
runas: root
index.html수정한 후 원래 codedeploy-sample.zip파일 삭제 후 다시 압축한다.
s3에 cp한다.
CodePipeline
deploy의 산출물이 S3로 보내게 되므로 EC2에 S3에 대한 권한이 필요하다.
production server를 만든다
build stage는 skip했다.
prd-server의 public ip로 가면 static 창이 나온다.
git add
git commit