Chúng ta cần cài đặt CodeDeploy Agent trên EC2 instance để AWS CodeDeploy có thể giao tiếp với nó và triển khai ứng dụng của bạn. Có hai cách phổ biến để cấu hình CodeDeploy Agent: kết nối thủ công vào instance hoặc sử dụng User Data trong quá trình khởi tạo.
Cách 1: Cài đặt thủ công

Khi bạn kích hoạt quá trình triển khai (deployment), mã nguồn của bạn thường được lưu trữ dưới dạng tệp nén trong Amazon S3 bucket. Các quyền s3:Get* và s3:List* trong IAM role này cho phép CodeDeploy Agent đang chạy bên trong EC2 instance của bạn kết nối đến S3, tìm mã nguồn và tải xuống instance để tiến hành cài đặt.
Mẹo: Nếu không có IAM role này, quá trình triển khai của bạn sẽ thất bại ở giai đoạn DownloadBundle với lỗi “Access Denied” (Từ chối truy cập) vì EC2 instance không có quyền mở S3 bucket chứa mã nguồn của bạn.

my-server).

Lưu ý quan trọng: Đảm bảo bạn sao chép toàn bộ khối code bên dưới và dán vào terminal. Hãy nhấn Enter để chắc chắn rằng lệnh cuối cùng được thực thi.
# 1. Obtain Token to access Metadata (IMDSv2)
TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600") &&
# 2. Automatically obtain Region from internal IP
REGION=$(curl -H "X-aws-ec2-metadata-token: $TOKEN" -s http://169.254.169.254/latest/meta-data/placement/availability-zone | sed 's/[a-z]$//') &&
# 3. Update system and install necessary packages
sudo dnf update -y &&
sudo dnf install -y ruby wget python3-pip &&
# 4. Download and install CodeDeploy Agent
cd /home/ec2-user &&
wget https://aws-codedeploy-$REGION.s3.amazonaws.com/latest/install &&
sudo chmod +x ./install &&
sudo ./install auto &&
# 5. Cleanup and verify service status
rm -f ./install &&
sudo systemctl enable codedeploy-agent &&
sudo systemctl start codedeploy-agent &&
sudo systemctl status codedeploy-agent

Cách 2: Cài đặt tự động qua User Data
Bạn chỉ cần thực hiện Cách 1 HOẶC Cách 2. Nếu bạn đã hoàn thành Cách 1 ở trên, bạn có thể bỏ qua phần này. Phương pháp này chỉ ra cách bạn có thể tự động hóa việc cài đặt ngay từ lúc khởi tạo EC2 instance.


#!/bin/bash
# 1. Obtain Token to access Metadata (IMDSv2)
TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
# 2. Automatically obtain Region from internal IP
REGION=$(curl -H "X-aws-ec2-metadata-token: $TOKEN" -s http://169.254.169.254/latest/meta-data/placement/availability-zone | sed 's/[a-z]$//')
# 3. Update system and install necessary packages
sudo dnf update -y
sudo dnf install -y ruby wget python3-pip
# 4. Download and install CodeDeploy Agent
cd /home/ec2-user
wget "https://aws-codedeploy-$REGION.s3.amazonaws.com/latest/install"
chmod +x ./install
sudo ./install auto
# 5. Cleanup and verify service status
rm -f ./install
sudo systemctl enable codedeploy-agent
sudo systemctl start codedeploy-agent
sudo systemctl status codedeploy-agent
