# terraform-auth

Part of **TERRAFORM**

<!-- intent-backlink:auto -->

> 💡 **Path Selection**: This skill is one implementation path for [Configure Terraform authentication with cloud provider](../../intent/terraform-manage-authentication/SKILL.md). If you're unsure which path to take, check the routing skill first.

# Terraform Identity Authentication

## Capabilities Overview

| Sub-capability | Calling Mode | Description |
|----------------|--------------|-------------|
| Configure Terraform Provider Authentication | Synchronous | Set up secure authentication for Terraform to access cloud APIs. |

## API Calling Mode

### Authentication
The primary authentication method is **static credential configuration** directly in the Terraform provider block or via environment variables.

- **Header format**: Not applicable (Terraform uses SDK-level credentials, not HTTP headers)
- **Environment variables**:
  - `ALICLOUD_ACCESS_KEY` — Your AccessKey ID
  - `ALICLOUD_SECRET_KEY` — Your AccessKey secret
  - `ALICLOUD_SECURITY_TOKEN` — STS security token (if using temporary credentials)

Alternative methods include instance RAM roles, OIDC role assumption, and shared configuration files. However, static credentials via environment variables are recommended for simplicity and clarity in most CI/CD and local development scenarios.

### Service Endpoint
The Terraform provider communicates with multiple Alibaba Cloud service endpoints dynamically based on the resources being managed. There is no single base URL.

- Endpoints follow the pattern: `https://{service}.{region}.aliyuncs.com`
- Common regions: `cn-hangzhou`, `cn-shanghai`, `cn-beijing`

### Credential Chain Resolution
The provider automatically attempts authentication methods in the following order until one succeeds:

1. Static credentials (`access_key` + `secret_key` in provider block)
2. Environment variables (`ALICLOUD_ACCESS_KEY`, etc.)
3. Shared credentials file (specified via `shared_credentials_file` and `profile`)
4. Credentials from URL (`credentials_url`)
5. ECS instance RAM role (`ecs_role_name`)
6. OIDC-based role assumption (`assume_role_with_oidc`)
7. Traditional role assumption (`assume_role`)

No explicit polling or async handling is required—authentication is resolved synchronously at plan/apply time.

## Parameter Reference

### Configure Terraform Provider Authentication

| Parameter | Type | Required | Default | Constraints | Description |
|----------|------|----------|---------|-------------|-------------|
| access_key | string | false | — | — | The AccessKey ID. |
| secret_key | string | false | — | — | The AccessKey secret. |
| security_token | string | false | — | — | The security token of a temporary STS credential. |
| ecs_role_name | string | false | — | — | The name of the RAM role attached to the ECS instance. |
| oidc_provider_arn | string | true (in OIDC block) | — | — | The ARN of the identity provider, in the format: `acs:ram::<Account ID>:oidc-provider/<Provider name>`. |
| oidc_token | string | false | — | — | An OIDC token issued by an external IdP. Must set either this or `oidc_token_file`. |
| oidc_token_file | string | false | — | — | Absolute path to the file storing the OIDC token. |
| role_arn | string | true (in assume_role blocks) | — | — | ARN of the RAM role to assume: `acs:ram::<Account ID>:role/<Role name>`. |
| policy | string | false | — | — | A RAM access policy. Final permissions are intersection of this and role policies. |
| role_session_name | string | false | `terraform` | — | Custom name for the role session. |
| session_expiration | integer | false | `3600` | range 900–43200 | Validity period (seconds) of temporary credential. |
| external_Id | string | false | — | — | External ID to prevent confused deputy problem. |
| credentials_url | string | false | — | — | Local or remote URI returning valid credentials (HTTP 200, correct format). |
| region | string | false | `cn-beijing` | — | Default region for resource creation. |
| profile | string | false | — | — | Name of the credential profile to use. |
| shared_credentials_file | string | false | — | — | Absolute path to the shared config file (e.g., `~/.aliyun/config.json`). |

## Code Examples

### Static Credentials - HCL - All Regions

```hcl
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>"
}
```

### Environment Variables - Bash - All Regions

```bash
$ export ALICLOUD_ACCESS_KEY="<Your AccessKey ID>"
$ export ALICLOUD_SECRET_KEY="<Your AccessKey secret>"
# If you use an STS credential, configure security_token.
$ export ALICLOUD_SECURITY_TOKEN="<Your STS token>"
```

### Instance RAM Role - HCL - All Regions

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

### OIDC Role Assumption - HCL - All Regions

```hcl
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             = "{\"Version\":\"1\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"oss:ListBuckets\",\"Resource\":\"acs:oss:oss-cn-hangzhou:*:*\"}]}"
    role_session_name  = "<Custom role session name>"
    session_expiration = 3600
  }
}
```

### Traditional Role Assumption - HCL - All Regions

```hcl
provider "alicloud" {
  access_key = "<AccessKey ID of the RAM user>"
  secret_key = "<AccessKey secret of the RAM user>"
  assume_role {
    role_arn           = "<ARN of a RAM role>"
    policy             = "{\"Version\":\"1\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"oss:ListBuckets\",\"Resource\":\"acs:oss:oss-cn-hangzhou:*:*\"}]}"
    session_name       = "<Custom role session name>"
    session_expiration = 3600
  }
}
```

### URL-Sourced Credentials - HCL - All Regions

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

### Shared Configuration File - HCL - All Regions

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

## Error Handling

| Error Code | Description | Recommended Action |
|------------|-------------|---------------------|
| 403 | Access denied. Check that the AccessKey has sufficient permissions and is not expired. | Verify IAM policies, ensure keys are active, and confirm role trust relationships. |
| 400 | Invalid request parameters. Verify that all required parameters are provided and correctly formatted. | Check JSON policy syntax, ARN formats, and required fields like `role_arn` in assume blocks. |
| 429 | Too many requests. Rate limiting is in effect. Wait before retrying. | Implement exponential backoff; reduce concurrent Terraform runs. |
| 500 | Internal server error. Retry after a short delay. Contact support if the issue persists. | Retry with backoff; check Alibaba Cloud status page for outages. |

## FAQ

Q: Which authentication method is most secure for production?
A: Use OIDC role assumption in CI/CD (e.g., GitHub Actions, GitLab CI) or instance RAM roles on ECS. Avoid hardcoding static credentials.

Q: Can I use multiple authentication methods at once?
A: No—the provider uses the first valid method in its credential chain. Explicitly configure only one method per environment to avoid ambiguity.

Q: Why am I getting a 403 error even with valid credentials?
A: The RAM user or assumed role may lack necessary permissions. Ensure the attached policies grant required actions (e.g., `ecs:DescribeInstances`).

Q: How do I rotate credentials without downtime?
A: For static credentials, update environment variables and re-run `terraform init`. For roles, rotate underlying keys or OIDC tokens externally—Terraform fetches fresh credentials on each run.

Q: Does the shared credentials file work with Terraform Cloud?
A: Only if the file is present in the workspace. Prefer environment variables or OIDC in remote execution environments.

## Pricing & Billing

### Billing Model
Free

### Free Tier
Free to use with no cost for authentication operations.

### Usage Limits
No specific quota limits mentioned; depends on underlying Alibaba Cloud services.

### Billing Notes
Authentication itself is free. Costs are incurred based on the resources managed via Terraform (e.g., ECS instances, OSS buckets).