provider.go 10 KB

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