-
Notifications
You must be signed in to change notification settings - Fork 42
/
resource_jenkins_credential_azure_service_principal.go
291 lines (257 loc) · 10.5 KB
/
resource_jenkins_credential_azure_service_principal.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
package jenkins
import (
"context"
"encoding/xml"
"fmt"
"strings"
"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"
)
// VaultAppRoleCredentials struct representing credential for storing Vault AppRole role id and secret id
type AzureServicePrincipalCredentials struct {
XMLName xml.Name `xml:"com.microsoft.azure.util.AzureCredentials"`
Id string `xml:"id"`
Scope string `xml:"scope"`
Description string `xml:"description"`
Data AzureServicePrincipalCredentialsData `xml:"data"`
}
type AzureServicePrincipalCredentialsData struct {
SubscriptionId string `xml:"subscriptionId"`
ClientId string `xml:"clientId"`
ClientSecret string `xml:"clientSecret"`
CertificateId string `xml:"certificateId"`
Tenant string `xml:"tenant"`
AzureEnvironmentName string `xml:"azureEnvironmentName"`
ServiceManagementURL string `xml:"serviceManagementURL"`
AuthenticationEndpoint string `xml:"authenticationEndpoint"`
ResourceManagerEndpoint string `xml:"resourceManagerEndpoint"`
GraphEndpoint string `xml:"graphEndpoint"`
}
func resourceJenkinsCredentialAzureServicePrincipal() *schema.Resource {
return &schema.Resource{
CreateContext: resourceJenkinsCredentialAzureServicePrincipalCreate,
ReadContext: resourceJenkinsCredentialAzureServicePrincipalRead,
UpdateContext: resourceJenkinsCredentialAzureServicePrincipalUpdate,
DeleteContext: resourceJenkinsCredentialAzureServicePrincipalDelete,
Importer: &schema.ResourceImporter{
StateContext: resourceJenkinsCredentialAzureServicePrincipalImport,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Description: "The credential id of the Azure serivce principal credential created in Jenkins.",
Required: true,
ForceNew: true,
},
"domain": {
Type: schema.TypeString,
Description: "The Jenkins domain that the credentials will be added to.",
Optional: true,
Default: "_",
// In-place updates should be possible, but gojenkins does not support move operations
ForceNew: true,
},
"folder": {
Type: schema.TypeString,
Description: "The Jenkins folder that the credentials will be added to.",
Optional: true,
ForceNew: true,
},
"scope": {
Type: schema.TypeString,
Description: "The Jenkins scope assigned to the credentials.",
Optional: true,
Default: "GLOBAL",
ValidateDiagFunc: validateCredentialScope,
},
"description": {
Type: schema.TypeString,
Description: "An optional description to help tell similar credentials apart.",
Optional: true,
},
"subscription_id": {
Type: schema.TypeString,
Description: "The Azure subscription id.",
Required: true,
},
"client_id": {
Type: schema.TypeString,
Description: "The client id (application id) of the Azure Service Principal.",
Required: true,
},
"client_secret": {
Type: schema.TypeString,
Description: "The client secret of the Azure Service Principal. Cannot be used with certificate_id.",
Sensitive: true,
Optional: true,
ExactlyOneOf: []string{"client_secret", "certificate_id"},
},
"certificate_id": {
Type: schema.TypeString,
Description: "The certificate reference of the Azure Service Principal, pointing to a Jenkins certificate credential. Cannot be used with client_secret.",
Sensitive: true,
Optional: true,
ExactlyOneOf: []string{"client_secret", "certificate_id"},
},
"tenant": {
Type: schema.TypeString,
Description: "The Azure Tenant ID of the Azure Service Principal.",
Required: true,
},
"azure_environment_name": {
Type: schema.TypeString,
Description: `The Azure Cloud enviroment name. Allowed values are "Azure", "Azure China", "Azure Germany", "Azure US Government".`,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Azure", "Azure China", "Azure Germany", "Azure US Government"}, false),
Default: "Azure",
},
"service_management_url": {
Type: schema.TypeString,
Description: "Override the Azure management endpoint URL for the selected Azure environment.",
Optional: true,
Default: "",
},
"authentication_endpoint": {
Type: schema.TypeString,
Description: "Override the Azure Active Directory endpoint for the selected Azure environment.",
Optional: true,
Default: "",
},
"resource_manager_endpoint": {
Type: schema.TypeString,
Description: "Override the Azure resource manager endpoint URL for the selected Azure environment.",
Optional: true,
Default: "",
},
"graph_endpoint": {
Type: schema.TypeString,
Description: "Override the Azure graph endpoint URL for the selected Azure environment.",
Optional: true,
Default: "",
},
},
}
}
func resourceJenkinsCredentialAzureServicePrincipalCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client := meta.(jenkinsClient)
cm := client.Credentials()
cm.Folder = formatFolderName(d.Get("folder").(string))
// return diag.FromErr(fmt.Errorf("invalid folder name '%s', '%s'", cm.Folder, d.Get("folder").(string)))
// Validate that the folder exists
if err := folderExists(ctx, client, cm.Folder); err != nil {
return diag.FromErr(fmt.Errorf("invalid folder name '%s' specified: %w", cm.Folder, err))
}
credData := AzureServicePrincipalCredentialsData{
SubscriptionId: d.Get("subscription_id").(string),
ClientId: d.Get("client_id").(string),
ClientSecret: d.Get("client_secret").(string),
CertificateId: d.Get("certificate_id").(string),
Tenant: d.Get("tenant").(string),
AzureEnvironmentName: d.Get("azure_environment_name").(string),
ServiceManagementURL: d.Get("service_management_url").(string),
AuthenticationEndpoint: d.Get("authentication_endpoint").(string),
ResourceManagerEndpoint: d.Get("resource_manager_endpoint").(string),
GraphEndpoint: d.Get("graph_endpoint").(string),
}
cred := AzureServicePrincipalCredentials{
Id: d.Get("name").(string),
Scope: d.Get("scope").(string),
Description: d.Get("description").(string),
Data: credData,
}
domain := d.Get("domain").(string)
err := cm.Add(ctx, domain, cred)
if err != nil {
return diag.Errorf("Could not create Azure service principal credentials: %s", err)
}
d.SetId(generateCredentialID(d.Get("folder").(string), cred.Id))
return resourceJenkinsCredentialAzureServicePrincipalRead(ctx, d, meta)
}
func resourceJenkinsCredentialAzureServicePrincipalRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cm := meta.(jenkinsClient).Credentials()
cm.Folder = formatFolderName(d.Get("folder").(string))
cred := AzureServicePrincipalCredentials{}
err := cm.GetSingle(
ctx,
d.Get("domain").(string),
d.Get("name").(string),
&cred,
)
if err != nil {
if strings.HasSuffix(err.Error(), "404") {
// Job does not exist
d.SetId("")
return nil
}
return diag.Errorf("Could not read Azure service principal credentials: %s", err)
}
d.SetId(generateCredentialID(d.Get("folder").(string), cred.Id))
_ = d.Set("description", cred.Description)
_ = d.Set("scope", cred.Scope)
// NOTE: We are NOT setting the password here, as the password returned by GetSingle is garbage
// Password only applies to Create/Update operations if the "password" property is non-empty
return nil
}
func resourceJenkinsCredentialAzureServicePrincipalUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cm := meta.(jenkinsClient).Credentials()
cm.Folder = formatFolderName(d.Get("folder").(string))
domain := d.Get("domain").(string)
credData := AzureServicePrincipalCredentialsData{
SubscriptionId: d.Get("subscription_id").(string),
ClientId: d.Get("client_id").(string),
Tenant: d.Get("tenant").(string),
AzureEnvironmentName: d.Get("azure_environment_name").(string),
ServiceManagementURL: d.Get("service_management_url").(string),
AuthenticationEndpoint: d.Get("authentication_endpoint").(string),
ResourceManagerEndpoint: d.Get("resource_manager_endpoint").(string),
GraphEndpoint: d.Get("graph_endpoint").(string),
}
cred := AzureServicePrincipalCredentials{
Id: d.Get("name").(string),
Scope: d.Get("scope").(string),
Description: d.Get("description").(string),
Data: credData,
}
// Only enforce the password if it is non-empty
if d.Get("client_secret").(string) != "" {
cred.Data.ClientSecret = d.Get("client_secret").(string)
}
if d.Get("certificate_id").(string) != "" {
cred.Data.ClientId = d.Get("certificate_id").(string)
}
err := cm.Update(ctx, domain, d.Get("name").(string), &cred)
if err != nil {
return diag.Errorf("Could not update Azure Service Principal credentials: %s", err)
}
d.SetId(generateCredentialID(d.Get("folder").(string), cred.Id))
return resourceJenkinsCredentialAzureServicePrincipalRead(ctx, d, meta)
}
func resourceJenkinsCredentialAzureServicePrincipalDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cm := meta.(jenkinsClient).Credentials()
cm.Folder = formatFolderName(d.Get("folder").(string))
err := cm.Delete(
ctx,
d.Get("domain").(string),
d.Get("name").(string),
)
if err != nil {
return diag.FromErr(err)
}
return nil
}
func resourceJenkinsCredentialAzureServicePrincipalImport(ctx context.Context, d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) {
ret := []*schema.ResourceData{d}
splitID := strings.Split(d.Id(), "/")
if len(splitID) < 2 {
return ret, fmt.Errorf("Import ID was improperly formatted. Imports need to be in the format \"[<folder>/]<domain>/<name>\"")
}
name := splitID[len(splitID)-1]
_ = d.Set("name", name)
domain := splitID[len(splitID)-2]
_ = d.Set("domain", domain)
folder := strings.Trim(strings.Join(splitID[0:len(splitID)-2], "/"), "/")
_ = d.Set("folder", folder)
d.SetId(generateCredentialID(folder, name))
return ret, nil
}