TerraformのGetting Startedをやってみた 〜インストールから作成、変更、削除まで〜

2018.08.01

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

ご機嫌いかがでしょうか、豊崎です。

CloudFormation派でしたがTerraform使ってみたので、インストールから作成、変更、削除までを備忘的に書き残しておきたいと思います。

基本的にGetting Startedを参考にして進めております。

https://www.terraform.io/intro/getting-started/install.html

それでは早速試して行きます。

インストールから初期化まで

今回はmacにTerraformをインストールしていこうと思います。 こちらからmacOS用のバイナリパッケージをダウンロードします。

$ mkdir ~/terraform
$ cd ~/terraform
$ curl -sL https://releases.hashicorp.com/terraform/0.11.7/terraform_0.11.7_darwin_amd64.zip > terraform.zip
$ unzip terraform.zip
Archive:  terraform.zip
  inflating: terraform
$ export PATH=$PATH:~/terraform/

これでパスが通ったと思いますので、terraformコマンドを実行してみます。 これでインストールは完了です。

$ terraform
Usage: terraform [--version] [--help] <command> [args]

The available commands for execution are listed below.
The most common, useful commands are shown first, followed by
less common or more advanced commands. If you're just getting
started with Terraform, stick with the common commands. For the
other commands, please read the help and docs before usage.

Common commands:
    apply              Builds or changes infrastructure
    console            Interactive console for Terraform interpolations
    destroy            Destroy Terraform-managed infrastructure
    env                Workspace management
    fmt                Rewrites config files to canonical format
    get                Download and install modules for the configuration
    graph              Create a visual graph of Terraform resources
    import             Import existing infrastructure into Terraform
    init               Initialize a Terraform working directory
    output             Read an output from a state file
    plan               Generate and show an execution plan
    providers          Prints a tree of the providers used in the configuration
    push               Upload this Terraform module to Atlas to run
    refresh            Update local state file against real resources
    show               Inspect Terraform state or plan
    taint              Manually mark a resource for recreation
    untaint            Manually unmark a resource as tainted
    validate           Validates the Terraform files
    version            Prints the Terraform version
    workspace          Workspace management

All other commands:
    debug              Debug output management (experimental)
    force-unlock       Manually unlock the terraform state
    state              Advanced state management

IAMユーザを作成してアクセスキー、シークレットキーを発行しておきましょう。

以下のファイルを ~/terraform/example.tf として作成します。

provider "aws" {
  access_key = "事前に用意していたACCESS_KEY"
  secret_key = "事前に用意していたSECRET_KEY"
  region     = "us-east-1"
}

resource "aws_instance" "example" {
  ami           = "ami-2757f631"
  instance_type = "t2.micro"
}

providerブロックの{}の前で、AWSを使っていることを記述しています。 中にはawsで利用するアクセスキー、シークレットキー、リソースを作成するリージョンを指定します。

resourceブロックの{}の前では リソースタイプとリソース名を記載しています。 リソースタイプが"aws_instance"で、リソース名が"example"となります。 ちなみに、リソースタイプのプレフィックスのaws部分は上述のproviderにマッピングされるので、ここでは"aws"providerで管理されているリソースであるということになります。

次に初期化をします。 以下のコマンドを実行しました。

$ terraform init

Initializing provider plugins...
- Checking for available provider plugins on https://releases.hashicorp.com...
- Downloading plugin for provider "aws" (1.29.0)...

The following providers do not have any version constraints in configuration,
so the latest version was installed.

To prevent automatic upgrades to new major versions that may contain breaking
changes, it is recommended to add version = "..." constraints to the
corresponding provider blocks in configuration, with the constraint strings
suggested below.

* provider.aws: version = "~> 1.29"

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.

リソースの作成、変更、削除

続いてファイルに記述した内容を作成してみましょう。以下のようにコマンドを実行します。 左側に「+」がついているリソースが作成されます。今回は作成だけですが、削除されるリソースあった場合は「-」と表示されます。 Gitのdiffみたいな感じです。

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

  + aws_instance.example
      id:                           <computed>
      ami:                          "ami-2757f631"
      associate_public_ip_address:  <computed>
      availability_zone:            <computed>
      cpu_core_count:               <computed>
      cpu_threads_per_core:         <computed>
      ebs_block_device.#:           <computed>
      ephemeral_block_device.#:     <computed>
      get_password_data:            "false"
      instance_state:               <computed>
      instance_type:                "t2.micro"
      ipv6_address_count:           <computed>
      ipv6_addresses.#:             <computed>
      key_name:                     <computed>
      network_interface.#:          <computed>
      network_interface_id:         <computed>
      password_data:                <computed>
      placement_group:              <computed>
      primary_network_interface_id: <computed>
      private_dns:                  <computed>
      private_ip:                   <computed>
      public_dns:                   <computed>
      public_ip:                    <computed>
      root_block_device.#:          <computed>
      security_groups.#:            <computed>
      source_dest_check:            "true"
      subnet_id:                    <computed>
      tenancy:                      <computed>
      volume_tags.%:                <computed>
      vpc_security_group_ids.#:     <computed>


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

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」と入力してEnterを押します。

  Enter a value: yes

aws_instance.example: Creating...
  ami:                          "" => "ami-2757f631"
  associate_public_ip_address:  "" => "<computed>"
  availability_zone:            "" => "<computed>"
  cpu_core_count:               "" => "<computed>"
  cpu_threads_per_core:         "" => "<computed>"
  ebs_block_device.#:           "" => "<computed>"
  ephemeral_block_device.#:     "" => "<computed>"
  get_password_data:            "" => "false"
  instance_state:               "" => "<computed>"
  instance_type:                "" => "t2.micro"
  ipv6_address_count:           "" => "<computed>"
  ipv6_addresses.#:             "" => "<computed>"
  key_name:                     "" => "<computed>"
  network_interface.#:          "" => "<computed>"
  network_interface_id:         "" => "<computed>"
  password_data:                "" => "<computed>"
  placement_group:              "" => "<computed>"
  primary_network_interface_id: "" => "<computed>"
  private_dns:                  "" => "<computed>"
  private_ip:                   "" => "<computed>"
  public_dns:                   "" => "<computed>"
  public_ip:                    "" => "<computed>"
  root_block_device.#:          "" => "<computed>"
  security_groups.#:            "" => "<computed>"
  source_dest_check:            "" => "true"
  subnet_id:                    "" => "<computed>"
  tenancy:                      "" => "<computed>"
  volume_tags.%:                "" => "<computed>"
  vpc_security_group_ids.#:     "" => "<computed>"
aws_instance.example: Still creating... (10s elapsed)
aws_instance.example: Still creating... (20s elapsed)
aws_instance.example: Still creating... (30s elapsed)
aws_instance.example: Creation complete after 31s (ID: i-xxxxxxxxxxxxxxxx)

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

EC2が起動しました。今回作成したのは1台だったので31秒で適用が完了しました。らくちんでした。 VPCの指定をしていなかったので、デフォルトVPCにEC2が作成されました。

また、状態ファイルとして実行したディレクトリに「terraform.tfstate」というステートファイルができています。 catコマンドで中を参照するとリソースの情報が見えます。terraformのコマンドでいうと「terraform show」で情報を参照可能です。

続いて、変更してみます。 今回はAMIの変更を行ってみます。

provider "aws" {
  access_key = "<事前に用意していたACCESS_KEY>"
  secret_key = "<事前に用意していたSECRET_KEY>"
  region     = "us-east-1"
}

resource "aws_instance" "example" {
  ami           = "ami-b374d5a5"
  instance_type = "t2.micro"
}

適用してみると、new resourceと書いてあるので、EC2の作り変えが発生することがわかります。 「yes」で実行してみましょう。 ※変更内容によってリソースの挙動は異なります。

$ terraform apply
aws_instance.example: Refreshing state... (ID: i-0c349399b0a9eccd8)

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

Terraform will perform the following actions:

-/+ aws_instance.example (new resource required)
      id:                           "i-0c349399b0a9eccd8" => <computed> (forces new resource)
      ami:                          "ami-2757f631" => "ami-b374d5a5" (forces new resource)
      ・
      ・
      <中略>
      ・
      ・
Plan: 1 to add, 0 to change, 1 to destroy.

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

  Enter a value:

既存EC2を削除+新しいEC2を作成しています。

aws_instance.example: Destroying... (ID: i-0c349399b0a9eccd8)
・
<中略>
・
aws_instance.example: Destruction complete after 55s
aws_instance.example: Creating...
  ami:                          "" => "ami-b374d5a5"
  associate_public_ip_address:  "" => "<computed>"
 ・
 ・

AWSマネジメントコンソールで確認するとこんな感じです。こちらも、らくちんでした。

最後にリソースの削除をしてみたいと思います。 これも非常に簡単で、以下コマンドを実行するだけです。

$ terraform destroy
aws_instance.example: Refreshing state... (ID: i-0d716454024e9a497)

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

Terraform will perform the following actions:

  - aws_instance.example


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

Do you really want to destroy?
  Terraform will destroy all your managed infrastructure, as shown above.
  There is no undo. Only 'yes' will be accepted to confirm.

  Enter a value:

内容を確認して、問題なければ同様に「yes」を入力してEnterを押しましょう。

  Enter a value: yes

aws_instance.example: Destroying... (ID: i-0d716454024e9a497)
aws_instance.example: Still destroying... (ID: i-0d716454024e9a497, 10s elapsed)
aws_instance.example: Still destroying... (ID: i-0d716454024e9a497, 20s elapsed)
aws_instance.example: Still destroying... (ID: i-0d716454024e9a497, 30s elapsed)
aws_instance.example: Still destroying... (ID: i-0d716454024e9a497, 40s elapsed)
aws_instance.example: Still destroying... (ID: i-0d716454024e9a497, 50s elapsed)
aws_instance.example: Destruction complete after 56s

Destroy complete! Resources: 1 destroyed.

また、少し待つとリソースの削除が完了します。

さいごに

遅ればせながら初めてTerraform触りましたが、わかりやすく、使いやすかったです。今回はGetting Startedを試しましたが、感覚が掴めたので色々触ってみたいと思います。