使用Terraform构建AWS环境.

我刚刚看了一下作为编排工具的 Amazon CloudFormation,但感觉有点麻烦,所以想试试流行的 Terraform。

我的电脑环境是Mac(Yosemite 10.10.2)。
我的目标是在AWS上构建和销毁EC2实例。

安装Terraform

使用Homebrew安装Go语言和Mecurial,从GitHub上下载源代码并进行编译。(由于Mac的ZIP版本[v0.3.7]似乎存在一些微妙的bug,所以源代码看起来更可靠。)

$ brew install hg
$ brew install go
$ echo 'export GOPATH=${HOME}/.golang' >> ~/.bash_profile
$ echo 'export PATH=${PATH}:${GOROOT}/bin:${GOPATH}/bin' >> ~/.bash_profile
$ source ~/.bash_profile
$ git clone https://github.com/hashicorp/terraform ${GOPATH}/src/github.com/hashicorp/terraform
$ cd ${GOPATH}/src/github.com/hashicorp/terraform
$ make updatedeps
$ make dev
$ terraform -version
Terraform v0.4.0-dev (da7f307e5696c640612173368b8faa4bc68e511a)

怎么制作

基本上,按照以下的步骤进行。 , de .)

    • 作業ディレクトリを作成し、そこに定義ファイル群を配置

terraform plan で構築の確認

terraform apply で構築実行

terraform show で確認
破棄する場合は terraform plan –destory で確認
OKなら terraform destroy で破壊

制定定义

创建一个工作目录,并在其中创建两个文件,一个是配置文件,另一个是变量文件。
虽然一个文件也可以,但考虑到后续需要分割的情况,最好从一开始就这样做。

大致上的做法是先定义提供者,然后定义与之相关的资源,并灵活运用变量。更详细的信息请参考官方文档。

另外,配置文件使用的是.tf扩展名,而变量文件使用的是.tfvars扩展名。特别是如果变量使用了.tf扩展名,会导致错误。
可以使用terraform plan命令来预先检查定义是否有问题。

$ mkdir -p ~/terraform/test
$ cd ~/terraform/test
$ vi test.tf
$ vi test.tfvars
$ terraform plan -var-file=test.ifvars
Refreshing Terraform state prior to plan...


The Terraform execution plan has been generated and is shown below.
Resources are shown in alphabetical order for quick scanning. Green resources
will be created (or destroyed and then created if an existing resource
exists), yellow resources are being changed in-place, and red resources
will be destroyed.

Note: You didn't specify an "-out" parameter to save this plan, so when
"apply" is called, Terraform can't guarantee this is what will execute.

+ aws_instance.test01
    ami:                       "" => "ami-XXXXXXXX"
    availability_zone:         "" => "ap-northeast-1X"
    ebs_block_device.#:        "" => "<computed>"
    ephemeral_block_device.#:  "" => "<computed>"
    instance_type:             "" => "t2.micro"
    key_name:                  "" => "XXXXXXXX"
    private_dns:               "" => "<computed>"
    private_ip:                "" => "X.X.X.X"
    public_dns:                "" => "<computed>"
    public_ip:                 "" => "<computed>"
    root_block_device.#:       "" => "<computed>"
    security_groups.#:         "" => "1"
    security_groups.348470369: "" => "sg-XXXXXXXX"
    subnet_id:                 "" => "subnet-XXXXXXXX"
    tags.#:                    "" => "1"
    tags.Name:                 "" => "TAG_NAME"
    tenancy:                   "" => "<computed>"

设定文件

声明变量并分别定义适用于AWS的提供商和适用于EC2实例的资源。
资源以”资源类型 名称”的格式定义,名称可以任意指定。但是,好像不能使用变量化。

variable "access_key" {}
variable "secret_key" {}
variable "key_path" {}
variable "key_name" {}
variable "region" {}

variable "ami" {}
variable "type" {}
variable "name" {}
variable "az" {}
variable "sg" {}
variable "subnet" {}
variable "ip" {}


provider "aws" {
    access_key = "${var.access_key}"
    secret_key = "${var.secret_key}"
    region = "${var.region}"
}

resource "aws_instance" "test01" {
    ami = "${var.ami}"
    instance_type = "${var.type}"
    availability_zone = "${var.az}"
    security_groups = ["${var.sg}"]
    subnet_id = "${var.subnet}"
    private_ip = "${var.ip}"
    key_name = "${var.key_name}"
    tags {
        Name = "${var.name}"
    }
}

变量文件

在设置文件中写入分配给变量的值。
如果文件的扩展名不是.tfvars,则即使通过参数指定也会导致错误。

access_key = "XXXXXXXX"
secret_key = "XXXXXXXX"
key_path = "/path/to/key.pem"
key_name = "XXXXXXXX"
region = "ap-northeast-1"
ami = "ami-XXXXXXXX"
type = "t2.micro"
name = "TAG_NAME"
az = "ap-northeast-1X"
sg = "sg-XXXXXXXX"
subnet = "subnet-XXXXXXXX"
ip = "X.X.X.X"

在执行时,基本的思想是给予变量一个值。因此,在设置内部只需要声明变量,将实际的值准备在变量文件中。

建立

如果terraform plan没有错误,则实际执行建设。
通过-var-file参数指定变量文件。

$ terraform apply -var-file=test.tfvars
aws_instance.test01: Creating...
  ami:                       "" => "ami-XXXXXXXX"
  availability_zone:         "" => "ap-northeast-1X"
  ebs_block_device.#:        "" => "<computed>"
  ephemeral_block_device.#:  "" => "<computed>"
  instance_type:             "" => "t2.micro"
  key_name:                  "" => "XXXXXXXX"
  private_dns:               "" => "<computed>"
  private_ip:                "" => "X.X.X.X"
  public_dns:                "" => "<computed>"
  public_ip:                 "" => "<computed>"
  root_block_device.#:       "" => "<computed>"
  security_groups.#:         "" => "1"
  security_groups.348470369: "" => "sg-XXXXXXXX"
  subnet_id:                 "" => "subnet-XXXXXXXX"
  tags.#:                    "" => "1"
  tags.Name:                 "" => "TAG_NAME"
  tenancy:                   "" => "<computed>"
aws_instance.test01: Creation complete

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

The state of your infrastructure has been saved to the path
below. This state is required to modify and destroy your
infrastructure, so keep it safe. To inspect the complete state
use the `terraform show` command.

State path: terraform.tfstate

在构建后会创建两个文件,分别是 terraform.tfstate 和 terraform.tfstate.backup。

确认

刚才创建的 terraform.tfstate 文件中包含了定义信息,但也可以通过命令进行确认。

$ terraform show
aws_instance.test01:
  id = i-XXXXXXXX
  ami = ami-XXXXXXXX
  availability_zone = ap-northeast-1X
  ebs_block_device.# = 0
  ebs_optimized = false
  ephemeral_block_device.# = 0
  instance_type = t2.micro
  key_name = XXXXXXXX
  private_dns = ip-X-X-X-X.ap-northeast-1.compute.internal
  private_ip = X.X.X.X
  public_dns =
  root_block_device.# = 1
  root_block_device.1234567890.delete_on_termination = true
  root_block_device.1234567890.iops = 0
  root_block_device.1234567890.volume_size = 8
  root_block_device.1234567890.volume_type = standard
  security_groups.# = 1
  security_groups.1234567890 = sg-XXXXXXXX
  subnet_id = subnet-XXXXXXXX
  tenancy = default

由于我们知道实例的ID,所以我们可以尝试使用AWS CLI来确认。

$ aws ec2 describe-instances --instance-ids i-XXXXXXXX --query 'Reservations[].Instances[].{ID:InstanceId,IP:PrivateIpAddress,TYPE:InstanceType,SUBNET:SubnetId,SG:SecurityGroups[0].GroupId,NAME:Tags[?Key==`Name`].Value|[0]}[0]'

{
    "SUBNET": "subnet-XXXXXXXX",
    "NAME": "TAG_NAME",
    "IP": "X.X.X.X",
    "TYPE": "t2.micro",
    "SG": "sg-XXXXXXXX",
    "ID": "i-XXXXXXXX"
}

毀壞

首先确认目标破坏。只需要在terraform plan命令后加上-destroy参数即可。

$ terraform plan -destroy -var-file=test.tfvars
Refreshing Terraform state prior to plan...

aws_instance.test01: Refreshing state... (ID: i-XXXXXXXX)

The Terraform execution plan has been generated and is shown below.
Resources are shown in alphabetical order for quick scanning. Green resources
will be created (or destroyed and then created if an existing resource
exists), yellow resources are being changed in-place, and red resources
will be destroyed.

Note: You didn't specify an "-out" parameter to save this plan, so when
"apply" is called, Terraform can't guarantee this is what will execute.

- aws_instance.test01

若没有问题就破坏。
因为要求确认是否真的可以这样做,所以输入”Yes”。

$ terraform destroy -var-file=test.tfvars
Do you really want to destroy?
  Terraform will delete all your managed infrastructure.
  There is no undo. Only 'yes' will be accepted to confirm.

  Enter a value: yes

aws_instance.test01: Refreshing state... (ID: i-XXXXXXXX)
aws_instance.test01: Destroying...
aws_instance.test01: Destruction complete

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

确认他真的不在了。

$ terraform show

$ aws ec2 describe-instances --instance-ids i-XXXXXXXX --query 'Reservations[].Instances[].[State.Name][]'
[
    "terminated"
]

以上。 .)

广告
将在 10 秒后关闭
bannerAds