Thursday, September 17, 2026

MongoDB with Microsoft Azure and ASP.NET Core – Complete End-to-End Guide with Real-Time E-Commerce Example

Introduction

Modern applications often need a database that can handle:

  • Large volumes of data

  • Rapidly changing data structures

  • High read/write workloads

  • Horizontal scalability

  • JSON-based application data

  • Microservices architectures

  • Event-driven applications

MongoDB is a popular NoSQL document database designed for these types of workloads.

When MongoDB is deployed using MongoDB Atlas on Microsoft Azure, we can build a cloud-native architecture where:

Angular / React / Mobile
          |
          v
     Azure Front Door
          |
          v
 Azure API Management
          |
          v
 ASP.NET Core Web API
          |
          v
     MongoDB Atlas
       on Azure

MongoDB Atlas is MongoDB's fully managed cloud database service, and Atlas supports Microsoft Azure as a cloud provider. (MongoDB)


1. What is MongoDB?

MongoDB is a NoSQL document-oriented database.

Unlike SQL Server, where data is normally organized as:

Database
   |
   +-- Tables
          |
          +-- Rows

MongoDB organizes data as:

Database
   |
   +-- Collections
          |
          +-- Documents

A MongoDB document looks similar to JSON:

{
  "customerId": "CUST1001",
  "name": "Ravi Kumar",
  "email": "ravi@example.com",
  "city": "Hyderabad"
}

Internally MongoDB stores documents using BSON, which extends JSON with additional data types.


2. SQL Server vs MongoDB

SQL ServerMongoDB
DatabaseDatabase
TableCollection
RowDocument
ColumnField
Primary Key_id
JOIN$lookup / application-level modeling
Stored ProcedureApplication/service logic
RelationalDocument-oriented
Fixed schema commonly usedFlexible document schema
SQLMongoDB Query API

For example, SQL Server might contain:

Customers
-------------------------
CustomerId
Name
Email
City

MongoDB could contain:

{
  "_id": "CUST1001",
  "name": "Ravi Kumar",
  "email": "ravi@example.com",
  "city": "Hyderabad"
}

3. What is MongoDB Atlas?

MongoDB Atlas is the managed cloud service for MongoDB.

Instead of installing and maintaining MongoDB servers yourself, Atlas manages much of the database infrastructure.

Conceptually:

Your Application
       |
       | MongoDB Driver
       |
       v
+----------------------+
|   MongoDB Atlas      |
|                      |
|  MongoDB Cluster     |
|                      |
|  Database            |
|    |                 |
|  Collection          |
|    |                 |
|  Documents           |
+----------------------+

Atlas can deploy MongoDB clusters on Microsoft Azure. (MongoDB)


4. Why MongoDB on Azure?

A common enterprise architecture is:

Azure
│
├── Azure Front Door
│
├── API Management
│
├── AKS / App Service
│       │
│       └── ASP.NET Core APIs
│
├── Key Vault
│
├── Application Insights
│
└── MongoDB Atlas
        │
        └── MongoDB Cluster

Advantages include:

Scalability

MongoDB can scale horizontally using sharding.

High availability

Atlas supports replica-set based deployments, and Azure availability zones can be used for supported regions. (MongoDB)

Managed infrastructure

Atlas manages much of the operational database infrastructure.

Flexible document model

Different documents can contain different fields when your application requires a flexible schema.

Cloud integration

Applications running on Azure can connect to MongoDB Atlas using standard or private networking approaches.


5. Real-Time Example

Let's take an E-Commerce Order Management System.

Suppose customers place orders through an Angular application.

Architecture:

                Customer
                   |
                   v
            Angular Application
                   |
                   v
           Azure API Management
                   |
                   v
          ASP.NET Core Web API
                   |
       +-----------+-----------+
       |                       |
       v                       v
 MongoDB Atlas             Azure Service Bus
       |                       |
       v                       v
 Orders Collection       Other Microservices

The Order Service needs to store:

  • Customer information

  • Order information

  • Products

  • Quantity

  • Price

  • Shipping address

  • Payment status

  • Order status

  • Created date

MongoDB is well suited to representing this as a document.


6. MongoDB Data Model

Our database can be:

ECommerceDB
   |
   +-- Orders
   |
   +-- Customers
   |
   +-- Products

For this example:

Database:
ECommerceDB

Collection:
Orders

7. Sample MongoDB Document

An order could look like this:

{
  "_id": "ORD10001",
  "customer": {
    "customerId": "CUST1001",
    "name": "Ravi Kumar",
    "email": "ravi@example.com"
  },
  "items": [
    {
      "productId": "P1001",
      "productName": "Laptop",
      "quantity": 1,
      "unitPrice": 75000
    },
    {
      "productId": "P1002",
      "productName": "Mouse",
      "quantity": 2,
      "unitPrice": 1500
    }
  ],
  "shippingAddress": {
    "street": "Hitech City",
    "city": "Hyderabad",
    "state": "Telangana",
    "country": "India",
    "postalCode": "500081"
  },
  "paymentStatus": "Paid",
  "orderStatus": "Confirmed",
  "totalAmount": 78000,
  "createdAt": "2026-09-17T08:30:00Z"
}

Notice that customer, items, and shipping information can be represented naturally inside the document.


8. MongoDB Terminology

Understanding the terminology is important.

MongoDB
   |
   +-- Database
          |
          +-- Collection
                  |
                  +-- Document
                          |
                          +-- Field

For our application:

MongoDB
   |
   +-- ECommerceDB
          |
          +-- Orders
          |
          +-- Customers
          |
          +-- Products

9. Create MongoDB Atlas on Azure

Go to MongoDB Atlas and create an Atlas organization/project.

When creating your cluster, select:

Cloud Provider:
Microsoft Azure

Then select an appropriate Azure region.

MongoDB currently lists Azure regions including Central India, South India and West India, among many other supported Azure regions. Availability and cluster-tier support vary by region. (MongoDB)

For an application primarily running in India, an appropriate India region can reduce network latency, subject to your application's requirements and the cluster tier available there.


10. Create Database User

Create a MongoDB database user such as:

Username:
ecommerce-api-user

Use a strong password.

Do not hard-code the password in source code.

Bad:

var connectionString =
    "mongodb+srv://user:password@cluster.mongodb.net";

Instead, use:

Azure Key Vault
       |
       v
ASP.NET Core
       |
       v
MongoDB Atlas

11. Configure Network Access

Atlas provides network controls that determine which clients can connect.

For development, you may configure an appropriate IP access rule.

For production, consider private networking where appropriate.

A production architecture could be:

Azure VNet
   |
   +-----------------------+
   |                       |
   v                       v
AKS                    Private Endpoint
   |                       |
   |                       v
   +--------------> MongoDB Atlas

MongoDB documents different connection approaches, including standard connections, peering and private endpoints depending on how the application network is configured. (MongoDB)


12. Get MongoDB Connection String

From Atlas, obtain the application connection string.

It generally resembles:

mongodb+srv://<username>:<password>@cluster0.xxxxx.mongodb.net/

The MongoDB .NET driver uses the connection URI together with MongoClient to establish the connection. (MongoDB)

Never publish your real connection string in GitHub or your blog.


13. Create ASP.NET Core Web API

Create the project:

dotnet new webapi -n Ecommerce.Api

Move into the project:

cd Ecommerce.Api

Install the MongoDB .NET driver:

dotnet add package MongoDB.Driver

MongoDB provides an official .NET/C# driver for connecting .NET applications to MongoDB deployments including Atlas. (MongoDB)


14. Configure appsettings.json

Create:

{
  "MongoDB": {
    "ConnectionString": "mongodb+srv://<username>:<password>@cluster0.xxxxx.mongodb.net/",
    "DatabaseName": "ECommerceDB",
    "OrdersCollectionName": "Orders"
  }
}

For production, don't store the actual secret directly in appsettings.json.

Instead:

Azure Key Vault
      |
      v
ASP.NET Core Configuration
      |
      v
MongoDB Driver

MongoDB's own REST API tutorial demonstrates storing the MongoDB URI, database name, and collection name in application configuration. (MongoDB)


15. Create MongoDB Settings Class

Create:

Configuration/
    MongoDbSettings.cs
public class MongoDbSettings
{
    public string ConnectionString { get; set; } = string.Empty;

    public string DatabaseName { get; set; } = string.Empty;

    public string OrdersCollectionName { get; set; } = string.Empty;
}

16. Create Order Model

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

public class Order
{
    [BsonId]
    public string Id { get; set; } = string.Empty;

    public Customer Customer { get; set; } = new();

    public List<OrderItem> Items { get; set; } = new();

    public ShippingAddress ShippingAddress { get; set; } = new();

    public decimal TotalAmount { get; set; }

    public string PaymentStatus { get; set; } = string.Empty;

    public string OrderStatus { get; set; } = string.Empty;

    public DateTime CreatedAt { get; set; }
}

17. Customer Model

public class Customer
{
    public string CustomerId { get; set; } = string.Empty;

    public string Name { get; set; } = string.Empty;

    public string Email { get; set; } = string.Empty;
}

18. OrderItem Model

public class OrderItem
{
    public string ProductId { get; set; } = string.Empty;

    public string ProductName { get; set; } = string.Empty;

    public int Quantity { get; set; }

    public decimal UnitPrice { get; set; }
}

19. ShippingAddress Model

public class ShippingAddress
{
    public string Street { get; set; } = string.Empty;

    public string City { get; set; } = string.Empty;

    public string State { get; set; } = string.Empty;

    public string Country { get; set; } = string.Empty;

    public string PostalCode { get; set; } = string.Empty;
}

20. Create MongoDB Service

Create:

Services/
    OrderService.cs
using MongoDB.Driver;

public class OrderService
{
    private readonly IMongoCollection<Order> _orders;

    public OrderService(IConfiguration configuration)
    {
        var connectionString =
            configuration["MongoDB:ConnectionString"];

        var databaseName =
            configuration["MongoDB:DatabaseName"];

        var collectionName =
            configuration["MongoDB:OrdersCollectionName"];

        var client = new MongoClient(connectionString);

        var database = client.GetDatabase(databaseName);

        _orders = database.GetCollection<Order>(collectionName);
    }
}

The basic MongoDB .NET architecture is:

MongoDB Connection String
          |
          v
     MongoClient
          |
          v
      Database
          |
          v
     Collection
          |
          v
      Documents

21. Insert Order

Add:

public async Task CreateAsync(Order order)
{
    await _orders.InsertOneAsync(order);
}

Complete example:

public async Task CreateAsync(Order order)
{
    order.Id = $"ORD{DateTime.UtcNow.Ticks}";

    order.CreatedAt = DateTime.UtcNow;

    await _orders.InsertOneAsync(order);
}

MongoDB creates the document in the Orders collection.


22. Insert Sample Data

You can insert this document:

{
  "_id": "ORD10001",
  "customer": {
    "customerId": "CUST1001",
    "name": "Ravi Kumar",
    "email": "ravi@example.com"
  },
  "items": [
    {
      "productId": "P1001",
      "productName": "Laptop",
      "quantity": 1,
      "unitPrice": 75000
    },
    {
      "productId": "P1002",
      "productName": "Mouse",
      "quantity": 2,
      "unitPrice": 1500
    }
  ],
  "shippingAddress": {
    "street": "Hitech City",
    "city": "Hyderabad",
    "state": "Telangana",
    "country": "India",
    "postalCode": "500081"
  },
  "totalAmount": 78000,
  "paymentStatus": "Paid",
  "orderStatus": "Confirmed",
  "createdAt": "2026-09-17T08:30:00Z"
}

23. Retrieve All Orders

public async Task<List<Order>> GetAllAsync()
{
    return await _orders
        .Find(_ => true)
        .ToListAsync();
}

Here:

.Find(_ => true)

means:

Return all documents.

24. Retrieve Order by ID

public async Task<Order?> GetByIdAsync(string id)
{
    return await _orders
        .Find(x => x.Id == id)
        .FirstOrDefaultAsync();
}

25. Search Orders by Customer

public async Task<List<Order>> GetByCustomerAsync(
    string customerId)
{
    return await _orders
        .Find(x => x.Customer.CustomerId == customerId)
        .ToListAsync();
}

This demonstrates querying a nested document property.


26. Search Orders by City

public async Task<List<Order>> GetByCityAsync(
    string city)
{
    return await _orders
        .Find(x => x.ShippingAddress.City == city)
        .ToListAsync();
}

For example:

GET /api/orders/city/Hyderabad

27. Update an Order

Suppose an order changes from:

Confirmed

to:

Shipped

We can write:

public async Task UpdateStatusAsync(
    string id,
    string status)
{
    var filter =
        Builders<Order>.Filter.Eq(x => x.Id, id);

    var update =
        Builders<Order>.Update
            .Set(x => x.OrderStatus, status);

    await _orders.UpdateOneAsync(
        filter,
        update);
}

28. Delete an Order

public async Task DeleteAsync(string id)
{
    await _orders.DeleteOneAsync(
        x => x.Id == id);
}

29. Create Controller

using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class OrdersController : ControllerBase
{
    private readonly OrderService _service;

    public OrdersController(OrderService service)
    {
        _service = service;
    }

    [HttpGet]
    public async Task<IActionResult> GetAll()
    {
        var orders = await _service.GetAllAsync();

        return Ok(orders);
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> GetById(string id)
    {
        var order = await _service.GetByIdAsync(id);

        if (order == null)
            return NotFound();

        return Ok(order);
    }

    [HttpPost]
    public async Task<IActionResult> Create(Order order)
    {
        await _service.CreateAsync(order);

        return Ok(order);
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> Delete(string id)
    {
        await _service.DeleteAsync(id);

        return NoContent();
    }
}

30. Register MongoDB Service

In Program.cs:

builder.Services.AddSingleton<OrderService>();

Then:

var app = builder.Build();

app.MapControllers();

app.Run();

A simplified architecture becomes:

HTTP Request
     |
     v
OrdersController
     |
     v
OrderService
     |
     v
MongoClient
     |
     v
MongoDB Atlas
     |
     v
Orders Collection

31. POST Request Example

Send:

POST /api/orders
Content-Type: application/json

Request body:

{
  "customer": {
    "customerId": "CUST1002",
    "name": "Suresh",
    "email": "suresh@example.com"
  },
  "items": [
    {
      "productId": "P2001",
      "productName": "Mobile Phone",
      "quantity": 1,
      "unitPrice": 45000
    }
  ],
  "shippingAddress": {
    "street": "Madhapur",
    "city": "Hyderabad",
    "state": "Telangana",
    "country": "India",
    "postalCode": "500081"
  },
  "totalAmount": 45000,
  "paymentStatus": "Paid",
  "orderStatus": "Confirmed"
}

32. GET Request

GET /api/orders

Response:

[
  {
    "_id": "ORD10001",
    "customer": {
      "customerId": "CUST1001",
      "name": "Ravi Kumar"
    },
    "totalAmount": 78000,
    "orderStatus": "Confirmed"
  }
]

33. MongoDB Query Example

MongoDB shell query:

db.Orders.find({
    "customer.customerId": "CUST1001"
})

Another example:

db.Orders.find({
    "shippingAddress.city": "Hyderabad"
})

Find paid orders:

db.Orders.find({
    "paymentStatus": "Paid"
})

34. MongoDB Operators

MongoDB provides many query operators.

Greater Than

db.Orders.find({
    "totalAmount": {
        $gt: 50000
    }
})

Less Than

db.Orders.find({
    "totalAmount": {
        $lt: 50000
    }
})

Greater Than or Equal

db.Orders.find({
    "totalAmount": {
        $gte: 50000
    }
})

IN

db.Orders.find({
    "orderStatus": {
        $in: ["Confirmed", "Shipped"]
    }
})

35. MongoDB Indexes

Indexes are extremely important for production applications.

Suppose we frequently search:

CustomerId

Create an index:

db.Orders.createIndex({
    "customer.customerId": 1
})

For city:

db.Orders.createIndex({
    "shippingAddress.city": 1
})

For order status:

db.Orders.createIndex({
    "orderStatus": 1
})

The application should create indexes based on actual query patterns rather than creating indexes on every field.

MongoDB's .NET driver documentation includes dedicated guidance for creating and managing indexes. (MongoDB)


36. Compound Index

Suppose the application frequently queries:

Customer + Order Status

We can create:

db.Orders.createIndex({
    "customer.customerId": 1,
    "orderStatus": 1
})

This can support queries such as:

db.Orders.find({
    "customer.customerId": "CUST1001",
    "orderStatus": "Confirmed"
})

37. MongoDB Aggregation

Aggregation is one of MongoDB's powerful features.

Suppose we want:

Total sales by city

We can use:

db.Orders.aggregate([
    {
        $group: {
            _id: "$shippingAddress.city",
            totalSales: {
                $sum: "$totalAmount"
            }
        }
    }
])

Example result:

[
  {
    "_id": "Hyderabad",
    "totalSales": 2500000
  },
  {
    "_id": "Bangalore",
    "totalSales": 1800000
  }
]

38. Aggregation Pipeline

MongoDB aggregation works as a pipeline:

Documents
    |
    v
   $match
    |
    v
  $group
    |
    v
  $sort
    |
    v
 Result

Example:

db.Orders.aggregate([
    {
        $match: {
            "paymentStatus": "Paid"
        }
    },
    {
        $group: {
            _id: "$shippingAddress.city",
            totalSales: {
                $sum: "$totalAmount"
            }
        }
    },
    {
        $sort: {
            totalSales: -1
        }
    }
])

39. Consuming MongoDB Data from Angular

The frontend does not normally connect directly to MongoDB.

Instead:

Angular
   |
   | HTTP
   v
ASP.NET Core Web API
   |
   | MongoDB Driver
   v
MongoDB Atlas

Angular service:

@Injectable({
  providedIn: 'root'
})
export class OrderService {

  private apiUrl = 'https://api.example.com/api/orders';

  constructor(private http: HttpClient) {}

  getOrders() {
    return this.http.get<any[]>(this.apiUrl);
  }

  getOrder(id: string) {
    return this.http.get<any>(
      `${this.apiUrl}/${id}`
    );
  }
}

Component:

export class OrdersComponent {

  orders: any[] = [];

  constructor(
    private orderService: OrderService
  ) {}

  ngOnInit() {

    this.orderService
      .getOrders()
      .subscribe(data => {
        this.orders = data;
      });

  }
}

40. Complete Data Flow

When the Angular application requests orders:

1. User opens Orders screen
             |
             v
2. Angular sends HTTP GET
             |
             v
3. Azure API Management
             |
             v
4. ASP.NET Core API
             |
             v
5. OrderService
             |
             v
6. MongoDB Driver
             |
             v
7. MongoDB Atlas
             |
             v
8. Orders Collection
             |
             v
9. MongoDB returns documents
             |
             v
10. ASP.NET Core returns JSON
             |
             v
11. Angular displays data

41. Production Azure Architecture

For a larger enterprise system, the architecture could look like this:

                         Internet
                            |
                            v
                  +-------------------+
                  | Azure Front Door  |
                  +-------------------+
                            |
                            v
                  +-------------------+
                  | Azure API         |
                  | Management        |
                  +-------------------+
                            |
                            v
                  +-------------------+
                  | Azure Application |
                  | / AKS             |
                  +-------------------+
                            |
               +------------+------------+
               |                         |
               v                         v
        Order Microservice       Customer Service
               |                         |
               v                         v
        MongoDB Atlas              MongoDB Atlas
               |
               v
       Orders Collection

Supporting services:

Azure Key Vault
Azure Monitor
Application Insights
Azure Service Bus
Azure Container Registry
Azure DevOps

42. MongoDB with Microservices

MongoDB works particularly well with microservice architectures when each service owns its data.

For example:

Order Service
     |
     v
OrderDB
     |
     +-- Orders

Customer Service
     |
     v
CustomerDB
     |
     +-- Customers

Product Service
     |
     v
ProductDB
     |
     +-- Products

Instead of:

All Microservices
       |
       v
One Shared Database

we can use:

Order Service --------> Order Database

Customer Service -----> Customer Database

Product Service ------> Product Database

This helps maintain service ownership and reduces tight database coupling.


43. MongoDB and Azure Service Bus

Consider an order workflow:

Customer
   |
   v
Order API
   |
   v
MongoDB
   |
   v
Order Created
   |
   v
Azure Service Bus
   |
   +-----------> Inventory Service
   |
   +-----------> Payment Service
   |
   +-----------> Notification Service

For example:

{
  "eventType": "OrderCreated",
  "orderId": "ORD10001",
  "customerId": "CUST1001",
  "totalAmount": 78000
}

MongoDB stores the order state while Azure Service Bus can be used for asynchronous communication between services.


44. Security Architecture

A production architecture should avoid exposing database credentials.

Recommended:

Azure Key Vault
       |
       | Secret
       v
ASP.NET Core
       |
       | TLS
       v
MongoDB Atlas

Instead of:

appsettings.json
       |
       +-- username
       +-- password

Use:

Key Vault
   |
   v
Managed Identity
   |
   v
ASP.NET Core

Also consider:

  • TLS encryption

  • Network restrictions

  • Private connectivity where appropriate

  • Least-privilege database users

  • Secret rotation

  • Application-level authentication and authorization

  • Audit and monitoring


45. Azure Deployment Flow

A typical CI/CD pipeline could be:

Developer
    |
    v
Git Repository
    |
    v
Azure DevOps Pipeline
    |
    +---- Build
    |
    +---- Unit Tests
    |
    +---- Security Scan
    |
    +---- Docker Build
    |
    +---- Push to ACR
    |
    v
Azure AKS
    |
    v
ASP.NET Core Container
    |
    v
MongoDB Atlas

46. Docker Example

A simplified Dockerfile:

FROM mcr.microsoft.com/dotnet/aspnet:9.0 AS base

WORKDIR /app

EXPOSE 8080

FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build

WORKDIR /src

COPY . .

RUN dotnet restore

RUN dotnet publish \
    -c Release \
    -o /app/publish

FROM base AS final

WORKDIR /app

COPY --from=build /app/publish .

ENTRYPOINT ["dotnet", "Ecommerce.Api.dll"]

The container can then be deployed to Azure services such as AKS or another appropriate Azure hosting platform.


47. Performance Considerations

When using MongoDB in production, pay attention to:

1. Indexes

Create indexes for frequently executed queries.

2. Document Size

Avoid unnecessarily huge documents.

3. Query Projection

Retrieve only the fields you need when appropriate.

4. Connection Management

Reuse MongoClient rather than creating a new client for every request.

5. Pagination

Don't return millions of records in a single API request.

Example:

GET /api/orders?page=1&pageSize=50

6. Monitoring

Monitor:

CPU
Memory
Disk
Connections
Query performance
Latency
Operations per second

48. Pagination Example

A simple MongoDB pagination query:

public async Task<List<Order>> GetPagedAsync(
    int page,
    int pageSize)
{
    return await _orders
        .Find(_ => true)
        .Skip((page - 1) * pageSize)
        .Limit(pageSize)
        .ToListAsync();
}

For example:

page = 1
pageSize = 20

MongoDB returns the first 20 documents.


49. MongoDB Repository Pattern

For larger applications, you can introduce a repository layer:

Controller
    |
    v
Application Service
    |
    v
Repository
    |
    v
MongoDB

Example:

public interface IOrderRepository
{
    Task<List<Order>> GetAllAsync();

    Task<Order?> GetByIdAsync(string id);

    Task CreateAsync(Order order);

    Task UpdateAsync(Order order);

    Task DeleteAsync(string id);
}

Implementation:

public class OrderRepository : IOrderRepository
{
    private readonly IMongoCollection<Order> _orders;

    public OrderRepository(IMongoDatabase database)
    {
        _orders = database.GetCollection<Order>("Orders");
    }

    public async Task<List<Order>> GetAllAsync()
    {
        return await _orders
            .Find(_ => true)
            .ToListAsync();
    }

    public async Task<Order?> GetByIdAsync(string id)
    {
        return await _orders
            .Find(x => x.Id == id)
            .FirstOrDefaultAsync();
    }

    public async Task CreateAsync(Order order)
    {
        await _orders.InsertOneAsync(order);
    }

    public async Task UpdateAsync(Order order)
    {
        await _orders.ReplaceOneAsync(
            x => x.Id == order.Id,
            order);
    }

    public async Task DeleteAsync(string id)
    {
        await _orders.DeleteOneAsync(
            x => x.Id == id);
    }
}

50. Recommended Enterprise Project Structure

A clean architecture could look like:

Ecommerce.Api
│
├── Controllers
│     └── OrdersController.cs
│
├── Models
│     ├── Order.cs
│     ├── Customer.cs
│     └── OrderItem.cs
│
├── DTOs
│     ├── CreateOrderRequest.cs
│     └── OrderResponse.cs
│
├── Services
│     └── OrderService.cs
│
├── Repositories
│     ├── IOrderRepository.cs
│     └── OrderRepository.cs
│
├── Configuration
│     └── MongoDbSettings.cs
│
├── Program.cs
│
└── appsettings.json

51. MongoDB vs SQL Server – When to Use Which?

MongoDB can be useful when:

  • Data is naturally document-oriented

  • Schema changes frequently

  • High-scale workloads require horizontal scaling

  • Application data is naturally represented as JSON-like documents

  • Microservices need independently owned data

  • Flexible document structures are valuable

SQL Server can be preferable when:

  • Strong relational modeling is central

  • Complex joins dominate the workload

  • Existing enterprise applications rely heavily on relational features

  • Strong transactional relational constraints are fundamental

The choice should be based on workload and data requirements rather than simply choosing NoSQL because it is newer.


52. Real-Time End-to-End Example

Let's put everything together.

Suppose a customer purchases a laptop.

Step 1 – Customer

Customer submits:

Laptop
Quantity: 1
Price: ₹75,000

Step 2 – Angular

Angular sends:

POST /api/orders

Step 3 – Azure API Management

APIM handles API gateway responsibilities.

Step 4 – ASP.NET Core

The Order Controller receives the request.

Step 5 – Order Service

The service validates the order.

Step 6 – MongoDB

The Order Service saves:

{
  "_id": "ORD10001",
  "customer": {
    "customerId": "CUST1001"
  },
  "items": [
    {
      "productId": "P1001",
      "quantity": 1,
      "unitPrice": 75000
    }
  ],
  "totalAmount": 75000,
  "orderStatus": "Confirmed"
}

Step 7 – Event

The service publishes:

OrderCreated

to Azure Service Bus.

Step 8 – Inventory

Inventory Service receives the event.

Laptop Stock
100 → 99

Step 9 – Payment

Payment Service processes payment.

Step 10 – Notification

Notification Service sends the order confirmation.

Complete flow:

Angular
   |
   v
Azure API Management
   |
   v
Order API
   |
   v
Order Service
   |
   +--------------------+
   |                    |
   v                    v
MongoDB Atlas       Azure Service Bus
   |                    |
   |             +------+------+
   |             |             |
   |             v             v
   |        Inventory      Payment
   |                         |
   |                         v
   |                    Notification
   |
   v
Order Status

53. Important Production Best Practices

Database

  • Use appropriate indexes.

  • Design documents around access patterns.

  • Avoid unnecessarily large documents.

  • Monitor slow queries.

  • Use appropriate replication/high availability configuration.

Application

  • Reuse MongoClient.

  • Use asynchronous APIs.

  • Implement pagination.

  • Use DTOs rather than exposing internal models directly.

  • Validate incoming requests.

Security

  • Never commit passwords.

  • Use Azure Key Vault.

  • Use least-privilege database accounts.

  • Restrict network access.

  • Use encrypted connections.

Azure

  • Use Application Insights/Azure Monitor.

  • Use managed identities where applicable.

  • Use private networking where appropriate.

  • Use CI/CD.

  • Use autoscaling based on workload requirements.

Architecture

  • Keep database ownership with the appropriate service.

  • Use Service Bus for asynchronous communication where appropriate.

  • Don't make every microservice directly access every other service's database.


54. Complete Architecture Summary

The complete enterprise architecture can be represented as:

                         USERS
                           |
                           v
                    Angular / Mobile
                           |
                           v
                  +-------------------+
                  | Azure Front Door  |
                  +-------------------+
                           |
                           v
                  +-------------------+
                  | Azure API         |
                  | Management        |
                  +-------------------+
                           |
                           v
                +-----------------------+
                | Azure AKS / App       |
                | Service               |
                +-----------------------+
                           |
                           v
                 ASP.NET Core Web API
                           |
              +------------+-------------+
              |                          |
              v                          v
       MongoDB Atlas              Azure Service Bus
              |                          |
              v                    +-----+------+
       ECommerceDB                 |            |
              |                    v            v
          Collections          Inventory     Payment
              |
       +------+------+
       |             |
    Orders        Customers
       |
       v
   Products
       
Supporting Services:
       
Azure Key Vault
Azure Monitor
Application Insights
Azure Container Registry
Azure DevOps

55. Conclusion

MongoDB provides a document-oriented approach to data storage that can be particularly useful for modern cloud-native and microservices applications.

When combined with MongoDB Atlas on Microsoft Azure, an ASP.NET Core application can follow a cloud architecture such as:

Frontend
   ↓
Azure API Management
   ↓
ASP.NET Core
   ↓
MongoDB Atlas on Azure

For an enterprise application, this can be extended with:

Azure Front Door
       ↓
API Management
       ↓
AKS
       ↓
Microservices
       ↓
MongoDB Atlas
       +
Azure Service Bus
       +
Azure Key Vault
       +
Application Insights

The official MongoDB .NET driver provides the APIs needed to connect to Atlas and perform CRUD, aggregation, indexing, and other database operations. (MongoDB)

Useful official references

MongoDB Atlas on Microsoft Azure
MongoDB .NET/C# Driver documentation
.NET Driver – Get Started
MongoDB Atlas Driver Connection Guide


Wednesday, September 16, 2026

Terraform: Complete Guide with Real-Time Azure and .NET Microservices Example -2026


Introduction

In modern cloud-based application development, manually creating and configuring infrastructure through the Azure Portal, AWS Console, or other cloud management portals can become difficult as applications grow.

A typical enterprise .NET application may require multiple infrastructure components such as:

  • Azure Virtual Network

  • Azure Kubernetes Service (AKS)

  • Azure Container Registry (ACR)

  • Azure SQL Database

  • Azure Service Bus

  • Azure Key Vault

  • Azure API Management

  • Application Gateway

  • Application Insights

  • Azure Monitor

  • Storage Accounts

  • Managed Identities

Creating all these resources manually can be time-consuming and error-prone.

This is where Terraform becomes extremely useful.

Terraform allows us to define infrastructure using code and manage that infrastructure consistently across different environments such as:

  • Development

  • QA

  • UAT

  • Production

Terraform is an Infrastructure as Code (IaC) tool developed by HashiCorp.

Instead of manually creating infrastructure, we describe what infrastructure we need in Terraform configuration files, and Terraform creates and manages those resources for us.


1. What Is Terraform?

Terraform is an Infrastructure as Code tool used to provision and manage infrastructure using configuration files.

For example, instead of opening the Azure Portal and manually creating a Resource Group, we can write:

resource "azurerm_resource_group" "oneview" {
  name     = "rg-oneview-dev"
  location = "East US"
}

Terraform interprets this configuration and creates the corresponding Azure Resource Group.

The basic idea is:

Terraform Configuration
        |
        v
    Terraform
        |
        v
   Azure Provider
        |
        v
 Azure Infrastructure

Terraform can manage infrastructure from many platforms and services.

Examples include:

  • Microsoft Azure

  • Amazon Web Services

  • Google Cloud

  • Kubernetes

  • GitHub

  • Databases

  • Monitoring platforms

  • SaaS applications


2. What Is Infrastructure as Code?

Infrastructure as Code means managing infrastructure through machine-readable configuration files instead of manually configuring infrastructure.

Traditional Approach

Suppose we need to create an AKS cluster.

An engineer may manually:

  1. Open Azure Portal

  2. Create Resource Group

  3. Create Virtual Network

  4. Create Subnet

  5. Create AKS

  6. Configure networking

  7. Configure identity

  8. Configure permissions

  9. Configure monitoring

  10. Connect AKS with ACR

This process can be repeated for every environment.

Developer
    |
    v
Azure Portal
    |
    +--> Resource Group
    +--> VNet
    +--> Subnet
    +--> AKS
    +--> ACR
    +--> SQL
    +--> Service Bus

The problem is that manual configuration can introduce inconsistencies.

For example:

DEV  -> 2 AKS nodes
QA   -> 3 AKS nodes
UAT  -> 4 AKS nodes
PROD -> 6 AKS nodes

Some differences may be intentional, while others may happen because of manual configuration.

Infrastructure as Code Approach

With Terraform:

Terraform Code
      |
      v
Terraform Plan
      |
      v
Terraform Apply
      |
      v
Azure Infrastructure

The infrastructure configuration is stored in Git just like application source code.


3. Why Do We Need Terraform?

Terraform solves several infrastructure management problems.

3.1 Automation

Infrastructure can be created automatically.

3.2 Repeatability

The same infrastructure configuration can be reused for multiple environments.

3.3 Version Control

Terraform files can be stored in Git.

For example:

Git
 |
 +-- Terraform Code
 |
 +-- Version History
 |
 +-- Pull Requests
 |
 +-- Code Reviews

3.4 Consistency

Dev, QA, UAT, and Production can use standardized infrastructure modules.

3.5 Disaster Recovery

Infrastructure can be recreated from code when appropriate.

3.6 Collaboration

Multiple developers, architects, and DevOps engineers can work with the same infrastructure definition.


4. Terraform Architecture

The Terraform architecture can be represented as follows:

                Terraform Configuration
                         |
                         v
                  Terraform CLI
                         |
          +--------------+--------------+
          |                             |
          v                             v
   Terraform State                 Terraform Provider
                                        |
                                        v
                                  Azure APIs
                                        |
                                        v
                              Azure Infrastructure

The major components are:

  1. Terraform CLI

  2. Terraform Configuration

  3. Providers

  4. Resources

  5. Variables

  6. Data Sources

  7. State

  8. Backend

  9. Modules

  10. Outputs

Let's understand each one.


5. Terraform Configuration Files

Terraform configuration files generally use the .tf extension.

For example:

main.tf
variables.tf
outputs.tf
provider.tf
network.tf
aks.tf
sql.tf
servicebus.tf

Terraform reads all .tf files in the working directory.

Therefore, we don't have to put everything into one file.

A large enterprise project can be organized into multiple files.


6. HCL — HashiCorp Configuration Language

Terraform configurations are generally written using HCL.

For example:

resource "azurerm_resource_group" "oneview" {
  name     = "rg-oneview-dev"
  location = "East US"
}

The syntax is:

resource "RESOURCE_TYPE" "RESOURCE_NAME" {
    configuration
}

In this example:

resource
   |
   +-- azurerm_resource_group
   |
   +-- oneview

7. Terraform Providers

A provider allows Terraform to communicate with an external platform or service.

For Azure, we commonly use:

azurerm

Example:

terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "~> 4.0"
    }
  }
}

provider "azurerm" {
  features {}
}

The provider acts as the bridge between Terraform and Azure.

Terraform
    |
    v
Azure Provider
    |
    v
Azure API
    |
    v
Azure Resources

8. Installing Terraform

After installing Terraform, verify the installation:

terraform version

You should see the installed Terraform version.

For Azure development, Azure CLI is also useful.

Check Azure CLI:

az version

Login to Azure:

az login

You can then select the required Azure subscription.

az account set --subscription "<subscription-id>"

9. Real-Time Project Example

Let's consider a real-world .NET application called:

OneView Workforce Planning Platform

Suppose OneView contains the following microservices:

  • Forecast Service

  • Workforce Service

  • Capacity Service

  • Hiring Service

A possible architecture is:

                         Users
                           |
                           v
                  Application Gateway
                           |
                           v
                  Azure API Management
                           |
          +----------------+----------------+
          |                |                |
          v                v                v
    Forecast API     Workforce API     Capacity API
          |                |                |
          +----------------+----------------+
                           |
                           v
                  Azure Service Bus
                           |
                           v
                     Hiring Service
                           |
                           v
                      Azure SQL

Supporting Azure services might include:

AKS
ACR
Azure SQL
Service Bus
Key Vault
API Management
Application Gateway
Application Insights
Azure Monitor
Virtual Network
Managed Identity

Terraform can provision much of this infrastructure.


10. Creating the Terraform Project

Let's create the following project structure:

oneview-infrastructure/
│
├── provider.tf
├── variables.tf
├── resource-group.tf
├── network.tf
├── acr.tf
├── aks.tf
├── servicebus.tf
├── outputs.tf
└── terraform.tfvars

For a larger enterprise project, we can later convert these resources into reusable modules.


11. Configure Azure Provider

Create:

provider.tf

Add:

terraform {
  required_version = ">= 1.6.0"

  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "~> 4.0"
    }
  }
}

provider "azurerm" {
  features {}
}

This tells Terraform that the project uses the Azure Resource Manager provider.


12. Create Azure Resource Group

Create:

resource-group.tf
resource "azurerm_resource_group" "oneview" {
  name     = var.resource_group_name
  location = var.location

  tags = {
    Environment = var.environment
    Application = "OneView"
    ManagedBy   = "Terraform"
  }
}

Instead of hardcoding values, we are using variables.


13. Terraform Variables

Create:

variables.tf
variable "resource_group_name" {
  description = "Azure Resource Group name"
  type        = string
}

variable "location" {
  description = "Azure region"
  type        = string
  default     = "East US"
}

variable "environment" {
  description = "Deployment environment"
  type        = string
  default     = "dev"
}

variable "aks_node_count" {
  description = "Number of AKS nodes"
  type        = number
  default     = 2
}

Now create:

terraform.tfvars
resource_group_name = "rg-oneview-dev"
location            = "East US"
environment         = "dev"
aks_node_count      = 2

14. Terraform Init

Navigate to the project directory:

cd oneview-infrastructure

Run:

terraform init

Terraform downloads the required provider and initializes the working directory.

Typical flow:

Terraform Project
       |
       v
terraform init
       |
       v
Download Providers
       |
       v
Initialized

15. Terraform Validate

Before creating infrastructure, validate the configuration:

terraform validate

This checks the Terraform configuration for syntax and configuration errors.


16. Terraform Format

Terraform provides a formatting command:

terraform fmt

This automatically formats Terraform files according to Terraform's standard formatting rules.


17. Terraform Plan

Now execute:

terraform plan

Terraform calculates what changes are required.

For example:

Plan: 1 to add, 0 to change, 0 to destroy.

The important point is:

terraform plan previews changes.

It is normally used before applying infrastructure changes.


18. Terraform Apply

To create the infrastructure:

terraform apply

Terraform displays the planned changes and asks for confirmation.

Enter:

yes

Terraform then creates the resources.

You can also use:

terraform apply -auto-approve

However, automatic approval should be used carefully, especially for production environments.


19. Creating Azure Virtual Network

Now let's create networking.

Create:

network.tf
resource "azurerm_virtual_network" "oneview" {
  name                = "vnet-oneview"
  location            = azurerm_resource_group.oneview.location
  resource_group_name = azurerm_resource_group.oneview.name
  address_space       = ["10.10.0.0/16"]

  tags = {
    Environment = var.environment
    Application = "OneView"
    ManagedBy   = "Terraform"
  }
}

Create an AKS subnet:

resource "azurerm_subnet" "aks" {
  name                 = "snet-aks"
  resource_group_name  = azurerm_resource_group.oneview.name
  virtual_network_name = azurerm_virtual_network.oneview.name
  address_prefixes     = ["10.10.1.0/24"]
}

20. Creating Azure Container Registry

.NET microservices can be packaged as Docker containers.

Those container images can be stored in Azure Container Registry.

Create:

acr.tf
resource "azurerm_container_registry" "oneview" {
  name                = "acroneviewdev123"
  resource_group_name = azurerm_resource_group.oneview.name
  location            = azurerm_resource_group.oneview.location

  sku = "Standard"

  admin_enabled = false

  tags = {
    Environment = var.environment
    Application = "OneView"
    ManagedBy   = "Terraform"
  }
}

The application deployment flow becomes:

.NET Source Code
       |
       v
Docker Build
       |
       v
Container Image
       |
       v
Azure Container Registry
       |
       v
AKS

21. Creating Azure Kubernetes Service

Now let's create AKS.

Create:

aks.tf

Example:

resource "azurerm_kubernetes_cluster" "oneview" {

  name                = "aks-oneview-dev"
  location            = azurerm_resource_group.oneview.location
  resource_group_name = azurerm_resource_group.oneview.name
  dns_prefix          = "oneview-dev"

  default_node_pool {
    name       = "system"
    node_count = var.aks_node_count
    vm_size    = "Standard_D2s_v5"
  }

  identity {
    type = "SystemAssigned"
  }

  tags = {
    Environment = var.environment
    Application = "OneView"
    ManagedBy   = "Terraform"
  }
}

Terraform now understands that AKS belongs to the resource group.


22. Terraform Dependency Management

Terraform automatically identifies many dependencies by analyzing resource references.

For example:

resource_group_name = azurerm_resource_group.oneview.name

Terraform understands:

Resource Group
       |
       v
      AKS

Therefore, Terraform creates the Resource Group before AKS.

This is called an implicit dependency.


23. Explicit Dependencies

Sometimes Terraform cannot determine a dependency automatically.

In those cases, we can use:

depends_on = [
  azurerm_resource_group.oneview
]

Example:

resource "some_resource" "example" {

  # configuration

  depends_on = [
    azurerm_resource_group.oneview
  ]
}

It is generally preferable to rely on implicit dependencies whenever possible.


24. Connect AKS with ACR

AKS needs permission to pull container images from ACR.

We can assign the AcrPull role to the AKS kubelet identity.

Example:

resource "azurerm_role_assignment" "aks_acr" {

  principal_id = azurerm_kubernetes_cluster.oneview
    .kubelet_identity[0]
    .object_id

  role_definition_name = "AcrPull"

  scope = azurerm_container_registry.oneview.id

  skip_service_principal_aad_check = true
}

The relationship is:

Azure Container Registry
          |
          | AcrPull
          v
         AKS
          |
          v
      Kubernetes
          |
          v
       .NET Pods

25. Azure Service Bus with Terraform

In a microservices architecture, Azure Service Bus can be used for asynchronous communication.

Create:

servicebus.tf

Example:

resource "azurerm_servicebus_namespace" "oneview" {

  name                = "sb-oneview-dev"
  location            = azurerm_resource_group.oneview.location
  resource_group_name = azurerm_resource_group.oneview.name

  sku = "Standard"

  tags = {
    Environment = var.environment
    Application = "OneView"
    ManagedBy   = "Terraform"
  }
}

Create a topic:

resource "azurerm_servicebus_topic" "forecast_events" {

  name         = "forecast-events"
  namespace_id = azurerm_servicebus_namespace.oneview.id
}

Create a subscription:

resource "azurerm_servicebus_subscription" "workforce" {

  name               = "workforce-subscription"
  topic_id           = azurerm_servicebus_topic.forecast_events.id
  max_delivery_count = 10
}

The communication flow becomes:

Forecast Service
       |
       | ForecastCreated
       v
forecast-events
       |
       v
workforce-subscription
       |
       v
Workforce Service

26. Terraform Outputs

Create:

outputs.tf
output "resource_group_name" {
  value = azurerm_resource_group.oneview.name
}

output "aks_cluster_name" {
  value = azurerm_kubernetes_cluster.oneview.name
}

output "acr_login_server" {
  value = azurerm_container_registry.oneview.login_server
}

After applying the configuration:

terraform output

Terraform can display the output values.


27. Terraform State

One of the most important concepts in Terraform is state.

Terraform maintains information about infrastructure it manages.

The local state file is commonly:

terraform.tfstate

Conceptually:

Terraform Configuration
          |
          v
     Desired State
          |
          |
Terraform State
          |
          v
     Actual Azure

Terraform uses state to understand relationships between configuration and infrastructure.


28. Why Remote State Is Important

In a team environment, storing state only on an individual developer's machine is usually not appropriate.

Imagine:

Developer A
     |
Developer B
     |
Developer C
     |
Azure DevOps
     |
     v
Shared Terraform State

For Azure, an Azure Storage Account can be used as a remote backend.

Example:

terraform {
  backend "azurerm" {
    resource_group_name  = "rg-terraform-state"
    storage_account_name = "tfstateoneview"
    container_name       = "tfstate"
    key                  = "oneview-dev.tfstate"
  }
}

The backend infrastructure should generally be bootstrapped separately before configuring the project to use it.


29. Terraform State Locking

Consider this situation:

Developer A --------+
                    |
Developer B --------+----> Terraform State
                    |
CI/CD Pipeline -----+

If multiple operations modify the same state concurrently, problems can occur.

Remote backends can provide state locking or concurrency controls, depending on the backend.

Therefore, enterprise Terraform implementations should carefully design:

  • Remote state

  • State isolation

  • Locking

  • Access control

  • Backup

  • Recovery


30. Terraform Modules

As Terraform projects become larger, we should avoid putting hundreds or thousands of lines into a single file.

Terraform supports reusable modules.

Example:

terraform/
│
├── modules/
│   ├── network/
│   ├── aks/
│   ├── acr/
│   ├── sql/
│   ├── servicebus/
│   ├── keyvault/
│   └── apim/
│
└── environments/
    ├── dev/
    ├── qa/
    ├── uat/
    └── prod/

A module can encapsulate a reusable infrastructure component.


31. Example Terraform Module

Suppose we have an AKS module:

modules/
└── aks/
    ├── main.tf
    ├── variables.tf
    └── outputs.tf

The root configuration can call it:

module "aks" {

  source = "./modules/aks"

  resource_group_name = azurerm_resource_group.oneview.name
  location            = var.location
  node_count          = var.aks_node_count
}

The same module can then be reused by different environments.


32. Multiple Environments

A real enterprise application normally has:

DEV
QA
UAT
PROD

We can structure Terraform as:

environments/
│
├── dev/
│   ├── main.tf
│   └── terraform.tfvars
│
├── qa/
│   ├── main.tf
│   └── terraform.tfvars
│
├── uat/
│   ├── main.tf
│   └── terraform.tfvars
│
└── prod/
    ├── main.tf
    └── terraform.tfvars

For example:

Development

environment    = "dev"
aks_node_count = 2

Production

environment    = "prod"
aks_node_count = 5

The infrastructure module can remain reusable while environment-specific values are separated.


33. Terraform Data Sources

A Terraform resource creates or manages infrastructure.

A data source reads information about existing infrastructure.

For example:

data "azurerm_resource_group" "shared" {
  name = "rg-shared-services"
}

We can then access:

data.azurerm_resource_group.shared.location

This is particularly useful when an enterprise already has shared infrastructure.

For example:

Existing Shared Infrastructure
             |
      +------+------+
      |             |
      v             v
   Shared VNet   Key Vault
      |
      v
Application Terraform

Terraform doesn't necessarily need to create every resource itself.


34. Terraform Drift

Drift occurs when infrastructure changes outside Terraform.

Suppose Terraform defines:

AKS Node Count = 3

But someone manually changes Azure:

AKS Node Count = 5

Now:

Desired State = 3

Actual State = 5

This is infrastructure drift.

Running:

terraform plan

can reveal differences Terraform detects between the configuration/state and the infrastructure.


35. Terraform Import

Suppose an Azure resource already exists:

Azure Portal
     |
     v
Existing Resource

But Terraform doesn't currently manage it.

Terraform supports importing existing resources into Terraform state.

Conceptually:

Existing Azure Resource
          |
          v
    Terraform Import
          |
          v
   Terraform State

After import, you should ensure the Terraform configuration accurately represents the resource.

Modern Terraform also supports declarative import blocks for import workflows.


36. Terraform Lifecycle

Terraform provides lifecycle controls.

For example:

lifecycle {
  prevent_destroy = true
}

This can be useful for resources where accidental destruction would be especially undesirable.

Another lifecycle option is:

lifecycle {
  ignore_changes = [
    tags
  ]
}

Lifecycle rules should be used carefully because they can change Terraform's normal reconciliation behavior.


37. Terraform with Docker

Terraform and Docker solve different problems.

Docker

Docker packages applications into containers.

.NET Application
       |
       v
Docker Build
       |
       v
Container Image

Terraform

Terraform provisions infrastructure.

Terraform
    |
    +--> AKS
    +--> ACR
    +--> VNet
    +--> SQL
    +--> Service Bus

Together:

.NET Application
       |
       v
Docker Image
       |
       v
ACR
       |
       v
AKS
       ^
       |
 Terraform

38. Terraform with Kubernetes

Terraform and Kubernetes YAML also have different responsibilities.

Terraform can provision:

Azure
 |
 +--> VNet
 +--> AKS
 +--> ACR
 +--> SQL
 +--> Service Bus

Kubernetes can manage:

AKS
 |
 +--> Deployment
 +--> Service
 +--> Ingress
 +--> ConfigMap
 +--> Secret
 +--> HPA

Therefore:

Terraform
    |
    v
Infrastructure
    |
    v
AKS
    |
    v
Kubernetes
    |
    v
.NET Microservices

Terraform can also manage Kubernetes resources, but organizations often separate infrastructure provisioning from application deployment for operational clarity.


39. Terraform with Azure DevOps

Terraform becomes especially powerful when integrated with CI/CD.

A typical pipeline looks like:

Developer
    |
    v
Git Commit
    |
    v
Azure DevOps
    |
    +--> terraform fmt
    |
    +--> terraform validate
    |
    +--> terraform plan
    |
    v
Approval
    |
    v
terraform apply
    |
    v
Azure Infrastructure

40. Example Azure DevOps Terraform Pipeline

A simplified example:

trigger:
- main

pool:
  vmImage: ubuntu-latest

steps:

- task: TerraformInstaller@1
  inputs:
    terraformVersion: 'latest'

- script: |
    terraform init
  displayName: 'Terraform Init'

- script: |
    terraform fmt -check
  displayName: 'Terraform Format Check'

- script: |
    terraform validate
  displayName: 'Terraform Validate'

- script: |
    terraform plan
  displayName: 'Terraform Plan'

- script: |
    terraform apply -auto-approve
  displayName: 'Terraform Apply'

A production pipeline should additionally consider:

  • Azure service connections

  • Secure authentication

  • Remote state

  • Plan artifacts

  • Approval gates

  • Environment protection

  • Separate plan/apply stages

  • Secret management

  • Policy checks


41. Terraform and Security

Security is extremely important when managing infrastructure.

Never hardcode sensitive credentials:

password = "MyPassword123"

Instead, use mechanisms such as:

  • Azure Key Vault

  • Managed Identity

  • Workload Identity

  • Azure DevOps secret variables

  • Secure pipeline variables

  • Environment variables

For example:

Terraform
    |
    v
Azure Identity
    |
    v
Key Vault
    |
    v
Secrets

42. Sensitive Variables

Terraform supports sensitive variables.

Example:

variable "database_password" {
  type      = string
  sensitive = true
}

This helps prevent the value from being displayed in normal Terraform output.

However, marking a value as sensitive does not automatically remove it from Terraform state. Therefore, state itself must be securely stored and access-controlled.


43. Terraform Workspaces

Terraform supports workspaces.

For example:

terraform workspace new dev
terraform workspace new qa
terraform workspace new prod

Select a workspace:

terraform workspace select dev

Workspaces can be useful in certain scenarios, but for larger enterprise environments, separate environment directories and isolated remote states can sometimes provide clearer isolation.


44. Important Terraform Commands

CommandDescription
terraform initInitializes Terraform
terraform fmtFormats Terraform files
terraform validateValidates configuration
terraform planShows proposed changes
terraform applyCreates/updates infrastructure
terraform destroyDestroys managed infrastructure
terraform outputDisplays outputs
terraform showDisplays state/plan information
terraform state listLists resources in state
terraform state showShows a resource from state
terraform providersDisplays configured providers
terraform workspace listLists workspaces

45. Terraform Destroy

Terraform can also remove infrastructure that it manages.

terraform destroy

Terraform shows the resources it intends to destroy.

For example:

Plan: 0 to add, 0 to change, 10 to destroy.

After confirmation, Terraform removes the managed resources.

This command should be used with extreme care in production.


46. Terraform vs ARM Templates vs Bicep

For Azure architects, this is an important interview topic.

FeatureTerraformARM TemplatesBicep
ProviderHashiCorpMicrosoftMicrosoft
AzureYesYesYes
AWSYesNoNo
GCPYesNoNo
Multi-cloudStrongNoNo
SyntaxHCLJSONBicep
ModulesYesYesYes
Azure NativeNoYesYes
CI/CDYesYesYes

Bicep is an Azure-native Infrastructure as Code language.

Terraform is particularly attractive when an organization wants a common IaC approach across multiple providers or already has a mature Terraform ecosystem.


47. Terraform vs Ansible

Terraform and Ansible are also frequently compared.

Terraform

Primarily focuses on infrastructure provisioning.

Terraform
    |
    +--> Network
    +--> VM
    +--> AKS
    +--> Database
    +--> Storage

Ansible

Primarily focuses on configuration and automation.

Ansible
    |
    +--> Install packages
    +--> Configure servers
    +--> Deploy configuration
    +--> Execute operational tasks

Simplified:

Terraform
    |
    v
Provision Infrastructure

Ansible
    |
    v
Configure / Automate Systems

48. Terraform vs Docker vs Kubernetes

These three technologies solve different problems.

Terraform
    |
    v
Infrastructure Provisioning

Docker
    |
    v
Application Containerization

Kubernetes
    |
    v
Container Orchestration

For a .NET microservices platform:

Terraform
    |
    +--> Azure VNet
    +--> AKS
    +--> ACR
    +--> SQL
    +--> Service Bus
    |
    v
Docker
    |
    v
.NET Container
    |
    v
ACR
    |
    v
Kubernetes / AKS
    |
    v
Running Microservices

49. Complete OneView Terraform Architecture

Let's put everything together.

                         Internet
                            |
                            v
                  Application Gateway
                            |
                            v
                   Azure API Management
                            |
                            v
                           AKS
                            |
          +-----------------+-----------------+
          |                 |                 |
          v                 v                 v
    Forecast API      Workforce API     Capacity API
          |                 |                 |
          +-----------------+-----------------+
                            |
                            v
                    Azure Service Bus
                            |
                            v
                     Hiring Service
                            |
                            v
                       Azure SQL


Supporting Azure Services
-------------------------

        +-----------------------------+
        | Azure Container Registry    |
        | Azure Key Vault             |
        | Application Insights        |
        | Azure Monitor               |
        | Managed Identity             |
        | Virtual Network             |
        +-----------------------------+

                 ^
                 |
              Terraform
                 |
                 v
          Infrastructure as Code

50. End-to-End Terraform Deployment Flow

A complete enterprise deployment can look like:

                     Developer
                         |
                         v
                  Git Repository
                         |
                         v
                  Azure DevOps
                         |
            +------------+------------+
            |                         |
            v                         v
       Terraform                  Application
          Code                       Code
            |                         |
            v                         v
    terraform validate          Docker Build
            |                         |
            v                         v
      terraform plan               ACR
            |                         |
            v                         v
        Approval                    AKS
            |
            v
    terraform apply
            |
            v
      Azure Infrastructure
            |
     +------+------+------+
     |      |      |      |
     v      v      v      v
    VNet   AKS    SQL   Service Bus

51. Enterprise Terraform Repository Structure

A production-style Terraform repository can look like:

terraform-infrastructure/
│
├── modules/
│   │
│   ├── network/
│   │   ├── main.tf
│   │   ├── variables.tf
│   │   └── outputs.tf
│   │
│   ├── aks/
│   │   ├── main.tf
│   │   ├── variables.tf
│   │   └── outputs.tf
│   │
│   ├── acr/
│   ├── sql/
│   ├── servicebus/
│   ├── keyvault/
│   ├── apim/
│   └── monitoring/
│
├── environments/
│   │
│   ├── dev/
│   │   ├── main.tf
│   │   ├── variables.tf
│   │   └── terraform.tfvars
│   │
│   ├── qa/
│   │
│   ├── uat/
│   │
│   └── prod/
│
└── pipelines/
    ├── terraform-plan.yml
    └── terraform-apply.yml

This structure provides:

Reusable Modules
       +
Environment Isolation
       +
CI/CD Automation
       +
Version Control

52. Terraform Best Practices

1. Use Remote State

Use an appropriate remote backend instead of relying on local state for team-managed infrastructure.

2. Use Modules

Create reusable modules for common infrastructure components.

3. Never Hardcode Secrets

Use Key Vault, managed identities, and secure CI/CD mechanisms.

4. Use Git

Store Terraform code in source control.

5. Review Terraform Plans

Use:

terraform plan

before applying important infrastructure changes.

6. Use Environment Isolation

Separate development and production state appropriately.

7. Use Naming Standards

For example:

rg-oneview-dev
rg-oneview-qa
rg-oneview-uat
rg-oneview-prod

8. Use Resource Tags

tags = {
  Application = "OneView"
  Environment = "Production"
  Owner       = "PlatformTeam"
  ManagedBy   = "Terraform"
}

9. Implement CI/CD

Terraform should be integrated with your organization's DevOps process.

10. Protect Production

Production infrastructure should have:

  • Approval processes

  • Restricted permissions

  • Remote state

  • Secure credentials

  • Policy validation

  • Monitoring

  • Backup/recovery processes


53. Terraform in a .NET Solution Architect's Architecture

From a Solution Architect perspective, Terraform is not responsible for writing the .NET application.

Instead, it manages the infrastructure required to run the application.

For example:

                   .NET Application
                         |
                         v
                    Docker Image
                         |
                         v
                         ACR
                         |
                         v
                        AKS
                         |
       +-----------------+----------------+
       |                 |                |
       v                 v                v
 Forecast           Workforce         Capacity
 Service             Service           Service
       |                 |                |
       +-----------------+----------------+
                         |
                         v
                  Service Bus
                         |
                         v
                   Hiring Service
                         |
                         v
                    Azure SQL


Terraform manages:
-------------------

VNet
AKS
ACR
SQL
Service Bus
Key Vault
APIM
Application Gateway
Monitoring
Identity

This separation is important.

Application code describes what the application does.

Terraform describes what infrastructure the application needs.


54. Real-World Scenario

Suppose a company wants to create a new production environment for OneView.

Without Terraform:

Engineer
   |
   +--> Create Resource Group
   +--> Create VNet
   +--> Create Subnets
   +--> Create ACR
   +--> Create AKS
   +--> Create SQL
   +--> Create Service Bus
   +--> Create Key Vault
   +--> Configure APIM
   +--> Configure Monitoring
   +--> Configure Permissions

With Terraform:

Terraform Repository
        |
        v
terraform plan
        |
        v
Approval
        |
        v
terraform apply
        |
        v
Azure Infrastructure

The infrastructure definition becomes repeatable, reviewable, and version controlled.


55. Terraform Workflow — Summary

The standard Terraform workflow is:

             Write Terraform Code
                      |
                      v
              terraform init
                      |
                      v
             terraform fmt
                      |
                      v
           terraform validate
                      |
                      v
              terraform plan
                      |
                      v
                 Review
                      |
                      v
             terraform apply
                      |
                      v
             Azure Resources
                      |
                      v
             Monitor / Maintain
                      |
                      v
               Code Changes
                      |
                      v
             terraform plan

56. Important Terraform Concepts for Interviews

If you are preparing for a .NET Solution Architect, Azure Architect, or DevOps interview, the following Terraform topics are particularly important:

Terraform Fundamentals

  • What is Terraform?

  • What is Infrastructure as Code?

  • What is HCL?

  • What is a provider?

  • What is a resource?

  • What is a data source?

  • What is a variable?

  • What is an output?

State Management

  • What is Terraform state?

  • Why is state required?

  • What is remote state?

  • What is state locking?

  • What is state drift?

  • How do you secure Terraform state?

Modules

  • What is a Terraform module?

  • Why use modules?

  • How do you create reusable modules?

  • How do you pass variables into modules?

  • How do modules expose outputs?

Enterprise

  • Terraform with Azure DevOps

  • Terraform with AKS

  • Terraform with ACR

  • Terraform with Azure SQL

  • Terraform with Service Bus

  • Terraform with Key Vault

  • Terraform with API Management

  • Terraform with Application Gateway

  • Terraform with Managed Identity

  • Terraform with Azure Monitor


57. Key Takeaways

Terraform provides a consistent way to manage cloud infrastructure through code.

The most important concepts are:

Terraform
   |
   +--> Infrastructure as Code
   |
   +--> Providers
   |
   +--> Resources
   |
   +--> Variables
   |
   +--> Data Sources
   |
   +--> State
   |
   +--> Remote Backend
   |
   +--> Modules
   |
   +--> Outputs
   |
   +--> Plan
   |
   +--> Apply
   |
   +--> Destroy

For a modern .NET microservices application:

Terraform
    |
    +--> Azure Infrastructure
             |
             +--> VNet
             +--> AKS
             +--> ACR
             +--> Azure SQL
             +--> Service Bus
             +--> Key Vault
             +--> APIM
             +--> Application Gateway
             +--> Monitoring

The application itself can then be built using:

.NET
  |
  v
Docker
  |
  v
ACR
  |
  v
AKS

Therefore, Terraform plays an important role in creating a repeatable and automated cloud foundation for modern .NET applications.


Conclusion

Terraform is much more than a tool for creating Azure resources.

In an enterprise environment, Terraform can become an important part of the overall Cloud Infrastructure and DevOps strategy.

A typical modern architecture can combine:

.NET
 +
Docker
 +
Kubernetes / AKS
 +
Azure
 +
Terraform
 +
Azure DevOps

where:

  • .NET develops the business applications

  • Docker packages applications into containers

  • AKS orchestrates containers

  • Azure provides cloud infrastructure and managed services

  • Terraform provisions and manages infrastructure as code

  • Azure DevOps automates the CI/CD lifecycle

The result is a repeatable, automated, version-controlled infrastructure platform that can support development through production environments.

Terraform + Azure + .NET + Kubernetes + DevOps is therefore a powerful combination for building and operating modern enterprise applications.


Don't Copy

Protected by Copyscape Online Plagiarism Checker