12
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

TerraformでIAMポリシーのJSONに変数を埋めたい場合はaws_iam_policy_documentを使う

Posted at

TL;DR

  • TerraformでIAMポリシーのJSONに変数を埋めたい場合はaws_iam_policy_documentを使えばよい
  • サンプルコードはTerraformでKMSキー作った時に、アクセス権限の管理をIAMグループで管理する例
  • aws_iam_policy_documentのドキュメントはこちら => AWS_IAM_POLICY_DOCUMENT

サンプル

KMSのキーARNを変数参照で埋め込んだIAMポリシー作って適当なIAMユーザ/グループ/ロールに付与するtfファイルこんなかんじ

data "aws_iam_policy_document" "kms_hoge" {
  statement {
    sid = "AllowUseOfTheKey"

    actions = [
      "kms:Encrypt",
      "kms:Decrypt",
      "kms:ReEncrypt*",
      "kms:GenerateDataKey*",
      "kms:DescribeKey",
    ]

    resources = ["${aws_kms_key.hoge_kms_key.arn}"]
  }
}

resource "aws_iam_policy" "kms_hoge_policy" {
  name        = "kms-hoge-policy"
  path        = "/"
  description = ""
  policy      = "${data.aws_iam_policy_document.kms_hoge.json}"
}

resource "aws_iam_policy_attachment" "kms_hoge_policy_attachment" {
  name = "kms-hoge-policy-attachment"

  users  = ["${aws_iam_user.hoge_user.name}"]
  groups = ["${aws_iam_group.hoge_group.name}"]
  roles  = ["${aws_iam_role.hoge_role.name}"]

  policy_arn = "${aws_iam_policy.kms_hoge_policy.arn}"
}

※このサンプル中ではIAMユーザ/グループ/ロールの定義は省略。

上記で参照しているKMSのキーとエイリアスのtfファイルはこんなかんじ

resource "aws_kms_key" "hoge_kms_key" {
  policy = "${file("../../kms-policies/aws_kms_policies/hoge_policy.json")}"
  enable_key_rotation = false
}

resource "aws_kms_alias" "hoge_kms_alias" {
  name          = "alias/hoge"
  target_key_id = "${aws_kms_key.hoge_kms_key.key_id}"
}

上記で参照しているKMSのキーポリシー ../../kms-policies/aws_kms_policies/hoge_policy.json は以下
※111122223333のところはAWSアカウントIDで読み替えて下さい

{
  "Version": "2012-10-17",
  "Id": "key-policy-for-hoge",
  "Statement": [
    {
      "Sid": "Enable IAM User Permissions",
      "Effect": "Allow",
      "Principal": {"AWS": "arn:aws:iam::111122223333:root"},
      "Action": "kms:*",
      "Resource": "*"
    }
  ]
}
12
8
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
12
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?