-
Notifications
You must be signed in to change notification settings - Fork 10
/
resource_appgate_client_profile.go
243 lines (218 loc) · 7.69 KB
/
resource_appgate_client_profile.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
package appgate
import (
"context"
"fmt"
"log"
"math/rand"
"net/http"
"strings"
"time"
"github.com/appgate/sdp-api-client-go/api/v15/openapi"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func resourceAppgateClientProfile() *schema.Resource {
return &schema.Resource{
Create: resourceAppgateClientProfileCreate,
Read: resourceAppgateClientProfileRead,
Update: resourceAppgateClientProfileUpdate,
Delete: resourceAppgateClientProfileDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
SchemaVersion: 1,
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(1 * time.Minute),
Delete: schema.DefaultTimeout(1 * time.Minute),
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"spa_key_name": {
Type: schema.TypeString,
Required: true,
},
"identity_provider_name": {
Type: schema.TypeString,
Required: true,
},
"url": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func getIdFromProfile(profile openapi.ClientConnectionsProfiles) string {
// names are case sensitive and the controller only allows 1 per case type.
// so it will be suitable as the identitfer.
return profile.GetName()
}
func resourceAppgateClientProfileCreate(d *schema.ResourceData, meta interface{}) error {
log.Printf("[DEBUG] Create Client Profile %s", d.Get("name"))
ctx := context.Background()
api := meta.(*Client).API.ClientConnectionsApi
err := resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
rand.Seed(time.Now().UnixNano())
duration := rand.Intn(10) // n will be between 0 and 20
log.Printf("[DEBUG] Create Client Profile %s Sleep %d", d.Get("name"), duration)
time.Sleep(time.Duration(duration) * time.Second)
if err := applianceStatsRetryable(ctx, meta); err != nil {
return err
}
token, err := meta.(*Client).GetToken()
if err != nil {
return resource.RetryableError(err)
}
clientConnections, _, err := api.ClientConnectionsGet(ctx).Authorization(token).Execute()
if err != nil {
return resource.RetryableError(err)
}
existingProfiles := clientConnections.GetProfiles()
log.Printf("[DEBUG] Create %s -- existing profiles count %d", d.Get("name"), len(existingProfiles))
profile := openapi.ClientConnectionsProfiles{}
if v, ok := d.GetOk("name"); ok {
profile.SetName(v.(string))
}
if v, ok := d.GetOk("spa_key_name"); ok {
profile.SetSpaKeyName(v.(string))
}
if v, ok := d.GetOk("identity_provider_name"); ok {
profile.SetIdentityProviderName(v.(string))
}
d.SetId(getIdFromProfile(profile))
existingProfiles = append(existingProfiles, profile)
clientConnections.SetProfiles(existingProfiles)
_, response, err := api.ClientConnectionsPut(ctx).ClientConnections(clientConnections).Authorization(token).Execute()
if err != nil {
if response.StatusCode == http.StatusConflict {
return resource.RetryableError(fmt.Errorf("Expected client profile %q to be created but was in state %s", d.Get("name").(string), response.Status))
}
return resource.NonRetryableError(fmt.Errorf("Error updating client connection profiles: %s", err))
}
return nil
})
if err != nil {
return fmt.Errorf("Error create: %s", err)
}
return resourceAppgateClientProfileRead(d, meta)
}
func resourceAppgateClientProfileRead(d *schema.ResourceData, meta interface{}) error {
log.Printf("[DEBUG] Reading Client Profile id: %+v", d.Id())
token, err := meta.(*Client).GetToken()
if err != nil {
return err
}
api := meta.(*Client).API.ClientConnectionsApi
ctx := context.Background()
clientConnections, _, err := api.ClientConnectionsGet(ctx).Authorization(token).Execute()
if err != nil {
return fmt.Errorf("Could not read Client Connections %+v", prettyPrintAPIError(err))
}
existingProfiles := clientConnections.GetProfiles()
var p *openapi.ClientConnectionsProfiles
for _, profile := range existingProfiles {
if strings.EqualFold(profile.GetName(), d.Id()) && profile.GetName() == d.Id() {
p = &profile
d.Set("name", p.GetName())
d.Set("spa_key_name", p.GetSpaKeyName())
d.Set("identity_provider_name", p.GetIdentityProviderName())
d.Set("url", p.GetUrl())
break
}
}
if p == nil {
return fmt.Errorf("could not find client profile %s during read", d.Id())
}
return nil
}
func resourceAppgateClientProfileUpdate(d *schema.ResourceData, meta interface{}) error {
log.Printf("[DEBUG] Updating Client Profile %+v", d.Id())
ctx := context.Background()
token, err := meta.(*Client).GetToken()
if err != nil {
return err
}
api := meta.(*Client).API.ClientConnectionsApi
clientConnections, _, err := api.ClientConnectionsGet(ctx).Authorization(token).Execute()
if err != nil {
return fmt.Errorf("Could not read Client Connections %+v", prettyPrintAPIError(err))
}
existingProfiles := clientConnections.GetProfiles()
var p *openapi.ClientConnectionsProfiles
for _, profile := range existingProfiles {
if strings.EqualFold(profile.GetName(), d.Id()) && profile.GetName() == d.Id() {
p = &profile
break
}
}
if p == nil {
diag.FromErr(fmt.Errorf("could not find client profile %s during update", d.Id()))
}
if d.HasChange("name") {
p.SetName(d.Get("name").(string))
}
if d.HasChange("spa_key_name") {
p.SetSpaKeyName(d.Get("spa_key_name").(string))
}
if d.HasChange("identity_provider_name") {
p.SetIdentityProviderName(d.Get("identity_provider_name").(string))
}
req := api.ClientConnectionsPut(ctx)
_, _, err = req.ClientConnections(clientConnections).Authorization(token).Execute()
if err != nil {
return fmt.Errorf("Could not update Client profile %s %+v", d.Id(), prettyPrintAPIError(err))
}
return resourceAppgateClientProfileRead(d, meta)
}
func resourceAppgateClientProfileDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[DEBUG] Delete client profile %+v", d.Id())
ctx := context.Background()
api := meta.(*Client).API.ClientConnectionsApi
err := resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
rand.Seed(time.Now().UnixNano())
duration := rand.Intn(10) // n will be between 0 and 20
log.Printf("[DEBUG] Create Client Profile %s Sleep %d", d.Get("name"), duration)
time.Sleep(time.Duration(duration) * time.Second)
if err := applianceStatsRetryable(ctx, meta); err != nil {
return err
}
token, err := meta.(*Client).GetToken()
if err != nil {
return resource.RetryableError(err)
}
clientConnections, _, err := api.ClientConnectionsGet(ctx).Authorization(token).Execute()
if err != nil {
return resource.RetryableError(fmt.Errorf("Could not read Client Connections during delete %+v", prettyPrintAPIError(err)))
}
existingProfiles := clientConnections.GetProfiles()
var p *openapi.ClientConnectionsProfiles
var newProfiles []openapi.ClientConnectionsProfiles
for i, profile := range existingProfiles {
if strings.EqualFold(profile.GetName(), d.Id()) && profile.GetName() == d.Id() {
p = &profile
// remove the profile from the list and maintain order.
newProfiles = append(existingProfiles[:i], existingProfiles[i+1:]...)
break
}
}
if p == nil {
diag.FromErr(fmt.Errorf("could not find client profile %s during delete", d.Id()))
}
clientConnections.SetProfiles(newProfiles)
_, _, err = api.ClientConnectionsPut(ctx).ClientConnections(clientConnections).Authorization(token).Execute()
if err != nil {
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return fmt.Errorf("Could not delete Client Connections after retry %+v", err)
}
d.SetId("")
return nil
}