All Products
Search
Document Center

Terraform:Terraform identity authentication

Last Updated:Jan 07, 2026

The Alibaba Cloud Terraform Provider supports multiple authentication methods. The appropriate method depends on your Terraform runtime environment and scenario.

Authentication method priority

When you configure the Alibaba Cloud provider, you typically select only one authentication method. The Terraform Provider searches for identity credentials in the following order and stops as soon as it finds a valid credential:

  1. Static configuration: The provider first reads the access_key, secret_key, security_token, or ecs_role_name parameters if they are explicitly specified in the provider block.

  2. Environment variables: If no static configuration is found, the provider reads system environment variables, such as ALICLOUD_ACCESS_KEY and ALICLOUD_SECRET_KEY.

  3. Shared configuration file:

    1. Static configuration: The provider reads authentication information for the specified profile from the local shared configuration file. This information can include an AccessKey pair, ram_role_arn, ram_role_name, or sts_token.

    2. Advanced configuration: If the shared configuration file does not contain a static configuration but is configured with CloudSSO, OAuth, an external program, or a chainable RAM role (ChainableRamRoleArn), the provider invokes the corresponding plugin to obtain a temporary Security Token Service (STS) credential.

  4. URL credential: If none of the above methods provide a credential, the provider attempts to retrieve credentials from the URL specified by credentials_uri.

Security recommendations

For enhanced security in production environments, use the following authentication methods that rely on temporary credentials:

  • Instance RAM role for ECS

  • RAM role assumption (AssumeRole)

  • OIDC IdP role assumption

These methods provide the following security advantages:

  • Avoid hard coding or exposing long-lived AccessKeys in your configuration to reduce the risk of key compromise.

  • They limit the duration of permissions using credentials with fixed expiration periods.

Support for fine-grained authorization

For fine-grained control over resource access based on dimensions such as applications, teams, or projects, use RAM role assumption and OIDC IdP role assumption. You can attach dedicated roles and access policies to different Terraform workloads to follow the least privilege principle.

Terraform authentication methods

The Alibaba Cloud Terraform Provider offers the following authentication methods:

Authentication method

Instructions

Use Cases

Static configuration

(access_key)

Defines an AccessKey (AK) in plaintext in the configuration file, or passes it as a parameter.

  • Testing and verification in development environments.

  • CI/CD resource management workflows.

Environment variables

(ALIBABA_CLOUD_ACCESS_KEY)

Reads AccessKey (AK) information from environment variables.

  • Testing and verification in development environments.

  • Standalone runtime environments, such as ECS instances.

Instance RAM role for ECS

(ecs_role_name)

Obtains the access credential for the attached RAM role from the metadata of an ECS instance.

Terraform runs on an ECS instance.

OIDC role assumption (assume_role_with_oidc)

Obtains an access credential by assuming a role through OpenID Connect (OIDC).

Terraform runs in a Kubernetes cluster that supports OIDC, such as Alibaba Cloud ACK.

Role assumption

(assume_role)

Obtains an access credential by assuming a RAM role.

  • Multi-account resource management.

  • CI/CD resource management workflows.

URL credential

(credentials_uri)

Specifies a URI to obtain a temporary credential.

Obtaining credentials from a custom credential service, such as an API or a file.

Shared configuration file

(profile)

Configures multiple authentication methods in a unified file using the Alibaba Cloud command-line interface (CLI). Obtains an access credential by specifying a profile name. The supported authentication methods include the following:

  • AK

  • STSToken

  • ECSRamRole

  • CloudSSO

  • ChainableRamRoleArn

  • External

  • OAuth

  • Multi-account and multi-region resource management.

  • Multi-environment resource management.

Static configuration

Static configuration refers to defining access credentials directly in the provider block of a Terraform configuration file.

Parameters

Parameter

Description

Example value

access_key

The AccessKey ID.

abcd*******

secret_key

The AccessKey secret.

abcd*******

security_token (Optional)

The security token of a temporary STS credential.

abcd*******

provider "alicloud" {
  access_key = "<Your AccessKey ID>"
  secret_key = "<Your AccessKey secret>"
  # If you use an STS credential, configure security_token.
  # security_token = "<Your STS token>"
}

Example configuration

For enhanced security, you can pass access credentials as variables instead of hard-coding them in plaintext in the configuration file. Do not set default values for the variables:

variable "access_key_id" {
  description = "The AccessKey ID for operating your infrastructure"
}
variable "access_key_secret" {
  description = "The AccessKey Secret for operating your infrastructure"
}
variable "security_token" {
  description = "The Security Token for operating your infrastructure"
}
provider "alicloud" {
  access_key = var.access_key_id
  secret_key = var.access_key_secret
  # If you use an STS credential, configure security_token.
  # security_token = var.security_token
}

When you run the terraform command, you can use the -var option to pass variable values:

$ terraform plan -var access_key_id="<Your AccessKey ID>" -var access_key_secret="<Your AccessKey secret>" -var security_token="<Your STS token>"

Environment variables

You can store access credentials in environment variables. If credentials are not statically configured in the configuration file, Terraform reads them from the specified environment variables.

Parameters

Parameter

Description

Example value

ALICLOUD_ACCESS_KEY

The AccessKey ID.

abcd*******

ALICLOUD_SECRET_KEY

The AccessKey secret.

abcd*******

ALICLOUD_SECURITY_TOKEN (Optional)

The security token of a temporary STS credential.

abcd*******

Example configuration

Linux/macOS
Note

Temporary environment variables configured with the export command are valid only for the current shell session. For long-term retention, you can add the export command to the shell's startup configuration file, such as .bash_profile or .zshrc.

# AccessKey ID
$ export ALICLOUD_ACCESS_KEY="<Your AccessKey ID>"
# AccessKey Secret
$ export ALICLOUD_SECRET_KEY="<Your AccessKey secret>"
# If you use an STS credential, configure security_token.
$ export ALICLOUD_SECURITY_TOKEN="<Your STS token>"
Windows
  1. Right-click This PC on your desktop and select Properties > Advanced system settings > Environment Variables.

  2. Under System variables or User variables, click New to create the following environment variables: ALICLOUD_ACCESS_KEY, ALICLOUD_SECRET_KEY, and ALICLOUD_SECURITY_TOKEN (optional).

After you set the environment variables, you do not need to declare credentials in the provider block. You can declare other information, such as the region:

provider "alicloud" {
  region = "cn-hangzhou"
}

You can also configure the region using the ALICLOUD_REGION environment variable. If you do not specify a region in the provider block or an environment variable, cn-beijing is used by default.

Compared to static configuration, using environment variables is more convenient and secure.

Instance RAM role for ECS

When Terraform runs on an ECS instance, you can use an instance RAM role for authentication. If you attach a RAM role to an ECS instance, applications on the instance, including Terraform, can automatically obtain and refresh temporary access credentials. This method eliminates the need to configure an AccessKey, which reduces the risk of key leakage. You can also implement fine-grained permission control using the RAM role. For more information, see Instance RAM roles.

Parameters

Parameter Name

Description

Example value

ecs_role_name

The name of the RAM role attached to the ECS instance.

terraform-ecs-role

Example configuration

  1. Prepare an ECS instance that has public network access.

  2. Create a RAM role and attach it to the ECS instance.

  3. In the provider block, set the ecs_role_name parameter to the name of the RAM role:

provider "alicloud" {
  ecs_role_name = "<Name of the RAM role attached to the ECS instance>"
}

You can also use the environment variable ALICLOUD_ECS_ROLE_NAME to set this parameter.

Authentication using an instance RAM role for ECS is highly secure. We recommend this method when you run Terraform on an ECS instance.

OIDC role assumption

OIDC role assumption is similar to role assumption (AssumeRole). Both methods obtain temporary credentials by assuming a RAM role to access Alibaba Cloud resources. The difference is that OIDC role assumption uses an identity issued by an OIDC IdP. For more information, see Manage OIDC IdPs.

Parameters

When you configure OIDC role assumption, all related parameters are set in the assume_role_with_oidc block:

Parameter Name

Description

Example value

oidc_provider_arn (Required)

The ARN of the identity provider, in the format: acs:ram::<Alibaba Cloud account ID>:oidc-provider/<RAM Provider role name>. You can obtain this ARN from the RAM console or using an API. You can also set this parameter using the environment variable ALIBABA_CLOUD_OIDC_PROVIDER_ARN.

acs:ram::151192xxxxxx:oidc-provider/ackrole

oidc_token (Optional)

An OpenID Connect (OIDC) token issued by an external Identity Provider (IdP). You must set either oidc_token or oidc_token_file. You can set this parameter using the ALIBABA_CLOUD_OIDC_TOKEN environment variable.

eyJhbGciOiJSUzI1NiIsImtpZCI6IjEifQ.************

oidc_token_file (Optional)

The absolute path of the file that stores the OIDC token. You must set either oidc_token or oidc_token_file. This parameter can be set using the environment variable ALIBABA_CLOUD_OIDC_TOKEN_FILE.

/var/run/secrets/oidc/token

role_arn (Required)

Specifies the ARN of the RAM role to assume, in the format acs:ram::<Alibaba Cloud account ID>:role/<RAM role name>. You can set this parameter using the ALIBABA_CLOUD_ROLE_ARN environment variable.

acs:ram::151192xxxxxx:role/k8srole

policy (Optional)

A RAM access policy. If set, the final permissions for the temporary credential are the intersection of this policy and the access policies associated with the role specified by role_arn. If not set, the final permissions are determined solely by the permissions of the role specified by role_arn.

{"Version":"1","Statement":[{"Effect":"Allow","Action":"oss:ListBuckets","Resource":"acs:oss:oss-cn-hangzhou:*:*"}]}

role_session_name (Optional)

A custom name for the role session, which is typically set to the identity of the user who assumes the role. If unspecified, the default is terraform. This parameter can be set using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.

username

session_expiration (Optional)

The validity period of the temporary credential, in seconds. The value must be between 900 and the MaxSessionDuration of the assumed role. The default value for MaxSessionDuration is 3600. You can modify the maximum session duration of the role to a value up to 43,200 seconds by updating the role information.

900

Example configuration

OIDC role assumption authentication is implemented by calling the AssumeRoleWithOIDC - Obtain a temporary credential for a RAM role of an OIDC IdP for role-based SSO operation. Before you configure this method, prepare the following information:

  1. Create an OIDC IdP, obtain an OIDC token from the external IdP, and record the OIDC IdP's ARN and the OIDC token.

  2. Create a RAM role with an identity provider as the trusted entity, grant the role the required permissions (such as AliyunOSSFullAccess), and record the ARN of the role.

  3. (Optional) You can write a custom RAM policy, such as one that allows access only to buckets in the China (Hangzhou) region. This policy is combined with the role's permissions for more fine-grained access control.

After you complete the preparations, add the following configuration in the provider block:

provider "alicloud" {
  assume_role_with_oidc {
    oidc_provider_arn  = "<ARN of the OIDC IdP>"
    oidc_token         = "<OIDC token issued by the external IdP>"
    role_arn           = "<ARN of the RAM role>"
    policy             = "<Content of the RAM access policy>"
    role_session_name  = "<Custom role session name>"
    session_expiration = <Maximum validity period of the temporary access credential>
  }
}

Alibaba Cloud Container Service for Kubernetes (ACK) lets you use the RAM Roles for Service Accounts (RRSA) feature to automatically create OIDC IdPs and issue OIDC tokens. For more information, see Use RRSA to authorize different pods to access different cloud services. After you enable the RRSA feature, the ack-pod-identity-webhook component automatically injects the ALIBABA_CLOUD_OIDC_PROVIDER_ARN, ALIBABA_CLOUD_OIDC_TOKEN_FILE, and ALIBABA_CLOUD_ROLE_ARN environment variables into pods. In this environment, if you run Terraform in an ACK pod, the preceding example can be simplified as follows:

provider "alicloud" {
  region = "cn-hangzhou"
  assume_role_with_oidc {
    policy             = <<EOF
    {
      "Version": "1",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": "oss:ListBuckets",
          "Resource": "acs:oss:oss-cn-hangzhou:*:*"
        }
      ]
    }
    EOF
    session_name = "terraform-assume-role-session"
    session_expiration = 1000
  }
}

If you do not need to use the policy parameter for fine-grained authorization, you can directly grant the required permissions to the RAM role. In this case, the configuration can be further simplified:

provider "alicloud" {
  region = "cn-hangzhou"
  assume_role_with_oidc {
    session_name = "terraform-assume-role-session"
    session_expiration = 1000
  }
}

Role assumption

Role assumption (AssumeRole) is suitable for scenarios where you need to separate permissions from an identity, such as a RAM user or an ECS instance role, or when you need to access resources across accounts. This method allows an existing identity, such as a RAM user, to assume another RAM role and obtain that role's temporary credentials to access resources.

Parameters

When you configure role assumption, the following parameters are supported:

  1. access_key and secret_key: Specifies the AccessKey of the RAM user that assumes the role. The user must have the sts:AssumeRole permission. You can also set these parameters using environment variables.

  2. assume_role: A configuration block that includes the following parameters:

Parameter

Description

Example value

role_arn (Required)

The ARN of the RAM role to assume. The format is `acs:ram::1234567890123456:role/<RAM role name>.

acs:ram::151192xxxxxx:role/k8srole

policy (Optional)

A RAM access policy. If this parameter is set, the final permissions of the temporary credential are the intersection of this policy and the access policies that are associated with the role specified by role_arn. If this parameter is not set, the final permissions are determined solely by the permissions of the role specified by role_arn.

{"Version":"1","Statement":[{"Effect":"Allow","Action":"oss:ListBuckets","Resource":"acs:oss:oss-cn-hangzhou:*:*"}]}

session_name (Optional)

The custom role session name. This name is used to distinguish the operator in the audit log. If this parameter is not set, the default is terraform.

terraform

session_expiration (Optional)

The validity period of the temporary credential, in seconds. The value can range from 900 to the MaxSessionDuration of the assumed role. The default value is 3600. You can modify the maximum session duration of the role to a value up to 43200 seconds. For more information, see Update role information.

3600

external_Id (Optional)

An external ID for the role, used to prevent the "confused deputy" problem. For more information, see Use an external ID to prevent the confused deputy problem.

ID

Example configuration

Role assumption authentication is implemented by calling the AssumeRole - Obtain a temporary credential for a RAM role operation. Before you configure this method, prepare the following:

  1. Create a RAM user and grant the AliyunSTSAssumeRoleAccess policy (or a custom policy that contains the sts:AssumeRole permission).

  2. Create an AccessKey for the RAM user.

  3. Create a RAM role whose trusted entity is an Alibaba Cloud account, grant it the required permissions (such as AliyunOSSFullAccess), and record its ARN.

  4. (Optional) You can write a custom RAM policy. This policy is combined with the role's permissions for more fine-grained access control.

After you complete the preparation, configure the provider block as follows:

provider "alicloud" {
  # The AccessKey ID of the RAM user that calls AssumeRole.
  access_key = "<AccessKey ID of the RAM user>"
  # The AccessKey secret of the RAM user that calls AssumeRole.
  secret_key = "<AccessKey secret of the RAM user>"
  assume_role {
    role_arn           = "<ARN of a RAM role>"
    policy             = "<Content of a RAM access policy>"
    session_name       = "<Custom role session name>"
    session_expiration = <Maximum validity period of the temporary access credential>
  }
}

The following example demonstrates how to obtain permissions to list OSS buckets in the Hangzhou region using role assumption. For security purposes, the access_key and secret_key in the example are set using environment variables and are not written in plaintext in the code:

provider "alicloud" {
  # For security, the access_key and secret_key here are set as environment variables.
  region = "cn-hangzhou"
  assume_role {
    role_arn           = "acs:ram::11827xxxxxx:role/tf-assume-role"
    policy             = <<EOF
    {
      "Version": "1",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": "oss:ListBuckets",
          "Resource": "acs:oss:oss-cn-hangzhou:*:*"
        }
      ]
    }
    EOF
    session_name       = "terraform-assume-role-session"
    session_expiration = 1000
  }
}
Note

Before you run this example, ensure that the tf-assume-role role has been granted the AliyunOSSFullAccess permission. Otherwise, access to the OSS bucket fails due to insufficient permissions.

If you run Terraform on an ECS instance, you can use an ECS instance RAM role to avoid hard-coding an AccessKey. In this case, you only need to grant the AliyunSTSAssumeRoleAccess policy to the RAM role that is attached to the ECS instance. The following code provides an example:

provider "alicloud" {
  ecs_role_name = "<Name of the RAM role attached to the ECS instance>"
  region        = "cn-hangzhou"
  assume_role {
    role_arn           = "acs:ram::11827xxxxxx:role/tf-assume-role"
    policy             = <<EOF
    {
      "Version": "1",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": "oss:ListBuckets",
          "Resource": "acs:oss:oss-cn-hangzhou:*:*"
        }
      ]
    }
    EOF
    session_name       = "terraform-assume-role-session"
    session_expiration = 1000
  }
}

URL credential

Obtains a credential by accessing a specified URI.

Parameters

Parameter

Description

Example value

credentials_url

A local or remote URI for obtaining a credential. If the URI does not return an HTTP 200 status code or if the returned content is incorrectly formatted, authentication fails.

http://credentials.uri/

region

The default region and zone.

Some cloud products do not support cross-region access. We recommend setting the default region to the region where your resources are located.

cn-hangzhou

Example configuration

provider "alicloud" {
  region = "cn-hangzhou"
  credentials_url= "http://credentials.uri/"
}

Shared configuration file

Terraform supports using access credentials from a shared configuration file. The shared configuration file is the config.json file generated by the Alibaba Cloud command-line interface (CLI). You can configure multiple types of credential information, such as static AccessKeys, ECS roles, and role assumption, in a single file and reference them using a profile name. For more information about configuration methods, see Configure credentials.

The default paths for the shared configuration file are as follows:

  • Linux/macOS: ~/.aliyun/config.json

  • Windows: C:\Users\USER_NAME\.aliyun\config.json

Configuration example

In the Terraform provider configuration, you can use the profile parameter to specify the name of the credential configuration to use. If the configuration file is not in the default path, you can use the shared_credentials_file parameter to specify the absolute path of the configuration file. The following code provides a sample configuration:

provider "alicloud" {
  region                  = "cn-hangzhou"
  shared_credentials_file = "~/.aliyun/config.json"
  profile                 = "TerraformTest"
}

The following is an example of a config.json file:

{
    "current": "<PROFILE_NAME>",
    "profiles": [
        {
            "name": "<PROFILE_NAME>",
            "mode": "AK",
            "access_key_id": "<ALIBABA_CLOUD_ACCESS_KEY_ID>",
            "access_key_secret": "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>"
        },
        {
            "name": "<PROFILE_NAME1>",
            "mode": "StsToken",
            "access_key_id": "<ALIBABA_CLOUD_ACCESS_KEY_ID>",
            "access_key_secret": "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>",
            "sts_token": "<SECURITY_TOKEN>"
        },
        {
            "name": "<PROFILE_NAME2>",
            "mode": "RamRoleArn",
            "access_key_id": "<ALIBABA_CLOUD_ACCESS_KEY_ID>",
            "access_key_secret": "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>",
            "ram_role_arn": "<ROLE_ARN>",
            "ram_session_name": "<ROLE_SESSION_NAME>",
            "expired_seconds": 3600
        },
        {
            "name": "<PROFILE_NAME3>",
            "mode": "EcsRamRole",
            "ram_role_name": "<RAM_ROLE_ARN>"
        },
        {
            "name": "<PROFILE_NAME4>",
            "mode": "External",
            "process_command": "<YOUR_COMMAND>",
            "region_id": "<REGION_ID>",
            "output_format": "json",
            "language": "en"
        },
        {
            "name": "<PROFILE_NAME5>",
            "mode": "OIDC",
            "oidc_provider_arn": "<OIDC_PROVIDER_ARN>",
            "oidc_token_file": "<OIDC_TOKEN_FILE>",
            "ram_role_arn": "<ROLE_ARN>",
            "ram_session_name": "<ROLE_SESSION_NAME>",
            "expired_seconds": 3600
        },
        {
            "name": "<PROFILE_NAME6>",
            "mode": "ChainableRamRoleArn",
            "source_profile": "<PROFILE_NAME>",
            "ram_role_arn": "<ROLE_ARN>",
            "ram_session_name": "<ROLE_SESSION_NAME>",
            "expired_seconds": 3600
        },
        {
            "name": "<PROFILE_NAME7>",
            "mode": "CloudSSO",
            "cloud_sso_sign_in_url": "https://******/login",
            "access_token": "eyJraWQiOiJiYzViMzUwYy******",
            "cloud_sso_access_token_expire": 1754316142,
            "cloud_sso_access_config": "ac-00s1******",
            "cloud_sso_account_id": "151266******"
        },
        {
            "name": "<PROFILE_NAME8>",
            "mode": "OAuth",
            "access_key_id": "<ALIBABA_CLOUD_ACCESS_KEY_ID>",
            "access_key_secret": "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>",
            "sts_token": "<SECURITY_TOKEN>",
            "region_id": "<REGION_ID>",
            "output_format": "json",
            "language": "<zh|en>",
            "sts_expiration": "<STS_EXPIRATION>",
            "oauth_access_token": "<OAUTH_ACCESS_TOKEN>",
            "oauth_refresh_token": "<OAUTH_REFRESH_TOKEN>",
            "oauth_access_token_expire": 1754316142,
            "oauth_site_type": "<CN|EN>"
        }
    ]
}

In the config.json file, you can use the mode parameter to specify different credential types:

  • AK: Uses the user's AccessKey as the credential.

  • StsToken: Uses an STS token as the credential.

  • RamRoleArn: Obtains the credential using the ARN of a RAM role.

  • EcsRamRole: Obtains the credential using the RAM role attached to an ECS instance.

  • External: Dynamically obtains a credential by running an external program command.

  • OIDC: Obtains the credential using an OIDC IdP ARN and an OIDC token.

  • ChainableRamRoleArn: Uses a role chain. It specifies the name of another credential in the config.json file using source_profile to obtain a new credential.

  • OAuth: The credential obtained by logging on to the CLI using OAuth.

  • CloudSSO: The credential obtained by a CloudSSO user using the Alibaba Cloud CLI.