-
Notifications
You must be signed in to change notification settings - Fork 251
/
Copy pathresource_cloud_access_policy.go
305 lines (265 loc) · 9.55 KB
/
resource_cloud_access_policy.go
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
package cloud
import (
"context"
"fmt"
"strings"
"time"
"github.com/grafana/grafana-com-public-clients/go/gcom"
"github.com/grafana/terraform-provider-grafana/v3/internal/common"
"github.com/hashicorp/go-cty/cty"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
)
var (
resourceAccessPolicyID = common.NewResourceID(
common.StringIDField("region"),
common.StringIDField("policyId"),
)
)
func resourceAccessPolicy() *common.Resource {
cloudAccessPolicyRealmSchema := &schema.Resource{
Schema: map[string]*schema.Schema{
"type": {
Type: schema.TypeString,
Required: true,
Description: "Whether a policy applies to a Cloud org or a specific stack. Should be one of `org` or `stack`.",
ValidateFunc: validation.StringInSlice([]string{"org", "stack"}, false),
},
"identifier": {
Type: schema.TypeString,
Required: true,
Description: "The identifier of the org or stack. For orgs, this is the slug, for stacks, this is the stack ID.",
},
"label_policy": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"selector": {
Type: schema.TypeString,
Required: true,
Description: "The label selector to match in metrics or logs query. Should be in PromQL or LogQL format.",
},
},
},
},
},
}
schema := &schema.Resource{
Description: `
* [Official documentation](https://grafana.com/docs/grafana-cloud/account-management/authentication-and-permissions/access-policies/)
* [API documentation](https://grafana.com/docs/grafana-cloud/developer-resources/api-reference/cloud-api/#create-an-access-policy)
Required access policy scopes:
* accesspolicies:read
* accesspolicies:write
* accesspolicies:delete
`,
CreateContext: withClient[schema.CreateContextFunc](createCloudAccessPolicy),
UpdateContext: withClient[schema.UpdateContextFunc](updateCloudAccessPolicy),
DeleteContext: withClient[schema.DeleteContextFunc](deleteCloudAccessPolicy),
ReadContext: withClient[schema.ReadContextFunc](readCloudAccessPolicy),
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
},
Schema: map[string]*schema.Schema{
"region": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "Region where the API is deployed. Generally where the stack is deployed. Use the region list API to get the list of available regions: https://grafana.com/docs/grafana-cloud/developer-resources/api-reference/cloud-api/#list-regions.",
},
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "Name of the access policy.",
},
"display_name": {
Type: schema.TypeString,
Optional: true,
Description: "Display name of the access policy. Defaults to the name.",
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if new == "" && old == d.Get("name").(string) {
return true
}
return false
},
},
"scopes": {
Type: schema.TypeSet,
Required: true,
Description: "Scopes of the access policy. See https://grafana.com/docs/grafana-cloud/account-management/authentication-and-permissions/access-policies/#scopes for possible values.",
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateDiagFunc: validateCloudAccessPolicyScope,
},
},
"realm": {
Type: schema.TypeSet,
Required: true,
Elem: cloudAccessPolicyRealmSchema,
},
// Computed
"policy_id": {
Type: schema.TypeString,
Computed: true,
Description: "ID of the access policy.",
},
"created_at": {
Type: schema.TypeString,
Computed: true,
Description: "Creation date of the access policy.",
},
"updated_at": {
Type: schema.TypeString,
Computed: true,
Description: "Last update date of the access policy.",
},
},
}
return common.NewLegacySDKResource(
"grafana_cloud_access_policy",
resourceAccessPolicyID,
schema,
).WithLister(cloudListerFunction(listAccessPolicies))
}
func listAccessPolicies(ctx context.Context, client *gcom.APIClient, data *ListerData) ([]string, error) {
regionsReq := client.StackRegionsAPI.GetStackRegions(ctx)
regionsResp, _, err := regionsReq.Execute()
if err != nil {
return nil, fmt.Errorf("failed to list regions: %w", err)
}
orgID, err := data.OrgID(ctx, client)
if err != nil {
return nil, err
}
var policies []string
for _, region := range regionsResp.Items {
regionSlug := region.FormattedApiStackRegionAnyOf.Slug
req := client.AccesspoliciesAPI.GetAccessPolicies(ctx).Region(regionSlug).OrgId(orgID)
resp, _, err := req.Execute()
if err != nil {
return nil, fmt.Errorf("failed to list access policies in region %s: %w", regionSlug, err)
}
for _, policy := range resp.Items {
policies = append(policies, resourceAccessPolicyID.Make(regionSlug, policy.Id))
}
}
return policies, nil
}
func createCloudAccessPolicy(ctx context.Context, d *schema.ResourceData, client *gcom.APIClient) diag.Diagnostics {
region := d.Get("region").(string)
displayName := d.Get("display_name").(string)
if displayName == "" {
displayName = d.Get("name").(string)
}
req := client.AccesspoliciesAPI.PostAccessPolicies(ctx).Region(region).XRequestId(ClientRequestID()).
PostAccessPoliciesRequest(gcom.PostAccessPoliciesRequest{
Name: d.Get("name").(string),
DisplayName: &displayName,
Scopes: common.ListToStringSlice(d.Get("scopes").(*schema.Set).List()),
Realms: expandCloudAccessPolicyRealm(d.Get("realm").(*schema.Set).List()),
})
result, _, err := req.Execute()
if err != nil {
return apiError(err)
}
d.SetId(resourceAccessPolicyID.Make(region, result.Id))
return readCloudAccessPolicy(ctx, d, client)
}
func updateCloudAccessPolicy(ctx context.Context, d *schema.ResourceData, client *gcom.APIClient) diag.Diagnostics {
split, err := resourceAccessPolicyID.Split(d.Id())
if err != nil {
return diag.FromErr(err)
}
region, id := split[0], split[1]
displayName := d.Get("display_name").(string)
if displayName == "" {
displayName = d.Get("name").(string)
}
req := client.AccesspoliciesAPI.PostAccessPolicy(ctx, id.(string)).Region(region.(string)).XRequestId(ClientRequestID()).
PostAccessPolicyRequest(gcom.PostAccessPolicyRequest{
DisplayName: &displayName,
Scopes: common.ListToStringSlice(d.Get("scopes").(*schema.Set).List()),
Realms: expandCloudAccessPolicyRealm(d.Get("realm").(*schema.Set).List()),
})
if _, _, err = req.Execute(); err != nil {
return apiError(err)
}
return readCloudAccessPolicy(ctx, d, client)
}
func readCloudAccessPolicy(ctx context.Context, d *schema.ResourceData, client *gcom.APIClient) diag.Diagnostics {
split, err := resourceAccessPolicyID.Split(d.Id())
if err != nil {
return diag.FromErr(err)
}
region, id := split[0], split[1]
result, _, err := client.AccesspoliciesAPI.GetAccessPolicy(ctx, id.(string)).Region(region.(string)).Execute()
if err, shouldReturn := common.CheckReadError("access policy", d, err); shouldReturn {
return err
}
d.Set("region", region)
d.Set("policy_id", result.Id)
d.Set("name", result.Name)
d.Set("display_name", result.DisplayName)
d.Set("scopes", result.Scopes)
d.Set("realm", flattenCloudAccessPolicyRealm(result.Realms))
d.Set("created_at", result.CreatedAt.Format(time.RFC3339))
if updated := result.UpdatedAt; updated != nil {
d.Set("updated_at", updated.Format(time.RFC3339))
}
d.SetId(resourceAccessPolicyID.Make(region, result.Id))
return nil
}
func deleteCloudAccessPolicy(ctx context.Context, d *schema.ResourceData, client *gcom.APIClient) diag.Diagnostics {
split, err := resourceAccessPolicyID.Split(d.Id())
if err != nil {
return diag.FromErr(err)
}
region, id := split[0], split[1]
_, _, err = client.AccesspoliciesAPI.DeleteAccessPolicy(ctx, id.(string)).Region(region.(string)).XRequestId(ClientRequestID()).Execute()
return apiError(err)
}
func validateCloudAccessPolicyScope(v interface{}, path cty.Path) diag.Diagnostics {
if strings.Count(v.(string), ":") != 1 {
return diag.Errorf("invalid scope: %s. Should be in the `service:permission` format", v.(string))
}
return nil
}
func flattenCloudAccessPolicyRealm(realm []gcom.AuthAccessPolicyRealmsInner) []interface{} {
var result []interface{}
for _, r := range realm {
labelPolicy := []interface{}{}
for _, lp := range r.LabelPolicies {
labelPolicy = append(labelPolicy, map[string]interface{}{
"selector": lp.Selector,
})
}
result = append(result, map[string]interface{}{
"type": r.Type,
"identifier": r.Identifier,
"label_policy": labelPolicy,
})
}
return result
}
func expandCloudAccessPolicyRealm(realm []interface{}) []gcom.PostAccessPoliciesRequestRealmsInner {
var result []gcom.PostAccessPoliciesRequestRealmsInner
for _, r := range realm {
r := r.(map[string]interface{})
labelPolicy := []gcom.PostAccessPoliciesRequestRealmsInnerLabelPoliciesInner{}
for _, lp := range r["label_policy"].(*schema.Set).List() {
lp := lp.(map[string]interface{})
labelPolicy = append(labelPolicy, gcom.PostAccessPoliciesRequestRealmsInnerLabelPoliciesInner{
Selector: lp["selector"].(string),
})
}
result = append(result, gcom.PostAccessPoliciesRequestRealmsInner{
Type: r["type"].(string),
Identifier: r["identifier"].(string),
LabelPolicies: labelPolicy,
})
}
return result
}