Skip to content

One Account, Many Teams: Governing a Shared AWS AI Space Without Account Sprawl

19 minute read
Content level: Expert
0

A practical blueprint for running one shared AWS account across many teams — keeping the efficiency of consolidation while enforcing strong isolation, cost discipline, and governance at scale.

`Isolate resources, data, and compute across 20+ teams in a single shared AWS account using attribute-based access control (ABAC), automated resource expiry, and tag-based lifecycle management — without managing per-team IAM policies.

Many organizations are consolidating AI and ML workloads into a shared AWS account — often called an "AI Space" — where multiple departments collaborate on experiments, training jobs, and model deployments. This model reduces account sprawl, but it introduces a critical question: how do you enforce department boundaries, prevent resource sprawl, and maintain governance at scale?

In this article, we walk through a proven, defense-in-depth approach that addresses three pillars of shared-account governance:

  1. Department and team boundary enforcement — ABAC with tags, permission boundaries, SageMaker domain isolation, subnet isolation, and S3 prefix-based access control.
  2. Automated resource expiry and cleanup — Ensuring sandbox resources are automatically removed after 60 days unless explicitly extended.
  3. Tag-based resource discovery and deletion — Finding and removing all resources belonging to a specific department or team on demand.

This article also includes an appendix on RDS schema segregation — isolating database access at the schema level using PostgreSQL grants and IAM Database Authentication.

Benefits of this approach

A tag-driven governance model provides several advantages for organizations running shared AI workloads:

  • Single ABAC policy for all departments — No per-department IAM policy management. New teams are onboarded in minutes by adding a tag value and a permission set.
  • Defense in depth — Five complementary isolation layers (ABAC, permission boundaries, SageMaker domains, subnet isolation, S3 prefix isolation) reinforce each other.
  • Automated lifecycle management — Resources are tagged with an expiry date at creation. A daily Lambda scanner warns owners and deletes expired resources automatically.
  • Self-service extensibility — Adding a new team or department requires no IAM policy changes. Tag matching handles access automatically.
  • Audit and compliance — Mandatory tags enforce accountability (owner, data classification, cost center), and AWS Config rules continuously scan for non-compliant resources.

Solution overview

The governance model covers three areas, each with multiple implementation options ranked by effort and strength. The recommended approach combines all layers for defense in depth.

The solution follows this deployment pattern:

  1. Define a mandatory tag strategy and enforce it with SCPs and tag policies.
  2. Implement ABAC-based department isolation with a single IAM policy.
  3. Layer additional boundaries — permission boundaries, SageMaker domains, subnet isolation, and S3 prefix isolation.
  4. Configure automated resource expiry with tag-based Lambda cleanup.
  5. Set up tag-based resource discovery and deletion for on-demand cleanup.
  6. (Optional) Configure RDS schema segregation for shared database instances.

Prerequisites

Make sure that you have the following:

  • An AWS account designated as the shared AI Space.
  • AWS Organizations enabled with Service Control Policies (SCPs) and Tag Policies.
  • AWS IAM Identity Center configured for user authentication.
  • AWS Config enabled in the account for compliance scanning.
  • Permission to create IAM policies, Lambda functions, and EventBridge rules.
  • (Optional) An Amazon RDS PostgreSQL instance if you plan to implement schema segregation.

Enforce department and team boundaries

The challenge

A single AWS account is shared by four departments, each with approximately five teams (20 teams total). Resources, data, and compute must be logically isolated so that Department A cannot access Department B's work — without the overhead of managing 20 separate accounts.

Option A: ABAC with tags (recommended)

How it works: Tag IAM principals (users and roles) with Department and Team. Tag every resource with the same keys. IAM policies enforce that a principal can only access resources whose tags match their own.

Step 1: Define the tag strategy

Define the following tag keys at account setup. Values can be added at any time for new teams.

Tag KeyRequiredExample ValuesPurpose
DepartmentYesAlpha, Beta, DataScience, AnalyticsABAC access control, cost allocation
TeamYesteam-a1, team-a2, team-b1, team-d3Finer-grained access, cost tracking
ProjectYesproject-x, data-pipelineCost tracking, audit
DataClassificationYesred, amber, greenCyber compliance
EnvironmentYessandbox, dev, qa, prodLifecycle stage
OwnerYesjohn.smith@example.comAccountability
ExpiryDateYes2026-11-11 (YYYY-MM-DD)Auto-cleanup (see auto-remediation section)
CostCenterOptionalCC-12345Finance chargeback

Step 2: Enforce tags with SCPs

Create an SCP that denies resource creation without the required tags:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "DenyUntaggedResources",
      "Effect": "Deny",
      "Action": [
        "ec2:RunInstances", "s3:CreateBucket",
        "rds:CreateDBInstance", "lambda:CreateFunction",
        "sagemaker:CreateNotebookInstance",
        "ecs:CreateService", "dynamodb:CreateTable"
      ],
      "Resource": "*",
      "Condition": {
        "Null": {
          "aws:RequestTag/Department": "true",
          "aws:RequestTag/Team": "true",
          "aws:RequestTag/ExpiryDate": "true"
        }
      }
    }
  ]
}

Step 3: Enforce tag values with tag policies

Use tag policies to restrict allowed values and prevent typos:

{
  "tags": {
    "Department": {
      "tag_key": { "@@assign": "Department" },
      "tag_value": {
        "@@assign": ["Alpha", "Beta", "DataScience", "Analytics"]
      },
      "enforced_for": {
        "@@assign": ["ec2:instance", "s3:bucket", "rds:db", "lambda:function"]
      }
    }
  }
}

Step 4: Enable continuous compliance scanning

Use the AWS Config managed rule required-tags to continuously scan for untagged resources and flag them as non-compliant.

Step 5: Create the ABAC IAM policy

This single policy works for all departments — no per-department policy is needed:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowAccessToOwnDeptResources",
      "Effect": "Allow",
      "Action": [
        "s3:GetObject", "s3:PutObject", "s3:ListBucket",
        "ec2:*", "rds:*", "lambda:*", "sagemaker:*",
        "dynamodb:*", "ecs:*", "bedrock:*"
      ],
      "Resource": "*",
      "Condition": {
        "StringEquals": {
          "aws:ResourceTag/Department": "${aws:PrincipalTag/Department}"
        }
      }
    },
    {
      "Sid": "AllowTaggingOwnDeptResources",
      "Effect": "Allow",
      "Action": [
        "ec2:CreateTags", "s3:PutObjectTagging",
        "rds:AddTagsToResource", "lambda:TagResource"
      ],
      "Resource": "*",
      "Condition": {
        "StringEquals": {
          "aws:RequestTag/Department": "${aws:PrincipalTag/Department}"
        }
      }
    },
    {
      "Sid": "AllowReadSharedResources",
      "Effect": "Allow",
      "Action": ["s3:GetObject", "s3:ListBucket"],
      "Resource": [
        "arn:aws:s3:::ai-space-shared",
        "arn:aws:s3:::ai-space-shared/*"
      ]
    }
  ]
}

Adding new teams later

No IAM policy changes are needed. The ABAC policy uses tag matching, so any new team tagged correctly gets access automatically.

StepActionTime
1Add new team value to the tag policy (for example, team-6).2 min
2Create a permission set in IAM Identity Center with session tags Department=Alpha, Team=team-6.5 min
3Assign users to the permission set.2 min
4Done — ABAC policies automatically grant access to matching resources.0 min

Option B: Separate IAM roles per department with permission boundaries

Create a dedicated IAM role per department, each with a permission boundary that limits what the role can do — even if an overly broad policy is attached:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "*",
      "Resource": "*",
      "Condition": {
        "StringEquals": {
          "aws:ResourceTag/Department": "Alpha"
        }
      }
    }
  ]
}

Pros: Hard ceiling on permissions — even if someone attaches an overly broad policy, the boundary limits them. Cons: More roles to manage (one per department versus one ABAC policy for all).

Option C: SageMaker domains per department

For ML workloads, create separate Amazon SageMaker Studio domains per department:

  • alpha-ml — Alpha users, with their own storage and execution roles.
  • beta-ml — Beta users, isolated.
  • datascience-ml — DataScience users, isolated.
  • analytics-ml — Analytics users, isolated.

Each domain has its own Amazon EFS storage, execution role, user profiles, and no cross-domain visibility.

Option D: Network isolation with subnets

Assign dedicated subnet ranges per department with security groups that prevent cross-department traffic:

SubnetCIDRSecurity Group
Alpha10.0.1.0/24Only alpha traffic
Beta10.0.2.0/24Only beta traffic
DataScience10.0.3.0/24Only datascience traffic
Analytics10.0.4.0/24Only analytics traffic
Shared services10.0.0.0/24Accessible by all (read-only)

Each department's security group only allows inbound traffic from its own subnet range and the shared services subnet.

Option E: S3 prefix-based isolation

Use a single Amazon S3 bucket with prefix-based access control:

s3://ai-space-data/
├── alpha/        → Only Dept=Alpha can read/write
├── beta/      → Only Dept=Beta can read/write
├── datascience/     → Only Dept=DataScience can read/write
├── analytics/     → Only Dept=Analytics can read/write
└── shared/          → All departments can read (not write)

Bucket policy:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "DeptIsolation",
      "Effect": "Allow",
      "Principal": "*",
      "Action": ["s3:GetObject", "s3:PutObject"],
      "Resource": "arn:aws:s3:::ai-space-data/${aws:PrincipalTag/Department}/*",
      "Condition": {
        "StringEquals": {
          "aws:PrincipalTag/Department": ["Alpha","Beta","DataScience","Analytics"]
        }
      }
    }
  ]
}

Combined recommendation — defense in depth

Use all five options together. Every layer reinforces the others:

OptionWhat It ProtectsEffortStrength
A. ABAC TagsIAM-level access controlLowHigh
B. Permission BoundariesHard ceiling per departmentMediumHigh
C. SageMaker DomainsML workspace isolationLowMedium
D. Subnet IsolationNetwork trafficMediumMedium
E. S3 Prefix IsolationData accessLowHigh

Configure auto-remediation — resource expiry after 60 days

The goal

Every resource in the AI Space sandbox must be automatically cleaned up after 60 days unless the owner explicitly extends it.

Option A: Tag-based expiry with Lambda cleanup (recommended)

Complete the following steps:

Step 1: Enforce the ExpiryDate tag on creation

Use the SCP from the boundary enforcement section to deny resource creation without an ExpiryDate tag:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "DenyWithoutExpiryDate",
      "Effect": "Deny",
      "Action": [
        "ec2:RunInstances", "s3:CreateBucket",
        "rds:CreateDBInstance", "lambda:CreateFunction",
        "sagemaker:CreateNotebookInstance",
        "dynamodb:CreateTable", "ecs:CreateService"
      ],
      "Resource": "*",
      "Condition": {
        "Null": {
          "aws:RequestTag/ExpiryDate": "true"
        }
      }
    }
  ]
}

Step 2: Deploy an auto-tagger Lambda as a fallback

If a resource is created without an ExpiryDate tag (for example, through the console where the SCP was not applied), deploy a Lambda function triggered by Amazon CloudTrail through Amazon EventBridge to auto-tag it:

import boto3
from datetime import datetime, timedelta

tagging = boto3.client('resourcegroupstaggingapi')

def lambda_handler(event, context):
    resource_arn = extract_arn_from_event(event)
    expiry = (datetime.now() + timedelta(days=60)).strftime('%Y-%m-%d')
    tagging.tag_resources(
        ResourceARNList=[resource_arn],
        Tags={'ExpiryDate': expiry}
    )
    print(f"Auto-tagged {resource_arn} with ExpiryDate={expiry}")

Step 3: Deploy a daily expiry scanner Lambda

Create a Lambda function triggered by an EventBridge scheduled rule (daily) that scans all resources for their ExpiryDate tag, warns owners 7 days before expiry, and deletes resources on the expiry date:

import boto3
from datetime import datetime, timedelta

tagging = boto3.client('resourcegroupstaggingapi')
sns = boto3.client('sns')

WARNING_TOPIC = 'arn:aws:sns:us-east-1:ACCOUNT:ai-space-expiry-warnings'
today = datetime.now().strftime('%Y-%m-%d')
warning_date = (datetime.now() + timedelta(days=7)).strftime('%Y-%m-%d')

def lambda_handler(event, context):
    paginator = tagging.get_paginator('get_resources')
    for page in paginator.paginate(TagFilters=[{'Key': 'ExpiryDate'}]):
        for resource in page['ResourceTagMappingList']:
            arn = resource['ResourceARN']
            tags = {t['Key']: t['Value'] for t in resource['Tags']}
            expiry = tags.get('ExpiryDate', '')
            owner = tags.get('Owner', 'unknown')

            if expiry <= today:
                delete_resource(arn)
                log_deletion(arn, owner, expiry)
            elif expiry <= warning_date:
                sns.publish(
                    TopicArn=WARNING_TOPIC,
                    Subject=f'Resource expiring soon: {arn}',
                    Message=f'Resource {arn} owned by {owner} expires on {expiry}. '
                            f'Update the ExpiryDate tag to extend.'
                )

Owner self-service: Resource owners can extend the expiry date at any time by updating the ExpiryDate tag value.

Option B: CloudFormation stack-based cleanup (cleanest)

If every project deploys through AWS CloudFormation, cleanup is straightforward — delete the stack and everything goes with it. CloudFormation knows resource dependencies and deletes them in the correct order automatically. No manual cleanup, no orphaned resources.

Option C: AWS Config with auto-remediation

  • Custom Config Rule — Evaluates whether a resource is older than 60 days and has a sandbox tag.
  • Auto-Remediation — An AWS Systems Manager Automation document that terminates or deletes the non-compliant resource.
  • Dashboard — The AWS Config compliance dashboard shows how many resources are approaching expiry.

This option provides enterprise-grade tracking with compliance dashboards. It requires more setup than Lambda but provides a centralized compliance view.

Option D: Service-native TTL

Use built-in expiry features where available:

ServiceFeatureHow to Set 60-Day Expiry
Amazon S3Lifecycle rulesExpiration: Days: 60
Amazon DynamoDBTTL attributeSet ttl field = creation_time + 60 days (epoch)
Amazon ECRLifecycle policysinceImagePushed: 60 days
Amazon CloudWatch LogsRetentionSet log group retention to 60 days
Amazon SageMakerAuto-stop idle notebooksLifecycleConfig

Combined auto-cleanup recommendation

  1. SCP: Deny creation without the ExpiryDate tag.
  2. CloudTrail + Lambda: Auto-tag anything that slips past.
  3. CloudFormation stacks: Deploy projects as stacks whenever possible.
  4. Daily Lambda: Scan ExpiryDate, warn at Day 53, delete at Day 60 (prefer stack deletion, with resource-level fallback).
  5. Service-native TTL: Amazon S3 lifecycle, DynamoDB TTL, Amazon ECR lifecycle.
  6. IAM Identity Center: No IAM user expiry problem — sessions expire automatically.

Find and delete resources by tag

The question

If an IAM role is tagged Department=Alpha, can you find and delete all resources associated with that tag?

Answer: Yes.

Step 1: Find all resources by tag

Method 1: AWS Resource Groups Tagging API (programmatic — recommended)

import boto3

tagging = boto3.client('resourcegroupstaggingapi')

def find_resources_by_tag(tag_key, tag_value):
    resources = []
    paginator = tagging.get_paginator('get_resources')
    for page in paginator.paginate(
        TagFilters=[{'Key': tag_key, 'Values': [tag_value]}]
    ):
        for resource in page['ResourceTagMappingList']:
            arn = resource['ResourceARN']
            parts = arn.split(':')
            service = parts[2]
            resources.append({
                'arn': arn,
                'service': service,
                'tags': {t['Key']: t['Value'] for t in resource['Tags']}
            })
    return resources

# Example usage
alpha_resources = find_resources_by_tag('Department', 'Alpha')
print(f"Found {len(alpha_resources)} resources tagged Department=Alpha")

Method 2: AWS Resource Explorer

Search tag.Department=Alpha in the Resource Explorer console.

Method 3: AWS Config advanced query

SELECT resourceId, resourceType, resourceName, tags, configuration
WHERE tags.Department = 'Alpha'

Method 4: AWS CLI

aws resourcegroupstaggingapi get-resources \
  --tag-filters Key=Department,Values=Alpha \
  --query 'ResourceTagMappingList[].ResourceARN' \
  --output table

Step 2: Delete all resources by tag

For dependency-aware deletion, use a phased approach. Delete resources in order from most dependent to least dependent:

Deletion order: Lambda → ECS → SageMaker → EC2 → RDS → DynamoDB → S3 → IAM

CloudFormation approach (cleanest):

# Find all stacks tagged with Department=Alpha
aws cloudformation describe-stacks \
  --query 'Stacks[?Tags[?Key==`Department` && Value==`Alpha`]].StackName' \
  --output text

# Delete each stack
aws cloudformation delete-stack --stack-name alpha-project-1

CloudFormation handles dependency ordering automatically — no custom deletion logic is needed.

Decision matrix

Boundary enforcement

RequirementBest OptionWhy
Lowest effort, scales to 20+ teamsABAC Tags (A)One policy for all teams, new teams auto-included
Hard security ceiling per departmentPermission Boundaries (B)Maximum effective permission cap
ML workload isolationSageMaker Domains (C)Purpose-built domain isolation
Network-level separationSubnet Isolation (D)Prevents cross-department network traffic
Data-level separationS3 Prefix Isolation (E)Fine-grained data access control
RecommendedA + B + D + E combinedDefense in depth

Auto-cleanup

RequirementBest OptionWhy
Fastest to implementService-native TTL (D)Built-in, zero custom code
Cleanest cleanup (no orphans)CloudFormation stacks (B)Dependency-aware, one command
Most flexible (any resource)Tag-based Lambda (A)Works for everything, including non-CloudFormation resources
Enterprise compliance trackingAWS Config (C)Compliance dashboard, audit trail
RecommendedA + B + D combinedCloudFormation stacks where possible, Lambda for the rest

Tag-based cleanup

RequirementBest OptionWhy
One-time departmental cleanupTagging API + ScriptQuick, targeted, scriptable
Ongoing automated cleanupLambda + Step FunctionsDependency-aware, audited
Safest (no orphans)Delete CloudFormation stacksHandles everything automatically
Nuclear optionaws-nukeFast but dangerous — use with extreme caution

(Optional) RDS schema segregation — multi-department access

When multiple departments share a single Amazon RDS for PostgreSQL instance, schema-level isolation ensures that each department can only see and interact with their own data. AWS resource tags operate at the instance level. Schema-level isolation is enforced by using PostgreSQL's built-in role and grant system combined with IAM Database Authentication.

How it works

  1. An AWS IAM Role (tagged Department=Alpha) authenticates through IAM DB Auth.
  2. A PostgreSQL User (alpha_iam) is mapped to a PostgreSQL role.
  3. A PostgreSQL Role (alpha_role) has access to only the alpha schema and read-only access to shared.
DepartmentTheir Schema (Full Access)Shared Schema (Read Only)Other Schemas
AlphaalphasharedInvisible
BetabetasharedInvisible
DataSciencedatasciencesharedInvisible
AnalyticsanalyticssharedInvisible

Step 1: Enable IAM Database Authentication

aws rds modify-db-instance \
  --db-instance-identifier ai-space-rds \
  --enable-iam-database-authentication \
  --apply-immediately

Step 2: Create schemas and roles

Run the following inside PostgreSQL:

-- Remove default public access
REVOKE ALL ON SCHEMA public FROM PUBLIC;
REVOKE CREATE ON SCHEMA public FROM PUBLIC;

-- Create department schemas
CREATE SCHEMA alpha;
CREATE SCHEMA beta;
CREATE SCHEMA datascience;
CREATE SCHEMA analytics;
CREATE SCHEMA shared;

-- Create department roles (no login — these are group roles)
CREATE ROLE alpha_role NOLOGIN;
CREATE ROLE beta_role NOLOGIN;
CREATE ROLE datascience_role NOLOGIN;
CREATE ROLE analytics_role NOLOGIN;

-- Grant each role access to ONLY their schema
GRANT USAGE, CREATE ON SCHEMA alpha TO alpha_role;
GRANT ALL ON ALL TABLES IN SCHEMA alpha TO alpha_role;
ALTER DEFAULT PRIVILEGES IN SCHEMA alpha GRANT ALL ON TABLES TO alpha_role;

-- Repeat for each department

-- Grant READ-ONLY on shared schema to all departments
GRANT USAGE ON SCHEMA shared TO alpha_role, beta_role,
  datascience_role, analytics_role;
GRANT SELECT ON ALL TABLES IN SCHEMA shared TO alpha_role,
  beta_role, datascience_role, analytics_role;
ALTER DEFAULT PRIVILEGES IN SCHEMA shared GRANT SELECT ON TABLES
  TO alpha_role, beta_role, datascience_role, analytics_role;

Step 3: Create IAM-authenticated database users

CREATE USER alpha_iam WITH LOGIN;
GRANT rds_iam TO alpha_iam;
GRANT alpha_role TO alpha_iam;
ALTER ROLE alpha_iam SET search_path = alpha, shared;

-- Repeat for each department

Step 4: Create IAM policies

Each department's IAM role gets a policy that allows connection as their specific database user only:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "rds-db:connect",
      "Resource": "arn:aws:rds-db:us-east-1:ACCOUNT_ID:dbuser:DB_RESOURCE_ID/alpha_iam"
    }
  ]
}

Note: Replace DB_RESOURCE_ID with the DbiResourceId from aws rds describe-db-instances.

Step 5: Connect to the database

# Generate IAM auth token
TOKEN=$(aws rds generate-db-auth-token \
  --hostname ai-space-rds.<hashid>.us-east-1.rds.amazonaws.com \
  --port 5432 \
  --username alpha_iam \
  --region us-east-1)

# Connect with the token as the password
psql "host=ai-space-rds.<hashid>.us-east-1.rds.amazonaws.com \
  port=5432 dbname=aispace \
  user=alpha_iam password=$TOKEN sslmode=require"

Adding new departments

No changes to existing schemas, roles, or IAM policies are needed. The following steps take approximately 5 minutes:

StepActionTime
1CREATE SCHEMA newdept;1 min
2CREATE ROLE newdept_role NOLOGIN;1 min
3GRANT USAGE, CREATE ON SCHEMA newdept TO newdept_role;1 min
4CREATE USER newdept_iam WITH LOGIN; GRANT rds_iam, newdept_role TO newdept_iam;1 min
5Add IAM policy for rds-db:connect to the new DB user.2 min

Key points

  • AWS tags control who can access the RDS instance (the AWS resource).
  • PostgreSQL grants control who can access which schema (the data inside).
  • IAM DB Auth bridges the two — mapping AWS identity to database identity.
  • Schemas are invisible to unauthorized departments, not just read-protected.
  • The shared schema provides a place for cross-department reference data (read-only).

Clean up

If you no longer require this governance setup in your AI Space account, complete the following steps to remove the components:

  1. Delete the expiry scanner and auto-tagger Lambda functions.
  2. Remove the associated EventBridge rules.
  3. Delete the SNS topic for expiry warnings.
  4. Remove the SCPs and tag policies from AWS Organizations.
  5. Remove the ABAC IAM policies and permission boundaries.
  6. (If applicable) Drop the PostgreSQL schemas, roles, and IAM database users.

Conclusion

Shared AI development environments do not require 20 separate AWS accounts to achieve department-level isolation. This article walked through a defense-in-depth governance model that uses ABAC tags as the foundation, layered with permission boundaries, SageMaker domain isolation, network segmentation, and S3 prefix-based access control.

The auto-cleanup mechanisms — SCP-enforced expiry tags, fallback auto-tagging, and a daily scanner Lambda — ensure sandbox resources do not accumulate indefinitely. And the tag-based discovery and deletion workflows provide on-demand control when a department's resources need to be located or removed.

To get started, implement the ABAC tag strategy (Option A) and the ExpiryDate SCP first — these two components provide the highest governance value with the lowest effort. Then layer additional controls as your organization's security requirements demand.

For more information about the services used in this article, see the following resources:

`