# Terraform

> 使用 terraform 置备云虚拟机
---

[Terraform](https://www.terraform.io/) 是一个流行的 IaC 工具。您可以使用一个命令在公有云上创建虚拟机。

阿里云和 AWS 模板用作示例提供商。您可以将 [`terraform.tf`](https://github.com/pgsty/pigsty/blob/v3.7.0/terraform/terraform.tf) 作为示例。

------

## 入门 {#get-started}

您可以在 macOS 上使用 [**homebrew**](https://brew.sh/) 安装 terraform

```bash {title="安装 homebrew 和 terraform"}
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
brew install terraform
```

然后初始化 terraform 云提供商，调整 `terraform.tf` 配置文件并应用它：

```bash {title="cd ~/pigsty/terraform"}
terraform init
terraform apply #-auto-approve
```

打印公共 IP 地址：

```bash
terraform output | grep -Eo '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
```

--------

## AWS 设置 {#aws-setup}

您必须设置 aws 配置和凭据才能使用 AWS 提供商。

```bash
# ~/.aws

# ~/.aws/config
[default]
region = cn-northwest-1

# ~/.aws/credentials
[default]
aws_access_key_id = <YOUR_AWS_ACCESS_KEY>
aws_secret_access_key =  <AWS_ACCESS_SECRET>

# ~/.aws/pigsty-key
# ~/.aws/pigsty-key.pub
```

有一个 AWS（Amazon Web Services）的贡献示例，但它没有得到积极维护。

- [spec/aws-cn.tf](https://github.com/pgsty/pigsty/blob/v3.7.0/terraform/spec/aws-cn.tf) : AWS 4 节点 CentOS7 环境

--------

## 阿里云设置 {#aliyun-setup}

您可以将您的阿里云凭据添加到环境文件中，例如 `~/.bash_profile`

```bash
export ALICLOUD_ACCESS_KEY="<your_access_key>"
export ALICLOUD_SECRET_KEY="<your_secret_key>"
export ALICLOUD_REGION="cn-beijing"
```

示例配置文件：

- [spec/aliyun-meta.tf](https://github.com/pgsty/pigsty/blob/v3.7.0/terraform/spec/aliyun-meta.tf) : 阿里云 1 元节点模板，适用于所有发行版和 amd/arm（默认）
- [spec/aliyun-full.tf](https://github.com/pgsty/pigsty/blob/v3.7.0/terraform/spec/aliyun-full.tf) : 阿里云 4 节点沙盒模板，适用于所有发行版和 amd/arm。
- [spec/aliyun-oss.tf](https://github.com/pgsty/pigsty/blob/v3.7.0/terraform/spec/aliyun-oss.tf) : 阿里云 5 节点构建模板，适用于所有发行版和 amd/arm。

以下是阿里云中使用的示例 [ECS 公共操作系统镜像](https://help.aliyun.com/zh/ecs/user-guide/public-mirroring-overview)：

| 发行版       | 镜像前缀              | 镜像前缀               |
|--------------|-----------------------|------------------------|
| CentOS 7.9   | `centos_7_9_x64`      | `rockylinux_8_10_arm6` |
| Rocky 8.10   | `rockylinux_8_10_x64` | `rockylinux_9_6_arm64` |
| Rocky 9.6    | `rockylinux_9_5_x64`  |                        |
| Debian 11.11 | `debian_11_11_x64`    |                        |
| Debian 12.11 | `debian_12_11_x64`    | `debian_12_11_arm64`   |
| Ubuntu 20.04 | `ubuntu_20_04_x64`    |                        |
| Ubuntu 22.04 | `ubuntu_22_04_x64`    | `ubuntu_22_04_arm64`   |
| Ubuntu 24.04 | `ubuntu_24_04_x64`    | `ubuntu_24_04_arm64`   |
| Anolis 8.8   | `anolisos_8_9_x64`    |                        |

--------

## 腾讯云设置 {#qcloud-setup}

有一个腾讯云的贡献示例，但它没有得到积极维护。

- [spec/tencentcloud.tf](https://github.com/pgsty/pigsty/blob/v3.7.0/terraform/spec/tencentcloud.tf) : 腾讯云 4 节点 CentOS7 环境
