terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.92"
}
}
}
provider "aws" {
region = "ap-northeast-2"
}
resource "aws_iot_thing" "rasberry" {
name = "rasberry"
}
resource "aws_iot_certificate" "cert" {
active = true
}
resource "aws_iot_policy" "pub" {
name = "PublishOnlyPolicy"
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect = "Allow"
Action = [
"iot:Connect",
"iot:Publish"
]
Resource = "*"
}
]
})
}
resource "aws_iot_policy_attachment" "attach" {
policy = aws_iot_policy.pub.name
target = aws_iot_certificate.cert.arn
}
resource "aws_iot_thing_principal_attachment" "attach_thing" {
thing = aws_iot_thing.rasberry.name
principal = aws_iot_certificate.cert.arn
}
data "aws_iot_endpoint" "endpoint" {
endpoint_type = "iot:Data-ATS"
}
output "iot_endpoint" {
value = data.aws_iot_endpoint.endpoint.endpoint_address
description = "MQTT broker endpoint"
}
output "certificate_pem" {
value = aws_iot_certificate.cert.certificate_pem
sensitive = true
}
output "private_key" {
value = aws_iot_certificate.cert.private_key
sensitive = true
}
resource "local_file" "cert" {
content = aws_iot_certificate.cert.certificate_pem
filename = "/home/woosupar/mqtt-terra/certs/cert.pem"
}
resource "local_file" "key" {
content = aws_iot_certificate.cert.private_key
filename = "/home/woosupar/mqtt-terra/certs/private.key"
file_permission = "0600"
}
aws_iot_policy_attachment
aws_iot_certificate 로 생성된 cert 리소스 객체의 arn을 이용하여 생성되는 iot policy와 연결한다.
aws_iot_endpoint
aws가 생성한 IoT 엔드포인트의 url을 가져온다.
output “iot_endpoint”
output으로 등록된 객체는 terraform output 명령어를 사용해서 실제 값을 확인 할 수 있다.
현재 구성하려는 구조에서 thing과 thing-cert 간 연결은 필수는 아니다. mqtt broker 역할을 할 IoT core는 인증서와 policy만 있으면 연격을 할 수 있다. 하지만 thing을 등록하면 shadow, job같은 기능을 추가로 사용할 수 있고, 콘솔로 원활한 관리가 가능해진다.
여기까지 작성한 terraform 파일을 가지고 apply를 실행하면 구성한대로 등록된 것을 aws console을 통해 확인할 수 있었다.
curl https://www.amazontrust.com/repository/AmazonRootCA1.pem -o ca.pem
해당 명령어로 aws 인증서를 받아준다. 해당 인증서는 tls 인증 과정에서 aws임을 식별하는데 사용한다.
지금까지의 과정을 보면 알 수 있듯이, IoT Core는 생각보다 단순하다. IoT Core는 mqtt broker 엔드포인트를 제공하고, 이 엔드포인트로 메시지를 pub하는 것이 전부이다. 이 과정에서 인증서와 policy로 보안을 강화하는 과정이 있을 뿐이다.
이후, 기존에 사용했던 mass_publisher.py 를 약간 수정하여 IoT Core로 메시지를 발행하도록 했고 잘 작동하는 것을 확인했다.
답글 남기기