1
0

More than 3 years have passed since last update.

terraformでIAMのRoleとPolicyを同時に作成・削除する

Posted at

はじめに

IAMの管理をterraformで行う際、RoleとPolicyを同時に作成、削除を行ったら思い通りの挙動ができずハマったのでその対処。
以下はLambda用に新たにロールを作成し(ロール名:test-lambda-role)、AmazonS3FullAccessをアタッチする例となります。

同時に作成・削除ができないパターン


resource "aws_iam_role" "test_lambda" {
  assume_role_policy = <<POLICY
{
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Effect": "Allow",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      }
    }
  ],
  "Version": "2012-10-17"
}
POLICY

  max_session_duration = "3600"
  name                 = "test-lambda-role"
  path                 = "/"
}

resource "aws_iam_role_policy_attachment" "test_lambda_AmazonS3FullAccess" {
  policy_arn = "arn:aws:iam::aws:policy/AmazonS3FullAccess"
  role       = "test-lambda-role"
}

上記の書式でterraform applyを実行すると以下のエラーが表示されます。

作成時のエラー

Error: Error attaching policy arn:aws:iam::aws:policy/AmazonS3FullAccess to IAM Role test-lambda-role: NoSuchEntity: The role with name test-lambda-role cannot be found.
status code: 404

削除時のエラー

Error: error deleting IAM Role (test-lambda-role): DeleteConflict: Cannot delete entity, must detach all policies first.
status code: 409

どうやらRoleとPolicyがうまく関連付いておらず、順序性が無いためにエラーとなっているように見えます。

同時に作成・削除ができるパターン



resource "aws_iam_role" "test_lambda" {
  assume_role_policy = <<POLICY
{
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Effect": "Allow",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      }
    }
  ],
  "Version": "2012-10-17"
}
POLICY

  max_session_duration = "3600"
  name                 = "test-lambda-role"
  path                 = "/"
}

resource "aws_iam_role_policy_attachment" "test_lambda_AmazonS3FullAccess" {
  policy_arn = "arn:aws:iam::aws:policy/AmazonS3FullAccess"
  role       = aws_iam_role.test_lambda.name
}

先のパターンとの違いは、aws_iam_role_policy_attachmentでのroleの指定を固定文字列ではなく、
("type").("local").("name")といったterraform内での参照方法とした記法としたことです。

・NGな書き方 : role = "test-lambda-role"
・OKな書き方 : role = aws_iam_role.test_lambda.name

何が起きていたか

roleの指定方法を変えた場合に何が起きていたのか、tfstateを覗くと違いがありました。
OKだったパターンでは、aws_iam_role_policy_attachmentの中にdependenciesという項目が追記されていたのでした。

{
  "type": "aws_iam_role_policy_attachment",
  "instances": [
    {
      "dependencies": [
        "aws_iam_role.test_lambda.name"
      ]
    }
  ]
},

おわりに

リソースの指定は固定文字列ではなく、terraformの言葉で書くようにすると幸せになれると思いますので、 事情がなければこちらを使おう。

1
0
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
1
0