본문으로 건너뛰기

AWS CLI를 사용하여 EC2 인스턴스 구성

AWS Command Line Interface(AWS CLI)를 사용하여 GitLab 설치용 EC2 인스턴스 구성

사전 조건

  • AWS CLI 설치 및 보안 자격 증명 구성이 되어 있어야 한다.

Amazon EC2 키 페어

Amazon EC2 인스턴스를 생성할 때 Amazon EC2에 키 페어를 제공한 다음, 인스턴스에 연결할 때 해당 키 페어를 사용하여 인증해야 한다.

키 페어 생성

키 페어를 생성하려면 create-key-pair 명령과 함께 --query 옵션 및 --output text 옵션을 사용하여 프라이빗 키를 직접 파일에 파이프한다.

aws ec2 create-key-pair --key-name gitlab-poc --query 'KeyMaterial' --output text > gitlab-poc.pem

결과로 나온 gitlab-poc.pem 파일은 아래와 유사하다.

-----BEGIN RSA PRIVATE KEY-----
EXAMPLEKEYKCAQEAy7WZhaDsrA1W3mRlQtvhwyORRX8gnxgDAfRt/gx42kWXsT4rXE/b5CpSgie/
...
oMo7yykABY7Ozd5wQewBQ4AdSlWSX4nGDtsiFxWiI5sKuAAeOCbTosy1s8w8fxoJ5Tz1sdoxNeGs
...
...
NWUH38v/nDCgEpIXD5Hn3qAEcju1IjmbwlvtW+nY2jVhv7UGd8MjwUTNGItdb6nsYqM2asrnF3qS
VRkAKKKYeGjkpUfVTrW0YFjXkfcrR/V+QFL5OndHAKJXjW7a4ejJLncTzmZSpYzwApc=
-----END RSA PRIVATE KEY-----

프라이빗 키는 AWS에 저장되지 않고 키가 생성될 때만 검색할 수 있다. 나중에 복구할 수 없으므로 잘 보관해야 한다. 프라이빗 키를 잃어버리면 새 키 페어를 생성해야 한다.

키 페어 표시

키 페어에서 "지문(Fingerprint)"이 생성되고 이 지문을 사용하여 로컬 시스템에 있는 프라이빗 키가 AWS에 저장된 퍼블릭 키와 일치하는지 확인할 수 있다. 지문은 프라이빗 키의 DER 인코딩된 사본에서 가져온 SHA1 해시이다. 이 값은 키 페어가 생성될 때 캡처되어 퍼블릭 키와 함께 AWS에 저장된다. 지문은 Amazon EC2 콘솔에서 보거나 AWS CLI 명령 aws ec2 describe-key-pairs를 실행하여 볼 수 있다.

명령을 실행하면 아래와 유사하다.

$ aws ec2 describe-key-pairs --key-name gitlab-poc
{
"KeyPairs": [
{
"KeyPairId": "key-example59cedd99xx",
"KeyFingerprint": "1f:51:ae:28:bf:89:e9:d8:1f:25:5d:37:2d:7d:b8:ca:9f:f5:f1:6f",
"KeyName": "gitlab-poc",
"Tags": []
}
]
}

Amazon EC2 보안 그룹

기본적으로 방화벽 역할을 하는 Amazon Elastic Compute Cloud(Amazon EC2) 인스턴스에 대한 보안 그룹과 함께, 들어오고 나가는 네트워크 트래픽을 결정하는 규칙(Inbound/Outbound rules)을 생성할 수 있다.

보안 그룹 생성

AWS 계정의 기본값 VPC(가상 사설 클라우드)와 연결된 보안 그룹을 만든다.

$ aws ec2 create-security-group --group-name gitlab-poc-sg --description "GitLab PoC security group" --vpc-id [Default VPC ID]
{
"GroupId": "sg-903004f8"
}

보안 그룹에 대한 초기 정보를 보려면 describe-security-groups 명령을 실행한다.

$ aws ec2 describe-security-groups --group-ids [Security Group ID]
{
"SecurityGroups": [
{
"Description": "GitLab PoC security group",
"GroupName": "gitlab-poc-sg",
"IpPermissions": [],
"OwnerId": "123456789012",
"GroupId": "sg-903004f8",
"IpPermissionsEgress": [
{
"IpProtocol": "-1",
"IpRanges": [
{
"CidrIp": "0.0.0.0/0"
}
],
"Ipv6Ranges": [],
"PrefixListIds": [],
"UserIdGroupPairs": []
}
],
"VpcId": "vpc-1a2b3c4d"
}
]
}

보안 그룹에 규칙 추가

Amazon EC2 인스턴스를 실행할 때 이미지에 연결하는 방법에 맞는 수신 네트워크 트래픽을 허용하려면 보안 그룹의 규칙을 활성화해야 한다. Linux 인스턴스를 시작할 경우, SSH 연결을 지원하기 위해 일반적으로 TCP 포트 22에서 인바운드 트래픽을 허용하는 규칙을 추가한다. authorize-security-group-ingress 명령을 사용하여 보안 그룹에 규칙을 추가한다. 이 명령의 필수 파라미터가 컴퓨터 또는 컴퓨터가 연결된 네트워크(주소 범위의 형식)의 퍼블릭 IP 주소(CIDR 표기법 사용)이다.

Public IP 확인

아래 명령을 실행하여 퍼블릭 주소를 확인한다.

$ curl https://checkip.amazonaws.com
203.0.113.57
SSH 인바운드 규칙 추가

아래 명령을 실행하여 보안 그룹의 인스턴스에 SSH를 활성화하는 규칙을 추가한다. 위에서 확인한 퍼블릭 주소의 CIDR 범위 203.0.113.0/24에서만 연결이 허용되도록 한다.

aws ec2 authorize-security-group-ingress --group-id [Security Group ID] --protocol tcp --port 22 --cidr 203.0.113.0/24

describe-security-groups 명령을 실행하여 보안 그룹의 변경 사항을 확인한다.

$ aws ec2 describe-security-groups --group-ids [Security Group ID]
{
"SecurityGroups": [
{
"Description": "GitLab PoC security group",
"GroupName": "gitlab-poc-sg",
"IpPermissions": [
{
"FromPort": 22,
"IpProtocol": "tcp",
"IpRanges": [
{
"CidrIp": "203.0.113.0/24"
}
],
"Ipv6Ranges": [],
"PrefixListIds": [],
"ToPort": 22,
"UserIdGroupPairs": []
}
],
"OwnerId": "123456789012",
"GroupId": "sg-903004f8",
"IpPermissionsEgress": [
{
"IpProtocol": "-1",
"IpRanges": [
{
"CidrIp": "0.0.0.0/0"
}
],
"Ipv6Ranges": [],
"PrefixListIds": [],
"UserIdGroupPairs": []
}
],
"VpcId": "vpc-1a2b3c4d"
}
]
}

Amazon EC2 인스턴스

현재 Ubuntu Server 18.04 LTS AMI 검색

AMI는 인스턴스를 시작하는 데 필요한 소프트웨어 구성(운영 체제, 애플리케이션 서버, 애플리케이션)이 포함된 템플릿이다.

$ aws ec2 describe-images \
--owners 099720109477 \
--filters 'Name=name,Values=ubuntu/images/hvm-ssd/ubuntu-bionic-18.04-amd64-server-????????' 'Name=state,Values=available' \
--query 'reverse(sort_by(Images, &CreationDate))[:1].ImageId' \
--output text
ami-05438a9ce08100b25

Amazon EC2 인스턴스 시작

run-instances 명령을 실행하여 Amazon EC2 인스턴스를 시작한다.

  • --image-id : 인스턴스에 사용할 AMI(Amazon Machine Image) ID
  • ami-05438a9ce08100b25: Ubuntu Server 18.04 LTS (HVM), SSD Volume Type
  • --instance-type : 인스턴스 유형
  • --count : 시작할 인스턴스의 수
  • --key-name : 사용할 키 페어의 이름
  • gitlab-poc : 위에서 만든 키 페어
  • --security-group-ids : 보안 그룹 ID
$ aws ec2 run-instances \
--image-id ami-05438a9ce08100b25 \
--count 1 \
--instance-type t3.large \
--key-name gitlab-poc \
--security-group-ids [Security Group ID]
{
"Groups": [],
"Instances": [
{
"AmiLaunchIndex": 0,
"ImageId": "ami-05438a9ce08100b25",
"InstanceId": "i-5203422c",
"InstanceType": "t3.large",
"KeyName": "gitlab-poc",
"LaunchTime": "2020-08-26T08:00:59+00:00",
"Monitoring": {
"State": "disabled"
},
"Placement": {
"AvailabilityZone": "ap-northeast-2b",
"GroupName": "",
"Tenancy": "default"
},
"PrivateDnsName": "ip-10-0-1-114.ap-northeast-2.compute.internal",
"PrivateIpAddress": "10.0.1.114",
"ProductCodes": [],
"PublicDnsName": "",
"State": {
"Code": 0,
"Name": "pending"
},
"StateTransitionReason": "",
"SubnetId": "subnet-6e7f829e",
"VpcId": "vpc-1a2b3c4d",
"Architecture": "x86_64",
"BlockDeviceMappings": [],
"ClientToken": "example1-abcd-efgh-xxxx-1234567890ab",
"EbsOptimized": false,
"Hypervisor": "xen",
"NetworkInterfaces": [
{
"Attachment": {
"AttachTime": "2020-08-26T08:00:59+00:00",
"AttachmentId": "eni-attach-52193138",
"DeleteOnTermination": true,
"DeviceIndex": 0,
"Status": "attaching"
},
"Description": "",
"Groups": [
{
"GroupName": "gitlab-poc-sg",
"GroupId": "sg-903004f8"
}
],
"Ipv6Addresses": [],
"MacAddress": "0a:b1:cc:dd:ee:ff",
"NetworkInterfaceId": "eni-a7edb1c9",
"OwnerId": "123456789012",
"PrivateDnsName": "ip-10-0-1-114.ap-northeast-2.compute.internal",
"PrivateIpAddress": "10.0.1.114",
"PrivateIpAddresses": [
{
"Primary": true,
"PrivateDnsName": "ip-10-0-1-114.ap-northeast-2.compute.internal",
"PrivateIpAddress": "10.0.1.114"
}
],
"SourceDestCheck": true,
"Status": "in-use",
"SubnetId": "subnet-6e7f829e",
"VpcId": "vpc-1a2b3c4d",
"InterfaceType": "interface"
}
],
"RootDeviceName": "/dev/sda1",
"RootDeviceType": "ebs",
"SecurityGroups": [
{
"GroupName": "gitlab-poc-sg",
"GroupId": "sg-903004f8"
}
],
"SourceDestCheck": true,
"StateReason": {
"Code": "pending",
"Message": "pending"
},
"VirtualizationType": "hvm",
"CpuOptions": {
"CoreCount": 1,
"ThreadsPerCore": 2
},
"CapacityReservationSpecification": {
"CapacityReservationPreference": "open"
},
"MetadataOptions": {
"State": "pending",
"HttpTokens": "optional",
"HttpPutResponseHopLimit": 1,
"HttpEndpoint": "enabled"
}
}
],
"OwnerId": "123456789012",
"ReservationId": "r-5875ca20"
}

Amazon EC2 인스턴스 나열(List)

AWS CLI를 사용하여 인스턴스를 나열하고 정보를 확인할 수 있다. 모든 인스턴스를 나열하거나 관심이 있는 인스턴스에 따라 결과를 필터링할 수 있다.

describe-instances 명령을 실행하여 인스턴스를 나열할 수 있다. 아래 명령은 목록을 t3.large 인스턴스로만 필터링하고 각 매치에 대한 InstanceId 값만 출력한다.

$ aws ec2 describe-instances --filters "Name=instance-type,Values=t3.large" --query "Reservations[].Instances[].InstanceId"
[
"i-05e998023d9c69f9a"
]

Amazon EC2 인스턴스 연결

프라이빗 키 파일 권한 설정
chmod 400 gitlab-poc.pem
SSH를 사용하여 연결
ssh -i "gitlab-poc.pem" ubuntu@[My-Instance-Public-DNS-Name]
The authenticity of host 'ec2-1-23-456-789.ap-northeast-2.compute.amazonaws.com (1.23.456.789)' can't be established.
ECDSA key fingerprint is SHA256:Fz/neBad9tvkgJf1QZWxheQmR59WgrgzEimCG6kZY.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added 'ec2-1-23-456-789.ap-northeast-2.compute.amazonaws.com' (ECDSA) to the list of known hosts.
Welcome to Ubuntu 18.04.5 LTS (GNU/Linux 5.3.0-1032-aws x86_64)

* Documentation: https://help.ubuntu.com
* Management: https://landscape.canonical.com
* Support: https://ubuntu.com/advantage

System information as of Wed Aug 26 08:59:01 UTC 2020

System load: 0.08 Processes: 93
Usage of /: 14.4% of 7.69GB Users logged in: 0
Memory usage: 2% IP address for ens5: 10.0.1.114
Swap usage: 0%

0 packages can be updated.
0 updates are security updates.



The programs included with the Ubuntu system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.

To run a command as administrator (user "root"), use "sudo <command>".
See "man sudo_root" for details.

ubuntu@ip-10-0-1-114:~$

Amazon EC2 인스턴스 중지 및 시작

콘솔이나 명령줄을 사용하여 Amazon EBS 기반 인스턴스를 중지했다가 시작할 수 있다. 인스턴스를 중지했다가 다시 시작해도 프라이빗 IPv4 주소와 모든 IPv6 주소는 유지된다. AWS에서 퍼블릭 IPv4 주소를 해제했다가 인스턴스가 시작되면 새 주소를 할당한다.

인스턴스 중지
$ aws ec2 stop-instances --instance-ids [Instance ID]
{
"StoppingInstances": [
{
"CurrentState": {
"Code": 64,
"Name": "stopping"
},
"InstanceId": "i-1234567890abcdef0",
"PreviousState": {
"Code": 16,
"Name": "running"
}
}
]
}
중지된 인스턴스 시작
$ aws ec2 start-instances --instance-ids [Instance ID]
{
"StartingInstances": [
{
"CurrentState": {
"Code": 0,
"Name": "pending"
},
"InstanceId": "i-1234567890abcdef0",
"PreviousState": {
"Code": 80,
"Name": "stopped"
}
}
]
}

참고

Amazon EC2 키 페어
Amazon EC2 보안 그룹
Amazon EC2 인스턴스
Amazon EC2 인스턴스 중지 및 시작