/
resource_artifactory_distribution_public_key.go
265 lines (226 loc) · 9.52 KB
/
resource_artifactory_distribution_public_key.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
package security
import (
"context"
"fmt"
"net/http"
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
"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/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/jfrog/terraform-provider-shared/util"
utilfw "github.com/jfrog/terraform-provider-shared/util/fw"
)
const DistributionPublicKeysAPIEndPoint = "artifactory/api/security/keys/trusted"
func NewDistributionPublicKeyResource() resource.Resource {
return &DistributionPublicKeyResource{
TypeName: "artifactory_distribution_public_key",
}
}
type DistributionPublicKeyResource struct {
ProviderData util.ProviderMetadata
TypeName string
}
// DistributionPublicKeyResourceModel describes the Terraform resource data model to match the
// resource schema.
type DistributionPublicKeyResourceModel struct {
KeyId types.String `tfsdk:"key_id"`
Alias types.String `tfsdk:"alias"`
Fingerprint types.String `tfsdk:"fingerprint"`
PublicKey TablessSigningKeyValue `tfsdk:"public_key"`
IssuedOn types.String `tfsdk:"issued_on"`
IssuedBy types.String `tfsdk:"issued_by"`
ValidUntil types.String `tfsdk:"valid_until"`
}
func (r *DistributionPublicKeyResourceModel) FromAPIModel(ctx context.Context, model *DistributionPublicKeyAPIModel) diag.Diagnostics {
r.KeyId = types.StringValue(model.KeyId)
r.Alias = types.StringValue(model.Alias)
r.Fingerprint = types.StringValue(model.Fingerprint)
r.PublicKey = tablessSigningKeyValue(model.PublicKey)
r.IssuedOn = types.StringValue(model.IssuedOn)
r.IssuedBy = types.StringValue(model.IssuedBy)
r.ValidUntil = types.StringValue(model.ValidUntil)
return nil
}
// DistributionPublicKeyAPIModel describes the API data model.
type DistributionPublicKeyAPIModel struct {
KeyId string `json:"kid,omitempty"`
Alias string `json:"alias"`
Fingerprint string `json:"fingerprint,omitempty"`
PublicKey string `json:"key"`
IssuedOn string `json:"issued_on,omitempty"`
IssuedBy string `json:"issued_by,omitempty"`
ValidUntil string `json:"valid_until,omitempty"`
}
type DistributionPublicKeysList struct {
Keys []DistributionPublicKeyAPIModel `json:"keys"`
}
func (r *DistributionPublicKeyResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = r.TypeName
}
func (r *DistributionPublicKeyResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
MarkdownDescription: "Manage the public GPG trusted keys used to verify distributed release bundles.",
Attributes: map[string]schema.Attribute{
"key_id": schema.StringAttribute{
MarkdownDescription: "Returns the key id by which this key is referenced in Artifactory.",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"alias": schema.StringAttribute{
MarkdownDescription: "Will be used as an identifier when uploading/retrieving the public key via REST API.",
Required: true,
Validators: []validator.String{stringvalidator.LengthAtLeast(1)},
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplaceIfConfigured(),
},
},
"fingerprint": schema.StringAttribute{
MarkdownDescription: "Returns the computed key fingerprint",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"public_key": schema.StringAttribute{
MarkdownDescription: "The Public key to add as a trusted distribution GPG key. To avoid state drift, ensure there are no leading tab or space characters for each line.",
Required: true,
CustomType: TablessSigningKeyType{},
Validators: []validator.String{signingKeyMustBeGPGOrRSA()},
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplaceIfConfigured(),
},
},
"issued_on": schema.StringAttribute{
MarkdownDescription: "Returns the date/time when this GPG key was created.",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"issued_by": schema.StringAttribute{
MarkdownDescription: "Returns the name and eMail address of issuer.",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"valid_until": schema.StringAttribute{
MarkdownDescription: "Returns the date/time when this GPG key expires.",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
},
}
}
func (r *DistributionPublicKeyResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
// Prevent panic if the provider has not been configured.
if req.ProviderData == nil {
return
}
r.ProviderData = req.ProviderData.(util.ProviderMetadata)
}
func (r *DistributionPublicKeyResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
go util.SendUsageResourceCreate(ctx, r.ProviderData.Client, r.ProviderData.ProductId, r.TypeName)
var plan *DistributionPublicKeyResourceModel
// Read Terraform plan data into the model
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
// Convert from Terraform data model into API data model
var publicKey DistributionPublicKeyAPIModel
body := DistributionPublicKeyAPIModel{
Alias: plan.Alias.ValueString(),
PublicKey: stripTabs(plan.PublicKey.ValueString()),
}
response, err := r.ProviderData.Client.R().
SetBody(body).
SetResult(&publicKey).
Post(DistributionPublicKeysAPIEndPoint)
if err != nil {
utilfw.UnableToCreateResourceError(resp, err.Error())
return
}
// Return error if the HTTP status code is not 200 OK
if response.StatusCode() != http.StatusCreated {
utilfw.UnableToCreateResourceError(resp, response.String())
return
}
// Assign the resource ID for the resource in the state
resp.Diagnostics.Append(plan.FromAPIModel(ctx, &publicKey)...)
// data.KeyId = types.StringValue(publicKey.KeyId)
// Save data into Terraform state
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
}
func (r *DistributionPublicKeyResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
go util.SendUsageResourceRead(ctx, r.ProviderData.Client, r.ProviderData.ProductId, r.TypeName)
var state *DistributionPublicKeyResourceModel
// Read Terraform prior state data into the model
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
// Convert from Terraform data model into API data model
var publicKeys DistributionPublicKeysList
response, err := r.ProviderData.Client.R().
SetResult(&publicKeys).
Get(DistributionPublicKeysAPIEndPoint)
// Treat HTTP 404 Not Found status as a signal to recreate resource
// and return early
if err != nil {
if response.StatusCode() == http.StatusNotFound {
resp.State.RemoveResource(ctx)
}
utilfw.UnableToRefreshResourceError(resp, err.Error())
return
}
// Convert from the API data model to the Terraform data model
// and refresh any attribute values.
for _, key := range publicKeys.Keys {
if key.Alias == state.Alias.ValueString() {
resp.Diagnostics.Append(state.FromAPIModel(ctx, &key)...)
tflog.Debug(ctx, fmt.Sprintf("state after: %v", state))
}
}
if resp.Diagnostics.HasError() {
return
}
// Save updated data into Terraform state
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func (r *DistributionPublicKeyResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
// Update is not supported
}
func (r *DistributionPublicKeyResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
go util.SendUsageResourceDelete(ctx, r.ProviderData.Client, r.ProviderData.ProductId, r.TypeName)
var state DistributionPublicKeyResourceModel
// Read Terraform prior state data into the model
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
response, err := r.ProviderData.Client.R().
Delete(fmt.Sprintf("%s/%s", DistributionPublicKeysAPIEndPoint, state.KeyId.ValueString()))
if err != nil {
utilfw.UnableToDeleteResourceError(resp, err.Error())
return
}
// Return error if the HTTP status code is not 204 No Content or 404 Not Found
if response.StatusCode() != http.StatusNoContent && response.StatusCode() != http.StatusOK {
utilfw.UnableToDeleteResourceError(resp, response.String())
return
}
// If the logic reaches here, it implicitly succeeded and will remove
// the resource from state if there are no other errors.
}
// ImportState imports the resource into the Terraform state.
func (r *DistributionPublicKeyResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
resource.ImportStatePassthroughID(ctx, path.Root("alias"), req, resp)
}