Skip to Content
Cloud Engineering Academy
10. Infrastructure as Code

Why infrastructure as code

Explain why a bank builds AWS environments from reviewed code instead of console clicks, name the three tools you will use in this module, and run a read-only inventory that shows how much of an account is not under code.

beginner⏱ 1 h 🟢 FreeDOP-C02SOA-C03

Assumes: .NET 10 LTS · AWS SDK for .NET v4 (AWSSDK.CloudFormation) · AWS CLI v2 · Region us-east-1. Verified against official sources on 2026-11-18.

Learning objectives

By the end of this lesson you can:

  • Explain, in two sentences, what infrastructure as code (IaC) is and which three problems it solves for a regulated bank.
  • Tell declarative from imperative infrastructure code, and say where CloudFormation, the AWS CDK and Terraform sit.
  • Describe the review flow that turns "someone clicked something" into "two people approved a diff".
  • List the honest costs of IaC (state, learning curve, blast radius) so you do not oversell it.
  • Run a read-only inventory of CloudFormation stacks with the CLI and with a small C# program, and use the results to see how much of an account is already under code.

Prerequisites

No AWS resources are created in this lesson. Everything you run is read-only and free.

Why this matters in banking

On a Friday afternoon an engineer at Harbourline opens the console to "quickly" widen a security group so a vendor can test a payment file upload. The vendor finishes on Monday. Nobody remembers the rule. Three months later a penetration tester finds a database port reachable from a vendor range that was supposed to be closed.

Everything that went wrong there is a process problem, not a skill problem:

  • The change was not reviewed: no second pair of eyes saw it.
  • The change was not recorded: the console has no pull request, no ticket link, no "why".
  • The change was not repeatable: test and production now differ, and nobody can say how.
  • The change was not reversible in a controlled way: the only undo is another click.

A bank also has to answer auditors who ask for evidence: "Show me every change to the production network in the last quarter and who approved each one." With IaC the answer is a Git log. Without it the answer is a CloudTrail search and a lot of guessing (CloudTrail is still your backstop, see CloudTrail for banks, but it tells you what happened, not whether it was approved).

Two more reasons are specific to regulated firms:

  • Disaster recovery and exit plans. Operational-resilience rules expect you to rebuild a service in another Region within a stated time. A rebuild from code is a command. A rebuild from memory is a project (see Operational resilience and third-party risk).
  • Separation of duties. The person who writes a change should not be the only person who can apply it. A pipeline that applies only merged, approved code enforces that.

The idea in plain language

Infrastructure as code means you describe your cloud resources (networks, databases, permissions, alarms) in text files, keep those files in Git, and let a tool make AWS match them.

Two styles exist:

StyleYou writeThe tool decidesExample
DeclarativeThe end state: "this bucket exists, is private and encrypted"The steps to get there, and what to change or deleteCloudFormation templates, Terraform HCL
ImperativeThe steps: "call CreateBucket, then PutBucketEncryption"Nothing, you drive every callA shell script of aws s3api commands, an AWS SDK program

Declarative wins for infrastructure because of idempotence: you can run it ten times and the tenth run changes nothing. It also gives you a diff: the tool compares what you want with what exists and shows the difference before it acts.

The AWS CDK is a small twist. You write C# (imperative-looking code with loops, classes and types), but the output is a declarative CloudFormation template. The C# is a generator; CloudFormation remains the engine that talks to AWS.

Analogy: a console click is a verbal instruction to a builder on site. IaC is the architect's drawing set. The drawing can be reviewed by the structural engineer before anyone lifts a tool, kept in the project file, compared with what was actually built, and used to build the same house again on another plot.

What problem the tools solve

Problem with console-built environmentsHow IaC addresses it
No reviewThe change is a pull request; branch protection requires an approver
No historygit log, git blame and tags are the change record
Environments differThe same code runs in dev, test and prod with different inputs only
Slow, error-prone rebuildsdeploy creates everything in dependency order
Hidden driftThe tool can compare code and reality and report differences
Security checks come lateScanners run on the plan or template before anything exists
Knowledge lives in headsThe code is the documentation that cannot go out of date

Honest limits

IaC is not free, and a good engineer says so:

  • You now operate a second system. For Terraform that is the state file; for CloudFormation it is the stack. Both can get stuck or corrupted.
  • The blast radius grows. A wrong destroy or a refactor that renames a resource can delete a production database. Protection (deletion policies, termination protection, plan review) is part of the work, not an extra. See Policy-as-code and secure deployment.
  • Not everything is supported on day one. New AWS features sometimes arrive in the console and API before CloudFormation, the CDK or the Terraform provider support them. CloudFormation is usually first among the three, but not always.
  • Secrets do not belong in code. The code may reference a secret by name. It must never contain its value.
  • Learning cost. Three tools, three vocabularies. This module spends 20 hours on them. That is cheaper than the first outage.

Microsoft / Azure comparison

You know (Microsoft/Azure)AWS equivalentWhat's different
ARM templates (JSON)CloudFormation templates (YAML or JSON)Same idea; CloudFormation has intrinsic functions (Ref, Fn::Sub) instead of ARM template expressions
BicepAWS CDK in C#Bicep is a new DSL that compiles to ARM. The CDK uses a real language you already know and compiles to CloudFormation
Terraform azurermTerraform aws providerSame tool and syntax. Resource names and state backends differ (S3 instead of an Azure Storage blob)
az deployment group what-ifCloudFormation change sets, cdk diff, terraform planThree flavours of "show me the diff first"
Azure Policy "deny" on deploymentCloudFormation Hooks, cdk-nag, Checkov, Service Control PoliciesPrevention is split between build-time scanners and account-level guardrails
Azure DevOps pipeline deploying an ARM templateCodePipeline / GitHub Actions deploying a stackModule 9 covers pipelines
Resource group as the deployment unitCloudFormation stack (CDK stack) or Terraform stateA stack is the unit that is created, updated and deleted together

Architecture

The same loop sits behind all three tools. Only the names change.

Security-boundary view. Two identities matter. The author can read and propose but cannot change production. The pipeline role can change production but only runs code that passed review. A third path, the console, should be read-only for production in a mature bank, with a monitored "break-glass" role for emergencies.

Three tools, one module

You will use all three, because real banks do.

CloudFormationAWS CDK (C#)Terraform
You writeYAML or JSON templateC# classesHCL files
EngineCloudFormation service (AWS)CloudFormation (via synthesis)Terraform CLI plus provider
StateHeld by AWS inside the stackHeld by AWS inside the stackA state file you store (S3)
DiffChange setcdk diffterraform plan
ReuseModules, nested stacksConstructs (L1/L2/L3), NuGet packagesModules
Testcfn-lint, Guard, validate-templatexUnit assertions, snapshot, cdk-nagterraform test, Checkov
ScopeAWS onlyAWS only (CDK for Terraform is a separate project)Any provider
CostFreeFreeFree CLI (paid HCP Terraform is optional)

The decision lesson compares them for a banking team. For now, keep one rule in mind: the tool matters less than the review flow around it.

A first look: the same bucket three ways

You will build this bucket properly in the next lessons. Read the three versions to see the shape of each tool. The bucket is private and encrypted with the account's S3-managed key to keep the examples short.

Resources:
  EvidenceBucket:
    Type: AWS::S3::Bucket
    Properties:
      PublicAccessBlockConfiguration:
        BlockPublicAcls: true
        BlockPublicPolicy: true
        IgnorePublicAcls: true
        RestrictPublicBuckets: true
      BucketEncryption:
        ServerSideEncryptionConfiguration:
          - ServerSideEncryptionByDefault:
              SSEAlgorithm: AES256

Notice what the CDK version does not say: how to build the public access block, the encryption configuration and the TLS-only bucket policy. The L2 construct fills those in from your three properties. That convenience is the CDK's main selling point, and the next lessons show where it can also hide things you should know about.

Step-by-step implementation

This lesson is a read-only investigation. You will measure how much of the sandbox account is "under code".

Sign in

aws sso login --profile learn-sandbox
aws sts get-caller-identity --profile learn-sandbox

You should see the sandbox account ID. If you get ExpiredToken, log in again.

List stacks that CloudFormation manages

# --stack-status-filter hides DELETE_COMPLETE stacks, which linger in the list for 90 days
aws cloudformation list-stacks --profile learn-sandbox --region us-east-1 \
  --stack-status-filter CREATE_COMPLETE UPDATE_COMPLETE UPDATE_ROLLBACK_COMPLETE ROLLBACK_COMPLETE \
  --query "StackSummaries[].[StackName,StackStatus,LastUpdatedTime||CreationTime]" --output table

A brand-new sandbox may show nothing, or only a CDKToolkit stack if you ran cdk bootstrap in an earlier lesson.

Count resources that carry the lab tags

Resources created by the labs carry the tag Project=cea-lab (the tagging convention every lab in this course follows). This call finds them wherever they live, regardless of how they were created:

aws resourcegroupstaggingapi get-resources --profile learn-sandbox --region us-east-1 \
  --tag-filters Key=Project,Values=cea-lab \
  --query "ResourceTagMappingList[].ResourceARN" --output text

Compare the two lists mentally. Resources in the second list that are not inside any stack from the first list were created by hand or by a tool you do not control. That gap is what this module closes.

Run the C# inventory

The program below does the first step in C#, so you can later extend it (for example to flag stacks without termination protection).

AWS Console instructions

Console → CloudFormation → Stacks. Use the status filter at the top, and the Drifted column once you have deployed something (the drift lesson explains it). Console → Resource Groups & Tag Editor → Tag Editor shows the tagged-resource view in the browser.

AWS CLI

The commands above are all you need. Two more are useful when investigating an unknown stack:

# what a stack contains, with the physical IDs
aws cloudformation list-stack-resources --stack-name <stack-name> --profile learn-sandbox

# the exact template CloudFormation last deployed (compare with Git)
aws cloudformation get-template --stack-name <stack-name> --profile learn-sandbox --query TemplateBody

Infrastructure as Code

The "Infrastructure as Code" section of this lesson is the three-way comparison above. The labs of the following lessons build the real thing.

Complete code

Create a console app and add the SDK package. The package is AWSSDK.CloudFormation (version 4.x of the AWS SDK for .NET; use whatever dotnet add package resolves to, ⚠ VERIFY the exact version in your lab notes).

dotnet new console -n StackInventory -f net10.0
cd StackInventory
dotnet add package AWSSDK.CloudFormation
dotnet add package AWSSDK.SSO
dotnet add package AWSSDK.SSOOIDC

The two extra packages let the SDK read an SSO profile created by aws configure sso.

Program.cs
using Amazon;
using Amazon.CloudFormation;
using Amazon.CloudFormation.Model;
using Amazon.Runtime.CredentialManagement;

// Read-only inventory of CloudFormation stacks in one Region.
// Usage: dotnet run -- learn-sandbox us-east-1
var profileName = args.Length > 0 ? args[0] : "learn-sandbox";
var region = RegionEndpoint.GetBySystemName(args.Length > 1 ? args[1] : "us-east-1");

var chain = new CredentialProfileStoreChain();
if (!chain.TryGetAWSCredentials(profileName, out var credentials))
{
    Console.Error.WriteLine($"Profile '{profileName}' not found. Run: aws configure sso");
    return 1;
}

using var cfn = new AmazonCloudFormationClient(credentials, region);

var live = new[]
{
    StackStatus.CREATE_COMPLETE, StackStatus.UPDATE_COMPLETE,
    StackStatus.UPDATE_ROLLBACK_COMPLETE, StackStatus.ROLLBACK_COMPLETE,
};

var stacks = new List<StackSummary>();
string? next = null;
do
{
    var page = await cfn.ListStacksAsync(new ListStacksRequest
    {
        StackStatusFilter = live.Select(s => s.Value).ToList(),
        NextToken = next,
    });
    stacks.AddRange(page.StackSummaries);
    next = page.NextToken;
} while (next is not null);

Console.WriteLine($"{stacks.Count} stack(s) in {region.SystemName}");
foreach (var s in stacks.OrderBy(s => s.StackName, StringComparer.Ordinal))
{
    var when = s.LastUpdatedTime ?? s.CreationTime;
    var flag = s.StackStatus == StackStatus.ROLLBACK_COMPLETE ? "  <-- failed create, delete it" : "";
    Console.WriteLine($"{s.StackName,-45} {s.StackStatus,-26} {when:yyyy-MM-dd}{flag}");
}

return 0;

Code explained line by line

  1. CredentialProfileStoreChain reads ~/.aws/config and ~/.aws/credentials, the same files as the CLI, so learn-sandbox works without any key in code.
  2. TryGetAWSCredentials returns false instead of throwing when the profile is missing, so the program can print a helpful message.
  3. new AmazonCloudFormationClient(credentials, region) creates a client. It is IDisposable, so using var releases the HTTP resources.
  4. live lists the statuses worth showing. ROLLBACK_COMPLETE is included on purpose: a stack in that state cannot be updated, only deleted, and it is a common surprise (see the CloudFormation lesson).
  5. ListStacksAsync returns one page at a time. The do/while loop follows NextToken until it is null.
  6. The output line pads columns with {value,-45} so the table lines up in a terminal.

Security considerations

⚠ Learning shortcut — not for production

You run this with your own SSO session in a sandbox. In production, an inventory like this runs from a read-only audit role in a security account, across all accounts, on a schedule. It should have cloudformation:ListStacks and cloudformation:DescribeStacks and nothing else. Never reuse a human administrator session for scheduled jobs.

  • IaC concentrates power: whoever can change the code that the pipeline applies can change production. Protect the main branch, require reviews and restrict who can edit the pipeline definition. See Git and GitHub for regulated teams.
  • The template is not secret, the parameters can be. Pass secret values through Secrets Manager references, never as plain parameters or in Git.
  • Stack outputs and Terraform state can reveal resource IDs and sometimes sensitive values. Treat them as internal data.
  • Never claim compliance from tooling alone. IaC gives you evidence of what was deployed and who approved it; your compliance team decides whether that meets a given control.

Banking use case

Harbourline's platform team owns a "landing" repository per environment. A developer who needs a new queue opens a pull request that adds six lines. The pipeline posts the change set into the pull request: "Create AWS::SQS::Queue, create AWS::IAM::Policy". A security engineer approves, and the merge triggers the deployment. Six months later an internal auditor samples ten changes: for each, the pull request shows who wrote it, who approved it, which scanner results were attached and which pipeline run applied it. The audit takes an afternoon instead of a week.

Common mistakes

  • "IaC means CDK or Terraform only." CloudFormation YAML is IaC too, and it is what the CDK produces. Learn it first, it makes every error message readable.
  • Treating the code as the whole truth. If people can still click in production, code and reality drift apart. Pair IaC with restricted console access and drift detection.
  • One giant stack or state for everything. A mistake then affects everything. Split by lifecycle and ownership (network, data, application).
  • Hard-coding account IDs and names. It prevents reuse. Take them from inputs, pseudo-parameters or data sources.
  • Skipping the diff. Applying without reading the plan or change set is the same as clicking blindly, only faster.

Troubleshooting

SymptomLikely causeFix
ExpiredToken or Unable to locate credentialsSSO session endedaws sso login --profile learn-sandbox
list-stacks shows nothingWrong Region, or nothing deployed yetAdd --region us-east-1, check the Region selector in the console
AccessDenied on resourcegroupstaggingapiThe permission set lacks tag:GetResourcesUse the sandbox administrator permission set for the lab, or ask for read access
C# program: Profile 'learn-sandbox' not foundThe profile name differs, or the SSO packages are missingCheck aws configure list-profiles, and add AWSSDK.SSO and AWSSDK.SSOOIDC
C# program: Token has expiredSSO session endedLog in with the CLI again, then rerun

Cost and cleanup

Cost: free. ListStacks and the tagging API are not charged. Nothing is created, so there is nothing to delete. Remove the StackInventory folder if you do not want to keep it.

# nothing to tear down; confirm your credentials still point at the sandbox
aws sts get-caller-identity --profile learn-sandbox --query Account --output text

Exercises

  • 🟢 Guided: run the three inventory commands, note how many stacks and how many tagged resources you found, and write one sentence on whether every tagged resource is inside a stack.
  • 🟡 Challenge: extend the C# program to call DescribeStacks and print, for each stack, whether termination protection is enabled. Add a --fail-if-unprotected flag that returns exit code 2 when any stack matching a name prefix is unprotected.
  • 🔴 Live problem: your CISO asks, "Which production resources were created outside code?" You have read-only access to one account. Write the approach: which APIs you would call, how you would compare resource lists with stack resources, what you could not detect, and what you would recommend to prevent the gap.

Assignment

Write a one-page IaC principles document for your portfolio repository titled "How Harbourline changes infrastructure". It must contain: the review flow (a diagram), who may apply to each environment, what happens in an emergency console change, and how drift is detected and reported. Keep it under 500 words.

Solutions

Knowledge check

Interview questions

  • "Why would you not just use the console for a one-off change?" Because a one-off change is not reviewed, recorded or repeatable, and one-offs are how environments drift. If an emergency forces it, record it, then bring the code into line the same day.
  • "Declarative or imperative: which do you prefer for infrastructure?" Declarative for the infrastructure itself because of idempotence and diffs. Imperative code is fine as a generator (the CDK) or for one-time migrations, as long as the output is reviewed as a declarative artefact.
  • "How do you prove to an auditor what changed in production?" The Git history for the environment repository, the approved pull requests, the pipeline run logs and the change set or plan attached to each run, with CloudTrail as independent confirmation.
  • "What is drift, and how do you handle it?" A difference between code and reality caused by out-of-band changes. Detect it on a schedule, decide whether to revert the resource or accept the change into code, and fix the process that allowed it.

Certification practice

Completion checklist

  • I can explain IaC and its three benefits for a bank in two sentences
  • I ran the CLI inventory and the C# program
  • I can say where CloudFormation, CDK and Terraform keep their state
  • I can name two honest costs of IaC
  • I confirmed nothing was created, so nothing is billing

Key takeaways

  • IaC turns infrastructure changes into reviewed, recorded, repeatable code changes. That is the audit story.
  • Declarative tools give idempotence and a diff; the CDK is a C# generator on top of CloudFormation.
  • Terraform keeps state in a file you protect; CloudFormation and the CDK keep it in AWS.
  • IaC without restricted console access and drift detection only gives you a recommended state, not a real one.
  • The review flow around the tool matters more than the tool.

Further reading

Independent learning resource — not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.

On this page