6
2

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 コマンドチートシート

Last updated at Posted at 2023-08-28

背景

業務でterraformを使ってAWSリソースをデプロイする機会が増えてきたので、自分用の備忘録としてコマンドチートシートを作成しました。

terraformとは何か

20200605_002206_01.png

Terraformとは、 HashiCorp社によって開発された オープンソースのサービス で、 開発環境を効率的に構築できるIaC(Infrastructure as Code)ツールの一種です。クラウドサーバーなどシステム開発に必要なインフラを、コードを記述することにより自動で構築できます。また、インフラの構成管理などもTerraformのコードによる宣言が可能な事も特徴です。

コマンド

# バージョン確認
$ terraform -v
# 初期化
$ terraform init

➡terraform作業ディレクトリの初期化 ※一番最初に実施すること
 .tf ファイルで利用している pluginのダウンロード処理等が走る
 このコマンドは複数回実行しても問題ありません。

# バックエンドをローカルからS3に移行

$ terraform init -migrate-state
 ⇒ 既存の状態を保ちながら、バックエンドを更新するオプション

# terraform init -reconfigure
 ⇒ 既存の状態を保持せずバックエンドを更新するオプション
# コードのフォーマット調整
$ terraform fmt
# サブディレクトリも含める
$ terraform fmt -recursive
# リソース確認
$ terraform plan

# 個別にリソース確認
$ terraform plan -target={resource}

# ファイル出力(色文字コード抜き)
$ terraform plan -no-color > nocolor.txt
# リソース投入
$ terraform apply

# 個別にリソース投入
$ terraform apply -target={resource}

# リソース投入(強制yes)
$ terraform apply -auto-approve
# リソース削除確認
$ terraform plan -destory
# リソース削除
$ terraform destory

# リソース削除(強制yes)
$ terraform destory -auto-approve
# 現在のリソースの状態(中身)を確認
$ terraform show
# tfstateで管理しているリソース一覧表示
$ terraform state list
# tfstate管理からリソースを削除
$ terraform state rm ${リソース名}
# tfstate管理に既存リソースを追加
$ terraform import ${tfstate上で管理したい名前} ${リソース名}
# 特定のモジュールのみ実行
$ terraform [plan|apply|destroy] -target=module.${モジュール名}
# outputに記載された内容を出力
$ terraform output

おまけ

# terraform コマンド省略(エイリアス)
$ alias tf = 'terraform'
➡これで若干コマンドを短くできます。
 例)tf state list
6
2
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
6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?