Sometimes we just want a pretty graph for Cloudwatch monitoring on Grafana. Working with Terraform it’s now great to set up a basic block to auto create this. This is the way I did it
Terraform Setup
- Set up a new feature in variables.tf
variable "features" {
description = "Features to enable (true/false mostly)"
type = object({
grafana = optional(bool, true) # Enable IAM setup for Grafana
})
}
- Set up a new features-grafana.tf file to hold the new block.
The user created is hardcoded as “grafana” and the Access Key and Secret Key is forced to screen ( you can hide it as per code)
##### Feature: Grafana
## Sets up user/permissions for use with Grafana externally with ReadOnly CloudWatch metrics
# Output:
# * Defines user as "grafana"
# * access/secret key to put into Grafana DataSource
#### Grafana IAM user
resource "aws_iam_user" "grafana" {
count = lookup(var.features, "grafana") == true ? 1 : 0
name = "grafana"
}
resource "aws_iam_access_key" "grafana" {
count = lookup(var.features, "grafana") == true ? 1 : 0
user = aws_iam_user.grafana[0].name
}
resource "aws_iam_user_policy_attachment" "grafana" {
count = lookup(var.features, "grafana") == true ? 1 : 0
user = aws_iam_user.grafana[0].name
policy_arn = "arn:aws:iam::aws:policy/CloudWatchReadOnlyAccess"
}
output "grafana_iam_access_key" {
value = lookup(var.features, "grafana") == true ? aws_iam_access_key.grafana[0].id : null
}
output "grafana_iam_secret_key" {
value = lookup(var.features, "grafana") == true ? nonsensitive(aws_iam_access_key.grafana[0].secret) : null
# sensitive = true
}
- Run it up
terraform apply
Grafana Setup
Log into Grafana (10.0.1 is what I’m using)
- (Left side) Connections > Add new connections
- CloudWatch (Plugin 5.0.0 at time of writing)
- “Create a CloudWatch data source” (top right)
- Fill in form – with 2 values outputted above
Name = “CloudWatch”
Authentication Provider = “Access & secret key”
Access Key ID = {grafana_iam_access_key}
Secret Access Key = {grafana_iam_secret_key} - Save & Test (bottom)
Now to set up some cool graphs as required 😉