Terraform on Your Laptop (Part 3)

Neil Haddley • November 29, 2026

I added a SQL Server container to the C# web site with Terraform, wrote the database layer as T-SQL stored procedures, and watched what Terraform replaced, kept and refused to destroy.

DevOpsSQLDockerTerraformterraformdockersql-serverstored-procedurescsharp

In Part 1 I ran a public image with Terraform. In Part 2 I built a C# web site and scaled it to three copies. The site had no memory, though. Every time Terraform replaced a container, nothing survived.

In this post I give the site a database layer: SQL Server, in its own Docker container, with all of its data access written as T-SQL stored procedures. Then I change the app, change a stored procedure, delete the database container by hand, and try to destroy everything. After each step I look at the plan and at the web site.

I ran everything on Docker Desktop on my Mac with Terraform 1.17.2. You can download the files: main.tf, init.sql, Program.cs, site.csproj, Dockerfile and terraform.tfvars. The starting point is where Part 2 ended: three copies of version 2.0 of the site.

What the database is for

I gave the database two small jobs, because each one shows something about Terraform:

  • A visit counter. Every page view calls a stored procedure that adds one to a counter for the container that served it. All three web copies share one database, so the page can show visits per container and a total. This shows three copies sharing one source of truth.
  • A product list. The page reads four products through another stored procedure. This is the data I later change the query for, to show Terraform noticing a change to database code.

Both are things I want to outlive any one web container. That is the point of the demo: I can replace the web containers freely, but the data has to stay.

The database layer: T-SQL

All of the database code lives in one script, init.sql. It creates the database, the two tables and three stored procedures. I wrote it so I can run it any number of times: it creates things only if they are missing, and CREATE OR ALTER PROCEDURE replaces a procedure with the new definition.

SQL
1IF DB_ID(N'ShopDemo') IS NULL
2    CREATE DATABASE ShopDemo;
3GO
4
5USE ShopDemo;
6GO
7
8IF OBJECT_ID(N'dbo.Visits', N'U') IS NULL
9    CREATE TABLE dbo.Visits (
10        Instance   nvarchar(64) NOT NULL PRIMARY KEY,
11        VisitCount int          NOT NULL
12    );
13GO
14
15IF OBJECT_ID(N'dbo.Products', N'U') IS NULL
16BEGIN
17    CREATE TABLE dbo.Products (
18        Id    int IDENTITY(1,1) PRIMARY KEY,
19        Name  nvarchar(100) NOT NULL,
20        Price decimal(10,2) NOT NULL
21    );
22
23    INSERT dbo.Products (Name, Price) VALUES
24        (N'Garden gloves', 12.50),
25        (N'Watering can',  24.00),
26        (N'Tomato seeds',   4.20),
27        (N'Compost 20 L',   9.80);
28END
29GO
30
31CREATE OR ALTER PROCEDURE dbo.usp_RecordVisit
32    @Instance nvarchar(64)
33AS
34BEGIN
35    SET NOCOUNT ON;
36
37    UPDATE dbo.Visits
38       SET VisitCount = VisitCount + 1
39     WHERE Instance = @Instance;
40
41    IF @@ROWCOUNT = 0
42        INSERT dbo.Visits (Instance, VisitCount) VALUES (@Instance, 1);
43END
44GO
45
46CREATE OR ALTER PROCEDURE dbo.usp_GetVisitSummary
47AS
48BEGIN
49    SET NOCOUNT ON;
50
51    SELECT COALESCE(Instance, N'Total') AS Instance,
52           SUM(VisitCount)              AS VisitCount
53      FROM dbo.Visits
54     GROUP BY ROLLUP (Instance)
55     ORDER BY GROUPING(Instance), Instance;
56END
57GO
58
59CREATE OR ALTER PROCEDURE dbo.usp_GetProducts
60AS
61BEGIN
62    SET NOCOUNT ON;
63
64    SELECT Name, Price
65      FROM dbo.Products
66     ORDER BY Name;
67END
68GO

Three things in the T-SQL are worth a note:

  • usp_RecordVisit updates the row and, if no row was updated (@@ROWCOUNT = 0), inserts one.
  • usp_GetVisitSummary uses GROUP BY ROLLUP (Instance), which adds a total row at the end of the per-container rows.
  • usp_GetProducts sorts by name. That is the line I change in Step 4.

The C# side

The web site no longer builds SQL. It only calls the stored procedures through Microsoft.Data.SqlClient:

CSHARP
1await using var conn = new SqlConnection(connectionString);
2await conn.OpenAsync();
3
4await using (var cmd = new SqlCommand("dbo.usp_RecordVisit", conn) { CommandType = CommandType.StoredProcedure })
5{
6    cmd.Parameters.AddWithValue("@Instance", Environment.MachineName);
7    await cmd.ExecuteNonQueryAsync();
8}
9
10await using (var cmd = new SqlCommand("dbo.usp_GetVisitSummary", conn) { CommandType = CommandType.StoredProcedure })
11await using (var reader = await cmd.ExecuteReaderAsync())
12{
13    while (await reader.ReadAsync())
14        visits.Append($"<tr><td>{WebUtility.HtmlEncode(reader.GetString(0))}</td><td>{reader.GetInt32(1)}</td></tr>");
15}

The connection string arrives as an environment variable, DB_CONNECTION, which Terraform sets. If the database is unreachable, the page shows a "Database error" message instead of crashing. That matters in Step 5.

The Terraform changes

I kept everything from Part 2 and added six resources. First, a password. I did not want to type or store one, so Terraform generates it:

HCL
1resource "random_password" "sa" {
2  length      = 20
3  min_upper   = 2
4  min_lower   = 2
5  min_numeric = 2
6  min_special = 1
7  special     = true
8  # Characters that are safe in a connection string
9  override_special = "!#-_"
10}

Then a network for the containers to talk on, and a volume to hold the data:

HCL
1resource "docker_network" "demo" {
2  name = "terraform-demo-net"
3}
4
5resource "docker_volume" "sqldata" {
6  name = "terraform-demo-sqldata"
7}

The database image and container come next:

HCL
1resource "docker_image" "sql" {
2  name         = "mcr.microsoft.com/mssql/server:2022-latest"
3  platform     = "linux/amd64"
4  keep_locally = true
5}
6
7resource "docker_container" "db" {
8  name  = "terraform-demo-db"
9  image = docker_image.sql.image_id
10
11  env = [
12    "ACCEPT_EULA=Y",
13    "MSSQL_SA_PASSWORD=${random_password.sa.result}",
14  ]
15
16  networks_advanced {
17    name = docker_network.demo.name
18  }
19
20  volumes {
21    volume_name    = docker_volume.sqldata.name
22    container_path = "/var/opt/mssql"
23  }
24
25  healthcheck {
26    test         = ["CMD-SHELL", "/opt/mssql-tools18/bin/sqlcmd -C -S localhost -U sa -P \"$MSSQL_SA_PASSWORD\" -Q 'SELECT 1' || exit 1"]
27    interval     = "5s"
28    timeout      = "3s"
29    retries      = 20
30    start_period = "5s"
31  }
32
33  wait         = true
34  wait_timeout = 120
35}

Two details in the container matter:

  • The healthcheck runs a trivial query every five seconds, and wait = true makes Terraform wait until it passes. Terraform does not move on to the next resource until SQL Server is really accepting connections.
  • The volumes block mounts the volume at /var/opt/mssql, where SQL Server keeps its data files. The data therefore lives in the volume, not in the container.

Next is the step that applies the T-SQL script:

HCL
1resource "terraform_data" "db_schema" {
2  triggers_replace = [
3    filesha1("${path.module}/db/init.sql"),
4    docker_container.db.id,
5  ]
6
7  provisioner "local-exec" {
8    command = "docker cp ${path.module}/db/init.sql terraform-demo-db:/tmp/init.sql && docker exec -e SQLCMDPASSWORD=\"$SA_PASSWORD\" terraform-demo-db /opt/mssql-tools18/bin/sqlcmd -C -b -S localhost -U sa -i /tmp/init.sql"
9
10    environment = {
11      SA_PASSWORD = random_password.sa.result
12    }
13  }
14}

terraform_data is a resource that does no infrastructure work of its own. Here it runs the script with sqlcmd inside the database container. Its triggers_replace list holds two things: the fingerprint of init.sql, and the ID of the database container. If either changes, Terraform runs the script again.

Finally, the web containers get the connection string, join the network, and wait for the schema step:

HCL
1resource "docker_container" "site" {
2  count = var.instances
3  name  = "terraform-demo-site-${count.index + 1}"
4  image = docker_image.site.image_id
5
6  env = [
7    "SITE_TITLE=${var.site_title}",
8    "SITE_COLOR=${var.site_color}",
9    "DB_CONNECTION=Server=terraform-demo-db;Database=ShopDemo;User Id=sa;Password=${random_password.sa.result};TrustServerCertificate=True",
10  ]
11
12  networks_advanced {
13    name = docker_network.demo.name
14  }
15
16  depends_on = [terraform_data.db_schema]
17
18  ports {
19    internal = 8080
20    external = 8080 + count.index
21  }
22}

Step 1: add the database layer

PROMPT
1terraform init
2terraform plan
3terraform apply -auto-approve

init downloaded one more provider, hashicorp/random. The plan said:

CODE
1# docker_container.db will be created
2    + env = (sensitive value)
3# docker_container.site[0] must be replaced
4    ~ env = (sensitive value) # forces replacement
5# docker_container.site[1] must be replaced
6# docker_container.site[2] must be replaced
7# docker_image.site must be replaced
8# docker_image.sql will be created
9# docker_network.demo will be created
10# docker_volume.sqldata will be created
11# random_password.sa will be created
12# terraform_data.db_schema will be created
13
14Plan: 10 to add, 0 to change, 4 to destroy.

The three web containers are replaced because their settings changed: they now have a connection string, and the password inside it is hidden. The web image is rebuilt because the C# code now uses SQL Server. The apply went in dependency order:

CODE
1docker_container.db: Creation complete after 6s
2terraform_data.db_schema: Provisioning with 'local-exec'...
3terraform_data.db_schema: Creation complete after 0s
4docker_container.site[1]: Creation complete after 1s
5docker_container.site[2]: Creation complete after 1s
6docker_container.site[0]: Creation complete after 1s
7
8Apply complete! Resources: 10 added, 0 changed, 4 destroyed.

The database container took 6 seconds because Terraform waited for the health check. The schema step ran only after that, and the web containers started last. I never wrote that order down. It comes from the references and from depends_on.

I opened a page on each of the three ports and then took a screenshot of the first one:

Version 3.0 on port 8080. Each container has counted its own visits, and the products come from the database

Version 3.0 on port 8080. Each container has counted its own visits, and the products come from the database

Docker Desktop listed four containers: the database, which publishes no port, and the three web copies on ports 8080 to 8082:

Docker Desktop showed the SQL Server container and the three web containers. The database row has the SQL Server image and no port

Docker Desktop showed the SQL Server container and the three web containers. The database row has the SQL Server image and no port

Step 2: three copies, one database

I loaded the pages on all three ports several times, and then opened the third:

Port 8082 showed the visits recorded by all three containers, not only its own

Port 8082 showed the visits recorded by all three containers, not only its own

The counts are the same whichever copy answers, because they are all asking the same database. With three copies of Part 2's site, each would have kept its own count, and the total would have been unknowable.

Step 3: change the C# code

I changed Program.cs: the version became 3.1 and I added one card saying the shop opens from 9am to 5pm.

PROMPT
1terraform plan
CODE
1# docker_container.site[0] must be replaced
2# docker_container.site[1] must be replaced
3# docker_container.site[2] must be replaced
4# docker_image.site must be replaced
5    ~ "source_hash" = "c60f139be72a549a714739ec41bc8d52079fcc67" -> "cd9b0f34da0913e67b2b642fd55f91a42252d206"
6
7Plan: 4 to add, 0 to change, 4 to destroy.

Look at what is missing. The database container, the volume, the network, the password and the schema step are not in the plan. Only the web image and the three web containers are. Terraform changes the parts that depend on the changed code and leaves the rest alone.

CODE
1docker_image.site: Creation complete after 3s
2docker_container.site[2]: Creation complete after 0s
3docker_container.site[1]: Creation complete after 0s
4docker_container.site[0]: Creation complete after 0s
5
6Apply complete! Resources: 4 added, 0 changed, 4 destroyed.
Version 3.1 with the new card. The visit counts are still there, even though every web container is new

Version 3.1 with the new card. The visit counts are still there, even though every web container is new

The old containers are gone, but their rows are still in the table, so the page lists them too. The data survived because it lives in the database, not in the containers.

Step 4: change a stored procedure

I edited one line in init.sql, so that the products appear most expensive first:

SQL
1     ORDER BY Price DESC;
PROMPT
1terraform plan
CODE
1# terraform_data.db_schema must be replaced
2    ~ triggers_replace = [
3        ~ "e0250276e782b5892184a4b8d6245015bb83f37e" -> "980b712e5f61d5b4f66fdd784a285c450cb5a1ba",
4          "e57e52e0dbfef1833b68186c5666c8b2d7bf1d98acfebfbc8f9bc17ec1c65768",
5      ]
6
7Plan: 1 to add, 0 to change, 1 to destroy.

One resource, and nothing else. The fingerprint of init.sql changed, so Terraform ran the script again. CREATE OR ALTER PROCEDURE replaced the procedure and left the tables and their data alone. The web containers were not touched:

CODE
1terraform_data.db_schema: Destruction complete after 0s
2terraform_data.db_schema: Provisioning with 'local-exec'...
3terraform_data.db_schema: Creation complete after 0s
4
5Apply complete! Resources: 1 added, 0 changed, 1 destroyed.
The products now run from $24.00 down to $4.20. The web site was not rebuilt or restarted, because only the stored procedure changed

The products now run from $24.00 down to $4.20. The web site was not rebuilt or restarted, because only the stored procedure changed

This is the part I like most. A change to database code is visible in the plan, in version control and in a reviewable diff, like any other change.

Step 5: lose the database container

Next I did what an unlucky colleague might do. I removed the database container by hand:

CODE
1$ docker rm -f terraform-demo-db

The web site noticed straight away:

With the database gone, the page showed a database error and did not crash

With the database gone, the page showed a database error and did not crash

Docker Desktop showed three web containers and no database:

Docker Desktop with the database container missing

Docker Desktop with the database container missing

PROMPT
1terraform plan
CODE
1# docker_container.db has been deleted
2# docker_container.db will be created
3# terraform_data.db_schema must be replaced
4
5Plan: 2 to add, 0 to change, 1 to destroy.

Terraform saw that the container was gone and planned to recreate it. It also planned to run the schema script again, because the schema step lists the database container's ID as one of its triggers. The web containers and the volume were not in the plan.

CODE
1docker_container.db: Creation complete after 7s
2terraform_data.db_schema: Provisioning with 'local-exec'...
3terraform_data.db_schema: Creation complete after 0s
4
5Apply complete! Resources: 2 added, 0 changed, 1 destroyed.
The new database container came up with all of the visit counts intact, because the data lives in the volume

The new database container came up with all of the visit counts intact, because the data lives in the volume

Docker Desktop with a new database container next to the three web containers that were never touched

Docker Desktop with a new database container next to the three web containers that were never touched

What Terraform replaced and what it kept: the web containers and the database container came and went, and the volume never changedScroll sideways, or tap the diagram to open it full size

What Terraform replaced and what it kept: the web containers and the database container came and went, and the volume never changed

Step 6: try to destroy everything

Destroying the demo would also destroy the volume, and with it all of the data. That is fine for a demo and a disaster for a real database, so I added a guard to the volume:

HCL
1resource "docker_volume" "sqldata" {
2  name = "terraform-demo-sqldata"
3
4  lifecycle {
5    prevent_destroy = true
6  }
7}

Applying this changed nothing: "No changes. Your infrastructure matches the configuration." Then I tried to destroy everything:

PROMPT
1terraform destroy
CODE
1Error: Instance cannot be destroyed
2
3  on main.tf line 46:
4  46: resource "docker_volume" "sqldata" {
5
6Resource docker_volume.sqldata has lifecycle.prevent_destroy set, but the
7plan calls for this resource to be destroyed. To avoid this error and
8continue with the plan, either disable lifecycle.prevent_destroy or reduce
9the scope of the plan using the -target option.

Terraform refused, and nothing was destroyed: all four containers were still running afterwards. To clean up I removed the guard on purpose and ran terraform destroy again:

CODE
1Destroy complete! Resources: 10 destroyed.
After I removed the guard and destroyed everything, Docker Desktop had no containers left

After I removed the guard and destroyed everything, Docker Desktop had no containers left

What Terraform gave me

What I changedWhat Terraform did
Added a database layerCreated the network, volume, password, image and container in the right order, and waited until SQL Server was ready
Changed the C# codeReplaced the web image and the three web containers, and left the database alone
Changed a stored procedureRe-ran only the schema script, and touched no containers
Deleted the database container by handRecreated only that container and re-ran the idempotent script, and the data was still there
Tried to destroy everythingRefused, because I had marked the volume as protected

Where this falls short

  • A shortcut for the schema. Running sqlcmd from terraform_data is simple enough to read in a blog post. Real projects usually apply database changes with a migration tool in the delivery pipeline, such as EF Core migrations, a DACPAC or Flyway, with versioned scripts and a history of what ran. Terraform is better at the infrastructure around it.
  • A throwaway password and the sa account. The web site logs in as the SQL Server administrator. A real site would use a login with only the permissions it needs, and it would execute only the stored procedures.
  • A development licence. The container runs SQL Server's Developer edition by default, which is licensed for development and testing, not for production.
  • A single database container. One container on one laptop gives me data that survives replacement, not high availability or backups.
  • Emulation. On Apple silicon, the Intel-only image runs under emulation, which is slower than native.

The workflow is the same one I used in Parts 1 and 2: plan, apply and destroy. The difference is that now it covers a stateful layer, and I had to think about which changes touch data and which do not. Part 4 moves the same site onto Kubernetes.

Everything in this post ran on Docker Desktop on my own machine, with Terraform 1.17.2, the kreuzwerker/docker provider 3.9.0, the hashicorp/random provider 3.9.1, Microsoft's public .NET 10 images and the public mssql/server:2022-latest image.