Windows環境にTerraformをインストールしてみた

今回は、Terraform始めてみた編です。 超初心者向けのTeraaformを実装するまでの準備を行っていきます。
2022.06.17

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

こんにちは、こんばんは、きだぱんです。

今回は、Terraform始めてみた編です。
超初心者向けのTeraaformを実装するまでの準備を行っていきます。
今回の記事では、コードを書く準備(環境設定)までになっています。

  • Terraformインストール
  • terraformファイル(tfファイル)作成とinit初期化

大まかに、この2点です!

それでは始めていきましょう!

Trraformとは

Terraformとは、簡単に言うとIaC(Infrastructure as Code)ツールの一つです。
Terraformはオープンソースであり、HashiCorpによってGo言語で開発されました。
TerraformではInfrastructure(AWS,GCP,Azureなど)の構成をコードで実現します。
詳しくは、こちらのブログをご覧ください。

Terraformの特性

Terraformはjsonなどのような汎用的なファイル形式で管理するのではなく、独自の拡張子のtfファイルとプログラミング言語で処理を記述します。

Terraformをインストールする

まずはTerraformの公式サイトから、実行ファイルをダウンロードいていきます。
macOS,Windows,Linux,FreeBSD,OpenBSD,Solarisと並んでいますので自分の環境にあったものを選んでいきましょう。
※今回は、Windows環境でおこなっていきます。

Windows版のところから、Windows 10の場合は64-bitを選んでいきます。

Zipファイルがダウンロードされるので、解凍します。
解凍すると、terraform_1.2.2_windows_amd64というフォルダが出てくるので、任意のフォルダに保存します。
今回、私は"C:\Windows\Terraform\terraform__1.2.2_windows_amd64"に保存します。
ここまで来たら、準備は整ったので、コマンドプロンプトを起動し確認していきます。
terraformコマンドを実行してみましょう。

C:\Windows\terraform\terraform_1.2.2_windows_amd64>terraform
Usage: terraform [global options] <subcommand> [args]

The available commands for execution are listed below.
The primary workflow commands are given first, followed by
less common or more advanced commands.

Main commands:
  init          Prepare your working directory for other commands
  validate      Check whether the configuration is valid
  plan          Show changes required by the current configuration
  apply         Create or update infrastructure
  destroy       Destroy previously-created infrastructure

All other commands:
  console       Try Terraform expressions at an interactive command prompt
  fmt           Reformat your configuration in the standard style
  force-unlock  Release a stuck lock on the current workspace
  get           Install or upgrade remote Terraform modules
  graph         Generate a Graphviz graph of the steps in an operation
  import        Associate existing infrastructure with a Terraform resource
  login         Obtain and save credentials for a remote host
  logout        Remove locally-stored credentials for a remote host
  output        Show output values from your root module
  providers     Show the providers required for this configuration
  refresh       Update the state to match remote systems
  show          Show the current state or a saved plan
  state         Advanced state management
  taint         Mark a resource instance as not fully functional
  test          Experimental support for module integration testing
  untaint       Remove the 'tainted' state from a resource instance
  version       Show the current Terraform version
  workspace     Workspace management

Global options (use these before the subcommand, if any):
  -chdir=DIR    Switch to a different working directory before executing the
                given subcommand.
  -help         Show this help output, or the help for a specified subcommand.
  -version      An alias for the "version" subcommand.

インストールされていることが確認できます。
念のため、バージョンも確認しときましょう。terraform -vを実行します。

C:\Users>cd :C:\Windows\Terraform\terraform__1.2.2_windows_amd64

C:\Windows\Terraform\terraform__1.2.2_windows_amd64>terraform -v
Terraform v1.2.2
on windows_amd64

インストール仕立てであれば、最新のものになっているかと思います。

tfファイル作成

S3バケット作成

Terraformのinit作業をします。 initの為にtfstateを保存するS3バケットを用意していきます。
ローカル環境での保存も可能ですが、実際に現場等で作業するとなるとローカルでの管理は少ないかと思いますので、今回はS3バケットに保存していきます。
では、AWSでS3バケットを作成していきます。 リージョンはアジアパシフィック(東京)にします。(後ほど記述しますので自分の指定したリージョンを確認しておきましょう)

パブリックアクセスは特に許可しなくても良いので、そのままブロックにしておきます。
バージョニング設定はどちらでも大丈夫です。

これにて、terraformのすべてを管理するtfstateファイルの箱が完成しました。

tfファイル作成

tfstateファイルを管理するS3バケットが出来たので、次にtfファイルを作成していきます。
※今回はwindows PowerShellにて、tfファイルを作成していきます。
test.tfという名前で進めていきます。(名前は何でも大丈夫です)
New-Item~コマンドを実行します。

PS C:\terraform> New-Item C:\terraform\test.tf
    ディレクトリ: C:\terraform
Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----        2022/06/16     18:16              0 test.tf

作成が完了しました。

S3バケット指定

先ほど作成した.tfファイルのどこに作成するかを指定していきます。 プロバイダーAWSに対して、S3はここを指定してねというコマンドを書きます。
こちらにも詳しく記載されてますので合わせてご覧ください。
下記コマンドを先ほど作成したtest.tfがある直下の環境で実行します。

terraform {
  required_version = ">= 0.13.0"
  backend "s3" {
    bucket = "作成したS3のバケット名" 
    region = "ap-northeast-1" # 東京リージョンに変更
    key = "terraform.tfstate"
  }
}
# プロバイダーの指定をします。今回はAWSを指定(AWS,Azure,GCP等のどれで使いたいかの設定)
provider "aws" {
  region = "ap-northeast-1" # 東京リージョンに変更
}

実行し、無事にproviderで指定したプラットフォームにアクセスし、初期化が成功するとファイルが置いてあるディレクトリに.terraformというファイルが作成されます。
これにて、tfファイルの作成とinit初期化の完了しましたのでコードを書く準備が整いました!

おわりに

ここまで終われば、準備完了です。後はWindows環境で自分の環境にあったInfrastructureをどんどん構成させていきましょう。
私もいろいろ、試してみてます! Terraformに関するブログも沢山展開されていますので、是非こちらもご覧ください。
Terraform の記事一覧 | DevelopersIO

この記事がどなたかのお役に立てば幸いです。