継続は力なり

タイトル通り定期的な更新を心掛けるブログです。

Datadog の GCP インテグレーションを設定する

タダです.

Datadog の GCP インテグレーション設定をしたのですが,備忘録でこの記事にまとめていきます.

GCP インテグレーション設定方法

ドキュメント記載の通り,GCP のサービスアカウントの発行と API の有効化が必要です.

docs.datadoghq.com

1,API の有効化

API の有効化するのは Stackdriver Monitoring API,Compute Engine API,Cloud Asset API を有効化を行います.いずれか1つでも有効化できてないと後続のサービスアカウントの鍵アップロードで失敗します.

2,サービスアカウントの作成と鍵のダウンロード

サービスアカウントを新規で作成します.権限として Compute 閲覧者,モニタリング閲覧者,Cloud Asset 閲覧者をアタッチし,鍵を JSON 形式でダウンロードしておきます.

3, Datadog GCP インテグレーションにサービスアカウントの鍵をアップロード

サービスアカウントの鍵を GCP インテグレーションの Configuration タブで Upload Key File を押してサービスアカウントの鍵をアップロードします.その後,Update Configuration を押した後, Service account successfully updated! が出れば成功です.

まとめ

ドキュメントの通りに進めていれば成功するのですが,API の有効化をし忘れてハマったので備忘録として記事にしました.

Security Hub から通知された『Lambda function policies should prohibit public access』に対応する

タダです.

業務で Security Hub から [Lambda.1] Lambda function policies should prohibit public access というアラートが飛んできました.対応してアラートを消したのですが,その対応を備忘録として書いておきます.

アラートの原因

アラートの原因は S3 イベントから発火する Lambda のリソースベースポリシー の設定が下記のようになっていました.

ポリシー例

{
    "Version": "2012-10-17",
    "Id": "default",
    "Statement": [
        {
            "Sid": "lambda-allow-s3-my-function",
            "Effect": "Allow",
            "Principal": {
              "Service": "s3.amazonaws.com"
            },
            "Action": "lambda:InvokeFunction",
            "Resource":  "arn:aws:lambda:ap-northeast-1:123456789012:function:my-function",
             "ArnLike": {
                "AWS:SourceArn": "arn:aws:s3:::my-bucket"
              }
            }
        }
     ]
}

原因の分析

リソースベースのポリシーには、別のアカウントまたは AWS のサービスが関数にアクセスしようとしたときに適用されるアクセス許可が表示されます

ドキュメントをみていた際に上記引用文の説明を見て,リソースベースポリシーでは AWS:SourceArn でリソースを明示してかつどの AWS アカウントからアクセスが有るかをポリシーに記載する必要があるかと思い,下記を追記してみることにしました.

"Condition": {
    "StringEquals": {
       "AWS:SourceAccount": "123456789012"
},

リソースベースポリシーに AWS アカウントを追加する

アラートが発生した Lambda の 設定 > アクセス権限 > リソースベースのポリシー から S3 のポリシーを選択して編集を押します.編集画面でソースアカウントに S3 がある AWS アカウント番号を記載して保存すれば反映完了です.

この対応後 Security Hub からのアラートも収まったので,対応として適切だった模様です.

まとめ

Security Hub からの Lambda に関するアラートを初めて対応したのでその模様を記事にしました.Security Hub のアラートの対応が初めてだったしリソースベースポリシーがどう影響するのかを学べた経験になりました.

terraform-provider-aws v4.9.0 のリリースで破壊的な S3 の変更がなくなったと聞いたので試してみた

タダです.

terraform-provider-aws の v4 で S3 リソースの変更をどうやって行くかなと思っていた頃に v4.9.0 で S3 の破壊的変更がなくなったという話がでてきたので,試した内容をまとめていきます.

resource/aws_s3_bucket: The acceleration_status, acl, cors_rule, grant, lifecycle_rule, logging, object_lock_configuration.rule, policy, replication_configuration, request_payer, server_side_encryption_configuration, versioning, and website parameters are now Optional. Please refer to the documentation for details on drift detection and potential conflicts when configuring these parameters with the standalone aws_s3_bucket_* resources.

github.com

provider のバージョンを 4.9.0 にあげたときの挙動

v4.9.0 が出た時にドキュメントに下記の引用文が追記されていました.4.9.0以降に上げることが推奨されています.

Versions 4.0.0 through v4.8.0 of the AWS Provider introduce significant breaking changes to the aws_s3_bucket resource. See S3 Bucket Refactor for more details. We recommend upgrading to v4.9.0 or later of the AWS Provider instead, where only non-breaking changes and deprecation notices are introduced to the aws_s3_bucket. See Changes to S3 Bucket Drift Detection for additional considerations when upgrading to v4.9.0 or later.

それでは実際にどんな挙動になるかを確認していきます.プロバイダーの指定を ~> 4.9.0 に変更後,terraform init および terraform plan を実行してみました.以前の記事で書きましたが,S3 の破壊的変更によって terraform plan をするとエラーがでていたのがでてなくなりました! その分 Warning: Argument is deprecated という警告がでるようになりました.

terraform-aws-provider 指定箇所抜粋

terraform {
  required_version = ">= 1.0.0"

  backend "s3" {
    encrypt        = true
    bucket         = "hoge"
    key            = "hoge.tfstate"
    region         = "ap-northeast-1"
  }

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.9.0"
    }
  }
}

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

terraform init および terraform plan の実行結果

$ terraform init
Initializing the backend...

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

Initializing provider plugins...
- Reusing previous version of hashicorp/aws from the dependency lock file
- Installing hashicorp/aws v4.9.0...

- Installed hashicorp/aws v4.9.0 (signed by HashiCorp)

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 plan
~中略~

No changes. Your infrastructure matches the configuration.

Your configuration already matches the changes detected above. If you'd like
to update the Terraform state to match, create and apply a refresh-only plan:
  terraform apply -refresh-only

Warning: Argument is deprecated

│   with aws_s3_bucket.v4_test,
│   on s3.tf line 9, in resource "aws_s3_bucket" "v4_test":
│    9: resource "aws_s3_bucket" "v4_test" {

│ Use the aws_s3_bucket_server_side_encryption_configuration resource instead

今回の変更に対する所感

v4.9.0 になったことで aws_s3_bucket リソースの変更を最悪行わなくてもプロバイダーバージョンのアップグレードを行えるようになったのですが,ドキュメントを見ると v5 になると aws_s3_bucket のパラメーターが削除されるためいずれにしても aws_s3_bucketで設定したパラメーターを分割せざるを得ないのだなと...暫定的な処置として v4.9.0 にあげた後でもリソース分割対応に向き合わなければなりません😇

  • acceleration_status
  • acl
  • cors_rule
  • grant
  • lifecycle_rule
  • logging
  • object_lock_configuration
  • policy
  • replication_configuration
  • request_payer
  • server_side_encryption_configuration
  • versioning
  • website

ドキュメント記載文

In the next major version, v5.0, the parameters listed below will be removed entirely from the aws_s3_bucket resource. For this reason, a deprecation notice is printed in the Terraform CLI for each of the parameters when used in a configuration.

registry.terraform.io

v4.9.0 にあげるための対応まとめ

v5 の事情を踏まえ業務で v4.9.0 にアップグレードしました.最後にその大まかな流れを備忘録としてまとめます.

  1. terraform-aws-provider を v4.9.0 にして terraform init で初期化
  2. tfrefactor で S3 バケットリソースを分割
  3. terraform plan で確認するとリソース分割した対象が差分として表示されるため,terraform import で差分を埋める

そして,その時に使った terraform import コマンド例です.

terraoform import コマンド例

$ terraform import aws_s3_bucket_acl.hoge hoge-bucket,private
$ terraform import aws_s3_bucket_lifecycle_configuration.hoge hoge-bucket
$ terraform import aws_s3_bucket_versioning.hoge hoge-bucket
$ terraform import aws_s3_bucket_cors_configuration.hoge hoge-bucket
$ terraform import aws_s3_bucket_server_side_encryption_configuration.hoge hoge-bucket
$ terraform import aws_s3_bucket_website_configuration.hoge hoge-bucket
$ terraform import aws_s3_bucket_request_payment_configuration.hoge hoge-bucket
$ terraform import aws_s3_bucket_replication_configuration.hoge hoge-bucket
$ terraform import aws_s3_bucket_policy.hoge hoge-bucket 
$ terraform import aws_s3_bucket_object_lock_configuration.hoge hoge-bucket
$ terraform import aws_s3_bucket_logging.hoge hoge-bucket

まとめ

terraform-provider-aws v4.9.0 の変更点とその影響,自分が実際にv4.9.0にアップグレードしたときの作業を簡単にまとめました.これまで業務で terraform-aws-provider をあげたことがなかったので,今回は勉強になりました.今度は v5 系が来るだろうと思うので情報収集や検証をしていければと思います.

関連記事

sadayoshi-tada.hatenablog.com

sadayoshi-tada.hatenablog.com

GitHub Actions で OIDC Provider を使って PR にコメントする

タダです.

GitHub Actions で Terraoform の実行計画を PR のコメントに書くようにしていたのですが,クレデンシャルとして IAM ユーザーのアクセスキーとシークレットアクセスキーを使う運用から OIDC Provider に置き換え る検証をした際にコメントができなくなりました.この記事でその対処として調べた結果をまとめていきます.

事象の概要

下記のような GitHub Actions に OIDC Provider に関する aws-actions/configure-aws-credentials を設定して検証してみたのですが,GitHub Actions を回した結果 Unhandled error: HttpError: Resource not accessible by integration というエラーがでたので権限系が怪しそうという思い調査してみました.

permissions:
  id-token: write
  contents: read

~中略~

jobs:
~中略~
      - name: Configure AWS Credentials 
        uses: aws-actions/configure-aws-credentials@v1
        with:
          aws-region: ap-northeast-1
          role-to-assume: hoge
          role-session-name: hoge-plan
          role-duration-seconds: 1200
~中略~

事象の調査と対応概要

GitHub Actions に permissions を指定していますが,permissions の指定してない時と差分を確認してみました.まず permissions を指定したときの Set up Job セクションの GITHUB_TOKEN Permissions を見てみたところ以下の設定になっていました.

GITHUB_TOKEN Permissions
  Contents: read
  Metadata: read

逆に IAM ユーザーのアクセスキーとシークレットアクセスキーはどうだったかを見ると,いろんな権限がついています.PullRequests: write の権限が OIDC Provider の設定でないことを見て pull-requests: write を追加してみたところ,Unhandled error: HttpError: Resource not accessible by integrationのエラーが無くなり,PR にコメントができるようになりました.

OIDC Provider の設定がない時

GITHUB_TOKEN Permissions
  Actions: write
  Checks: write
  Contents: write
  Deployments: write
  Discussions: write
  Issues: write
  Metadata: read
  Packages: write
  Pages: write
  PullRequests: write
  RepositoryProjects: write
  SecurityEvents: write
  Statuses: write

修正した GitHub Actions の定義

permissions:
  id-token: write
  contents: read
  pull-requests: write <= 追加

まとめ

OIDC Provider への置換え過程で,GitHub Actions の結果を PR コメントに反映するようにするために行った調査と対応をまとめました.今回の調査でいろんな権限の設定の仕方があるのだと学べました.

関連記事

sadayoshi-tada.hatenablog.com

sadayoshi-tada.hatenablog.com

Terraform AWS Provider v3 -> v4 へ移行するのに役立つツール『tfrefactor』を試してみる

タダです.

Terraform AWS Provider の v4 が出てきたことでバージョンアップされた方も多いと思います.v4 へのバージョンアップでは S3 周りの変更が多く苦労するという情報が見かけられ,その変更をサポートするツールとして tfrefactor が紹介されてたので検証で試した内容をこの記事にまとめていきます.

github.com

tfrefactor とは

tfrefactor の特徴は以下の3つがあります.v4 以降の aws_s3_bucket リソースの移行,AWS Provider のバージョン制約の更新,リソースのインポートが必要があるが,そのサポートとしての CSV 出力があげられてます.

・Migrate aws_s3_bucket resource arguments to independent resources available since v4.0.0 of the Terraform AWS Provider.

・Update version constraints of the Terraform AWS Provider defined in configurations.

・Get a table (in .csv format) of each new resource with its parent aws_s3_bucket to enable resource import.

tfrefactor の導入

tfrefactor は Go で開発されており,バージョン 1.17以上なら次のコマンドで導入できます.

$ ghq get https://github.com/anGie44/ohmyhcl
$ make install
cd ./tfrefactor && go mod download
cd ./tfrefactor && go install
$ which tfrefactor
/Users/hoge/go/bin/tfrefactor

検証用の Terraform 設定

まずは Provider の設定や S3 のコードは次のようにしました.

terraform {
  required_version = ">= 1.0.0"

  backend "s3" {
    encrypt        = true
    bucket         = "hoge"
    key            = "hoge.tfstate"
    region         = "ap-northeast-1"
  }

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.8.0"
    }
  }
}

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

resource "aws_s3_bucket" "v3_test" {
  bucket = "hoge"
  acl = "private"
  cors_rule {
    allowed_origins = [ "*" ]
    allowed_methods = ["GET"]
  }

  server_side_encryption_configuration {
    rule {
      apply_server_side_encryption_by_default {
        kms_master_key_id = data.aws_kms.hoge.arn
        sse_algorithm     = "aws:kms"
      }
    }
  }

  versioning {
    enabled = true
  }
}

この状態で terraform plan で確認すると v3 では問題なかった定義がエラーとして表示されるようになりました.

╷
│ Error: Value for unconfigurable attribute
│ 
│   with aws_s3_bucket.v3_test,
│   on s3.tf line 9, in resource "aws_s3_bucket" "v3_test":
│    9: resource "aws_s3_bucket" "v3_test" {
│ 
│ Can't configure a value for "versioning": its value will be decided automatically based on the result of applying this configuration.


│ Error: Value for unconfigurable attribute

│   with aws_s3_bucket.v3_test,
│   on s3.tf line 9, in resource "aws_s3_bucket" "v3_test":
│    9: resource "aws_s3_bucket" "v3_test" {

│ Can't configure a value for "cors_rule": its value will be decided automatically based on the result of applying this configuration.
╵
╷
│ Error: Value for unconfigurable attribute
│ 
│   with aws_s3_bucket.v3_test,
│   on s3.tf line 9, in resource "aws_s3_bucket" "v3_test":
│    9: resource "aws_s3_bucket" "v3_test" {
│ 
│ Can't configure a value for "server_side_encryption_configuration": its value will be decided automatically based on the result of
│ applying this configuration.


│ Error: Value for unconfigurable attribute

│   with aws_s3_bucket.v3_test,
│   on s3.tf line 11, in resource "aws_s3_bucket" "v3_test":
│   11:   acl = "private"

│ Can't configure a value for "acl": its value will be decided automatically based on the result of applying this configuration.

tfrefactor の実行

そこで,tfrefactor の出番です.対象のリソースとファイル名を指定してコマンドを実行すると,s3_migrated.tf というファイルが新規に作成されます.コマンドオプションとして -c をつければ CSV 出力がされます(s3_new_resources.csvという名前のファイルが作成されます).

$ tfrefactor resource aws_s3_bucket s3.tf

作成されたファイルの内容を確認すると,エラーになっていた属性値が別リソースとして定義し直されています.もともとあったファイルは別名に変更して terraform plan をかけたら実行計画の確認が成功しましたが,新規リソースが作られるため,terraform importを使ってリソースの紐付けを行わないといけないです.

resource "aws_s3_bucket" "v3_test" {
  bucket = "hoge"
}
resource "aws_s3_bucket_acl" "v3_test_acl" {
  bucket = aws_s3_bucket.v3_test.id
  acl    = "private"
}

resource "aws_s3_bucket_cors_configuration" "v3_test_cors_configuration" {
  bucket = aws_s3_bucket.v3_test.id
  cors_rule {
    allowed_origins = [ "*" ]
    allowed_methods = ["GET"]
  }
}

resource "aws_s3_bucket_versioning" "v3_test_versioning" {
  bucket = aws_s3_bucket.v3_test.id
  versioning_configuration {
    status = "Enabled"
  }
}

resource "aws_s3_bucket_server_side_encryption_configuration" "v3_test_server_side_encryption_configuration" {
  bucket = aws_s3_bucket.v3_test.id
  rule {
    apply_server_side_encryption_by_default {
      kms_master_key_id = data.aws_kms.hoge.arn
      sse_algorithm     = "aws:kms"
    }
  }
}

terraform plan の確認

$ terraform plan
~中略~
Plan: 5 to add, 0 to change, 0 to destroy.

───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

Note: You didn't use the -out option to save this plan, so Terraform can't guarantee to take exactly these actions if you run "terraform
apply" now.

まとめ

tfrefactor の紹介と試しに使ってみた内容をまとめました.業務でも v4 へのバージョンアップを行うのでこの検証した内容を生かしていきたいです.

関連

sadayoshi-tada.hatenablog.com