IoT infrastructure in Azure with Terraform, seamlessly integrating with existing backend resources.
This Terraform script automates the deployment of an IoT-based smart farming system on Azure. The setup includes:
- IoT Hub → Serves as the MQTT broker for ESP32-based devices.
- Cosmos DB (MongoDB API) → Stores IoT sensor data.
- Azure Function App → Processes messages from IoT Hub and stores them in Cosmos DB.
- Storage Account → Used for function logs and metadata storage.
Note: Device Provisioning Service (DPS) can be included in future, to automate device registrations.
Before running Terraform, ensure that you have:
- Terraform installed (
>=1.3
) - Azure CLI authenticated (
az login
) - An active Azure Subscription (e.g., "Azure for Students")
terraform init
terraform plan
terraform apply -auto-approve
Check deployed resources in Azure:
terraform state list
az iot hub device-identity create --hub-name azurefarming-iothub --device-id ESP32-Device
az iot hub device-identity show-connection-string --hub-name azurefarming-iothub --device-id ESP32-Device
Simulate an ESP32 device sending telemetry:
curl -X POST https://azurefarming-function.azurewebsites.net/api/iot_event_handler -H "Content-Type: application/json" -d '{"temperature": 25, "humidity": 50}'
Once the Azure Function is deployed, the backend API can fetch IoT device status:
curl -X GET "https://azurefarming-function.azurewebsites.net/api/device/{device_id}/status"
The web application can send control commands (e.g., turning on water pumps):
curl -X POST "https://azurefarming-function.azurewebsites.net/api/device/{device_id}/command" \
-H "Content-Type: application/json" \
-d '{"command": "water_on"}'
To remove all deployed Azure resources:
terraform destroy -auto-approve
✅ Modular Deployment → IoT Hub, Cosmos DB, and Functions are separately deployed for flexibility.
✅ Scalable → The system is designed to handle multiple devices and large data volumes.
✅ Web-Ready → The function API exposes IoT data to web and mobile applications.
✅ Secure Communication → IoT Hub ensures authenticated MQTT messaging for devices.
1️⃣ Run the Terraform script ✅
2️⃣ Test MQTT communication with IoT Hub
3️⃣ Verify that IoT data is being stored in Cosmos DB
4️⃣ Expose the Function API for frontend integration