-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathresource.go
More file actions
2768 lines (2486 loc) · 107 KB
/
resource.go
File metadata and controls
2768 lines (2486 loc) · 107 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
package observability
import (
"context"
"fmt"
"net/http"
"strconv"
"strings"
"github.com/google/go-cmp/cmp"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/utils"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/utils/planmodifiers/int64planmodifier"
observabilityUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/observability/utils"
"github.com/hashicorp/terraform-plugin-framework-validators/listvalidator"
"github.com/hashicorp/terraform-plugin-framework-validators/setvalidator"
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
"github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/booldefault"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/boolplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/mapplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/tfsdk"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-framework/types/basetypes"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/stackitcloud/stackit-sdk-go/core/oapierror"
"github.com/stackitcloud/stackit-sdk-go/services/observability"
"github.com/stackitcloud/stackit-sdk-go/services/observability/wait"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
)
// Currently, due to incorrect types in the API, the maximum recursion level for child routes is set to 1.
// Once this is fixed, the value should be set to 10 and toRoutePayload needs to be adjusted, to support it.
const childRouteMaxRecursionLevel = 1
// Ensure the implementation satisfies the expected interfaces.
var (
_ resource.Resource = &instanceResource{}
_ resource.ResourceWithConfigure = &instanceResource{}
_ resource.ResourceWithImportState = &instanceResource{}
)
type Model struct {
Id types.String `tfsdk:"id"` // needed by TF
ProjectId types.String `tfsdk:"project_id"`
InstanceId types.String `tfsdk:"instance_id"`
Name types.String `tfsdk:"name"`
PlanName types.String `tfsdk:"plan_name"`
PlanId types.String `tfsdk:"plan_id"`
Parameters types.Map `tfsdk:"parameters"`
DashboardURL types.String `tfsdk:"dashboard_url"`
IsUpdatable types.Bool `tfsdk:"is_updatable"`
GrafanaURL types.String `tfsdk:"grafana_url"`
GrafanaPublicReadAccess types.Bool `tfsdk:"grafana_public_read_access"`
// Deprecated: GrafanaInitialAdminPassword is deprecated and will be removed after 5th July 2026. Use GrafanaAdminEnabled instead.
GrafanaInitialAdminPassword types.String `tfsdk:"grafana_initial_admin_password"`
// Deprecated: GrafanaInitialAdminUser is deprecated and will be removed after 5th July 2026. Use GrafanaAdminEnabled instead.
GrafanaInitialAdminUser types.String `tfsdk:"grafana_initial_admin_user"`
GrafanaAdminEnabled types.Bool `tfsdk:"grafana_admin_enabled"`
MetricsRetentionDays types.Int64 `tfsdk:"metrics_retention_days"`
MetricsRetentionDays5mDownsampling types.Int64 `tfsdk:"metrics_retention_days_5m_downsampling"`
MetricsRetentionDays1hDownsampling types.Int64 `tfsdk:"metrics_retention_days_1h_downsampling"`
MetricsURL types.String `tfsdk:"metrics_url"`
MetricsPushURL types.String `tfsdk:"metrics_push_url"`
TargetsURL types.String `tfsdk:"targets_url"`
AlertingURL types.String `tfsdk:"alerting_url"`
LogsRetentionDays types.Int64 `tfsdk:"logs_retention_days"`
TracesRetentionDays types.Int64 `tfsdk:"traces_retention_days"`
LogsURL types.String `tfsdk:"logs_url"`
LogsPushURL types.String `tfsdk:"logs_push_url"`
JaegerTracesURL types.String `tfsdk:"jaeger_traces_url"`
JaegerUIURL types.String `tfsdk:"jaeger_ui_url"`
OtlpTracesURL types.String `tfsdk:"otlp_traces_url"`
ZipkinSpansURL types.String `tfsdk:"zipkin_spans_url"`
ACL types.Set `tfsdk:"acl"`
AlertConfig types.Object `tfsdk:"alert_config"`
}
// Struct corresponding to Model.AlertConfig
type alertConfigModel struct {
GlobalConfiguration types.Object `tfsdk:"global"`
Receivers types.List `tfsdk:"receivers"`
Route types.Object `tfsdk:"route"`
}
var alertConfigTypes = map[string]attr.Type{
"receivers": types.ListType{ElemType: types.ObjectType{AttrTypes: receiversTypes}},
"route": types.ObjectType{AttrTypes: mainRouteTypes},
"global": types.ObjectType{AttrTypes: globalConfigurationTypes},
}
// Struct corresponding to Model.AlertConfig.global
type globalConfigurationModel struct {
OpsgenieApiKey types.String `tfsdk:"opsgenie_api_key"`
OpsgenieApiUrl types.String `tfsdk:"opsgenie_api_url"`
ResolveTimeout types.String `tfsdk:"resolve_timeout"`
SmtpAuthIdentity types.String `tfsdk:"smtp_auth_identity"`
SmtpAuthPassword types.String `tfsdk:"smtp_auth_password"`
SmtpAuthUsername types.String `tfsdk:"smtp_auth_username"`
SmtpFrom types.String `tfsdk:"smtp_from"`
SmtpSmartHost types.String `tfsdk:"smtp_smart_host"`
}
var globalConfigurationTypes = map[string]attr.Type{
"opsgenie_api_key": types.StringType,
"opsgenie_api_url": types.StringType,
"resolve_timeout": types.StringType,
"smtp_auth_identity": types.StringType,
"smtp_auth_password": types.StringType,
"smtp_auth_username": types.StringType,
"smtp_from": types.StringType,
"smtp_smart_host": types.StringType,
}
// Struct corresponding to Model.AlertConfig.route
type mainRouteModel struct {
Continue types.Bool `tfsdk:"continue"`
GroupBy types.List `tfsdk:"group_by"`
GroupInterval types.String `tfsdk:"group_interval"`
GroupWait types.String `tfsdk:"group_wait"`
Receiver types.String `tfsdk:"receiver"`
RepeatInterval types.String `tfsdk:"repeat_interval"`
Routes types.List `tfsdk:"routes"`
}
// Struct corresponding to Model.AlertConfig.route
// This is used to map the routes between the mainRouteModel and the last level of recursion of the routes field
type routeModelMiddle struct {
Continue types.Bool `tfsdk:"continue"`
GroupBy types.List `tfsdk:"group_by"`
GroupInterval types.String `tfsdk:"group_interval"`
GroupWait types.String `tfsdk:"group_wait"`
// Deprecated: Match is deprecated and will be removed after 10th March 2026. Use Matchers instead
Match types.Map `tfsdk:"match"`
// Deprecated: MatchRegex is deprecated and will be removed after 10th March 2026. Use Matchers instead
MatchRegex types.Map `tfsdk:"match_regex"`
Matchers types.List `tfsdk:"matchers"`
Receiver types.String `tfsdk:"receiver"`
RepeatInterval types.String `tfsdk:"repeat_interval"`
Routes types.List `tfsdk:"routes"`
}
// Struct corresponding to Model.AlertConfig.route but without the recursive routes field
// This is used to map the last level of recursion of the routes field
type routeModelNoRoutes struct {
Continue types.Bool `tfsdk:"continue"`
GroupBy types.List `tfsdk:"group_by"`
GroupInterval types.String `tfsdk:"group_interval"`
GroupWait types.String `tfsdk:"group_wait"`
// Deprecated: Match is deprecated and will be removed after 10th March 2026. Use Matchers instead
Match types.Map `tfsdk:"match"`
// Deprecated: MatchRegex is deprecated and will be removed after 10th March 2026. Use Matchers instead
MatchRegex types.Map `tfsdk:"match_regex"`
Matchers types.List `tfsdk:"matchers"`
Receiver types.String `tfsdk:"receiver"`
RepeatInterval types.String `tfsdk:"repeat_interval"`
}
var mainRouteTypes = map[string]attr.Type{
"continue": types.BoolType,
"group_by": types.ListType{ElemType: types.StringType},
"group_interval": types.StringType,
"group_wait": types.StringType,
"receiver": types.StringType,
"repeat_interval": types.StringType,
"routes": types.ListType{ElemType: getRouteListType()},
}
// Struct corresponding to Model.AlertConfig.receivers
type receiversModel struct {
Name types.String `tfsdk:"name"`
EmailConfigs types.List `tfsdk:"email_configs"`
OpsGenieConfigs types.List `tfsdk:"opsgenie_configs"`
WebHooksConfigs types.List `tfsdk:"webhooks_configs"`
}
var receiversTypes = map[string]attr.Type{
"name": types.StringType,
"email_configs": types.ListType{ElemType: types.ObjectType{AttrTypes: emailConfigsTypes}},
"opsgenie_configs": types.ListType{ElemType: types.ObjectType{AttrTypes: opsgenieConfigsTypes}},
"webhooks_configs": types.ListType{ElemType: types.ObjectType{AttrTypes: webHooksConfigsTypes}},
}
// Struct corresponding to Model.AlertConfig.receivers.emailConfigs
type emailConfigsModel struct {
AuthIdentity types.String `tfsdk:"auth_identity"`
AuthPassword types.String `tfsdk:"auth_password"`
AuthUsername types.String `tfsdk:"auth_username"`
From types.String `tfsdk:"from"`
SendResolved types.Bool `tfsdk:"send_resolved"`
Smarthost types.String `tfsdk:"smart_host"`
To types.String `tfsdk:"to"`
}
var emailConfigsTypes = map[string]attr.Type{
"auth_identity": types.StringType,
"auth_password": types.StringType,
"auth_username": types.StringType,
"from": types.StringType,
"send_resolved": types.BoolType,
"smart_host": types.StringType,
"to": types.StringType,
}
// Struct corresponding to Model.AlertConfig.receivers.opsGenieConfigs
type opsgenieConfigsModel struct {
ApiKey types.String `tfsdk:"api_key"`
ApiUrl types.String `tfsdk:"api_url"`
Tags types.String `tfsdk:"tags"`
Priority types.String `tfsdk:"priority"`
SendResolved types.Bool `tfsdk:"send_resolved"`
}
var opsgenieConfigsTypes = map[string]attr.Type{
"api_key": types.StringType,
"api_url": types.StringType,
"tags": types.StringType,
"priority": types.StringType,
"send_resolved": types.BoolType,
}
// Struct corresponding to Model.AlertConfig.receivers.webHooksConfigs
type webHooksConfigsModel struct {
Url types.String `tfsdk:"url"`
MsTeams types.Bool `tfsdk:"ms_teams"`
GoogleChat types.Bool `tfsdk:"google_chat"`
SendResolved types.Bool `tfsdk:"send_resolved"`
}
var webHooksConfigsTypes = map[string]attr.Type{
"url": types.StringType,
"ms_teams": types.BoolType,
"google_chat": types.BoolType,
"send_resolved": types.BoolType,
}
var routeDescriptions = map[string]string{
"continue": "Whether an alert should continue matching subsequent sibling nodes.",
"group_by": "The labels by which incoming alerts are grouped together. For example, multiple alerts coming in for cluster=A and alertname=LatencyHigh would be batched into a single group. To aggregate by all possible labels use the special value '...' as the sole label name, for example: group_by: ['...']. This effectively disables aggregation entirely, passing through all alerts as-is. This is unlikely to be what you want, unless you have a very low alert volume or your upstream notification system performs its own grouping.",
"group_interval": "How long to wait before sending a notification about new alerts that are added to a group of alerts for which an initial notification has already been sent. (Usually ~5m or more.)",
"group_wait": "How long to initially wait to send a notification for a group of alerts. Allows to wait for an inhibiting alert to arrive or collect more initial alerts for the same group. (Usually ~0s to few minutes.)",
"match": "A set of equality matchers an alert has to fulfill to match the node. This field is deprecated and will be removed after 10th March 2026, use `matchers` in the `routes` instead",
"match_regex": "A set of regex-matchers an alert has to fulfill to match the node. This field is deprecated and will be removed after 10th March 2026, use `matchers` in the `routes` instead",
"matchers": "A list of matchers that an alert has to fulfill to match the node. A matcher is a string with a syntax inspired by PromQL and OpenMetrics.",
"receiver": "The name of the receiver to route the alerts to.",
"repeat_interval": "How long to wait before sending a notification again if it has already been sent successfully for an alert. (Usually ~3h or more).",
"routes": "List of child routes.",
}
// getRouteListType is a helper function to return the route list attribute type.
func getRouteListType() types.ObjectType {
return getRouteListTypeAux(1, childRouteMaxRecursionLevel)
}
// getRouteListTypeAux returns the type of the route list attribute with the given level of child routes recursion.
// The level is used to determine the current depth of the nested object.
// The limit is used to determine the maximum depth of the nested object.
// The level should be lower or equal to the limit, if higher, the function will produce a stack overflow.
func getRouteListTypeAux(level, limit int) types.ObjectType {
attributeTypes := map[string]attr.Type{
"continue": types.BoolType,
"group_by": types.ListType{ElemType: types.StringType},
"group_interval": types.StringType,
"group_wait": types.StringType,
"match": types.MapType{ElemType: types.StringType},
"match_regex": types.MapType{ElemType: types.StringType},
"matchers": types.ListType{ElemType: types.StringType},
"receiver": types.StringType,
"repeat_interval": types.StringType,
}
if level != limit {
attributeTypes["routes"] = types.ListType{ElemType: getRouteListTypeAux(level+1, limit)}
}
return types.ObjectType{AttrTypes: attributeTypes}
}
func getRouteNestedObject() schema.ListNestedAttribute {
return getRouteNestedObjectAux(false, 1, childRouteMaxRecursionLevel)
}
func getDatasourceRouteNestedObject() schema.ListNestedAttribute {
return getRouteNestedObjectAux(true, 1, childRouteMaxRecursionLevel)
}
// getRouteNestedObjectAux returns the nested object for the route attribute with the given level of child routes recursion.
// The isDatasource is used to determine if the route is used in a datasource schema or not. If it is a datasource, all fields are computed.
// The level is used to determine the current depth of the nested object.
// The limit is used to determine the maximum depth of the nested object.
// The level should be lower or equal to the limit, if higher, the function will produce a stack overflow.
func getRouteNestedObjectAux(isDatasource bool, level, limit int) schema.ListNestedAttribute {
attributesMap := map[string]schema.Attribute{
"continue": schema.BoolAttribute{
Description: routeDescriptions["continue"],
Optional: !isDatasource,
Computed: true,
},
"group_by": schema.ListAttribute{
Description: routeDescriptions["group_by"],
Optional: !isDatasource,
Computed: isDatasource,
ElementType: types.StringType,
},
"group_interval": schema.StringAttribute{
Description: routeDescriptions["group_interval"],
Optional: !isDatasource,
Computed: true,
},
"group_wait": schema.StringAttribute{
Description: routeDescriptions["group_wait"],
Optional: !isDatasource,
Computed: true,
},
"match": schema.MapAttribute{
Description: routeDescriptions["match"],
DeprecationMessage: "Use `matchers` in the `routes` instead.",
Optional: !isDatasource,
Computed: isDatasource,
ElementType: types.StringType,
},
"match_regex": schema.MapAttribute{
Description: routeDescriptions["match_regex"],
DeprecationMessage: "Use `matchers` in the `routes` instead.",
Optional: !isDatasource,
Computed: isDatasource,
ElementType: types.StringType,
},
"matchers": schema.ListAttribute{
Description: routeDescriptions["matchers"],
Optional: !isDatasource,
Computed: isDatasource,
ElementType: types.StringType,
},
"receiver": schema.StringAttribute{
Description: routeDescriptions["receiver"],
Required: !isDatasource,
Computed: isDatasource,
},
"repeat_interval": schema.StringAttribute{
Description: routeDescriptions["repeat_interval"],
Optional: !isDatasource,
Computed: true,
},
}
if level != limit {
attributesMap["routes"] = getRouteNestedObjectAux(isDatasource, level+1, limit)
}
return schema.ListNestedAttribute{
Description: routeDescriptions["routes"],
Optional: !isDatasource,
Computed: isDatasource,
Validators: []validator.List{
listvalidator.SizeAtLeast(1),
},
NestedObject: schema.NestedAttributeObject{
Attributes: attributesMap,
},
}
}
// NewInstanceResource is a helper function to simplify the provider implementation.
func NewInstanceResource() resource.Resource {
return &instanceResource{}
}
// instanceResource is the resource implementation.
type instanceResource struct {
client *observability.APIClient
}
// Metadata returns the resource type name.
func (r *instanceResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_observability_instance"
}
// Configure adds the provider configured client to the resource.
func (r *instanceResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
providerData, ok := conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
if !ok {
return
}
apiClient := observabilityUtils.ConfigureClient(ctx, &providerData, &resp.Diagnostics)
if resp.Diagnostics.HasError() {
return
}
r.client = apiClient
tflog.Info(ctx, "Observability instance client configured")
}
// Schema defines the schema for the resource.
func (r *instanceResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Observability instance resource schema. Must have a `region` specified in the provider configuration.",
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
Description: "Terraform's internal resource ID. It is structured as \"`project_id`,`instance_id`\".",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"project_id": schema.StringAttribute{
Description: "STACKIT project ID to which the instance is associated.",
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
Validators: []validator.String{
validate.UUID(),
validate.NoSeparator(),
},
},
"instance_id": schema.StringAttribute{
Description: "The Observability instance ID.",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
Validators: []validator.String{
validate.UUID(),
validate.NoSeparator(),
},
},
"name": schema.StringAttribute{
Description: "The name of the Observability instance.",
Required: true,
Validators: []validator.String{
stringvalidator.LengthAtLeast(1),
stringvalidator.LengthAtMost(200),
},
},
"plan_name": schema.StringAttribute{
Description: "Specifies the Observability plan. E.g. `Observability-Monitoring-Medium-EU01`.",
Required: true,
Validators: []validator.String{
stringvalidator.LengthAtLeast(1),
stringvalidator.LengthAtMost(200),
},
},
"plan_id": schema.StringAttribute{
Description: "The Observability plan ID.",
Computed: true,
Validators: []validator.String{
validate.UUID(),
},
},
"parameters": schema.MapAttribute{
Description: "Additional parameters.",
Optional: true,
Computed: true,
ElementType: types.StringType,
PlanModifiers: []planmodifier.Map{
mapplanmodifier.UseStateForUnknown(),
},
},
"dashboard_url": schema.StringAttribute{
Description: "Specifies Observability instance dashboard URL.",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"is_updatable": schema.BoolAttribute{
Description: "Specifies if the instance can be updated.",
Computed: true,
PlanModifiers: []planmodifier.Bool{
boolplanmodifier.UseStateForUnknown(),
},
},
"grafana_public_read_access": schema.BoolAttribute{
Description: "If true, anyone can access Grafana dashboards without logging in.",
Computed: true,
PlanModifiers: []planmodifier.Bool{
boolplanmodifier.UseStateForUnknown(),
},
},
"grafana_url": schema.StringAttribute{
Description: "Specifies Grafana URL.",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"grafana_initial_admin_user": schema.StringAttribute{
DeprecationMessage: "This attribute is deprecated and will be removed on July 5, 2026. Use `grafana_admin_enabled` instead.",
Description: "Specifies an initial Grafana admin username.",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"grafana_initial_admin_password": schema.StringAttribute{
DeprecationMessage: "This attribute is deprecated and will be removed on July 5, 2026. Use `grafana_admin_enabled` instead.",
Description: "Specifies an initial Grafana admin password.",
Computed: true,
Sensitive: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"grafana_admin_enabled": schema.BoolAttribute{
Description: "If true, a default Grafana server admin user is created. It's recommended to set this to false and use STACKIT SSO (Owner or Observability Grafana Server Admin role) instead. It is still possible to manually create a new Grafana admin user via the Grafana UI later.",
Optional: true,
Computed: true,
Default: booldefault.StaticBool(true),
},
"traces_retention_days": schema.Int64Attribute{
Description: "Specifies for how many days the traces are kept. Default is set to `7`.",
Optional: true,
Computed: true,
},
"logs_retention_days": schema.Int64Attribute{
Description: "Specifies for how many days the logs are kept. Default is set to `7`.",
Optional: true,
Computed: true,
},
"metrics_retention_days": schema.Int64Attribute{
Description: "Specifies for how many days the raw metrics are kept. Default is set to `90`.",
Optional: true,
Computed: true,
PlanModifiers: []planmodifier.Int64{
int64planmodifier.UseStateForUnknownIf(int64planmodifier.Int64Changed, "metrics_retention_days", "sets `UseStateForUnknown` only if `metrics_retention_days` has not changed"),
},
},
"metrics_retention_days_5m_downsampling": schema.Int64Attribute{
Description: "Specifies for how many days the 5m downsampled metrics are kept. must be less than the value of the general retention. Default is set to `90`.",
Optional: true,
Computed: true,
PlanModifiers: []planmodifier.Int64{
int64planmodifier.UseStateForUnknownIf(int64planmodifier.Int64Changed, "metrics_retention_days_5m_downsampling", "sets `UseStateForUnknown` only if `metrics_retention_days_5m_downsampling` has not changed"),
},
},
"metrics_retention_days_1h_downsampling": schema.Int64Attribute{
Description: "Specifies for how many days the 1h downsampled metrics are kept. must be less than the value of the 5m downsampling retention. Default is set to `90`.",
Optional: true,
Computed: true,
PlanModifiers: []planmodifier.Int64{
int64planmodifier.UseStateForUnknownIf(int64planmodifier.Int64Changed, "metrics_retention_days_1h_downsampling", "sets `UseStateForUnknown` only if `metrics_retention_days_1h_downsampling` has not changed"),
},
},
"metrics_url": schema.StringAttribute{
Description: "Specifies metrics URL.",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"metrics_push_url": schema.StringAttribute{
Description: "Specifies URL for pushing metrics.",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"targets_url": schema.StringAttribute{
Description: "Specifies Targets URL.",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"alerting_url": schema.StringAttribute{
Description: "Specifies Alerting URL.",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"logs_url": schema.StringAttribute{
Description: "Specifies Logs URL.",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"logs_push_url": schema.StringAttribute{
Description: "Specifies URL for pushing logs.",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"jaeger_traces_url": schema.StringAttribute{
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"jaeger_ui_url": schema.StringAttribute{
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"otlp_traces_url": schema.StringAttribute{
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"zipkin_spans_url": schema.StringAttribute{
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"acl": schema.SetAttribute{
Description: "The access control list for this instance. Each entry is an IP address range that is permitted to access, in CIDR notation.",
ElementType: types.StringType,
Optional: true,
Validators: []validator.Set{
setvalidator.ValueStringsAre(
validate.CIDR(),
),
},
},
"alert_config": schema.SingleNestedAttribute{
Description: "Alert configuration for the instance.",
Optional: true,
Attributes: map[string]schema.Attribute{
"receivers": schema.ListNestedAttribute{
Description: "List of alert receivers.",
Required: true,
Validators: []validator.List{
listvalidator.SizeAtLeast(1),
},
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"name": schema.StringAttribute{
Description: "Name of the receiver.",
Required: true,
},
"email_configs": schema.ListNestedAttribute{
Description: "List of email configurations.",
Optional: true,
Validators: []validator.List{
listvalidator.SizeAtLeast(1),
},
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"auth_identity": schema.StringAttribute{
Description: "SMTP authentication information. Must be a valid email address",
Optional: true,
},
"auth_password": schema.StringAttribute{
Description: "SMTP authentication password.",
Optional: true,
Sensitive: true,
},
"auth_username": schema.StringAttribute{
Description: "SMTP authentication username.",
Optional: true,
},
"from": schema.StringAttribute{
Description: "The sender email address. Must be a valid email address",
Optional: true,
},
"send_resolved": schema.BoolAttribute{
Description: "Whether to notify about resolved alerts.",
Optional: true,
Computed: true,
Default: booldefault.StaticBool(true),
},
"smart_host": schema.StringAttribute{
Description: "The SMTP host through which emails are sent.",
Optional: true,
},
"to": schema.StringAttribute{
Description: "The email address to send notifications to. Must be a valid email address",
Optional: true,
},
},
},
},
"opsgenie_configs": schema.ListNestedAttribute{
Description: "List of OpsGenie configurations.",
Optional: true,
Validators: []validator.List{
listvalidator.SizeAtLeast(1),
},
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"api_key": schema.StringAttribute{
Description: "The API key for OpsGenie.",
Optional: true,
},
"api_url": schema.StringAttribute{
Description: "The host to send OpsGenie API requests to. Must be a valid URL",
Optional: true,
},
"tags": schema.StringAttribute{
Description: "Comma separated list of tags attached to the notifications.",
Optional: true,
},
"priority": schema.StringAttribute{
Description: "Priority of the alert. " + utils.FormatPossibleValues("P1", "P2", "P3", "P4", "P5"),
Optional: true,
},
"send_resolved": schema.BoolAttribute{
Description: "Whether to notify about resolved alerts.",
Optional: true,
Computed: true,
Default: booldefault.StaticBool(true),
},
},
},
},
"webhooks_configs": schema.ListNestedAttribute{
Description: "List of Webhooks configurations.",
Optional: true,
Validators: []validator.List{
listvalidator.SizeAtLeast(1),
},
NestedObject: schema.NestedAttributeObject{
Validators: []validator.Object{
WebhookConfigMutuallyExclusive(),
},
Attributes: map[string]schema.Attribute{
"url": schema.StringAttribute{
Description: "The endpoint to send HTTP POST requests to. Must be a valid URL",
Optional: true,
Sensitive: true,
},
"ms_teams": schema.BoolAttribute{
Description: "Microsoft Teams webhooks require special handling, set this to true if the webhook is for Microsoft Teams.",
Optional: true,
Computed: true,
Default: booldefault.StaticBool(false),
},
"google_chat": schema.BoolAttribute{
Description: "Google Chat webhooks require special handling, set this to true if the webhook is for Google Chat.",
Optional: true,
Computed: true,
Default: booldefault.StaticBool(false),
},
"send_resolved": schema.BoolAttribute{
Description: "Whether to notify about resolved alerts.",
Optional: true,
Computed: true,
Default: booldefault.StaticBool(true),
},
},
},
},
},
},
},
"route": schema.SingleNestedAttribute{
Description: "Route configuration for the alerts.",
Required: true,
Attributes: map[string]schema.Attribute{
"continue": schema.BoolAttribute{
Description: routeDescriptions["continue"],
Computed: true,
Default: booldefault.StaticBool(false),
},
"group_by": schema.ListAttribute{
Description: routeDescriptions["group_by"],
Optional: true,
ElementType: types.StringType,
},
"group_interval": schema.StringAttribute{
Description: routeDescriptions["group_interval"],
Optional: true,
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"group_wait": schema.StringAttribute{
Description: routeDescriptions["group_wait"],
Optional: true,
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"receiver": schema.StringAttribute{
Description: routeDescriptions["receiver"],
Required: true,
},
"repeat_interval": schema.StringAttribute{
Description: routeDescriptions["repeat_interval"],
Optional: true,
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"routes": getRouteNestedObject(),
},
},
"global": schema.SingleNestedAttribute{
Description: "Global configuration for the alerts. If nothing passed the default argus config will be used. It is only possible to update the entire global part, not individual attributes.",
Optional: true,
Computed: true,
Attributes: map[string]schema.Attribute{
"opsgenie_api_key": schema.StringAttribute{
Description: "The API key for OpsGenie.",
Optional: true,
Sensitive: true,
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"opsgenie_api_url": schema.StringAttribute{
Description: "The host to send OpsGenie API requests to. Must be a valid URL",
Optional: true,
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"resolve_timeout": schema.StringAttribute{
Description: "The default value used by alertmanager if the alert does not include EndsAt. After this time passes, it can declare the alert as resolved if it has not been updated. This has no impact on alerts from Prometheus, as they always include EndsAt.",
Optional: true,
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"smtp_auth_identity": schema.StringAttribute{
Description: "SMTP authentication information. Must be a valid email address",
Optional: true,
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"smtp_auth_password": schema.StringAttribute{
Description: "SMTP Auth using LOGIN and PLAIN.",
Optional: true,
Sensitive: true,
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"smtp_auth_username": schema.StringAttribute{
Description: "SMTP Auth using CRAM-MD5, LOGIN and PLAIN. If empty, Alertmanager doesn't authenticate to the SMTP server.",
Optional: true,
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"smtp_from": schema.StringAttribute{
Description: "The default SMTP From header field. Must be a valid email address",
Optional: true,
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"smtp_smart_host": schema.StringAttribute{
Description: "The default SMTP smarthost used for sending emails, including port number in format `host:port` (eg. `smtp.example.com:587`). Port number usually is 25, or 587 for SMTP over TLS (sometimes referred to as STARTTLS).",
Optional: true,
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
},
},
},
},
},
}
}
// ModifyPlan will be called in the Plan phase.
// It will check if the plan contains a change that requires replacement. If yes, it will show an error to the user.
// Since there are observabiltiy plans which do not support specific configurations the request needs to be aborted with an error.
func (r *instanceResource) ModifyPlan(ctx context.Context, req resource.ModifyPlanRequest, resp *resource.ModifyPlanResponse) { // nolint:gocritic // function signature required by Terraform
// If the plan is empty we are deleting the resource
if req.Plan.Raw.IsNull() {
return
}
var configModel Model
// skip initial empty configuration to avoid follow-up errors
if req.Config.Raw.IsNull() {
return
}
resp.Diagnostics.Append(req.Config.Get(ctx, &configModel)...)
if resp.Diagnostics.HasError() {
return
}
plan, err := loadPlanId(ctx, *r.client, &configModel)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error validating plan", fmt.Sprintf("Loading service plan: %v", err))
return
}
if plan.GetGrafanaGlobalDashboards() == 0 {
// If grafana_admin_enabled was set, return an error to the user
if !(utils.IsUndefined(configModel.GrafanaAdminEnabled)) {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error validating plan", fmt.Sprintf("Plan (%s) has no Grafana included. Remove `grafana_admin_enabled` from your config or use a different plan.", *plan.Name))
}
}
// Plan does not support alert config
if plan.GetAlertMatchers() == 0 && plan.GetAlertReceivers() == 0 {
// If an alert config was set, return an error to the user
if !(utils.IsUndefined(configModel.AlertConfig)) {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error validating plan", fmt.Sprintf("Plan (%s) does not support configuring an alert config. Remove this from your config or use a different plan.", *plan.Name))
}
}
// Plan does not support metrics retention
if plan.GetTotalMetricSamples() == 0 {
metricsRetentionDays := conversion.Int64ValueToPointer(configModel.MetricsRetentionDays)
metricsRetentionDays5mDownsampling := conversion.Int64ValueToPointer(configModel.MetricsRetentionDays5mDownsampling)
metricsRetentionDays1hDownsampling := conversion.Int64ValueToPointer(configModel.MetricsRetentionDays1hDownsampling)
if metricsRetentionDays != nil || metricsRetentionDays5mDownsampling != nil || metricsRetentionDays1hDownsampling != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error validating plan", fmt.Sprintf("Plan (%s) does not support configuring metrics retention days. Remove this from your config or use a different plan.", *plan.Name))
}
}
// Plan does not support log storage and trace storage
if plan.GetLogsStorage() == 0 && plan.GetTracesStorage() == 0 {
logsRetentionDays := conversion.Int64ValueToPointer(configModel.LogsRetentionDays)
tracesRetentionDays := conversion.Int64ValueToPointer(configModel.TracesRetentionDays)
// If logs retention days are set, return an error to the user
if logsRetentionDays != nil {
resp.Diagnostics.AddAttributeError(path.Root("logs_retention_days"), "Error validating plan", fmt.Sprintf("Plan (%s) does not support configuring logs retention days. Remove this from your config or use a different plan.", *plan.Name))
}
// If traces retention days are set, return an error to the user
if tracesRetentionDays != nil {
resp.Diagnostics.AddAttributeError(path.Root("traces_retention_days"), "Error validating plan", fmt.Sprintf("Plan (%s) does not support configuring trace retention days. Remove this from your config or use a different plan.", *plan.Name))
}
}
}
// Create creates the resource and sets the initial Terraform state.
func (r *instanceResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
// Retrieve values from plan
var model Model
diags := req.Plan.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
ctx = core.InitProviderContext(ctx)
acl := []string{}
if !(model.ACL.IsNull() || model.ACL.IsUnknown()) {
diags = model.ACL.ElementsAs(ctx, &acl, false)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
}
alertConfig := alertConfigModel{}
if !(model.AlertConfig.IsNull() || model.AlertConfig.IsUnknown()) {
diags = model.AlertConfig.As(ctx, &alertConfig, basetypes.ObjectAsOptions{})
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
}
projectId := model.ProjectId.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId)
plan, err := loadPlanId(ctx, *r.client, &model)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Loading service plan: %v", err))
return
}
// Generate API request body from model
createPayload, err := toCreatePayload(&model, plan.GetGrafanaGlobalDashboards() != 0)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Creating API payload: %v", err))
return
}
createResp, err := r.client.CreateInstance(ctx, projectId).CreateInstancePayload(*createPayload).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Calling API: %v", err))
return
}