-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1393 lines (1191 loc) · 60.6 KB
/
main.py
File metadata and controls
1393 lines (1191 loc) · 60.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import argparse
import importlib.util
import json
import os
import pprint
import re
from rootly_sdk import AuthenticatedClient
from rootly_sdk.api.services import create_service, list_services, update_service
from rootly_sdk.api.roles import create_role, list_roles, update_role
from rootly_sdk.api.teams import create_team, list_teams, update_team
from rootly_sdk.api.alert_sources import create_alerts_source, list_alerts_sources, update_alerts_source
from rootly_sdk.api.alert_routes import create_alert_route, list_alert_routes, update_alert_route
from rootly_sdk.api.escalation_policies import (
create_escalation_policy,
list_escalation_policies,
update_escalation_policy,
)
from rootly_sdk.models.new_service import NewService
from rootly_sdk.models.new_role import NewRole
from rootly_sdk.models.new_team import NewTeam
from rootly_sdk.models.update_service import UpdateService
from rootly_sdk.models.update_role import UpdateRole
from rootly_sdk.models.update_team import UpdateTeam
from rootly_sdk.models.new_alerts_source import NewAlertsSource
from rootly_sdk.models.update_alerts_source import UpdateAlertsSource
from rootly_sdk.models.new_alert_route import NewAlertRoute
from rootly_sdk.models.update_alert_route import UpdateAlertRoute
from rootly_sdk.models.new_escalation_policy import NewEscalationPolicy
from rootly_sdk.models.update_escalation_policy import UpdateEscalationPolicy
from rootly_sdk.types import UNSET
# --- Additional SDK imports for Pulumi-import coverage ---
from rootly_sdk.api.environments import list_environments
from rootly_sdk.api.severities import list_severities
from rootly_sdk.api.functionalities import list_functionalities
from rootly_sdk.api.causes import list_causes
from rootly_sdk.api.incident_types import list_incident_types
from rootly_sdk.api.incident_roles import list_incident_roles
from rootly_sdk.api.incident_role_tasks import list_incident_role_tasks
from rootly_sdk.api.schedules import list_schedules
from rootly_sdk.api.schedule_rotations import list_schedule_rotations
from rootly_sdk.api.schedule_rotation_active_days import list_schedule_rotation_active_days
from rootly_sdk.api.schedule_rotation_users import list_schedule_rotation_users
from rootly_sdk.api.playbooks import list_playbooks
from rootly_sdk.api.playbook_tasks import list_playbook_tasks
from rootly_sdk.api.webhooks_endpoints import list_webhooks_endpoints
from rootly_sdk.api.secrets import list_secrets
from rootly_sdk.api.status_pages import list_status_pages
from rootly_sdk.api.status_page_templates import list_status_page_templates
from rootly_sdk.api.form_fields import list_form_fields
from rootly_sdk.api.form_field_options import list_form_field_options
from rootly_sdk.api.form_field_positions import list_form_field_positions
from rootly_sdk.api.custom_forms import list_custom_forms
from rootly_sdk.api.incident_permission_sets import list_incident_permission_sets
from rootly_sdk.api.incident_permission_set_booleans import list_incident_permission_set_booleans
from rootly_sdk.api.incident_permission_set_resources import list_incident_permission_set_resources
from rootly_sdk.api.workflows import list_workflows
from rootly_sdk.api.workflow_groups import list_workflow_groups
from rootly_sdk.api.retrospective_templates import list_postmortem_templates
from rootly_sdk.api.retrospective_processes import list_retrospective_processes
from rootly_sdk.api.retrospective_steps import list_retrospective_steps
from rootly_sdk.api.retrospective_configurations import list_retrospective_configurations
from rootly_sdk.api.dashboards import list_dashboards
from rootly_sdk.api.dashboard_panels import list_dashboard_panels
from rootly_sdk.api.escalation_paths import list_escalation_paths
from rootly_sdk.api.escalation_levels_path import list_escalation_levels_paths
from rootly_sdk.models.action_item_trigger_params import ActionItemTriggerParams
from rootly_sdk.models.alert_trigger_params import AlertTriggerParams
from rootly_sdk.models.incident_trigger_params import IncidentTriggerParams
from rootly_sdk.models.pulse_trigger_params import PulseTriggerParams
from rootly_sdk.models.simple_trigger_params import SimpleTriggerParams
DATA_FILE = os.path.join(os.path.dirname(__file__), "data.py")
# Writable service fields that are readable from the Service response model.
# Excludes read-only fields (created_at, updated_at, slug, alerts_email_address)
# and fields present in NewServiceDataAttributes but absent from Service
# (opsgenie_team_id, show_uptime, show_uptime_last_days).
_SERVICE_SIMPLE_WRITABLE = [
"name", "description", "public_description", "notify_emails", "color", "position",
"backstage_id", "pagerduty_id", "external_id", "opsgenie_id", "cortex_id",
"service_now_ci_sys_id", "github_repository_name", "github_repository_branch",
"gitlab_repository_name", "gitlab_repository_branch", "environment_ids",
"service_ids", "owner_group_ids", "owner_user_ids", "kubernetes_deployment_name",
"alerts_email_enabled", "alert_urgency_id", "escalation_policy_id",
"alert_broadcast_enabled", "incident_broadcast_enabled",
]
# Writable team fields that are readable from the Team response model.
# Excludes read-only fields (created_at, updated_at, slug, alerts_email_address)
# and opsgenie_team_id (create-only, absent from Team response and UpdateTeamDataAttributes).
_TEAM_SIMPLE_WRITABLE = [
"name", "description", "notify_emails", "color", "position",
"backstage_id", "external_id", "pagerduty_id", "pagerduty_service_id",
"opsgenie_id", "victor_ops_id", "pagertree_id", "cortex_id",
"service_now_ci_sys_id", "user_ids", "admin_ids",
"alerts_email_enabled", "alert_urgency_id",
"alert_broadcast_enabled", "incident_broadcast_enabled",
"auto_add_members_when_attached",
]
# Alert source fields that exist only in the response (server-generated); strip on export.
_ALERT_SOURCE_READ_ONLY = {"status", "secret", "created_at", "updated_at", "email", "webhook_endpoint"}
# Writable fields for nested alert source sub-resources.
_URGENCY_RULE_WRITABLE = {"json_path", "operator", "value", "conditionable_type", "conditionable_id", "kind", "alert_urgency_id"}
_ALERT_FIELD_WRITABLE = {"alert_field_id", "template_body"}
_ALERT_TEMPLATE_WRITABLE = {"title", "description", "external_url"}
# Escalation policy fields that exist only in the response; strip on export.
_ESCALATION_POLICY_READ_ONLY = {"created_by_user_id", "last_updated_by_user_id", "created_at", "updated_at"}
# Common server-generated fields present on most resources.
_COMMON_READ_ONLY = {"created_at", "updated_at"}
# Per-type additional read-only fields (beyond _COMMON_READ_ONLY).
# slug is auto-generated from name on create, so strip it to avoid conflicts on re-import.
_SLUG_FIELD = {"slug"}
_WEBHOOK_READ_ONLY = _COMMON_READ_ONLY | _SLUG_FIELD | {"secret"} # server-generated HMAC secret
_POST_MORTEM_READ_ONLY = _COMMON_READ_ONLY | _SLUG_FIELD | {"content_html", "content_json"} # derived render fields
_WORKFLOW_READ_ONLY = _COMMON_READ_ONLY | _SLUG_FIELD | {"created_by_user_id", "last_updated_by_user_id"}
# All writable permission list fields on roles.
_ROLE_PERMISSION_FIELDS = [
"alerts_permissions", "api_keys_permissions", "audits_permissions",
"billing_permissions", "environments_permissions", "form_fields_permissions",
"functionalities_permissions", "groups_permissions", "incident_causes_permissions",
"incident_feedbacks_permissions", "incident_roles_permissions", "incident_types_permissions",
"incidents_permissions", "integrations_permissions", "invitations_permissions",
"playbooks_permissions", "private_incidents_permissions", "pulses_permissions",
"retrospective_permissions", "roles_permissions", "secrets_permissions",
"services_permissions", "severities_permissions", "status_pages_permissions",
"webhooks_permissions", "workflows_permissions",
]
# --- Pagination helpers ---
def fetch_all_services(client: AuthenticatedClient) -> list:
"""Fetch every service from Rootly, handling pagination."""
items = []
page = 1
while True:
response = list_services.sync_detailed(client=client, pagenumber=page, pagesize=100)
if response.status_code != 200 or response.parsed is None:
print(f"Error fetching services (page {page}): {response.status_code}")
break
items.extend(response.parsed.data)
if response.parsed.links.next_ is None:
break
page += 1
return items
def fetch_all_roles(client: AuthenticatedClient) -> list:
"""Fetch every role from Rootly, handling pagination."""
items = []
page = 1
while True:
response = list_roles.sync_detailed(client=client, pagenumber=page, pagesize=100)
if response.status_code != 200 or response.parsed is None:
print(f"Error fetching roles (page {page}): {response.status_code}")
break
items.extend(response.parsed.data)
if response.parsed.links.next_ is None:
break
page += 1
return items
def fetch_all_teams(client: AuthenticatedClient) -> list:
"""Fetch every team from Rootly, handling pagination."""
items = []
page = 1
while True:
response = list_teams.sync_detailed(client=client, pagenumber=page, pagesize=100)
if response.status_code != 200 or response.parsed is None:
print(f"Error fetching teams (page {page}): {response.status_code}")
break
items.extend(response.parsed.data)
if response.parsed.links.next_ is None:
break
page += 1
return items
def fetch_all_alert_sources(client: AuthenticatedClient) -> list:
"""Fetch every alert source from Rootly, handling pagination."""
items = []
page = 1
while True:
response = list_alerts_sources.sync_detailed(client=client, pagenumber=page, pagesize=100)
if response.status_code != 200 or response.parsed is None:
print(f"Error fetching alert sources (page {page}): {response.status_code}")
break
items.extend(response.parsed.data)
if response.parsed.links.next_ is None:
break
page += 1
return items
def fetch_all_alert_routes(client: AuthenticatedClient) -> list:
"""Fetch every alert route from Rootly, handling pagination."""
items = []
page = 1
while True:
response = list_alert_routes.sync_detailed(client=client, pagenumber=page, pagesize=100)
if response.status_code != 200 or response.parsed is None:
print(f"Error fetching alert routes (page {page}): {response.status_code}")
break
items.extend(response.parsed.data)
if response.parsed.links.next_ is None:
break
page += 1
return items
def fetch_all_escalation_policies(client: AuthenticatedClient) -> list:
"""Fetch every escalation policy from Rootly, handling pagination."""
items = []
page = 1
while True:
response = list_escalation_policies.sync_detailed(client=client, pagenumber=page, pagesize=100)
if response.status_code != 200 or response.parsed is None:
print(f"Error fetching escalation policies (page {page}): {response.status_code}")
break
items.extend(response.parsed.data)
if response.parsed.links.next_ is None:
break
page += 1
return items
# --- Generic fetch helpers for Pulumi-import coverage ---
def _fetch_paginated_list(client: AuthenticatedClient, list_fn, label: str) -> list:
"""Generic paginated top-level resource fetcher.
Works with any list function whose sync_detailed() accepts ``client``,
``pagenumber``, and ``pagesize`` and returns a response whose ``.parsed``
has a ``.data`` list and an optional ``.links.next_`` sentinel.
"""
items = []
page = 1
while True:
response = list_fn.sync_detailed(client=client, pagenumber=page, pagesize=100)
if response.status_code != 200 or response.parsed is None:
print(f" Error fetching {label} (page {page}): {response.status_code}")
break
items.extend(response.parsed.data)
links = getattr(response.parsed, "links", None)
if links is None or links.next_ is None:
break
page += 1
return items
def _fetch_sub_resource_list(client: AuthenticatedClient, list_fn, parent_items: list, label: str) -> list:
"""Generic sub-resource fetcher.
For each item in *parent_items*, calls ``list_fn.sync_detailed(parent.id, …)``
and collects all paginated results. The parent ID is passed as the first
positional argument, matching the SDK's convention for every child endpoint.
"""
items = []
for parent in parent_items:
page = 1
while True:
response = list_fn.sync_detailed(str(parent.id), client=client, pagenumber=page, pagesize=100)
if response.status_code != 200 or response.parsed is None:
print(f" Error fetching {label} for parent {parent.id}: {response.status_code}")
break
items.extend(response.parsed.data)
links = getattr(response.parsed, "links", None)
if links is None or links.next_ is None:
break
page += 1
return items
# --- Conversion helpers ---
def service_to_writable_dict(item) -> dict:
"""Extract only writable attributes from a ServiceListDataItem."""
attrs = item.attributes
d = {}
for field in _SERVICE_SIMPLE_WRITABLE:
val = getattr(attrs, field)
if val is not UNSET and val is not None:
d[field] = val
# Complex fields whose values are SDK objects that need serialization.
if attrs.slack_channels is not UNSET and attrs.slack_channels is not None:
d["slack_channels"] = [ch.to_dict() for ch in attrs.slack_channels]
if attrs.slack_aliases is not UNSET and attrs.slack_aliases is not None:
d["slack_aliases"] = [a.to_dict() for a in attrs.slack_aliases]
if attrs.alert_broadcast_channel is not UNSET and attrs.alert_broadcast_channel is not None:
d["alert_broadcast_channel"] = attrs.alert_broadcast_channel.to_dict()
if attrs.incident_broadcast_channel is not UNSET and attrs.incident_broadcast_channel is not None:
d["incident_broadcast_channel"] = attrs.incident_broadcast_channel.to_dict()
return d
def role_to_writable_dict(item) -> dict:
"""Extract only writable attributes from a RoleListDataItem."""
attrs = item.attributes
# name and slug are always present on a Role response.
d = {"name": attrs.name, "slug": attrs.slug}
if attrs.incident_permission_set_id is not UNSET and attrs.incident_permission_set_id is not None:
d["incident_permission_set_id"] = attrs.incident_permission_set_id
for field in _ROLE_PERMISSION_FIELDS:
val = getattr(attrs, field)
# val is a list (possibly empty); only include if non-empty.
if val is not UNSET and len(val) > 0:
d[field] = list(val)
return d
def team_to_writable_dict(item) -> dict:
"""Extract only writable attributes from a TeamListDataItem."""
attrs = item.attributes
d = {}
for field in _TEAM_SIMPLE_WRITABLE:
val = getattr(attrs, field)
if val is not UNSET and val is not None:
d[field] = val
# Complex fields whose values are SDK objects that need serialization.
if attrs.slack_channels is not UNSET and attrs.slack_channels is not None:
d["slack_channels"] = [ch.to_dict() for ch in attrs.slack_channels]
if attrs.slack_aliases is not UNSET and attrs.slack_aliases is not None:
d["slack_aliases"] = [a.to_dict() for a in attrs.slack_aliases]
if attrs.alert_broadcast_channel is not UNSET and attrs.alert_broadcast_channel is not None:
d["alert_broadcast_channel"] = attrs.alert_broadcast_channel.to_dict()
if attrs.incident_broadcast_channel is not UNSET and attrs.incident_broadcast_channel is not None:
d["incident_broadcast_channel"] = attrs.incident_broadcast_channel.to_dict()
return d
def alert_source_to_writable_dict(item) -> dict:
"""Extract only writable attributes from an AlertsSourceListDataItem.
Calls the SDK's own to_dict() for correct serialization (e.g. enum → str),
then strips server-generated read-only keys (top-level and nested).
"""
d = item.attributes.to_dict()
for key in _ALERT_SOURCE_READ_ONLY:
d.pop(key, None)
# Strip read-only and None fields from urgency rule items.
if d.get("alert_source_urgency_rules_attributes"):
d["alert_source_urgency_rules_attributes"] = [
{k: v for k, v in rule.items() if k in _URGENCY_RULE_WRITABLE and v is not None}
for rule in d["alert_source_urgency_rules_attributes"]
]
# Strip read-only fields from alert field items (keep only alert_field_id + template_body).
if d.get("alert_source_fields_attributes"):
d["alert_source_fields_attributes"] = [
{k: v for k, v in field.items() if k in _ALERT_FIELD_WRITABLE}
for field in d["alert_source_fields_attributes"]
]
# Strip read-only fields from alert template (keep only title, description, external_url).
if d.get("alert_template_attributes") and isinstance(d["alert_template_attributes"], dict):
d["alert_template_attributes"] = {
k: v for k, v in d["alert_template_attributes"].items()
if k in _ALERT_TEMPLATE_WRITABLE
}
return d
def alert_route_to_writable_dict(item) -> dict:
"""Extract all attributes from an AlertRouteListDataItem.
AlertRoute has no server-generated read-only fields; to_dict() handles
UUID → str serialization for alerts_source_ids and owning_team_ids.
"""
return item.attributes.to_dict()
def escalation_policy_to_writable_dict(item) -> dict:
"""Extract only writable attributes from an EscalationPolicyListDataItem.
Calls the SDK's own to_dict() for correct serialization (business_hours),
then strips server-generated read-only keys.
"""
d = item.attributes.to_dict()
for key in _ESCALATION_POLICY_READ_ONLY:
d.pop(key, None)
return d
def _generic_to_writable_dict(item, read_only: set | None = None) -> dict:
"""Generic writable-dict extractor for resources with no special nesting.
Uses the SDK's own to_dict() for correct enum/UUID serialisation, then
strips the specified read-only fields (default: created_at + updated_at).
None values are removed so the resulting dict stays compact.
"""
d = item.attributes.to_dict()
for key in (read_only if read_only is not None else _COMMON_READ_ONLY):
d.pop(key, None)
return {k: v for k, v in d.items() if v is not None}
def workflow_to_writable_dict(item) -> dict:
"""Extract only writable attributes from a WorkflowListDataItem."""
d = item.attributes.to_dict()
for key in _WORKFLOW_READ_ONLY:
d.pop(key, None)
return {k: v for k, v in d.items() if v is not None}
# --- Report field specs ---
#
# Each entry is a (label, extractor_fn) tuple where:
# extractor_fn(item, context) -> str
#
# 'context' is a dict with:
# "id_to_name": dict[str, str] - maps service id -> service name
#
# The first field in each list is printed as the item heading (no label/indent).
# All subsequent fields are printed indented with aligned labels.
# To add a new field, append a tuple here.
def _resolve_service_names(ids, id_to_name: dict) -> str:
if not ids or ids is UNSET:
return "(none)"
return ", ".join(id_to_name.get(sid, sid) for sid in ids)
SERVICE_REPORT_FIELDS = [
("Name", lambda item, ctx: item.attributes.name),
("ID", lambda item, ctx: item.id),
("Dependencies", lambda item, ctx: _resolve_service_names(
item.attributes.service_ids
if item.attributes.service_ids not in (None, UNSET)
else [],
ctx["id_to_name"],
)),
]
ROLE_REPORT_FIELDS = [
("Name", lambda item, ctx: item.attributes.name),
("Slug", lambda item, ctx: item.attributes.slug),
]
TEAM_REPORT_FIELDS = [
("Name", lambda item, ctx: item.attributes.name),
("Slug", lambda item, ctx: item.attributes.slug),
]
ALERT_SOURCE_REPORT_FIELDS = [
("Name", lambda item, ctx: item.attributes.name),
("ID", lambda item, ctx: item.id),
("Source Type", lambda item, ctx: item.attributes.source_type if item.attributes.source_type is not UNSET else "(none)"),
("Status", lambda item, ctx: item.attributes.status),
]
ALERT_ROUTE_REPORT_FIELDS = [
("Name", lambda item, ctx: item.attributes.name),
("ID", lambda item, ctx: item.id),
("Enabled", lambda item, ctx: item.attributes.enabled if item.attributes.enabled is not UNSET else "(unset)"),
("Sources", lambda item, ctx: ", ".join(str(sid) for sid in item.attributes.alerts_source_ids)
if item.attributes.alerts_source_ids else "(none)"),
]
ESCALATION_POLICY_REPORT_FIELDS = [
("Name", lambda item, ctx: item.attributes.name),
("ID", lambda item, ctx: item.id),
("Repeat Count", lambda item, ctx: item.attributes.repeat_count),
("Description", lambda item, ctx: item.attributes.description
if item.attributes.description not in (None, UNSET) else "(none)"),
]
def _print_section(title: str, items: list, fields: list, context: dict) -> None:
"""Print one report section with aligned labels."""
label_width = max((len(label) for label, _ in fields[1:]), default=0)
heading_fn = fields[0][1]
print(f"\n{title} ({len(items)})")
print("=" * 60)
for item in items:
print(heading_fn(item, context))
for label, extractor in fields[1:]:
print(f" {label:<{label_width}}: {extractor(item, context)}")
print()
def print_report(client: AuthenticatedClient) -> None:
"""Print a human-readable report of all resources."""
print("Fetching all services...")
service_items = fetch_all_services(client)
print("Fetching all roles...")
role_items = fetch_all_roles(client)
print("Fetching all teams...")
team_items = fetch_all_teams(client)
print("Fetching all alert sources...")
alert_source_items = fetch_all_alert_sources(client)
print("Fetching all alert routes...")
alert_route_items = fetch_all_alert_routes(client)
print("Fetching all escalation policies...")
escalation_policy_items = fetch_all_escalation_policies(client)
id_to_name = {item.id: item.attributes.name for item in service_items}
context = {"id_to_name": id_to_name}
_print_section("Services", service_items, SERVICE_REPORT_FIELDS, context)
_print_section("Roles", role_items, ROLE_REPORT_FIELDS, context)
_print_section("Teams", team_items, TEAM_REPORT_FIELDS, context)
_print_section("Alert Sources", alert_source_items, ALERT_SOURCE_REPORT_FIELDS, context)
_print_section("Alert Routes", alert_route_items, ALERT_ROUTE_REPORT_FIELDS, context)
_print_section("Escalation Policies", escalation_policy_items, ESCALATION_POLICY_REPORT_FIELDS, context)
# --- Export ---
def export_to_data_file(client: AuthenticatedClient) -> None:
"""Fetch all resources from Rootly and overwrite data.py."""
def _fetch_and_convert(label: str, list_fn, converter) -> list:
"""Fetch a paginated top-level resource and apply converter."""
print(f"Fetching all {label}...")
items = _fetch_paginated_list(client, list_fn, label)
converted = [converter(i) for i in items]
print(f" Fetched {len(converted)} {label}.")
return converted
# --- existing resources ---
print("Fetching all services...")
service_items = fetch_all_services(client)
services = [service_to_writable_dict(s) for s in service_items]
print(f" Fetched {len(services)} services.")
print("Fetching all roles...")
role_items = fetch_all_roles(client)
roles = [role_to_writable_dict(r) for r in role_items]
print(f" Fetched {len(roles)} roles.")
print("Fetching all teams...")
team_items = fetch_all_teams(client)
teams = [team_to_writable_dict(t) for t in team_items]
print(f" Fetched {len(teams)} teams.")
print("Fetching all alert sources...")
alert_source_items = fetch_all_alert_sources(client)
alert_sources = [alert_source_to_writable_dict(s) for s in alert_source_items]
print(f" Fetched {len(alert_sources)} alert sources.")
print("Fetching all alert routes...")
alert_route_items = fetch_all_alert_routes(client)
alert_routes = [alert_route_to_writable_dict(r) for r in alert_route_items]
print(f" Fetched {len(alert_routes)} alert routes.")
print("Fetching all escalation policies...")
escalation_policy_items = fetch_all_escalation_policies(client)
escalation_policies = [escalation_policy_to_writable_dict(p) for p in escalation_policy_items]
print(f" Fetched {len(escalation_policies)} escalation policies.")
# --- newly covered resources ---
_ro = _COMMON_READ_ONLY | _SLUG_FIELD # strip created_at/updated_at/slug for most
environments = _fetch_and_convert("environments", list_environments, lambda i: _generic_to_writable_dict(i, _ro))
severities = _fetch_and_convert("severities", list_severities, lambda i: _generic_to_writable_dict(i, _ro))
functionalities = _fetch_and_convert("functionalities", list_functionalities, lambda i: _generic_to_writable_dict(i, _ro))
causes = _fetch_and_convert("causes", list_causes, lambda i: _generic_to_writable_dict(i, _ro))
incident_types = _fetch_and_convert("incident types", list_incident_types, lambda i: _generic_to_writable_dict(i, _ro))
incident_roles = _fetch_and_convert("incident roles", list_incident_roles, lambda i: _generic_to_writable_dict(i, _ro))
schedules = _fetch_and_convert("schedules", list_schedules, lambda i: _generic_to_writable_dict(i, _COMMON_READ_ONLY))
playbooks = _fetch_and_convert("playbooks", list_playbooks, lambda i: _generic_to_writable_dict(i, _COMMON_READ_ONLY))
webhooks_endpoints = _fetch_and_convert("webhooks endpoints", list_webhooks_endpoints, lambda i: _generic_to_writable_dict(i, _WEBHOOK_READ_ONLY))
secrets = _fetch_and_convert("secrets", list_secrets, lambda i: _generic_to_writable_dict(i, _COMMON_READ_ONLY))
status_pages = _fetch_and_convert("status pages", list_status_pages, lambda i: _generic_to_writable_dict(i, _ro))
form_fields = _fetch_and_convert("form fields", list_form_fields, lambda i: _generic_to_writable_dict(i, _ro))
custom_forms = _fetch_and_convert("custom forms", list_custom_forms, lambda i: _generic_to_writable_dict(i, _ro))
incident_permission_sets = _fetch_and_convert("incident permission sets", list_incident_permission_sets, lambda i: _generic_to_writable_dict(i, _ro))
workflows = _fetch_and_convert("workflows", list_workflows, workflow_to_writable_dict)
workflow_groups = _fetch_and_convert("workflow groups", list_workflow_groups, lambda i: _generic_to_writable_dict(i, _ro))
postmortem_templates = _fetch_and_convert("post-mortem templates", list_postmortem_templates, lambda i: _generic_to_writable_dict(i, _POST_MORTEM_READ_ONLY))
retrospective_processes = _fetch_and_convert("retrospective processes", list_retrospective_processes, lambda i: _generic_to_writable_dict(i, _COMMON_READ_ONLY))
retrospective_configurations = _fetch_and_convert("retrospective configurations", list_retrospective_configurations, lambda i: _generic_to_writable_dict(i, _COMMON_READ_ONLY))
dashboards = _fetch_and_convert("dashboards", list_dashboards, lambda i: _generic_to_writable_dict(i, _COMMON_READ_ONLY))
def fmt(obj):
return pprint.pformat(obj, indent=4, sort_dicts=False)
content = (
f"SERVICES = {fmt(services)}\n\n"
f"ROLES = {fmt(roles)}\n\n"
f"TEAMS = {fmt(teams)}\n\n"
f"ALERT_SOURCES = {fmt(alert_sources)}\n\n"
f"ALERT_ROUTES = {fmt(alert_routes)}\n\n"
f"ESCALATION_POLICIES = {fmt(escalation_policies)}\n\n"
f"ENVIRONMENTS = {fmt(environments)}\n\n"
f"SEVERITIES = {fmt(severities)}\n\n"
f"FUNCTIONALITIES = {fmt(functionalities)}\n\n"
f"CAUSES = {fmt(causes)}\n\n"
f"INCIDENT_TYPES = {fmt(incident_types)}\n\n"
f"INCIDENT_ROLES = {fmt(incident_roles)}\n\n"
f"SCHEDULES = {fmt(schedules)}\n\n"
f"PLAYBOOKS = {fmt(playbooks)}\n\n"
f"WEBHOOKS_ENDPOINTS = {fmt(webhooks_endpoints)}\n\n"
f"SECRETS = {fmt(secrets)}\n\n"
f"STATUS_PAGES = {fmt(status_pages)}\n\n"
f"FORM_FIELDS = {fmt(form_fields)}\n\n"
f"CUSTOM_FORMS = {fmt(custom_forms)}\n\n"
f"INCIDENT_PERMISSION_SETS = {fmt(incident_permission_sets)}\n\n"
f"WORKFLOWS = {fmt(workflows)}\n\n"
f"WORKFLOW_GROUPS = {fmt(workflow_groups)}\n\n"
f"POSTMORTEM_TEMPLATES = {fmt(postmortem_templates)}\n\n"
f"RETROSPECTIVE_PROCESSES = {fmt(retrospective_processes)}\n\n"
f"RETROSPECTIVE_CONFIGURATIONS = {fmt(retrospective_configurations)}\n\n"
f"DASHBOARDS = {fmt(dashboards)}\n"
)
with open(DATA_FILE, "w") as f:
f.write(content)
new_counts = {
"environments": len(environments),
"severities": len(severities),
"functionalities": len(functionalities),
"causes": len(causes),
"incident_types": len(incident_types),
"incident_roles": len(incident_roles),
"schedules": len(schedules),
"playbooks": len(playbooks),
"webhooks_endpoints": len(webhooks_endpoints),
"secrets": len(secrets),
"status_pages": len(status_pages),
"form_fields": len(form_fields),
"custom_forms": len(custom_forms),
"incident_permission_sets": len(incident_permission_sets),
"workflows": len(workflows),
"workflow_groups": len(workflow_groups),
"postmortem_templates": len(postmortem_templates),
"retrospective_processes": len(retrospective_processes),
"retrospective_configurations": len(retrospective_configurations),
"dashboards": len(dashboards),
}
total_new = sum(new_counts.values())
print(
f"\nWrote {len(services)} services, {len(roles)} roles, {len(teams)} teams, "
f"{len(alert_sources)} alert sources, {len(alert_routes)} alert routes, "
f"{len(escalation_policies)} escalation policies, and "
f"{total_new} additional resources ({', '.join(f'{v} {k}' for k, v in new_counts.items() if v)}) "
f"to {DATA_FILE}"
)
# --- Find helpers (used by ensure functions) ---
def find_existing_service(client: AuthenticatedClient, name: str) -> str | None:
"""Find a service by name and return its id, or None if not found."""
response = list_services.sync_detailed(client=client, filtername=name)
if response.status_code != 200 or response.parsed is None:
return None
for svc in response.parsed.data:
if svc.attributes.name == name:
return svc.id
return None
def find_existing_role(client: AuthenticatedClient, name: str) -> str | None:
"""Find a role by name and return its id, or None if not found."""
response = list_roles.sync_detailed(client=client, filtername=name)
if response.status_code != 200 or response.parsed is None:
return None
for r in response.parsed.data:
if r.attributes.name == name:
return r.id
return None
def find_existing_team(client: AuthenticatedClient, name: str) -> str | None:
"""Find a team by name and return its id, or None if not found."""
response = list_teams.sync_detailed(client=client, filtername=name)
if response.status_code != 200 or response.parsed is None:
return None
for t in response.parsed.data:
if t.attributes.name == name:
return t.id
return None
def find_existing_alert_source(client: AuthenticatedClient, name: str) -> str | None:
"""Find an alert source by name and return its id, or None if not found."""
response = list_alerts_sources.sync_detailed(client=client, filtername=name)
if response.status_code != 200 or response.parsed is None:
return None
for s in response.parsed.data:
if s.attributes.name == name:
return s.id
return None
def find_existing_alert_route(client: AuthenticatedClient, name: str) -> str | None:
"""Find an alert route by name and return its id, or None if not found."""
response = list_alert_routes.sync_detailed(client=client, filtername=name)
if response.status_code != 200 or response.parsed is None:
return None
for r in response.parsed.data:
if r.attributes.name == name:
return r.id
return None
def find_existing_escalation_policy(client: AuthenticatedClient, name: str) -> str | None:
"""Find an escalation policy by name and return its id, or None if not found."""
response = list_escalation_policies.sync_detailed(client=client, filtername=name)
if response.status_code != 200 or response.parsed is None:
return None
for p in response.parsed.data:
if p.attributes.name == name:
return p.id
return None
# --- Ensure (idempotent create/update) ---
def ensure_service(client: AuthenticatedClient, service_dict: dict) -> None:
"""Create a service if it doesn't exist, or update it if it does."""
name = service_dict["name"]
existing_id = find_existing_service(client, name)
if existing_id is not None:
payload = UpdateService.from_dict({
"data": {
"type": "services",
"attributes": service_dict,
}
})
response = update_service.sync_detailed(
existing_id, client=client, body=payload
)
if response.status_code == 200:
print(f"Updated service: {name} (id: {existing_id})")
else:
print(f"Failed to update service '{name}': {response.status_code}")
if response.parsed:
print(f" Error: {response.parsed}")
else:
payload = NewService.from_dict({
"data": {
"type": "services",
"attributes": service_dict,
}
})
response = create_service.sync_detailed(client=client, body=payload)
if response.status_code == 201:
result = response.parsed
print(f"Created service: {name} (id: {result.data.id})")
else:
print(f"Failed to create service '{name}': {response.status_code}")
if response.parsed:
print(f" Error: {response.parsed}")
def ensure_role(client: AuthenticatedClient, role_dict: dict) -> None:
"""Create a role if it doesn't exist, or update it if it does."""
name = role_dict["name"]
if not name or name == "None":
# Some built-in roles (e.g. no_access) have a null name in the API; skip them.
return
existing_id = find_existing_role(client, name)
if existing_id is not None:
payload = UpdateRole.from_dict({
"data": {
"type": "roles",
"attributes": role_dict,
}
})
response = update_role.sync_detailed(
existing_id, client=client, body=payload
)
if response.status_code == 200:
print(f"Updated role: {name} (id: {existing_id})")
elif response.status_code == 404:
# Built-in system roles (owner, admin, observer) return 404; they can't be modified.
print(f"Skipping role '{name}': not modifiable (system role).")
else:
print(f"Failed to update role '{name}': {response.status_code}")
if response.parsed:
print(f" Error: {response.parsed}")
else:
payload = NewRole.from_dict({
"data": {
"type": "roles",
"attributes": role_dict,
}
})
response = create_role.sync_detailed(client=client, body=payload)
if response.status_code == 201:
result = response.parsed
print(f"Created role: {name} (id: {result.data.id})")
else:
print(f"Failed to create role '{name}': {response.status_code}")
if response.parsed:
print(f" Error: {response.parsed}")
def ensure_team(client: AuthenticatedClient, team_dict: dict) -> None:
"""Create a team if it doesn't exist, or update it if it does."""
name = team_dict["name"]
existing_id = find_existing_team(client, name)
if existing_id is not None:
payload = UpdateTeam.from_dict({
"data": {
"type": "groups",
"attributes": team_dict,
}
})
response = update_team.sync_detailed(
existing_id, client=client, body=payload
)
if response.status_code == 200:
print(f"Updated team: {name} (id: {existing_id})")
else:
print(f"Failed to update team '{name}': {response.status_code}")
if response.parsed:
print(f" Error: {response.parsed}")
else:
payload = NewTeam.from_dict({
"data": {
"type": "groups",
"attributes": team_dict,
}
})
response = create_team.sync_detailed(client=client, body=payload)
if response.status_code == 201:
result = response.parsed
print(f"Created team: {name} (id: {result.data.id})")
else:
print(f"Failed to create team '{name}': {response.status_code}")
if response.parsed:
print(f" Error: {response.parsed}")
def ensure_alert_source(client: AuthenticatedClient, alert_source_dict: dict) -> None:
"""Create an alert source if it doesn't exist, or update it if it does."""
name = alert_source_dict["name"]
existing_id = find_existing_alert_source(client, name)
if existing_id is not None:
payload = UpdateAlertsSource.from_dict({
"data": {
"type": "alert_sources",
"attributes": alert_source_dict,
}
})
response = update_alerts_source.sync_detailed(
existing_id, client=client, body=payload
)
if response.status_code == 200:
print(f"Updated alert source: {name} (id: {existing_id})")
else:
print(f"Failed to update alert source '{name}': {response.status_code}")
if response.parsed:
print(f" Error: {response.parsed}")
else:
payload = NewAlertsSource.from_dict({
"data": {
"type": "alert_sources",
"attributes": alert_source_dict,
}
})
response = create_alerts_source.sync_detailed(client=client, body=payload)
if response.status_code == 201:
result = response.parsed
print(f"Created alert source: {name} (id: {result.data.id})")
else:
print(f"Failed to create alert source '{name}': {response.status_code}")
if response.parsed:
print(f" Error: {response.parsed}")
def ensure_alert_route(client: AuthenticatedClient, alert_route_dict: dict) -> None:
"""Create an alert route if it doesn't exist, or update it if it does."""
name = alert_route_dict["name"]
existing_id = find_existing_alert_route(client, name)
if existing_id is not None:
payload = UpdateAlertRoute.from_dict({
"data": {
"type": "alert_routes",
"attributes": alert_route_dict,
}
})
response = update_alert_route.sync_detailed(
existing_id, client=client, body=payload
)
if response.status_code == 200:
print(f"Updated alert route: {name} (id: {existing_id})")
else:
print(f"Failed to update alert route '{name}': {response.status_code}")
if response.parsed:
print(f" Error: {response.parsed}")
else:
payload = NewAlertRoute.from_dict({
"data": {
"type": "alert_routes",
"attributes": alert_route_dict,
}
})
response = create_alert_route.sync_detailed(client=client, body=payload)
if response.status_code == 201:
result = response.parsed
print(f"Created alert route: {name} (id: {result.data.id})")
else:
print(f"Failed to create alert route '{name}': {response.status_code}")
if response.parsed:
print(f" Error: {response.parsed}")
def ensure_escalation_policy(client: AuthenticatedClient, policy_dict: dict) -> None:
"""Create an escalation policy if it doesn't exist, or update it if it does."""
name = policy_dict["name"]
existing_id = find_existing_escalation_policy(client, name)
if existing_id is not None:
payload = UpdateEscalationPolicy.from_dict({
"data": {
"type": "escalation_policies",
"attributes": policy_dict,
}
})
response = update_escalation_policy.sync_detailed(
existing_id, client=client, body=payload
)
if response.status_code == 200:
print(f"Updated escalation policy: {name} (id: {existing_id})")
else:
print(f"Failed to update escalation policy '{name}': {response.status_code}")
if response.parsed:
print(f" Error: {response.parsed}")
else:
payload = NewEscalationPolicy.from_dict({
"data": {
"type": "escalation_policies",
"attributes": policy_dict,
}
})
response = create_escalation_policy.sync_detailed(client=client, body=payload)
if response.status_code == 201:
result = response.parsed
print(f"Created escalation policy: {name} (id: {result.data.id})")
else:
print(f"Failed to create escalation policy '{name}': {response.status_code}")
if response.parsed:
print(f" Error: {response.parsed}")
# --- Import ---
def load_data_file(path: str) -> tuple[list, list, list, list, list, list]:
"""Dynamically load all resource lists from a Python data file.
Returns the six resource lists that ``run_import`` manages. Additional
variables written by ``--export`` (ENVIRONMENTS, WORKFLOWS, etc.) are
present in the module but not returned here; they serve as a read-only
reference snapshot.
"""
abs_path = os.path.abspath(path)
spec = importlib.util.spec_from_file_location("_rootly_data", abs_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
teams = getattr(module, "TEAMS", [])
alert_sources = getattr(module, "ALERT_SOURCES", [])
alert_routes = getattr(module, "ALERT_ROUTES", [])
escalation_policies = getattr(module, "ESCALATION_POLICIES", [])
return module.SERVICES, module.ROLES, teams, alert_sources, alert_routes, escalation_policies
def run_import(client: AuthenticatedClient, path: str) -> None:
"""Load definitions from a file and ensure them in Rootly."""
services, roles, teams, alert_sources, alert_routes, escalation_policies = load_data_file(path)
print(
f"Loaded {len(services)} services, {len(roles)} roles, {len(teams)} teams, "
f"{len(alert_sources)} alert sources, {len(alert_routes)} alert routes, and "
f"{len(escalation_policies)} escalation policies from {path}"
)
print("\nEnsuring services...")
for service_dict in services:
ensure_service(client, service_dict)
print("\nEnsuring roles...")
for role_dict in roles:
ensure_role(client, role_dict)
print("\nEnsuring teams...")