0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Terraform学習記録(terraform、provider、data、resouce、output)

0
Last updated at Posted at 2025-08-17

使用教材

terrafrom

  • terraformはAWSだけでなくAzureやGCPなどのマルチクラウド対応している
  • terraform本体とは別に各クラウドサービスに対応したモジュールが用意されている
  • それぞれバージョンが違うため、terraformブロックでバージョン指定する
terraform {
  required_version = "value" #terraformのバージョン指定
  required_providers {
    aws = {
        source = "hashicorp/aws" #terraformのawsプロバイダーを取り込み
        version = "~> 5.0" #5.0以上のバージョン
    }
    random = {
        source = "hashicorp/random" #もし、S3のバケット名やリソース名などにランダムで一意の値を付けたい場合はこのプロバイダーを取り込む
        version = ">=3.5.0" #3.5.0以下のバージョン
     }
  }
}

provider

  • リージョンの指定ができる
provider "aws" {
  region = "ap-northeast-1" #東京リージョン
}

data

  • terraform以外で作成したリソースを参照したい場合に使用する
  • 参照したいリソースによって記述内容が異なる
  • 例えばデフォルトVPCを使用したい場合
data "aws_vpc" "default" {
  default = true
}

resouce

  • 作成したいリソースを指定
  • 例えばランダムプロバイダーで作成した値をS3バケット名に設定したい場合
#取り込んだrandomプロバイダーで生成する値の形式指定
resource "random_string" "suffix" {
    length = 6 #文字数
    upper = false #大文字アルファベット
    lower = true #小文字アルファベット
    number = true #数字
    special = false #記号
}

#S3を作成する
resource "aws_s3_bucket" "sample" {
  bucket = "my-bucket-${random_string.suffix.result}" #ここで生成された値を代入する
}

output

  • terraformの変数を外部から参照させたい場合に記述
  • 同一ファイル内での参照であればアドレス指定でoutputブロックは不要
#S3バケットのバケット名を外部参照できるようにアウトプット
output "s3_bucketname" {
  value = aws_s3_bucket.sample.bucket
}
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?