Terraformを開始するシンプルな手順

Terraform

はじめに

今回は、Terraformを開始する手順をシンプルに確認していきます。

Terraformとは?

Terraformとは、IaC(Infrastructure as Code)を実現するOSSの一種で、インフラの構成をコードで管理、運用することをサポートしてくれます。

近年では、DevOpsが当たり前になり、その運用を実現するために必要不可欠となる”インフラのコード化”は、インフラエンジニアの必須知識となっています。

特にクラウドシェアトップのAWSにおいて、IaCを実現する技術には、以下の代表的な3つがあります。

  • AWS CloudFormation
  • AWS CDK
  • Terraform

その中でもTerraformは世界的にも広く使われており、様々なプロバイダー(AWS,Azure,GCP等)に利用できる点で優れています。

※他の選択肢には、別の利点があるため、一概にTerraformがよいとは言えません

手順

では、早速、手順を確認していきましょう。

※手順のメモを紹介します。ベストプラクティスや仔細は、公式ドキュメント等を確認するようにしましょう。

AWS | Terraform | HashiCorp Developer
Build, change, and destroy AWS infrastructure using Terraform. Step-by-step, command-line tutorials will walk you throug...

以下に、実際に実行する流れを記載します。

  1. tfenvをインストール
  2. プロジェクトフォルダを作成
  3. 使用バージョンを決めてインストール
  4. 使用バージョンを指定
  5. 初期化
  6. Terraformファイルの作成
  7. コードの記述
  8. リソース作成前に確認
  9. リソースをデプロイする
  10. リソースを削除する

AWSであれば、AWSアカウント及び認証情報の設定は必要ですので対応しておきましょう。

の設定 AWS CLI - AWS Command Line Interface
が とやり取り AWS CLI するために使用する設定を構成します AWS。

tfenvをインストール

$ brew install tfenv
GitHub - tfutils/tfenv: Terraform version manager
Terraform version manager. Contribute to tfutils/tfenv development by creating an account on GitHub.

プロジェクトフォルダを作成

$ touch Terraformtest
$ cd Terraformtest $ code .

codeコマンドは、エディタにVScodeを使っている場合に使用できる便利な機能。

Running Visual Studio Code on macOS
Get Visual Studio Code up and running on Mac (macOS).

使用バージョンを決めてインストール

$ tfenv list-remote
$ tfenv install 0.13.6

M1macはエラーが出るので以下を入力

$ TFENV_ARCH=amd64 tfenv install 0.13.6

使用バージョンを指定

$ tfenv use 0.13.6
$ terraform --version

Terraformファイルの作成、必要なコードの記述

$ touch hogehoge.tf

上記で作成したファイルに、試しに以下を記載

# providerを指定
provider "aws" { 
    region = "eu-west-1"
}
# 作成するVPCを定義
resource "aws_vpc" "this" {
    cidr_block = "10.0.0.0/16"
    tags = { 
        "Name" = "sample_vpc"
    }
}

初期化

$ terraform init

初期化が走り、指定したproviderに応じた必要なファイルが生成される。

Command: init | Terraform | HashiCorp Developer
The terraform init command initializes a working directory containing configuration files and installs plugins for requi...

リソース作成前に確認

$ terraform plan

リソースを実際に作成(terraform apply)する前に、実行した場合の作成内容を確認できる。

Command: plan | Terraform | HashiCorp Developer
The terraform plan command creates an execution plan with a preview of the changes that Terraform will make to your infr...

リソースをデプロイする

$ terraform apply

実際に定義したリソースが作成されます。
AWSのマネジメントコンソールを開き、リソースが作成されていることを確認します。

Command: apply | Terraform | HashiCorp Developer
The terraform apply command executes the actions proposed in a Terraform plan to create, update, or destroy infrastructu...

リソースを削除する

$ terraform destroy

作成したリソースが綺麗に削除されます。

Command: destroy | Terraform | HashiCorp Developer
The terraform destroy command destroys all objects managed by a Terraform configuration.

おわりに

準備を整えられたら、実際にコードを書いて試していきたいです。

最後までご覧いただきありがとうございました。

コメント

タイトルとURLをコピーしました