Managing DNS Records with AWS Route 53
#1 웹 서비스를 제공하는 인스턴스 두 개를 생성
서비스 인스턴스 구분을 위해서 index.html 파일에 인스턴스의 IP 주소를 추가
$ sudo vi /var/www/html/index.html
: <h1>Test Page @ 해당_인스턴스의_IP주소</h1> : |
#2 로드밸런서 생성
#3 DNS 설정
도메인 주소로 접근했을 때 서비스가 되지 않는 것을 확인 ⇒ IP 주소로 맵핑이 되지 않았기 때문
A(Address Record) 유형의 레코드를 추가 ⇒ 별칭을 이용해서 로드밸런스를 연결
도메인 주소로 서비스 접속 여부를 확인
AWS ELB Connectivity Troubleshooting Scenario
#1 인스턴스 확인
#2 인스턴스의 퍼블릭 IP로 접근했을 때 서비스되는 것을 확인
#3 로드밸런스 확인
#4 로드밸런스의 DNS 이름으로 접속되지 않는 것을 확인
연결할 수 없다 ⇒ 서비스 포트로 접속할 수 없다 ⇒ 서비스 포트로 서비스 되고 있지 않거나, 방화벽 등으로 차단된 경우
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
해당 인스턴스로 직접 접속했을 때는 서비스 되는 것을 확인
#5 로드밸런스의 보안그룹 설정을 확인 ⇒ 인바운드 규칙에 80 포트가 빠져 있음
#6 다시, 로드밸런스의 DNS 이름으로 접속되지 않는 것을 확인
#7 인스턴스의 상태를 점검 ⇒ OutOfService ⇒ 인스턴스로 직접 접속했을 때는 서비스되는 것을 확인 ⇒ 헬스체크 로직이 잘못되었음
#8 로드밸런스의 상태검사(health check) 설정을 확인 ⇒ 서비스 포트가 아닌 다른 포트로 헬스체크를 수행
서비스 포트(80)로 헬스체크 대상을 변경
#9 인스턴스의 상태가 InService로 변경된 것을 확인
#10 로드밸런스가 정상적으로 동작하는 것을 확인
Creating an Amazon Aurora RDS Database (MySQL Compatible)
https://learn.acloud.guru/handson/dfd4c330-f9e9-465d-a69b-b9211c7f9903
SSH Hostname: Public Subnet에 위치한 EC2 인스턴스의 퍼블릭 IP
SSH Key File: EC2 인스턴스 생성 시 발행된 개인키 파일
MySQL Hostname: 쓰기 유형의 DB 엔드포인트
AWS DynamoDB in the Console - Creating Tables, Items, and Indexes
DynamoDB
완벽하게 관리되는 NoSQL 데이터베이스 서비스
~~~~~~~~~~~~~ ⇒ 운영에 오버헤드가 없어짐
-
배포가 단순하고 신속
-
확장이 단순하고 신속
-
데이터를 자동으로 백업
-
빠르고 일관된 응답 시간을 제공
-
보조 인덱스를 통한 빠른 조회
-
사용한 만큼 지불
핵심 구성요소(Core Components)
-
table
-
itmes(항목)
-
attributes(속성)
Person 테이블
-
PersonID가 102인 항목은 Address 속성으로 끝나고, PersonID가 103인 항목은 FavoriteColor 속성으로 끝남 ⇒ 기본 키(Primary Key)를 제외하고는 스키마가 없다
-
대부분의 속성은 스칼라(scalar)로 문자열 또는 숫자 같이 하나의 값만 가질 수 있으며, Address 처럼 내포 속성을 가질 수 있음 (DynamoDB는 32depth까지만 지원)
기본 키(Primary Key)
테이블의 각 항목을 나타내는 고유한 식별자 = 동일한 키를 가질 수 없음
-
단순 기본 키 = 파티션 키 하나로 구성
-
일치(equal) 방식의 검색만 가능
-
복합 기본 키 = 파티션 키와 정렬 키로 구성
-
일치, 부등호, 포함 등의 범위를 지정한 검색을 지원
첫번째 항목과 두번째 항목의 파티션 키(Artist)가 동일하므로, 항목을 구분할 수 있도록 SongTitle이라는 정렬키를 추가
보조 인덱스(Secondary Index)
-
테이블에서는 하나 이상의 보조 인덱스를 생성할 수 있음
-
보조 인덱스를 사용하면 기본 키에 대한 쿼리 외에 대체 키를 사용해서 테이블의 데이터를 쿼리할 수 있음
-
DynamoDB에서는 각 테이블에 20개의 Global Secondary Index와 5개의 Local Secondary Index를 제공
Global Secondary Index
-
파티션 키 및 정렬 키가 테이블의 파티션 키 및 정렬 키와 다를 수 있는 인덱스
Local Secondary Index
-
테이블과 파티션 키는 동일하지만 정렬 키는 다른 인덱스
Python을 사용하여 DynamoDB 테이블 쿼리 및 관리
https://aws.amazon.com/ko/getting-started/hands-on/create-manage-nonrelational-database-dynamodb/
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb.html
#1 PC에서 PowerShell 실행 후 AWS CLI 설치 확인
PS C:\dynamodb> aws --version
aws-cli/2.1.27 Python/3.7.9 Windows/10 exe/AMD64 prompt/off
설치되어 있지 않은 경우 아래 URL에서 다운로드 후 설치
https://docs.aws.amazon.com/ko_kr/cli/latest/userguide/install-cliv2-windows.html
#2 boto3 설치
PS C:\dynamodb> pip install boto3
#3 AWS DynamoDB in the Console - Creating Tables, Items, and Indexes 랩 시작
#4 IAM에서 cloud_user 사용자의 액세스 키 생성
생성한 액세스 키는 csv 파일 다운로드를 통해 보관
#5 aws configure 명령어로 액세스 키와 리전 정보를 설정
PS C:\dynamodb> aws configure
AWS Access Key ID [****************C3U3]: AKIAWUML4UQXD4EO3EGR
AWS Secret Access Key [****************FAoZ]: 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
Default region name [us-east-1]: us-east-1
Default output format [None]:
#6 DynamoDB 테이블 생성
c:\dynamodb\create_table.py
import boto3 # boto3 is the AWS SDK library for Python. # We can use the low-level client to make API calls to DynamoDB. client = boto3.client('dynamodb', region_name='us-east-1') try: resp = client.create_table( TableName="Books", # Declare your Primary Key in the KeySchema argument KeySchema=[ { "AttributeName": "Author", "KeyType": "HASH" }, { "AttributeName": "Title", "KeyType": "RANGE" } ], # Any attributes used in KeySchema or Indexes must be declared in AttributeDefinitions AttributeDefinitions=[ { "AttributeName": "Author", "AttributeType": "S" }, { "AttributeName": "Title", "AttributeType": "S" } ], # ProvisionedThroughput controls the amount of data you can read or write to DynamoDB per second. # You can control read and write capacity independently. ProvisionedThroughput={ "ReadCapacityUnits": 1, "WriteCapacityUnits": 1 } ) print("Table created successfully!") except Exception as e: print("Error creating table:") print(e) |
PS C:\dynamodb> python .\create_table.py
Table created successfully!
아래 AWS CLI 명령어와 동일한 결과
PS C:\dynamodb> aws dynamodb create-table --table-name Books --attribute-definitions AttributeName=Author,AttributeType=S AttributeName=Title,AttributeType=S --key-schema AttributeName=Author,KeyType=HASH AttributeName=Title,KeyType=RANGE --provisioned-throughput ReadCapacityUnits=1,WriteCapacityUnits=1 { "TableDescription": { "AttributeDefinitions": [ { "AttributeName": "Author", "AttributeType": "S" }, { "AttributeName": "Title", "AttributeType": "S" } ], "TableName": "Books", "KeySchema": [ { "AttributeName": "Author", "KeyType": "HASH" }, { "AttributeName": "Title", "KeyType": "RANGE" } ], "TableStatus": "CREATING", "CreationDateTime": "2021-03-03T17:40:42.486000+09:00", "ProvisionedThroughput": { "NumberOfDecreasesToday": 0, "ReadCapacityUnits": 1, "WriteCapacityUnits": 1 }, "TableSizeBytes": 0, "ItemCount": 0, "TableArn": "arn:aws:dynamodb:us-east-1:456096785454:table/Books", "TableId": "c8ac2e84-77c0-4de4-abd7-f40e9f9e2935" } } |
PS C:\dynamodb> aws dynamodb list-tables
{
"TableNames": [
"Books", ⇐ 테이블이 생성된 것을 확인
"MusicExample"
]
}
#7 Books 테이블에 항목을 로드
c:\dynamodb\insert_items.py
import boto3 # boto3 is the AWS SDK library for Python. # The "resources" interface allow for a higher-level abstraction than the low-level client interface. # More details here: http://boto3.readthedocs.io/en/latest/guide/resources.html dynamodb = boto3.resource('dynamodb', region_name='us-east-1') table = dynamodb.Table('Books') # The BatchWriteItem API allows us to write multiple items to a table in one request. with table.batch_writer() as batch: batch.put_item(Item={"Author": "John Grisham", "Title": "The Rainmaker", "Category": "Suspense", "Formats": { "Hardcover": "J4SUKVGU", "Paperback": "D7YF4FCX" } }) batch.put_item(Item={"Author": "John Grisham", "Title": "The Firm", "Category": "Suspense", "Formats": { "Hardcover": "Q7QWE3U2", "Paperback": "ZVZAYY4F", "Audiobook": "DJ9KS9NM" } }) batch.put_item(Item={"Author": "James Patterson", "Title": "Along Came a Spider", "Category": "Suspense", "Formats": { "Hardcover": "C9NR6RJ7", "Paperback": "37JVGDZG", "Audiobook": "6348WX3U" } }) batch.put_item(Item={"Author": "Dr. Seuss", "Title": "Green Eggs and Ham", "Category": "Children", "Formats": { "Hardcover": "GVJZQ7JK", "Paperback": "A4TFUR98", "Audiobook": "XWMGHW96" } }) batch.put_item(Item={"Author": "William Shakespeare", "Title": "Hamlet", "Category": "Drama", "Formats": { "Hardcover": "GVJZQ7JK", "Paperback": "A4TFUR98", "Audiobook": "XWMGHW96" } }) |
PS C:\dynamodb> python .\insert_items.py
#8 Books 테이블에 항목을 검색
c:\dynamodb\get_item.py
import boto3 # boto3 is the AWS SDK library for Python. # The "resources" interface allow for a higher-level abstraction than the low-level client interface. # More details here: http://boto3.readthedocs.io/en/latest/guide/resources.html dynamodb = boto3.resource('dynamodb', region_name='us-east-1') table = dynamodb.Table('Books') # When making a GetItem call, we specify the Primary Key attributes defined on our table for the desired item. resp = table.get_item(Key={"Author": "John Grisham", "Title": "The Rainmaker"}) print(resp['Item']) |
PS C:\dynamodb> python .\get_item.py
{'Title': 'The Rainmaker', 'Formats': {'Hardcover': 'J4SUKVGU', 'Paperback': 'D7YF4FCX'}, 'Author': 'John Grisham', 'Category': 'Suspense'}
#9 하나의 쿼리로 여러 항목 검색
c:\dynamodb\query_items.py
import boto3 from boto3.dynamodb.conditions import Key # boto3 is the AWS SDK library for Python. # The "resources" interface allows for a higher-level abstraction than the low-level client interface. # For more details, go to http://boto3.readthedocs.io/en/latest/guide/resources.html dynamodb = boto3.resource('dynamodb', region_name='us-east-1') table = dynamodb.Table('Books') # When making a Query API call, we use the KeyConditionExpression parameter to specify the hash key on which we want to query. # We're using the Key object from the Boto3 library to specify that we want the attribute name ("Author") # to equal "John Grisham" by using the ".eq()" method. resp = table.query(KeyConditionExpression=Key('Author').eq('John Grisham')) print("The query returned the following items:") for item in resp['Items']: print(item) |
PS C:\dynamodb> python .\query_items.py
The query returned the following items:
{'Title': 'The Firm', 'Formats': {'Hardcover': 'Q7QWE3U2', 'Paperback': 'ZVZAYY4F', 'Audiobook': 'DJ9KS9NM'}, 'Author': 'John Grisham', 'Category': 'Suspense'}
{'Title': 'The Rainmaker', 'Formats': {'Hardcover': 'J4SUKVGU', 'Paperback': 'D7YF4FCX'}, 'Author': 'John Grisham', 'Category': 'Suspense'}
#10 보조 인덱스 생성
c:\dynamodb\add_secondary_index.py
import boto3 # Boto3 is the AWS SDK library for Python. # We can use the low-level client to make API calls to DynamoDB. client = boto3.client('dynamodb', region_name='us-east-1') try: resp = client.update_table( TableName="Books", # Any attributes used in our new global secondary index must be declared in AttributeDefinitions AttributeDefinitions=[ { "AttributeName": "Category", "AttributeType": "S" }, ], # This is where we add, update, or delete any global secondary indexes on our table. GlobalSecondaryIndexUpdates=[ { "Create": { # You need to name your index and specifically refer to it when using it for queries. "IndexName": "CategoryIndex", # Like the table itself, you need to specify the key schema for an index. # For a global secondary index, you can do a simple or composite key schema. "KeySchema": [ { "AttributeName": "Category", "KeyType": "HASH" } ], # You can choose to copy only specific attributes from the original item into the index. # You might want to copy only a few attributes to save space. "Projection": { "ProjectionType": "ALL" }, # Global secondary indexes have read and write capacity separate from the underlying table. "ProvisionedThroughput": { "ReadCapacityUnits": 1, "WriteCapacityUnits": 1, } } } ], ) print("Secondary index added!") except Exception as e: print("Error updating table:") print(e) |
PS C:\dynamodb> python .\add_secondary_index.py
Secondary index added!
AWS 관리형 콘솔에서는 아래와 같은 설정과 동일
#11 보조 인덱스 쿼리
c:\dynamodb\query_with_index.py
import time import boto3 from boto3.dynamodb.conditions import Key # Boto3 is the AWS SDK library for Python. # The "resources" interface allows for a higher-level abstraction than the low-level client interface. # For more details, go to: http://boto3.readthedocs.io/en/latest/guide/resources.html dynamodb = boto3.resource('dynamodb', region_name='us-east-1') table = dynamodb.Table('Books') # When adding a global secondary index to an existing table, you cannot query the index until it has been backfilled. # This portion of the script waits until the index is in the “ACTIVE” status, indicating it is ready to be queried. while True: if not table.global_secondary_indexes or table.global_secondary_indexes[0]['IndexStatus'] != 'ACTIVE': print('Waiting for index to backfill...') time.sleep(5) table.reload() else: break # When making a Query call, we use the KeyConditionExpression parameter to specify the hash key on which we want to query. # If we want to use a specific index, we also need to pass the IndexName in our API call. resp = table.query( # Add the name of the index you want to use in your query. IndexName="CategoryIndex", KeyConditionExpression=Key('Category').eq('Suspense'), ) print("The query returned the following items:") for item in resp['Items']: print(item) |
PS C:\dynamodb> python .\query_with_index.py
The query returned the following items:
{'Title': 'The Firm', 'Formats': {'Hardcover': 'Q7QWE3U2', 'Paperback': 'ZVZAYY4F', 'Audiobook': 'DJ9KS9NM'}, 'Author': 'John Grisham', 'Category': 'Suspense'}
{'Title': 'The Rainmaker', 'Formats': {'Hardcover': 'J4SUKVGU', 'Paperback': 'D7YF4FCX'}, 'Author': 'John Grisham', 'Category': 'Suspense'}
{'Title': 'Along Came a Spider', 'Formats': {'Hardcover': 'C9NR6RJ7', 'Paperback': '37JVGDZG', 'Audiobook': '6348WX3U'}, 'Author': 'James Patterson', 'Category': 'Suspense'}
#12 테이블 삭제
c:\dynamodb\delete_table.py
import boto3 client = boto3.client('dynamodb', region_name='us-east-1') try: resp = client.delete_table( TableName="Books", ) print("Table deleted successfully!") except Exception as e: print("Error deleting table:") print(e) |
PS C:\dynamodb> python .\delete_table.py
Table deleted successfully!
PS C:\dynamodb> aws dynamodb list-tables
{
"TableNames": [
"MusicExample"
]
}
'CLOUD > AWS' 카테고리의 다른 글
3/5 - A Cloud Guru를 이용한 AWS 6차시 (0) | 2021.03.05 |
---|---|
3/4 - A Cloud Guru를 이용한 AWS 5차시 (0) | 2021.03.04 |
3/2 - A Cloud Guru를 이용한 AWS 3차시 (0) | 2021.03.02 |
2/26 - A Cloud Guru를 이용한 AWS 2차시 (0) | 2021.02.26 |
2/25 - A Cloud Guru를 이용한 AWS 1차시 (0) | 2021.02.26 |