TerraformPilot

DevOps

Terraform for FreeRTOS IoT Cloud on AWS IoT Core

Provision AWS IoT Core for FreeRTOS devices with Terraform: thing types, policies, certificates, jobs for OTA, and Greengrass core devices.

LLuca Berton1 min read

FreeRTOS is the Amazon-stewarded RTOS for microcontrollers. Pairing FreeRTOS devices with AWS IoT Core gives you MQTT, device shadows, Jobs for OTA, and Defender. Terraform owns all of it: thing types, policies, certificates, jobs, and rules.

Thing Type and Policy

#
resource "aws_iot_thing_type" "sensor" {
  name = "freertos-sensor-v1"
 
  properties {
    description           = "FreeRTOS temperature sensor"
    searchable_attributes = ["firmware_version", "site"]
  }
}
 
resource "aws_iot_policy" "sensor" {
  name = "freertos-sensor-policy"
 
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Effect = "Allow"
        Action = ["iot:Connect"]
        Resource = "arn:aws:iot:${var.region}:${data.aws_caller_identity.me.account_id}:client/$${iot:ClientId}"
      },
      {
        Effect = "Allow"
        Action = ["iot:Publish"]
        Resource = "arn:aws:iot:${var.region}:${data.aws_caller_identity.me.account_id}:topic/devices/$${iot:Connection.Thing.ThingName}/telemetry"
      }
    ]
  })
}

OTA Job

#
resource "aws_iot_job" "ota" {
  job_id = "ota-${var.fw_version}"
 
  targets = [aws_iot_thing_group.production.arn]
  document = jsonencode({
    operation = "ota"
    file_url  = "https://${aws_s3_bucket.fw.bucket_regional_domain_name}/v${var.fw_version}.bin"
    sha256    = var.fw_sha256
  })
 
  job_executions_rollout_config {
    maximum_per_minute = 50
  }
  abort_config {
    criteria_list {
      action          = "CANCEL"
      failure_type    = "FAILED"
      min_number_of_executed_things = 100
      threshold_percentage          = 10.0
    }
  }
}

Defender Audit

#
resource "aws_iot_account_audit_configuration" "this" {
  account_id = data.aws_caller_identity.me.account_id
  role_arn   = aws_iam_role.iot_audit.arn
 
  audit_check_configurations {
    name    = "DEVICE_CERTIFICATE_KEY_QUALITY_CHECK"
    enabled = true
  }
}

Best Practices

#
  • Per-device X.509 certs, never shared keys.
  • Policy templating with ${iot:Connection.Thing.ThingName} prevents one device from publishing as another.
  • OTA abort thresholds — kill bad rollouts at 10% failure.
  • Defender audit on a schedule — weakly-keyed devices get spotted automatically.
#
#Terraform#FreeRTOS#AWS IoT Core#OTA#MQTT

Share this article