provider.go 9.9 KB

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