Skip to content

Instantly share code, notes, and snippets.

@diyan
Last active April 28, 2020 22:33
Show Gist options
  • Save diyan/d70cb81bcbf213ca7812ed25a99ddbce to your computer and use it in GitHub Desktop.
Save diyan/d70cb81bcbf213ca7812ed25a99ddbce to your computer and use it in GitHub Desktop.
Examples of Terraform and AWS IAM resources

AWS IAM using Terraform

Example 1

// Data Resource for IAM Policy Document
// String interpolation
// Separate IAM Policy attached to IAM Role
data "aws_iam_policy_document" "cloudwatch_logs_write_policy" {
  statement {
    actions = [
      "logs:CreateLogStream",
      "logs:PutLogEvents",
      "logs:PutLogEventsBatch",
    ]
    resources = [
      "arn:aws:logs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:log-group:/dev/app/${var.project}:*"
    ]
  }
}

resource "aws_iam_policy" "cloudwatch_logs_write_policy" {
  name   = "cloudwatch_logs_write_policy"
  policy = data.aws_iam_policy_document.cloudwatch_logs_write_policy.json
}

resource "aws_iam_role_policy_attachment" "cloudwatch_logs_write_policy" {
  role = aws_iam_role.vm_iam_role.name
  policy_arn = aws_iam_policy.cloudwatch_logs_write_policy.arn
}

Example 2

// jsonencode function for IAM Policy Document
// String format for large literals
// Separate IAM Policy attached to IAM Role
resource "aws_iam_policy" "cloudwatch_logs_write_policy" {
  name   = "${var.project}_cloudwatch_logs_write_policy"
  policy = jsonencode({
    Statement = [{
      Effect = "Allow"
      Action = [
        "logs:CreateLogStream",
        "logs:PutLogEvents",
        "logs:PutLogEventsBatch",
      ]
      Resource = format("arn:aws:logs:%s:%s:log-group:/dev/app/%s:*",
        data.aws_region.current.name,
        data.aws_caller_identity.current.account_id,
        var.project)
    }]
    Version = "2012-10-17"
  })
}

resource "aws_iam_role_policy_attachment" "cloudwatch_logs_write_policy" {
  role = aws_iam_role.vm_iam_role.name
  policy_arn = aws_iam_policy.cloudwatch_logs_write_policy.arn
}

Example 3

// jsonencode function for IAM Policy Document
// String format for large literals
// IAM Policy embedded to IAM Role
resource "aws_iam_role_policy" "cloudwatch_logs_write_policy" {
  name = "${var.project}_cloudwatch_logs_write_policy"
  role = aws_iam_role.vm_iam_role.id
  policy = jsonencode({
    Statement = [{
      Effect = "Allow"
      Action = [
        "logs:CreateLogStream",
        "logs:PutLogEvents",
        "logs:PutLogEventsBatch",
      ]
      Resource = format("arn:aws:logs:%s:%s:log-group:/dev/app/%s:*",
        data.aws_region.current.name,
        data.aws_caller_identity.current.account_id,
        var.project)
    }]
    Version = "2012-10-17"
  })
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment