현재 진행 중인 팀프로젝트로 SQS를 사용하는데, 이를 구현하면서 만난 문제를 소개합니다.
현재 구현하고자 하는 클라우드 환경은 위의 그림과 같습니다.
드론에서 데이터를 수집하고 이 데이터를 클라우드로 전송하는 과정을 구현하는데 실시간 데이터 처리를 위해 SQS를 사용하고 있습니다.
전체적인 과정은 프로젝트가 완료되고 정리하도록 하겠습니다.
SQS Docs Sample code
import boto3
# Create SQS client
sqs = boto3.client('sqs')
queue_url = 'SQS_QUEUE_URL'
# Send message to SQS queue
response = sqs.send_message(
QueueUrl=queue_url,
DelaySeconds=10,
MessageAttributes={
'Title': {
'DataType': 'String',
'StringValue': 'The Whistler'
},
'Author': {
'DataType': 'String',
'StringValue': 'John Grisham'
},
'WeeksOn': {
'DataType': 'Number',
'StringValue': '6'
}
},
MessageBody=(
'Information about current NY Times fiction bestseller for '
'week of 12/11/2016.'
)
)
print(response['MessageId'])
위의 코드는 Boto3 Docs를 보면 나오는 SQS Send Example code입니다.
처음 이를 보고 IAM 관련 정보를 입력받지 않길래, 의아해 했습니다.
이전에 s3에 데이터를 올리는 작업에서는 IAM정보를 입력했던 것과 차이가 있었거든요.
import boto3
# Create SQS client
sqs = boto3.client('sqs')
queue_url = 'SQS_QUEUE_URL'
# Send message to SQS queue
response = sqs.send_message(
QueueUrl=queue_url,
MessageBody="sqs_test"
)
print(response['MessageId'])
필요하지 않은 코드는 삭제하고나니 위의 코드만 남더라구요.
이를 실행하니 오류가 2개 발견되었습니다.
먼저 region설정을 하라고 하는 오류가 생겼습니다.
region_name 정의하기
import boto3
# Create SQS client
sqs = boto3.client('sqs', region_name='ap-northeast-2')
queue_url = 'SQS_QUEUE_URL'
# Send message to SQS queue
response = sqs.send_message(
QueueUrl=queue_url,
MessageBody="sqs_test"
)
print(response['MessageId'])
이는 이전에도 만난적 있는 오류라 가볍게 해결했습니다.
client를 정의할 때, region_name에 사용할 sqs 리전을 입력해주면 해결되는 문제였습니다.
나머지 하나는 예상했던 것 같이 IAM 관련 정보 입력이였습니다.
CLI를 통해 하는 것이 아닌경우, AWS SDK에 의해 정의를 해야하더라구요.
IAM 정보 정의하기
본 내용은 Linux에 적용하는 방법입니다.
기본적으로 SDK를 이용할 때, 사용하는 파일은 ~/.aws/credentials
입니다.
만약 폴더 및 파일이 없다면, 해당 경로에 폴더 및 파일을 생성하면됩니다.
이후 credentials에 IAM관련 정보를 정의합니다.
[default] ; default Profile section information
aws_access_key_id = YOUR_ACCESS_KEY1
aws_secret_access_key = YOUR_SECRET_KEY1
정확히는 ini파일이라고, initialization 파일로 부르더라구요.
위의 형식대로 설정해서 사용하면됩니다.
[Profile1]
aws_access_key_id = YOUR_ACCESS_KEY1
aws_secret_access_key = YOUR_SECRET_KEY1
저는 Profile1 이라는 이름을 사용하여 정의했습니다.
boto3에 정의하기
import boto3
import os
os.environ['AWS_PROFILE'] = "Profile1"
sqs = boto3.client('sqs', region_name='ap-northeast-2')
queue_url = "https://sqs.ap-northeast-2.amazonaws.com/996145069080/edge_data"
def send_message(message):
response = sqs.send_message(QueueUrl=queue_url,
MessageBody=message)
send_message("send message : hello world")
os 파이썬 내장라이브러리를 이용해서 이를 호출해주면 됩니다.
os.environ['AWS_PROFILE'] = "Profile1"
이렇게 코드를 작성하면, .aws/credentials에서 정의한 값을 가져옵니다.
이렇게 하니 정상적으로 sqs에 전송되는 것을 확인했습니다.
- region_name 같은경우도 ,default 로 정의하면 client 정의할때 추가로 적지 않아도 되는 것 같습니다.