我尝试使用Terraform来构建EC2实例。(使用了Terraform、AWS、EC2)

Terraform 是一种工具

用代码构建和设置基础设施似乎是为了方便进行。在构建EC2时,使用Terraform可以高效地进行构建。只需创建一个模板,即可在构建其他EC2时重新使用。

可以做的事情

    • ローカル(Mac)にTerraformをインストール

 

    Terraformを利用して、AWSにtestEC2という名前のインスタンスを作成する

前提 tí)

    • ローカルにXcodeインストール済み

 

    • IAMを登録済み(AWSを操作するために、ACCESS_KEY,SECRET_KEYが必要になります。)

 

    • セキュリティグループは既存のものを適用します

 

    キーペアを作成済み

安装Terraform

1. 安装Homebrew

$ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

2. 确认版本

$ brew -v
Homebrew 1.1.11

3. 安装Terraform

$ brew install terraform
==> Downloading https://homebrew.bintray.com/bottles/terraform-0.9.1_1.sierra.bo
######################################################################## 100.0%
==> Pouring terraform-0.9.1_1.sierra.bottle.tar.gz
==> Caveats
zsh completion has been installed to:
  /usr/local/share/zsh/site-functions
==> Summary
?  /usr/local/Cellar/terraform/0.9.1_1: 7 files, 131.6MB

4. 确认版本

$ terraform --version
Terraform v0.9.1

创建模板文件

1. 创建一个用于作业的目录

$ mkdir terraform

创建模板文件

Terraform 模板文件的扩展名为 .tf。

$ cd terraform
$ touch main.tf

记录提供者的设置

在Terraform中,支持多种提供商,因此需要定义使用哪个提供商。

$ vi main.tf
provider "aws" {
    access_key = "ACCESS_KEY"
    secret_key = "SECRET_KEY"
    region = "ap-northeast-1"
}

资源设定

如果想创建VPC,可以使用aws_vpc。如果想创建EC2实例,可以使用aws_instance进行定义。语法为resource “资源类型” “资源名称”。在定义资源后,接下来进行资源设置的流程。有关资源的详细信息请参阅此处 →https://www.terraform.io/docs/providers/aws/index.html

$ vi main.tf
resource "aws_instance" "testEC2" {   
    ami = "ami-eec1c380"  
    instance_type = "t2.micro"   
    key_name = "AWS-takahashi"   
    vpc_security_group_ids = [
      "sg-161a9f71"   
    ]
    associate_public_ip_address = "true"
    root_block_device = {
      volume_type = "gp2"
      volume_size = "20"
    }
    ebs_block_device = {
      device_name = "/dev/sdf"
      volume_type = "gp2"
      volume_size = "10"
    }
    tags {
        Name = "testEC2"
    }
}

output "public ip of testEC2" {
  value = "${aws_instance.testEC2.public_ip}"

整体的感觉是这样的

$ cat main.tf
provider "aws" {
    access_key = "任意のアクセスキー"
    secret_key = "任意のシークレットキー"
    region = "ap-northeast-1"
}

resource "aws_instance" "testEC2" {
    ami = "ami-eec1c380"
    instance_type = "t2.micro"
    key_name = "AWS-takahashi"
    vpc_security_group_ids = [
      "sg-161a9f71"
    ]
    associate_public_ip_address = "true"
    root_block_device = {
      volume_type = "gp2"
      volume_size = "20"
    }
    ebs_block_device = {
      device_name = "/dev/sdf"
      volume_type = "gp2"
      volume_size = "10"
    }
    tags {
        Name = "testEC2"
    }
}

output "public ip of testEC2" {
  value = "${aws_instance.testEC2.public_ip}"
}

在亚马逊云上构建!

在那之前,我們需要確認一下模板是否沒有錯誤。

只需检查设置在块中的参数错误,即使指定不存在的ami等,在执行terraform plan时也不会报错!

$ 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.

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. Cyan entries are data sources to be read.

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.testEC2
    ami:                                               "ami-eec1c38"
    associate_public_ip_address:                       "true"
    availability_zone:                                 "<computed>"
    ebs_block_device.#:                                "1"
    ebs_block_device.2659407853.delete_on_termination: "true"
    ebs_block_device.2659407853.device_name:           "/dev/sdf"
    ebs_block_device.2659407853.encrypted:             "<computed>"
    ebs_block_device.2659407853.iops:                  "<computed>"
    ebs_block_device.2659407853.snapshot_id:           "<computed>"
    ebs_block_device.2659407853.volume_size:           "10"
    ebs_block_device.2659407853.volume_type:           "gp2"
    ephemeral_block_device.#:                          "<computed>"
    instance_state:                                    "<computed>"
    instance_type:                                     "t2.micro"
    ipv6_addresses.#:                                  "<computed>"
    key_name:                                          "AWS-takahashi"
    network_interface_id:                              "<computed>"
    placement_group:                                   "<computed>"
    private_dns:                                       "<computed>"
    private_ip:                                        "<computed>"
    public_dns:                                        "<computed>"
    public_ip:                                         "<computed>"
    root_block_device.#:                               "1"
    root_block_device.0.delete_on_termination:         "true"
    root_block_device.0.iops:                          "<computed>"
    root_block_device.0.volume_size:                   "20"
    root_block_device.0.volume_type:                   "gp2"
    security_groups.#:                                 "sg-161a9f71"
    source_dest_check:                                 "true"
    subnet_id:                                         "<computed>"
    tags.%:                                            "1"
    tags.Name:                                         "testEC2"
    tenancy:                                           "<computed>"
    vpc_security_group_ids.#:                          "<computed>"


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

2. 开始建构!

$ terraform apply

顺便提一下,如果指定了不存在的ami,会出现这样的错误!

Error applying plan:

1 error(s) occurred:

* aws_instance.testEC2: 1 error(s) occurred:

* aws_instance.testEC2: InvalidAMIID.NotFound: The image id '[ami-takahashiiiii]' does not exist
    status code: 400, request id: 6a9d7118-5f23-4cae-9521-0ccc47cc775e

Terraform does not automatically rollback in the face of errors.
Instead, your Terraform state file has been partially updated with
any resources that successfully completed. Please address the error
above and apply again to incrementally change your infrastructure.

在AWS控制台上确认!

スクリーンショット 2017-03-26 19.25.47.png

输出

在main.tf的底部,有一个名为output的块,它用于在构建过程中显示希望了解的信息到控制台上。
这次我尝试将IP地址显示出来。
语法如下:output “<要输出的属性描述>” { value = “<要输出的属性值>” }

可以这样写…

$ vi main.tf
output "public ip of testEC2" {
  value = "${aws_instance.testEC2.public_ip}"

变成了这个样子↓!

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

Outputs:

public ip of testEC2 = 54.250.156.45```

最后

使用一个命令来创建EC2真是太方便了!而且还可以将模板文件分开,使用变量将访问密钥、秘密密钥等保存在不同的文件中。这次只进行了EC2的创建,下次可以试试创建vpc和安全组!

广告
将在 10 秒后关闭
bannerAds