0
0

More than 3 years have passed since last update.

[aws] terraform インスタンスの作成

Posted at

概要

AWSの環境を作成する上で普段はCloudFormationを使用していましたが、terraformを使用したことがなかったので、本記事でインスタンスの作成まで行い動作確認をしようと思います。

環境

  • MacOS
$ sw_vers
ProductName:    Mac OS X
ProductVersion: 10.15.2
BuildVersion:   19C57

terraformとは

terraformとはCloudFormationと同じ、インフラストラクチャを安全かつ効率的に管理するためのツールです。
コードはHCLというHashiCorp社が設計した言語で実装されています。

事前準備

awsアカウントを作成し、IAMユーザでアクセスキー、シークレットキーを予め作成します。
本手順はここでは割愛します。

Homebrewを使用し、terraformをインストールします。

$ brew install terraform
$ terraform version
Terraform v0.13.5

環境変数にアクセスキー、シークレットキーなどの設定を行います。
実際の値は各自の環境に合わせてください。
アクセスキー・シークレットキーは流出しないよう注意する必要があります。

$ export AWS_ACCESS_KEY_ID=xxxxxxxxxxxxxxxxxxx
$ export AWS_SECRET_ACCESS_KEY=xxxxxxxxxxxxxxx
$ export AWS_DEFAULT_REGION=ap-northeast-1

その後aws-cliコマンドを叩き、自分のawsアカウントが表示されるか確認を行います。

$ aws sts get-caller-identity --query Account --output text

terraform インスタンスの作成

tfファイルを作成し、インスタンスを一つ作成する定義を行います。

main.tf
resource "aws_instance" "example"{
  ami = "ami-0c3fd0f5d33134a76"
  instance_type = "t3.micro"
}

上記コード作成後、terraform initコマンドを実行します。
Terraform has been successfully initialized!と出力されれば成功です。

$ terraform init
Initializing the backend...

Terraform has been successfully initialized!

次に、terraform planコマンドを実行します。
本コマンドは後に変更となるリソース情報などを教えてくれます。

$ terraform plan

terraform applyコマンドで環境のデプロイを行います。
terraform planで実行した内容が再度表示され、Enter a valueと聞かれるのでyesと入力するとリソース作成が実行されます。

$ terraform apply
Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

AWSコンソール画面でインスタンスが作成されていることが確認できます。

インスタンスの編集

上記で作成したインスタンスにタグ付けを行います。
tfファイルを以下の様に編集後、terraform applyを実行します。

resource "aws_instance" "example"{
  ami = "ami-0c3fd0f5d33134a76"
  instance_type = "t3.micro"

  tags = {
    Name = "example"
  }
}
$ terraform apply
  # aws_instance.example will be updated in-place
      ~ tags                         = {
          + "Name" = "example"
        }

AWSコンソール画面でインスタンスにタグが付与されていることを確認できます。

インスタンスの削除

terraformで作成した環境はterraform destoroyコマンドで環境の削除を行うことが可能です。
Do you really want to destroy all resources?と聞かれるため、yesと入力します。

$ terraform destroy

Do you really want to destroy all resources?
  Terraform will destroy all your managed infrastructure, as shown above.
  There is no undo. Only 'yes' will be accepted to confirm.

  Enter a value: yes

AWSコンソール画面で今回作成した環境が削除されていることを確認できます。

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