# CloudPeek read-only access: the CloudPeekReadOnly policy and, if you want one, an IAM user to
# sign in to CloudPeek with. The Terraform twin of cloudpeek-access.yaml.
# Guide: https://cloudpeek.app/docs/getting-started.html#access
#
# This configuration doesn't create an access key, so no secret ever lands in Terraform state.
# After applying, make one for the user:
#   aws iam create-access-key --user-name cloudpeek
#
# Save this file in an empty directory, then run: terraform init && terraform apply
# To add it to an existing configuration instead, leave out the terraform and provider blocks.

terraform {
  required_version = ">= 1.3"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = ">= 5.0"
    }
  }
}

# IAM is global; any region will do.
provider "aws" {
  region = "us-east-1"
}

variable "policy_name" {
  description = "Name of the read-only IAM policy. IAM Identity Center permission sets can attach it by this name as a customer managed policy."
  type        = string
  default     = "CloudPeekReadOnly"
}

variable "create_user" {
  description = "Create an IAM user with the policy attached, for signing in to CloudPeek with an access key. Set to false if you sign in with IAM Identity Center."
  type        = bool
  default     = true
}

variable "user_name" {
  description = "Name of the IAM user (used only when create_user is true)."
  type        = string
  default     = "cloudpeek"
}

# The four read-only CloudWatch actions CloudPeek uses. These actions don't support resource-level
# permissions for this use, so the resource is "*".
data "aws_iam_policy_document" "cloudpeek" {
  statement {
    sid    = "CloudPeekReadOnly"
    effect = "Allow"
    actions = [
      "cloudwatch:ListDashboards",
      "cloudwatch:GetDashboard",
      "cloudwatch:GetMetricData",
      "cloudwatch:DescribeAlarms",
    ]
    resources = ["*"]
  }
}

resource "aws_iam_policy" "cloudpeek" {
  name        = var.policy_name
  description = "Read-only CloudWatch access for the CloudPeek app (dashboards, metric data and alarms)."
  policy      = data.aws_iam_policy_document.cloudpeek.json
}

resource "aws_iam_user" "cloudpeek" {
  count = var.create_user ? 1 : 0
  name  = var.user_name
}

resource "aws_iam_user_policy_attachment" "cloudpeek" {
  count      = var.create_user ? 1 : 0
  user       = aws_iam_user.cloudpeek[0].name
  policy_arn = aws_iam_policy.cloudpeek.arn
}

output "policy_arn" {
  description = "The read-only policy. Attach it to a role, or reference it by name from an IAM Identity Center permission set."
  value       = aws_iam_policy.cloudpeek.arn
}

output "next_step" {
  description = "Create an access key for the user, then enter it in CloudPeek. The secret is shown only once."
  value       = var.create_user ? "aws iam create-access-key --user-name ${aws_iam_user.cloudpeek[0].name}" : "Attach ${aws_iam_policy.cloudpeek.name} to an IAM Identity Center permission set."
}
