# 基础设施即代码

#### Terraform简介 <a href="#toc1007530171" id="toc1007530171"></a>

Terraform是一个用于创建和管理云和企业环境中资源的开源基础设施即代码工具。它使用声明式配置文件来描述要部署的资源，并通过调用API接口来自动创建和配置这些资源。 这一章会介绍通过Terraform来构建公有云的漏洞环境。

一些使用场景例如：

* &#x20;在AWS中使用Terraform来部署EC2实例。
* &#x20;在Kubernetes中使用Terraform来部署应用程序
* &#x20;在腾讯云中使用Terraform来部署CVM、COS

**Terraform工作原理**

* &#x20;Terraform 通过其应用程序编程接口在云平台和其他服务上创建和管理资源。
* &#x20;Provider使Terraform能够通过可访问的API与几乎任何平台或服务一起工作。

<figure><img src="/files/Bwfh8gKQNDYGdJmGThrj" alt=""><figcaption></figcaption></figure>

Terraform执行流程包括三个阶段：

Write -> Plan -> Apple

* &#x20;写入：定义所需要的资源，这些资源可以跨多个云提供商和服务
* &#x20;计划：创建一个执行计划，将根据配置文件创建、更新、销毁。
* &#x20;应用：在批准后Terraform会按照资源依赖关系顺序执行

&#x20;

大多数时候不用自己从头开始编写脚本，Terraform社区已经编写了 2664 providers, 11506 modules，来管理数千种不同类型的资源和服务，可以通过官网查找：

{% embed url="<https://registry.terraform.io/>" %}

<figure><img src="/files/047U5Bxr0zo911TlqGll" alt=""><figcaption></figcaption></figure>

#### Terraform入门 <a href="#toc651027402" id="toc651027402"></a>

**安装Terraform**

{% embed url="<https://developer.hashicorp.com/terraform/downloads>" %}

```bash
#Centos7
sudo yum install -y yum-utils
sudo yum-config-manager --add-repo
https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo
sudo yum -y install terraform
```

**配置语法**

* &#x20;Terraform的配置文件以 .tf 为后缀
* &#x20;json代码文件以 .tf.json 为后缀
* &#x20;Terraform只支持两种格式：HCL、JSON

在使用Terraform调用云服务时，需要开启云服务的RAM帐户，这里以腾讯云为例子：

<figure><img src="/files/Wv3VmbKAf78N3Q0abaCP" alt=""><figcaption></figcaption></figure>

**配置Provider**

Terraform通过provider管理基础设施，使用provider与云供应商API 进行交互

Tencentcloud：

* &#x20;<https://registry.terraform.io/providers/tencentcloudstack/tencentcloud/1.78.15>
* &#x20;<https://github.com/tencentcloudstack/terraform-provider-tencentcloud>

```bash
terraform {
  required_providers {
    tencentcloud = {
        source = "tencentcloudstack/tencentcloud"
        version = "1.78.15"
    }
  }
}
```

* &#x20;required\_providers：定义providers
* &#x20;source：定义providers的源地址
* &#x20;version：指定providers版本号

编辑完后通过以下方式进行测试：

```bash
mkdir test
cd test
vim version.tf
terraform init
```

**配置AK**

定义Variables

Terraform 会自动加载许多变量定义文件：

文件名为 terraform.tfvars 或 terraform.tfvars.json 的文件。

文件名称以 .auto.tfvars 或 .auto.tfvars.json 结尾的文件。

若同时使用多种赋值方式时，同一个变量可能会被赋值多次。Terraform会使用新值覆盖旧值。Terraform 加载变量值的顺序是：

1\. 环境变量

2\. terraform.tfvars 文件（若存在）

3\. terraform.tfvars.json 文件（若存在）

4\. 所有的 .auto.tfvars 或 .auto.tfvars.json 文件，以字母顺序排序处理。

5\. 通过 -var 或 -var-file 命令行参数传递的输入变量，按照在命令行参数中定义的顺序加载。

(1) 创建variables.tf文件，存储变量

(2) 可以从环境变量或者文本中读取

```bash
variable "tencentcloud_secret_id" {
  type        = string
  description = "Set TencentCloud access key id."
  sensitive   = true
  nullable    = false
}
 
variable "tencentcloud_secret_key" {
  type        = string
  description = "Set TencentCloud secret access key."
  sensitive   = true
  nullable    = false
}
tencentcloud_secret_id  = "xxx" #填写AK
tencentcloud_secret_key = "xxx" #填写密钥
provider "tencentcloud" {
  secret_id  = var.tencentcloud_secret_id
  secret_key = var.tencentcloud_secret_key
  region     = "ap-beijing"
}
```

不通过以上方式，可以在本机定义变量，通过环境变量读取AK

```bash
export TF_VAR_tencentcloud_access_key="LxxxT”
export TF_VAR_tencentcloud_secret_key="zWSKxxxIUu”
export TF_VAR_region="cn-beijing-b"
```

**定义资源**

* &#x20;资源来自Provider， 是Terraform中最重要的元素。每个资源块描述一个或多个基础对象，例如网络、计算实例或更高级别的组件，例如 DNS 记录。
* &#x20;资源名称必须以字母或下划线开头，并且只能包含字母、数字、下划线和破折号。

腾讯云Terraform文档参考：

<https://registry.terraform.io/providers/tencentcloudstack/tencentcloud/latest/docs>

地域和可用区：<https://cloud.tencent.com/document/product/213/6091>

```bash
provider "tencentcloud" {
    secret_id  = var.tencentcloud_secret_id
    secret_key = var.tencentcloud_secret_key
    region     = "ap-hongkong"
}
 
resource "tencentcloud_instance" "test" {
    instance_name = "test_terraform" #实例名称
    availability_zone = "ap-hongkong-2" #地区
    image_id = "img-l8og963d" #镜像ID
    instance_type = "SA2.MEDIUM2" #机器类型
    allocate_public_ip = true
    internet_max_bandwidth_out = 50
    security_groups = ["sg-3yy8drp7"] #安全组
    user_data_raw = <<EOF
#!/bin/bash
touch /tmp/test.txt
EOF
}
 
terraform init #初始化
terraform plan #计划与预览
terraform apply #申请资源
terraform show #显示资源
terraform destroy #销毁资源
```

整个执行流程如下：

<figure><img src="/files/cSr65SdaH4q5wd5hYutl" alt=""><figcaption></figcaption></figure>

#### 构建公有云漏洞环境 <a href="#toc388363949" id="toc388363949"></a>

TerraformGoat 是一个支持多云的云场景漏洞靶场搭建工具，目前支持阿里云、腾讯云、华为云、Amazon Web Services、Google Cloud Platform、Microsoft Azure 六个云厂商的云场景漏洞搭建。

{% embed url="<https://github.com/HXSecurity/TerraformGoat>" %}

&#x20;

通过Docker构建腾讯云环境：

```bash
docker pull
registry.cn-hongkong.aliyuncs.com/huoxian_pub/terraformgoat_tencentcloud:0.0.7
docker run -itd --name terraformgoat_tencentcloud_0.0.7
registry.cn-hongkong.aliyuncs.com/huoxian_pub/terraformgoat_tencentcloud:0.0.7
docker exec -it terraformgoat_tencentcloud_0.0.7 /bin/bash 
```

构建SSRF漏洞的CVM环境：

```bash
cd /TerraformGoat/tencentcloud/cvm/cvm_ssrf/
```

编辑 terraform.tfvars 文件，在文件中填入你

的 tencentcloud\_secret\_id 和 tencentcloud\_secret\_key

```bash
vim terraform.tfvars
```

部署靶场

```bash
terraform init
terraform apply
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://lzcloudsecurity.gitbook.io/yun-an-quan-gong-fang-ru-men/di-si-zhang-gong-you-yun-gong-fang/ji-chu-she-shi-ji-dai-ma.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
