provider.go 11 KB

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