provider.go 11 KB

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