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をGitHubに公開する際の注意事項

Last updated at Posted at 2025-06-29

はじめに

アウトプットのアピールの為、GitHubにIacを公開しようとした際にセキュリティ面から考慮しなければならない点をメモとして残していこうと思います。

.gitignoreの記述

以下のファイルをGitHubへのプッシュの対象から除く

# Terraform state

## 機密情報が含まれる可能性ありのファイル
## →RDS,SecretsManager,SSMなどの値が含まれる
## →複数人の開発時にステートファイルの競合が起こる可能性がある

*.tfstate
*.tfstate.backup

## .terraform内部ディレクトリ
## →プラットフォーム依存のバイナリが含まれ再現性や移植性が下がる(実行環境特有の内容が含まれる)
## →容量もかなり大きくGitには不向きであり、一時ファイルであるため

.terraform/

## Terraformがクラッシュした際のログ
## デバックの際に活用するもので、パスワードなどの機密情報を含む可能性がある

crash.log

# Local values

## 認証情報やアカウントIDパスワードの具体的な入力値が含まれる可能性があるため
## 環境依存の構成が公開に不向き
## 意図せずアカウントIDや機密情報を含む可能性があるため

terraform.tfvars
terraform.tfvars.json

# Sensitive values

## 開発者が個別にローカル上に上書きした設定を記述するファイル
## 本番とは違う構成になっている可能性があるファイル

override.tf
override.tf.json
*_override.tf
*_override.tf.json

# Plan files

## Terraformの実行結果をバイナリ形式で保存したファイル
## 一部環境の状態情報やおあすワードが含まれる可能性がある
## バージョン互換性もなく公開に不向きな内容

*.tfplan

実際の記述方法

頻出パターンを上げていきます。

AWSアカウント

AWSアカウントIDを公開しないようにするためには、.tfvarsを使用します。

1,variables.tfの作成

役割としては変数名とその仕様を定義するイメージ

variable "aws_account_id" {
  type        = string
  description = "The AWS account ID to be used in IAM roles, ARNs, etc."
}
2,terraform.tfvarsの作成

実際に変数に代入する値を記載する

aws_account_id = "123456789012"
3,その変数を使用してリソースを定義する
resource "aws_iam_role" "example" {
  name = "example-role"

  assume_role_policy = jsonencode({
    Version = "2012-10-17",
    Statement = [{
      Effect = "Allow",
      Principal = {
        AWS = "arn:aws:iam::${var.aws_account_id}:root"←ココ
      },
      Action = "sts:AssumeRole"
    }]
  })
}

DB認証情報

random_passwordというTerraformのランダムパスワード生成リソースを使用する

1,パスワード生成リソースの定義

resource "random_password" "db_password" {
  length  = 12
  special = true
}

2,outputする

参照先:

output "db_password" {
  value     = random_password.db_password.result
  sensitive = true
}

参照元:

data "terraform_remote_state" "db_password"{
    backend = ""
    config = {
        path "../example/terraform.tfstate"
    }
    
}

resource "aws_rds_cluster" "auto_maintenance_pg_cluster" {
  cluster_identifier              = "aurora-cluster"
  engine                          = "aurora-postgresql"
  engine_version                  = "15.10"
  master_username                 = "exampleadmin"
  master_password                 = data.terraform_remote_state.db_password(dataリソース名).outputs.db_password(outputリソース名)
  ...etc

最後に

今後もTerraformやっていくので追記していきます。
お疲れ様でした。

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?