/
data_source_hiera5.go
90 lines (73 loc) · 2.45 KB
/
data_source_hiera5.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
package hiera5
import (
"context"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/types"
)
var _ datasource.DataSource = &Hiera5StringDataSource{}
type Hiera5StringDataSource struct {
client hiera5
}
type Hiera5StringDataSourceModel struct {
ID types.String `tfsdk:"id"`
Key types.String `tfsdk:"key"`
Value types.String `tfsdk:"value"`
Default types.String `tfsdk:"default"`
Scope types.Map `tfsdk:"scope"`
}
func NewStringDataSource() datasource.DataSource {
return &Hiera5StringDataSource{}
}
func (hb *Hiera5StringDataSource) Metadata(ctx context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
resp.TypeName = "hiera5"
}
func (hb *Hiera5StringDataSource) Configure(_ context.Context, req datasource.ConfigureRequest, _ *datasource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
hb.client = req.ProviderData.(hiera5)
}
func (hb *Hiera5StringDataSource) Schema(ctx context.Context, req datasource.SchemaRequest, resp *datasource.SchemaResponse) {
resp.Schema = schema.Schema{
Attributes: map[string]schema.Attribute{
"id": idAttribute,
"key": keyAttribute,
"value": schema.StringAttribute{
Computed: true,
Description: valueDescription,
},
"default": schema.StringAttribute{
Optional: true,
Description: defaultDescription,
},
"scope": scopeOverrideAttribute,
},
}
}
func (hb *Hiera5StringDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
var data Hiera5StringDataSourceModel
// Read Terraform configuration data into the model
resp.Diagnostics.Append(req.Config.Get(ctx, &data)...)
scopeOverride, diag := processScopeOverrideAttribute(ctx, data.Scope)
resp.Diagnostics.Append(diag...)
if resp.Diagnostics.HasError() {
return
}
v, err := hb.client.value(ctx, data.Key.ValueString(), WithScopeOverride(scopeOverride))
if err != nil && data.Default.IsNull() {
resp.Diagnostics.AddAttributeError(path.Root("key"),
"key not found",
"the value was not found and the default value was not set")
return
}
data.ID = data.Key
if err != nil {
data.Value = data.Default
} else {
data.Value = types.StringValue(v)
}
// Save data into Terraform state
resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
}