Service Accounts in Grafana
Introduction
Service accounts in Grafana are special types of accounts designed specifically for backend services, automated tools, and integration systems rather than human users. Unlike regular user accounts, service accounts are intended for machine-to-machine communication, enabling various automation scenarios while maintaining robust security practices.
Service accounts were introduced as a more secure and manageable alternative to API keys, offering better control, trackability, and integration with Grafana's permission system. They provide a way to grant systems programmatic access to Grafana without using personal credentials.
Why Use Service Accounts?
Service accounts solve several key challenges when automating tasks in Grafana:
- Separation of concerns: Service accounts allow separation between human users and automated systems
- Fine-grained access control: You can limit a service account to only the specific permissions it needs
- Better audit trails: Actions performed by service accounts are clearly distinguished in logs
- Token management: You can create multiple tokens for a single service account and revoke them individually
- No expiration by default: Service account tokens don't expire automatically (unlike API keys in some versions)
Service Accounts vs. API Keys
Before service accounts, API keys were the primary method for automated access to Grafana. Here's how they compare:
Feature | Service Accounts | API Keys |
---|---|---|
Granular permissions | ✅ Uses Grafana's RBAC | ❌ Limited to predefined roles |
Multiple tokens | ✅ Can have multiple active tokens | ❌ One key per purpose |
Token revocation | ✅ Individual tokens can be revoked | ❌ Must regenerate the entire key |
Audit logging | ✅ Better attribution in logs | ❌ Limited attribution |
Management UI | ✅ Full-featured management interface | ❌ Basic interface |
Long-term support | ✅ Active development | ❌ Being deprecated |
Creating a Service Account
Let's create a service account in Grafana:
- Navigate to Administration → Service accounts in the sidebar
- Click Add service account
- Enter the following details:
- Display name: A descriptive name (e.g., "Prometheus Integration")
- Role: Select the appropriate role from the dropdown
Example: Creating a Dashboard Publisher Service Account
Let's create a service account for a system that will automatically publish dashboards:
// Service Account Details
{
"name": "Dashboard Publisher",
"role": "Editor",
"isDisabled": false
}
Managing Service Account Tokens
Once you've created a service account, you need to generate tokens for it to authenticate:
- Navigate to the service account details page
- Click Add service account token
- Enter a descriptive name for the token
- Click Generate token
- Important: Copy and securely store the token immediately - it will not be shown again
Example: Token Generation Response
{
"id": 1,
"name": "Dashboard Publisher Token",
"key": "glsa_Xh93qMj3OQl39d9F3kDR92h4k2sl39dm_5c49b726",
"created": "2023-05-12T15:32:44Z"
}
Using Service Account Tokens in API Calls
Once you have a token, you can use it to make API calls to Grafana. Here's how to use it with curl:
curl -H "Authorization: Bearer glsa_Xh93qMj3OQl39d9F3kDR92h4k2sl39dm_5c49b726" \
https://your-grafana-instance/api/dashboards/uid/my-dashboard
Or in a Python script:
import requests
headers = {
'Authorization': 'Bearer glsa_Xh93qMj3OQl39d9F3kDR92h4k2sl39dm_5c49b726',
'Content-Type': 'application/json'
}
response = requests.get(
'https://your-grafana-instance/api/dashboards/uid/my-dashboard',
headers=headers
)
print(response.json())
Practical Example: Automated Dashboard Provisioning
Let's look at a real-world example of using a service account to automatically provision dashboards from a CI/CD pipeline:
- Create a service account with the Editor role
- Generate a token for this service account
- Store the token securely in your CI/CD system's secrets management
- Create a script that provisions dashboards
Here's a sample Python script that could run in a CI/CD pipeline:
import requests
import json
import os
# Get the service account token from environment variable
token = os.environ.get('GRAFANA_SA_TOKEN')
# Dashboard JSON definition
dashboard = {
"dashboard": {
"id": None,
"title": "Automated Dashboard",
"tags": ["automated", "ci-cd"],
"timezone": "browser",
"panels": [
{
"id": 1,
"title": "Panel Title",
"type": "graph",
# Panel configuration would go here
}
],
"schemaVersion": 26,
"version": 0
},
"folderId": 0,
"overwrite": True
}
# API call to create/update the dashboard
headers = {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json'
}
response = requests.post(
'https://your-grafana-instance/api/dashboards/db',
headers=headers,
data=json.dumps(dashboard)
)
if response.status_code == 200:
print("Dashboard successfully provisioned!")
print(response.json())
else:
print(f"Error: {response.status_code}")
print(response.text)
Service Account Permissions
Service accounts in Grafana support fine-grained permissions through Grafana's Role-Based Access Control (RBAC) system. You can:
- Assign basic roles (Viewer, Editor, Admin) when creating the service account
- Modify permissions at any time in the UI
- Assign specific permissions to folders, dashboards, or other resources
Example: Setting Specific Permissions
To set granular permissions:
- Navigate to the service account details
- Go to the Permissions tab
- Click Add permission
- Select the resource type (e.g., Dashboards, Folders)
- Choose the specific resource
- Assign the appropriate permission level
Best Practices for Service Accounts
To use service accounts securely and effectively:
- Least privilege principle: Grant only the permissions needed for the specific task
- One purpose per account: Create separate service accounts for different systems or functions
- Descriptive naming: Use clear names that identify the purpose or system using the account
- Token rotation: Periodically rotate tokens for critical systems
- Regular audits: Review service accounts and their permissions regularly
- Token protection: Store tokens securely, preferably in a secrets manager
- Disable unused accounts: Temporarily disable service accounts when not in use
Troubleshooting Service Accounts
If you encounter issues with service accounts:
- Check permissions: Verify the service account has the necessary permissions
- Verify token: Ensure you're using the correct token and it hasn't been revoked
- Check logs: Examine Grafana server logs for authentication failures
- Test manually: Try the same API call manually to isolate the issue
Common Error Messages
// Invalid token
{
"message": "Invalid Bearer token",
"statusCode": 401
}
// Insufficient permissions
{
"message": "Permission denied",
"statusCode": 403
}
Summary
Service accounts in Grafana provide a secure, manageable way to enable programmatic access to your Grafana instance. They offer significant advantages over traditional API keys, including better permission management, audit trails, and token handling.
By following the guidelines and examples in this article, you can effectively use service accounts to automate various tasks in Grafana, from dashboard provisioning to data source management and alerting configuration.
Additional Resources
Exercises
- Create a service account with Viewer permissions and use it to fetch a list of dashboards via the API.
- Set up a service account that can only access a specific folder of dashboards.
- Create a script that uses a service account to automatically backup your Grafana dashboards to a Git repository.
- Implement a token rotation strategy for an existing service account without disrupting services.
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)