けけずんセルフハッキング

エンジニアっぽい雰囲気を醸しだしているかのようなブログです!

Terraform使ってみる(1) 〜 インストールして動かしてみる編

概要

いつも簡単なインフラばかり構築してたからコード化する必要ないよねって思ってたけど、最近それすら億劫になっている。 というわけで今更だけどTerraformを使ってみるよ。

Terraformのインストール

公式サイト的なのはこちら。

HashCorp Learn - Install Terraform

ひとまずコマンド実行。

$ brew tap hashicorp/tap
$ brew install hashicorp/tap/terraform

インストールされたか確認する。

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

...

ヘルプっぽいものが表示されたからおそくら大丈夫でしょう。

Terraformで最低限のAWSインフラ作る

公式サイト的なのの手順に従ってAWSでインフラ作っていこう。

HashCorp Learn - Build Infrastructure

事前準備

以下の手順を済ませておく。

設定ファイルの作成と初期化

作業用のフォルダを作成し、その下に移動する。

$ mkdir terraform-example
$ cd terraform-example

設定ファイルを以下の内容で作成する。 今回はEC2インスタンスを一台立ち上げるだけ。

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 2.70"
    }
  }
}

provider "aws" {
  profile = "default"
  region = 'ap-northeast-1"
}

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

以下のコマンドでそれぞれコードの整形と設定の検証してくれる。

$ terraform fmt
$ terraform validate
Success! The configuration is valid.

初期化処理を実行する。

$ terraform init

Initializing the backend...

Initializing provider plugins...
- Finding hashicorp/aws versions matching "~> 2.70"...
- Installing hashicorp/aws v2.70.0...
- Installed hashicorp/aws v2.70.0 (signed by HashiCorp)

terraform init を実行すると .terraform というフォルダが作成される。 terraform init は設定ファイルを作成した際や、gitなど既存の設定ファイルをcheckoutした際に実行すればよいらしい。

インフラの作成

以下のコマンドを実行するとAWS上にインフラが構築される。

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

  # ここに作成されるリソースが一覧される
  + resource "aws_instance" "example" {
      + ami = "ami-830c94e3"
      + arn = (known after apply)
      ...略
    }

...略

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

ここでAWSのコンソールを見てみるとEC2インスタンスが作成されている、すごい。

Terraformその他コマンド

インフラの更新

更新は設定ファイルを書き換えた後、terraform apply を再度実行するだけ。 このときに差分が見れるので、差分を見ながら問題がなければ yes と入力して実行する。

インフラの詳細確認

以下のコマンドで作成したリソースの情報を表示できる。

$ terraform show

インフラの削除

以下のコマンドで作成したリソースの削除ができる。

$ terraform destroy

おわりに

Terraformの基本的な使い方だけ書いた。 設定ファルで変数を使用したり、モジュール化したりなど色々なことができるらしいので、次回はそれを触ってみたい。