LoginSignup
2
3

More than 1 year has passed since last update.

TerraformでAWSリソースをデプロイしてみる

Last updated at Posted at 2022-11-27

お仕事で使う機会があったのでメモ📝

1.AWS環境の設定

AWS環境へのデプロイなので、端末の下準備が必要です。

①CLIインストール
端末でAWSのコマンドが通るように設定します。
https://docs.aws.amazon.com/ja_jp/cli/latest/userguide/getting-started-install.html

②profileの設定
クレデンシャルがTerraformコードに内に直書きにならないよう、
AWSアカウントを端末側に設定します。

今回はqiita-deployというprofile名で設定します。

aws configure --profile qiita-deploy

この後対話形式になるので、クレデンシャルを登録していきましょう。
リージョンはap-northeast-1、formatは空欄のままでOKです。

■proflie確認コマンド
・profile一覧

aws configure list-profiles

・該当profile確認

aws sts get-caller-identity --profile qiita-deploy

2.Terraformでのデプロイ

①Terraformインストール
brewでインストールします。

※brewが導入されてない人はこちらへ。
https://brew.sh/index_ja

brew install terraform

②デプロイ用ファイルの作成
下記3ファイルを作成します。

1.デプロイ対象ファイルの作成
とりあえずEC2だけデプロイするので、EC2に関する記述だけ記載します。
他にも指定したい項目がある場合は適宜追加してください。

qiita-deploy.tf
resource "aws_instance" "qiita-deploy" {
    ami = "ami-XXXXXXXXXX"
    instance_type = "t1.micro"
}

2.provider.tfの作成
デプロイ先(AWS)の取得情報を記載します。

provider.tf
variable "aws_shared_credentials_file" {
  type = string
}
variable "aws_profile" {
  type = string
}
variable "aws_region" {
  type = string
}

provider "aws" {
  shared_credentials_file = var.aws_shared_credentials_file
  profile                 = var.aws_profile
  region                  = var.aws_region
}

3.terraform.tfvars
2.の取得先になる変数ファイルを作成します。

terraform.tfvars
aws_shared_credentials_file = "~/.aws/credentials"
aws_profile  = "qiita-deploy"
aws_region  = "ap-northeast-1"

③デプロイ
1.ワークスペースの初期化

terraform init

2.デプロイの事前確認
applyが正しくできるか確認します。

terraform plan

※ここで下記Warning(属性の非推奨)が出る場合がありますが、次へ進んでOKです。
・Warning: Argument is deprecated
・Warning: Attribute Deprecated

おそらくcredentialsという文字列に反応してくれてるのではないかと思います。

3.デプロイ
ここでAWSへ②-1で記載したインスタンスがデプロイされます。

terraform apply

※削除する場合

terraform destroy

以上です:relaxed:

2
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
2
3