0
# Admin and RBAC
1
2
Administrative functions, user management, role-based access control, service accounts, and system-level operations with comprehensive permission management. This covers both administrative operations and the fine-grained RBAC system introduced in Grafana Enterprise.
3
4
## Capabilities
5
6
### Administrative Operations
7
8
System-level administrative functions for managing users, settings, and global configurations.
9
10
```python { .api }
11
def settings(self):
12
"""
13
Get admin settings and configuration.
14
15
Returns:
16
dict: System settings and configuration parameters
17
"""
18
...
19
20
def stats(self):
21
"""
22
Get admin statistics about the Grafana instance.
23
24
Returns:
25
dict: Usage statistics, user counts, dashboard counts, etc.
26
"""
27
...
28
29
def create_user(self, user: dict):
30
"""
31
Create a new user (admin only).
32
33
Args:
34
user (dict): User data (name, email, login, password, orgId)
35
36
Returns:
37
dict: Created user with ID and metadata
38
"""
39
...
40
41
def change_user_password(self, user_id: int, password: str):
42
"""
43
Change user's password (admin only).
44
45
Args:
46
user_id (int): User ID
47
password (str): New password
48
49
Returns:
50
dict: Password change result
51
"""
52
...
53
54
def change_user_permissions(self, user_id: int, is_grafana_admin: bool):
55
"""
56
Change user's admin permissions (admin only).
57
58
Args:
59
user_id (int): User ID
60
is_grafana_admin (bool): Grant/revoke admin permissions
61
62
Returns:
63
dict: Permission change result
64
"""
65
...
66
67
def delete_user(self, user_id: int):
68
"""
69
Delete user (admin only).
70
71
Args:
72
user_id (int): User ID to delete
73
74
Returns:
75
dict: Deletion result
76
"""
77
...
78
79
def pause_all_alerts(self, pause: bool):
80
"""
81
Pause or unpause all alerts globally (admin only).
82
83
Args:
84
pause (bool): True to pause alerts, False to unpause
85
86
Returns:
87
dict: Pause operation result
88
"""
89
...
90
91
def set_user_enabled(self, user_id: int, enabled: bool):
92
"""
93
Enable or disable user account (admin only).
94
95
Args:
96
user_id (int): User ID
97
enabled (bool): True to enable, False to disable
98
99
Returns:
100
dict: User status change result
101
"""
102
...
103
```
104
105
**Administrative Operations Usage Example:**
106
107
```python
108
from grafana_client import GrafanaApi, TokenAuth
109
110
# Must use admin token/credentials
111
api = GrafanaApi(auth=TokenAuth("admin-token"), host="grafana.example.com")
112
113
# Get system statistics
114
stats = api.admin.stats()
115
print(f"Total users: {stats.get('users', 0)}")
116
print(f"Total dashboards: {stats.get('dashboards', 0)}")
117
print(f"Total organizations: {stats.get('orgs', 0)}")
118
119
# Get system settings (be careful with sensitive data)
120
settings = api.admin.settings()
121
print(f"Grafana version: {settings.get('buildInfo', {}).get('version', 'unknown')}")
122
123
# Create new user
124
new_user = {
125
"name": "John Doe",
126
"email": "john.doe@example.com",
127
"login": "johndoe",
128
"password": "secure-password-123",
129
"orgId": 1
130
}
131
132
created_user = api.admin.create_user(new_user)
133
user_id = created_user['id']
134
print(f"Created user: {user_id}")
135
136
# Grant admin permissions
137
api.admin.change_user_permissions(user_id, is_grafana_admin=True)
138
print(f"Granted admin permissions to user {user_id}")
139
140
# Change user password
141
api.admin.change_user_password(user_id, "new-secure-password-456")
142
print("Password changed")
143
144
# Disable user temporarily
145
api.admin.set_user_enabled(user_id, enabled=False)
146
print("User disabled")
147
148
# Enable user
149
api.admin.set_user_enabled(user_id, enabled=True)
150
print("User enabled")
151
152
# Pause all alerts (emergency operation)
153
api.admin.pause_all_alerts(pause=True)
154
print("All alerts paused")
155
156
# Unpause alerts
157
api.admin.pause_all_alerts(pause=False)
158
print("All alerts unpaused")
159
```
160
161
### Role-Based Access Control (RBAC)
162
163
Fine-grained permission management system for controlling access to resources (Grafana Enterprise feature).
164
165
```python { .api }
166
def get_rbac_roles_all(self):
167
"""
168
Get all RBAC roles available in the system.
169
170
Returns:
171
list: List of all RBAC roles with permissions
172
"""
173
...
174
175
def add_rbac_role_team(self, team_id: int, role_uid: str):
176
"""
177
Add RBAC role to team.
178
179
Args:
180
team_id (int): Team ID
181
role_uid (str): RBAC role UID to assign
182
183
Returns:
184
dict: Role assignment result
185
"""
186
...
187
188
def remove_rbac_role_team(self, team_id: int, role_uid: str):
189
"""
190
Remove RBAC role from team.
191
192
Args:
193
team_id (int): Team ID
194
role_uid (str): RBAC role UID to remove
195
196
Returns:
197
dict: Role removal result
198
"""
199
...
200
201
def get_rbac_datasources(self, datasource_uid: str):
202
"""
203
Get RBAC permissions for data source.
204
205
Args:
206
datasource_uid (str): Data source UID
207
208
Returns:
209
dict: Data source RBAC permissions
210
"""
211
...
212
213
def set_rbac_datasources_teams(self, datasource_uid: str, team_id: int, permission: str):
214
"""
215
Set team RBAC permissions for data source.
216
217
Args:
218
datasource_uid (str): Data source UID
219
team_id (int): Team ID
220
permission (str): Permission level ("Query", "Edit", "Admin")
221
222
Returns:
223
dict: Permission assignment result
224
"""
225
...
226
227
def set_rbac_datasources_builtin_roles(self, datasource_uid: str, builtin_role: str, permission: str):
228
"""
229
Set built-in role RBAC permissions for data source.
230
231
Args:
232
datasource_uid (str): Data source UID
233
builtin_role (str): Built-in role ("Viewer", "Editor", "Admin")
234
permission (str): Permission level ("Query", "Edit", "Admin")
235
236
Returns:
237
dict: Permission assignment result
238
"""
239
...
240
```
241
242
**RBAC Usage Example:**
243
244
```python
245
# Get all available RBAC roles
246
rbac_roles = api.rbac.get_rbac_roles_all()
247
print("Available RBAC roles:")
248
for role in rbac_roles:
249
print(f"- {role['name']} ({role['uid']}): {role.get('description', 'No description')}")
250
251
# Assign specific role to team
252
custom_role_uid = "custom:reports.creator"
253
team_id = 5
254
255
try:
256
api.rbac.add_rbac_role_team(team_id, custom_role_uid)
257
print(f"Assigned role {custom_role_uid} to team {team_id}")
258
except Exception as e:
259
print(f"Failed to assign role: {e}")
260
261
# Get data source permissions
262
datasource_uid = "prometheus-main"
263
ds_permissions = api.rbac.get_rbac_datasources(datasource_uid)
264
print(f"Data source permissions: {ds_permissions}")
265
266
# Set team permissions for data source
267
api.rbac.set_rbac_datasources_teams(
268
datasource_uid=datasource_uid,
269
team_id=team_id,
270
permission="Query" # Query, Edit, or Admin
271
)
272
print(f"Set Query permission for team {team_id} on data source {datasource_uid}")
273
274
# Set built-in role permissions
275
api.rbac.set_rbac_datasources_builtin_roles(
276
datasource_uid=datasource_uid,
277
builtin_role="Editor",
278
permission="Query"
279
)
280
print("Set Query permission for Editor role on data source")
281
282
# Remove role from team
283
api.rbac.remove_rbac_role_team(team_id, custom_role_uid)
284
print(f"Removed role {custom_role_uid} from team {team_id}")
285
```
286
287
### Service Account Management
288
289
Managing service accounts for programmatic access and automation.
290
291
```python { .api }
292
def get(self, service_account_id: int):
293
"""
294
Get service account by ID.
295
296
Args:
297
service_account_id (int): Service account ID
298
299
Returns:
300
dict: Service account information
301
"""
302
...
303
304
def create(self, service_account: dict):
305
"""
306
Create new service account.
307
308
Args:
309
service_account (dict): Service account configuration (name, role)
310
311
Returns:
312
dict: Created service account with ID
313
"""
314
...
315
316
def update(self, service_account_id: int, service_account: dict):
317
"""
318
Update service account.
319
320
Args:
321
service_account_id (int): Service account ID
322
service_account (dict): Updated configuration
323
324
Returns:
325
dict: Update result
326
"""
327
...
328
329
def delete(self, service_account_id: int):
330
"""
331
Delete service account.
332
333
Args:
334
service_account_id (int): Service account ID to delete
335
336
Returns:
337
dict: Deletion result
338
"""
339
...
340
341
def search(self, query: Optional[str] = None, page: int = 1, perpage: int = 1000):
342
"""
343
Search service accounts.
344
345
Args:
346
query (Optional[str]): Search query
347
page (int): Page number (default: 1)
348
perpage (int): Results per page (default: 1000)
349
350
Returns:
351
list: List of service accounts matching criteria
352
"""
353
...
354
355
def search_one(self, service_account_name: str):
356
"""
357
Search for single service account by name.
358
359
Args:
360
service_account_name (str): Service account name
361
362
Returns:
363
dict: Service account if found, None otherwise
364
"""
365
...
366
367
def get_tokens(self, service_account_id: int):
368
"""
369
Get tokens for service account.
370
371
Args:
372
service_account_id (int): Service account ID
373
374
Returns:
375
list: List of tokens associated with service account
376
"""
377
...
378
379
def create_token(self, service_account_id: int, content: dict):
380
"""
381
Create token for service account.
382
383
Args:
384
service_account_id (int): Service account ID
385
content (dict): Token configuration (name, secondsToLive)
386
387
Returns:
388
dict: Created token with key (only returned once)
389
"""
390
...
391
392
def delete_token(self, service_account_id: int, service_account_token_id: int):
393
"""
394
Delete service account token.
395
396
Args:
397
service_account_id (int): Service account ID
398
service_account_token_id (int): Token ID to delete
399
400
Returns:
401
dict: Deletion result
402
"""
403
...
404
```
405
406
**Service Account Management Usage Example:**
407
408
```python
409
# Create service account for automation
410
automation_sa = {
411
"name": "automation-service",
412
"role": "Editor" # Viewer, Editor, or Admin
413
}
414
415
created_sa = api.serviceaccount.create(automation_sa)
416
sa_id = created_sa['id']
417
print(f"Created service account: {sa_id}")
418
419
# Create token for service account
420
token_config = {
421
"name": "automation-token-prod",
422
"secondsToLive": 86400 * 365 # 1 year
423
}
424
425
token_result = api.serviceaccount.create_token(sa_id, token_config)
426
token_key = token_result['key'] # Store this securely - only shown once
427
print(f"Created token: {token_result['name']} (expires: {token_result['expiration']})")
428
429
# Search service accounts
430
all_service_accounts = api.serviceaccount.search()
431
print(f"Total service accounts: {len(all_service_accounts)}")
432
433
# Search for specific service account
434
automation_accounts = api.serviceaccount.search(query="automation")
435
for sa in automation_accounts:
436
print(f"Service account: {sa['name']} (ID: {sa['id']}, Role: {sa['role']})")
437
438
# Find service account by name
439
specific_sa = api.serviceaccount.search_one("automation-service")
440
if specific_sa:
441
print(f"Found service account: {specific_sa['name']}")
442
443
# Get service account details
444
sa_details = api.serviceaccount.get(sa_id)
445
print(f"Service account details: {sa_details}")
446
447
# List tokens for service account
448
tokens = api.serviceaccount.get_tokens(sa_id)
449
print(f"Service account has {len(tokens)} tokens")
450
for token in tokens:
451
print(f"Token: {token['name']} (ID: {token['id']}, Expires: {token['expiration']})")
452
453
# Update service account
454
api.serviceaccount.update(sa_id, {
455
"name": "automation-service-updated",
456
"role": "Admin"
457
})
458
print("Service account updated")
459
460
# Delete token (when rotating)
461
if tokens:
462
token_to_delete = tokens[0]['id']
463
api.serviceaccount.delete_token(sa_id, token_to_delete)
464
print(f"Deleted token {token_to_delete}")
465
466
# Create new token for rotation
467
new_token = api.serviceaccount.create_token(sa_id, {
468
"name": "automation-token-rotated",
469
"secondsToLive": 86400 * 90 # 90 days
470
})
471
print(f"Created replacement token: {new_token['name']}")
472
```
473
474
### Health and System Monitoring
475
476
System health checks and monitoring capabilities for administrative oversight.
477
478
```python { .api }
479
# Health check (via Health API)
480
def check(self):
481
"""
482
Check Grafana system health.
483
484
Returns:
485
dict: Health status information
486
"""
487
...
488
```
489
490
**System Health Usage Example:**
491
492
```python
493
# Check system health
494
try:
495
health_status = api.health.check()
496
print(f"System health: {health_status}")
497
498
if health_status.get('database') == 'ok':
499
print("Database connection is healthy")
500
else:
501
print("Database connection issues detected")
502
503
except Exception as e:
504
print(f"Health check failed: {e}")
505
506
# Combined admin monitoring
507
def admin_health_check():
508
"""Comprehensive admin health check"""
509
try:
510
# System stats
511
stats = api.admin.stats()
512
print(f"System load - Users: {stats.get('users', 0)}, "
513
f"Dashboards: {stats.get('dashboards', 0)}, "
514
f"Data sources: {stats.get('datasources', 0)}")
515
516
# Health status
517
health = api.health.check()
518
print(f"Health status: {health}")
519
520
# Service accounts audit
521
service_accounts = api.serviceaccount.search()
522
print(f"Active service accounts: {len(service_accounts)}")
523
524
return True
525
except Exception as e:
526
print(f"Admin health check failed: {e}")
527
return False
528
529
# Run comprehensive check
530
admin_health_check()
531
```
532
533
### Bulk Administrative Operations
534
535
Performing administrative operations at scale:
536
537
```python
538
# Bulk user management
539
def bulk_user_operations():
540
"""Example of bulk user management operations"""
541
542
# Get all users for audit
543
all_users = api.users.search_users()
544
print(f"Total users to audit: {len(all_users)}")
545
546
admin_users = []
547
inactive_users = []
548
549
for user in all_users:
550
user_details = api.users.get_user(user['id'])
551
552
# Check if user is admin
553
if user_details.get('isGrafanaAdmin', False):
554
admin_users.append(user_details)
555
556
# Check last login (if available in user details)
557
# This would depend on your Grafana version and configuration
558
if not user_details.get('lastSeenAt'):
559
inactive_users.append(user_details)
560
561
print(f"Admin users: {len(admin_users)}")
562
print(f"Potentially inactive users: {len(inactive_users)}")
563
564
# Disable inactive users (with caution)
565
for user in inactive_users[:5]: # Limit to first 5 for safety
566
try:
567
api.admin.set_user_enabled(user['id'], enabled=False)
568
print(f"Disabled inactive user: {user['login']}")
569
except Exception as e:
570
print(f"Failed to disable user {user['login']}: {e}")
571
572
# Bulk RBAC operations
573
def bulk_rbac_setup():
574
"""Set up RBAC permissions for multiple teams and data sources"""
575
576
# Get all teams
577
teams = api.teams.search_teams()
578
579
# Get all data sources
580
datasources = api.datasource.list_datasources()
581
582
# Define permission mapping
583
team_permissions = {
584
"DevOps": "Admin",
585
"Development": "Edit",
586
"QA": "Query",
587
"Support": "Query"
588
}
589
590
for team in teams:
591
team_name = team['name']
592
if team_name in team_permissions:
593
permission = team_permissions[team_name]
594
595
# Apply permission to all data sources
596
for ds in datasources:
597
try:
598
api.rbac.set_rbac_datasources_teams(
599
datasource_uid=ds['uid'],
600
team_id=team['id'],
601
permission=permission
602
)
603
print(f"Set {permission} permission for team {team_name} on {ds['name']}")
604
except Exception as e:
605
print(f"Failed to set permission: {e}")
606
607
# Run bulk operations (with caution)
608
# bulk_user_operations()
609
# bulk_rbac_setup()
610
```
611
612
### Error Handling
613
614
Administrative operation error handling:
615
616
```python
617
from grafana_client import GrafanaClientError, GrafanaUnauthorizedError
618
619
try:
620
# Administrative operation requiring admin privileges
621
stats = api.admin.stats()
622
623
except GrafanaUnauthorizedError as e:
624
print(f"Admin access required: {e.message}")
625
print("Current user does not have admin privileges")
626
627
except GrafanaClientError as e:
628
if e.status_code == 403:
629
print("Forbidden: Insufficient permissions for admin operation")
630
else:
631
print(f"Admin operation failed: {e.message}")
632
633
# Service account operation error handling
634
try:
635
# Create service account with invalid data
636
invalid_sa = {
637
"name": "", # Empty name
638
"role": "InvalidRole" # Invalid role
639
}
640
api.serviceaccount.create(invalid_sa)
641
642
except Exception as e:
643
print(f"Service account creation failed: {e}")
644
```
645
646
### Async Admin and RBAC Operations
647
648
All admin and RBAC operations support async versions:
649
650
```python
651
import asyncio
652
from grafana_client import AsyncGrafanaApi, TokenAuth
653
654
async def async_admin_operations():
655
api = AsyncGrafanaApi(auth=TokenAuth("admin-token"), host="grafana.example.com")
656
657
# Concurrent admin operations
658
admin_tasks = [
659
api.admin.stats(),
660
api.admin.settings(),
661
api.rbac.get_rbac_roles_all(),
662
api.serviceaccount.search()
663
]
664
665
stats, settings, rbac_roles, service_accounts = await asyncio.gather(*admin_tasks)
666
667
print(f"System stats: {len(stats)} metrics")
668
print(f"RBAC roles: {len(rbac_roles)}")
669
print(f"Service accounts: {len(service_accounts)}")
670
671
# Concurrent service account token management
672
token_tasks = []
673
for sa in service_accounts[:3]: # First 3 service accounts
674
task = api.serviceaccount.get_tokens(sa['id'])
675
token_tasks.append(task)
676
677
token_results = await asyncio.gather(*token_tasks, return_exceptions=True)
678
679
for i, tokens in enumerate(token_results):
680
if isinstance(tokens, Exception):
681
print(f"Failed to get tokens for SA {i}: {tokens}")
682
else:
683
print(f"Service account {i} has {len(tokens)} tokens")
684
685
asyncio.run(async_admin_operations())
686
```
687
688
### Best Practices
689
690
1. **Security First**: Always use principle of least privilege for admin operations
691
2. **Audit Regularly**: Monitor admin actions and service account usage
692
3. **Token Rotation**: Implement regular rotation for service account tokens
693
4. **RBAC Planning**: Design RBAC roles and permissions systematically
694
5. **Backup First**: Always backup before bulk administrative changes
695
6. **Error Handling**: Implement robust error handling for admin operations
696
7. **Monitoring**: Monitor system health and performance metrics
697
8. **Documentation**: Document all administrative procedures and RBAC policies