EC2 안에서 인스턴스 ID나 리전을 알아낼 때는 169.254.169.254로 curl을 날리는 게 익숙했다. Amazon Linux 2에서는 그 한 줄이면 됐다. 2023년 3월 15일에 후속 버전으로 Amazon Linux 2023이 나왔고, 여기서는 같은 요청 앞에 토큰을 받는 단계가 하나 더 붙는다.

Amazon Linux 2와 2023의 메타데이터 조회 방법을 나란히 놓고, 덤으로 Amazon Linux 2023에서 MySQL 클라이언트를 깔아 RDS에 붙는 과정까지 정리한다.

Amazon Linux 2에서는 curl 한 줄이었다

/latest/meta-data/를 부르면 조회할 수 있는 항목 목록이 나오고, 그중 하나를 경로에 붙이면 값이 나온다.

curl http://169.254.169.254/latest/meta-data/
> (실행결과)
ami-id
ami-launch-index
ami-manifest-path
block-device-mapping/
events/
hostname
identity-credentials/
instance-action
instance-id
instance-life-cycle
instance-type
local-hostname
local-ipv4
mac
metrics/
network/
placement/
profile
public-hostname
public-ipv4
public-keys/
reservation-id
security-groups
services/


# AMI ID 조회
curl http://169.254.169.254/latest/meta-data/ami-id

# 인스턴스 ID 조회
curl http://169.254.169.254/latest/meta-data/instance-id
> (실행결과)
i-0df8321768b104bcb

# Region 조회
curl http://169.254.169.254/latest/meta-data/placement/region
> (실행결과)
ap-northeast-2

Amazon Linux 2023에서는 토큰을 먼저 받는다

이 방식은 IMDSv1이라고 부른다. AWS 문서에 따르면 Amazon Linux 2023 AMI는 기본값이 IMDSv2 전용이라, 토큰 없이 보낸 요청에는 메타데이터를 내주지 않는다. IMDSv2는 PUT으로 세션 토큰을 먼저 받고, 이후 모든 조회에 그 토큰을 헤더로 붙이는 방식이다.

# 1. 세션 토큰 발급 (유효시간 3600초)
TOKEN=$(curl --request PUT "http://169.254.169.254/latest/api/token" --header "X-aws-ec2-metadata-token-ttl-seconds: 3600")

echo $TOKEN

# 2. 이후 조회마다 토큰을 헤더로 전달
INSTANCE_METADATA=$(curl -s http://169.254.169.254/latest/meta-data/ --header "X-aws-ec2-metadata-token: $TOKEN")

echo $INSTANCE_METADATA

INSTANCE_ID=$(curl -s http://169.254.169.254/latest/meta-data/instance-id --header "X-aws-ec2-metadata-token: $TOKEN")

REGION=$(curl -s http://169.254.169.254/latest/meta-data/placement/region --header "X-aws-ec2-metadata-token: $TOKEN")

토큰 요청은 GET이 아니라 PUT이고, 유효시간은 X-aws-ec2-metadata-token-ttl-seconds 헤더로 정한다. 받은 토큰은 변수에 담아 두고 TTL 안에서 계속 쓴다. 경로(instance-id, placement/region)는 Amazon Linux 2 때와 같아서 기존 스크립트라면 토큰 발급 한 줄과 헤더만 더하면 된다.

MySQL 클라이언트는 mariadb105 패키지로 깐다

Amazon Linux 2023 서버에서 RDS에 붙어 볼 일도 있었다. AWS 공식 문서(DB 인스턴스에 연결)대로 패키지 매니저는 dnf이고, MySQL 클라이언트로는 mariadb105를 설치한다.

# install
sudo dnf install mariadb105

# check
mysql --version

# connect
# (ex. user: master, password: tf-password, endpoint: tf-db.cso8wtmrwb6r.ap-northeast-2.rds.amazonaws.com)
mysql -umaster -ptf-password -htf-db.cso8wtmrwb6r.ap-northeast-2.rds.amazonaws.com

-p 뒤에 비밀번호를 바로 붙이면 쉘 히스토리에 남는다. 예시라서 그대로 적었지만, 실제로는 -p만 주고 프롬프트에서 입력하는 편이 낫다.

접속한 뒤 데이터베이스와 테이블을 확인했다.

MySQL [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| innodb             |
| mysql              |
| performance_schema |
| sys                |
| tf                 |
+--------------------+

MySQL [(none)]> use tf
Database changed

MySQL [tf]> show tables;
Empty set (0.00 sec)

MySQL [tf]> quit
Bye

tf 데이터베이스는 보이지만 테이블은 아직 비어 있다.

결국 Amazon Linux 2023으로 넘어오면서 메타데이터 조회에 토큰 발급 한 단계가 늘었다. MySQL 클라이언트는 패키지 이름이 mariadb105라는 것만 기억.