使用Terraform进行AWS基础架构的构建和自动化运维的入门

如果使用Terraform,它可以根据定义文件的状态来构建云上的资源。说实话,习惯了使用Terraform进行构建和运维后,在控制台上点点鼠标操作就会变得很麻烦。这次我打算使用Terraform来入门自动化构建和运维AWS环境。

本篇将介绍以下内容:
1. 在CentOS7上安装terraform执行环境
2. 命令的解释
3. 使用terraform实际创建AWS的VPC

前提 – Assumption/condition

已创建AWS帐户
已创建IAM用户,并已生成用户访问密钥和秘密密钥

1、在CentOS 7上安装terraform执行环境。

我们将以root用户进行操作。

部署执行环境

# terraformダウンロード
wget https://releases.hashicorp.com/terraform/0.11.13/terraform_0.11.13_linux_amd64.zip

# terraform配置
unzip ./terraform_0.11.13_linux_amd64.zip -d /usr/local/bin/

# 確認
terraform -v

# terraform用ディレクトリ作成
mkdir terraform
cd terraform

最初设置

创建一个用于设置凭证信息的文件。

vi terraform.tfvars
※以下記載

aws_access_key = "アクセスキー"
aws_secret_key = "シークレットキー"

关于访问密钥和秘密密钥的传递方式。(Regarding the method of passing values for access keys and secret keys.)

以下是值传递的几种方法。

用Terraform命令传递值

$ terraform apply \
-var 'aws_access_key=アクセスキー' \
-var 'aws_secret_key=シークレットキー'

在环境变量中传递值

$ export TF_VAR_aws_access_key="アクセスキー"
$ export TF_VAR_aws_secret_key="シークレットキー"

在文件中传递值

vi terraform.tfvars
※以下記載
aws_access_key = "アクセスキー"
aws_secret_key = "シークレットキー"

在Terraform的官方文件中,建议使用terraform.tfvars文件的方法。

2,解释命令等

在创建资源之前,先简要说明一下命令等。

基本指令

# 初期化
terraform init

# ドライ・ラン
terraform plan

# 適用
terraform apply

# 削除確認
terraform plan -destroy

# リソース一括削除
terraform destroy

办公空间

在Workspace概念中,可以根据不同的环境进行分割,例如生产/验证/开发等。
即使没有指定任何内容,也可以在名为”default”的Workspace上进行操作。

# workspace の一覧表示
terraform workspace list

# workspace を選択
terraform workspace select ワークスペース名

# workspace を作成
terraform workspace new ワークスペース名

# workspace を削除
terraform workspace delete ワークスペース名

# workspace を表示
terraform workspace show

用terraform在AWS上创建VPC。

我們將以名為VPC01的名字來建立一個VPC,並準備一個公有子網和一個私有子網,這是我們的配置方案。

現在,我們將進行以下的資源定義,並簡單介紹一下資源設定。

资源会在资源块中进行设置。语法是 `resource “<资源类型>” “<资源名称>” {}`。
如果提供者是AWS,那么资源类型在Terraform中预先定义为aws_ *。
如果是VPC,则为aws_vpc;如果是EC2,则为aws_instance。资源名称可以任意设置。

我们将创建一个名为main.tf的文件。

vi main.tf
※以下記載

# クレデンシャル変数設定
variable "aws_access_key" {}
variable "aws_secret_key" {}

provider "aws" {
    access_key = "${var.aws_access_key}"
    secret_key = "${var.aws_secret_key}"
    region = "ap-northeast-1"
}

# 以下VPCリソース定義
resource "aws_vpc" "VPC01" {
    cidr_block = "10.0.0.0/16"
    instance_tenancy = "default"
    enable_dns_support = "true"
    enable_dns_hostnames = "false"
    tags {
      Name = "VPC01"
    }
}

resource "aws_internet_gateway" "myGW" {
    vpc_id = "${aws_vpc.VPC01.id}"
}

resource "aws_subnet" "public-a" {
    vpc_id = "${aws_vpc.VPC01.id}"
    cidr_block = "10.0.0.0/24"
    availability_zone = "ap-northeast-1a"
}

resource "aws_subnet" "private-a" {
    vpc_id = "${aws_vpc.VPC01.id}"
    cidr_block = "10.0.1.0/24"
    availability_zone = "ap-northeast-1a"
}

resource "aws_route_table" "public-route" {
    vpc_id = "${aws_vpc.VPC01.id}"
    route {
        cidr_block = "0.0.0.0/0"
        gateway_id = "${aws_internet_gateway.myGW.id}"
    }
}

resource "aws_route_table_association" "pubclic-a" {
    subnet_id = "${aws_subnet.public-a.id}"
    route_table_id = "${aws_route_table.public-route.id}"
}

resource "aws_security_group" "SG01" {
    name = "admin"
    description = "Allow SSH inbound"
    vpc_id = "${aws_vpc.VPC01.id}"
    ingress {
        from_port = 22
        to_port = 22
        protocol = "tcp"
        cidr_blocks = ["X.X.X.X/XX"] # SSHをアクセスしたいネットワークを指定。
    }
    egress {
        from_port = 0
        to_port = 0
        protocol = "-1"
        cidr_blocks = ["0.0.0.0/0"]
    }
}

在资源块内的配置项,如果是VPC,则会描述cidr_block、instance_tenancy等。
有关在AWS资源上进行配置的项可在Provider: AWS – Terraform by HashiCorp中进行参考。

我们将应用我们定义的资源。

初始化

# terraform init
※ Terraform has been successfully initialized! と表示される。

乾燥跑

# terraform plan
※以下表示される。

Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.


------------------------------------------------------------------------

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  + aws_internet_gateway.myGW
      id:                                          <computed>
      owner_id:                                    <computed>
      vpc_id:                                      "${aws_vpc.VPC01.id}"

…以下省略

Plan: 7 to add, 0 to change, 0 to destroy.

当执行terraform plan时,会生成一个名为terraform.tfstate的JSON文件,该文件显示了资源的状态。新创建的资源将带有「+」标记,并且最后一行会显示创建、更改和删除的资源数量。

创建资源

# terraform apply
※以下表示される。

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

 Enter a value: 確認されるので"yes"と入力する

…以下省略

 Apply complete! Resources: 7 added, 0 changed, 0 destroyed.

如果想要更改资源,只需修改main.tf文件的内容并再次执行terraform apply。

如果想要删除资源,可以使用terraform plan -destroy进行模拟删除,使用terraform destroy可以批量删除资源。

キャプチャ.PNG

有关tf文件的分割。

过去我们把资源定义都放在一个模板文件(main.tf)中,但是现在Terraform可以自动识别扩展名为*.tf的文件作为模板使用。
所以现在我们可以把模板文件拆分成多个部分。
例如,可以将凭证放在 variables.tf,VPC 放在 vpc.tf,S3 放在 s3.tf等文件中进行管理。
我们在 GitHub 上准备了一个示例供您参考。
https://github.com/y-araki-git/terraform-aws-sample

在执行Terraform时需要注意的事项

假设我们使用Terraform进行资源管理,在使用Terraform搭建完成后,其他人可能会在控制台上手动创建资源而我们没有注意到。
如果不知情地再次使用Terraform执行搭建,可能会覆盖和删除手动创建的资源。
我认为,如果团队要使用Terraform,应该明确决定策略并进行运维。

bannerAds