AWS
EC2
Terraform

TerraformでEC2のインスタンスプロファイルを生成する

More than 1 year has passed since last update.

TerraformでEC2のインスタンスプロファイルを生成する

解説

まずData Sourceを用いてIAMのロールを生成します。

data "aws_iam_policy_document" "ec2-role" {

  statement {
    effect = "Allow"

    actions = ["sts:AssumeRole"]

    principals {
      type        = "Service"
      identifiers = ["ec2.amazonaws.com"]
    }
  }
}

上記を元に実際に生成されたロールは下記のようになります。

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

同じくData Sourceを用いてポリシーを作成します。

data "aws_iam_policy_document" "ec2-role_policy" {
  statement {
    effect = "Allow"
    actions = [
        "autoscaling:Describe*",
        "cloudwatch:*",
        "logs:*",
        "sns:*",
    ]

    resources = [
      "*",
    ]
  }
}

上記を元に実際に生成されたポリシーは下記のようになります。

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Action": [
        "sns:*",
        "logs:*",
        "cloudwatch:*",
        "autoscaling:Describe*"
      ],
      "Resource": "*"
    }
  ]
}

次に、生成されたJSONデータをロール、ポリシーに割り当てます。

# Role
resource "aws_iam_role" "ec2-role" {
  name               = "${var.general_name}-ec2-role"
  assume_role_policy = "${data.aws_iam_policy_document.ec2-role.json}"
}
# Role END

# Role-Policy
resource "aws_iam_role_policy" "ec2-role_policy" {
  name   = "${var.general_name}-ec2-role-policy"
  role   = "${aws_iam_role.ec2-role.id}"
  policy = "${data.aws_iam_policy_document.ec2-role_policy.json}"
}
# Role-Policy END

下記のようにすることで、生成されたJOSNデータを割り当てることができます。

assume_role_policy = "${data.aws_iam_policy_document.ec2-role.json}"

policy = "${data.aws_iam_policy_document.ec2-role_policy.json}"

まとめるとこんな感じ

iam.tf
# IAM Role for EC2
data "aws_iam_policy_document" "ec2-role" {

  statement {
    effect = "Allow"

    actions = ["sts:AssumeRole"]

    principals {
      type        = "Service"
      identifiers = ["ec2.amazonaws.com"]
    }
  }
}
# IAM Role for EC2 END

# IAM Role Policy for EC2
data "aws_iam_policy_document" "ec2-role_policy" {
  statement {
    effect = "Allow"
    actions = [
        "autoscaling:Describe*",
        "cloudwatch:*",
        "logs:*",
        "sns:*",
    ]

    resources = [
      "*",
    ]
  }
}
# IAM Role Policy for EC2 END

# IAM Instance Profile
resource "aws_iam_instance_profile" "ec2-profile" {
  name  = "ec2-profile"
  roles = ["${aws_iam_role.ec2-role.name}"]
}
# IAM Instance Profile END

# Role
resource "aws_iam_role" "ec2-role" {
  name               = "${var.general_name}-ec2-role"
  assume_role_policy = "${data.aws_iam_policy_document.ec2-role.json}"
}
# Role END

# Role-Policy
resource "aws_iam_role_policy" "ec2-role_policy" {
  name   = "${var.general_name}-ec2-role-policy"
  role   = "${aws_iam_role.ec2-role.id}"
  policy = "${data.aws_iam_policy_document.ec2-role_policy.json}"
}
# Role-Policy END