Aller au contenu

Example - IAM Role#

  • uses the aws_iam_role_policy_attachments_exclusive
Terraform
# https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document
data "aws_iam_policy_document" "my_instance_allows" {
  statement {
    sid = "AdminOnDataBucket"
    effect = "Allow"
    actions = [
      "s3:*"
    ]
    resources = [
      "arn:aws:s3:::${var.data_bucket}/*",
      "arn:aws:s3:::${var.data_bucket}",
    ]
  }
}

# https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role
resource "aws_iam_role" "my_instance_role" {
  name = "${local.prefix}-instance-role"
  tags = local.common_tags

  # Terraform's "jsonencode" function converts a
  # Terraform expression result to valid JSON syntax.
  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Effect = "Allow"
        Action = "sts:AssumeRole"
        Principal = {
          Service = "ec2.amazonaws.com"
        }
      },
    ]
  })
}

# https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy_attachments_exclusive
resource "aws_iam_role_policy_attachments_exclusive" "my_instance_role" {
  role_name   = aws_iam_role.my_instance_role.name
  policy_arns = ["arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"]
}

#https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy#policy
resource "aws_iam_role_policy" "my_instance_role" {
  role   = aws_iam_role.my_instance_role.id
  name   = "${local.prefix}-allows"
  policy = data.aws_iam_policy_document.my_instance_allows.json
}