-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathdatasource.go
More file actions
204 lines (184 loc) · 6.64 KB
/
datasource.go
File metadata and controls
204 lines (184 loc) · 6.64 KB
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
package project
import (
"context"
"fmt"
"time"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-framework/types/basetypes"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/stackitcloud/stackit-sdk-go/services/iaas"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
iaasUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/iaas/utils"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/utils"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
)
var (
_ datasource.DataSourceWithConfigure = &projectDataSource{}
)
type DatasourceModel struct {
Id types.String `tfsdk:"id"` // needed by TF
ProjectId types.String `tfsdk:"project_id"`
AreaId types.String `tfsdk:"area_id"`
InternetAccess types.Bool `tfsdk:"internet_access"`
State types.String `tfsdk:"state"`
CreatedAt types.String `tfsdk:"created_at"`
UpdatedAt types.String `tfsdk:"updated_at"`
}
// NewProjectDataSource is a helper function to simplify the provider implementation.
func NewProjectDataSource() datasource.DataSource {
return &projectDataSource{}
}
// projectDatasource is the data source implementation.
type projectDataSource struct {
client *iaas.APIClient
}
func (d *projectDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
providerData, ok := conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
if !ok {
return
}
apiClient := iaasUtils.ConfigureClient(ctx, &providerData, &resp.Diagnostics)
if resp.Diagnostics.HasError() {
return
}
d.client = apiClient
tflog.Info(ctx, "iaas client configured")
}
// Metadata returns the data source type name.
func (d *projectDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_iaas_project"
}
// Schema defines the schema for the datasource.
func (d *projectDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
descriptions := map[string]string{
"main": "Project details. Must have a `region` specified in the provider configuration.",
"id": "Terraform's internal resource ID. It is structured as \"`project_id`\".",
"project_id": "STACKIT project ID.",
"area_id": "The area ID to which the project belongs to.",
"internet_access": "Specifies if the project has internet_access",
"state": "Specifies the state of the project.",
"created_at": "Date-time when the project was created.",
"updated_at": "Date-time when the project was last updated.",
}
resp.Schema = schema.Schema{
MarkdownDescription: descriptions["main"],
Description: descriptions["main"],
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
Description: descriptions["id"],
Computed: true,
},
"project_id": schema.StringAttribute{
Description: descriptions["project_id"],
Required: true,
Validators: []validator.String{
validate.UUID(),
validate.NoSeparator(),
},
},
"area_id": schema.StringAttribute{
Description: descriptions["area_id"],
Computed: true,
},
"internet_access": schema.BoolAttribute{
Description: descriptions["internet_access"],
Computed: true,
},
"state": schema.StringAttribute{
Description: descriptions["state"],
Computed: true,
},
"created_at": schema.StringAttribute{
Description: descriptions["created_at"],
Computed: true,
},
"updated_at": schema.StringAttribute{
Description: descriptions["updated_at"],
Computed: true,
},
},
}
}
// Read refreshes the Terraform state with the latest data.
func (d *projectDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
var model DatasourceModel
diags := req.Config.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
projectId := model.ProjectId.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId)
projectResp, err := d.client.GetProjectDetailsExecute(ctx, projectId)
if err != nil {
utils.LogError(
ctx,
&resp.Diagnostics,
err,
"Reading project",
fmt.Sprintf("Project with ID %q does not exists.", projectId),
nil,
)
resp.State.RemoveResource(ctx)
return
}
// Map response body to schema
err = mapDataSourceFields(projectResp, &model)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading project", fmt.Sprintf("Process API payload: %v", err))
return
}
// Set refreshed state
diags = resp.State.Set(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "project read")
}
func mapDataSourceFields(projectResp *iaas.Project, model *DatasourceModel) error {
if projectResp == nil {
return fmt.Errorf("response input is nil")
}
if model == nil {
return fmt.Errorf("model input is nil")
}
var projectId string
if model.ProjectId.ValueString() != "" {
projectId = model.ProjectId.ValueString()
} else if projectResp.ProjectId != nil {
projectId = *projectResp.ProjectId
} else {
return fmt.Errorf("project id is not present")
}
model.Id = utils.BuildInternalTerraformId(projectId)
model.ProjectId = types.StringValue(projectId)
var areaId basetypes.StringValue
if projectResp.AreaId != nil {
if projectResp.AreaId.String != nil {
areaId = types.StringPointerValue(projectResp.AreaId.String)
} else if projectResp.AreaId.StaticAreaID != nil {
areaId = types.StringValue(string(*projectResp.AreaId.StaticAreaID))
}
}
var createdAt basetypes.StringValue
if projectResp.CreatedAt != nil {
createdAtValue := *projectResp.CreatedAt
createdAt = types.StringValue(createdAtValue.Format(time.RFC3339))
}
var updatedAt basetypes.StringValue
if projectResp.UpdatedAt != nil {
updatedAtValue := *projectResp.UpdatedAt
updatedAt = types.StringValue(updatedAtValue.Format(time.RFC3339))
}
model.AreaId = areaId
model.InternetAccess = types.BoolPointerValue(projectResp.InternetAccess)
model.State = types.StringPointerValue(projectResp.State)
model.CreatedAt = createdAt
model.UpdatedAt = updatedAt
return nil
}