# terraform-iac

Part of **TERRAFORM**

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

> 💡 **Path Selection**: This skill is one implementation path for the following routing skills. If you're unsure which path to take, check the corresponding routing skill:

> - [Automate Terraform execution via CI/CD pipelines](../../intent/terraform-automate-cd/SKILL.md)
> - [Bring existing cloud resources under Terraform management](../../intent/terraform-import-resources/SKILL.md)
> - [Configure Terraform authentication with cloud provider](../../intent/terraform-manage-authentication/SKILL.md)
> - [Provision cloud infrastructure (compute, network, storage)](../../intent/terraform-provision-infrastructure/SKILL.md)

# Terraform Infrastructure as Code

## Capabilities Overview

| Sub-capability | Calling Mode | Description |
|----------------|--------------|-------------|
| Manage Cloud Resources with Terraform | Synchronous | Use Terraform APIs and providers to interact with supported cloud services. |

## API Calling Patterns

### Authentication
The primary authentication method for Terraform with Alibaba Cloud is via **AccessKey credentials** passed through environment variables or provider configuration.

- **Header format**: Not applicable — Terraform uses provider-level authentication, not per-request headers.
- **Environment variables**:
  - `ALICLOUD_ACCESS_KEY` (or `ALIBABA_CLOUD_ACCESS_KEY_ID`)
  - `ALICLOUD_SECRET_KEY` (or `ALIBABA_CLOUD_ACCESS_KEY_SECRET`)
- **Alternative**: You can also authenticate using RAM roles, STS tokens, or instance metadata in ECS environments, but AccessKey is recommended for local development and CI/CD pipelines.

### Service Endpoint
Terraform does not call a single REST API endpoint directly. Instead, it uses the **Alibaba Cloud Terraform Provider**, which internally communicates with regional Alibaba Cloud service endpoints.

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

The provider automatically selects the correct endpoint based on the configured region in your Terraform configuration.

### Synchronous Execution Flow
Terraform operates synchronously by default:

1. **`terraform init`**: Downloads the Alibaba Cloud provider plugin and initializes the working directory.
2. **`terraform plan`**: Generates an execution plan by comparing the desired state (HCL code) with the current state (stored in `terraform.tfstate` or remote backend).
3. **`terraform apply`**: Applies the plan by making synchronous API calls to Alibaba Cloud services to create, update, or delete resources.
4. **State update**: After successful execution, Terraform updates the state file to reflect the new infrastructure state.

All operations block until completion. There is no built-in async or streaming mode — each `apply` runs to completion before returning control.

## Parameter Reference

### Manage Cloud Resources with Terraform

| Parameter | Type | Required | Default | Constraints | Description |
|----------|------|--------|--------|------------|-------------|
| region | string | Yes | — | Must be a valid Alibaba Cloud region (e.g., `cn-hangzhou`) | Specifies the region where resources are provisioned |
| access_key | string | Conditional | — | Required if not using RAM role or ECS metadata | Alibaba Cloud AccessKey ID |
| secret_key | string | Conditional | — | Required if `access_key` is provided | Alibaba Cloud AccessKey Secret |
| configuration_mode | string | No | `"Default"` | Enum: `"Default"`, `"AK"`, `"StsToken"`, `"EcsRamRole"`, `"RamRoleArn"` | Authentication method used by the provider |
| assume_role | object | No | — | Only valid with `RamRoleArn` mode | Specifies role ARN and session name for cross-account access |

> Note: These parameters are used in the `provider "alicloud"` block in HCL, not as HTTP request parameters.

## Code Examples

### Basic VPC Provisioning - HCL - cn-hangzhou

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

resource "alicloud_vpc" "example" {
  vpc_name   = "tf-example-vpc"
  cidr_block = "10.0.0.0/16"
}

resource "alicloud_vswitch" "example" {
  vpc_id       = alicloud_vpc.example.id
  cidr_block   = "10.0.1.0/24"
  zone_id      = "cn-hangzhou-i"
  vswitch_name = "tf-example-vswitch"
}
```

### Authenticate Using Environment Variables - Bash

```bash
export ALICLOUD_ACCESS_KEY="your-access-key-id"
export ALICLOUD_SECRET_KEY="your-access-key-secret"
export ALICLOUD_REGION="cn-shanghai"

terraform init
terraform plan
terraform apply -auto-approve
```

### Use RAM Role for Cross-Account Access - HCL

```hcl
provider "alicloud" {
  region           = "cn-beijing"
  configuration_mode = "RamRoleArn"
  assume_role {
    role_arn     = "acs:ram::123456789012:role/terraform-role"
    session_name = "terraform-session"
  }
}

resource "alicloud_oss_bucket" "logs" {
  bucket = "my-logs-bucket-2024"
  acl    = "private"
}
```

### Modular Infrastructure with Remote Module - HCL

```hcl
module "web_server" {
  source  = "registry.terraform.io/alibaba/cloud-modules/ecs-instance/alicloud"
  version = "1.2.0"

  instance_name = "web-prod"
  image_id      = "ubuntu_22_04_x64_20G_alibase_20231218.vhd"
  instance_type = "ecs.g7.large"
  vswitch_id    = "vsw-xxxxxx"
  security_groups = ["sg-xxxxxx"]
}

output "instance_ip" {
  value = module.web_server.public_ip
}
```

## Response Format

*Not applicable.* Terraform CLI outputs human-readable logs and structured state files (in JSON format), but there is no standardized JSON API response since Terraform is a client-side orchestration tool, not a REST API.

## Error Handling

*No standardized error codes.* Errors are surfaced as descriptive messages from the Alibaba Cloud provider during `plan` or `apply`. Common issues include:

- Invalid credentials → "InvalidAccessKeyId.NotFound"
- Insufficient permissions → "Forbidden.RAM"
- Quota exceeded → "QuotaExceeded"
- Invalid parameter → "InvalidParameter"

These map to underlying Alibaba Cloud service errors, which follow standard Alibaba Cloud error conventions.

### Rate Limits & Retry
Terraform automatically retries transient errors (e.g., network timeouts) using exponential backoff. For rate-limited requests (HTTP 429), the provider respects the `Retry-After` header when present. However, users should design configurations to avoid hitting service quotas (e.g., by batching changes or using lifecycle rules).

## Environment Requirements

- **Terraform CLI**: v1.0 or higher (`https://developer.hashicorp.com/terraform/downloads`)
- **Alibaba Cloud Provider**: Automatically installed via `terraform init`; latest version recommended
- **Authentication**: Set `ALICLOUD_ACCESS_KEY` and `ALICLOUD_SECRET_KEY` as environment variables, or configure provider block with credentials
- **Permissions**: RAM user must have appropriate policies attached (e.g., `AliyunVPCFullAccess`, `AliyunECSFullAccess`)

## FAQ

Q: Do I need to pay to use Terraform with Alibaba Cloud?
A: No. Terraform itself is open-source and free to use. You only pay for the underlying Alibaba Cloud resources (ECS, VPC, OSS, etc.) that you provision.

Q: Can I use Terraform in a CI/CD pipeline?
A: Yes. Store your `.tf` files in version control, authenticate using secure secrets (e.g., GitHub Actions secrets or Jenkins credentials), and run `terraform plan` and `apply` in your pipeline stages.

Q: How does Terraform handle state?
A: By default, state is stored locally in `terraform.tfstate`. For team collaboration, use a remote backend like Alibaba Cloud OSS with locking enabled to prevent concurrent modifications.

Q: What if my infrastructure drifts from the Terraform state?
A: Run `terraform refresh` (or `terraform plan` in newer versions) to reconcile. For unmanaged changes, use `terraform import` to bring existing resources under Terraform control.

Q: Where can I find pre-built modules?
A: Browse the [Alibaba Cloud Module Registry](https://registry.terraform.io/namespaces/alibaba) for official and community modules that simplify common deployment patterns.

## Pricing & Billing

### Billing Model
Free — Terraform is an open-source tool with no usage fees.

### Free Tier
No cost for using Terraform with Alibaba Cloud resources.

### Usage Limits
Subject to individual Alibaba Cloud service quotas (e.g., max VPCs per region, ECS instance limits). Terraform does not impose additional limits.

### Billing Notes
Billing is based solely on the Alibaba Cloud resources you create (e.g., compute hours, storage GB, network traffic). Terraform operations themselves incur no charges.