Building an Org-Wide AWS Security Baseline with Terraform

Building an Org-Wide AWS Security Baseline with Terraform

What a Baseline Needs to Cover

Standing up a multi-account AWS organization is the easy half. The harder half is making sure that the fortieth account created next year has the same threat detection, the same guardrails and the same audit trail as the third one created today, without anyone remembering to click through a checklist.

Most teams start by enabling GuardDuty in the production account, then Security Hub in another, then a Config rule or two somewhere else. Within a few months the coverage is a patchwork: some accounts report findings, some do not, and nobody can say with confidence which is which. A security baseline fixes that by treating coverage as a property of the organization instead of a property of each account.

This post builds that baseline in Terraform using the delegated administrator pattern: the management account stays nearly empty, a dedicated security account runs GuardDuty, Security Hub, IAM Access Analyzer and AWS Config for the whole organization, and every new account is enrolled automatically. It also adds preventive guardrails with Service Control Policies, a small per-account hardening module, and centralized human access through IAM Identity Center.

The post assumes a working AWS Organization with a dedicated security account, familiarity with Terraform modules and provider aliases, and a state backend already in place. Organization and account creation are covered in the earlier landing zone post.

Org-wide AWS security baseline architecture showing the management account designating a security account as delegated administrator for GuardDuty, Security Hub, Access Analyzer and Config, with member accounts enrolled automatically and SCPs inherited by every OU

Organization-wide security baseline: the security account centrally manages detective services while SCPs provide preventive guardrails across member accounts.

Three Layers of an AWS Security Baseline

Security tooling falls into three layers, and each answers a different question:

Layer Question it answers Tools used here
Preventive What can never happen, whatever IAM says? Service Control Policies, account-level hardening
Detective What is happening, and what drifted? GuardDuty, Security Hub, IAM Access Analyzer, AWS Config
Access Who can get in, and with what permissions? IAM Identity Center permission sets

A baseline that covers only one layer leaves gaps. Detection without prevention produces a steady stream of findings about things that could have been blocked outright. Prevention without detection means the first sign of a problem is an incident.

The Delegated Administrator Pattern

Every service in this post supports the same arrangement. The management account designates one member account as the delegated administrator for the service. From then on:

The sequence is the same for each service, and it is what the numbers in the diagram show:

  1. The management account enables the service's trusted access in AWS Organizations and designates the security account.
  2. The security account turns the service on and sets the organization-wide configuration, including auto-enable for members.
  3. Member accounts are enrolled automatically, and findings flow up.

The management account establishes the relationship. The security account operates the service. Member accounts provide the security data.

Project Layout

The Terraform code is organized into three main areas: the organization configuration, resources that live in the security account, and a reusable module for account-level hardening.

security-baseline/
├── org/                       # applied from the management account
│   ├── providers.tf           # default provider (management) + aliased provider (security)
│   ├── delegated_admins.tf    # designate the security account for each service
│   ├── scps.tf                # preventive guardrails
│   └── identity_center.tf     # permission sets and assignments
│
├── security-account/          # resources that live in the security account
│   ├── guardduty.tf
│   ├── securityhub.tf
│   ├── access_analyzer.tf
│   └── config.tf
│
└── modules/
    └── account-baseline/      # applied to every account, including new ones
        ├── main.tf
        └── variables.tf

For clarity the snippets below sit in one root module, using two provider configurations. Teams that prefer stronger blast-radius separation can split security-account/ into its own state and read the account ID from a variable. The trade-off is discussed in the pitfalls section.

Provider alias reminder: The default AWS provider is configured for the management account. The aliased aws.security provider assumes a role in the dedicated security account.

Step 0: Enable Trusted Access for the Services

The organization resource must list the service principals, otherwise the designation calls fail. This lives with the organization definition, typically in the landing zone code:

resource "aws_organizations_organization" "this" {
  feature_set = "ALL"

  aws_service_access_principals = [
    "guardduty.amazonaws.com",
    "securityhub.amazonaws.com",
    "access-analyzer.amazonaws.com",
    "config.amazonaws.com",
    "config-multiaccountsetup.amazonaws.com",
    "sso.amazonaws.com",
  ]

  enabled_policy_types = ["SERVICE_CONTROL_POLICY"]
}

Adding principals to an existing organization is safe, and it is the one change in this post that touches the organization resource itself.

Step 1: Two Providers, One Apply

The root module talks to the management account by default and to the security account through an aliased provider that assumes the role AWS creates in every member account:

# org/providers.tf

terraform {
  required_version = ">= 1.7"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.81"
    }
  }
}

variable "region" {
  type    = string
  default = "ap-south-1"
}

variable "security_account_id" {
  type = string
}

provider "aws" {
  region = var.region
}

provider "aws" {
  alias  = "security"
  region = var.region

  assume_role {
    role_arn     = "arn:aws:iam::${var.security_account_id}:role/OrganizationAccountAccessRole"
    session_name = "terraform-security-baseline"
  }
}

data "aws_organizations_organization" "this" {}

Everything created with provider = aws.security lands in the security account. Everything else lands in the management account.

Keep the account boundary clear. Before applying, confirm which provider each resource uses. A missing provider alias can cause a resource to be created in the management account instead of the security account.

Step 2: Designate the Delegated Administrators

This is the only part that must run from the management account. One resource per service:

# org/delegated_admins.tf

# GuardDuty needs a detector in the management account before the designation
resource "aws_guardduty_detector" "management" {
  enable = true
}

resource "aws_guardduty_organization_admin_account" "this" {
  admin_account_id = var.security_account_id
  depends_on       = [aws_guardduty_detector.management]
}

# Security Hub must be enabled in the management account first
resource "aws_securityhub_account" "management" {}

resource "aws_securityhub_organization_admin_account" "this" {
  admin_account_id = var.security_account_id
  depends_on       = [aws_securityhub_account.management]
}

# Services without a dedicated resource use the generic delegation resource
resource "aws_organizations_delegated_administrator" "access_analyzer" {
  account_id        = var.security_account_id
  service_principal = "access-analyzer.amazonaws.com"
}

resource "aws_organizations_delegated_administrator" "config" {
  account_id        = var.security_account_id
  service_principal = "config.amazonaws.com"
}

resource "aws_organizations_delegated_administrator" "config_multiaccount" {
  account_id        = var.security_account_id
  service_principal = "config-multiaccountsetup.amazonaws.com"
}

Designations can be confirmed from the CLI:

aws organizations list-delegated-administrators
aws guardduty list-organization-admin-accounts
aws securityhub list-organization-admin-accounts

The resources are quick to create and disruptive to remove, so adding lifecycle { prevent_destroy = true } to each is a cheap safeguard.

Protect delegated administrator resources. Removing a designation can interrupt centralized security management and automatic enrollment. Treat these resources as long-lived organization infrastructure.

Step 3: GuardDuty Across the Organization

GuardDuty is the first detective control to enable because it needs no agents and starts producing signal immediately: unusual API calls, credential exfiltration patterns, crypto-mining behavior, suspicious DNS and network activity.

# security-account/guardduty.tf

resource "aws_guardduty_detector" "security" {
  provider                     = aws.security
  enable                       = true
  finding_publishing_frequency = "FIFTEEN_MINUTES"
}

resource "aws_guardduty_organization_configuration" "this" {
  provider                         = aws.security
  detector_id                      = aws_guardduty_detector.security.id
  auto_enable_organization_members = "ALL"

  depends_on = [aws_guardduty_organization_admin_account.this]
}

locals {
  guardduty_features = [
    "S3_DATA_EVENTS",
    "EBS_MALWARE_PROTECTION",
    "RDS_LOGIN_EVENTS",
    "LAMBDA_NETWORK_LOGS",
  ]
}

resource "aws_guardduty_organization_configuration_feature" "this" {
  for_each = toset(local.guardduty_features)
  provider = aws.security

  detector_id = aws_guardduty_detector.security.id
  name        = each.value
  auto_enable = "ALL"

  depends_on = [aws_guardduty_organization_configuration.this]
}

Two settings deserve attention:

Start with the workloads you actually run. Enabling every protection feature without reviewing its relevance and pricing can increase costs unnecessarily.

Step 4: Security Hub as the Single Pane

Security Hub collects findings from GuardDuty, Access Analyzer, Config and other integrations, normalizes them into one format, and adds its own continuous control checks against security standards.

# security-account/securityhub.tf

resource "aws_securityhub_account" "security" {
  provider                 = aws.security
  enable_default_standards = false
  auto_enable_controls     = true
}

# Collect findings from every region into the home region
resource "aws_securityhub_finding_aggregator" "this" {
  provider     = aws.security
  linking_mode = "ALL_REGIONS"

  depends_on = [aws_securityhub_account.security]
}

resource "aws_securityhub_organization_configuration" "this" {
  provider              = aws.security
  auto_enable           = true
  auto_enable_standards = "DEFAULT"

  depends_on = [
    aws_securityhub_organization_admin_account.this,
    aws_securityhub_finding_aggregator.this,
  ]
}

resource "aws_securityhub_standards_subscription" "fsbp" {
  provider      = aws.security
  standards_arn = "arn:aws:securityhub:${var.region}::standards/aws-foundational-security-best-practices/v/1.0.0"

  depends_on = [aws_securityhub_account.security]
}

The AWS Foundational Security Best Practices standard is the most useful starting point. It is broad, maintained by AWS, and its controls map to real misconfigurations rather than audit paperwork. The CIS benchmark and PCI DSS standards can be added the same way when a compliance requirement calls for them.

Two cautions for teams adopting this at scale:

Step 5: IAM Access Analyzer for the Whole Organization

Access Analyzer answers a question nothing else here does: which resources can principals outside the organization reach? That covers S3 buckets with permissive policies, KMS keys shared externally, IAM roles with trust policies that name foreign accounts, and similar cases.

# security-account/access_analyzer.tf

resource "aws_accessanalyzer_analyzer" "org_external_access" {
  provider      = aws.security
  analyzer_name = "org-external-access"
  type          = "ORGANIZATION"

  depends_on = [aws_organizations_delegated_administrator.access_analyzer]
}

An analyzer of type ORGANIZATION treats the whole organization as the zone of trust. Anything reachable from outside it becomes a finding, and those findings appear in Security Hub alongside everything else.

Think of the organization as the trust boundary. Access Analyzer helps identify resources that are shared outside that boundary, so teams can review whether the access is intentional.

Step 6: AWS Config Aggregation and Organization Rules

Config records resource configuration over time and evaluates it against rules. The aggregator brings that data from every account and region into the security account.

# security-account/config.tf

data "aws_iam_policy_document" "config_assume" {
  statement {
    actions = ["sts:AssumeRole"]
    principals {
      type        = "Service"
      identifiers = ["config.amazonaws.com"]
    }
  }
}

resource "aws_iam_role" "config_aggregator" {
  provider           = aws.security
  name               = "config-org-aggregator"
  assume_role_policy = data.aws_iam_policy_document.config_assume.json
}

resource "aws_iam_role_policy_attachment" "config_aggregator" {
  provider   = aws.security
  role       = aws_iam_role.config_aggregator.name
  policy_arn = "arn:aws:iam::aws:policy/service-role/AWSConfigRoleForOrganizations"
}

resource "aws_config_configuration_aggregator" "org" {
  provider = aws.security
  name     = "org-aggregator"

  organization_aggregation_source {
    all_regions = true
    role_arn    = aws_iam_role.config_aggregator.arn
  }

  depends_on = [
    aws_iam_role_policy_attachment.config_aggregator,
    aws_organizations_delegated_administrator.config,
  ]
}

locals {
  org_config_rules = {
    "s3-bucket-public-read-prohibited"  = "S3_BUCKET_PUBLIC_READ_PROHIBITED"
    "s3-bucket-public-write-prohibited" = "S3_BUCKET_PUBLIC_WRITE_PROHIBITED"
    "root-account-mfa-enabled"          = "ROOT_ACCOUNT_MFA_ENABLED"
    "iam-root-access-key-check"         = "IAM_ROOT_ACCESS_KEY_CHECK"
    "encrypted-volumes"                 = "ENCRYPTED_VOLUMES"
    "cloudtrail-enabled"                = "CLOUD_TRAIL_ENABLED"
  }
}

resource "aws_config_organization_managed_rule" "this" {
  for_each = local.org_config_rules
  provider = aws.security

  name            = each.key
  rule_identifier = each.value

  depends_on = [aws_organizations_delegated_administrator.config_multiaccount]
}

Organization rules are deployed into every member account, but a rule can only evaluate resources in an account where the Config recorder is running. That is why the account baseline module below turns the recorder on.

Do not forget the Config recorder. Creating organization rules does not by itself guarantee that resources are being recorded. The recorder and delivery channel must also be configured in each account.

Step 7: Preventive Guardrails with SCPs

Detection tells the security team that something happened. SCPs make some things impossible. Three policies cover the most important cases: root user usage, tampering with the security tooling, and leaving the approved regions (the region policy from the landing zone post can be reused here).

# org/scps.tf

resource "aws_organizations_policy" "deny_root_user" {
  name = "deny-root-user-actions"
  type = "SERVICE_CONTROL_POLICY"

  content = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Sid      = "DenyRootUser"
      Effect   = "Deny"
      Action   = "*"
      Resource = "*"
      Condition = {
        StringLike = {
          "aws:PrincipalArn" = ["arn:aws:iam::*:root"]
        }
      }
    }]
  })
}

resource "aws_organizations_policy" "protect_security_tooling" {
  name = "protect-security-tooling"
  type = "SERVICE_CONTROL_POLICY"

  content = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Sid    = "DenyDisablingSecurityServices"
      Effect = "Deny"
      Action = [
        "guardduty:DeleteDetector",
        "guardduty:DisassociateFromAdministratorAccount",
        "guardduty:DisassociateFromMasterAccount",
        "securityhub:DisableSecurityHub",
        "securityhub:DisassociateFromAdministratorAccount",
        "securityhub:DisassociateFromMasterAccount",
        "securityhub:BatchDisableStandards",
        "config:DeleteConfigurationRecorder",
        "config:StopConfigurationRecorder",
        "config:DeleteDeliveryChannel",
        "access-analyzer:DeleteAnalyzer",
      ]
      Resource = "*"
    }]
  })
}

variable "workload_ou_ids" {
  description = "OU IDs that receive the guardrails. Test on a sandbox OU first."
  type        = map(string)
}

locals {
  baseline_scps = {
    deny_root_user            = aws_organizations_policy.deny_root_user.id
    protect_security_tooling  = aws_organizations_policy.protect_security_tooling.id
  }

  scp_attachments = {
    for pair in setproduct(keys(var.workload_ou_ids), keys(local.baseline_scps)) :
    "${pair[0]}-${pair[1]}" => {
      ou     = var.workload_ou_ids[pair[0]]
      policy = local.baseline_scps[pair[1]]
    }
  }
}

resource "aws_organizations_policy_attachment" "baseline" {
  for_each  = local.scp_attachments
  policy_id = each.value.policy
  target_id = each.value.ou
}

Some properties of SCPs matter in practice:

The root-user policy pairs well with AWS's centralized root access management for member accounts, which removes the need for root credentials in member accounts altogether. That feature is worth enabling once the SCP is in place.

Test SCPs before applying them broadly. Attach policies to a sandbox OU first. Verify that expected actions are denied and that essential operational workflows continue to work before moving the policies to production.

Step 8: The Per-Account Hardening Module

Some controls are properties of a single account and region rather than of the organization. A small module, applied to every account by the same pipeline that creates it, closes those gaps and turns on the Config recorder that the organization rules depend on:

# modules/account-baseline/main.tf

variable "config_bucket" {
  description = "Central S3 bucket in the log archive account for Config snapshots"
  type        = string
}

# Block public S3 access for every bucket in the account, present and future
resource "aws_s3_account_public_access_block" "this" {
  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}

# New EBS volumes are encrypted by default (this setting is per region)
resource "aws_ebs_encryption_by_default" "this" {
  enabled = true
}

# Config recorder, so organization rules can actually evaluate resources
resource "aws_iam_service_linked_role" "config" {
  aws_service_name = "config.amazonaws.com"
}

resource "aws_config_configuration_recorder" "this" {
  name     = "default"
  role_arn = aws_iam_service_linked_role.config.arn

  recording_group {
    all_supported                 = true
    include_global_resource_types = false
  }
}

resource "aws_config_delivery_channel" "this" {
  name           = "default"
  s3_bucket_name = var.config_bucket

  depends_on = [aws_config_configuration_recorder.this]
}

resource "aws_config_configuration_recorder_status" "this" {
  name       = aws_config_configuration_recorder.this.name
  is_enabled = true

  depends_on = [aws_config_delivery_channel.this]
}

include_global_resource_types = false avoids recording IAM and other global resources redundantly in every region. One region, usually the home region, should record them.

Apply this module consistently. The account baseline should be part of the account provisioning workflow, so newly created accounts receive the same hardening controls without a separate manual step.

Step 9: Human Access Through IAM Identity Center

The detective tools are only useful if the security team can reach them without long-lived credentials. Identity Center permission sets give a group the same role in every account, with short sessions, and assignments are plain Terraform:

# org/identity_center.tf

data "aws_ssoadmin_instances" "this" {}

locals {
  sso_instance_arn  = tolist(data.aws_ssoadmin_instances.this.arns)[0]
  identity_store_id = tolist(data.aws_ssoadmin_instances.this.identity_store_ids)[0]
}

variable "all_account_ids" {
  description = "Account IDs that the security team can audit"
  type        = map(string) # name => account ID
}

resource "aws_ssoadmin_permission_set" "security_audit" {
  name             = "SecurityAudit"
  description      = "Read-only security review access"
  instance_arn     = local.sso_instance_arn
  session_duration = "PT4H"
}

resource "aws_ssoadmin_managed_policy_attachment" "security_audit" {
  instance_arn       = local.sso_instance_arn
  permission_set_arn = aws_ssoadmin_permission_set.security_audit.arn
  managed_policy_arn = "arn:aws:iam::aws:policy/SecurityAudit"
}

data "aws_identitystore_group" "security_team" {
  identity_store_id = local.identity_store_id

  alternate_identifier {
    unique_attribute {
      attribute_path  = "DisplayName"
      attribute_value = "security-team"
    }
  }
}

resource "aws_ssoadmin_account_assignment" "security_audit" {
  for_each = var.all_account_ids

  instance_arn       = local.sso_instance_arn
  permission_set_arn = aws_ssoadmin_permission_set.security_audit.arn

  principal_id   = data.aws_identitystore_group.security_team.group_id
  principal_type = "GROUP"

  target_id   = each.value
  target_type = "AWS_ACCOUNT"
}

Assignments go to groups rather than individual users, so onboarding and offboarding happen in the identity provider and nothing in Terraform changes. The for_each uses a map of account names rather than a list of IDs created in the same apply, which keeps the keys known at plan time.

Use groups instead of individual assignments. This makes access easier to manage as team members join, leave, or change responsibilities.

Verifying the Baseline

A baseline that has never been tested is a hypothesis. Four checks cover the main claims:

  1. Enrollment. In the security account, aws guardduty list-members --detector-id <id> should list every member account with a status of Enabled. In Security Hub, the accounts page should show the same set.
  2. Findings flow. In a member account, generate sample findings with aws guardduty create-sample-findings --detector-id <member-detector-id> --finding-types Recon:EC2/PortProbeUnprotectedPort. Within a few minutes the finding should appear in the security account's Security Hub, labeled with the member's account ID.
  3. Guardrails hold. In a sandbox account under the SCP-attached OU, try aws guardduty delete-detector. The expected result is AccessDenied with an explicit deny from a service control policy.
  4. New accounts enroll themselves. Create a throwaway account through the landing zone pipeline, then confirm GuardDuty and Security Hub appear enabled in it without any manual step. This is the check that actually proves "baseline" rather than "configuration of existing accounts".
The new-account test is especially important. Existing accounts may already have been configured manually. Creating a new account and confirming automatic enrollment proves that the organization-level baseline is working.

Cost: Where the Bill Grows

All four detective services price by usage, which means the cost of a baseline scales with how busy the accounts are:

Sandbox and short-lived accounts are the obvious place to review. Recording every resource type in a throwaway account that lives for a day rarely earns its cost.

Review costs as coverage expands. More accounts, more regions, additional GuardDuty protection features and more Config recording can all increase the bill. Review usage and pricing before enabling new coverage organization-wide.

Common Pitfalls

Where This Goes Next

The underlying idea carries across all of them: security coverage should be defined once at the organization level, applied automatically to every account, and tested by creating a new account and checking that nothing has to be done by hand.

Final Takeaway

An organization-wide security baseline is not just about enabling individual AWS security services. It is about making security coverage consistent, repeatable and automatic across every account.

By using a dedicated security account, delegated administrators, organization-wide detection, preventive SCPs, account-level hardening and IAM Identity Center, teams can build a foundation that scales as the AWS organization grows.

The goal is simple: every account should start with the same security baseline, and no account should depend on someone remembering to enable it manually.

Suggested Screenshots

The following screenshots can make the implementation easier to understand and demonstrate that the baseline is working:

← Back to All Blogs