/
gen_obj_inventory_source_data_source.go
297 lines (274 loc) · 9.92 KB
/
gen_obj_inventory_source_data_source.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
292
293
294
295
296
297
package awx
import (
"context"
"fmt"
"net/http"
"net/url"
p "path"
c "github.com/ilijamt/terraform-provider-awx/internal/client"
"github.com/ilijamt/terraform-provider-awx/internal/helpers"
"github.com/ilijamt/terraform-provider-awx/internal/hooks"
"github.com/hashicorp/terraform-plugin-framework-validators/int64validator"
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types"
)
var (
_ datasource.DataSource = &inventorySourceDataSource{}
_ datasource.DataSourceWithConfigure = &inventorySourceDataSource{}
)
// NewInventorySourceDataSource is a helper function to instantiate the InventorySource data source.
func NewInventorySourceDataSource() datasource.DataSource {
return &inventorySourceDataSource{}
}
// inventorySourceDataSource is the data source implementation.
type inventorySourceDataSource struct {
client c.Client
endpoint string
}
// Configure adds the provider configured client to the data source.
func (o *inventorySourceDataSource) Configure(_ context.Context, req datasource.ConfigureRequest, _ *datasource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
o.client = req.ProviderData.(c.Client)
o.endpoint = "/api/v2/inventory_sources/"
}
// Metadata returns the data source type name.
func (o *inventorySourceDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_inventory_source"
}
// Schema defines the schema for the data source.
func (o *inventorySourceDataSource) Schema(ctx context.Context, req datasource.SchemaRequest, resp *datasource.SchemaResponse) {
resp.Schema = schema.Schema{
Attributes: map[string]schema.Attribute{
// Data only elements
"credential": schema.Int64Attribute{
Description: "Cloud credential to use for inventory updates.",
Sensitive: false,
Computed: true,
Validators: []validator.Int64{},
},
"description": schema.StringAttribute{
Description: "Optional description of this inventory source.",
Sensitive: false,
Computed: true,
Validators: []validator.String{},
},
"enabled_value": schema.StringAttribute{
Description: "Only used when enabled_var is set. Value when the host is considered enabled. For example if enabled_var=\"status.power_state\"and enabled_value=\"powered_on\" with host variables:{ \"status\": { \"power_state\": \"powered_on\", \"created\": \"2020-08-04T18:13:04+00:00\", \"healthy\": true }, \"name\": \"foobar\", \"ip_address\": \"192.168.2.1\"}The host would be marked enabled. If power_state where any value other than powered_on then the host would be disabled when imported. If the key is not found then the host will be enabled",
Sensitive: false,
Computed: true,
Validators: []validator.String{},
},
"enabled_var": schema.StringAttribute{
Description: "Retrieve the enabled state from the given dict of host variables. The enabled variable may be specified as \"foo.bar\", in which case the lookup will traverse into nested dicts, equivalent to: from_dict.get(\"foo\", {}).get(\"bar\", default)",
Sensitive: false,
Computed: true,
Validators: []validator.String{},
},
"execution_environment": schema.Int64Attribute{
Description: "The container image to be used for execution.",
Sensitive: false,
Computed: true,
Validators: []validator.Int64{},
},
"host_filter": schema.StringAttribute{
Description: "Regex where only matching hosts will be imported.",
Sensitive: false,
Computed: true,
Validators: []validator.String{},
},
"id": schema.Int64Attribute{
Description: "Database ID for this inventory source.",
Sensitive: false,
Optional: true,
Computed: true,
Validators: []validator.Int64{
int64validator.ExactlyOneOf(
path.MatchRoot("id"),
path.MatchRoot("name"),
),
},
},
"inventory": schema.Int64Attribute{
Description: "Inventory",
Sensitive: false,
Computed: true,
Validators: []validator.Int64{},
},
"name": schema.StringAttribute{
Description: "Name of this inventory source.",
Sensitive: false,
Optional: true,
Computed: true,
Validators: []validator.String{
stringvalidator.ExactlyOneOf(
path.MatchRoot("id"),
path.MatchRoot("name"),
),
},
},
"overwrite": schema.BoolAttribute{
Description: "Overwrite local groups and hosts from remote inventory source.",
Sensitive: false,
Computed: true,
Validators: []validator.Bool{},
},
"overwrite_vars": schema.BoolAttribute{
Description: "Overwrite local variables from remote inventory source.",
Sensitive: false,
Computed: true,
Validators: []validator.Bool{},
},
"source": schema.StringAttribute{
Description: "Source",
Sensitive: false,
Computed: true,
Validators: []validator.String{
stringvalidator.OneOf([]string{"file", "scm", "ec2", "gce", "azure_rm", "vmware", "satellite6", "openstack", "rhv", "controller", "insights"}...),
},
},
"source_path": schema.StringAttribute{
Description: "Source path",
Sensitive: false,
Computed: true,
Validators: []validator.String{},
},
"source_project": schema.Int64Attribute{
Description: "Project containing inventory file used as source.",
Sensitive: false,
Computed: true,
Validators: []validator.Int64{},
},
"source_vars": schema.StringAttribute{
Description: "Inventory source variables in YAML or JSON format.",
Sensitive: false,
Computed: true,
Validators: []validator.String{},
},
"timeout": schema.Int64Attribute{
Description: "The amount of time (in seconds) to run before the task is canceled.",
Sensitive: false,
Computed: true,
Validators: []validator.Int64{
int64validator.Between(-2147483648, 2147483647),
},
},
"update_cache_timeout": schema.Int64Attribute{
Description: "Update cache timeout",
Sensitive: false,
Computed: true,
Validators: []validator.Int64{
int64validator.Between(0, 2147483647),
},
},
"update_on_launch": schema.BoolAttribute{
Description: "Update on launch",
Sensitive: false,
Computed: true,
Validators: []validator.Bool{},
},
"verbosity": schema.StringAttribute{
Description: "Verbosity",
Sensitive: false,
Computed: true,
Validators: []validator.String{
stringvalidator.OneOf([]string{"0", "1", "2"}...),
},
},
// Write only elements
},
}
}
func (o *inventorySourceDataSource) ConfigValidators(ctx context.Context) []datasource.ConfigValidator {
return []datasource.ConfigValidator{}
}
// Read refreshes the Terraform state with the latest data.
func (o *inventorySourceDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
var state inventorySourceTerraformModel
var err error
var endpoint string
var searchDefined bool
// Only one group should evaluate to True, terraform should prevent from being able to set
// the conflicting groups
// Evaluate group 'by_id' based on the schema definition
var groupByIdExists = func() bool {
var groupByIdExists = true
var paramsById = []any{o.endpoint}
var attrID types.Int64
req.Config.GetAttribute(ctx, path.Root("id"), &attrID)
groupByIdExists = groupByIdExists && (!attrID.IsNull() && !attrID.IsUnknown())
paramsById = append(paramsById, attrID.ValueInt64())
if groupByIdExists {
endpoint = p.Clean(fmt.Sprintf("%s/%d/", paramsById...))
}
return groupByIdExists
}()
searchDefined = searchDefined || groupByIdExists
// Evaluate group 'by_name' based on the schema definition
var groupByNameExists = func() bool {
var groupByNameExists = true
var paramsByName = []any{o.endpoint}
var attrName types.String
req.Config.GetAttribute(ctx, path.Root("name"), &attrName)
groupByNameExists = groupByNameExists && (!attrName.IsNull() && !attrName.IsUnknown())
paramsByName = append(paramsByName, url.PathEscape(attrName.ValueString()))
if groupByNameExists {
endpoint = p.Clean(fmt.Sprintf("%s/?name__exact=%s", paramsByName...))
}
return groupByNameExists
}()
searchDefined = searchDefined || groupByNameExists
if !searchDefined {
var detailMessage string
resp.Diagnostics.AddError(
"missing configuration for one of the predefined search groups",
detailMessage,
)
return
}
// Creates a new request for InventorySource
var r *http.Request
if r, err = o.client.NewRequest(ctx, http.MethodGet, endpoint, nil); err != nil {
resp.Diagnostics.AddError(
fmt.Sprintf("Unable to create a new request for InventorySource on %s for read", o.endpoint),
err.Error(),
)
return
}
// Try and actually fetch the data for InventorySource
var data map[string]any
if data, err = o.client.Do(ctx, r); err != nil {
resp.Diagnostics.AddError(
fmt.Sprintf("Unable to read resource for InventorySource on %s", endpoint),
err.Error(),
)
return
}
var d diag.Diagnostics
if data, d, err = helpers.ExtractDataIfSearchResult(data); err != nil {
resp.Diagnostics.Append(d...)
return
}
if d, err = state.updateFromApiData(data); err != nil {
resp.Diagnostics.Append(d...)
return
}
// Set state
if err = hooks.RequireResourceStateOrOrig(ctx, ApiVersion, hooks.SourceData, hooks.CalleeRead, nil, &state); err != nil {
resp.Diagnostics.AddError(
"Unable to process custom hook for the state on InventorySource",
err.Error(),
)
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
}