Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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": "*"
    }
  ]
}
crowdworks
21世紀の新しいワークスタイルを提供する日本最大級のクラウドソーシング「クラウドワークス」のエンジニアチームです!
https://crowdworks.co.jp/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away