zaki work log

作業ログやら生活ログやらなんやら

[Terraform / AWS] aws_iam_roleリソースでinline_policyがdeprecatedになってたのでコード修正

以前作成したEC2に対するEventBridge Schedulerを使うためのロール設定内のポリシー設定、いつのまにか inline_policy がdeprecatedになっていたのでその修正コードについてまとめ。

完成品

2025年2月時点で動くコードは以下。

resource "aws_iam_role" "stopstart_role" {
  name = "ec2-stop-start-role"
  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Action = "sts:AssumeRole"
        Effect = "Allow"
        Principal = {
          Service = "scheduler.amazonaws.com"
        }
      },
    ]
  })

  path = "/"
}

resource "aws_iam_role_policy" "stopstart_policy" {
  name = "start_stop_policy"
  role = aws_iam_role.stopstart_role.id

  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Action   = ["ec2:StartInstances", "ec2:StopInstances"]
        Effect   = "Allow"
        Resource = "*"
      },
    ]
  })
}

inline_policyで定義していたコードをaws_iam_role_policyリソースを使って外に出し、role属性で対象ロールを指定すればOK

以前のinline_policyを使ったコード

resource "aws_iam_role" "stopstart_role" {
  name = "ec2-stop-start-role"
  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Action = "sts:AssumeRole"
        Effect = "Allow"
        Principal = {
          Service = "scheduler.amazonaws.com"
        }
      },
    ]
  })

  path = "/"

  inline_policy {
    name = "start_stop_policy"
    policy = jsonencode({
      Version = "2012-10-17"
      Statement = [
        {
          Action   = ["ec2:StartInstances", "ec2:StopInstances"]
          Effect   = "Allow"
          Resource = "*"
        },
      ]
    })
  }
}

これは約1年前の2024年の2月に書いたコード

zaki-hmkc.hatenablog.com

2025年2月時点で、以下の警告が出るようになっている。

The inline_policy argument is deprecated. Use the aws_iam_role_policy resource instead. If Terraform should exclusively manage all inline policy associations (the current behavior of this argument), use the aws_iam_role_policies_exclusive resource as well.

aws_iam_role | Resources | hashicorp/aws | Terraform | Terraform Registry

Terraformコマンドでplanapplyすればすぐ気付けるんだけど、構築自動化してる中の処理だったので警告が見えてなかった。

環境

$ terraform -version
Terraform v1.9.2
on linux_amd64
+ provider registry.terraform.io/hashicorp/aws v5.84.0

Your version of Terraform is out of date! The latest version
is 1.10.5. You can update by downloading from https://www.terraform.io/downloads.html

Terraformがちょっと古いですね…