初めてのTerraformチャレンジ

カテゴリ: aws | タグ: ,

Terraformを使ったAWS環境構築を初めて試したとき時のコマンドを備忘録として書いておきます。

作業環境

OS: macOS
terraform: ver1.1.7

インストール

brewでインストールする

brew install hashicorp/tap/terraform

インストールできたか、バージョンを確認

terraform --version

実行結果は下記のとおり

Terraform v1.1.7
on darwin_amd64

awsのクレデンシャルを設定

awsコマンドで設定するか、~/.awsのファイルを直接編集してawsコマンドでアクセスできるようにする。

awsコマンドで設定する場合

aws configure

configureで設定できたか確認する。(useridやaccountが設定したものになっていればOK)

aws sts get-caller-identity

~/.awsのファイルを直接編集する場合

mkdir ~/.aws
touch ~/.aws/config
touch ~/.aws/credentials
  • .aws/configの記入例
[default]
region=ap-northeast-1
output=json
  • .aws/credentialsの記入例
[default]
aws_access_key_id=AKIA....
aws_secret_access_key=...

tfファイルを作成する

terraformはサーバ環境の設定ファイルを*.tfで作成する。

terraformはカレントディレクトリにある全ての*.tfファイルを読み込む。

慣習として、入口になる設定ファイルはmain.tfにすることが多い。

mkdir test01
cd test01

# main.tfの作成
cat <<EOL > main.tf
resource "aws_instance" "myFirstEc2" {
    ami = "ami-0ab0bbbd329f565e6"
    instance_type = "t2.micro"
}

provider "aws" {
    region = "ap-northeast-1"
}
EOL

terraformの初期化

最初にinitで初期化が必要。これによってawsのリソース操作に必要なファイルがダウンロードされる。

terraform init
  • 実行結果
Initializing the backend...

Initializing provider plugins...
- Finding latest version of hashicorp/aws...
- Installing hashicorp/aws v4.8.0...
- Installed hashicorp/aws v4.8.0 (signed by HashiCorp)

Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
you run "terraform init" in the future.

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.

このタイミングでディレクトリ.terraform/と、ファイル.terraform.lock.hclが作成される

more .terraform.lock.hcl

# This file is maintained automatically by "terraform init".
# Manual edits may be lost in future updates.

provider "registry.terraform.io/hashicorp/aws" {
  version = "4.8.0"
  hashes = [
    "h1:....",
    ...
    "zh:..",
  ]
}
find .terraform -type f
.terraform/providers/registry.terraform.io/hashicorp/aws/4.8.0/darwin_amd64/terraform-provider-aws_v4.8.0_x5

事前確認

terraformではインフラに対する変更内容が意図したものかをplanコマンドで事前チェックできる。

terraform plan

結果が1 to addになっているので、1つリソースが作成されることがわかる。

Terraform used the selected providers to generate the following execution plan. 
Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # aws_instance.myFirstEc2 will be created
  + resource "aws_instance" "myFirstEc2" {
      ...

Plan: 1 to add, 0 to change, 0 to destroy.

変更を適用

applyで変更を適用する。

しばらく待つとリソースが作成される。ec2だと30秒ぐらいで、CloudFormationよりかなり速い。

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_instance.myFirstEc2: Creating...
aws_instance.myFirstEc2: Still creating... [10s elapsed]
aws_instance.myFirstEc2: Still creating... [20s elapsed]
aws_instance.myFirstEc2: Still creating... [30s elapsed]
aws_instance.myFirstEc2: Creation complete after 32s [id=i-0c62922a2a38b3aec]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
...

インフラ設定を変更してみる

作ったリソースに対して、以下のような感じでmain.tfへNameのtagを追加してみる

resource "aws_instance" "myFirstEc2" {
    ami = "ami-0ab0bbbd329f565e6"
    instance_type = "t2.micro"
    tags = {
        "Name" = "Ec2Name"
    }
}

provider "aws" {
    region = "ap-northeast-1"
}

変更される内容をを確認

再度planで確認する

terraform plan

tagの追加に関するchangeがin-placeで行われることが事前確認できる

...
Terraform will perform the following actions:

  # aws_instance.myFirstEc2 will be updated in-place
  ~ resource "aws_instance" "myFirstEc2" {
        id                                   = "i-0c62922a2a38b3aec"
      ~ tags                                 = {
          + "Name" = "Ec2Name"
        }

        ...

Plan: 0 to add, 1 to change, 0 to destroy.

再度適用する。これはタグの変更だけなのですぐに実行完了する。

terrafaorm apply

適用結果を確認すると、tagがついていることがわかる

aws ec2 describe-instances | jq ".Reservations[].Instances[].Tags"
[
  {
    "Key": "Name",
    "Value": "Ec2Name"
  }
]

in-placeではない変更を適用する

次はec2のamiを変更してみる。
(AWSでamiを変更するときはインスタンスの再作成が必要になるのでin-placeで変更できない)

gsed -i "s/ami-0ab0bbbd329f565e6/ami-0521a4a0a1329ff86/" main.tf

planすると1つのリソースがdestroyされることがわかる。

terraform plan

...
Plan: 1 to add, 0 to change, 1 to destroy.

applyするとEC2のインスタンスが再作成される。

terraform apply

実行結果を見ると、別のインスタンスIDで新しいインスタンスが生成されている。

...
Plan: 1 to add, 0 to change, 1 to destroy.

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_instance.myFirstEc2: Destroying... [id=i-0c62922a2a38b3aec]
aws_instance.myFirstEc2: Still destroying... [id=i-0c62922a2a38b3aec, 10s elapsed]
aws_instance.myFirstEc2: Still destroying... [id=i-0c62922a2a38b3aec, 20s elapsed]
aws_instance.myFirstEc2: Destruction complete after 30s
aws_instance.myFirstEc2: Creating...
aws_instance.myFirstEc2: Still creating... [10s elapsed]
aws_instance.myFirstEc2: Still creating... [20s elapsed]
aws_instance.myFirstEc2: Still creating... [30s elapsed]
aws_instance.myFirstEc2: Creation complete after 32s [id=i-0123e7523fe579cd9]

Apply complete! Resources: 1 added, 0 changed, 1 destroyed.

リソースの削除

作ったリソースはdestroyで削除できる

terraform destroy

実行結果

aws_instance.myFirstEc2: Refreshing state... [id=i-0123e7523fe579cd9]

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  - destroy

Terraform will perform the following actions:

  # aws_instance.myFirstEc2 will be destroyed
  - resource "aws_instance" "myFirstEc2" {
    - ami                                  = "ami-0521a4a0a1329ff86" -> null
    ...


aws_instance.myFirstEc2: Destroying... [id=i-0123e7523fe579cd9]
aws_instance.myFirstEc2: Still destroying... [id=i-0123e7523fe579cd9, 10s elapsed]
aws_instance.myFirstEc2: Still destroying... [id=i-0123e7523fe579cd9, 20s elapsed]
aws_instance.myFirstEc2: Destruction complete after 30s

Destroy complete! Resources: 1 destroyed.

terraformでの操作履歴

AWSのcloudtrailから何のリソースが操作されたかを確認できる。

設定ファイルのフォーマット

下記のコマンドで書式のフォーマットを合わせられる。
-recursiveオプションを付けるとサブディレクトリも合わせて再帰的に適用できる。

terraform fmt -recursive

Amazonでおトクに買い物する方法
AmazonチャージでポイントGET


Amazonは買いもの前にAmazonギフト券をチャージしてポイントをゲットしないと損!

こちらもおススメ

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です