Ikkyu's Tech Blog

技術系に関するブログです。

Terraformをちょっと触ってみた。

最近Terraformという言葉を聞くことが多くなり、 だいたいやってることは想像できるけど...でもちゃんと調べておこうと思ったのがきっかけです。

今回はBuild Infrastructure | Terraform - HashiCorp Learnを参考に

  1. Terraformをインストール
  2. AWSでEC2インスタンスを作成
  3. 作成したインスタンスを削除

までやりました。 その時「調べたこと」や「やったこと」をメモしたものになります。

環境

前提

  • Homebrewのインストールしている
  • AWSのアカウントを作成している
  • AWS CLIのインストールしている
  • AWS IAMでユーザを作成している

以上を前提に説明してますので、準備できてない人は申し訳ないのですがググってください。。 いい記事いっぱいあるので、すぐ準備ができると思います。😅 (こういう導入的な記事もあった方がいいのかもな。。)

Terraformとは?

HashiCorp社が開発した、インフラストラクチャを安全に効率的に構築・変更・バージョニングするためのツール

具体的には、HCL(HashiCorp Configuration Language)を使用して、構築したいインフラストラクチャを定義します。 CLIを使い、クラウドにデプロイする流れです。

公式サイトを見ると、以下のクラウドサービスに対応しているようです。

  • AWS
  • Azure
  • GCP
  • Terraform Cloud

Terraformをインストール

Homebrew を使用してインストールします。

$ brew install terraform
==> Downloading https://homebrew.bintray.com/bottles/terraform-0.12.20.catalina.
==> Downloading from https://akamai.bintray.com/25/25c7620a0343e13244b141db9aea3
######################################################################## 100.0%
==> Pouring terraform-0.12.20.catalina.bottle.tar.gz
🍺  /usr/local/Cellar/terraform/0.12.20: 6 files, 50.2MB

terraformコマンドが使用できるか確認してみます。

$ terraform -v
Terraform v0.12.20

AWSでEC2インスタンスを作成

設定ファイル作成

$ touch example.tf

参考:

provider "aws" {
  profile = "default"
  region  = "us-east-1"
}

resource "aws_instance" "example_terraform" {
  ami = "ami-062f7200baf2fa504"
  instance_type = "t2.micro"
}

初期化

initコマンドを使用して、必要なプラグインをダウンロードします。

$ terraform init

Initializing the backend...

Initializing provider plugins...
- Checking for available provider plugins...
- Downloading plugin for provider "aws" (hashicorp/aws) 2.47.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 = "~> 2.47"

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.

.terraform/pluginsに必要なプラグインが保存されました。

プラグインのversionを指定しておくと良いとのことなので追加します。

provider "aws" {
  version = "~> 2.10" // 追加
  profile = "default"
  region  = "us-east-1"
}

resource "aws_instance" "example_terraform" {
  ami = "ami-062f7200baf2fa504"
  instance_type = "t2.micro"
}

フォーマット

fmtコマンドを使用することで、フォーマットしてくれるみたいです。 git commit前にやっておくとよさそうです。

$ terraform fmt
example.tf
provider "aws" {
  version = "~> 2.10"
  profile = "default"
  region  = "us-east-1"
}

resource "aws_instance" "example_terraform" {
  ami           = "ami-062f7200baf2fa504"
  instance_type = "t2.micro"
}

見易くなりました!!!これはいいですね!!!

バリデート

validateコマンドを使用して、作成したtfファイルを検証します

$ terraform validate
Success! The configuration is valid.

デプロイ

applyコマンドを使用してデプロイします。

$ 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_terraform will be created
  + resource "aws_instance" "example_terraform" {
      + ami                          = "ami-062f7200baf2fa504"
      ...
    }

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

aws_instance.example_terraform: Creating...
aws_instance.example_terraform: Still creating... [10s elapsed]
aws_instance.example_terraform: Still creating... [20s elapsed]
aws_instance.example_terraform: Still creating... [30s elapsed]
aws_instance.example_terraform: Creation complete after 33s [id=i-0e49c17dbc1555de1]

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

コンソールで確認してみます。

f:id:Ikkyu:20200202002024p:plain
AWSのコンソール画面

できました!!

作成したインスタンスを削除

削除には、destroyコマンドを使用します。

$ terraform destroy                                                             1m
aws_instance.example_terraform: Refreshing state... [id=i-0e49c17dbc1555de1]

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_terraform will be destroyed
  - resource "aws_instance" "example_terraform" {
      - ami                          = "ami-062f7200baf2fa504" -> null
      ...
    }

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

Do you really want to destroy all resources?
  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

aws_instance.example_terraform: Destroying... [id=i-0e49c17dbc1555de1]
aws_instance.example_terraform: Still destroying... [id=i-0e49c17dbc1555de1, 10s elapsed]
aws_instance.example_terraform: Still destroying... [id=i-0e49c17dbc1555de1, 20s elapsed]
aws_instance.example_terraform: Destruction complete after 23s

Destroy complete! Resources: 1 destroyed.

できました!

コンソールで確認してみます。

f:id:Ikkyu:20200202002623p:plain
AWSのコンソール画面

削除できています。

以上です。 かなり使いやすいなーと思いました。

今年はサイトを作ってみようと思うので、その時にTerraformを使ってみようと思います。