Build a Three-Account AWS Landing Zone

Build and test a secure AWS landing zone with Terraform mocks.

Introduction

30 Second Summary

Security gets harder to trust when important systems and activity records all live in one place. A single mistake can blur ownership and make problems harder to trace.

In this project, you will build a locally tested three-account AWS landing zone blueprint with Terraform. Mocked tests will prove each account boundary without creating live cloud resources.

What You'll Build

When you run the finished blueprint, you will see green security checks and a rendered architecture diagram that traces governance, private workload traffic, and centralized audit logs across three accounts.

By the end of this project, you'll have:

  • A locally testable account blueprint that proves management, security, and workload resources target the intended accounts without requesting AWS credentials.
  • A private Amazon VPC where application traffic can reach the database only through a TCP 5432 path enforced by security groups.
  • A centralized audit design that protects logs in Amazon S3. AWS CloudTrail and VPC Flow Logs feed that destination. A rendered Mermaid diagram makes every account boundary and log flow visible.
  • Secret Mission: Decode the generated bucket policy in a Terraform test and prove each logging service is restricted to its intended source.

Are there any prerequisites?

You need a Mac for the guaranteed local path. The guide sets up every required tool and does not require cloud credentials or an existing organization.

Before We Start

This opening checkpoint locks in your reason for building a locally tested three-account AWS security blueprint before any hands-on work begins. The blueprint assigns governance to the management account, centralized logs to the security account, and the private workload to the workload account.

Set Up the Mac Toolchain

Your landing-zone blueprint needs a predictable local toolchain before any Terraform files can exist. Your Mac currently has none of the required tools.

The guaranteed path stays local. It does not request AWS credentials or create AWS resources.

In this step, get ready to:
  • Verify that your macOS version supports Homebrew.
  • Install Terraform CLI 1.16.4.
  • Prepare Visual Studio Code with an empty project folder.
Check macOS and install Homebrew

Homebrew provides the supported package-manager path for macOS Sonoma 14 or newer. An older Mac uses HashiCorp's direct Terraform download instead.

  • Press Cmd+Space to open Spotlight.
  • Type Terminal in Spotlight.
  • Press Enter to open Terminal.
  • Check your installed macOS version by running this command:
sw_vers -productVersion

What does this command do?

The command prints only your installed macOS product version. The first number determines whether Homebrew supports your Mac.

✔️ My Mac runs Sonoma or newer

A version beginning with 14 or a higher number supports the Homebrew path.

What should I expect?

The installer can request confirmation or your Mac login password. Password characters stay hidden while you type in Terminal.

  • Install Homebrew by running its official installer:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

What does this command do?

The command downloads the official Homebrew installer over HTTPS. The shell then runs that installer on your Mac.

The installer ends with a completion summary. Homebrew is now available for the Terraform installation.

Did the Homebrew installer stop?

Check that your internet connection is active. Respond to any confirmation request still waiting in Terminal.

If the installer reports a permissions problem, confirm that your macOS account can approve software installations.

Help me troubleshoot the Homebrew installation on my Mac.

ⓧ My Mac runs an older macOS version

This Mac needs the direct Terraform binary path. You can skip Homebrew for this project.

  • Continue to the Terraform check below.

Why use the direct download?

Homebrew supports macOS Sonoma 14 or newer. HashiCorp also distributes Terraform as a standalone executable for manual installation.

Install and verify Terraform

The project pins Terraform CLI to 1.16.4. Using that exact version keeps your local tests aligned with the configuration you build next.

  • Check the Terraform version currently available in Terminal by running:
terraform version

What does this command do?

The command prints the installed Terraform binary version. It also reports the platform used by the binary.

✔️ I see Terraform v1.16.4

Terraform v1.16.4 is ready. You can continue to the Visual Studio Code setup.

ⓧ I see a different Terraform version

Your installed Terraform version does not match the project's 1.16.4 pin. Choose the installation path that matches your earlier macOS check.

Homebrew path

  • Upgrade Terraform from HashiCorp's Homebrew tap by running:
brew upgrade hashicorp/tap/terraform
What does this command do?

Homebrew replaces the installed Terraform formula with the latest version in HashiCorp's tap. That version is 1.16.4 for this project.

  • Confirm the upgraded version by running:
terraform version
What does this command do?

This check reads the Terraform executable now available through your shell. The first line identifies the installed version.

You should now see Terraform v1.16.4 in the first line.

Still seeing a different version?

Close Terminal after the upgrade. Reopen it through Spotlight so the new shell can find the upgraded executable.

Help me find why Terminal still uses another Terraform version.

Direct binary path

Your Downloads folder now contains the Terraform 1.16.4 archive.

  • Double-click the downloaded archive in Finder to extract it.

Finder now shows the extracted terraform executable in your Downloads folder.

The next command replaces the executable in your command path. macOS can request your login password before making this system-level change.

  • Move the extracted Terraform executable into your command path by running:
sudo mv ~/Downloads/terraform /usr/local/bin/
What does this command do?

The command moves the Terraform executable from Downloads into /usr/local/bin/. Terminal searches this directory for commands.

  • Confirm the replacement by running:
terraform version
What does this command do?

This check runs the Terraform executable from your command path. The first line identifies its version.

You should now see Terraform v1.16.4 in the first line.

Does Terminal still use the old binary?

Close Terminal after moving the executable. Reopen it through Spotlight before checking the version again.

Help me replace an older Terraform binary on macOS.

ⓧ Command not found

Terraform is not installed yet. Choose the path that matches your earlier macOS check.

Homebrew path

  • Add HashiCorp's Homebrew tap by running these commands:
brew tap hashicorp/tap
brew install hashicorp/tap/terraform
What do these commands do?
  • The first command adds HashiCorp's official package repository to Homebrew.
  • The second command installs Terraform from that repository.

The download can take a minute while Homebrew retrieves the signed Terraform binary. The installation summary confirms when the executable is ready.

  • Verify the installed version by running:
terraform version
What does this command do?

The command runs the newly installed Terraform executable. The first line identifies its version.

You should see Terraform v1.16.4 in the first line. Your local infrastructure tool is ready.

Is Terraform still unavailable?

Close Terminal after the installation. Reopen it through Spotlight so your shell can load the updated command path.

If Homebrew is unavailable too, confirm that its installer completed in the previous substep.

Help me make the Terraform command available after installing it with Homebrew.

Direct binary path

Your Downloads folder now contains the Terraform 1.16.4 archive.

  • Double-click the downloaded archive in Finder to extract it.

Finder now shows the extracted terraform executable in your Downloads folder.

The next command places the executable in your command path. macOS can request your login password before making this system-level change.

  • Move the extracted Terraform executable into your command path by running:
sudo mv ~/Downloads/terraform /usr/local/bin/
What does this command do?

The command moves the Terraform executable from Downloads into /usr/local/bin/. Terminal searches this directory for commands.

  • Verify the installed version by running:
terraform version
What does this command do?

The command runs the Terraform executable from your command path. The first line identifies its version.

You should see Terraform v1.16.4 in the first line. Your local infrastructure tool is ready.

Is the manual installation unavailable?

Confirm that Finder extracted a file named terraform in Downloads. Close Terminal after moving the file.

Reopen Terminal through Spotlight before checking the version again.

Help me complete the manual Terraform installation on macOS.

Install Visual Studio Code and open the workspace

Visual Studio Code gives the Terraform blueprint one workspace for files and terminal commands. Its shell command lets Terminal open the current folder directly in the editor.

Your Downloads folder now contains a Visual Studio Code .dmg file.

  • Open the downloaded .dmg file.
  • Drag Visual Studio Code.app into Applications.

The Applications folder now contains Visual Studio Code.

  • Press Cmd+Space to open Spotlight.
  • Type Visual Studio Code in Spotlight.
  • Press Enter to start the editor.

Visual Studio Code opens to its initial editor window.

  • Press Cmd+Shift+P to open the Command Palette.
  • Type Shell Command: Install 'code' command in PATH.
  • Select the matching command from the Command Palette.

Visual Studio Code confirms that the shell command is installed. Terminal can now use code . to open a folder.

  • Switch back to the Terminal window from earlier.
  • Create the secure-aws-landing-zone folder on your Desktop by running these commands:
cd ~/Desktop
mkdir secure-aws-landing-zone
cd secure-aws-landing-zone

What do these commands do?

  • The first command moves Terminal to your Desktop.
  • The second command creates the secure-aws-landing-zone folder.
  • The final command makes that folder Terminal's current location.

Before you run the final check, what two signs would prove that Terraform and Visual Studio Code are both ready?

  • Verify Terraform from the project folder by running these commands:
terraform version
code .

What do these commands prove?

  • The first command confirms which Terraform binary is available inside the project folder.
  • The second command opens the current folder in Visual Studio Code.

You should see Terraform v1.16.4 in Terminal. Visual Studio Code opens the empty secure-aws-landing-zone folder.

That is the toolchain complete. Your editor and Terraform CLI now point at the same empty workspace.

Did the final check fail?

If Terraform is unavailable, reopen Terminal before checking the version again. If code . is unavailable, repeat the shell-command installation from the Visual Studio Code Command Palette.

If the folder does not open, confirm that Terminal is inside ~/Desktop/secure-aws-landing-zone.

Help me finish the macOS toolchain verification.

Your local workspace is ready without any cloud access. Next, you'll encode the three account boundaries and prove the first private network plan with mocked tests.

Draw the Account Boundaries

Your local toolchain is ready. The empty project now needs a Terraform structure that makes every AWS account boundary visible.

This step maps each account to an explicit provider alias. It also builds the first private Amazon VPC plan. A mocked test proves the design works without credentials or cloud resources.

In this step, get ready to:
  • Pin Terraform 1.16.4 with HashiCorp AWS Provider 6.66.0.
  • Map the management, security, and workload account targets.
  • Test the private workload network with mocked providers.
Map the account boundaries

Provider aliases let one Terraform module target several AWS accounts. Each resource can name its intended account instead of relying on an ambiguous default provider.

Why use explicit provider aliases?

AWS accounts act as security isolation boundaries. Separate aliases make those boundaries visible in the configuration.

Each alias uses its own AssumeRole input. The allowed_account_ids guardrail prevents a provider from targeting an unexpected account.

  • Select the Explorer view in the Visual Studio Code Activity Bar.
  • Select the New File... button.
  • Enter versions.tf and press Enter.
  • Pin the required Terraform and AWS provider versions by adding this configuration:
terraform {
  required_version = "= 1.16.4"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "= 6.66.0"
    }
  }
}

What does this configuration do?

  • The required_version constraint keeps the module on Terraform 1.16.4.
  • The required_providers block tells Terraform to install hashicorp/aws at version 6.66.0.
  • Save versions.tf.
  • Confirm versions.tf appears inside secure-aws-landing-zone in the Explorer.

Don't see versions.tf?

Check that the Explorer still shows secure-aws-landing-zone as the open folder. Recreate the file inside that folder if it appears elsewhere.

Make sure the filename ends in .tf.

Help me find my Terraform file.

The module also needs inputs for account IDs, deployment roles, and network ranges. Defaults are safe for local planning because the mocked test supplies example account values.

  • Select the New File... button in the Explorer.
  • Enter variables.tf and press Enter.
  • Define the Region and account ID inputs by adding this first group:
variable "aws_region" {
  description = "AWS Region used by the three provider configurations."
  type        = string
  default     = "us-east-1"
}

variable "management_account_id" {
  description = "AWS Organizations management account ID."
  type        = string
}

variable "security_account_id" {
  description = "Security and log archive account ID."
  type        = string
}

variable "workload_account_id" {
  description = "Workload account ID."
  type        = string
}

What do these variables represent?

The Region controls where regional resources belong. The three account IDs define the governance, logging, and workload boundaries.

The local test supplies example values for every account ID. No AWS account lookup occurs.

  • Add the role and organization inputs below the existing account variables:
variable "management_role_arn" {
  description = "Pre-provisioned deployment role ARN in the management account."
  type        = string
}

variable "security_role_arn" {
  description = "Pre-provisioned deployment role ARN in the security account."
  type        = string
}

variable "workload_role_arn" {
  description = "Pre-provisioned deployment role ARN in the workload account."
  type        = string
}

variable "organization_id" {
  description = "AWS Organizations organization ID."
  type        = string
}

variable "audit_bucket_name" {
  description = "Globally unique name for the central audit-log bucket."
  type        = string
}

Why pass role ARNs as inputs?

A live deployment needs a pre-provisioned role in each account. Keeping those ARNs as inputs lets the blueprint describe trust paths without attempting to bootstrap its own access.

The organization ID and audit bucket name support the centralized logging configuration added later.

  • Add the workload network inputs at the bottom of variables.tf.
variable "workload_vpc_cidr" {
  description = "CIDR block for the workload VPC."
  type        = string
  default     = "10.20.0.0/16"
}

variable "app_subnet_cidr" {
  description = "CIDR block for the private application subnet."
  type        = string
  default     = "10.20.10.0/24"
}

variable "data_subnet_cidr" {
  description = "CIDR block for the private data subnet."
  type        = string
  default     = "10.20.20.0/24"
}

How is the network divided?

The workload VPC uses 10.20.0.0/16 as its address range. The application subnet receives 10.20.10.0/24.

The data subnet receives 10.20.20.0/24. Separate ranges make the two workload tiers visible in the plan.

  • Save variables.tf.
  • Confirm the file ends with the data_subnet_cidr variable.

Seeing red underlines in variables.tf?

Check that every variable block has matching braces. Confirm that each description and default value has matching quotation marks.

Compare the variable names carefully because the provider configuration uses them exactly.

Help me check my Terraform variables.

The provider configuration is the actual account map. Each alias carries one role ARN plus one allowed account ID.

  • Select the New File... button in the Explorer.
  • Enter providers.tf and press Enter.
  • Define the shared tags and organization trail identity by adding this block:
locals {
  common_tags = {
    Project   = "secure-three-account-landing-zone"
    ManagedBy = "Terraform"
  }

  trail_name = "organization-security-trail"
  trail_arn  = "arn:aws:cloudtrail:${var.aws_region}:${var.management_account_id}:trail/${local.trail_name}"
}

What do these local values hold?

The common_tags map gives every supported resource the same project ownership labels. The trail_name value keeps the future organization trail name consistent.

The trail_arn value combines the Region with the management account ID. The audit policy uses that identity later.

  • Add the management-account provider below the locals block:
provider "aws" {
  alias               = "management"
  region              = var.aws_region
  allowed_account_ids = [var.management_account_id]

  assume_role {
    role_arn     = var.management_role_arn
    session_name = "terraform-landing-zone"
  }

  default_tags {
    tags = local.common_tags
  }
}

What does the management alias control?

The aws.management alias represents the AWS Organizations management account. Its future responsibility is the organization trail.

The session name identifies the Terraform role session. The account guardrail accepts only the management account ID.

  • Add the security-account provider below the management provider:
provider "aws" {
  alias               = "security"
  region              = var.aws_region
  allowed_account_ids = [var.security_account_id]

  assume_role {
    role_arn     = var.security_role_arn
    session_name = "terraform-landing-zone"
  }

  default_tags {
    tags = local.common_tags
  }
}

What does the security alias control?

The aws.security alias represents the security account. That account becomes the destination for centralized audit logs.

Its guardrail checks the security account ID before a live provider can proceed.

  • Add the workload-account provider at the bottom of providers.tf.
provider "aws" {
  alias               = "workload"
  region              = var.aws_region
  allowed_account_ids = [var.workload_account_id]

  assume_role {
    role_arn     = var.workload_role_arn
    session_name = "terraform-landing-zone"
  }

  default_tags {
    tags = local.common_tags
  }
}

What does the workload alias control?

The aws.workload alias owns the application network. Every VPC resource in this step names that provider explicitly.

This keeps workload resources away from the governance and logging accounts.

  • Save providers.tf.
  • Confirm the file contains exactly three provider "aws" blocks.

Missing a provider alias?

Check for the aliases management, security, and workload.

Confirm that each provider references the matching account ID and role ARN.

Help me compare my provider aliases.

The test needs one visible value that summarizes the three targets. A small output exposes that map without revealing credentials.

  • Select the New File... button in the Explorer.
  • Enter outputs.tf and press Enter.
  • Expose the three account targets by adding this output:
output "account_targets" {
  description = "AWS account IDs targeted by each provider boundary."
  value = {
    management = var.management_account_id
    security   = var.security_account_id
    workload   = var.workload_account_id
  }
}

Why add this output now?

The account_targets output gives the local test an observable account map. Its values come from the mocked test inputs.

No role ARN or credential appears in the output.

  • Save outputs.tf.
  • Confirm outputs.tf appears beside the other Terraform files.

Account output showing a warning?

Confirm the output references management_account_id, security_account_id, and workload_account_id exactly.

Help me fix my account output.

Build the private workload network

The workload account needs separate application and data tiers. Empty route tables keep both subnets private because the configuration adds no internet route.

  • Select the New File... button in the Explorer.
  • Enter network.tf and press Enter.
  • Create the workload VPC by adding this resource:
resource "aws_vpc" "workload" {
  provider = aws.workload

  cidr_block           = var.workload_vpc_cidr
  enable_dns_support   = true
  enable_dns_hostnames = true

  tags = {
    Name = "workload-vpc"
  }
}

What does the VPC resource establish?

The aws_vpc.workload resource explicitly uses aws.workload. Its address range comes from workload_vpc_cidr.

DNS support gives private workloads names they can resolve inside the VPC.

  • Save network.tf.
  • Confirm the file begins with resource "aws_vpc" "workload".

VPC resource showing a warning?

Confirm the provider reference is aws.workload. Check that workload_vpc_cidr matches the variable name exactly.

Help me check my workload VPC resource.

  • Add the private application and data subnets below the VPC resource:
resource "aws_subnet" "app" {
  provider = aws.workload

  vpc_id                  = aws_vpc.workload.id
  cidr_block              = var.app_subnet_cidr
  map_public_ip_on_launch = false

  tags = {
    Name = "private-app"
    Tier = "application"
  }
}

resource "aws_subnet" "data" {
  provider = aws.workload

  vpc_id                  = aws_vpc.workload.id
  cidr_block              = var.data_subnet_cidr
  map_public_ip_on_launch = false

  tags = {
    Name = "private-data"
    Tier = "data"
  }
}

How do the subnets stay private?

Both subnets belong to aws_vpc.workload and use separate CIDR ranges. The map_public_ip_on_launch setting is false for each subnet.

The tags distinguish the application tier from the data tier in a plan.

  • Save network.tf.
  • Confirm both subnet resources set map_public_ip_on_launch to false.

Subnet references not resolving?

Check that both vpc_id values reference aws_vpc.workload.id.

Confirm the CIDR variable names match variables.tf.

Help me fix my subnet references.

  • Add empty route tables for the two private tiers:
resource "aws_route_table" "app" {
  provider = aws.workload

  vpc_id = aws_vpc.workload.id
  route  = []

  tags = {
    Name = "private-app"
  }
}

resource "aws_route_table" "data" {
  provider = aws.workload

  vpc_id = aws_vpc.workload.id
  route  = []

  tags = {
    Name = "private-data"
  }
}

Why are the route lists empty?

The explicit empty route lists declare that Terraform manages no extra routes. The implicit local VPC route remains available.

No internet gateway route exists in either table.

  • Save network.tf.
  • Confirm both route table resources contain route = [].

Route table lists not empty?

Remove any nested route blocks. Each route table should contain the single assignment route = [].

Help me check my private route tables.

  • Associate each private subnet with its matching route table:
resource "aws_route_table_association" "app" {
  provider = aws.workload

  subnet_id      = aws_subnet.app.id
  route_table_id = aws_route_table.app.id
}

resource "aws_route_table_association" "data" {
  provider = aws.workload

  subnet_id      = aws_subnet.data.id
  route_table_id = aws_route_table.data.id
}

What do the associations enforce?

The application subnet receives the application route table. The data subnet receives the data route table.

This removes ambiguity about which routing policy applies to each tier.

  • Save network.tf.
  • Confirm each association references the matching subnet and route table names.

Association names crossed over?

Check that the app association uses both aws_subnet.app.id and aws_route_table.app.id.

Check that the data association uses the two matching data references.

Help me fix my route table associations.

  • Lock down the VPC default security group by adding this final resource:
resource "aws_default_security_group" "workload" {
  provider = aws.workload

  vpc_id  = aws_vpc.workload.id
  ingress = []
  egress  = []

  tags = {
    Name = "workload-default-deny"
  }
}

What does default deny mean here?

The aws_default_security_group.workload resource adopts the VPC default security group. Its empty ingress and egress lists remove the default traffic rules.

Future workloads need dedicated security groups with explicit paths.

  • Save network.tf.
  • Confirm the final resource contains empty ingress and egress lists.

Default security group still allows traffic?

Check that both rule attributes use empty lists. Remove any nested ingress or egress blocks.

Confirm the resource type is aws_default_security_group.

Help me verify the default-deny configuration.

Test the local plan

A mock provider uses the real AWS provider schema while replacing cloud operations during the plan. This lets the test evaluate account and network assertions without credentials.

  • Right-click the secure-aws-landing-zone folder in the Explorer.
  • Select New Folder.
  • Enter tests and press Enter.
  • Select the new tests folder.
  • Select the New File... button.
  • Enter landing_zone.tftest.hcl and press Enter.
  • Add the three mocked provider configurations:
mock_provider "aws" {
  alias           = "management"
  override_during = plan
}

mock_provider "aws" {
  alias           = "security"
  override_during = plan

  mock_resource "aws_s3_bucket" {
    defaults = {
      arn = "arn:aws:s3:::secure-landing-zone-audit-logs-example"
    }
  }
}

mock_provider "aws" {
  alias           = "workload"
  override_during = plan
}

How do the mocks replace AWS access?

Each mock has the same alias as its root provider configuration. The override_during = plan setting keeps the test on a local plan path.

The security mock supplies a predictable future S3 bucket ARN. No bucket is created.

The test run is longer than one code chunk. Add the following pieces in order. The final piece closes the run block before you save the file.

  • Start the plan-only test with example account values:
run "landing_zone_is_secure" {
  command = plan

  variables {
    aws_region            = "us-east-1"
    management_account_id = "111111111111"
    security_account_id   = "222222222222"
    workload_account_id   = "333333333333"
    management_role_arn   = "arn:aws:iam::111111111111:role/TerraformExecutionRole"
    security_role_arn     = "arn:aws:iam::222222222222:role/TerraformExecutionRole"
    workload_role_arn     = "arn:aws:iam::333333333333:role/TerraformExecutionRole"
    organization_id       = "o-exampleorgid"
    audit_bucket_name     = "secure-landing-zone-audit-logs-example"
  }

What does this test run plan?

The command = plan setting evaluates the module without applying it. The variables provide deterministic values for every required input.

The role ARNs are examples consumed by the mocked providers. Terraform does not use them to contact AWS.

  • Add the account-boundary assertion inside the open run block:
  assert {
    condition = (
      output.account_targets.management == "111111111111" &&
      output.account_targets.security == "222222222222" &&
      output.account_targets.workload == "333333333333"
    )
    error_message = "Each provider boundary must target the intended AWS account."
  }

What does the account assertion prove?

The assertion compares every account output with the matching test input. A crossed account ID makes the test fail with a specific explanation.

  • Add the private-network assertion below the account assertion:
  assert {
    condition = (
      aws_vpc.workload.cidr_block == "10.20.0.0/16" &&
      aws_subnet.app.map_public_ip_on_launch == false &&
      aws_subnet.data.map_public_ip_on_launch == false &&
      length(aws_route_table.app.route) == 0 &&
      length(aws_route_table.data.route) == 0
    )
    error_message = "The workload VPC must use private subnets with no configured internet routes."
  }

What does the network assertion prove?

The assertion checks the workload CIDR plus both public-IP settings. It also confirms that neither route table contains a configured route.

A passing result proves the planned subnets have no direct internet path in this configuration.

  • Add the default security-group assertion below the network assertion:
  assert {
    condition = (
      length(aws_default_security_group.workload.ingress) == 0 &&
      length(aws_default_security_group.workload.egress) == 0
    )
    error_message = "The workload default security group must not allow ingress or egress."
  }
}

What does the final assertion prove?

The final assertion counts the default security group's ingress and egress rules. Both collections must be empty.

The last brace closes the landing_zone_is_secure run block.

  • Save tests/landing_zone.tftest.hcl.
  • Confirm the Explorer shows landing_zone.tftest.hcl inside the tests folder.

Test file showing unmatched braces?

Confirm the final code chunk ends with two closing braces. One closes the assertion. The other closes the run block.

Check that all three mock provider blocks appear before the run block.

Help me check my Terraform test structure.

The first initialization can take a minute while Terraform downloads the AWS provider. A short pause here is expected.

  • Initialize the local module without a backend by running this command in the existing project terminal:
terraform init -backend=false

What does this command do?

The command installs the pinned provider into the local Terraform working directory. The -backend=false flag prevents backend initialization.

This keeps the project local while Terraform prepares the provider schema needed by the test.

You should see Terraform report successful initialization. The provider installation uses version 6.66.0.

Initialization did not succeed?

Confirm the terminal is still inside the secure-aws-landing-zone folder. Check that versions.tf contains the exact provider source and version pin.

A provider download failure can come from a temporary network problem. Retry the command after confirming your internet connection.

Help me troubleshoot Terraform initialization.

Before you run the test, consider whether mocked providers can produce a valid plan without AWS credentials.

  • Run the account-boundary and private-network test with this command:
terraform test

What does this command test?

Terraform searches the tests directory and evaluates the plan with the three mock provider aliases. The assertions inspect the planned account map plus the private network controls.

The command creates no AWS resources. It also requires no AWS credentials.

You should see the landing_zone_is_secure run report pass. That result proves the three account targets and private network can be planned locally.

Terraform test did not pass?

Read the assertion message first. It identifies whether the mismatch involves account targets, private subnet settings, route tables, or the default security group.

Check that every network resource uses provider = aws.workload where shown. Confirm that the mock aliases match the root provider aliases exactly.

Help me debug the failing Terraform test.

✔️ Awesome, I've got everything!

Great work. Save every file and keep the passing test visible in your terminal.

ⓧ I'd like to double check the full code

Check versions.tf
terraform {
  required_version = "= 1.16.4"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "= 6.66.0"
    }
  }
}
Check variables.tf
variable "aws_region" {
  description = "AWS Region used by the three provider configurations."
  type        = string
  default     = "us-east-1"
}

variable "management_account_id" {
  description = "AWS Organizations management account ID."
  type        = string
}

variable "security_account_id" {
  description = "Security and log archive account ID."
  type        = string
}

variable "workload_account_id" {
  description = "Workload account ID."
  type        = string
}

variable "management_role_arn" {
  description = "Pre-provisioned deployment role ARN in the management account."
  type        = string
}

variable "security_role_arn" {
  description = "Pre-provisioned deployment role ARN in the security account."
  type        = string
}

variable "workload_role_arn" {
  description = "Pre-provisioned deployment role ARN in the workload account."
  type        = string
}

variable "organization_id" {
  description = "AWS Organizations organization ID."
  type        = string
}

variable "audit_bucket_name" {
  description = "Globally unique name for the central audit-log bucket."
  type        = string
}

variable "workload_vpc_cidr" {
  description = "CIDR block for the workload VPC."
  type        = string
  default     = "10.20.0.0/16"
}

variable "app_subnet_cidr" {
  description = "CIDR block for the private application subnet."
  type        = string
  default     = "10.20.10.0/24"
}

variable "data_subnet_cidr" {
  description = "CIDR block for the private data subnet."
  type        = string
  default     = "10.20.20.0/24"
}
Check providers.tf
locals {
  common_tags = {
    Project   = "secure-three-account-landing-zone"
    ManagedBy = "Terraform"
  }

  trail_name = "organization-security-trail"
  trail_arn  = "arn:aws:cloudtrail:${var.aws_region}:${var.management_account_id}:trail/${local.trail_name}"
}

provider "aws" {
  alias               = "management"
  region              = var.aws_region
  allowed_account_ids = [var.management_account_id]

  assume_role {
    role_arn     = var.management_role_arn
    session_name = "terraform-landing-zone"
  }

  default_tags {
    tags = local.common_tags
  }
}

provider "aws" {
  alias               = "security"
  region              = var.aws_region
  allowed_account_ids = [var.security_account_id]

  assume_role {
    role_arn     = var.security_role_arn
    session_name = "terraform-landing-zone"
  }

  default_tags {
    tags = local.common_tags
  }
}

provider "aws" {
  alias               = "workload"
  region              = var.aws_region
  allowed_account_ids = [var.workload_account_id]

  assume_role {
    role_arn     = var.workload_role_arn
    session_name = "terraform-landing-zone"
  }

  default_tags {
    tags = local.common_tags
  }
}
Check outputs.tf
output "account_targets" {
  description = "AWS account IDs targeted by each provider boundary."
  value = {
    management = var.management_account_id
    security   = var.security_account_id
    workload   = var.workload_account_id
  }
}
Check network.tf
resource "aws_vpc" "workload" {
  provider = aws.workload

  cidr_block           = var.workload_vpc_cidr
  enable_dns_support   = true
  enable_dns_hostnames = true

  tags = {
    Name = "workload-vpc"
  }
}

resource "aws_subnet" "app" {
  provider = aws.workload

  vpc_id                  = aws_vpc.workload.id
  cidr_block              = var.app_subnet_cidr
  map_public_ip_on_launch = false

  tags = {
    Name = "private-app"
    Tier = "application"
  }
}

resource "aws_subnet" "data" {
  provider = aws.workload

  vpc_id                  = aws_vpc.workload.id
  cidr_block              = var.data_subnet_cidr
  map_public_ip_on_launch = false

  tags = {
    Name = "private-data"
    Tier = "data"
  }
}

resource "aws_route_table" "app" {
  provider = aws.workload

  vpc_id = aws_vpc.workload.id
  route  = []

  tags = {
    Name = "private-app"
  }
}

resource "aws_route_table" "data" {
  provider = aws.workload

  vpc_id = aws_vpc.workload.id
  route  = []

  tags = {
    Name = "private-data"
  }
}

resource "aws_route_table_association" "app" {
  provider = aws.workload

  subnet_id      = aws_subnet.app.id
  route_table_id = aws_route_table.app.id
}

resource "aws_route_table_association" "data" {
  provider = aws.workload

  subnet_id      = aws_subnet.data.id
  route_table_id = aws_route_table.data.id
}

resource "aws_default_security_group" "workload" {
  provider = aws.workload

  vpc_id  = aws_vpc.workload.id
  ingress = []
  egress  = []

  tags = {
    Name = "workload-default-deny"
  }
}
Check landing_zone.tftest.hcl
mock_provider "aws" {
  alias           = "management"
  override_during = plan
}

mock_provider "aws" {
  alias           = "security"
  override_during = plan

  mock_resource "aws_s3_bucket" {
    defaults = {
      arn = "arn:aws:s3:::secure-landing-zone-audit-logs-example"
    }
  }
}

mock_provider "aws" {
  alias           = "workload"
  override_during = plan
}

run "landing_zone_is_secure" {
  command = plan

  variables {
    aws_region            = "us-east-1"
    management_account_id = "111111111111"
    security_account_id   = "222222222222"
    workload_account_id   = "333333333333"
    management_role_arn   = "arn:aws:iam::111111111111:role/TerraformExecutionRole"
    security_role_arn     = "arn:aws:iam::222222222222:role/TerraformExecutionRole"
    workload_role_arn     = "arn:aws:iam::333333333333:role/TerraformExecutionRole"
    organization_id       = "o-exampleorgid"
    audit_bucket_name     = "secure-landing-zone-audit-logs-example"
  }

  assert {
    condition = (
      output.account_targets.management == "111111111111" &&
      output.account_targets.security == "222222222222" &&
      output.account_targets.workload == "333333333333"
    )
    error_message = "Each provider boundary must target the intended AWS account."
  }

  assert {
    condition = (
      aws_vpc.workload.cidr_block == "10.20.0.0/16" &&
      aws_subnet.app.map_public_ip_on_launch == false &&
      aws_subnet.data.map_public_ip_on_launch == false &&
      length(aws_route_table.app.route) == 0 &&
      length(aws_route_table.data.route) == 0
    )
    error_message = "The workload VPC must use private subnets with no configured internet routes."
  }

  assert {
    condition = (
      length(aws_default_security_group.workload.ingress) == 0 &&
      length(aws_default_security_group.workload.egress) == 0
    )
    error_message = "The workload default security group must not allow ingress or egress."
  }
}

That's the account map working. Terraform can now plan three explicit boundaries plus a private workload network without reaching AWS.

Your first landing-zone plan is green. Next, you'll put its network boundary under a stricter security test.

Expose the Broad Network Rule

Your aliased providers now preserve the three account boundaries. Your private Amazon VPC plan also passes through local Terraform mocks.

Private subnets still need strict east-west controls. A broad security group rule can allow unrestricted traffic inside an otherwise private network.

In this step, you will deliberately add unrestricted application egress. You will then prove that your test detects the weak trust boundary without contacting AWS.

In this step, get ready to:
  • Define distinct security-group identities for both workload tiers.
  • Introduce unrestricted application egress.
  • Prove the mocked test detects the broad trust boundary.
Define the workload tiers

The application tier needs its own network identity. This lets later rules target the application independently from the rest of the VPC.

  • In the Explorer sidebar in Visual Studio Code, return to network.tf from the previous step.
  • Place your cursor after the closing brace of aws_default_security_group.workload.
  • Give the application tier its own identity by pasting this resource:
resource "aws_security_group" "app" {
  provider = aws.workload

  name        = "workload-app"
  description = "Application tier with explicit egress only"
  vpc_id      = aws_vpc.workload.id

  tags = {
    Name = "workload-app"
  }
}

What Does This Resource Do?

  • The aws_security_group.app resource gives the application tier its own network identity.
  • The aws.workload provider keeps the resource inside the workload account boundary.
  • The group contains no inline traffic rules. Its permitted paths stay explicit in separate resources.
  • Save network.tf.
  • Check the updated configuration by running this command in the terminal from earlier:
terraform validate

What Does This Check Prove?

The command checks the configuration syntax. It also checks internal references without contacting remote services.

Terraform should report that the configuration is valid. This confirms the application security group fits the existing module.

Seeing a Validation Error?

Check that the new resource sits outside aws_default_security_group.workload. A missing closing brace can accidentally nest the resource.

Compare the resource labels with aws_security_group.app. Terraform references must match those labels exactly.

Help me fix the application security-group validation error.

The database tier needs a different network identity. This separation makes a precise application-to-database path possible later.

  • Place your cursor after the closing brace of aws_security_group.app.
  • Give the database tier its own identity by pasting this resource:
resource "aws_security_group" "database" {
  provider = aws.workload

  name        = "workload-database"
  description = "Database tier reachable only from the application tier"
  vpc_id      = aws_vpc.workload.id

  tags = {
    Name = "workload-database"
  }
}

What Does This Resource Do?

  • The aws_security_group.database resource gives the database tier a separate network identity.
  • The shared aws_vpc.workload.id reference places both tier identities in the same workload VPC.
  • The database group also contains no inline traffic rules. Access requires an explicit standalone rule.
  • Save network.tf.
  • Verify the second security-group resource by running:
terraform validate

What Does This Result Confirm?

A successful validation confirms that both tier identities reference the existing workload VPC correctly.

Terraform should report that the configuration is valid again. Both workload tiers now have explicit security-group identities.

Still Seeing a Validation Error?

Check that the database resource uses the label database. Check that its VPC reference is aws_vpc.workload.id.

Help me fix the database security-group resource.

See how broad egress is expressed

An egress rule controls traffic leaving a security group. The temporary rule below allows every protocol to every IPv4 destination.

  • Place your cursor after the closing brace of aws_security_group.database.
  • Create the temporary application egress path by pasting this resource:
resource "aws_vpc_security_group_egress_rule" "app_to_database" {
  provider = aws.workload

  security_group_id = aws_security_group.app.id
  cidr_ipv4         = "0.0.0.0/0"
  ip_protocol       = "-1"
}

Why Is This Rule Broad?

  • The security_group_id value attaches the rule to the application tier.
  • The 0.0.0.0/0 destination covers every IPv4 address.
  • The -1 protocol value covers all protocols.
  • Together, these settings create unrestricted application egress.
  • Save network.tf.
  • Confirm the temporary rule is valid Terraform by running:
terraform validate

Why Can an Unsafe Rule Validate?

Validation checks whether the configuration is structurally valid. It does not decide whether the network policy meets your security requirements.

A valid plan can still express an unsafe trust boundary. Tests turn that security expectation into an enforceable check.

Terraform should report that the configuration is valid. The unsafe rule is now ready for a security test.

Does the Rule Fail Validation?

Check that cidr_ipv4 sits inside aws_vpc_security_group_egress_rule.app_to_database. Check that the quoted protocol value is -1.

Help me validate the temporary egress rule.

✔️ Awesome, I've got everything!

Your network.tf now contains both workload-tier identities plus the temporary unrestricted egress rule.

ⓧ I'd like to double check the full code

resource "aws_vpc" "workload" {
  provider = aws.workload

  cidr_block           = var.workload_vpc_cidr
  enable_dns_support   = true
  enable_dns_hostnames = true

  tags = {
    Name = "workload-vpc"
  }
}

resource "aws_subnet" "app" {
  provider = aws.workload

  vpc_id                  = aws_vpc.workload.id
  cidr_block              = var.app_subnet_cidr
  map_public_ip_on_launch = false

  tags = {
    Name = "private-app"
    Tier = "application"
  }
}

resource "aws_subnet" "data" {
  provider = aws.workload

  vpc_id                  = aws_vpc.workload.id
  cidr_block              = var.data_subnet_cidr
  map_public_ip_on_launch = false

  tags = {
    Name = "private-data"
    Tier = "data"
  }
}

resource "aws_route_table" "app" {
  provider = aws.workload

  vpc_id = aws_vpc.workload.id
  route  = []

  tags = {
    Name = "private-app"
  }
}

resource "aws_route_table" "data" {
  provider = aws.workload

  vpc_id = aws_vpc.workload.id
  route  = []

  tags = {
    Name = "private-data"
  }
}

resource "aws_route_table_association" "app" {
  provider = aws.workload

  subnet_id      = aws_subnet.app.id
  route_table_id = aws_route_table.app.id
}

resource "aws_route_table_association" "data" {
  provider = aws.workload

  subnet_id      = aws_subnet.data.id
  route_table_id = aws_route_table.data.id
}

resource "aws_default_security_group" "workload" {
  provider = aws.workload

  vpc_id  = aws_vpc.workload.id
  ingress = []
  egress  = []

  tags = {
    Name = "workload-default-deny"
  }
}

resource "aws_security_group" "app" {
  provider = aws.workload

  name        = "workload-app"
  description = "Application tier with explicit egress only"
  vpc_id      = aws_vpc.workload.id

  tags = {
    Name = "workload-app"
  }
}

resource "aws_security_group" "database" {
  provider = aws.workload

  name        = "workload-database"
  description = "Database tier reachable only from the application tier"
  vpc_id      = aws_vpc.workload.id

  tags = {
    Name = "workload-database"
  }
}

resource "aws_vpc_security_group_egress_rule" "app_to_database" {
  provider = aws.workload

  security_group_id = aws_security_group.app.id
  cidr_ipv4         = "0.0.0.0/0"
  ip_protocol       = "-1"
}

What Should This File Contain?

This reference preserves the private VPC resources from the previous step. It adds the two workload-tier security groups plus the temporary unrestricted application egress rule.

Turn the trust boundary into a test

The existing mocked test already proves the VPC is private. A new assertion can now inspect the planned egress destination directly.

  • Return to tests/landing_zone.tftest.hcl in the Explorer sidebar.
  • Find the assertion whose message says The workload default security group must not allow ingress or egress..
  • Place your cursor after that assertion's closing brace.
  • Add the broad-egress assertion by pasting this block:
  assert {
    condition     = aws_vpc_security_group_egress_rule.app_to_database.cidr_ipv4 != "0.0.0.0/0"
    error_message = "Application egress must target the database security group instead of 0.0.0.0/0."
  }

What Does This Assertion Check?

  • The condition reads the planned cidr_ipv4 value from the temporary egress rule.
  • The comparison rejects 0.0.0.0/0 as an acceptable destination.
  • The error message names the narrower trust boundary the design requires.
  • Save tests/landing_zone.tftest.hcl.

✔️ Awesome, I've got everything!

Your test file now keeps its original boundary checks. It also contains the assertion that rejects unrestricted application egress.

ⓧ I'd like to double check the full code

mock_provider "aws" {
  alias           = "management"
  override_during = plan
}

mock_provider "aws" {
  alias           = "security"
  override_during = plan

  mock_resource "aws_s3_bucket" {
    defaults = {
      arn = "arn:aws:s3:::secure-landing-zone-audit-logs-example"
    }
  }
}

mock_provider "aws" {
  alias           = "workload"
  override_during = plan
}

run "landing_zone_is_secure" {
  command = plan

  variables {
    aws_region            = "us-east-1"
    management_account_id = "111111111111"
    security_account_id   = "222222222222"
    workload_account_id   = "333333333333"
    management_role_arn   = "arn:aws:iam::111111111111:role/TerraformExecutionRole"
    security_role_arn     = "arn:aws:iam::222222222222:role/TerraformExecutionRole"
    workload_role_arn     = "arn:aws:iam::333333333333:role/TerraformExecutionRole"
    organization_id       = "o-exampleorgid"
    audit_bucket_name     = "secure-landing-zone-audit-logs-example"
  }

  assert {
    condition = (
      output.account_targets.management == "111111111111" &&
      output.account_targets.security == "222222222222" &&
      output.account_targets.workload == "333333333333"
    )
    error_message = "Each provider boundary must target the intended AWS account."
  }

  assert {
    condition = (
      aws_vpc.workload.cidr_block == "10.20.0.0/16" &&
      aws_subnet.app.map_public_ip_on_launch == false &&
      aws_subnet.data.map_public_ip_on_launch == false &&
      length(aws_route_table.app.route) == 0 &&
      length(aws_route_table.data.route) == 0
    )
    error_message = "The workload VPC must use private subnets with no configured internet routes."
  }

  assert {
    condition = (
      length(aws_default_security_group.workload.ingress) == 0 &&
      length(aws_default_security_group.workload.egress) == 0
    )
    error_message = "The workload default security group must not allow ingress or egress."
  }

  assert {
    condition     = aws_vpc_security_group_egress_rule.app_to_database.cidr_ipv4 != "0.0.0.0/0"
    error_message = "Application egress must target the database security group instead of 0.0.0.0/0."
  }
}

What Should This File Contain?

This reference keeps the three mocked provider aliases plus the original plan assertions. The final assertion deliberately conflicts with the temporary egress destination.

Before you run the test, do you think the new assertion can pass while application egress still targets 0.0.0.0/0?

  • Expose the broad trust boundary by running this command in the terminal from earlier:
terraform test

What Should You See?

The landing_zone_is_secure run reports fail. The assertion explains that application egress must target the database security group instead of 0.0.0.0/0.

That failure is the win here. Your local test has detected a broad trust boundary without AWS credentials or resource creation.

Does the Test Pass Unexpectedly?

Check that the new assertion is inside the landing_zone_is_secure run block. Check that its condition references aws_vpc_security_group_egress_rule.app_to_database.cidr_ipv4.

Confirm that network.tf still sets cidr_ipv4 to 0.0.0.0/0.

Help me make the broad-egress test fail as intended.

Your test now catches unrestricted application egress before any infrastructure exists. Next, you will replace that broad destination with one explicit database path on TCP port 5432.

Enforce Least-Privilege Paths

Your failing Terraform test exposed unrestricted traffic leaving the application security group. The private network still has a broad trust boundary until that rule names one destination.

This step applies least privilege to the complete path. Application traffic gets one database destination on one port. Exclusive rule ownership prevents undeclared access from creeping into either group.

In this step, get ready to:
  • Replace unrestricted application egress with a peer security-group reference.
  • Add matching database ingress on TCP port 5432.
  • Prove both security groups own only their declared rules.
Restrict application egress

The temporary rule trusts every destination through 0.0.0.0/0. A peer security-group reference ties permission to the database tier even if its private addresses change.

  • In network.tf, find aws_vpc_security_group_egress_rule.app_to_database.
  • Replace the complete resource block with this code:
resource "aws_vpc_security_group_egress_rule" "app_to_database" {
  provider = aws.workload

  security_group_id            = aws_security_group.app.id
  referenced_security_group_id = aws_security_group.database.id
  description                  = "PostgreSQL from application to database"
  from_port                    = 5432
  to_port                      = 5432
  ip_protocol                  = "tcp"
}

What does this rule enforce?

  • The security_group_id value applies the rule to the application security group.
  • The referenced_security_group_id value makes the database security group the only destination.
  • The port range permits only 5432 through 5432.
  • The tcp protocol matches PostgreSQL traffic.
  • Save network.tf.

Before you test, do you expect the assertion that rejected unrestricted egress to keep failing?

  • Check the narrower destination by running this command in the terminal from earlier:
terraform test

What does this check prove?

The mocked plan evaluates the changed rule without contacting AWS. It can now confirm that application egress no longer targets every IPv4 destination.

You should see the existing test report pass. That result proves the broad destination has left the plan.

Does the test still fail?

Check that the egress resource no longer contains cidr_ipv4. Confirm that referenced_security_group_id points to aws_security_group.database.id.

Confirm that both port values are 5432. Confirm that ip_protocol is tcp.

Help me debug the application egress rule.

Own both security-group rule sets

The database needs a matching inbound rule before the path is complete. Exclusive ownership records the full permitted rule set for each group.

  • In network.tf, find the closing brace of aws_vpc_security_group_egress_rule.app_to_database.
  • Add the database ingress resource directly below it:
resource "aws_vpc_security_group_ingress_rule" "database_from_app" {
  provider = aws.workload

  security_group_id            = aws_security_group.database.id
  referenced_security_group_id = aws_security_group.app.id
  description                  = "PostgreSQL from application security group"
  from_port                    = 5432
  to_port                      = 5432
  ip_protocol                  = "tcp"
}

How does the return side work?

This rule belongs to the database security group. Its source reference names the application security group.

The matching protocol and port range complete one explicit application-to-database path. No CIDR range can use this permission.

  • Save network.tf.
  • Verify that the mocked plan accepts the matching ingress rule by running:
terraform test

What does this run check?

Terraform builds a mocked plan containing both directions of the database path. The command still creates no AWS resources.

You should see the suite report pass. The matching ingress rule is now valid in the planned network.

Is the ingress rule invalid?

Check that security_group_id points to aws_security_group.database.id. Check that the peer reference points to aws_security_group.app.id.

Help me debug the matching database ingress rule.

Standalone rules define allowed traffic. The exclusive resources add drift control by declaring every rule each security group is permitted to own.

  • Add the application exclusive-rule resource below aws_vpc_security_group_ingress_rule.database_from_app in network.tf.
resource "aws_vpc_security_group_rules_exclusive" "app" {
  provider = aws.workload

  security_group_id = aws_security_group.app.id
  ingress_rule_ids  = []
  egress_rule_ids   = [aws_vpc_security_group_egress_rule.app_to_database.id]
}

What does the application group own?

The empty ingress list denies configured inbound rules. The single egress ID makes the database path the complete outbound rule set.

  • Save network.tf.
  • Confirm that Terraform accepts the application rule set by running:
terraform test

What does this run confirm?

The mocked plan reconciles the application's declared rule IDs. It confirms that the exclusive resource can own the one egress rule.

You should see the suite report pass. The application group now owns no ingress rules and one egress rule.

Is the application rule set failing?

Confirm that ingress_rule_ids is an empty list. Confirm that egress_rule_ids contains aws_vpc_security_group_egress_rule.app_to_database.id.

Help me debug the application exclusive-rule resource.

  • Add the database exclusive-rule resource below aws_vpc_security_group_rules_exclusive.app in network.tf.
resource "aws_vpc_security_group_rules_exclusive" "database" {
  provider = aws.workload

  security_group_id = aws_security_group.database.id
  ingress_rule_ids  = [aws_vpc_security_group_ingress_rule.database_from_app.id]
  egress_rule_ids   = []
}

What does the database group own?

The single ingress ID permits traffic from the application group. The empty egress list prevents the configuration from owning any outbound database rule.

  • Save network.tf.
  • Confirm that Terraform accepts both exclusive rule sets by running:
terraform test

What does this run confirm?

The plan now contains exclusive ownership for both security groups. The application owns one egress rule. The database owns one ingress rule.

You should see the suite report pass. Both exclusive resources are valid in the mocked plan.

Is the database rule set failing?

Confirm that ingress_rule_ids contains aws_vpc_security_group_ingress_rule.database_from_app.id. Confirm that egress_rule_ids is an empty list.

Help me debug the database exclusive-rule resource.

✔️ Awesome, I've got everything!

Great. Save network.tf before strengthening the tests.

ⓧ I'd like to double check the full code

resource "aws_vpc" "workload" {
  provider = aws.workload

  cidr_block           = var.workload_vpc_cidr
  enable_dns_support   = true
  enable_dns_hostnames = true

  tags = {
    Name = "workload-vpc"
  }
}

resource "aws_subnet" "app" {
  provider = aws.workload

  vpc_id                  = aws_vpc.workload.id
  cidr_block              = var.app_subnet_cidr
  map_public_ip_on_launch = false

  tags = {
    Name = "private-app"
    Tier = "application"
  }
}

resource "aws_subnet" "data" {
  provider = aws.workload

  vpc_id                  = aws_vpc.workload.id
  cidr_block              = var.data_subnet_cidr
  map_public_ip_on_launch = false

  tags = {
    Name = "private-data"
    Tier = "data"
  }
}

resource "aws_route_table" "app" {
  provider = aws.workload

  vpc_id = aws_vpc.workload.id
  route  = []

  tags = {
    Name = "private-app"
  }
}

resource "aws_route_table" "data" {
  provider = aws.workload

  vpc_id = aws_vpc.workload.id
  route  = []

  tags = {
    Name = "private-data"
  }
}

resource "aws_route_table_association" "app" {
  provider = aws.workload

  subnet_id      = aws_subnet.app.id
  route_table_id = aws_route_table.app.id
}

resource "aws_route_table_association" "data" {
  provider = aws.workload

  subnet_id      = aws_subnet.data.id
  route_table_id = aws_route_table.data.id
}

resource "aws_default_security_group" "workload" {
  provider = aws.workload

  vpc_id  = aws_vpc.workload.id
  ingress = []
  egress  = []

  tags = {
    Name = "workload-default-deny"
  }
}

resource "aws_security_group" "app" {
  provider = aws.workload

  name        = "workload-app"
  description = "Application tier with explicit egress only"
  vpc_id      = aws_vpc.workload.id

  tags = {
    Name = "workload-app"
  }
}

resource "aws_security_group" "database" {
  provider = aws.workload

  name        = "workload-database"
  description = "Database tier reachable only from the application tier"
  vpc_id      = aws_vpc.workload.id

  tags = {
    Name = "workload-database"
  }
}

resource "aws_vpc_security_group_egress_rule" "app_to_database" {
  provider = aws.workload

  security_group_id            = aws_security_group.app.id
  referenced_security_group_id = aws_security_group.database.id
  description                  = "PostgreSQL from application to database"
  from_port                    = 5432
  to_port                      = 5432
  ip_protocol                  = "tcp"
}

resource "aws_vpc_security_group_ingress_rule" "database_from_app" {
  provider = aws.workload

  security_group_id            = aws_security_group.database.id
  referenced_security_group_id = aws_security_group.app.id
  description                  = "PostgreSQL from application security group"
  from_port                    = 5432
  to_port                      = 5432
  ip_protocol                  = "tcp"
}

resource "aws_vpc_security_group_rules_exclusive" "app" {
  provider = aws.workload

  security_group_id = aws_security_group.app.id
  ingress_rule_ids  = []
  egress_rule_ids   = [aws_vpc_security_group_egress_rule.app_to_database.id]
}

resource "aws_vpc_security_group_rules_exclusive" "database" {
  provider = aws.workload

  security_group_id = aws_security_group.database.id
  ingress_rule_ids  = [aws_vpc_security_group_ingress_rule.database_from_app.id]
  egress_rule_ids   = []
}

How should I use this reference?

Compare this reference with your saved network.tf. Every workload resource should use aws.workload.

The final four rule resources should form one TCP 5432 path with exclusive ownership on both sides.

Prove the final trust boundary

The earlier assertion only caught the known broad CIDR. The final test checks the permitted destination plus its protocol and port range.

  • In tests/landing_zone.tftest.hcl, find the assertion that rejects unrestricted application egress.
  • Replace that complete assertion with this final traffic-path assertion:
  assert {
    condition = (
      aws_vpc_security_group_egress_rule.app_to_database.referenced_security_group_id == aws_security_group.database.id &&
      aws_vpc_security_group_egress_rule.app_to_database.ip_protocol == "tcp" &&
      aws_vpc_security_group_egress_rule.app_to_database.from_port == 5432 &&
      aws_vpc_security_group_egress_rule.app_to_database.to_port == 5432 &&
      aws_vpc_security_group_ingress_rule.database_from_app.referenced_security_group_id == aws_security_group.app.id
    )
    error_message = "Application traffic must target only the database security group on TCP 5432."
  }

What does this assertion prove?

The assertion checks the application rule's destination. It also checks the exact protocol and port range.

The final condition verifies that database ingress points back to the application security group. Both ends must describe the same trust path.

  • Save tests/landing_zone.tftest.hcl.
  • Run the strengthened traffic-path test with this command:
terraform test

What does this run prove?

The test now validates the complete application-to-database rule. A broad destination or a different protocol would fail this assertion.

You should see the suite report pass. The peer references and TCP 5432 settings match.

Is the traffic-path assertion failing?

Compare the peer references in network.tf with the resource names in the assertion. A reversed application or database reference changes the trust direction.

Check both occurrences of 5432. Check that the protocol value remains lowercase tcp.

Help me debug the final traffic-path assertion.

The traffic test proves what the path allows. One more assertion proves that neither security group owns any additional rule.

  • Add this assertion directly below the traffic-path assertion in tests/landing_zone.tftest.hcl.
  assert {
    condition = (
      length(aws_vpc_security_group_rules_exclusive.app.ingress_rule_ids) == 0 &&
      length(aws_vpc_security_group_rules_exclusive.app.egress_rule_ids) == 1 &&
      length(aws_vpc_security_group_rules_exclusive.database.ingress_rule_ids) == 1 &&
      length(aws_vpc_security_group_rules_exclusive.database.egress_rule_ids) == 0
    )
    error_message = "The app and database security groups must own only their declared rules."
  }

What does ownership add?

The application security group must own zero ingress rules and one egress rule. The database security group must own one ingress rule and zero egress rules.

These counts turn the intended rule set into a testable boundary. An additional managed rule changes a count and fails the suite.

  • Save tests/landing_zone.tftest.hcl.

Before you run the final check, do you expect every account-boundary and network-security assertion to pass?

  • Run the complete mocked test suite with this command:
terraform test

What does the final test cover?

The suite checks the three account targets. It also checks the private subnets and empty route tables.

The remaining assertions verify default-deny behavior plus the TCP 5432 path and exclusive rule ownership. Mocked providers keep the entire check local.

You should see the suite report pass with no failed assertions. Your application can now reach only the database security group on TCP port 5432.

Does the final suite fail?

Read the failing assertion's message to identify whether the mismatch is in the peer references or the exclusive rule counts. Compare only that resource with the matching reference tab.

Check that no temporary 0.0.0.0/0 rule remains in network.tf. Check that the old broad-egress assertion has been replaced.

Help me debug the final least-privilege test suite.

✔️ Awesome, I've got everything!

Excellent. Your mocked suite now proves the workload network has one declared application-to-database path.

ⓧ I'd like to double check the full code

mock_provider "aws" {
  alias           = "management"
  override_during = plan
}

mock_provider "aws" {
  alias           = "security"
  override_during = plan
}

mock_provider "aws" {
  alias           = "workload"
  override_during = plan
}

run "landing_zone_is_secure" {
  command = plan

  variables {
    aws_region            = "us-east-1"
    management_account_id = "111111111111"
    security_account_id   = "222222222222"
    workload_account_id   = "333333333333"
    management_role_arn   = "arn:aws:iam::111111111111:role/TerraformExecutionRole"
    security_role_arn     = "arn:aws:iam::222222222222:role/TerraformExecutionRole"
    workload_role_arn     = "arn:aws:iam::333333333333:role/TerraformExecutionRole"
    organization_id       = "o-exampleorgid"
    audit_bucket_name     = "secure-landing-zone-audit-logs-example"
  }

  assert {
    condition = (
      output.account_targets.management == "111111111111" &&
      output.account_targets.security == "222222222222" &&
      output.account_targets.workload == "333333333333"
    )
    error_message = "Each provider boundary must target the intended AWS account."
  }

  assert {
    condition = (
      aws_vpc.workload.cidr_block == "10.20.0.0/16" &&
      aws_subnet.app.map_public_ip_on_launch == false &&
      aws_subnet.data.map_public_ip_on_launch == false &&
      length(aws_route_table.app.route) == 0 &&
      length(aws_route_table.data.route) == 0
    )
    error_message = "The workload VPC must use private subnets with no configured internet routes."
  }

  assert {
    condition = (
      length(aws_default_security_group.workload.ingress) == 0 &&
      length(aws_default_security_group.workload.egress) == 0
    )
    error_message = "The workload default security group must not allow ingress or egress."
  }

  assert {
    condition = (
      aws_vpc_security_group_egress_rule.app_to_database.referenced_security_group_id == aws_security_group.database.id &&
      aws_vpc_security_group_egress_rule.app_to_database.ip_protocol == "tcp" &&
      aws_vpc_security_group_egress_rule.app_to_database.from_port == 5432 &&
      aws_vpc_security_group_egress_rule.app_to_database.to_port == 5432 &&
      aws_vpc_security_group_ingress_rule.database_from_app.referenced_security_group_id == aws_security_group.app.id
    )
    error_message = "Application traffic must target only the database security group on TCP 5432."
  }

  assert {
    condition = (
      length(aws_vpc_security_group_rules_exclusive.app.ingress_rule_ids) == 0 &&
      length(aws_vpc_security_group_rules_exclusive.app.egress_rule_ids) == 1 &&
      length(aws_vpc_security_group_rules_exclusive.database.ingress_rule_ids) == 1 &&
      length(aws_vpc_security_group_rules_exclusive.database.egress_rule_ids) == 0
    )
    error_message = "The app and database security groups must own only their declared rules."
  }
}

How should I use this reference?

Compare this reference with your saved test file. The final two assertions should follow the default security-group assertion.

The file should contain one mocked plan run. Its five assertions should all report pass.

That broad trust boundary is closed. Next, you'll send organization activity and workload flow records into protected centralized storage.

Centralize and Document Audit Logging

Your workload network now passes every segmentation test. Those boundaries still need a protected record of organization activity and network traffic.

This step adds centralized logging through AWS CloudTrail, Amazon S3, and VPC Flow Logs. You will test the complete Terraform blueprint locally before documenting its trust paths with Mermaid.

In this step, get ready to:
  • Protect a central audit bucket with encryption and delivery policies.
  • Send organization activity and workload flow records to the bucket.
  • Test the complete blueprint and render its architecture diagram.
Protect the central audit bucket

The security account owns the audit destination. Versioning preserves earlier object versions while encryption protects stored records.

  • Create logging.tf in the open secure-aws-landing-zone folder.
  • Add the central audit bucket resource to logging.tf by pasting this code:
resource "aws_s3_bucket" "audit" {
  provider = aws.security

  bucket        = var.audit_bucket_name
  force_destroy = false

  tags = {
    Name = "central-audit-logs"
  }
}

What does this resource do?

The explicit aws.security provider places the bucket behind the security-account boundary. The bucket name comes from the existing audit_bucket_name input.

  • Add bucket versioning below the audit bucket resource by pasting this code:
resource "aws_s3_bucket_versioning" "audit" {
  provider = aws.security

  bucket = aws_s3_bucket.audit.id

  versioning_configuration {
    status = "Enabled"
  }
}

Why enable versioning?

Versioning retains previous versions when an audit object changes or is deleted. That history strengthens the bucket as an audit destination.

  • Save logging.tf.
  • Confirm the new resources still produce a valid mocked plan by running:
terraform test

What does this check prove?

The mocked providers evaluate the new resource schemas without requesting credentials. No bucket is created in AWS.

You should see the existing test run finish with a passing result. Your security-account logging destination now fits the local plan.

Does the test stop on logging.tf?

Check that both resources use aws.security. Confirm that the versioning resource references aws_s3_bucket.audit.id.

Help me fix the first audit bucket resources in logging.tf.

  • Add the bucket encryption configuration below the versioning resource by pasting this code:
resource "aws_s3_bucket_server_side_encryption_configuration" "audit" {
  provider = aws.security

  bucket = aws_s3_bucket.audit.id

  rule {
    apply_server_side_encryption_by_default {
      sse_algorithm = "AES256"
    }

    blocked_encryption_types = ["SSE-C"]
  }
}

How is stored data protected?

The bucket applies AES256 encryption by default. Blocking SSE-C prevents callers from supplying their own encryption keys for these audit objects.

  • Add the public-access block below the encryption resource by pasting this code:
resource "aws_s3_bucket_public_access_block" "audit" {
  provider = aws.security

  bucket = aws_s3_bucket.audit.id

  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}

What do these controls cover?

All four public-access settings are enabled. This closes both access-control-list and bucket-policy paths that could expose the audit destination publicly.

  • Save logging.tf.
  • Check the encrypted private bucket configuration by running:
terraform test

Why rerun the suite now?

This short loop catches a malformed encryption block or public-access setting before the bucket policy adds more detail.

The test should still pass through the mocked plan. The bucket now has storage protection and public-access controls.

Seeing a configuration error?

Check that blocked_encryption_types sits inside the rule block. Confirm that every public-access setting is inside aws_s3_bucket_public_access_block.audit.

Help me debug the audit bucket encryption or public-access block.

The bucket policy starts with a transport guardrail. Requests made without TLS are denied across the bucket and its objects.

  • Add the initial bucket policy below the public-access block by pasting this code:
resource "aws_s3_bucket_policy" "audit" {
  provider = aws.security

  bucket = aws_s3_bucket.audit.id
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Sid       = "AllowSSLRequestsOnly"
        Effect    = "Deny"
        Principal = "*"
        Action    = "s3:*"
        Resource = [
          aws_s3_bucket.audit.arn,
          "${aws_s3_bucket.audit.arn}/*"
        ]
        Condition = {
          Bool = {
            "aws:SecureTransport" = false
          }
        }
      }
    ]
  })

  depends_on = [aws_s3_bucket_public_access_block.audit]
}

How does the TLS guardrail work?

The policy denies every S3 action when aws:SecureTransport is false. The resource list covers the bucket ARN and every object stored beneath it.

  • Save logging.tf.
  • Confirm that Terraform can encode the policy by running:
terraform test

What is Terraform checking?

Terraform evaluates the policy object through jsonencode during the mocked plan. This catches invalid HCL structure before any service permissions are added.

The passing result confirms that the protected bucket and TLS policy form a valid local plan.

Does the policy fail to parse?

Match each opening brace with its closing brace. Check that Statement remains a list containing the TLS policy object.

Help me find the HCL nesting problem in my audit bucket policy.

Connect organization and network logs

The destination now needs narrowly scoped delivery permissions. Separate policy statements give each logging service only its required bucket actions and source conditions.

  • Find the TLS statement inside aws_s3_bucket_policy.audit.
  • Add a comma after that statement's closing brace.
  • Paste this CloudTrail ACL-check statement below it:
      {
        Sid    = "AWSCloudTrailAclCheck20150319"
        Effect = "Allow"
        Principal = {
          Service = "cloudtrail.amazonaws.com"
        }
        Action   = "s3:GetBucketAcl"
        Resource = aws_s3_bucket.audit.arn
        Condition = {
          StringEquals = {
            "aws:SourceArn" = local.trail_arn
          }
        }
      },

Why allow an ACL check?

CloudTrail checks the bucket ACL before delivering logs. The source condition restricts that permission to the organization trail ARN already defined in providers.tf.

  • Paste the management-account CloudTrail write statement below the ACL-check statement:
      {
        Sid    = "AWSCloudTrailWrite20150319"
        Effect = "Allow"
        Principal = {
          Service = "cloudtrail.amazonaws.com"
        }
        Action   = "s3:PutObject"
        Resource = "${aws_s3_bucket.audit.arn}/AWSLogs/${var.management_account_id}/*"
        Condition = {
          StringEquals = {
            "s3:x-amz-acl" = "bucket-owner-full-control"
            "aws:SourceArn" = local.trail_arn
          }
        }
      },

What is scoped here?

The object path is limited to the management account prefix. The conditions require bucket-owner control and the expected trail ARN.

  • Save logging.tf.
  • Check the first CloudTrail permissions by running:
terraform test

What should remain unchanged?

The new policy statements should extend the destination without changing the passing workload-network assertions.

You should see the mocked test remain green. CloudTrail can now inspect the bucket and write management-account records in the modeled policy.

Does the policy list fail?

Check the comma between each statement object. Confirm that both statements remain inside the existing Statement list.

Help me fix the CloudTrail statements in my bucket policy.

  • Paste the organization-wide CloudTrail write statement below the management-account write statement:
      {
        Sid    = "AWSCloudTrailOrganizationWrite20150319"
        Effect = "Allow"
        Principal = {
          Service = "cloudtrail.amazonaws.com"
        }
        Action   = "s3:PutObject"
        Resource = "${aws_s3_bucket.audit.arn}/AWSLogs/${var.organization_id}/*"
        Condition = {
          StringEquals = {
            "s3:x-amz-acl" = "bucket-owner-full-control"
            "aws:SourceArn" = local.trail_arn
          }
        }
      },

Why add an organization prefix?

Organization-member events use the organization ID path. The source ARN condition still ties delivery to the management-owned trail.

  • Paste the VPC Flow Logs write statement below the organization statement:
      {
        Sid    = "AWSLogDeliveryWrite"
        Effect = "Allow"
        Principal = {
          Service = "delivery.logs.amazonaws.com"
        }
        Action   = "s3:PutObject"
        Resource = "${aws_s3_bucket.audit.arn}/AWSLogs/${var.workload_account_id}/*"
        Condition = {
          StringEquals = {
            "aws:SourceAccount" = var.workload_account_id
            "s3:x-amz-acl"      = "bucket-owner-full-control"
          }
          ArnLike = {
            "aws:SourceArn" = "arn:aws:logs:${var.aws_region}:${var.workload_account_id}:*"
          }
        }
      },

How is flow-log delivery constrained?

The object path and aws:SourceAccount condition both point to the workload account. The source ARN also limits delivery to that account's regional logs service.

  • Save logging.tf.
  • Check the organization and flow-log write statements by running:
terraform test

Why test these statements together?

Both statements introduce cross-account delivery paths. The mocked plan confirms that their interpolated account and organization values produce valid policy JSON.

The suite should pass again. The policy now separates organization records from workload network records.

Seeing malformed policy JSON?

Check that StringEquals and ArnLike are siblings inside the flow-log Condition object. Confirm the organization statement ends with a comma.

Help me repair the organization and flow-log policy statements.

  • Paste the VPC Flow Logs ACL-check statement after the write statement:
      {
        Sid    = "AWSLogDeliveryAclCheck"
        Effect = "Allow"
        Principal = {
          Service = "delivery.logs.amazonaws.com"
        }
        Action   = "s3:GetBucketAcl"
        Resource = aws_s3_bucket.audit.arn
        Condition = {
          StringEquals = {
            "aws:SourceAccount" = var.workload_account_id
          }
          ArnLike = {
            "aws:SourceArn" = "arn:aws:logs:${var.aws_region}:${var.workload_account_id}:*"
          }
        }
      }

Why is this the final statement?

The delivery service can inspect the bucket ACL only when the request comes from the workload account's logs service. The object does not need a trailing comma because it closes the policy list.

  • Add the workload flow-log resource below the bucket policy by pasting this code:
resource "aws_flow_log" "workload" {
  provider = aws.workload

  log_destination      = aws_s3_bucket.audit.arn
  log_destination_type = "s3"
  traffic_type         = "ALL"
  vpc_id               = aws_vpc.workload.id

  depends_on = [
    aws_s3_bucket_policy.audit,
    aws_s3_bucket_server_side_encryption_configuration.audit
  ]
}

What traffic is captured?

The workload provider owns the flow log. It captures ALL traffic for aws_vpc.workload and sends records to the security-account bucket.

  • Save logging.tf.
  • Check the complete flow-log path by running:
terraform test

What does this mocked result establish?

The plan can connect a workload-account resource to the central bucket through the aliased providers. Terraform evaluates the relationship without contacting AWS.

A passing result confirms that the private VPC now has a modeled network-audit path.

Does the flow log fail to plan?

Confirm that the resource uses aws.workload. Check that vpc_id references aws_vpc.workload.id.

Help me debug the workload VPC Flow Log resource.

Organization activity belongs to the management account. The trail writes into the same security-account bucket so governance and network evidence meet at one protected destination.

  • Add the organization trail below the flow-log resource by pasting this code:
resource "aws_cloudtrail" "organization" {
  provider = aws.management

  name                          = local.trail_name
  s3_bucket_name                = aws_s3_bucket.audit.id
  enable_logging                = true
  enable_log_file_validation    = true
  include_global_service_events = true
  is_multi_region_trail         = true
  is_organization_trail         = true

  depends_on = [
    aws_s3_bucket_policy.audit,
    aws_s3_bucket_versioning.audit,
    aws_s3_bucket_server_side_encryption_configuration.audit
  ]
}

What does the trail cover?

The management provider owns organization-security-trail. It records organization activity across Regions and global services while enabling log-file validation.

  • Save logging.tf.
  • Confirm that both logging sources plan together by running:
terraform test

What is connected now?

The mocked plan contains a management-account trail and a workload-account flow log. Both target the protected security-account bucket.

That passing result completes the centralized logging path without creating cloud resources.

Does the trail configuration fail?

Check that the provider is aws.management. Confirm that the trail name uses local.trail_name and the bucket uses aws_s3_bucket.audit.id.

Help me debug the organization CloudTrail resource.

Test and document the blueprint

Outputs turn the design into inspectable results. New assertions then prove that the logging controls remain part of every future plan.

  • Create outputs.tf in the open project folder.
  • Add the account-target output by pasting this code:
output "account_targets" {
  description = "AWS account IDs targeted by each provider boundary."
  value = {
    management = var.management_account_id
    security   = var.security_account_id
    workload   = var.workload_account_id
  }
}

What does this output expose?

The map makes each provider boundary visible by account ID. The existing account-target assertion can inspect these values during the mocked plan.

  • Add the workload-network output below it by pasting this code:
output "workload_network" {
  description = "Identifiers for the segmented workload network."
  value = {
    vpc_id         = aws_vpc.workload.id
    app_subnet_id  = aws_subnet.app.id
    data_subnet_id = aws_subnet.data.id
  }
}

Why expose network identifiers?

The output groups the private VPC and subnet identifiers. A future module can consume the segmented network without searching individual resources.

  • Save outputs.tf.
  • Confirm that the first two outputs plan correctly by running:
terraform test

What does this run catch?

The test catches a misspelled variable or resource reference before the logging output adds more fields.

You should see the suite pass with the account and network outputs available in memory.

  • Add the logging-controls output below the network output by pasting this code:
output "logging_controls" {
  description = "Security controls enabled by the logging baseline."
  value = {
    audit_bucket                = aws_s3_bucket.audit.id
    flow_logs_enabled           = true
    organization_trail_enabled  = aws_cloudtrail.organization.is_organization_trail
    multi_region_trail_enabled  = aws_cloudtrail.organization.is_multi_region_trail
    log_file_validation_enabled = aws_cloudtrail.organization.enable_log_file_validation
  }
}

What can you inspect here?

The output summarizes the audit destination and the major logging switches. These values make the blueprint's security posture visible to downstream automation.

  • Save outputs.tf.
  • Switch back to tests/landing_zone.tftest.hcl from the earlier steps.
  • Paste this encryption assertion before the final closing brace of run "landing_zone_is_secure":
  assert {
    condition = (
      length([
        for configuration in aws_s3_bucket_versioning.audit.versioning_configuration : configuration
        if configuration.status == "Enabled"
      ]) == 1 &&
      length([
        for rule in aws_s3_bucket_server_side_encryption_configuration.audit.rule : rule
        if length([
          for encryption in rule.apply_server_side_encryption_by_default : encryption
          if encryption.sse_algorithm == "AES256"
        ]) == 1
      ]) == 1
    )
    error_message = "The audit bucket must have versioning and AES256 default encryption enabled."
  }

What does this assertion inspect?

Filtered for expressions locate one enabled versioning configuration and one default AES256 encryption rule. The test checks the planned resource values directly.

  • Paste this public-access assertion below the encryption assertion:
  assert {
    condition = (
      aws_s3_bucket_public_access_block.audit.block_public_acls &&
      aws_s3_bucket_public_access_block.audit.block_public_policy &&
      aws_s3_bucket_public_access_block.audit.ignore_public_acls &&
      aws_s3_bucket_public_access_block.audit.restrict_public_buckets
    )
    error_message = "Every S3 public-access block setting must be enabled."
  }

Why check every switch?

The condition requires all four settings to remain true. A future change that disables one public-access control makes the suite fail.

  • Save tests/landing_zone.tftest.hcl.
  • Run the suite to test the bucket controls:
terraform test

What changed in the suite?

The test now verifies versioning, default encryption, and every public-access setting. The checks still use the in-memory mocked plan.

You should see the test pass with the new storage-control assertions included.

Did a bucket assertion fail?

Compare the asserted resource names with logging.tf. Check that every public-access value is true and that the encryption algorithm is AES256.

Help me debug the audit bucket test assertions.

  • Paste this flow-log assertion below the public-access assertion:
  assert {
    condition = (
      aws_flow_log.workload.log_destination_type == "s3" &&
      aws_flow_log.workload.traffic_type == "ALL" &&
      aws_flow_log.workload.log_destination == aws_s3_bucket.audit.arn
    )
    error_message = "Workload VPC Flow Logs must capture all traffic in the central audit bucket."
  }

What flow-log properties matter?

The assertion requires an S3 destination, all traffic, and the exact central bucket ARN. A different destination or narrower traffic setting fails the test.

  • Paste this organization-trail assertion below the flow-log assertion:
  assert {
    condition = (
      aws_cloudtrail.organization.enable_logging &&
      aws_cloudtrail.organization.enable_log_file_validation &&
      aws_cloudtrail.organization.include_global_service_events &&
      aws_cloudtrail.organization.is_multi_region_trail &&
      aws_cloudtrail.organization.is_organization_trail &&
      aws_cloudtrail.organization.s3_bucket_name == aws_s3_bucket.audit.id
    )
    error_message = "CloudTrail must be enabled organization-wide, across Regions, with validation and central storage."
  }

What does the final logging assertion protect?

The test requires active logging, file validation, global service events, multi-Region coverage, organization mode, and the central bucket destination.

  • Save tests/landing_zone.tftest.hcl.
  • Run the expanded suite by entering:
terraform test

What does a pass establish?

A pass proves that the planned network and logging resources satisfy the complete local security baseline. The providers remain mocked throughout the run.

Your tests now cover account boundaries, network segmentation, encrypted storage, VPC Flow Logs, and organization-wide CloudTrail settings.

Did a logging assertion fail?

Read the assertion's message to identify the changed control. Compare the matching resource in logging.tf with the condition in the test file.

Help me diagnose the failing logging assertion.

Local state and variable files can contain deployment details. The ignore file keeps those artifacts outside normal source-control commits.

  • Create .gitignore in the secure-aws-landing-zone folder.
  • Add the Terraform exclusions by pasting this code:
.terraform/
*.tfstate
*.tfstate.*
crash.log
*.tfvars

What stays out of source control?

The rules exclude downloaded provider data, local state, crash logs, and variable-value files. Your reusable Terraform configuration remains visible.

  • Save .gitignore.
  • Confirm that .gitignore appears in the VS Code Explorer sidebar.

The file in the Explorer confirms that your local Terraform artifacts now have explicit source-control exclusions.

The final document turns the configuration into an architecture you can review. Its diagram makes account ownership and cross-account log delivery visible.

  • Create README.md in the open project folder.
  • Add the project introduction by pasting this Markdown:
# Secure Three-Account AWS Landing Zone Blueprint

This Terraform root module models three explicit AWS account boundaries:

- Management account: owns the organization trail.
- Security account: owns the central audit bucket.
- Workload account: owns the private VPC and VPC Flow Logs.

The default project path uses mocked providers and does not contact AWS.

What does the introduction establish?

The opening assigns one responsibility to each account. It also records that the default path uses mocks and does not contact AWS.

  • Save README.md.
  • Open the Markdown preview by pressing Shift+Command+V.

You should see the title and three account responsibilities rendered in the preview.

  • Return to the README.md editor tab.
  • Add the first part of the architecture section below the introduction:
## Architecture

```mermaid
flowchart LR
  TF[Terraform root module]

  subgraph MGMT[Management account]
    CT[Organization CloudTrail]
  end

  subgraph SEC[Security account]
    S3[Encrypted and versioned audit bucket]
  end

  subgraph WORK[Workload account]
    VPC[Private workload VPC]
    APP[Application security group]
    DB[Database security group]
    FLOW[VPC Flow Logs]

    VPC --> APP
    VPC --> DB
    APP -->|TCP 5432 only| DB
  end

What does this diagram define?

The three subgraphs mirror the provider boundaries. The workload subgraph also shows that application traffic reaches the database only on TCP port 5432.

  • Complete the Mermaid diagram by adding these trust and delivery paths:
  TF -->|aws.management| CT
  TF -->|aws.security| S3
  TF -->|aws.workload| VPC
  CT -->|Organization logs| S3
  FLOW -->|Network flow records| S3
```

What do the arrows reveal?

Three arrows show Terraform selecting an aliased provider boundary. Two delivery arrows converge on the security-account audit bucket.

  • Save README.md.
  • Open the Markdown preview by pressing Shift+Command+V.

You should see three labeled account boxes. CloudTrail and VPC Flow Logs should both point to the encrypted audit bucket.

Does the diagram stay as plain text?

Check that the opening fence uses mermaid and that the closing fence contains three backticks. Confirm that each subgraph has a matching end.

Help me fix the Mermaid preview in README.md.

  • Return to the README.md editor tab.
  • Add the security-control summary below the diagram:
## Security controls

- Every Terraform resource names its account-specific provider.
- Each provider uses a separate role ARN and an `allowed_account_ids` guardrail.
- The workload subnets do not assign public IP addresses and have no configured internet route.
- The default security group allows no traffic.
- The application security group can reach only the database security group on TCP 5432.
- The audit bucket enables versioning, AES256 default encryption, SSE-C blocking, TLS-only access, and all four S3 public-access blocks.
- The organization trail includes global service events, covers all Regions, and enables log-file validation.
- VPC Flow Logs capture `ALL` traffic and deliver it to the security account.

Why document the controls?

The list translates individual resources into reviewable security outcomes. A reader can trace each statement back to a test or configuration block.

  • Add the local verification and live-deployment boundary below the security controls:
## Local verification

```shell
terraform init -backend=false
terraform fmt -check
terraform validate
terraform test
```

The test file replaces all three AWS provider configurations with mocks. No AWS credentials are required and no AWS resources are created.

## Live deployment boundary

Do not deploy this configuration until all of the following exist:

- An AWS Organization with management, security, and workload accounts.
- CloudTrail trusted access enabled in AWS Organizations.
- A pre-provisioned deployment role in each account.
- A globally unique audit bucket name.
- An encrypted remote Terraform state backend with locking and restricted access.

The project intentionally stops before live deployment so that local state does not become an unencrypted fourth storage location.

Why record the deployment boundary?

The local commands explain how to reproduce the mocked checks. The prerequisite list prevents the blueprint from being mistaken for a safe live-deployment workflow.

  • Save README.md.
  • Open the Markdown preview by pressing Shift+Command+V.

You should see the rendered diagram followed by the security controls, verification commands, and live-deployment prerequisites.

✔️ Awesome, I've got everything!

Great. Save every open file before running the final checks.

ⓧ I'd like to double check the full code

resource "aws_s3_bucket" "audit" {
  provider = aws.security

  bucket        = var.audit_bucket_name
  force_destroy = false

  tags = {
    Name = "central-audit-logs"
  }
}

resource "aws_s3_bucket_versioning" "audit" {
  provider = aws.security

  bucket = aws_s3_bucket.audit.id

  versioning_configuration {
    status = "Enabled"
  }
}

resource "aws_s3_bucket_server_side_encryption_configuration" "audit" {
  provider = aws.security

  bucket = aws_s3_bucket.audit.id

  rule {
    apply_server_side_encryption_by_default {
      sse_algorithm = "AES256"
    }

    blocked_encryption_types = ["SSE-C"]
  }
}

resource "aws_s3_bucket_public_access_block" "audit" {
  provider = aws.security

  bucket = aws_s3_bucket.audit.id

  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}

resource "aws_s3_bucket_policy" "audit" {
  provider = aws.security

  bucket = aws_s3_bucket.audit.id
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Sid       = "AllowSSLRequestsOnly"
        Effect    = "Deny"
        Principal = "*"
        Action    = "s3:*"
        Resource = [
          aws_s3_bucket.audit.arn,
          "${aws_s3_bucket.audit.arn}/*"
        ]
        Condition = {
          Bool = {
            "aws:SecureTransport" = false
          }
        }
      },
      {
        Sid    = "AWSCloudTrailAclCheck20150319"
        Effect = "Allow"
        Principal = {
          Service = "cloudtrail.amazonaws.com"
        }
        Action   = "s3:GetBucketAcl"
        Resource = aws_s3_bucket.audit.arn
        Condition = {
          StringEquals = {
            "aws:SourceArn" = local.trail_arn
          }
        }
      },
      {
        Sid    = "AWSCloudTrailWrite20150319"
        Effect = "Allow"
        Principal = {
          Service = "cloudtrail.amazonaws.com"
        }
        Action   = "s3:PutObject"
        Resource = "${aws_s3_bucket.audit.arn}/AWSLogs/${var.management_account_id}/*"
        Condition = {
          StringEquals = {
            "s3:x-amz-acl" = "bucket-owner-full-control"
            "aws:SourceArn" = local.trail_arn
          }
        }
      },
      {
        Sid    = "AWSCloudTrailOrganizationWrite20150319"
        Effect = "Allow"
        Principal = {
          Service = "cloudtrail.amazonaws.com"
        }
        Action   = "s3:PutObject"
        Resource = "${aws_s3_bucket.audit.arn}/AWSLogs/${var.organization_id}/*"
        Condition = {
          StringEquals = {
            "s3:x-amz-acl" = "bucket-owner-full-control"
            "aws:SourceArn" = local.trail_arn
          }
        }
      },
      {
        Sid    = "AWSLogDeliveryWrite"
        Effect = "Allow"
        Principal = {
          Service = "delivery.logs.amazonaws.com"
        }
        Action   = "s3:PutObject"
        Resource = "${aws_s3_bucket.audit.arn}/AWSLogs/${var.workload_account_id}/*"
        Condition = {
          StringEquals = {
            "aws:SourceAccount" = var.workload_account_id
            "s3:x-amz-acl"      = "bucket-owner-full-control"
          }
          ArnLike = {
            "aws:SourceArn" = "arn:aws:logs:${var.aws_region}:${var.workload_account_id}:*"
          }
        }
      },
      {
        Sid    = "AWSLogDeliveryAclCheck"
        Effect = "Allow"
        Principal = {
          Service = "delivery.logs.amazonaws.com"
        }
        Action   = "s3:GetBucketAcl"
        Resource = aws_s3_bucket.audit.arn
        Condition = {
          StringEquals = {
            "aws:SourceAccount" = var.workload_account_id
          }
          ArnLike = {
            "aws:SourceArn" = "arn:aws:logs:${var.aws_region}:${var.workload_account_id}:*"
          }
        }
      }
    ]
  })

  depends_on = [aws_s3_bucket_public_access_block.audit]
}

resource "aws_flow_log" "workload" {
  provider = aws.workload

  log_destination      = aws_s3_bucket.audit.arn
  log_destination_type = "s3"
  traffic_type         = "ALL"
  vpc_id               = aws_vpc.workload.id

  depends_on = [
    aws_s3_bucket_policy.audit,
    aws_s3_bucket_server_side_encryption_configuration.audit
  ]
}

resource "aws_cloudtrail" "organization" {
  provider = aws.management

  name                          = local.trail_name
  s3_bucket_name                = aws_s3_bucket.audit.id
  enable_logging                = true
  enable_log_file_validation    = true
  include_global_service_events = true
  is_multi_region_trail         = true
  is_organization_trail         = true

  depends_on = [
    aws_s3_bucket_policy.audit,
    aws_s3_bucket_versioning.audit,
    aws_s3_bucket_server_side_encryption_configuration.audit
  ]
}

What should logging.tf contain?

The complete file protects one security-account bucket and connects the management trail plus workload flow logs to it.

output "account_targets" {
  description = "AWS account IDs targeted by each provider boundary."
  value = {
    management = var.management_account_id
    security   = var.security_account_id
    workload   = var.workload_account_id
  }
}

output "workload_network" {
  description = "Identifiers for the segmented workload network."
  value = {
    vpc_id         = aws_vpc.workload.id
    app_subnet_id  = aws_subnet.app.id
    data_subnet_id = aws_subnet.data.id
  }
}

output "logging_controls" {
  description = "Security controls enabled by the logging baseline."
  value = {
    audit_bucket                = aws_s3_bucket.audit.id
    flow_logs_enabled           = true
    organization_trail_enabled  = aws_cloudtrail.organization.is_organization_trail
    multi_region_trail_enabled  = aws_cloudtrail.organization.is_multi_region_trail
    log_file_validation_enabled = aws_cloudtrail.organization.enable_log_file_validation
  }
}

What should outputs.tf contain?

The complete file exposes account targets, workload network identifiers, and the major centralized logging controls.

mock_provider "aws" {
  alias           = "management"
  override_during = plan
}

mock_provider "aws" {
  alias           = "security"
  override_during = plan

  mock_resource "aws_s3_bucket" {
    defaults = {
      arn = "arn:aws:s3:::secure-landing-zone-audit-logs-example"
    }
  }
}

mock_provider "aws" {
  alias           = "workload"
  override_during = plan
}

run "landing_zone_is_secure" {
  command = plan

  variables {
    aws_region            = "us-east-1"
    management_account_id = "111111111111"
    security_account_id   = "222222222222"
    workload_account_id   = "333333333333"
    management_role_arn   = "arn:aws:iam::111111111111:role/TerraformExecutionRole"
    security_role_arn     = "arn:aws:iam::222222222222:role/TerraformExecutionRole"
    workload_role_arn     = "arn:aws:iam::333333333333:role/TerraformExecutionRole"
    organization_id       = "o-exampleorgid"
    audit_bucket_name     = "secure-landing-zone-audit-logs-example"
  }

  assert {
    condition = (
      output.account_targets.management == "111111111111" &&
      output.account_targets.security == "222222222222" &&
      output.account_targets.workload == "333333333333"
    )
    error_message = "Each provider boundary must target the intended AWS account."
  }

  assert {
    condition = (
      aws_vpc.workload.cidr_block == "10.20.0.0/16" &&
      aws_subnet.app.map_public_ip_on_launch == false &&
      aws_subnet.data.map_public_ip_on_launch == false &&
      length(aws_route_table.app.route) == 0 &&
      length(aws_route_table.data.route) == 0
    )
    error_message = "The workload VPC must use private subnets with no configured internet routes."
  }

  assert {
    condition = (
      length(aws_default_security_group.workload.ingress) == 0 &&
      length(aws_default_security_group.workload.egress) == 0
    )
    error_message = "The workload default security group must not allow ingress or egress."
  }

  assert {
    condition = (
      aws_vpc_security_group_egress_rule.app_to_database.referenced_security_group_id == aws_security_group.database.id &&
      aws_vpc_security_group_egress_rule.app_to_database.ip_protocol == "tcp" &&
      aws_vpc_security_group_egress_rule.app_to_database.from_port == 5432 &&
      aws_vpc_security_group_egress_rule.app_to_database.to_port == 5432 &&
      aws_vpc_security_group_ingress_rule.database_from_app.referenced_security_group_id == aws_security_group.app.id
    )
    error_message = "Application traffic must target only the database security group on TCP 5432."
  }

  assert {
    condition = (
      length(aws_vpc_security_group_rules_exclusive.app.ingress_rule_ids) == 0 &&
      length(aws_vpc_security_group_rules_exclusive.app.egress_rule_ids) == 1 &&
      length(aws_vpc_security_group_rules_exclusive.database.ingress_rule_ids) == 1 &&
      length(aws_vpc_security_group_rules_exclusive.database.egress_rule_ids) == 0
    )
    error_message = "The app and database security groups must own only their declared rules."
  }

  assert {
    condition = (
      length([
        for configuration in aws_s3_bucket_versioning.audit.versioning_configuration : configuration
        if configuration.status == "Enabled"
      ]) == 1 &&
      length([
        for rule in aws_s3_bucket_server_side_encryption_configuration.audit.rule : rule
        if length([
          for encryption in rule.apply_server_side_encryption_by_default : encryption
          if encryption.sse_algorithm == "AES256"
        ]) == 1
      ]) == 1
    )
    error_message = "The audit bucket must have versioning and AES256 default encryption enabled."
  }

  assert {
    condition = (
      aws_s3_bucket_public_access_block.audit.block_public_acls &&
      aws_s3_bucket_public_access_block.audit.block_public_policy &&
      aws_s3_bucket_public_access_block.audit.ignore_public_acls &&
      aws_s3_bucket_public_access_block.audit.restrict_public_buckets
    )
    error_message = "Every S3 public-access block setting must be enabled."
  }

  assert {
    condition = (
      aws_flow_log.workload.log_destination_type == "s3" &&
      aws_flow_log.workload.traffic_type == "ALL" &&
      aws_flow_log.workload.log_destination == aws_s3_bucket.audit.arn
    )
    error_message = "Workload VPC Flow Logs must capture all traffic in the central audit bucket."
  }

  assert {
    condition = (
      aws_cloudtrail.organization.enable_logging &&
      aws_cloudtrail.organization.enable_log_file_validation &&
      aws_cloudtrail.organization.include_global_service_events &&
      aws_cloudtrail.organization.is_multi_region_trail &&
      aws_cloudtrail.organization.is_organization_trail &&
      aws_cloudtrail.organization.s3_bucket_name == aws_s3_bucket.audit.id
    )
    error_message = "CloudTrail must be enabled organization-wide, across Regions, with validation and central storage."
  }
}

What should the test file prove?

The complete mocked suite checks account targets, private networking, least-privilege rules, protected storage, flow logging, and organization-wide CloudTrail.

.terraform/
*.tfstate
*.tfstate.*
crash.log
*.tfvars

What should .gitignore exclude?

The file excludes provider downloads, state files, crash logs, and variable-value files.

# Secure Three-Account AWS Landing Zone Blueprint

This Terraform root module models three explicit AWS account boundaries:

- Management account: owns the organization trail.
- Security account: owns the central audit bucket.
- Workload account: owns the private VPC and VPC Flow Logs.

The default project path uses mocked providers and does not contact AWS.

## Architecture

```mermaid
flowchart LR
  TF[Terraform root module]

  subgraph MGMT[Management account]
    CT[Organization CloudTrail]
  end

  subgraph SEC[Security account]
    S3[Encrypted and versioned audit bucket]
  end

  subgraph WORK[Workload account]
    VPC[Private workload VPC]
    APP[Application security group]
    DB[Database security group]
    FLOW[VPC Flow Logs]

    VPC --> APP
    VPC --> DB
    APP -->|TCP 5432 only| DB
  end

  TF -->|aws.management| CT
  TF -->|aws.security| S3
  TF -->|aws.workload| VPC
  CT -->|Organization logs| S3
  FLOW -->|Network flow records| S3
```

## Security controls

- Every Terraform resource names its account-specific provider.
- Each provider uses a separate role ARN and an `allowed_account_ids` guardrail.
- The workload subnets do not assign public IP addresses and have no configured internet route.
- The default security group allows no traffic.
- The application security group can reach only the database security group on TCP 5432.
- The audit bucket enables versioning, AES256 default encryption, SSE-C blocking, TLS-only access, and all four S3 public-access blocks.
- The organization trail includes global service events, covers all Regions, and enables log-file validation.
- VPC Flow Logs capture `ALL` traffic and deliver it to the security account.

## Local verification

```shell
terraform init -backend=false
terraform fmt -check
terraform validate
terraform test
```

The test file replaces all three AWS provider configurations with mocks. No AWS credentials are required and no AWS resources are created.

## Live deployment boundary

Do not deploy this configuration until all of the following exist:

- An AWS Organization with management, security, and workload accounts.
- CloudTrail trusted access enabled in AWS Organizations.
- A pre-provisioned deployment role in each account.
- A globally unique audit bucket name.
- An encrypted remote Terraform state backend with locking and restricted access.

The project intentionally stops before live deployment so that local state does not become an unencrypted fourth storage location.

What should README.md show?

The complete document explains the account model, renders the architecture, lists its controls, and separates local testing from live deployment.

Before you run the final checks, do you expect the complete blueprint to pass without AWS credentials?

  • Return to the terminal in the secure-aws-landing-zone folder.
  • Initialize without a backend before checking formatting, validation, and tests by running:
terraform init -backend=false
terraform fmt -check
terraform validate
terraform test

What does the final sequence verify?

  • The initialization command prepares the pinned provider without using a configured backend.
  • The formatting check confirms that every Terraform file uses canonical formatting.
  • The validation command checks syntax and internal references.
  • The test command executes the mocked plan and every security assertion.

All four commands should succeed. The final test reports a passing run without requesting AWS credentials or creating AWS resources.

Did a final check fail?

Use the first failing command to narrow the problem. A formatting failure points to file layout while a validation failure points to syntax or references.

A test failure names the security assertion that needs attention. Compare that condition with the matching resource before rerunning the sequence.

Help me diagnose my final Terraform verification failure.

  • Return to README.md in VS Code.
  • Open the rendered preview by pressing Shift+Command+V.

You should see management, security, and workload account boundaries. The organization trail and workload flow logs should both point to the encrypted audit bucket.

You now have a locally tested three-account landing-zone blueprint with centralized audit logging and rendered architecture documentation. Every major trust boundary is visible in code, tests, and the diagram.

Secret mission

Prove the Bucket Policy Is Scoped

A bucket policy can look secure while one statement quietly trusts the wrong source. You will decode the generated policy inside the mocked test. Two new assertions prove that each logging service is constrained to its intended source.

Clean Up Your Resources

Clean Up Your Resources

Your entire Terraform landing-zone blueprint stays on your Mac, so it has no ongoing cost. The mocked path creates no AWS resources for you to clean up.

Decide whether to keep the local files, pause your work, or delete the project folder entirely.

Resources you used:

  • Local source files in the secure-aws-landing-zone folder on your Desktop.
  • Downloaded HashiCorp AWS Provider files in secure-aws-landing-zone/.terraform/.

What stays installed?

Homebrew, Terraform, and Visual Studio Code stay on your Mac because they are reusable tools. The cleanup choices below only affect secure-aws-landing-zone.

Keep everything running

No action is needed. Choose this option if you want to keep testing or extending your landing-zone blueprint.

  • Keep the secure-aws-landing-zone folder on your Desktop.
  • Leave the .terraform/ provider cache in place for future test runs.
  • Continue using the mocked test path without ongoing costs or cloud resources.

Pause - I'll come back to this later

This option keeps every project file while freeing the memory used by your editor. Terraform leaves no background infrastructure running after the tests finish.

  • Close the Visual Studio Code window.
  • Keep the secure-aws-landing-zone folder on your Desktop.
  • Use the local verification commands in README.md when you return.

Delete - I don't want to use this again

Deleting the folder is permanent. The command only touches your local blueprint because the mocked path created no AWS resources.

  • Close the Visual Studio Code window.
  • Delete the secure-aws-landing-zone folder from your Desktop by running this command:
rm -rf ~/Desktop/secure-aws-landing-zone

What does this command remove?

This removes the local secure-aws-landing-zone folder plus its downloaded provider cache. It does not contact AWS.

  • Check your Desktop in Finder.

You should no longer see the secure-aws-landing-zone folder.

Still see the project folder?

  • Confirm that the folder is on your Desktop with the exact name secure-aws-landing-zone.
  • Help me safely remove my local secure-aws-landing-zone folder.

Nice Work!

Nice Work!

You did it! You built a locally tested three-account AWS landing zone blueprint with Terraform.

What you learned:

  • Defined three explicit account targets through Terraform provider aliases. Protected each target with a separate AssumeRole input. Added allowed account guardrails.
  • Modeled a private Amazon VPC with separate application and data subnets. Restricted database access to TCP 5432 through exclusive security group rules.
  • Centralized AWS CloudTrail events plus VPC Flow Logs in an encrypted Amazon S3 audit bucket. Proved the logging controls with mocked Terraform tests. Documented the trust paths in a Mermaid diagram.
  • Secret Mission: Decoded the generated bucket policy with jsondecode. Proved AWSCloudTrailOrganizationWrite20150319 is scoped by local.trail_arn. Proved AWSLogDeliveryWrite is scoped by var.workload_account_id.

Ready to quiz yourself?