|
| 1 | +// Copyright (c) HashiCorp, Inc. |
| 2 | +// SPDX-License-Identifier: MPL-2.0 |
| 3 | +package provider |
| 4 | + |
| 5 | +import ( |
| 6 | + "context" |
| 7 | + "errors" |
| 8 | + "fmt" |
| 9 | + "time" |
| 10 | + |
| 11 | + tfe "github.com/hashicorp/go-tfe" |
| 12 | + "github.com/hashicorp/terraform-plugin-framework-timetypes/timetypes" |
| 13 | + "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" |
| 14 | + "github.com/hashicorp/terraform-plugin-framework/resource" |
| 15 | + "github.com/hashicorp/terraform-plugin-framework/schema/validator" |
| 16 | + "github.com/hashicorp/terraform-plugin-framework/types/basetypes" |
| 17 | + |
| 18 | + "github.com/hashicorp/terraform-plugin-framework/resource/schema" |
| 19 | + "github.com/hashicorp/terraform-plugin-framework/resource/schema/boolplanmodifier" |
| 20 | + "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" |
| 21 | + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" |
| 22 | + "github.com/hashicorp/terraform-plugin-framework/types" |
| 23 | + "github.com/hashicorp/terraform-plugin-log/tflog" |
| 24 | +) |
| 25 | + |
| 26 | +type resourceAuditTrailToken struct { |
| 27 | + config ConfiguredClient |
| 28 | +} |
| 29 | + |
| 30 | +var _ resource.Resource = &resourceAuditTrailToken{} |
| 31 | +var _ resource.ResourceWithConfigure = &resourceAuditTrailToken{} |
| 32 | +var _ resource.ResourceWithImportState = &resourceAuditTrailToken{} |
| 33 | +var _ resource.ResourceWithModifyPlan = &resourceAuditTrailToken{} |
| 34 | + |
| 35 | +func NewAuditTrailTokenResource() resource.Resource { |
| 36 | + return &resourceAuditTrailToken{} |
| 37 | +} |
| 38 | + |
| 39 | +type modelTFEAuditTrailTokenV0 struct { |
| 40 | + ID types.String `tfsdk:"id"` |
| 41 | + Organization types.String `tfsdk:"organization"` |
| 42 | + Token types.String `tfsdk:"token"` |
| 43 | + ExpiredAt timetypes.RFC3339 `tfsdk:"expired_at"` |
| 44 | + ForceRegenerate types.Bool `tfsdk:"force_regenerate"` |
| 45 | +} |
| 46 | + |
| 47 | +func modelFromTFEOrganizationToken(v *tfe.OrganizationToken, organization string, token types.String, forceRegen types.Bool) modelTFEAuditTrailTokenV0 { |
| 48 | + result := modelTFEAuditTrailTokenV0{ |
| 49 | + Organization: types.StringValue(organization), |
| 50 | + ID: types.StringValue(organization), |
| 51 | + ForceRegenerate: forceRegen, |
| 52 | + Token: token, |
| 53 | + } |
| 54 | + |
| 55 | + if !v.ExpiredAt.IsZero() { |
| 56 | + result.ExpiredAt = timetypes.NewRFC3339TimeValue(v.ExpiredAt) |
| 57 | + } |
| 58 | + |
| 59 | + return result |
| 60 | +} |
| 61 | + |
| 62 | +func (r *resourceAuditTrailToken) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { |
| 63 | + resp.TypeName = req.ProviderTypeName + "_audit_trail_token" |
| 64 | +} |
| 65 | + |
| 66 | +func (r *resourceAuditTrailToken) ModifyPlan(ctx context.Context, req resource.ModifyPlanRequest, resp *resource.ModifyPlanResponse) { |
| 67 | + // If an audit trail token uses the default organization, then if the deafault org. changes, it should trigger a modification |
| 68 | + modifyPlanForDefaultOrganizationChange(ctx, r.config.Organization, req.State, req.Config, req.Plan, resp) |
| 69 | +} |
| 70 | + |
| 71 | +func (r *resourceAuditTrailToken) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) { |
| 72 | + // Prevent panic if the provider has not been configured. |
| 73 | + if req.ProviderData == nil { |
| 74 | + return |
| 75 | + } |
| 76 | + |
| 77 | + client, ok := req.ProviderData.(ConfiguredClient) |
| 78 | + if !ok { |
| 79 | + resp.Diagnostics.AddError( |
| 80 | + "Unexpected resource Configure type", |
| 81 | + fmt.Sprintf("Expected tfe.ConfiguredClient, got %T. This is a bug in the tfe provider, so please report it on GitHub.", req.ProviderData), |
| 82 | + ) |
| 83 | + } |
| 84 | + r.config = client |
| 85 | +} |
| 86 | + |
| 87 | +func (r *resourceAuditTrailToken) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { |
| 88 | + resp.Schema = schema.Schema{ |
| 89 | + Version: 0, |
| 90 | + Attributes: map[string]schema.Attribute{ |
| 91 | + "id": schema.StringAttribute{ |
| 92 | + Computed: true, |
| 93 | + Description: "Service-generated identifier for the token", |
| 94 | + PlanModifiers: []planmodifier.String{ |
| 95 | + stringplanmodifier.UseStateForUnknown(), |
| 96 | + }, |
| 97 | + }, |
| 98 | + "expired_at": schema.StringAttribute{ |
| 99 | + Description: "The time when the audit trail token will expire. This must be a valid ISO8601 timestamp.", |
| 100 | + CustomType: timetypes.RFC3339Type{}, |
| 101 | + Optional: true, |
| 102 | + PlanModifiers: []planmodifier.String{ |
| 103 | + stringplanmodifier.RequiresReplace(), |
| 104 | + }, |
| 105 | + }, |
| 106 | + "organization": schema.StringAttribute{ |
| 107 | + Description: "Name of the organization. If omitted, organization must be defined in the provider config.", |
| 108 | + Optional: true, |
| 109 | + Computed: true, |
| 110 | + Validators: []validator.String{ |
| 111 | + stringvalidator.LengthAtLeast(1), |
| 112 | + }, |
| 113 | + PlanModifiers: []planmodifier.String{ |
| 114 | + stringplanmodifier.RequiresReplace(), |
| 115 | + }, |
| 116 | + }, |
| 117 | + "token": schema.StringAttribute{ |
| 118 | + Description: "The authentication token for accessing Audit Trails.", |
| 119 | + Sensitive: true, |
| 120 | + Computed: true, |
| 121 | + PlanModifiers: []planmodifier.String{ |
| 122 | + stringplanmodifier.UseStateForUnknown(), |
| 123 | + }, |
| 124 | + }, |
| 125 | + "force_regenerate": schema.BoolAttribute{ |
| 126 | + Description: "When set to true will force the audit trail token to be recreated.", |
| 127 | + Optional: true, |
| 128 | + PlanModifiers: []planmodifier.Bool{ |
| 129 | + boolplanmodifier.RequiresReplace(), |
| 130 | + }, |
| 131 | + }, |
| 132 | + }, |
| 133 | + } |
| 134 | +} |
| 135 | + |
| 136 | +func (r *resourceAuditTrailToken) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { |
| 137 | + var state modelTFEAuditTrailTokenV0 |
| 138 | + |
| 139 | + // Read Terraform current state into the model |
| 140 | + resp.Diagnostics.Append(req.State.Get(ctx, &state)...) |
| 141 | + if resp.Diagnostics.HasError() { |
| 142 | + return |
| 143 | + } |
| 144 | + |
| 145 | + var organization string |
| 146 | + resp.Diagnostics.Append(r.config.dataOrDefaultOrganization(ctx, req.State, &organization)...) |
| 147 | + if resp.Diagnostics.HasError() { |
| 148 | + return |
| 149 | + } |
| 150 | + |
| 151 | + tokenType := tfe.AuditTrailToken |
| 152 | + |
| 153 | + tflog.Debug(ctx, "Reading audit trail token") |
| 154 | + token, err := r.config.Client.OrganizationTokens.ReadWithOptions(ctx, organization, tfe.OrganizationTokenReadOptions{TokenType: &tokenType}) |
| 155 | + if err != nil { |
| 156 | + if errors.Is(err, tfe.ErrResourceNotFound) { |
| 157 | + resp.State.RemoveResource(ctx) |
| 158 | + } else { |
| 159 | + resp.Diagnostics.AddError("Error reading Organization Audit Trail Token", "Could not read Organization Audit Trail Token, unexpected error: "+err.Error()) |
| 160 | + } |
| 161 | + return |
| 162 | + } |
| 163 | + |
| 164 | + result := modelFromTFEOrganizationToken(token, organization, state.Token, state.ForceRegenerate) |
| 165 | + |
| 166 | + // Save updated data into Terraform state |
| 167 | + resp.Diagnostics.Append(resp.State.Set(ctx, &result)...) |
| 168 | +} |
| 169 | + |
| 170 | +func (r *resourceAuditTrailToken) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { |
| 171 | + var plan modelTFEAuditTrailTokenV0 |
| 172 | + |
| 173 | + // Read Terraform planned changes into the model |
| 174 | + resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) |
| 175 | + if resp.Diagnostics.HasError() { |
| 176 | + return |
| 177 | + } |
| 178 | + |
| 179 | + tokenType := tfe.AuditTrailToken |
| 180 | + |
| 181 | + var organization string |
| 182 | + resp.Diagnostics.Append(r.config.dataOrDefaultOrganization(ctx, req.Plan, &organization)...) |
| 183 | + |
| 184 | + if resp.Diagnostics.HasError() { |
| 185 | + return |
| 186 | + } |
| 187 | + |
| 188 | + // Check if an audit trail token already exists for the organization and only |
| 189 | + // continue if the force_regenerate flag is set. |
| 190 | + tflog.Debug(ctx, fmt.Sprintf("Check if an audit trail token already exists for organization: %s", organization)) |
| 191 | + if token, err := r.config.Client.OrganizationTokens.ReadWithOptions(ctx, organization, tfe.OrganizationTokenReadOptions{TokenType: &tokenType}); err != nil { |
| 192 | + if !errors.Is(err, tfe.ErrResourceNotFound) { |
| 193 | + resp.Diagnostics.AddError("Error while checking if an audit token exists for organization", fmt.Sprintf("error checking if an audit token exists for organization %s: %s", organization, err)) |
| 194 | + return |
| 195 | + } |
| 196 | + } else if token != nil { |
| 197 | + if !plan.ForceRegenerate.ValueBool() { |
| 198 | + resp.Diagnostics.AddError("An audit trail token already exists", fmt.Sprintf("an audit trail token already exists for organization: %s", organization)) |
| 199 | + return |
| 200 | + } |
| 201 | + tflog.Debug(ctx, fmt.Sprintf("Regenerating existing audit trail token for organization: %s", organization)) |
| 202 | + } |
| 203 | + |
| 204 | + options := tfe.OrganizationTokenCreateOptions{ |
| 205 | + TokenType: &tokenType, |
| 206 | + } |
| 207 | + |
| 208 | + // Optional ExpiryAt |
| 209 | + expireString := plan.ExpiredAt.ValueString() |
| 210 | + if expireString != "" { |
| 211 | + expiry, err := time.Parse(time.RFC3339, expireString) |
| 212 | + if err != nil { |
| 213 | + resp.Diagnostics.AddError("Invalid date", fmt.Sprintf("%s must be a valid date or time, provided in iso8601 format", expireString)) |
| 214 | + return |
| 215 | + } |
| 216 | + options.ExpiredAt = &expiry |
| 217 | + } |
| 218 | + |
| 219 | + tflog.Debug(ctx, fmt.Sprintf("Create audit trail token for organization %s", organization)) |
| 220 | + token, err := r.config.Client.OrganizationTokens.CreateWithOptions(ctx, organization, options) |
| 221 | + if err != nil { |
| 222 | + resp.Diagnostics.AddError("Unable to create organization audit trail token", err.Error()) |
| 223 | + return |
| 224 | + } |
| 225 | + |
| 226 | + result := modelFromTFEOrganizationToken(token, organization, types.StringValue(token.Token), plan.ForceRegenerate) |
| 227 | + |
| 228 | + // Save data into Terraform state |
| 229 | + resp.Diagnostics.Append(resp.State.Set(ctx, &result)...) |
| 230 | +} |
| 231 | + |
| 232 | +func (r *resourceAuditTrailToken) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { |
| 233 | + resp.Diagnostics.AddError("Audit trail tokens cannot be updated", "Audit trail tokens cannot be updated. Please regenerate token.") |
| 234 | +} |
| 235 | + |
| 236 | +func (r *resourceAuditTrailToken) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { |
| 237 | + var state modelTFEAuditTrailTokenV0 |
| 238 | + diags := req.State.Get(ctx, &state) |
| 239 | + resp.Diagnostics.Append(diags...) |
| 240 | + if resp.Diagnostics.HasError() { |
| 241 | + return |
| 242 | + } |
| 243 | + |
| 244 | + var organization string |
| 245 | + resp.Diagnostics.Append(r.config.dataOrDefaultOrganization(ctx, req.State, &organization)...) |
| 246 | + if resp.Diagnostics.HasError() { |
| 247 | + return |
| 248 | + } |
| 249 | + tokenType := tfe.AuditTrailToken |
| 250 | + |
| 251 | + options := tfe.OrganizationTokenDeleteOptions{ |
| 252 | + TokenType: &tokenType, |
| 253 | + } |
| 254 | + |
| 255 | + tflog.Debug(ctx, fmt.Sprintf("Delete organization audit trail token %s", organization)) |
| 256 | + err := r.config.Client.OrganizationTokens.DeleteWithOptions(ctx, organization, options) |
| 257 | + // Ignore 404s for delete |
| 258 | + if err != nil && !errors.Is(err, tfe.ErrResourceNotFound) { |
| 259 | + resp.Diagnostics.AddError( |
| 260 | + "Error deleting organization audit trail token", |
| 261 | + fmt.Sprintf("Couldn't delete organization audit trail token %s: %s", organization, err.Error()), |
| 262 | + ) |
| 263 | + } |
| 264 | + // Resource is implicitly deleted from resp.State if diagnostics have no errors. |
| 265 | +} |
| 266 | + |
| 267 | +func (r *resourceAuditTrailToken) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { |
| 268 | + organization := req.ID |
| 269 | + |
| 270 | + tokenType := tfe.AuditTrailToken |
| 271 | + |
| 272 | + tflog.Debug(ctx, "Reading audit trail token") |
| 273 | + if token, err := r.config.Client.OrganizationTokens.ReadWithOptions(ctx, organization, tfe.OrganizationTokenReadOptions{TokenType: &tokenType}); err != nil { |
| 274 | + resp.Diagnostics.AddError("Error importing organization audit trail token", err.Error()) |
| 275 | + } else if token == nil { |
| 276 | + resp.Diagnostics.AddError( |
| 277 | + "Error importing organization audit trail token", |
| 278 | + "Audit trail token does not exist or has no details", |
| 279 | + ) |
| 280 | + } else { |
| 281 | + result := modelFromTFEOrganizationToken(token, organization, basetypes.NewStringNull(), basetypes.NewBoolNull()) |
| 282 | + resp.Diagnostics.Append(resp.State.Set(ctx, &result)...) |
| 283 | + } |
| 284 | +} |
0 commit comments