일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 31 |
- gcc 업데이트
- g++ 업데이트
- semanage
- c3 step graph
- regex_search
- subporcess path
- linux시간으로 변경
- 1697
- gcc regex
- python os
- selinux port 등록
- c3 축 없애기
- 정규식 컴파일
- c++ 정규식
- c3 second
- snmp
- grafana dashboard
- 정규식 문자열 출력
- influxdb 설치
- python subprocess
- telegraf
- snmp test
- InfluxDB
- CentOS7
- 백준
- python popen
- c3 초
- 정규식 활용
- centos pyhon 설치
- c3 축 가리기
- Today
- Total
리셋 되지 말자
[Terraform] AWS - Lightsail 생성 본문
Lightsail 이란?
간단하게 구성할 수 있는 VPS (Virtual Private Server) 라고 한다. 잘 정리된 글이 있어서 설명을 대신한다.
https://www.44bits.io/ko/keyword/amazon-lightsail
EC2 대신 쓰는 이유?
간단하게 구현할 수 있다. 무엇보다도 가격이 저렴하다.
시스템 사양
os : ubuntu 18.04
terraform version : 0.14.8
하게될 것
- Lightsail 생성을 위한 Lightsail 전용 IAM 사용자 생성
- Lightsail IAM 사용자에 대한 권한 부여
- Lightsail 전용 keypair 생성
- ubuntu 18.04 이미지의 Lightsail 인스턴스 생성 (사양 : micro)
- aws cli 설치 (Lightsail에 사용할 이미지 목록 확인)
실습에 쓰인 최종 소스코드
깃허브 : https://github.com/Penguin135/IaC/tree/main/terraform/aws/example-3
aws cli 버전 2 설치
참고 : https://docs.aws.amazon.com/ko_kr/cli/latest/userguide/install-cliv2-linux.html
1. apt update
sudo apt update -y
2. unzip install
sudo apt install -y unzip
3. aws cli 2 설치 파일 다운로드
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
4. 압축해제
unzip awscliv2.zip
5. 설치 프로그램 실행
sudo ./aws/install
6. 설치 확인 (aws --version 명령어 사용)
aws --version
aws-cli/2.2.10 Python/3.8.8 Linux/4.15.0-143-generic exe/x86_64.ubuntu.18 prompt/off
정책 생성
1. aws 콘솔에 루트 계정으로 로그인
2. IAM 서비스 검색 후, 이동
3. '정책 생성' 선택
4. 서비스 에서 'Lightsail' 입력 후, 검색된 'Lightsail' 선택
5. '수동 작업'의 '모든 Lightsail 작업' 체크
6. '리소스'의 '모든 리소스' 체크 후, 우측 하단의 '다음' 선택
7. 생략. 우측 하단 '다음' 선택
8. 이름, 설명을 자유롭게 입력 후, 우측 하단 '정책 생성' 선택
9. 생성된 정책 확인
IAM 사용자 생성
1. aws 콘솔에 루트 계정으로 로그인
2. IAM 서비스 검색 후, 이동
3. 사용자 추가 선택
4. 사용자 이름 입력, 액세스 유형 '프로그래밍 방식 액세스' 선택, 우측하단 '다음'
5. '기존 정책 직접 연결' 선택 후, 정책 필터에 'LightsailFullAccessPolicy' 검색 후, 선택한 뒤 우측하단 '다음' 선택
6. 생략 (태그 추가) - 우측 하단 '다음' 선택
7. 우측 하단 '사용자 만들기' 선택
8. 액세스 키, 시크릿 키 확인 (창 닫으면 다시 확인 불가능 하니, 둘 다 반드시 기록해 놓아야함)
AWS CLI를 통한 bundle, blueprint 확인
위에서 aws cli 버전 2를 설치했다고 가정하고 수행
bundle은 생성할 Lightsail 인스턴스의 사양, blueprint는 인스턴스의 image 라고 생각하면 될것 같다
참고 - blueprint : https://docs.aws.amazon.com/cli/latest/reference/lightsail/get-blueprints.html
참고 - bundle : https://aws.amazon.com/ko/premiumsupport/knowledge-center/lightsail-aws-cli-commands/
1. bundle 명령어 수행 - 'aws configure' 명령어로 credential 설정하라고 출력됨
aws lightsail get-bundles
You must specify a region. You can also configure your region by running "aws configure".
aws lightsail get-bundles --region ap-northeast-2
Unable to locate credentials. You can configure credentials by running "aws configure".
2. credential 설정 - 'ap-northeast-2' 는 서울 region
aws configure
AWS Access Key ID [None]: AKIAVYDYMS3KRG2HHUYW
AWS Secret Access Key [None]: 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
Default region name [None]: ap-northeast-2
Default output format [None]: json
3. bundle 확인 - 다양한 bundle 확인 가능. price는 월 요금. 밑에서는 cpu 1개, ram 1 GB인 'micro_2_0'을 사용
aws lightsail get-bundles --region ap-northeast-2
{
"bundles": [
{
"price": 3.5,
"cpuCount": 1,
"diskSizeInGb": 20,
"bundleId": "nano_2_0",
"instanceType": "nano",
"isActive": true,
"name": "Nano",
"power": 300,
"ramSizeInGb": 0.5,
"transferPerMonthInGb": 1024,
"supportedPlatforms": [
"LINUX_UNIX"
]
},
{
"price": 5.0,
"cpuCount": 1,
"diskSizeInGb": 40,
"bundleId": "micro_2_0",
"instanceType": "micro",
"isActive": true,
"name": "Micro",
"power": 500,
"ramSizeInGb": 1.0,
"transferPerMonthInGb": 2048,
"supportedPlatforms": [
"LINUX_UNIX"
]
},
{
"price": 10.0,
"cpuCount": 1,
"diskSizeInGb": 60,
"bundleId": "small_2_0",
"instanceType": "small",
"isActive": true,
"name": "Small",
"power": 1000,
"ramSizeInGb": 2.0,
"transferPerMonthInGb": 3072,
"supportedPlatforms": [
"LINUX_UNIX"
]
},
{
"price": 20.0,
"cpuCount": 2,
"diskSizeInGb": 80,
"bundleId": "medium_2_0",
"instanceType": "medium",
"isActive": true,
"name": "Medium",
"power": 2000,
"ramSizeInGb": 4.0,
"transferPerMonthInGb": 4096,
"supportedPlatforms": [
"LINUX_UNIX"
]
},
{
"price": 40.0,
"cpuCount": 2,
"diskSizeInGb": 160,
"bundleId": "large_2_0",
"instanceType": "large",
"isActive": true,
"ramSizeInGb": 32.0,
"transferPerMonthInGb": 7168,
"supportedPlatforms": [
"LINUX_UNIX"
]
},
{
"price": 8.0,
"cpuCount": 1,
"diskSizeInGb": 30,
"bundleId": "nano_win_2_0",
"instanceType": "nano",
"isActive": true,
"name": "Nano",
"power": 300,
"ramSizeInGb": 0.5,
"transferPerMonthInGb": 1024,
"supportedPlatforms": [
"WINDOWS"
]
},
3-1. table 형태로 더 보기 쉽게 출력 가능
참고 : https://aws.amazon.com/ko/premiumsupport/knowledge-center/lightsail-aws-cli-commands/
aws lightsail get-bundles --region ap-northeast-2 --query 'bundles[].{price:price,cpuCount:cpuCount,ramSizeInGb:ramSizeInGb,diskSizeInGb:diskSizeInGb,bundleId:bundleId,instanceType:instanceType,supportedPlatforms:supportedPlatforms[0]}' --output table
---------------------------------------------------------------------------------------------------------------
| GetBundles |
+-----------------+-----------+---------------+---------------+--------+---------------+----------------------+
| bundleId | cpuCount | diskSizeInGb | instanceType | price | ramSizeInGb | supportedPlatforms |
+-----------------+-----------+---------------+---------------+--------+---------------+----------------------+
| nano_2_0 | 1 | 20 | nano | 3.5 | 0.5 | LINUX_UNIX |
| micro_2_0 | 1 | 40 | micro | 5.0 | 1.0 | LINUX_UNIX |
| small_2_0 | 1 | 60 | small | 10.0 | 2.0 | LINUX_UNIX |
| medium_2_0 | 2 | 80 | medium | 20.0 | 4.0 | LINUX_UNIX |
| large_2_0 | 2 | 160 | large | 40.0 | 8.0 | LINUX_UNIX |
| xlarge_2_0 | 4 | 320 | xlarge | 80.0 | 16.0 | LINUX_UNIX |
| 2xlarge_2_0 | 8 | 640 | 2xlarge | 160.0 | 32.0 | LINUX_UNIX |
| nano_win_2_0 | 1 | 30 | nano | 8.0 | 0.5 | WINDOWS |
| micro_win_2_0 | 1 | 40 | micro | 12.0 | 1.0 | WINDOWS |
| small_win_2_0 | 1 | 60 | small | 20.0 | 2.0 | WINDOWS |
| medium_win_2_0 | 2 | 80 | medium | 40.0 | 4.0 | WINDOWS |
| large_win_2_0 | 2 | 160 | large | 70.0 | 8.0 | WINDOWS |
| xlarge_win_2_0 | 4 | 320 | xlarge | 120.0 | 16.0 | WINDOWS |
| 2xlarge_win_2_0| 8 | 640 | 2xlarge | 240.0 | 32.0 | WINDOWS |
+-----------------+-----------+---------------+---------------+--------+---------------+----------------------+
4. blueprint 확인 - '| grep ubuntu' 를 사용하지 않으면, 자세한 정보 확인 가능. 밑에서는 'ubuntu_18_04' 사용
aws lightsail get-blueprints --region ap-northeast-2 | grep ubuntu
"blueprintId": "ubuntu_20_04",
"group": "ubuntu_20",
"blueprintId": "ubuntu_18_04",
"group": "ubuntu_18",
"blueprintId": "ubuntu_16_04_2",
"group": "ubuntu",
"blueprintId": "plesk_ubuntu_18_0_34",
"group": "plesk_ubuntu",
4.1 bundle과 blueprint 모두 테이블 형태로 보기 쉽게 출력 가능
aws lightsail get-bundles --region eu-west-1 --query 'bundles[].{price:price,cpuCount:cpuCount,ramSizeInGb:ramSizeInGb,diskSizeInGb:diskSizeInGb,bundleId:bundleId,instanceType:instanceType,supportedPlatforms:supportedPlatforms[0]}' --output table
---------------------------------------------------------------------------------------------------------------
| GetBundles |
+-----------------+-----------+---------------+---------------+--------+---------------+----------------------+
| bundleId | cpuCount | diskSizeInGb | instanceType | price | ramSizeInGb | supportedPlatforms |
+-----------------+-----------+---------------+---------------+--------+---------------+----------------------+
| nano_2_0 | 1 | 20 | nano | 3.5 | 0.5 | LINUX_UNIX |
| micro_2_0 | 1 | 40 | micro | 5.0 | 1.0 | LINUX_UNIX |
| small_2_0 | 1 | 60 | small | 10.0 | 2.0 | LINUX_UNIX |
| medium_2_0 | 2 | 80 | medium | 20.0 | 4.0 | LINUX_UNIX |
| large_2_0 | 2 | 160 | large | 40.0 | 8.0 | LINUX_UNIX |
| xlarge_2_0 | 4 | 320 | xlarge | 80.0 | 16.0 | LINUX_UNIX |
| 2xlarge_2_0 | 8 | 640 | 2xlarge | 160.0 | 32.0 | LINUX_UNIX |
| nano_win_2_0 | 1 | 30 | nano | 8.0 | 0.5 | WINDOWS |
| micro_win_2_0 | 1 | 40 | micro | 12.0 | 1.0 | WINDOWS |
| small_win_2_0 | 1 | 60 | small | 20.0 | 2.0 | WINDOWS |
| medium_win_2_0 | 2 | 80 | medium | 40.0 | 4.0 | WINDOWS |
| large_win_2_0 | 2 | 160 | large | 70.0 | 8.0 | WINDOWS |
| xlarge_win_2_0 | 4 | 320 | xlarge | 120.0 | 16.0 | WINDOWS |
---------------------------------------------------------------------------------------------------------------------------------------------------------------------
| GetBlueprints |
+--------------------------------------+-----------------------+--------------------------------+-------------+-----------------------------------------------------+
| blueprintId | group | name | platform | productUrl |
+--------------------------------------+-----------------------+--------------------------------+-------------+-----------------------------------------------------+
| windows_server_2019 | windows_2019 | Windows Server 2019 | WINDOWS | https://aws.amazon.com/marketplace/pp/B07QZ4XZ8F |
| windows_server_2016 | windows_2016 | Windows Server 2016 | WINDOWS | https://aws.amazon.com/marketplace/pp/B01M7SJEU7 |
| windows_server_2012 | windows_2012 | Windows Server 2012 R2 | WINDOWS | https://aws.amazon.com/marketplace/pp/B00KQOWCAQ |
| windows_server_2016_sql_2016_express| windows_2016_sql_exp | SQL Server 2016 Express | WINDOWS | https://aws.amazon.com/marketplace/pp/B01MAZHH98 |
| amazon_linux_2 | amazon_linux_2 | Amazon Linux 2 | LINUX_UNIX | https://aws.amazon.com/amazon-linux-2/ |
| amazon_linux | amazon-linux | Amazon Linux | LINUX_UNIX | https://aws.amazon.com/marketplace/pp/B00CIYTQTC |
| ubuntu_20_04 | ubuntu_20 | Ubuntu | LINUX_UNIX | https://aws.amazon.com/marketplace/pp/B087QQNGF1 |
| ubuntu_18_04 | ubuntu_18 | Ubuntu | LINUX_UNIX | https://aws.amazon.com/marketplace/pp/B07CQ33QKV |
| ubuntu_16_04_2 | ubuntu | Ubuntu | LINUX_UNIX | https://aws.amazon.com/marketplace/pp/B01JBL2M0O |
| debian_10 | debian_10 | Debian | LINUX_UNIX | https://aws.amazon.com/marketplace/pp/B0859NK4HC |
| debian_9_13 | debian_9 | Debian | LINUX_UNIX | https://aws.amazon.com/marketplace/pp/B073HW9SP3 |
| debian_8_7 | debian | Debian | LINUX_UNIX | https://aws.amazon.com/marketplace/pp/B00WUNJIEE |
| freebsd_12 | freebsd | FreeBSD | LINUX_UNIX | https://aws.amazon.com/marketplace/pp/B07L6QV354 |
| opensuse_15_2 | opensuse | openSUSE | LINUX_UNIX | https://aws.amazon.com/marketplace/pp/B01N4R3GJI |
| centos_8 | centos_8 | CentOS | LINUX_UNIX | https://aws.amazon.com/marketplace/pp/B08KYLN2CG |
| centos_7_2009_01 | centos | CentOS | LINUX_UNIX | https://aws.amazon.com/marketplace/pp/B00O7WM7QW |
| wordpress | wordpress | WordPress | LINUX_UNIX | https://aws.amazon.com/marketplace/pp/B00NN8Y43U |
| wordpress_multisite | wordpress_multisite | WordPress Multisite | LINUX_UNIX | https://aws.amazon.com/marketplace/pp/B00NN8XE6S |
| lamp_7 | lamp_7 | LAMP (PHP 7) | LINUX_UNIX | https://aws.amazon.com/marketplace/pp/B072JNJZ5C |
| nodejs | node | Node.js | LINUX_UNIX | https://aws.amazon.com/marketplace/pp/B00NNZUAKO |
| joomla | joomla | Joomla | LINUX_UNIX | https://aws.amazon.com/marketplace/pp/B00NNZUP54 |
| magento | magento | Magento | LINUX_UNIX | https://aws.amazon.com/marketplace/pp/B00NNZTA6Y |
| mean | mean | MEAN | LINUX_UNIX | https://aws.amazon.com/marketplace/pp/B00NO1HJ56 |
| drupal | drupal | Drupal | LINUX_UNIX | https://aws.amazon.com/marketplace/pp/B00NNZSUMO |
| gitlab | gitlab | GitLab CE | LINUX_UNIX | https://aws.amazon.com/marketplace/pp/B00NNZU5PO |
| redmine | redmine | Redmine | LINUX_UNIX | https://aws.amazon.com/marketplace/pp/B00NNZUVHQ |
| nginx | nginx | Nginx | LINUX_UNIX | https://aws.amazon.com/marketplace/pp/B00NPHKI3Y |
| ghost_bitnami | ghost_bitnami | Ghost | LINUX_UNIX | https://aws.amazon.com/marketplace/pp/B00NPHLY8W |
| django_bitnami | django_bitnami | Django | LINUX_UNIX | https://aws.amazon.com/marketplace/pp/B00NNZTDNO |
| prestashop_bitnami | prestashop_bitnami | PrestaShop | LINUX_UNIX | https://aws.amazon.com/marketplace/pp/B00NPHLR4I |
| plesk_ubuntu_18_0_34 | plesk_ubuntu | Plesk Hosting Stack on Ubuntu | LINUX_UNIX | https://aws.amazon.com/marketplace/pp/B077MJL7Z2 |
| cpanel_whm_linux | cpanel_whm_linux | cPanel & WHM for Linux | LINUX_UNIX | https://aws.amazon.com/marketplace/pp/B07RRX2TVV |
+--------------------------------------+-----------------------+--------------------------------+-------------+-----------------------------------------------------+
5. 최종 확인
- 사용할 bundle (인스턴스 사양) : 1 cpu, 1 GB memory, micro_2_0
- 사용할 bluprint (이미지) : ubuntu_18_04
Terraform 설치
아래 링크에서 진행
https://not-to-be-reset.tistory.com/368
액세스 키, 시크릿 키 환경변수에 등록
.tf 파일에 직접 지정해도 되지만, 안전하지 않은 방법임으로 환경 변수에 등록하여 사용한다.
export AWS_ACCESS_KEY_ID=AKIAVYDYMS3KRG2HHUYW
export AWS_SECRET_ACCESS_KEY=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
실습 디렉토리 생성 및 이동
여기서 생성하고, 이동하는 디렉토리가 모든 .tf 파일이 작성될 장소다.
mkdir terraform-prac
cd terraform-prac/
versions.tf 파일 작성 및 terraform init 수행
1. versions.tf 파일 작성 - provider 로 aws를 지정
Terraform은 모든 .tf 파일을 먼저 읽은 뒤, 그래프 형태로 .tf 파일들에 리소스들을 인식하기 때문에 파일 이름은 상관없다
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 3.0"
}
}
}
provider "aws" {
access_key = ""
secret_key = ""
region = "ap-northeast-2"
}
2. terraform init 명령어 실행
init에 성공하면 아래와 같이 문구들이 출력된다.
terraform init
Initializing the backend...
Initializing provider plugins...
- Finding hashicorp/aws versions matching "~> 3.0"...
- Installing hashicorp/aws v3.44.0...
- Installed hashicorp/aws v3.44.0 (self-signed, key ID 34365D9472D7468F)
Partner and community providers are signed by their developers.
If you'd like to know more about provider signing, you can read about it here:
https://www.terraform.io/docs/cli/plugins/signing.html
Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
you run "terraform init" in the future.
Terraform has been successfully initialized!
You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.
If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.
3. terraform version 명령어 실행
버전이 출력되면서 aws가 provider로 등록된 것을 확인할 수 있다.
terraform version
Terraform v0.14.8
+ provider registry.terraform.io/hashicorp/aws v3.44.0
main.tf 파일 작성 및 terraform plan, apply 수행 - Lightsail 키페어 생성
참고 : https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lightsail_key_pair
1. lightsail의 key pair에 사용할 ssh key 생성
rsa 타입의 ssh 키페어를 생성한다.
생성되는 경로는 ' ./ ' 이고, 이름은 'lightsail_key' 이다. (이름은 자유다)
passphrase는 입력하지 않고 Enter를 입력하여 넘어갔다.
ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/vagrant/.ssh/id_rsa): ./lightsail_key
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in ./lightsail_key.
Your public key has been saved in ./lightsail_key.pub.
The key fingerprint is:
SHA256:89VQzuRL+r4whVktsvijha/RI0VwByC1apN+PlZCZj0 vagrant@ubuntu100
The key's randomart image is:
+---[RSA 2048]----+
| ..+.o.+ |
| . + B . |
| ..+ B .|
| o+oE@ o |
| S+. B.+ |
| o +.*.o |
| . *oO . |
| oo* * |
| .+o. o. |
+----[SHA256]-----+
2. 생성된 key 확인
키페어 생성 경로를 ' ./ ' 로 지정했기 때문에, 현재 위치(versions.tf 파일이 있는 위치)에 두 개의 키가 생성된다.
여기서 사용할 키는 .pub로 끝나는 public key 이다.
ls
lightsail_key lightsail_key.pub versions.tf
3. main.tf에 lightsail 키페어 생성 리소스 선언
- main.tf
resource "aws_lightsail_key_pair" "lightsail-test" { # lightsail-test라는 이름의 aws_lightsail_key_pair 라는 타입의 리소스를 정의한다.
name = "lightsail-test" # 생성될 lightsail 키페어의 이름
public_key = file("./lightsail_key.pub") # 키페어에 사용할 public key 지정
}
main.tf 에 위의 코드를 작성한다. 작성한 후의 디렉토리의 상태는 아래와 같다.
- 현재 작업중인 디렉토리의 파일 목록
ls
lightsail_key lightsail_key.pub main.tf versions.tf
4. terraform plan 명령어 테스트
terraform plan
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
+ create
Terraform will perform the following actions:
# aws_lightsail_key_pair.lightsail-test will be created
+ resource "aws_lightsail_key_pair" "lightsail-test" {
+ arn = (known after apply)
+ encrypted_fingerprint = (known after apply)
+ encrypted_private_key = (known after apply)
+ fingerprint = (known after apply)
+ id = (known after apply)
+ name = "lightsail-test"
+ private_key = (known after apply)
+ public_key = <<-EOT
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDWNVVArryuJmGyi6JQcf3cz+Agu3fyiPMJdwerZzzrPRY7vbs0Xj5cdkXBXif3P4yJIkjli/rReOlZnSR4/DwA2WlmCqBa/VXp/f5e58gYvwm32Q8gCvscTk1Ne7t4Sb+Url3g9OI5Er7os8rrGVVP8cK35DxRgbsjd7cQRdN4YS9XmBsH7A58SG53OwsziHlBVkWxMFNmk71fdhqtgDxGNgH+jsF18qDYvKeXdZBEzQmwWEFKPovC6mXrummxC0SXrS2D9FsJ3YqhDNskAa7IadWVwwDOaw158fGo5FtyLrmEjDyL6bgq7FyC8ZiihCi2Z2eAHYSNdJsd316nZ4uR vagrant@ubuntu100
EOT
}
Plan: 1 to add, 0 to change, 0 to destroy.
------------------------------------------------------------------------
Note: You didn't specify an "-out" parameter to save this plan, so Terraform
can't guarantee that exactly these actions will be performed if
"terraform apply" is subsequently run.
'terraform plan' 명령어를 수행하면, 'terraform apply' 명령어를 수행하면 실제로 "aws_lightsail_key_pair" 가 생성된다고 출력된다.
5. terraform apply 수행
terraform apply
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
+ create
Terraform will perform the following actions:
# aws_lightsail_key_pair.lightsail-test will be created
+ resource "aws_lightsail_key_pair" "lightsail-test" {
+ arn = (known after apply)
+ encrypted_fingerprint = (known after apply)
+ encrypted_private_key = (known after apply)
+ fingerprint = (known after apply)
+ id = (known after apply)
+ name = "lightsail-test"
+ private_key = (known after apply)
+ public_key = <<-EOT
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDWNVVArryuJmGyi6JQcf3cz+Agu3fyiPMJdwerZzzrPRY7vbs0Xj5cdkXBXif3P4yJIkjli/rReOlZnSR4/DwA2WlmCqBa/VXp/f5e58gYvwm32Q8gCvscTk1Ne7t4Sb+Url3g9OI5Er7os8rrGVVP8cK35DxRgbsjd7cQRdN4YS9XmBsH7A58SG53OwsziHlBVkWxMFNmk71fdhqtgDxGNgH+jsF18qDYvKeXdZBEzQmwWEFKPovC6mXrummxC0SXrS2D9FsJ3YqhDNskAa7IadWVwwDOaw158fGo5FtyLrmEjDyL6bgq7FyC8ZiihCi2Z2eAHYSNdJsd316nZ4uR vagrant@ubuntu100
EOT
}
Plan: 1 to add, 0 to change, 0 to destroy.
Do you want to perform these actions?
Terraform will perform the actions described above.
Only 'yes' will be accepted to approve.
Enter a value: yes
aws_lightsail_key_pair.lightsail-test: Creating...
aws_lightsail_key_pair.lightsail-test: Creation complete after 7s [id=lightsail-test]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
'aws_lightsail_key_pair'가 생성되었다고 출력된다.
6. 생성된 키페어를 확인하기 위해 lightsail 서비스로 이동
7. 인스턴스 생성 선택 (실제로 인스턴스를 생성하지는 않지만, 키페어가 생성되었는지 확인하기 위함)
8. 아래로 창을 스크롤 하여 'SSH 키 페어 변경' 클릭
9. 'lightsail-test' 라는 이름의 키페어가 있는것을 확인
키페어가 생성된 것을 확인했으니, 생성 작업을 취소한다.
main.tf 파일 작성 및 terraform plan, apply 수행 - Lightsail 인스턴스 생성
참고 : https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lightsail_instance
1. main.tf 추가 작성
- main.tf
resource "aws_lightsail_key_pair" "lightsail-test" { # lightsail-test라는 이름의 aws_lightsail_key_pair 라는 타입의 리소스를 정의한다.
name = "lightsail-test" # 생성될 lightsail 키페어의 이름
public_key = file("./lightsail_key.pub") # 키페어에 사용할 public key 지정
}
# Create a new Lightsail Instance
resource "aws_lightsail_instance" "lightsail_test" {
name = "lightsail-test-instance"
availability_zone = "ap-northeast-2a" # seoul regin 'a'
blueprint_id = "ubuntu_18_04"
bundle_id = "micro_2_0"
key_pair_name = aws_lightsail_key_pair.lightsail-test.name
tags = {
Name = "my-lightsail"
}
}
'aws_light_instance' 를 정의한다.
- name : 임의로 설정
- availability_zone : 서울 region의 'a'
a가 왜 붙는지 궁금하면 - 참고 : https://a1010100z.tistory.com/174 - blueprint_id, bundle_id : aws cli를 통해 알아낸 것들 중 원하는 것의 id
- key_pair_name : 'lightsail-test'라는 이름으로 생성한 lightsail 키페어의 'name'
- tags : (필수 아님) 생성할 인스턴스에 tag 추가
2. terraform plan 명령어 테스트
terraform plan
aws_lightsail_key_pair.lightsail-test: Refreshing state... [id=lightsail-test]
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
+ create
Terraform will perform the following actions:
# aws_lightsail_instance.lightsail_test will be created
+ resource "aws_lightsail_instance" "lightsail_test" {
+ arn = (known after apply)
+ availability_zone = "ap-northeast-2a"
+ blueprint_id = "ubuntu_18_04"
+ bundle_id = "micro_2_0"
+ cpu_count = (known after apply)
+ created_at = (known after apply)
+ id = (known after apply)
+ ipv6_address = (known after apply)
+ ipv6_addresses = (known after apply)
+ is_static_ip = (known after apply)
+ key_pair_name = "lightsail-test"
+ name = "lightsail-test-instance"
+ private_ip_address = (known after apply)
+ public_ip_address = (known after apply)
+ ram_size = (known after apply)
+ tags = {
+ "Name" = "my-lightsail"
}
+ tags_all = {
+ "Name" = "my-lightsail"
}
+ username = (known after apply)
}
Plan: 1 to add, 0 to change, 0 to destroy.
------------------------------------------------------------------------
Note: You didn't specify an "-out" parameter to save this plan, so Terraform
can't guarantee that exactly these actions will be performed if
"terraform apply" is subsequently run.
lighsail 키페어는 이미 생성되어 있으니, 인스턴스만 생성되는 plan을 확인할 수 있다.
3. terraform apply 수행
terraform apply
aws_lightsail_key_pair.lightsail-test: Refreshing state... [id=lightsail-test]
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
+ create
Terraform will perform the following actions:
# aws_lightsail_instance.lightsail_test will be created
+ resource "aws_lightsail_instance" "lightsail_test" {
+ arn = (known after apply)
+ availability_zone = "ap-northeast-2a"
+ blueprint_id = "ubuntu_18_04"
+ bundle_id = "micro_2_0"
+ cpu_count = (known after apply)
+ created_at = (known after apply)
+ id = (known after apply)
+ ipv6_address = (known after apply)
+ ipv6_addresses = (known after apply)
+ is_static_ip = (known after apply)
+ key_pair_name = "lightsail-test"
+ name = "lightsail-test-instance"
+ private_ip_address = (known after apply)
+ public_ip_address = (known after apply)
+ ram_size = (known after apply)
+ tags = {
+ "Name" = "my-lightsail"
}
+ tags_all = {
+ "Name" = "my-lightsail"
}
+ username = (known after apply)
}
Plan: 1 to add, 0 to change, 0 to destroy.
Do you want to perform these actions?
Terraform will perform the actions described above.
Only 'yes' will be accepted to approve.
Enter a value: yes
aws_lightsail_instance.lightsail_test: Creating...
aws_lightsail_instance.lightsail_test: Still creating... [10s elapsed]
aws_lightsail_instance.lightsail_test: Still creating... [20s elapsed]
aws_lightsail_instance.lightsail_test: Still creating... [30s elapsed]
aws_lightsail_instance.lightsail_test: Creation complete after 39s [id=lightsail-test-instance]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
4. 생성된 인스턴스 확인
Lightsail 서비스 홈을 확인하면, main.tf에 설정한 대로 Light sail 인스턴스가 생성된 것을 확인할 수 있다.
Lightsail 인스턴스 접속
1. 접속 - 관리 선택
위의 상태에서, 우측 상단의
모양을 클릭하면
오른쪽에 메뉴가 나타는데, 여기서 '관리'를 선택한다.
2. ssh 접속 정보 확인
ssh접속할 때 사용해야하는 사용자 이름 'ubnutu'과 연결할 IP 주소 '3.36.111.181을 확인한다
3. ssh 접속
- 현재 디렉토리 파일 목록
ls
lightsail_key lightsail_key.pub main.tf terraform.tfstate terraform.tfstate.backup versions.tf
'ssh-keygen -t rsa' 명령어로 생성했던 private key인 'lightsail_key' 가 있는 곳(현재 작업중이던 디렉토리)에서 ssh 접속을 할 것이다
- ssh 접속 실행
ssh -i ./lightsail_key ubuntu@3.36.111.181
The authenticity of host '3.36.111.181 (3.36.111.181)' can't be established.
ECDSA key fingerprint is SHA256:h8Cd+Lc1PA8JWRERNHUCXRBYKM6l6xrmabP5U7jLPc0.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '3.36.111.181' (ECDSA) to the list of known hosts.
Welcome to Ubuntu 18.04.1 LTS (GNU/Linux 4.15.0-1021-aws x86_64)
* Documentation: https://help.ubuntu.com
* Management: https://landscape.canonical.com
* Support: https://ubuntu.com/advantage
System information as of Wed Jun 9 04:30:04 UTC 2021
System load: 0.0 Processes: 85
Usage of /: 2.7% of 38.71GB Users logged in: 0
Memory usage: 14% IP address for eth0: 172.26.3.90
Swap usage: 0%
Get cloud support with Ubuntu Advantage Cloud Guest:
http://www.ubuntu.com/business/services/cloud
0 packages can be updated.
0 updates are security updates.
New release '20.04.2 LTS' available.
Run 'do-release-upgrade' to upgrade to it.
Last login: Wed Jun 9 04:27:18 2021 from 54.239.116.105
To run a command as administrator (user "root"), use "sudo <command>".
See "man sudo_root" for details.
ubuntu@ip-172-26-3-90:~$
-i 옵션으로 ssh 접속에 사용할 private key를 지정하여 접속한다.
Lightsail 포트 설정
Lightsail 인스턴스의 '관리' 메뉴에 들어간뒤. '네트워킹' 탭을 선택하면 위와같이 IPv4 방화벽에 두 가지 규칙이 존재한다.
- SSH : ssh 접속을 위한 22 포트
- HTTP : http 통신을 위한 80 포트
외부 연결을 위해 다른 포트도 열어야할 때가 있다. 예를들어 외부 MySQL 서버 연결을 위한 3306 포트라던지
'+ 규칙 추가' 버튼으로 직접 규칙을 추가할 수도 있지만, Terraform으로도 가능하다.
1. main.tf 에 소스코드 추가
resource "aws_lightsail_key_pair" "lightsail-test" { # lightsail-test라는 이름의 aws_lightsail_key_pair 라는 타입의 리소스를 정의
name = "lightsail-test" # 생성될 lightsail 키페어의 이름
public_key = file("./lightsail_key.pub") # 키페어에 사용할 public key 지정
}
# Create a new Lightsail Instance
resource "aws_lightsail_instance" "lightsail_test" {
name = "lightsail-test-instance"
availability_zone = "ap-northeast-2a" # seoul regin 'a'
blueprint_id = "ubuntu_18_04"
bundle_id = "micro_2_0"
key_pair_name = aws_lightsail_key_pair.lightsail-test.name
tags = {
Name = "my-lightsail"
}
}
resource "aws_lightsail_instance_public_ports" "lightsail_firewall_test" { # lightsail_firewall_test 라는 이름의 aws_lightsail_instance_public_ports 라는 타입의 리소스 정의
instance_name = aws_lightsail_instance.lightsail_test.name # 적용할 lightsail instance의 이름
# port information
port_info {
protocol = "tcp"
from_port = 80
to_port = 0
}
port_info {
protocol = "tcp"
from_port = 22
to_port = 0
}
port_info {
protocol = "tcp"
from_port = 3306
to_port = 0
}
}
'to_port'의 0 은 all 을 의미한다.
2. terraform plan 테스트
terraform plan
aws_lightsail_key_pair.lightsail-test: Refreshing state... [id=lightsail-test]
aws_lightsail_instance.lightsail_test: Refreshing state... [id=lightsail-test-instance]
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
+ create
Terraform will perform the following actions:
# aws_lightsail_instance_public_ports.lightsail_firewall_test will be created
+ resource "aws_lightsail_instance_public_ports" "lightsail_firewall_test" {
+ id = (known after apply)
+ instance_name = "lightsail-test-instance"
+ port_info {
+ cidrs = (known after apply)
+ from_port = 22
+ protocol = "tcp"
+ to_port = 0
}
+ port_info {
+ cidrs = (known after apply)
+ from_port = 3306
+ protocol = "tcp"
+ to_port = 0
}
+ port_info {
+ cidrs = (known after apply)
+ from_port = 80
+ protocol = "tcp"
+ to_port = 0
}
}
Plan: 1 to add, 0 to change, 0 to destroy.
------------------------------------------------------------------------
Note: You didn't specify an "-out" parameter to save this plan, so Terraform
can't guarantee that exactly these actions will be performed if
"terraform apply" is subsequently run.
3. terraform apply 수행
terraform apply
aws_lightsail_key_pair.lightsail-test: Refreshing state... [id=lightsail-test]
aws_lightsail_instance.lightsail_test: Refreshing state... [id=lightsail-test-instance]
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
+ create
Terraform will perform the following actions:
# aws_lightsail_instance_public_ports.lightsail_firewall_test will be created
+ resource "aws_lightsail_instance_public_ports" "lightsail_firewall_test" {
+ id = (known after apply)
+ instance_name = "lightsail-test-instance"
+ port_info {
+ cidrs = (known after apply)
+ from_port = 22
+ protocol = "tcp"
+ to_port = 0
}
+ port_info {
+ cidrs = (known after apply)
+ from_port = 3306
+ protocol = "tcp"
+ to_port = 0
}
+ port_info {
+ cidrs = (known after apply)
+ from_port = 80
+ protocol = "tcp"
+ to_port = 0
}
}
Plan: 1 to add, 0 to change, 0 to destroy.
Do you want to perform these actions?
Terraform will perform the actions described above.
Only 'yes' will be accepted to approve.
Enter a value: yes
aws_lightsail_instance_public_ports.lightsail_firewall_test: Creating...
aws_lightsail_instance_public_ports.lightsail_firewall_test: Creation complete after 3s [id=lightsail-test-instance-3944337474]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
4. Lightsail 방화벽 재확인
3306 포트가 추가된 것을 확인할 수 있다.
Lightsail 같은 경우, 특정 포트들을 특정 서비스에 쓰도록 정의되어 있다.
참고 : https://lightsail.aws.amazon.com/ls/docs/ko_kr/articles/understanding-firewall-and-port-mappings-in-amazon-lightsail
5. ssh 재접속 테스트
ssh 접속이 되어있는 상태에서 'exit'를 입력하여 종료한 뒤, 다시 ssh 접속을 해본다.
- logout
exit
logout
Connection to 3.36.111.181 closed.
- ssh login
ssh -i ./lightsail_key ubuntu@3.36.111.181
Welcome to Ubuntu 18.04.1 LTS (GNU/Linux 4.15.0-1021-aws x86_64)
* Documentation: https://help.ubuntu.com
* Management: https://landscape.canonical.com
* Support: https://ubuntu.com/advantage
System information as of Wed Jun 9 07:12:54 UTC 2021
System load: 0.0 Processes: 85
Usage of /: 2.7% of 38.71GB Users logged in: 0
Memory usage: 17% IP address for eth0: 172.26.3.90
Swap usage: 0%
* Super-optimized for small spaces - read how we shrank the memory
footprint of MicroK8s to make it the smallest full K8s around.
https://ubuntu.com/blog/microk8s-memory-optimisation
Get cloud support with Ubuntu Advantage Cloud Guest:
http://www.ubuntu.com/business/services/cloud
* Canonical Livepatch is available for installation.
- Reduce system reboots and improve kernel security. Activate at:
https://ubuntu.com/livepatch
0 packages can be updated.
0 updates are security updates.
New release '20.04.2 LTS' available.
Run 'do-release-upgrade' to upgrade to it.
Last login: Wed Jun 9 07:11:39 2021 from 113.198.137.97
To run a command as administrator (user "root"), use "sudo <command>".
See "man sudo_root" for details.
ubuntu@ip-172-26-3-90:~$
마무리
1 cpu, 1 GB 메모리면 사양이 좋은건 아니지만, ec2나 타 클라우드 서비스의 동일 사양 인스턴스의 사용 비용보다 훨씬 저렴한 편이다 (한달에 5달러- Micro 기준)
프리티어가 끝났다면, 한달 5천원으로 간단한 Jenkins 서버 정도는 돌릴 수 있을 것 같다.
ubuntu 같은 OS blueprint 이외에도 wordpress, nodejs, GitlabCE 등 다양한 어플리케이션을 제공하기 때문에 OS 인스턴스를 띄우고 거기에 또 wordpress, nodejs 같은 어플리케이션을 설치하는 수고를 덜 수 있다.
물론 이러한 방식의 사용법은 또 익혀야 겠지만...
간단한 웹서버, 실습용으로는 복잡한 EC2보다 Lightsail이 좋은것 같다. Terraform 코드도 보다 간단하다.
실습이 끝났으니 생성한 인스턴스 들을 제거한다.
- logout
exit
logout
Connection to 3.36.111.181 closed.
- terraform destroy
terraform destroy
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
- destroy
Terraform will perform the following actions:
# aws_lightsail_instance.lightsail_test will be destroyed
- resource "aws_lightsail_instance" "lightsail_test" {
- arn = "arn:aws:lightsail:ap-northeast-2:395389474517:Instance/9ce3c443-6ca2-454f-9cb3-85532df92aaa" -> null
- availability_zone = "ap-northeast-2a" -> null
- blueprint_id = "ubuntu_18_04" -> null
- bundle_id = "micro_2_0" -> null
- cpu_count = 1 -> null
- created_at = "2021-06-09T04:12:12Z" -> null
- id = "lightsail-test-instance" -> null
- ipv6_address = "2406:da12:40:1000:6bcb:65d5:4403:149d" -> null
- ipv6_addresses = [
- "2406:da12:40:1000:6bcb:65d5:4403:149d",
] -> null
- is_static_ip = false -> null
- key_pair_name = "lightsail-test" -> null
- name = "lightsail-test-instance" -> null
- private_ip_address = "172.26.3.90" -> null
- public_ip_address = "3.36.111.181" -> null
- ram_size = 1 -> null
- tags = {
- "Name" = "my-lightsail"
} -> null
- tags_all = {
- "Name" = "my-lightsail"
} -> null
- username = "ubuntu" -> null
}
# aws_lightsail_instance_public_ports.lightsail_firewall_test will be destroyed
- resource "aws_lightsail_instance_public_ports" "lightsail_firewall_test" {
- id = "lightsail-test-instance-3944337474" -> null
- instance_name = "lightsail-test-instance" -> null
- port_info {
- cidrs = [
- "0.0.0.0/0",
] -> null
- from_port = 22 -> null
- protocol = "tcp" -> null
- to_port = 22 -> null
}
- port_info {
- cidrs = [
- "0.0.0.0/0",
] -> null
- from_port = 3306 -> null
- protocol = "tcp" -> null
- to_port = 3306 -> null
}
- port_info {
- cidrs = [
- "0.0.0.0/0",
] -> null
- from_port = 80 -> null
- protocol = "tcp" -> null
- to_port = 80 -> null
}
}
# aws_lightsail_key_pair.lightsail-test will be destroyed
- resource "aws_lightsail_key_pair" "lightsail-test" {
- arn = "arn:aws:lightsail:ap-northeast-2:395389474517:KeyPair/0521c4c3-4d57-491d-a1e5-7259c92669e4" -> null
- fingerprint = "82:da:24:62:42:56:07:c1:02:de:89:fd:f8:6f:f7:38" -> null
- id = "lightsail-test" -> null
- name = "lightsail-test" -> null
- public_key = <<-EOT
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDWNVVArryuJmGyi6JQcf3cz+Agu3fyiPMJdwerZzzrPRY7vbs0Xj5cdkXBXif3P4yJIkjli/rReOlZnSR4/DwA2WlmCqBa/VXp/f5e58gYvwm32Q8gCvscTk1Ne7t4Sb+Url3g9OI5Er7os8rrGVVP8cK35DxRgbsjd7cQRdN4YS9XmBsH7A58SG53OwsziHlBVkWxMFNmk71fdhqtgDxGNgH+jsF18qDYvKeXdZBEzQmwWEFKPovC6mXrummxC0SXrS2D9FsJ3YqhDNskAa7IadWVwwDOaw158fGo5FtyLrmEjDyL6bgq7FyC8ZiihCi2Z2eAHYSNdJsd316nZ4uR vagrant@ubuntu100
EOT -> null
}
Plan: 0 to add, 0 to change, 3 to destroy.
Do you really want to destroy all resources?
Terraform will destroy all your managed infrastructure, as shown above.
There is no undo. Only 'yes' will be accepted to confirm.
Enter a value: yes
aws_lightsail_instance_public_ports.lightsail_firewall_test: Destroying... [id=lightsail-test-instance-3944337474]
aws_lightsail_instance_public_ports.lightsail_firewall_test: Destruction complete after 5s
aws_lightsail_instance.lightsail_test: Destroying... [id=lightsail-test-instance]
aws_lightsail_instance.lightsail_test: Destruction complete after 6s
aws_lightsail_key_pair.lightsail-test: Destroying... [id=lightsail-test]
aws_lightsail_key_pair.lightsail-test: Destruction complete after 7s
Destroy complete! Resources: 3 destroyed.
Advanced
고정 아이피가 부여되고, docker가 설치된 상태로 Lightsail 인스턴스를 생성하는 예제.
나중에 시간되면 추가해봐야지
'Infra' 카테고리의 다른 글
[Ansible] ubuntu에서 ansible playbook을 이용한 nginx 설치 및 삭제 (0) | 2021.06.11 |
---|---|
[Ansible] ssh key 관련 정리 - ansible 명령어에 private key 지정 (0) | 2021.06.11 |
[Terraform] AWS - 보안그룹 out boud 규칙 - egress all 설정 (0) | 2021.06.07 |
[Terraform] AWS - EC2 Keypair RDS 생성 테스트 (0) | 2021.06.07 |
[Ansible] Ubuntu Ansible 설치 (0) | 2021.04.07 |