Integration & Automation

Best practices for creating IaC for AWS GovCloud (US)

In this blog post, we present best practices for AWS GovCloud (US) DevOps teams to consider as they work to maintain a secure infrastructure and adhere to compliance guidelines. We also provide code examples, including how to create Terraform modules for multi-partition environments.

Overview

DevOps teams who manage AWS GovCloud (US) environments often face challenges related to strict security and compliance requirements, especially when those teams use Infrastructure as Code (IaC) methods to provision applications and updates. IaC is crucial for managing cloud resources in a consistent, repeatable, and automated manner.

AWS GovCloud (US) customers such as government agencies and organizations that work with sensitive data and regulated workloads typically operate in an isolated environment for security reasons. This isolation can contribute to the challenges that DevOps teams face as they rework code, fork codebases, and deploy workloads using IaC.

One challenge involves the variations in Amazon Resource Numbers (ARNs) between AWS GovCloud (US) and commercial cloud partitions. The ARNs for AWS services and deployed resources require manual updates. For example, the arn:aws:service:region:account-id:resource-type:resource-id string must be updated to
arn:aws-us-gov:service:region:account-id:resource-type:resource-id.

Multi-partition environments can be problematic for AWS GovCloud (US) teams. Although teams typically use dynamic or region-aware code blocks to manage multi-region deployments, few of these teams use this technique for multi-partition deployments.

Understanding compliance requirements

Before diving into the technical aspects of creating IaC for AWS GovCloud (US), understand the following compliance requirements.

Depending on the nature of your workloads and data, you may need to consider additional compliance requirements. For example, if you are handling law enforcement data, you should comply with the Criminal Justice Information Services (CJIS) standards. If you are dealing with healthcare data, you should adhere to the Health Insurance Portability and Accountability Act (HIPAA) regulations.

AWS GovCloud (US) eligibility

For entities and persons based in the U.S, access to AWS GovCloud (US) is restricted to federal agencies, state and local governments, educational institutions, and commercial organizations that meet specific requirements. Due to these requirements and eligibility restrictions, a separate AWS GovCloud (US) account is required. Before signing up for an account, confirm that your organization qualifies. For details, see AWS GovCloud (US) Sign Up.

Networking and VPC configuration

One of the first steps in setting up your GovCloud environment is creating a Virtual Private Cloud (VPC) tailored to your specific needs. Carefully configure subnets, route tables, and create security groups to ensure proper network segmentation and access control.

For enhanced security and performance, consider using AWS Direct Connect or AWS Site-to-Site VPN to establish a dedicated network connection between your on-premises infrastructure and AWS GovCloud (US) environment.

Securing your AWS GovCloud (US) infrastructure

Secure your AWS GovCloud (US) infrastructure using AWS Identity and Access Management (IAM) policies and AWS services that are designed to help you maintain security.

IAM policies

Define and enforce IAM policies to control access to your AWS GovCloud (US) resources. Follow the principle of least privilege and regularly review and update your policies to maintain a secure posture. For an additional layer of security, implement multi-factor authentication (MFA) to require users to provide a second form of authentication in addition to their passwords.

If you need to grant access to resources across multiple AWS accounts, you can set up cross-account roles and permissions. This maintains the principle of least privilege and ensures that access is granted only to the necessary resources.

Security controls

Use the following AWS services to help you maintain security:

Also consider configuring security groups and network access control lists (NACLs) to control inbound and outbound traffic to your resources. This will allow only necessary traffic while blocking unauthorized access.

Data management and disaster recovery

To help you manage and store data, take these actions:

  • Configure Amazon Simple Storage Service (S3) buckets with appropriate policies, versioning, and logging to store and manage your data securely.
  • Encrypt Amazon Elastic Block Store (EBS) volumes to protect your data at rest and take regular snapshots for backup and recovery purposes.
  • Implement AWS Backup or other backup solutions to automate backups and enable data recovery in case of data loss or corruption.

Disaster recovery and availability

To ensure high availability and disaster recovery capabilities, consider deploying your workloads across multiple AWS GovCloud (US) regions. Also, define and implement Recovery Time Objectives (RTO) and Recovery Point Objectives (RPO) for your critical workloads to ensure that you can recover from disruptions within acceptable timeframes and with minimal data loss.

Cost management

For budgeting and cost allocation, use AWS Cost Explorer and set up billing alerts to monitor and manage costs effectively. Implement cost allocation tags to track and attribute costs to specific projects or departments.

For long-term workloads with predictable usage patterns, consider purchasing Amazon Elastic Compute Cloud (Amazon EC2) Reserved Instances to benefit from significant cost savings compared to on-demand pricing. Also consider Compute and EC2 Instance Savings Plans for flexible pricing models.

Service-specific considerations

Availability of AWS services may differ across AWS Regions, so verify which services are available in your AWS GovCloud (US) Region. Plan your architecture accordingly and be prepared to use alternative services or solutions if necessary. Also, if you plan to use third-party solutions or services from AWS Marketplace, confirm that they’re compatible with and supported in the AWS GovCloud (US) environment.

Example code

See the following IaC examples for the AWS GovCloud (US).

Terraform

This code snippet provisions an Amazon EC2 instance for AWS GovCloud (US) in the US-West Region. It specifies the Amazon Machine Image (AMI) ID via a variable using the t3.micro instance type. The instance that’s created is tagged with the name HelloGovCloud for easy identification.

resource "aws_instance" "web" {
provider      = aws.us-gov-west-1
ami           = var.ami_id
instance_type = "t3.micro"

tags = {
Name = "HelloGovCloud"
}
}

The following configuration defines an IAM role named DynamoDB_IAM_Role with permissions to list and describe all Amazon DynamoDB tables within the current AWS account and specified Region.

data "aws_caller_identity" "current" {}

data "aws_partition" "current" {}

resource "aws_iam_role" "dynamoDB_role" {
  name = "DynamoDB_IAM_Role"
  assume_role_policy = jsonencode({
    "Version" : "2012-10-17",
    "Statement" : [
      {
        "Effect" : "Allow",
        "Action" : [
          "dynamodb:ListTables"
        ],
        "Resource" : "*"
      },
      {
        "Effect" : "Allow",
        "Action" : [
          "dynamodb:DescribeTable"
        ],
        "Resource" : "arn:${data.aws_partition.current.partition}:dynamodb:${var.region}:${data.aws_caller_identity.current.account_id}:table/*"
      }
    ]
  })

  tags = {
    tag-key = "tag-value"
  }
}

The following code snippet configures two AWS providers, one for the us-gov-east-1 region and another for the us-gov-west-1 region. The us-gov-west-1 provider is assigned the alias us-gov-west-1. Using this configuration, you can manage resources in both regions within the same Terraform project.

provider "aws" {
  region = "us-gov-east-1"
}

provider "aws" {
  region = "us-gov-west-1"
  alias  = "us-gov-west-1"
}

The following code sample defines two variables:

  • ami_id—a string representing the AMI ID used to create an EC2 instance.
  • region—a string that specifies the AWS GovCloud (US) Region for deployment with a default value us-gov-west-1.
variable "ami_id" {
  type        = string
  description = "AMI ID to create Ec2 Instance"
}

variable "region" {
  type        = string
  description = "GovCloud Region to deploy"
  default     = "us-gov-west-1"
}

CloudFormation

The following CloudFormation template creates an IAM role with permissions for an AWS Lambda function to assume the role and an IAM policy granting Amazon DynamoDB access to specific resources in the current AWS account and region. The policy is attached to the IAM role.

Resources:
  Role1ABCC5F0:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
          - Action: sts:AssumeRole
            Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
        Version: "2012-10-17"
  RoleDefaultPolicy5FFB7DAB:
    Type: AWS::IAM::Policy
    Properties:
      PolicyDocument:
        Statement:
          - Action: dynamodb:*
            Effect: Allow
            Resource:
              - Fn::Join:
                  - ""
                  - - "arn:"
                    - Ref: AWS::Partition
                    - ":dynamodb:"
                    - Ref: AWS::Region
                    - ":"
                    - Ref: AWS::AccountId
                    - :table/src-orchestratorEksMetadata
              - Fn::Join:
                  - ""
                  - - "arn:"
                    - Ref: AWS::Partition
                    - ":dynamodb:"
                    - Ref: AWS::Region
                    - ":"
                    - Ref: AWS::AccountId
                    - :table/src-orchestratorEksMetadata/index/*
              - Fn::Join:
                  - ""
                  - - "arn:"
                    - Ref: AWS::Partition
                    - ":dynamodb:"
                    - Ref: AWS::Region
                    - ":"
                    - Ref: AWS::AccountId
                    - :table/src-orchestratorEksMetadata/stream/*
        Version: "2012-10-17"
      PolicyName: RoleDefaultPolicy5FFB7DAB
      Roles:
        - Ref: Role1ABCC5F0

AWS CDK

The following AWS Cloud Development Kit (AWS CDK) code snippet defines a stack that creates an IAM role with permissions for a Lambda function to access specific DynamoDB resources within the current AWS account and region. The role’s policy statements dynamically build ARNs using the partition, region, and account from the stack context.

import { Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { Role, ServicePrincipal, PolicyStatement, Effect } from 'aws-cdk-lib/aws-iam';

export class PartitionIndependentArnStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    const partition = this.partition
    /**
     *  If we are using inside L3 contruct we can access partition to build the dynamic ARN from following way 
     *  Stack.of(this).partition
     */
    const account = Stack.of(this).account
    const region = Stack.of(this).region
    const policyStatement = new PolicyStatement({
      effect: Effect.ALLOW,
      actions: [
        "dynamodb:*",
      ],
      resources: [
        `arn:${partition}:dynamodb:${region}:${account}:table/src-orchestratorEksMetadata`,
        `arn:${partition}:dynamodb:${region}:${account}:table/src-orchestratorEksMetadata/index/*`,
        `arn:${partition}:dynamodb:${region}:${account}:table/src-orchestratorEksMetadata/stream/*`
      ]
    });
    const role = new Role(this, 'Role', {
      assumedBy: new ServicePrincipal('lambda.amazonaws.com'),
    });
    role.addToPolicy(policyStatement)

  }
}

More security best practices

We also recommend these additional security best practices to maintain optimal security.

Enable WAF

You can use AWS WAF, a web application firewall, to observe web requests that are sent to an Application Load Balancer or Amazon API Gateway. AWS WAF also lets you apply criteria to restrict or approve requests depending on the source IP addresses or the values they include.

Enable Security Hub

AWS Security Hub helps you evaluate your AWS environment compared to security industry standards and best practices, giving you a full view of your security status in AWS. Security Hub also helps you examine your security patterns and pinpoint the most important security risks by gathering security data from all of your AWS accounts, services, and approved third-party products.

Designed to help you manage the security posture of your company, Security Hub supports a number of external compliance framework security standards from various sources, including:

Enable IAM authentication for database instance

Use IAM database authentication to authenticate with and connect to your database instance without entering a password. IAM database authentication is compatible with PostgreSQL, MariaDB, and MySQL. As an alternative, you can use an authentication token.

Use FIPS endpoints

Organizations that must adhere to stringent security and compliance standards can use Federal Information Processing Standard (FIPS) endpoints, particularly when handling sensitive data or operating in regulated sectors. FIPS endpoints offer a high degree of confidence that the cryptographic techniques employed are safe, dependable, and in-line with national regulations.

Conclusion

Congratulations. You’ve learned some important best practices for helping you meet strict security and compliance requirements in your AWS GovCloud (US) environment. We hope you can apply these recommendations to your IaC methodology so you can manage your cloud resources consistently in an automated fashion.

If you have feedback about this article, use the Comments section.

About the authors

Aniket DekateAniket Dekate is an AWS Cloud DevOps Consultant who specializes in cloud infrastructure, automation, containerization and CI/CD. He has extensive experience in building secure, scalable and highly available cloud-native architectures. He has a deep understanding & expertise in designing and implementing cutting-edge cloud solutions using DevOps methodologies. Outside of work, he enjoys playing cricket, badminton and table tennis.

Aarti RajputAarti Rajput is an experienced AWS Lead DevOps Consultant, specializing in designing, implementing, and managing robust and scalable cloud-native architectures. She excels in using cutting-edge DevOps methodologies to streamline operations, enhance security, and ensure the high availability of mission-critical systems. Outside of work, she enjoys traveling the globe and exploring diverse cuisines.

Sandeep GawandeSandeep Gawande is an AWS Senior Lead Consultant. He specializes in cloud infrastructure, automation, containerization, cloud-native architectures, and generative AI applications. With a background in development and product engineering, he focuses on building resilient, scalable, and reliable cloud-native architectures, particularly in the telecom, finance, and security domains. Outside of work, he enjoys hiking, riding bicycles, and spending time with his family.