3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Terraform 入門:Terraform の最初の一歩として、ローカル環境で "Hello, Terraform!" を試してみた

Posted at

はじめに

Terraform は、インフラをコードで管理するためのツールであり、クラウド環境やローカル環境でのリソース管理を自動化できます。

本記事では、Terraform をローカル環境で試す方法を紹介します。

書こうと思ったきっかけ

Terraform を学び始めた際に、基本的な使い方がまとまっている情報が欲しかったため、自分自身の理解を深める目的も兼ねてまとめました。

特に、初めて Terraform を使う人がスムーズに環境を構築できるように、シンプルな例を用意しました。

Terraform の導入方法

Windows 環境と Mac 環境への導入方法については、以下の記事が分かりやすく解説されているので、参考にしてみてください。

Windows 環境

Mac 環境

Terraform の動作確認

Terraform をインストールしたら、以下のコマンドで動作確認を行います。

terraform -v

バージョンが表示されればインストールが正しく完了しています。

実際のターミナル画面

Screenshot 2025-03-02 at 13.15.20.png

Terraform プロジェクトの作成

Terraform の設定ファイル (.tf ファイル) を作成し、ローカル環境で動作させます。

Terraform のワークスペース準備

まず、新しいディレクトリを作成し、その中に移動します。

mkdir terraform-demo
cd terraform-demo

実際のターミナル画面

Screenshot 2025-03-02 at 13.00.13.png

Terraform 設定ファイルの作成

main.tf を作成し、シンプルな設定を記述します。

provider "local" {}

resource "local_file" "example" {
  filename = "hello.txt"
  content  = "Hello, Terraform!"
}

Terraform の初期化

Terraform を使用する前に、以下のコマンドで初期化を行います。

terraform init

実際のターミナル画面

Screenshot 2025-03-02 at 13.01.58.png

Terraform の実行

リソースの確認

実際にリソースを作成する前に、変更内容を確認できます。

terraform plan

実際のターミナル画面

Screenshot 2025-03-02 at 13.07.16.png

リソースの適用

リソースを作成するには、以下のコマンドを実行します。

terraform apply

実際のターミナル画面

Screenshot 2025-03-02 at 13.08.00.png

途中で yes を入力すると、hello.txt ファイルが作成されます。

実際のターミナル画面

Screenshot 2025-03-02 at 13.09.12.png

リソースの削除

作成したリソースを削除するには、以下のコマンドを実行します。

terraform destroy

実際のターミナル画面

Screenshot 2025-03-02 at 13.09.57.png

こちらも yes を入力すると、hello.txt ファイルが削除されます。

実際のターミナル画面

Screenshot 2025-03-02 at 13.10.38.png

Terraform の設定を管理(おまけ)

Terraform の状態 (terraform.tfstate) を確認することで、管理されているリソースを把握できます。

terraform show

また、設定ファイルのフォーマットを整えたり、構文のバリデーションを行うことも可能です。

terraform fmt
terraform validate

Terraform のプラグインとバックエンド

Terraform は AWS, Azure, GCP などのクラウド環境でも使用可能ですが、ローカル環境で試す場合は local プロバイダーを利用し、terraform.tfstate をローカルで管理します。

リモート環境で状態管理を行いたい場合は、S3 や Terraform Cloud などのバックエンドを利用できます。

まとめ

Terraform は、インフラの管理をコード化することで、環境の再現性や自動化を実現する強力なツールです。本記事では、ローカル環境で Terraform を試す手順を紹介しました。

  • Terraform をインストール
  • terraform-demo ディレクトリを作成し、main.tf を作成
  • terraform init で初期化
  • terraform apply でリソース適用
  • terraform destroy でリソース削除
  • terraform fmt, terraform validate でコード管理

この手順を実行することで、Terraform をローカル環境で試すことができます。ぜひ、自分の環境で実践してみてください!

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?