run-ec2.sh
#!/bin/bash
SUBNETS=$(aws ec2 describe-subnets --filter Name=tag:Name,Values=*private* --query 'Subnets[].SubnetId' --output text)
SUBNET_IDS=($SUBNETS)
SELECTED_SUBNET=${SUBNET_IDS[$RANDOM % ${#SUBNET_IDS[@]}]}
AVAILABILITYZONE=$(aws ec2 describe-subnets --filter Name=subnet-id,Values=$SELECTED_SUBNET --query 'Subnets[].AvailabilityZone' --output text)
aws ec2 run-instances \
--image-id ami-0ff56409a6e8ea2a0 \
--key-name 0310 \
--security-group-ids sg-093a3b40a466235e2 \
--instance-type t3.small \
--subnet-id $SELECTED_SUBNET \
--tag-specifications 'ResourceType=instance,Tags=[{Key=deploy:group,Value=dev-api},{Key=Name,Value='$1'}]' \
--iam-instance-profile Arn=arn:aws:iam::<your-account>:instance-profile/EC2-codedeploy-role \
--user-data file://install_codedeploy_agent.sh &&\
echo "생성된 EC2의 가용영역은: '$AVAILABILITYZONE'입니다"
install_codedeploy_agent.sh (run-ec2.sh와 같은 경로에 파일 생성)
#!/bin/bash
sudo yum update -y
sudo yum install ruby -y
sudo yum install wget -y
wget https://aws-codedeploy-ap-northeast-2.s3.ap-northeast-2.amazonaws.com/latest/install
chmod +x ./install
./install auto
service codedeploy-agent start
SUBNETS=$(aws ec2 describe-subnets --filter Name=tag:Name,Values=*private* --query 'Subnets[].SubnetId' --output text)
SUBNET_IDS=($SUBNETS)
SELECTED_SUBNET=${SUBNET_IDS[$RANDOM % ${#SUBNET_IDS[@]}]}
AVAILABILITYZONE=$(aws ec2 describe-subnets --filter Name=subnet-id,Values=$SELECTED_SUBNET --query 'Subnets[].AvailabilityZone' --output text)
프라이빗 서브넷(이름에 "private"이 포함되어 있어야함) 중 한 곳을 랜덤하게 선택하고 서브넷과 가용영역을 변수로 선언한다.
aws ec2 run-instances
--image-id ami-0ff56409a6e8ea2a0 #<change to your-ami>\
--key-name 0310 #<change to your-keypair-name>\
--security-group-ids sg-093a3b40a466235e2 #<change to your security-group> \
--instance-type t3.small #<change to your instance-type> \
--subnet-id $SELECTED_SUBNET #<chane to your subnet>\
--tag-specifications 'ResourceType=instance,Tags=[{Key=deploy:group,Value=dev-api},{Key=Name,Value='$@'}]' #<change to your tag> \
--iam-instance-profile Arn=arn:aws:iam::<your-account>:instance-profile/EC2-codedeploy-role #<change to your iam profile> \
--user-data file://install_codedeploy_agent.sh &&\
echo "생성된 EC2의 가용영역은: '$AVAILABILITYZONE'입니다"
ami, keypair, security-group 등 인스턴스 생성에 필요한 값들을 할당하고
인스턴스 태그에 Key=deploy:group, Value=dev-api인 태그를 생성함
이 태그들은 CodeDeploy 배포 그룹 태그에 사용하면 된다.
run-ec2.sh 명령 다음의 인자를 받아 인스턴스 Name 태그로 설정해준다.
사용 예시)
sh run-ec2.sh api-1
인스턴스가 생성된다면 인스턴스가 생성된 가용영역을 알려준다
#!/bin/bash
sudo yum update -y
sudo yum install ruby -y
sudo yum install wget -y
wget https://aws-codedeploy-ap-northeast-2.s3.ap-northeast-2.amazonaws.com/latest/install
chmod +x ./install
./install auto
codedeploy_agent를 설치한다
리전은 ap-northeast-2로 설정되어있으나 us-east-1 등 다른 리전을 사용해도 상관 없다.
작동은 하지만 agent Log 시간이 다르게 표시될 수 있다.
service codedeploy-agent start
codedeploy-agent를 실행시켜준다.