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.
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
- Module 10 overview, especially the "How the pieces fit" diagram.
- Module 1: AWS fundamentals: accounts, Regions and the console.
- Tools: AWS CLI v2 with the
learn-sandboxSSO profile, .NET 10 SDK (or Docker).
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:
| Style | You write | The tool decides | Example |
|---|---|---|---|
| Declarative | The end state: "this bucket exists, is private and encrypted" | The steps to get there, and what to change or delete | CloudFormation templates, Terraform HCL |
| Imperative | The steps: "call CreateBucket, then PutBucketEncryption" | Nothing, you drive every call | A 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 environments | How IaC addresses it |
|---|---|
| No review | The change is a pull request; branch protection requires an approver |
| No history | git log, git blame and tags are the change record |
| Environments differ | The same code runs in dev, test and prod with different inputs only |
| Slow, error-prone rebuilds | deploy creates everything in dependency order |
| Hidden drift | The tool can compare code and reality and report differences |
| Security checks come late | Scanners run on the plan or template before anything exists |
| Knowledge lives in heads | The 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
destroyor 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 equivalent | What's different |
|---|---|---|
| ARM templates (JSON) | CloudFormation templates (YAML or JSON) | Same idea; CloudFormation has intrinsic functions (Ref, Fn::Sub) instead of ARM template expressions |
| Bicep | AWS 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 azurerm | Terraform aws provider | Same tool and syntax. Resource names and state backends differ (S3 instead of an Azure Storage blob) |
az deployment group what-if | CloudFormation change sets, cdk diff, terraform plan | Three flavours of "show me the diff first" |
| Azure Policy "deny" on deployment | CloudFormation Hooks, cdk-nag, Checkov, Service Control Policies | Prevention is split between build-time scanners and account-level guardrails |
| Azure DevOps pipeline deploying an ARM template | CodePipeline / GitHub Actions deploying a stack | Module 9 covers pipelines |
| Resource group as the deployment unit | CloudFormation stack (CDK stack) or Terraform state | A 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.
| CloudFormation | AWS CDK (C#) | Terraform | |
|---|---|---|---|
| You write | YAML or JSON template | C# classes | HCL files |
| Engine | CloudFormation service (AWS) | CloudFormation (via synthesis) | Terraform CLI plus provider |
| State | Held by AWS inside the stack | Held by AWS inside the stack | A state file you store (S3) |
| Diff | Change set | cdk diff | terraform plan |
| Reuse | Modules, nested stacks | Constructs (L1/L2/L3), NuGet packages | Modules |
| Test | cfn-lint, Guard, validate-template | xUnit assertions, snapshot, cdk-nag | terraform test, Checkov |
| Scope | AWS only | AWS only (CDK for Terraform is a separate project) | Any provider |
| Cost | Free | Free | Free 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: AES256Notice 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-sandboxYou 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 tableA 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 textCompare 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 TemplateBodyInfrastructure 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.SSOOIDCThe two extra packages let the SDK read an SSO profile created by aws configure sso.
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
CredentialProfileStoreChainreads~/.aws/configand~/.aws/credentials, the same files as the CLI, solearn-sandboxworks without any key in code.TryGetAWSCredentialsreturnsfalseinstead of throwing when the profile is missing, so the program can print a helpful message.new AmazonCloudFormationClient(credentials, region)creates a client. It isIDisposable, sousing varreleases the HTTP resources.livelists the statuses worth showing.ROLLBACK_COMPLETEis included on purpose: a stack in that state cannot be updated, only deleted, and it is a common surprise (see the CloudFormation lesson).ListStacksAsyncreturns one page at a time. Thedo/whileloop followsNextTokenuntil it is null.- 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
| Symptom | Likely cause | Fix |
|---|---|---|
ExpiredToken or Unable to locate credentials | SSO session ended | aws sso login --profile learn-sandbox |
list-stacks shows nothing | Wrong Region, or nothing deployed yet | Add --region us-east-1, check the Region selector in the console |
AccessDenied on resourcegroupstaggingapi | The permission set lacks tag:GetResources | Use the sandbox administrator permission set for the lab, or ask for read access |
C# program: Profile 'learn-sandbox' not found | The profile name differs, or the SSO packages are missing | Check aws configure list-profiles, and add AWSSDK.SSO and AWSSDK.SSOOIDC |
C# program: Token has expired | SSO session ended | Log 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 textExercises
- 🟢 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
DescribeStacksand print, for each stack, whether termination protection is enabled. Add a--fail-if-unprotectedflag 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
Expected shape: the list-stacks output shows zero or a few stacks (for example CDKToolkit); the tag query shows resources only if you deployed earlier labs. Your sentence should say that tagged resources not inside any stack were created by hand or by another tool, and that this is exactly the gap IaC removes. If you see a stack in ROLLBACK_COMPLETE, note that it must be deleted before it can be reused.
Call DescribeStacksAsync(new DescribeStacksRequest()) and read Stack.EnableTerminationProtection for each stack (it is a nullable boolean in the SDK model, so treat null as false). Filter with StackName.StartsWith(prefix, StringComparison.Ordinal). Track a bool anyUnprotected and return 2 at the end if the flag was passed and it is true. Use distinct exit codes (0 fine, 1 usage error, 2 policy failure) so a pipeline can tell the cases apart. The reason to do this in code: a check that runs on a schedule and fails loudly beats a checklist item.
Use AWS Config or the Resource Explorer for a full resource list (listing every service by hand does not scale), then call list-stack-resources for every stack and compare physical IDs. What you cannot detect: resources of types the inventory does not cover, and changes inside a resource (a security group rule) unless you run drift detection. Recommend: restrict console write access in production with a Service Control Policy plus a break-glass role, run drift detection on a schedule, and tag every resource with the owning stack or repository so orphans stand out.
Knowledge check
Answer: The tool compares the desired and current state and works out the steps, so it is repeatable (idempotent) and can show a diff first. A script does exactly what it says every time, even if the resource already exists, and cannot tell you what it will change.
Answer: The C# runs only at synthesis time and produces a CloudFormation template. CloudFormation, the engine that talks to AWS, is declarative. Your loops and conditions generate a document; they do not run during deployment.
Answer: It cannot stop people changing resources in the console (you need permissions and guardrails for that), and it cannot decide whether a design meets a regulation (people do). It also does not remove the need to protect state, secrets and the pipeline.
Answer: Terraform keeps a state file that you store and protect (usually S3). CloudFormation keeps that information inside the stack, in the AWS service, so there is no file for you to host.
Answer: It enforces separation of duties: only reviewed, merged code reaches production, the applying identity has a narrow, auditable permission set, and a compromised laptop cannot change production directly.
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
A team provisions production resources by running a shell script of AWS CLI calls from a laptop. Auditors want proof of who approved each infrastructure change and the ability to recreate the environment in another Region. What should the team do?
A. Store the script in an S3 bucket with versioning. B. Convert the environment to CloudFormation templates in Git and deploy through a pipeline with pull-request approval. C. Enable CloudTrail and keep the logs for seven years. D. Give every engineer the AdministratorAccess managed policy so changes are faster.
Answer: B. Templates in Git with a pipeline give review, history and repeatable deployment to another Region. A is storage, not review or declarative repeatability. C records events but does not provide approval or recreation. D removes controls.
An operations engineer must deploy the same stack to three Regions with identical settings except an instance size. Which approach minimises manual work and error?
A. Click through the console in each Region. B. Use one template with a parameter for the instance size and deploy it per Region. C. Copy and edit three separate templates. D. Use a different tool per Region.
Answer: B. One reviewed template with parameters keeps environments consistent. A and C introduce drift and copy errors. D multiplies tooling for no benefit.
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.
Related lessons and next steps
- Next: AWS CloudFormation fundamentals
- Later in this module: CloudFormation vs CDK vs Terraform
- Already available: Terraform fundamentals
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.
Module 10: Infrastructure as Code
Define whole AWS environments as reviewable code with CloudFormation, the AWS CDK in C# and Terraform. You learn state, drift, testing and policy-as-code, then build the same banking environment twice, in CDK and in Terraform, and deploy, change, detect drift and destroy it.
AWS CloudFormation fundamentals
Write a CloudFormation template for a private, KMS-encrypted audit bucket, lint it locally, deploy it through a reviewed change set, read what happens on rollback, and protect data with deletion policies.