Skip to content

AWS Provider

Use the Amazon Web Services (AWS) provider to interact with the many resources supported by AWS. You must configure the provider with the proper credentials before you can use it.

Use the navigation to the left to read about the available resources.

To learn the basics of Terraform using this provider, follow the hands-on get started tutorials. Interact with AWS services, including Lambda, RDS, and IAM by following the AWS services tutorials.

Example Usage

Terraform 0.13 and later:

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
new aws.provider.AwsProvider(this, "aws", {
  region: "us-east-1",
});
new aws.vpc.Vpc(this, "example", {
  cidrBlock: "10.0.0.0/16",
});

Terraform 0.12 and earlier:

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
new aws.provider.AwsProvider(this, "aws", {
  region: "us-east-1",
});
new aws.vpc.Vpc(this, "example", {
  cidrBlock: "10.0.0.0/16",
});

Authentication and Configuration

Configuration for the AWS Provider can be derived from several sources, which are applied in the following order:

  1. Parameters in the provider configuration
  2. Environment variables
  3. Shared credentials files
  4. Shared configuration files
  5. Container credentials
  6. Instance profile credentials and region

This order matches the precedence used by the AWS CLI and the AWS SDKs.

The AWS Provider supports assuming an IAM role, either in the provider configuration block parameter assumeRole or in a named profile.

The AWS Provider supports assuming an IAM role using web identity federation and OpenID Connect (OIDC). This can be configured either using environment variables or in a named profile.

When using a named profile, the AWS Provider also supports sourcing credentials from an external process.

Provider Configuration

!> Warning: Hard-coded credentials are not recommended in any Terraform configuration and risks secret leakage should this file ever be committed to a public version control system.

Credentials can be provided by adding an accessKey, secretKey, and optionally token, to the aws provider block.

Usage:

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
new aws.provider.AwsProvider(this, "aws", {
  accessKey: "my-access-key",
  region: "us-west-2",
  secretKey: "my-secret-key",
});

Other settings related to authorization can be configured, such as:

  • profile
  • sharedConfigFiles
  • sharedCredentialsFiles

Environment Variables

Credentials can be provided by using the AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and optionally AWS_SESSION_TOKEN environment variables. The region can be set using the AWS_REGION or AWS_DEFAULT_REGION environment variables.

For example:

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
new aws.provider.AwsProvider(this, "aws", {});
$ export AWS_ACCESS_KEY_ID="anaccesskey"
$ export AWS_SECRET_ACCESS_KEY="asecretkey"
$ export AWS_REGION="us-west-2"
$ terraform plan

Other environment variables related to authorization are:

  • AWS_PROFILE
  • AWS_CONFIG_FILE
  • AWS_SHARED_CREDENTIALS_FILE

Shared Configuration and Credentials Files

The AWS Provider can source credentials and other settings from the shared configuration and credentials files. By default, these files are located at $home/Aws/config and $home/Aws/credentials on Linux and macOS, and "%userprofile%\Aws\config" and "%userprofile%\Aws\credentials" on Windows.

If no named profile is specified, the default profile is used. Use the profile parameter or AWS_PROFILE environment variable to specify a named profile.

The locations of the shared configuration and credentials files can be configured using either the parameters sharedConfigFiles and sharedCredentialsFiles or the environment variables AWS_CONFIG_FILE and AWS_SHARED_CREDENTIALS_FILE.

For example:

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
new aws.provider.AwsProvider(this, "aws", {
  profile: "customprofile",
  sharedConfigFiles: ["/Users/tf_user/.aws/conf"],
  sharedCredentialsFiles: ["/Users/tf_user/.aws/creds"],
});

Container Credentials

If you're running Terraform on CodeBuild or ECS and have configured an IAM Task Role, Terraform can use the container's Task Role. This support is based on the underlying AWS_CONTAINER_CREDENTIALS_RELATIVE_URI and AWS_CONTAINER_CREDENTIALS_FULL_URI environment variables being automatically set by those services or manually for advanced usage.

If you're running Terraform on EKS and have configured IAM Roles for Service Accounts (IRSA), Terraform can use the pod's role. This support is based on the underlying AWS_ROLE_ARN and AWS_WEB_IDENTITY_TOKEN_FILE environment variables being automatically set by Kubernetes or manually for advanced usage.

Instance profile credentials and region

When the AWS Provider is running on an EC2 instance with an IAM Instance Profile set, the provider can source credentials from the EC2 Instance Metadata Service. Both IMDS v1 and IMDS v2 are supported.

A custom endpoint for the metadata service can be provided using the ec2MetadataServiceEndpoint parameter or the AWS_EC2_METADATA_SERVICE_ENDPOINT environment variable.

Assuming an IAM Role

If provided with a role ARN, the AWS Provider will attempt to assume this role using the supplied credentials.

Usage:

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
new aws.provider.AwsProvider(this, "aws", {
  assumeRole: [
    {
      externalId: "EXTERNAL_ID",
      roleArn: "arn:aws:iam::123456789012:role/ROLE_NAME",
      sessionName: "SESSION_NAME",
    },
  ],
});

Hands-on: Try the Use AssumeRole to Provision AWS Resources Across Accounts tutorial.

Assuming an IAM Role Using A Web Identity

If provided with a role ARN and a token from a web identity provider, the AWS Provider will attempt to assume this role using the supplied credentials.

Usage:

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
new aws.provider.AwsProvider(this, "aws", {
  assumeRoleWithWebIdentity: [
    {
      roleArn: "arn:aws:iam::123456789012:role/ROLE_NAME",
      sessionName: "SESSION_NAME",
      webIdentityTokenFile: "/Users/tf_user/secrets/web-identity-token",
    },
  ],
});

Using an External Credentials Process

To use an external process to source credentials, the process must be configured in a named profile, including the default profile. The profile is configured in a shared configuration file.

For example:

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
new aws.provider.AwsProvider(this, "aws", {
  profile: "customprofile",
});
[profile customprofile]
credential_process = custom-process --username jdoe

AWS Configuration Reference

Setting Provider Environment Variable Shared Config
Access Key ID accessKey AWS_ACCESS_KEY_ID awsAccessKeyId
Secret Access Key secretKey AWS_SECRET_ACCESS_KEY awsSecretAccessKey
Session Token token AWS_SESSION_TOKEN awsSessionToken
Region region AWS_REGION or AWS_DEFAULT_REGION region
Custom CA Bundle customCaBundle AWS_CA_BUNDLE caBundle
EC2 IMDS Endpoint ec2MetadataServiceEndpoint AWS_EC2_METADATA_SERVICE_ENDPOINT N/A
EC2 IMDS Endpoint Mode ec2MetadataServiceEndpointMode AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE N/A
Disable EC2 IMDS skipMetadataApiCheck AWS_EC2_METADATA_DISABLED N/A
HTTP Proxy httpProxy HTTP_PROXY or HTTPS_PROXY N/A
Max Retries maxRetries AWS_MAX_ATTEMPTS maxAttempts
Profile profile AWS_PROFILE or AWS_DEFAULT_PROFILE N/A
Shared Config Files sharedConfigFiles AWS_CONFIG_FILE N/A
Shared Credentials Files sharedCredentialsFiles or sharedCredentialsFile AWS_SHARED_CREDENTIALS_FILE N/A
Use DualStack Endpoints useDualstackEndpoint AWS_USE_DUALSTACK_ENDPOINT useDualstackEndpoint
Use FIPS Endpoints useFipsEndpoint AWS_USE_FIPS_ENDPOINT useFipsEndpoint

Assume Role Configuration Reference

Configuation for assuming an IAM role can be done using provider configuration or a named profile in shared configuration files. In the provider, all parameters for assuming an IAM role are set in the assumeRole block.

See the assume role documentation for more information.

Setting Provider Environment Variable Shared Config
Role ARN roleArn AWS_ROLE_ARN roleArn
Duration duration or durationSeconds N/A durationSeconds
External ID externalId N/A externalId
Policy policy N/A N/A
Policy ARNs policyArns N/A N/A
Session Name sessionName AWS_ROLE_SESSION_NAME roleSessionName
Source Identity sourceIdentity N/A N/A
Tags tags N/A N/A
Transitive Tag Keys transitiveTagKeys N/A N/A

Assume Role with Web Identity Configuration Reference

Configuration for assuming an IAM role using web identify federation can be done using provider configuration, environment variables, or a named profile in shared configuration files. In the provider, all parameters for assuming an IAM role are set in the assumeRoleWithWebIdentity block.

See the assume role documentation section on web identities for more information.

Setting Provider Environment Variable Shared Config
Role ARN roleArn AWS_ROLE_ARN roleArn
Web Identity Token webIdentityToken N/A N/A
Web Identity Token File webIdentityTokenFile AWS_WEB_IDENTITY_TOKEN_FILE webIdentityTokenFile
Duration duration N/A durationSeconds
Policy policy N/A policy
Policy ARNs policyArns N/A policyArns
Session Name sessionName AWS_ROLE_SESSION_NAME roleSessionName

Custom User-Agent Information

By default, the underlying AWS client used by the Terraform AWS Provider creates requests with User-Agent headers including information about Terraform and AWS SDK for Go versions. To provide additional information in the User-Agent headers, the TF_APPEND_USER_AGENT environment variable can be set and its value will be directly added to HTTP requests. E.g.,

$ export TF_APPEND_USER_AGENT="JenkinsAgent/i-12345678 BuildID/1234 (Optional Extra Information)"

Argument Reference

In addition to generic provider arguments (e.g., alias and version), the following arguments are supported in the AWS provider block:

assume_role Configuration Block

The assumeRole configuration block supports the following arguments:

  • duration - (Optional, Conflicts with durationSeconds) Duration of the assume role session. You can provide a value from 15 minutes up to the maximum session duration setting for the role. Represented by a string such as 1H, 2H45M, or 30M15S.
  • durationSeconds - (Optional, Deprecated use duration instead) Number of seconds to restrict the assume role session duration. You can provide a value from 900 seconds (15 minutes) up to the maximum session duration setting for the role.
  • externalId - (Optional) External identifier to use when assuming the role.
  • policy - (Optional) IAM Policy JSON describing further restricting permissions for the IAM Role being assumed.
  • policyArns - (Optional) Set of Amazon Resource Names (ARNs) of IAM Policies describing further restricting permissions for the IAM Role being assumed.
  • roleArn - (Required) ARN of the IAM Role to assume.
  • sessionName - (Optional) Session name to use when assuming the role.
  • sourceIdentity - (Optional) Source identity specified by the principal assuming the role.
  • tags - (Optional) Map of assume role session tags.
  • transitiveTagKeys - (Optional) Set of assume role session tag keys to pass to any subsequent sessions.

assume_role_with_web_identity Configuration Block

The assumeRoleWithWebIdentity configuration block supports the following arguments:

  • duration - (Optional) Duration of the assume role session. You can provide a value from 15 minutes up to the maximum session duration setting for the role. Represented by a string such as 1H, 2H45M, or 30M15S.
  • policy - (Optional) IAM Policy JSON describing further restricting permissions for the IAM Role being assumed.
  • policyArns - (Optional) Set of Amazon Resource Names (ARNs) of IAM Policies describing further restricting permissions for the IAM Role being assumed.
  • roleArn - (Required) ARN of the IAM Role to assume. Can also be set with the AWS_ROLE_ARN environment variable.
  • sessionName - (Optional) Session name to use when assuming the role. Can also be set with the AWS_ROLE_SESSION_NAME environment variable.
  • webIdentityToken - (Optional) Value of a web identity token from an OpenID Connect (OIDC) or OAuth provider. One of webIdentityToken or webIdentityTokenFile is required.
  • webIdentityTokenFile - (Optional) File containing a web identity token from an OpenID Connect (OIDC) or OAuth provider. One of webIdentityTokenFile or webIdentityToken is required. Can also be set with the AWS_WEB_IDENTITY_TOKEN_FILE environment variable.

default_tags Configuration Block

Hands-on: Try the Configure Default Tags for AWS Resources tutorial.

Example: Resource with provider default tags

import * as cdktf from "cdktf";
/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
new aws.provider.AwsProvider(this, "aws", {
  defaultTags: [
    {
      tags: {
        environment: "Test",
        name: "Provider Tag",
      },
    },
  ],
});
const awsVpcExample = new aws.vpc.Vpc(this, "example", {});
new cdktf.TerraformOutput(this, "vpc_all_tags", {
  value: awsVpcExample.tagsAll,
});
new cdktf.TerraformOutput(this, "vpc_resource_level_tags", {
  value: awsVpcExample.tags,
});

Outputs:

$ terraform apply
...
Outputs:

vpc_all_tags = tomap({
  "Environment" = "Test"
  "Name" = "Provider Tag"
})

Example: Resource with tags and provider default tags

import * as cdktf from "cdktf";
/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
new aws.provider.AwsProvider(this, "aws", {
  defaultTags: [
    {
      tags: {
        environment: "Test",
        name: "Provider Tag",
      },
    },
  ],
});
const awsVpcExample = new aws.vpc.Vpc(this, "example", {
  tags: {
    Owner: "example",
  },
});
new cdktf.TerraformOutput(this, "vpc_all_tags", {
  value: awsVpcExample.tagsAll,
});
new cdktf.TerraformOutput(this, "vpc_resource_level_tags", {
  value: awsVpcExample.tags,
});

Outputs:

$ terraform apply
...
Outputs:

vpc_all_tags = tomap({
  "Environment" = "Test"
  "Name" = "Provider Tag"
  "Owner" = "example"
})
vpc_resource_level_tags = tomap({
  "Owner" = "example"
})

Example: Resource overriding provider default tags

import * as cdktf from "cdktf";
/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
new aws.provider.AwsProvider(this, "aws", {
  defaultTags: [
    {
      tags: {
        environment: "Test",
        name: "Provider Tag",
      },
    },
  ],
});
const awsVpcExample = new aws.vpc.Vpc(this, "example", {
  tags: {
    Environment: "Production",
  },
});
new cdktf.TerraformOutput(this, "vpc_all_tags", {
  value: awsVpcExample.tagsAll,
});
new cdktf.TerraformOutput(this, "vpc_resource_level_tags", {
  value: awsVpcExample.tags,
});

Outputs:

$ terraform apply
...
Outputs:

vpc_all_tags = tomap({
  "Environment" = "Production"
  "Name" = "Provider Tag"
})
vpc_resource_level_tags = tomap({
  "Environment" = "Production"
})

The defaultTags configuration block supports the following argument:

  • tags - (Optional) Key-value map of tags to apply to all resources.

ignore_tags Configuration Block

Example:

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
new aws.provider.AwsProvider(this, "aws", {
  ignoreTags: [
    {
      keys: ["TagKey1"],
    },
  ],
});

The ignoreTags configuration block supports the following arguments:

  • keys - (Optional) List of exact resource tag keys to ignore across all resources handled by this provider. This configuration prevents Terraform from returning the tag in any tags attributes and displaying any configuration difference for the tag value. If any resource configuration still has this tag key configured in the tags argument, it will display a perpetual difference until the tag is removed from the argument or ignoreChanges is also used.
  • keyPrefixes - (Optional) List of resource tag key prefixes to ignore across all resources handled by this provider. This configuration prevents Terraform from returning any tag key matching the prefixes in any tags attributes and displaying any configuration difference for those tag values. If any resource configuration still has a tag matching one of the prefixes configured in the tags argument, it will display a perpetual difference until the tag is removed from the argument or ignoreChanges is also used.

Getting the Account ID

If you use either allowedAccountIds or forbiddenAccountIds, Terraform uses several approaches to get the actual account ID in order to compare it with allowed or forbidden IDs.

Approaches differ per authentication providers:

  • EC2 instance w/ IAM Instance Profile - Metadata API is always used. Introduced in Terraform 0616.
  • All other providers (environment variable, shared credentials file, ...) will try three approaches in the following order
  • iam:getUser - Typically useful for IAM Users. It also means that each user needs to be privileged to call iam:getUser for themselves.
  • sts:getCallerIdentity - Should work for both IAM Users and federated IAM Roles, introduced in Terraform 0616.
  • iam:listRoles - This is specifically useful for IdP-federated profiles which cannot use iam:getUser. It also means that each federated user need to be assuming an IAM role which allows iam:listRoles. Used in Terraform 0616+. There used to be no better way to get account ID out of the API when using the federated account until sts:getCallerIdentity was introduced.