dehio3’s diary

仕事、生活、趣味のメモ

terraformでインラインポリシーとAWS管理ポリシーを適用したIAMロールを作成する

f:id:dehio3:20190710094851p:plain

内容

terraformでインラインポリシーとAWS管理ポリシーを適用したIAMロールを作成する場合のtfファイルの記述方法

例としてredashのathena接続用のIAMロールを記載

iam.tf

  • インラインポリシーはaws_iam_role_policyでアタッチ
  • AWS管理ポリシーはaws_iam_policy_attachmentでアタッチ
# iam
resource "aws_iam_role" "redash" {
  name = "redash-instance-role"
  path = "/"

  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Principal": {
        "Service": "ec2.amazonaws.com"
      },
      "Effect": "Allow",
      "Sid": ""
    }
  ]
}
EOF
}

resource "aws_iam_instance_profile" "redash" {
  name = "redash-instance-role"
  role = "${aws_iam_role.redash.name}"
}

data "aws_iam_policy_document" "redash" {
  statement {
    effect  = "Allow"
    actions = [
      "s3:GetObject"
    ]
    resources = [
      "${aws_s3_bucket.redash.arn}/*",
    ]
  }
  statement {
    effect  = "Allow"
    actions = [
      "s3:GetBucketLocation",
      "s3:ListBucket",
    ]
    resources = [
      "${aws_s3_bucket.redash.arn}",
    ]
  }
}

resource "aws_iam_role_policy" "redash" {
  name    = "redash"
  role    = "${aws_iam_role.redash.id}"
  policy  = "${data.aws_iam_policy_document.redash.json}"
}

resource "aws_iam_policy_attachment" "redash" {
    name       = "redash"
    policy_arn = "arn:aws:iam::aws:policy/service-role/AWSQuicksightAthenaAccess"
    roles      = [
      "${aws_iam_role.redash.name}"
      ]
}