LoginSignup
1
0

More than 1 year has passed since last update.

terraform入門メモ

Last updated at Posted at 2022-02-28

terraform入門

terraformチュートリアル(AWS)

tfenvインストール

brew install tfenv

tfenv --version
> tfenv 2.2.2

# 使用可能なバージョン一覧
tfenv list-remote

# 指定バージョンインストール
tfenv install 1.1.5

# 使用バージョン指定
tfenv use 1.1.5

# 現在インストールされているバージョン
tfenv list
> * 1.1.5 (set by /usr/local/Cellar/tfenv/2.2.2/version)

terraform -v
> Terraform v1.1.5
> on darwin_amd64

required_providersについて

required_providersのバージョンは公式のレジストリから確認すると良い
https://registry.terraform.io/providers/hashicorp/aws

  • version = ">= 1.0"は最小バージョン指定。1.0以上
  • version = "~> 3.27"はパッチバージョンのみ許可。3.27.0以上、3.28.0未満
terraform {
  required_version = ">= 1.1.5"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 3.27"
    }
  }
}

provider "aws" {
  profile = "dev-user"
  region  = "ap-northeast-1"
}

tfstateファイルをS3で共有管理するためバケット作成

参考
https://qiita.com/mintak21/items/ecc8d568c2859210c0c4

ECRにイメージプッシュ

参考
https://docs.aws.amazon.com/ja_jp/AmazonECR/latest/userguide/getting-started-cli.html

# ecrログイン
aws ecr get-login-password --region ap-northeast-1 | docker login --username AWS --password-stdin xxxxxxxxxx.dkr.ecr.ap-northeast-1.amazonaws.com

# リポジトリ作成
aws ecr create-repository \
    --repository-name y-oka/nginx \
    --image-scanning-configuration scanOnPush=true \
    --region ap-northeast-1

# タグ作成&push
docker pull nginx:latest
docker tag nginx:latest xxxxxxxxxx.dkr.ecr.ap-northeast-1.amazonaws.com/y-oka/nginx:latest
docker push xxxxxxxxxx.dkr.ecr.ap-northeast-1.amazonaws.com/y-oka/nginx:latest

terraformを触ってみてのQ&A

Q1. 違うユーザーでソース(tfファイル)を更新、applyしたらインフラはどうなる?

A1. 追加で同じインフラが作成される。複数のユーザーでインフラを管理したい場合はtfstateファイルを共有する必要がある

Q2. destroyを使わず特定のインフラを削除したい場合、たとえばドメインをtfファイルから削除したら、そのドメインも消える?

A2. tfstateファイルとtfファイルとの差分で削除される。tfstateファイルで管理されていない場合は削除されない。

Q3. tfファイルのリソース名を変更しても、インフラに影響ない?

A3. 影響ある。リソース名を変更してしまうと、削除→新規作成されてしまう。planで確認する

Q4. tfファイルのリソース内のパラメータを変更しても、インフラへの影響は最小限で済む?

A4. 分からない。planで確認する

Q5. tfファイルとtfstateファイルに差分がある状態でdestroyした場合どうなる?

A5. tfstateに存在するインフラが削除される。

Q6. 既存のインフラをterraformで管理したい場合はどうする?

A6. importコマンドで1つ1つ、tfファイルとtfstateファイルに取り込んでいく必要がある。はじめて管理する場合は「Terraformer」というツールでまとめてインポートしてから修正していくと良さそう。

1
0
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
1
0