With a Grafana environment up and running, it’s time to get a service account active via some Terraform so that Python can be used to interacting with Grafana.

Why A Service Account ?

Grafana has a User Interface (UI) that is not too hard to get to grips with, but sometimes you may want to integrate data from Grafana or implement multiple changes in a programatic repeatable way. This is where a Service Account (SA) comes in. One is required for Terraform (so needs creating in Grafana before Terraform can be used) but I am also looking to use one for some Python based fun. I am a separate SA from the Terraform one (which has Admin privileges) as my Python based SA requires a lot less permission.

Terraform To Create A Service Account

The Terraform Grafana provider has options for creating both the Service Account and the token that the account will use. These are “grafana_service_account” which I am using to create a resource called “python_sa”, and “grafana_service_account_rotating_token” which I am using to create a token called “python_token”.

I’m then using a Terraform output to output the token, which is a sensitive value, so that I may (in future) use it in some Python.

Added to main.tf:

resource "grafana_service_account" "python_sa" {
name = "python-service-account"
role = "Viewer"
}
resource "grafana_service_account_rotating_token" "python_token" {
name_prefix = "python_token"
service_account_id = grafana_service_account.python_sa.id
seconds_to_live = 604800
early_rotation_window_seconds = 302400
}

Added as output.tf:

output "service_account_python_sa_token_key" {
value = grafana_service_account_rotating_token.python_token.key
sensitive = true
}

Terraform Viewing The Sensitive Output

The token is sensitive, and not something that should be shown in outputs / plans etc. So it’s marked as sensitive and requires the Terraform output command to be viewed. In a production environment the secret should be outputted into a secure environment/secure storage vault.

terraform output -json

View It On GitHub

This is part of my ongoing “Grafana Playground” repository. The work in this blog post can be viewed in a commit in the repository.