AWS IoT 개체 생성 + 통신하기

다넌·2022년 11월 3일
0

본격적으로 로그를 올리기에 앞서 EC2를 새로 생성하여 처음부터 진행해 보았다.


1. EC2 접속

AWS CLI를 사용하기 위해선 최초 1회 aws configure 정보를 등록해줘야 한다.

각자 환경에 맞춰 입력해준다. (output format 생략 가능)

혹시나 액세스 키를 모르실 경우 Access keys 링크 참고 바랍니다. 본문에 아래처럼 나와 있습니다.

You provide your AWS access keys to make programmatic calls to AWS or to use the AWS Command Line Interface or AWS Tools for PowerShell.



2. 모듈 세팅

mqtt로 통신하기 위해서는 mosquitto 패키지를 서버에 설치해주어야 한다. > sudo yum install mosquitto

그러나 위와 같은 오류가 뜰 경우 다음 명령을 사전에 실행해준다.> sudo amazon-linux-extras install epel

필요 시 sudo yum install openssl 까지 설치한다.



3. 인증서 생성

디바이스와 AWS 간 통신을 위해서는 x.509 인증이 필요하다.


= 인증서를 맞춰주지 않을 경우 저처럼 무수한 통신 오류를 맞닥뜨리기 때문에 꼭 조심해주세요 ..


설명서의 Provisioning with the API를 참고합니다.

저는 IoT Core에서 사물을 미리 만들어 둔 상태였기 때문에 aws iot create-thing --thing-name $THING_NAME 는 생략했습니다.


그 후 아래 부분을 따라가 주시면 됩니다.

aws iot create-keys-and-certificate --set-as-active \
  --public-key-outfile $THING_NAME.public.key \
  --private-key-outfile $THING_NAME.private.key \
  --certificate-pem-outfile $THING_NAME.certificate.pem > /tmp/create_cert_and_keys_response
# $THING_NAME에는 사물 이름을 넣어주세요


# look at the output from the previous command
cat /tmp/create_cert_and_keys_response

# output values from the previous call needed in further steps
# 마찬가지로 jq 오류 시 설치 > sudo yum -y install jq

CERTIFICATE_ARN=$(jq -r ".certificateArn" /tmp/create_cert_and_keys_response)
CERTIFICATE_ID=$(jq -r ".certificateId" /tmp/create_cert_and_keys_response)
echo $CERTIFICATE_ARN
echo $CERTIFICATE_ID


# create an IoT policy
# 정책명은 임의로 생성하셔도 되고 or 기존에 있는 정책 연결해도 됩니다
POLICY_NAME=${THING_NAME}_Policy

aws iot create-policy --policy-name $POLICY_NAME \
  --policy-document '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action": "iot:*","Resource":"*"}]}'

# attach the policy to your certificate
aws iot attach-policy --policy-name $POLICY_NAME \
  --target $CERTIFICATE_ARN

# attach the certificate to your thing
aws iot attach-thing-principal --thing-name $THING_NAME \
  --principal $CERTIFICATE_ARN

4. 완료

여기까지 하셨으면 정상적으로 mqtt 통신이 가능합니다.

mosquitto_pub 명령으로 테스트 해보시거나 AWS에서 제공하는 파이썬 모듈 설치해서 테스트 해보시면 됩니다. (다음 포스트)

0개의 댓글