LoginSignup
1
0

More than 1 year has passed since last update.

Terraform とは

Last updated at Posted at 2021-09-17

Terraform の概要について調べてみる。

Terraform とは?

インフラの構成をコードで宣言できる、IaC(Infrastructure as Code)を実現するツール。
インフラ開発がシンプルかつ高速になる。
AWS, Azure, Google Cloud Platform などに対応。
.tf ファイルと HCL (HashiCorp Configuration Language) により実装。

基本的なコマンド

terraform の操作を行うための基本的なコマンド。

terraform init

ワークスペースを初期化するコマンド、 terraform を実行するのに初期化は必須。
.tf で使用しているプラグインのダウンロードなども走る。

% terraform init
Initializing modules...

Initializing the backend...

Successfully configured the backend "s3"! Terraform will automatically
use this backend unless the backend configuration changes.

Initializing provider plugins...
......

terraform plan

コードを実行すると何が起こるか、リソースがどのように変更されるかを terraform が教えてくれる。

% terraform plan
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
.......
Plan: 1 to add, 0 to change, 0 to destroy.

terraform apply

書いたコードを実際のインフラに適応する。
改めて plan の結果が表示された後、確認が表示される。

% terraform apply
......
Plan: 0 to add, 2 to change, 0 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
......

構成要素

terraform を構成する基本的なブロック。

resource

EC2 インスタンスのようなリソースの定義を行う。

resource "aws_security_group" "ec2" {
   ......
}

variable

変数を定義する。
以下の例ではデフォルト値を設定している、 terraform 実行時に上書きしない場合はこの値が使われる。

variable "region"    { default = "ap-northeast-1" }

locals

ローカル変数を定義できる。
variable と異なりコマンド実行時に上書きできない変数。

locals {
    cf_zone_id = "cfzoneid"
    site_origin_id = "siteoriginid"
}

output

出力値を定義できる。
値は apply 時にターミナルで確認したり別のモジュールから取得したりできる。

output "region" {
    value = var.region
}

data

外部データを参照できる。
以下の例では Amazon Linux 2 の AMI リストを参照している。

data "aws_ami" "recent_amazon_linux_2" {
   ......
}

provider

Terrraform は AWS 以外にも GCO, Azure などに対応しているがその違いを吸収するのがプロバイダ。

provider "aws" {
    region = "us-east-1"
    alias  = "virginia"
}

参考資料

1
0
2

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