provider.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. package provider
  2. import (
  3. "context"
  4. "os"
  5. "github.com/hashicorp-demoapp/hashicups-client-go"
  6. "github.com/hashicorp/terraform-plugin-framework/datasource"
  7. "github.com/hashicorp/terraform-plugin-framework/function"
  8. "github.com/hashicorp/terraform-plugin-framework/path"
  9. "github.com/hashicorp/terraform-plugin-framework/provider"
  10. "github.com/hashicorp/terraform-plugin-framework/provider/schema"
  11. "github.com/hashicorp/terraform-plugin-framework/resource"
  12. "github.com/hashicorp/terraform-plugin-framework/types"
  13. "github.com/hashicorp/terraform-plugin-log/tflog"
  14. )
  15. // Ensure the implementation satisfies the expected interfaces.
  16. var (
  17. _ provider.Provider = &hashicupsProvider{}
  18. _ provider.ProviderWithFunctions = &hashicupsProvider{}
  19. )
  20. // New is a helper function to simplify provider server and testing implementation.
  21. func New(version string) func() provider.Provider {
  22. return func() provider.Provider {
  23. return &hashicupsProvider{
  24. version: version,
  25. }
  26. }
  27. }
  28. // hashicupsProvider is the provider implementation.
  29. type hashicupsProvider struct {
  30. // version is set to the provider version on release, "dev" when the
  31. // provider is built and ran locally, and "test" when running acceptance
  32. // testing.
  33. version string
  34. }
  35. // The Terraform Plugin Framework uses Go struct types with tfsdk struct field tags
  36. // to map schema definitions into Go types with the actual data.
  37. // The types within the struct must align with the types in the schema.
  38. type hashicupsProviderModel struct {
  39. Host types.String `tfsdk:"host"`
  40. Username types.String `tfsdk:"username"`
  41. Password types.String `tfsdk:"password"`
  42. }
  43. // Metadata returns the provider type name.
  44. func (p *hashicupsProvider) Metadata(_ context.Context, _ provider.MetadataRequest, resp *provider.MetadataResponse) {
  45. resp.TypeName = "hashicups"
  46. resp.Version = p.version
  47. }
  48. // Schema defines the provider-level schema for configuration data.
  49. func (p *hashicupsProvider) Schema(_ context.Context, _ provider.SchemaRequest, resp *provider.SchemaResponse) {
  50. resp.Schema = schema.Schema{
  51. Attributes: map[string]schema.Attribute{
  52. "host": schema.StringAttribute{
  53. Optional: true,
  54. },
  55. "username": schema.StringAttribute{
  56. Optional: true,
  57. },
  58. "password": schema.StringAttribute{
  59. Optional: true,
  60. Sensitive: true,
  61. },
  62. },
  63. }
  64. }
  65. func (p *hashicupsProvider) Configure(ctx context.Context, req provider.ConfigureRequest, resp *provider.ConfigureResponse) {
  66. tflog.Info(ctx, "Configuring HashiCups client")
  67. // 1. Retrieves values from the configuration.
  68. // The method will attempt to retrieve values from the provider configuration and convert it to an providerModel struct.
  69. var config hashicupsProviderModel
  70. diags := req.Config.Get(ctx, &config)
  71. resp.Diagnostics.Append(diags...)
  72. if resp.Diagnostics.HasError() {
  73. return
  74. }
  75. // 2. Checks for unknown configuration values.
  76. // The method prevents an unexpectedly misconfigured client, if Terraform configuration values are only known after another resource is applied.
  77. //
  78. // If practitioner provided a configuration value for any of the attributes, it must be a known value.
  79. // 2.1 host
  80. if config.Host.IsUnknown() {
  81. resp.Diagnostics.AddAttributeError(
  82. path.Root("host"),
  83. "Unknown HashiCups API Host",
  84. "The provider cannot create the HashiCups API client as there is an unknown configuration value for the HashiCups API host. "+
  85. "Either target apply the source of the value first, set the value statically in the configuration, or use the HASHICUPS_HOST environment variable.",
  86. )
  87. }
  88. // 2.2 username
  89. if config.Username.IsUnknown() {
  90. resp.Diagnostics.AddAttributeError(
  91. path.Root("username"),
  92. "Unknown HashiCups API Username",
  93. "The provider cannot create the HashiCups API client as there is an unknown configuration value for the HashiCups API username. "+
  94. "Either target apply the source of the value first, set the value statically in the configuration, or use the HASHICUPS_USERNAME environment variable.",
  95. )
  96. }
  97. // 2.3 password
  98. if config.Password.IsUnknown() {
  99. resp.Diagnostics.AddAttributeError(
  100. path.Root("password"),
  101. "Unknown HashiCups API Password",
  102. "The provider cannot create the HashiCups API client as there is an unknown configuration value for the HashiCups API password. "+
  103. "Either target apply the source of the value first, set the value statically in the configuration, or use the HASHICUPS_PASSWORD environment variable.",
  104. )
  105. }
  106. // 2.4 check results
  107. if resp.Diagnostics.HasError() {
  108. return
  109. }
  110. // 3. Retrieves values from environment variables.
  111. // The method retrieves values from environment variables, then overrides them with any set Terraform configuration values.
  112. // 3.1 Default values to environment variables.
  113. host := os.Getenv("HASHICUPS_HOST") // See docker-compose/docker-compose.yml: http://localhost:19090
  114. username := os.Getenv("HASHICUPS_USERNAME") // We used: curl -X POST localhost:19090/signup -d '{"username":"education", "password":"test123"}'
  115. password := os.Getenv("HASHICUPS_PASSWORD") // We used: curl -X POST localhost:19090/signup -d '{"username":"education", "password":"test123"}'
  116. // 3.2 but override with Terraform configuration value if set.
  117. if !config.Host.IsNull() {
  118. host = config.Host.ValueString()
  119. }
  120. if !config.Username.IsNull() {
  121. username = config.Username.ValueString()
  122. }
  123. if !config.Password.IsNull() {
  124. password = config.Password.ValueString()
  125. }
  126. // 3.3 verify values are set
  127. // If any of the expected configurations are missing, return
  128. // errors with provider-specific guidance.
  129. if host == "" {
  130. resp.Diagnostics.AddAttributeError(
  131. path.Root("host"),
  132. "Missing HashiCups API Host",
  133. "The provider cannot create the HashiCups API client as there is a missing or empty value for the HashiCups API host. "+
  134. "Set the host value in the configuration or use the HASHICUPS_HOST environment variable. "+
  135. "If either is already set, ensure the value is not empty.",
  136. )
  137. }
  138. if username == "" {
  139. resp.Diagnostics.AddAttributeError(
  140. path.Root("username"),
  141. "Missing HashiCups API Username",
  142. "The provider cannot create the HashiCups API client as there is a missing or empty value for the HashiCups API username. "+
  143. "Set the username value in the configuration or use the HASHICUPS_USERNAME environment variable. "+
  144. "If either is already set, ensure the value is not empty.",
  145. )
  146. }
  147. if password == "" {
  148. resp.Diagnostics.AddAttributeError(
  149. path.Root("password"),
  150. "Missing HashiCups API Password",
  151. "The provider cannot create the HashiCups API client as there is a missing or empty value for the HashiCups API password. "+
  152. "Set the password value in the configuration or use the HASHICUPS_PASSWORD environment variable. "+
  153. "If either is already set, ensure the value is not empty.",
  154. )
  155. }
  156. // 3.4 check results
  157. if resp.Diagnostics.HasError() {
  158. return
  159. }
  160. // All fields added to context will be included in subsequent log messages.
  161. ctx = tflog.SetField(ctx, "hashicups_host", host)
  162. ctx = tflog.SetField(ctx, "hashicups_username", username)
  163. ctx = tflog.SetField(ctx, "hashicups_password", password)
  164. ctx = tflog.MaskFieldValuesWithFieldKeys(ctx, "hashicups_password")
  165. tflog.Debug(ctx, "Creating HashiCups API Client")
  166. // 4. Creates API client.
  167. // The method invokes the HashiCups API client's NewClient function.
  168. //
  169. // Create a new HashiCups client using the configuration values
  170. client, err := hashicups.NewClient(&host, &username, &password)
  171. if err != nil {
  172. resp.Diagnostics.AddError(
  173. "Unable to Create HashiCups API Client",
  174. "An unexpected error occurred when creating the HashiCups API client. "+
  175. "If the error is not clear, please contact the provider developers.\n\n"+
  176. "HashiCups Client Error: "+err.Error(),
  177. )
  178. return
  179. }
  180. // 5. Stores configured client for data source and resource usage.
  181. // The method sets the DataSourceData and ResourceData fields of the response,
  182. // so the client is available for usage by data source and resource implementations.
  183. //
  184. // Make the HashiCups client available during DataSource and Resource type Configure methods.
  185. resp.DataSourceData = client
  186. resp.ResourceData = client
  187. // Fields can also be added to only a single log message.
  188. tflog.Info(ctx, "Successfully created HashiCups API Client", map[string]any{
  189. "success": true,
  190. })
  191. }
  192. // DataSources defines the data sources implemented in the provider.
  193. func (p *hashicupsProvider) DataSources(_ context.Context) []func() datasource.DataSource {
  194. return []func() datasource.DataSource{
  195. NewCoffeesDataSource,
  196. }
  197. }
  198. // Resources defines the resources implemented in the provider.
  199. func (p *hashicupsProvider) Resources(_ context.Context) []func() resource.Resource {
  200. return []func() resource.Resource{
  201. NewOrderResource,
  202. }
  203. }
  204. func (p *hashicupsProvider) Functions(ctx context.Context) []func() function.Function {
  205. return []func() function.Function{
  206. NewComputeTaxFunction,
  207. }
  208. }
  209. //// Ensure hashicupsProvider satisfies various provider interfaces.
  210. //var _ provider.Provider = &hashicupsProvider{}
  211. //var _ provider.ProviderWithFunctions = &hashicupsProvider{}
  212. //
  213. //// hashicupsProvider defines the provider implementation.
  214. //type hashicupsProvider struct {
  215. // // version is set to the provider version on release, "dev" when the
  216. // // provider is built and ran locally, and "test" when running acceptance
  217. // // testing.
  218. // version string
  219. //}
  220. //
  221. //// ScaffoldingProviderModel describes the provider data model.
  222. //type ScaffoldingProviderModel struct {
  223. // Endpoint types.String `tfsdk:"endpoint"`
  224. //}
  225. //
  226. //func (p *hashicupsProvider) Metadata(ctx context.Context, req provider.MetadataRequest, resp *provider.MetadataResponse) {
  227. // resp.TypeName = "scaffolding"
  228. // resp.Version = p.version
  229. //}
  230. //
  231. //func (p *hashicupsProvider) Schema(ctx context.Context, req provider.SchemaRequest, resp *provider.SchemaResponse) {
  232. // resp.Schema = schema.Schema{
  233. // Attributes: map[string]schema.Attribute{
  234. // "endpoint": schema.StringAttribute{
  235. // MarkdownDescription: "Example provider attribute",
  236. // Optional: true,
  237. // },
  238. // },
  239. // }
  240. //}
  241. //
  242. //func (p *hashicupsProvider) Configure(ctx context.Context, req provider.ConfigureRequest, resp *provider.ConfigureResponse) {
  243. // var data ScaffoldingProviderModel
  244. //
  245. // resp.Diagnostics.Append(req.Config.Get(ctx, &data)...)
  246. //
  247. // if resp.Diagnostics.HasError() {
  248. // return
  249. // }
  250. //
  251. // // Configuration values are now available.
  252. // // if data.Endpoint.IsNull() { /* ... */ }
  253. //
  254. // // Example client configuration for data sources and resources
  255. // client := http.DefaultClient
  256. // resp.DataSourceData = client
  257. // resp.ResourceData = client
  258. //}
  259. //
  260. //func (p *hashicupsProvider) Resources(ctx context.Context) []func() resource.Resource {
  261. // return []func() resource.Resource{
  262. // NewExampleResource,
  263. // }
  264. //}
  265. //
  266. //func (p *hashicupsProvider) DataSources(ctx context.Context) []func() datasource.DataSource {
  267. // return []func() datasource.DataSource{
  268. // NewExampleDataSource,
  269. // }
  270. //}
  271. //
  272. //func (p *hashicupsProvider) Functions(ctx context.Context) []func() function.Function {
  273. // return []func() function.Function{
  274. // NewExampleFunction,
  275. // }
  276. //}
  277. //
  278. //func New(version string) func() provider.Provider {
  279. // return func() provider.Provider {
  280. // return &hashicupsProvider{
  281. // version: version,
  282. // }
  283. // }
  284. //}