example_data_source.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package provider
  2. import (
  3. "context"
  4. "log"
  5. "github.com/hashicorp/terraform-plugin-framework/diag"
  6. "github.com/hashicorp/terraform-plugin-framework/tfsdk"
  7. "github.com/hashicorp/terraform-plugin-framework/types"
  8. )
  9. // Ensure provider defined types fully satisfy framework interfaces
  10. var _ tfsdk.DataSourceType = exampleDataSourceType{}
  11. var _ tfsdk.DataSource = exampleDataSource{}
  12. type exampleDataSourceType struct{}
  13. func (t exampleDataSourceType) GetSchema(ctx context.Context) (tfsdk.Schema, diag.Diagnostics) {
  14. return tfsdk.Schema{
  15. // This description is used by the documentation generator and the language server.
  16. MarkdownDescription: "Example data source",
  17. Attributes: map[string]tfsdk.Attribute{
  18. "configurable_attribute": {
  19. MarkdownDescription: "Example configurable attribute",
  20. Optional: true,
  21. Type: types.StringType,
  22. },
  23. "id": {
  24. MarkdownDescription: "Example identifier",
  25. Type: types.StringType,
  26. Computed: true,
  27. },
  28. },
  29. }, nil
  30. }
  31. func (t exampleDataSourceType) NewDataSource(ctx context.Context, in tfsdk.Provider) (tfsdk.DataSource, diag.Diagnostics) {
  32. provider, diags := convertProviderType(in)
  33. return exampleDataSource{
  34. provider: provider,
  35. }, diags
  36. }
  37. type exampleDataSourceData struct {
  38. ConfigurableAttribute types.String `tfsdk:"configurable_attribute"`
  39. Id types.String `tfsdk:"id"`
  40. }
  41. type exampleDataSource struct {
  42. provider provider
  43. }
  44. func (d exampleDataSource) Read(ctx context.Context, req tfsdk.ReadDataSourceRequest, resp *tfsdk.ReadDataSourceResponse) {
  45. var data exampleDataSourceData
  46. diags := req.Config.Get(ctx, &data)
  47. resp.Diagnostics.Append(diags...)
  48. log.Printf("got here")
  49. if resp.Diagnostics.HasError() {
  50. return
  51. }
  52. log.Printf("got here")
  53. // If applicable, this is a great opportunity to initialize any necessary
  54. // provider client data and make a call using it.
  55. // example, err := d.provider.client.ReadExample(...)
  56. // if err != nil {
  57. // resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to read example, got error: %s", err))
  58. // return
  59. // }
  60. // For the purposes of this example code, hardcoding a response value to
  61. // save into the Terraform state.
  62. data.Id = types.String{Value: "example-id"}
  63. diags = resp.State.Set(ctx, &data)
  64. resp.Diagnostics.Append(diags...)
  65. }