diff --git a/GNUmakefile b/GNUmakefile index 56eaa5ca..680e5c46 100644 --- a/GNUmakefile +++ b/GNUmakefile @@ -53,4 +53,12 @@ test-compile: fi go test -c $(TEST) $(TESTARGS) -.PHONY: build test testacc vet fmt test-compile notify-upstream +resource: + @echo "Skaffolding resource $(name)..." + @cd skaff && go run cmd/main.go -type=resource -name=$(name) + +datasource: + @echo "Skaffolding datasource $(name)..." + @cd skaff && go run cmd/main.go -type=data_source -name=$(name) + +.PHONY: build test testacc vet fmt test-compile notify-upstream resource datasource diff --git a/go.mod b/go.mod index 90852689..70eb3bfe 100644 --- a/go.mod +++ b/go.mod @@ -7,10 +7,12 @@ require ( github.com/hashicorp/hcl v0.0.0-20180404174102-ef8a98b0bbce github.com/hashicorp/terraform-plugin-docs v0.16.0 github.com/hashicorp/terraform-plugin-framework v1.13.0 + github.com/hashicorp/terraform-plugin-framework-validators v0.15.0 github.com/hashicorp/terraform-plugin-go v0.25.0 github.com/hashicorp/terraform-plugin-log v0.9.0 github.com/hashicorp/terraform-plugin-mux v0.17.0 github.com/hashicorp/terraform-plugin-sdk/v2 v2.35.0 + github.com/hashicorp/terraform-plugin-testing v1.11.0 github.com/hashicorp/terraform-svchost v0.1.1 github.com/scalr/go-scalr v0.0.0-20241111151759-2c33e05ca45e ) @@ -40,7 +42,7 @@ require ( github.com/hashicorp/go-uuid v1.0.3 // indirect github.com/hashicorp/go-version v1.7.0 // indirect github.com/hashicorp/hc-install v0.9.0 // indirect - github.com/hashicorp/hcl/v2 v2.22.0 // indirect + github.com/hashicorp/hcl/v2 v2.23.0 // indirect github.com/hashicorp/logutils v1.0.0 // indirect github.com/hashicorp/terraform-exec v0.21.0 // indirect github.com/hashicorp/terraform-json v0.23.0 // indirect @@ -66,14 +68,14 @@ require ( github.com/vmihailenco/msgpack/v5 v5.4.1 // indirect github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect github.com/zclconf/go-cty v1.15.0 // indirect - golang.org/x/crypto v0.28.0 // indirect + golang.org/x/crypto v0.29.0 // indirect golang.org/x/exp v0.0.0-20230626212559-97b1e661b5df // indirect golang.org/x/mod v0.21.0 // indirect golang.org/x/net v0.28.0 // indirect golang.org/x/oauth2 v0.22.0 // indirect - golang.org/x/sync v0.8.0 // indirect - golang.org/x/sys v0.26.0 // indirect - golang.org/x/text v0.19.0 // indirect + golang.org/x/sync v0.9.0 // indirect + golang.org/x/sys v0.27.0 // indirect + golang.org/x/text v0.20.0 // indirect golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d // indirect google.golang.org/appengine v1.6.8 // indirect google.golang.org/genproto v0.0.0-20200904004341-0bd0a958aa1d // indirect diff --git a/go.sum b/go.sum index df258143..a222cf50 100644 --- a/go.sum +++ b/go.sum @@ -112,8 +112,8 @@ github.com/hashicorp/hc-install v0.9.0 h1:2dIk8LcvANwtv3QZLckxcjyF5w8KVtiMxu6G6e github.com/hashicorp/hc-install v0.9.0/go.mod h1:+6vOP+mf3tuGgMApVYtmsnDoKWMDcFXeTxCACYZ8SFg= github.com/hashicorp/hcl v0.0.0-20180404174102-ef8a98b0bbce h1:xdsDDbiBDQTKASoGEZ+pEmF1OnWuu8AQ9I8iNbHNeno= github.com/hashicorp/hcl v0.0.0-20180404174102-ef8a98b0bbce/go.mod h1:oZtUIOe8dh44I2q6ScRibXws4Ajl+d+nod3AaR9vL5w= -github.com/hashicorp/hcl/v2 v2.22.0 h1:hkZ3nCtqeJsDhPRFz5EA9iwcG1hNWGePOTw6oyul12M= -github.com/hashicorp/hcl/v2 v2.22.0/go.mod h1:62ZYHrXgPoX8xBnzl8QzbWq4dyDsDtfCRgIq1rbJEvA= +github.com/hashicorp/hcl/v2 v2.23.0 h1:Fphj1/gCylPxHutVSEOf2fBOh1VE4AuLV7+kbJf3qos= +github.com/hashicorp/hcl/v2 v2.23.0/go.mod h1:62ZYHrXgPoX8xBnzl8QzbWq4dyDsDtfCRgIq1rbJEvA= github.com/hashicorp/logutils v1.0.0 h1:dLEQVugN8vlakKOUE3ihGLTZJRB4j+M2cdTm/ORI65Y= github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64= github.com/hashicorp/terraform-exec v0.21.0 h1:uNkLAe95ey5Uux6KJdua6+cv8asgILFVWkd/RG0D2XQ= @@ -124,6 +124,8 @@ github.com/hashicorp/terraform-plugin-docs v0.16.0 h1:UmxFr3AScl6Wged84jndJIfFcc github.com/hashicorp/terraform-plugin-docs v0.16.0/go.mod h1:M3ZrlKBJAbPMtNOPwHicGi1c+hZUh7/g0ifT/z7TVfA= github.com/hashicorp/terraform-plugin-framework v1.13.0 h1:8OTG4+oZUfKgnfTdPTJwZ532Bh2BobF4H+yBiYJ/scw= github.com/hashicorp/terraform-plugin-framework v1.13.0/go.mod h1:j64rwMGpgM3NYXTKuxrCnyubQb/4VKldEKlcG8cvmjU= +github.com/hashicorp/terraform-plugin-framework-validators v0.15.0 h1:RXMmu7JgpFjnI1a5QjMCBb11usrW2OtAG+iOTIj5c9Y= +github.com/hashicorp/terraform-plugin-framework-validators v0.15.0/go.mod h1:Bh89/hNmqsEWug4/XWKYBwtnw3tbz5BAy1L1OgvbIaY= github.com/hashicorp/terraform-plugin-go v0.25.0 h1:oi13cx7xXA6QciMcpcFi/rwA974rdTxjqEhXJjbAyks= github.com/hashicorp/terraform-plugin-go v0.25.0/go.mod h1:+SYagMYadJP86Kvn+TGeV+ofr/R3g4/If0O5sO96MVw= github.com/hashicorp/terraform-plugin-log v0.9.0 h1:i7hOA+vdAItN1/7UrfBqBwvYPQ9TFvymaRGZED3FCV0= @@ -132,6 +134,8 @@ github.com/hashicorp/terraform-plugin-mux v0.17.0 h1:/J3vv3Ps2ISkbLPiZOLspFcIZ0v github.com/hashicorp/terraform-plugin-mux v0.17.0/go.mod h1:yWuM9U1Jg8DryNfvCp+lH70WcYv6D8aooQxxxIzFDsE= github.com/hashicorp/terraform-plugin-sdk/v2 v2.35.0 h1:wyKCCtn6pBBL46c1uIIBNUOWlNfYXfXpVo16iDyLp8Y= github.com/hashicorp/terraform-plugin-sdk/v2 v2.35.0/go.mod h1:B0Al8NyYVr8Mp/KLwssKXG1RqnTk7FySqSn4fRuLNgw= +github.com/hashicorp/terraform-plugin-testing v1.11.0 h1:MeDT5W3YHbONJt2aPQyaBsgQeAIckwPX41EUHXEn29A= +github.com/hashicorp/terraform-plugin-testing v1.11.0/go.mod h1:WNAHQ3DcgV/0J+B15WTE6hDvxcUdkPPpnB1FR3M910U= github.com/hashicorp/terraform-registry-address v0.2.3 h1:2TAiKJ1A3MAkZlH1YI/aTVcLZRu7JseiXNRHbOAyoTI= github.com/hashicorp/terraform-registry-address v0.2.3/go.mod h1:lFHA76T8jfQteVfT7caREqguFrW3c4MFSPhZB7HHgUM= github.com/hashicorp/terraform-svchost v0.1.1 h1:EZZimZ1GxdqFRinZ1tpJwVxxt49xc/S52uzrw4x0jKQ= @@ -238,8 +242,8 @@ golang.org/x/crypto v0.0.0-20200414173820-0848c9571904/go.mod h1:LzIPMQfyMNhhGPh golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.3.0/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4= -golang.org/x/crypto v0.28.0 h1:GBDwsMXVQi34v5CCYUm2jkJvu4cbtru2U4TN2PSyQnw= -golang.org/x/crypto v0.28.0/go.mod h1:rmgy+3RHxRZMyY0jjAJShp2zgEdOqj2AO7U0pYmeQ7U= +golang.org/x/crypto v0.29.0 h1:L5SG1JTTXupVV3n6sUqMTeWbjAyfPwoda2DLX8J8FrQ= +golang.org/x/crypto v0.29.0/go.mod h1:+F4F4N5hv6v38hfeYwTdx20oUvLLc+QfrE9Ax9HtgRg= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20230626212559-97b1e661b5df h1:UA2aFVmmsIlefxMk29Dp2juaUSth8Pyn3Tq5Y5mJGME= golang.org/x/exp v0.0.0-20230626212559-97b1e661b5df/go.mod h1:FXUEEKJgO7OQYeo8N01OfiKP8RXMtf6e8aTskBGqWdc= @@ -267,8 +271,8 @@ golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ= -golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.9.0 h1:fEo0HyrW1GIgZdpbhCRO0PkJajUS5H9IFUztCgEo2jQ= +golang.org/x/sync v0.9.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -284,21 +288,21 @@ golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo= -golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.27.0 h1:wBqf8DvsY9Y/2P8gAfPDEYNuS30J4lPHJxXSb/nJZ+s= +golang.org/x/sys v0.27.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc= -golang.org/x/term v0.25.0 h1:WtHI/ltw4NvSUig5KARz9h521QvRC8RmF/cuYqifU24= -golang.org/x/term v0.25.0/go.mod h1:RPyXicDX+6vLxogjjRxjgD2TKtmAO6NZBsBRfrOLu7M= +golang.org/x/term v0.26.0 h1:WEQa6V3Gja/BhNxg540hBip/kkaYtRg3cxg4oXSw4AU= +golang.org/x/term v0.26.0/go.mod h1:Si5m1o57C5nBNQo5z1iq+XDijt21BDBDp2bK0QI8e3E= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.19.0 h1:kTxAhCbGbxhK0IwgSKiMO5awPoDQ0RpfiVYBfK860YM= -golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= +golang.org/x/text v0.20.0 h1:gK/Kv2otX8gz+wn7Rmb3vT96ZwuoxnQlY+HlJVj7Qug= +golang.org/x/text v0.20.0/go.mod h1:D4IsuqiFMhST5bX19pQ9ikHC2GsaKyk/oF+pn3ducp4= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= diff --git a/internal/client/client.go b/internal/client/client.go index 4b978797..eead14d6 100644 --- a/internal/client/client.go +++ b/internal/client/client.go @@ -7,16 +7,18 @@ import ( "net/http" "net/url" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/logging" - svchost "github.com/hashicorp/terraform-svchost" + "github.com/hashicorp/terraform-svchost" "github.com/hashicorp/terraform-svchost/disco" "github.com/scalr/go-scalr" + + "github.com/scalr/terraform-provider-scalr/internal/logging" ) var scalrServiceIDs = []string{"iacp.v3"} +// Configure configures and returns a new Scalr client. func Configure(h, t, v string) (*scalr.Client, error) { - // Parse the hostname for comparison, + // Parse the hostname for comparison hostname, err := svchost.ForComparison(h) if err != nil { return nil, err @@ -31,7 +33,7 @@ func Configure(h, t, v string) (*scalr.Client, error) { credsSrc := credentialsSource(config) services := disco.NewWithCredentialsSource(credsSrc) services.SetUserAgent(providerUaString) - services.Transport = logging.NewLoggingHTTPTransport(services.Transport) + services.Transport = logging.NewLoggingTransport(services.Transport) // Add any static host configurations service discovery object. for userHost, hostConfig := range config.Hosts { @@ -93,7 +95,7 @@ func Configure(h, t, v string) (*scalr.Client, error) { } httpClient := scalr.DefaultConfig().HTTPClient - httpClient.Transport = logging.NewLoggingHTTPTransport(httpClient.Transport) + httpClient.Transport = logging.NewLoggingTransport(httpClient.Transport) headers := make(http.Header) headers.Add("User-Agent", providerUaString) diff --git a/internal/client/config.go b/internal/client/config.go index 0a36c29c..f05b6194 100644 --- a/internal/client/config.go +++ b/internal/client/config.go @@ -5,7 +5,7 @@ import ( "os" "github.com/hashicorp/hcl" - svchost "github.com/hashicorp/terraform-svchost" + "github.com/hashicorp/terraform-svchost" "github.com/hashicorp/terraform-svchost/auth" ) @@ -17,15 +17,15 @@ const ( // config is the structure of the configuration for the Terraform CLI. type config struct { - Hosts map[string]*configHost `hcl:"host"` - Credentials map[string]map[string]interface{} `hcl:"credentials"` + Hosts map[string]*configHost `hcl:"host"` + Credentials map[string]map[string]any `hcl:"credentials"` } // configHost is the structure of the "host" nested block within the CLI // configuration, which can be used to override the default service host // discovery behavior for a particular hostname. type configHost struct { - Services map[string]interface{} `hcl:"services"` + Services map[string]any `hcl:"services"` } // CliConfig tries to find and parse the configuration of the Terraform CLI. @@ -57,7 +57,7 @@ func cliConfig() *config { // hostnames. combinedConfig.Credentials = credentialsConfig.Credentials if combinedConfig.Credentials == nil { - combinedConfig.Credentials = make(map[string]map[string]interface{}) + combinedConfig.Credentials = make(map[string]map[string]any) } for host, creds := range mainConfig.Credentials { combinedConfig.Credentials[host] = creds @@ -71,7 +71,7 @@ func credentialsSource(config *config) auth.CredentialsSource { // Add all configured credentials to the credentials source. if len(config.Credentials) > 0 { - staticTable := map[svchost.Hostname]map[string]interface{}{} + staticTable := map[svchost.Hostname]map[string]any{} for userHost, creds := range config.Credentials { host, err := svchost.ForComparison(userHost) if err != nil { diff --git a/internal/framework/datasource.go b/internal/framework/datasource.go new file mode 100644 index 00000000..e8fb8c97 --- /dev/null +++ b/internal/framework/datasource.go @@ -0,0 +1,32 @@ +package framework + +import ( + "context" + "fmt" + + "github.com/hashicorp/terraform-plugin-framework/datasource" + + "github.com/scalr/go-scalr" +) + +type DataSourceWithScalrClient struct { + Client *scalr.Client +} + +func (d *DataSourceWithScalrClient) Configure(_ context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) { + if req.ProviderData == nil { + return + } + + c, ok := req.ProviderData.(*scalr.Client) + if !ok { + resp.Diagnostics.AddError( + "Unexpected Data Source Configure Type", + fmt.Sprintf("Expected *scalr.Client, got: %T. Please report this issue to the provider developers.", req.ProviderData), + ) + + return + } + + d.Client = c +} diff --git a/internal/framework/defaults/account.go b/internal/framework/defaults/account.go new file mode 100644 index 00000000..c981899d --- /dev/null +++ b/internal/framework/defaults/account.go @@ -0,0 +1,54 @@ +package defaults + +import ( + "context" + "fmt" + "os" + + "github.com/hashicorp/terraform-plugin-framework/diag" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/defaults" + "github.com/hashicorp/terraform-plugin-framework/types" +) + +const CurrentAccountIDEnvVar = "SCALR_ACCOUNT_ID" + +func GetDefaultScalrAccountID() (string, diag.Diagnostics) { + var diags diag.Diagnostics + v := os.Getenv(CurrentAccountIDEnvVar) + if v == "" { + diags.AddError( + "Cannot infer current account", + fmt.Sprintf( + "Default value for `account_id` could not be computed."+ + "\nIf you are using Scalr Provider for local runs, please set the attribute in resources explicitly,"+ + "\nor export `%s` environment variable prior the run.", + CurrentAccountIDEnvVar, + ), + ) + } + return v, diags +} + +// AccountIDRequired returns a default account id value handler. +// +// Use AccountIDRequired when a default value for account id must be set. +func AccountIDRequired() defaults.String { + return accountIDRequiredDefault{} +} + +// accountIDRequiredDefault implements defaults.String +type accountIDRequiredDefault struct{} + +func (r accountIDRequiredDefault) Description(_ context.Context) string { + return "value defaults to current Scalr account id" +} + +func (r accountIDRequiredDefault) MarkdownDescription(ctx context.Context) string { + return r.Description(ctx) +} + +func (r accountIDRequiredDefault) DefaultString(_ context.Context, _ defaults.StringRequest, resp *defaults.StringResponse) { + s, diags := GetDefaultScalrAccountID() + resp.Diagnostics.Append(diags...) + resp.PlanValue = types.StringValue(s) +} diff --git a/internal/framework/resource.go b/internal/framework/resource.go new file mode 100644 index 00000000..f186eebc --- /dev/null +++ b/internal/framework/resource.go @@ -0,0 +1,32 @@ +package framework + +import ( + "context" + "fmt" + + "github.com/hashicorp/terraform-plugin-framework/resource" + + "github.com/scalr/go-scalr" +) + +type ResourceWithScalrClient struct { + Client *scalr.Client +} + +func (r *ResourceWithScalrClient) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) { + if req.ProviderData == nil { + return + } + + c, ok := req.ProviderData.(*scalr.Client) + if !ok { + resp.Diagnostics.AddError( + "Unexpected Resource Configure Type", + fmt.Sprintf("Expected *scalr.Client, got: %T. Please report this issue to the provider developers.", req.ProviderData), + ) + + return + } + + r.Client = c +} diff --git a/internal/framework/validation/string_not_whitespace.go b/internal/framework/validation/string_not_whitespace.go new file mode 100644 index 00000000..4c1df9c1 --- /dev/null +++ b/internal/framework/validation/string_not_whitespace.go @@ -0,0 +1,45 @@ +package validation + +import ( + "context" + "fmt" + "strings" + + "github.com/hashicorp/terraform-plugin-framework-validators/helpers/validatordiag" + "github.com/hashicorp/terraform-plugin-framework/schema/validator" +) + +// Compile-time interface check +var _ validator.String = stringIsNotWhiteSpaceValidator{} + +type stringIsNotWhiteSpaceValidator struct{} + +func (v stringIsNotWhiteSpaceValidator) Description(_ context.Context) string { + return "must not be empty or consisting entirely of whitespace characters" +} + +func (v stringIsNotWhiteSpaceValidator) MarkdownDescription(ctx context.Context) string { + return v.Description(ctx) +} + +func (v stringIsNotWhiteSpaceValidator) ValidateString(ctx context.Context, req validator.StringRequest, resp *validator.StringResponse) { + if req.ConfigValue.IsNull() || req.ConfigValue.IsUnknown() { + return + } + + value := req.ConfigValue.ValueString() + + if strings.TrimSpace(value) == "" { + resp.Diagnostics.Append(validatordiag.InvalidAttributeValueDiagnostic( + req.Path, + v.Description(ctx), + fmt.Sprintf("%q", value), + )) + + return + } +} + +func StringIsNotWhiteSpace() validator.String { + return stringIsNotWhiteSpaceValidator{} +} diff --git a/internal/logging/http.go b/internal/logging/http.go new file mode 100644 index 00000000..d5ec38b5 --- /dev/null +++ b/internal/logging/http.go @@ -0,0 +1,144 @@ +package logging + +import ( + "bytes" + "io" + "net/http" + + "github.com/hashicorp/terraform-plugin-log/tflog" +) + +// NewLoggingTransport returns a wrapper around http.RoundTripper +// that logs HTTP requests and responses using the `tflog` package. +// The context.Context of the underlying http.Request is passed to the logger. +func NewLoggingTransport(transport http.RoundTripper) http.RoundTripper { + return &loggingTransport{transport: transport} +} + +// loggingTransport is a http.RoundTripper that logs HTTP requests and responses. +type loggingTransport struct { + transport http.RoundTripper +} + +func (t *loggingTransport) RoundTrip(req *http.Request) (*http.Response, error) { + ctx := req.Context() + + fields, err := collectRequestFields(req) + if err != nil { + tflog.Error(ctx, "Failed to parse request for logging", map[string]interface{}{ + "error": err, + }) + } else { + tflog.Debug(ctx, "Sending HTTP Request", fields) + } + + resp, err := t.transport.RoundTrip(req) + if err != nil { + return resp, err + } + + fields, err = collectResponseFields(resp) + if err != nil { + tflog.Error(ctx, "Failed to parse response for logging", map[string]interface{}{ + "error": err, + }) + } else { + tflog.Debug(ctx, "Received HTTP Response", fields) + } + return resp, nil +} + +func collectRequestFields(req *http.Request) (map[string]interface{}, error) { + fields := make(map[string]interface{}) + + fields["http_op"] = "request" + fields["http_url"] = req.URL.String() + fields["http_method"] = req.Method + + // Collect request headers + for name, values := range req.Header { + if len(values) == 1 { + fields[name] = values[0] + } else { + fields[name] = values + } + } + + // Collect the request body + body, err := bodyFromRequest(req) + if err != nil { + return nil, err + } + fields["http_req_body"] = body + + return fields, nil +} + +func bodyFromRequest(req *http.Request) (string, error) { + if req.Body == nil { + return "", nil + } + + // Read and log the body without consuming it + var buf bytes.Buffer + tee := io.TeeReader(req.Body, &buf) + + // Read the body into a byte slice + bodyBytes, err := io.ReadAll(tee) + if err != nil { + return "", err + } + + // Restore the original request body for the actual request + req.Body = io.NopCloser(&buf) + + return string(bodyBytes), nil +} + +func collectResponseFields(resp *http.Response) (map[string]interface{}, error) { + fields := make(map[string]interface{}) + + fields["http_op"] = "response" + fields["http_status"] = resp.StatusCode + + // Collect response headers + for name, values := range resp.Header { + if len(values) == 1 { + fields[name] = values[0] + } else { + fields[name] = values + } + } + + // Collect the response body + body, err := bodyFromResponse(resp) + if err != nil { + return nil, err + } + fields["http_resp_body"] = body + + return fields, nil +} + +func bodyFromResponse(resp *http.Response) (string, error) { + if resp.Body == nil { + return "", nil + } + + // Read the response body + bodyBytes, err := io.ReadAll(resp.Body) + if err != nil { + return "", err + } + + // Close the original response body + err = resp.Body.Close() + if err != nil { + return "", err + } + + // Restore the response body for the client + resp.Body = io.NopCloser(bytes.NewBuffer(bodyBytes)) + + return string(bodyBytes), nil +} diff --git a/scalr/data_source_scalr_access_policy.go b/internal/provider/data_source_scalr_access_policy.go similarity index 99% rename from scalr/data_source_scalr_access_policy.go rename to internal/provider/data_source_scalr_access_policy.go index bc16fd44..c90ebe5b 100644 --- a/scalr/data_source_scalr_access_policy.go +++ b/internal/provider/data_source_scalr_access_policy.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "context" diff --git a/scalr/data_source_scalr_access_policy_test.go b/internal/provider/data_source_scalr_access_policy_test.go similarity index 89% rename from scalr/data_source_scalr_access_policy_test.go rename to internal/provider/data_source_scalr_access_policy_test.go index f088bf8c..8ef037f4 100644 --- a/scalr/data_source_scalr_access_policy_test.go +++ b/internal/provider/data_source_scalr_access_policy_test.go @@ -1,17 +1,17 @@ -package scalr +package provider import ( "fmt" "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func TestAccScalrAccessPolicyDataSource_basic(t *testing.T) { resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: testAccScalrAccessPolicyDataSourceConfig(), diff --git a/scalr/data_source_scalr_agent_pool.go b/internal/provider/data_source_scalr_agent_pool.go similarity index 95% rename from scalr/data_source_scalr_agent_pool.go rename to internal/provider/data_source_scalr_agent_pool.go index e1f8cbaa..aef98c71 100644 --- a/scalr/data_source_scalr_agent_pool.go +++ b/internal/provider/data_source_scalr_agent_pool.go @@ -1,11 +1,12 @@ -package scalr +package provider import ( "context" "errors" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "log" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/scalr/go-scalr" @@ -71,7 +72,7 @@ func dataSourceScalrAgentPoolRead(ctx context.Context, d *schema.ResourceData, m envID := d.Get("environment_id").(string) options := scalr.AgentPoolListOptions{ - Account: scalr.String(accountID), + Account: ptr(accountID), } if agentPoolID != "" { @@ -83,11 +84,11 @@ func dataSourceScalrAgentPoolRead(ctx context.Context, d *schema.ResourceData, m } if envID != "" { - options.Environment = scalr.String(envID) + options.Environment = ptr(envID) } if vcsEnabled, ok := d.GetOkExists("vcs_enabled"); ok { //nolint:staticcheck - options.VcsEnabled = scalr.Bool(vcsEnabled.(bool)) + options.VcsEnabled = ptr(vcsEnabled.(bool)) } agentPoolsList, err := scalrClient.AgentPools.List(ctx, options) diff --git a/scalr/data_source_scalr_agent_pool_test.go b/internal/provider/data_source_scalr_agent_pool_test.go similarity index 93% rename from scalr/data_source_scalr_agent_pool_test.go rename to internal/provider/data_source_scalr_agent_pool_test.go index 532e9d3e..ced121fe 100644 --- a/scalr/data_source_scalr_agent_pool_test.go +++ b/internal/provider/data_source_scalr_agent_pool_test.go @@ -1,17 +1,17 @@ -package scalr +package provider import ( "fmt" "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func TestAccScalrAgentPoolDataSource_basic(t *testing.T) { resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: `data scalr_agent_pool test {}`, @@ -60,8 +60,8 @@ func TestAccScalrAgentPoolDataSource_basic(t *testing.T) { } func TestAccScalrAgentPoolDataSource_basic_env(t *testing.T) { resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: testAccScalrAgentPoolEnvDataSourceConfig(), diff --git a/scalr/data_source_scalr_current_account.go b/internal/provider/data_source_scalr_current_account.go similarity index 90% rename from scalr/data_source_scalr_current_account.go rename to internal/provider/data_source_scalr_current_account.go index 604e8b0f..6fd865d5 100644 --- a/scalr/data_source_scalr_current_account.go +++ b/internal/provider/data_source_scalr_current_account.go @@ -1,12 +1,15 @@ -package scalr +package provider import ( "context" "errors" + "log" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/scalr/go-scalr" - "log" + + "github.com/scalr/terraform-provider-scalr/internal/framework/defaults" ) func dataSourceScalrCurrentAccount() *schema.Resource { @@ -35,7 +38,7 @@ func dataSourceScalrCurrentAccountRead(ctx context.Context, d *schema.ResourceDa accID, ok := getDefaultScalrAccountID() if !ok { - log.Printf("[DEBUG] %s is not set", currentAccountIDEnvVar) + log.Printf("[DEBUG] %s is not set", defaults.CurrentAccountIDEnvVar) return diag.Errorf("Current account is not set") } diff --git a/scalr/data_source_scalr_current_account_test.go b/internal/provider/data_source_scalr_current_account_test.go similarity index 73% rename from scalr/data_source_scalr_current_account_test.go rename to internal/provider/data_source_scalr_current_account_test.go index 04fb4a88..73ce7f9b 100644 --- a/scalr/data_source_scalr_current_account_test.go +++ b/internal/provider/data_source_scalr_current_account_test.go @@ -1,22 +1,24 @@ -package scalr +package provider import ( "os" "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + + "github.com/scalr/terraform-provider-scalr/internal/framework/defaults" ) func TestAccCurrentAccount_basic(t *testing.T) { resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), PreventPostDestroyRefresh: true, Steps: []resource.TestStep{ { PreConfig: func() { - _ = os.Unsetenv(currentAccountIDEnvVar) + _ = os.Unsetenv(defaults.CurrentAccountIDEnvVar) }, Config: testAccCurrentAccountDataSourceConfig(), PlanOnly: true, @@ -24,7 +26,7 @@ func TestAccCurrentAccount_basic(t *testing.T) { }, { PreConfig: func() { - _ = os.Setenv(currentAccountIDEnvVar, defaultAccount) + _ = os.Setenv(defaults.CurrentAccountIDEnvVar, defaultAccount) }, Config: testAccCurrentAccountDataSourceConfig(), PlanOnly: true, diff --git a/scalr/data_source_scalr_current_run.go b/internal/provider/data_source_scalr_current_run.go similarity index 99% rename from scalr/data_source_scalr_current_run.go rename to internal/provider/data_source_scalr_current_run.go index 31ae7a5c..127f820a 100644 --- a/scalr/data_source_scalr_current_run.go +++ b/internal/provider/data_source_scalr_current_run.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "context" diff --git a/scalr/data_source_scalr_current_run_test.go b/internal/provider/data_source_scalr_current_run_test.go similarity index 92% rename from scalr/data_source_scalr_current_run_test.go rename to internal/provider/data_source_scalr_current_run_test.go index 08ad365b..1061c0f9 100644 --- a/scalr/data_source_scalr_current_run_test.go +++ b/internal/provider/data_source_scalr_current_run_test.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "fmt" @@ -6,7 +6,7 @@ import ( "os" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/scalr/go-scalr" ) @@ -15,7 +15,7 @@ func TestAccCurrentRun_basic(t *testing.T) { resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), PreventPostDestroyRefresh: true, Steps: []resource.TestStep{ { @@ -46,7 +46,7 @@ func TestAccCurrentRun_basic(t *testing.T) { func launchRun(environmentName, workspaceName string) func() { return func() { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) options := GetEnvironmentByNameOptions{ Name: &environmentName, diff --git a/scalr/data_source_scalr_environment.go b/internal/provider/data_source_scalr_environment.go similarity index 98% rename from scalr/data_source_scalr_environment.go rename to internal/provider/data_source_scalr_environment.go index 67e5252c..c69719be 100644 --- a/scalr/data_source_scalr_environment.go +++ b/internal/provider/data_source_scalr_environment.go @@ -1,10 +1,11 @@ -package scalr +package provider import ( "context" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "log" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/scalr/go-scalr" @@ -115,7 +116,7 @@ func dataSourceEnvironmentRead(ctx context.Context, d *schema.ResourceData, meta options := GetEnvironmentByNameOptions{ Name: &envName, Account: &accountID, - Include: scalr.String("created-by"), + Include: ptr("created-by"), } environment, err = GetEnvironmentByName(ctx, options, scalrClient) if err != nil { diff --git a/scalr/data_source_scalr_environment_test.go b/internal/provider/data_source_scalr_environment_test.go similarity index 96% rename from scalr/data_source_scalr_environment_test.go rename to internal/provider/data_source_scalr_environment_test.go index 9c4aced4..c9832884 100644 --- a/scalr/data_source_scalr_environment_test.go +++ b/internal/provider/data_source_scalr_environment_test.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "fmt" @@ -6,7 +6,7 @@ import ( "strconv" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func TestAccEnvironmentDataSource_basic(t *testing.T) { @@ -21,8 +21,8 @@ func TestAccEnvironmentDataSource_basic(t *testing.T) { cuttedRInt := strconv.Itoa(rInt)[:len(strconv.Itoa(rInt))-1] resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: `data scalr_environment test {}`, diff --git a/scalr/data_source_scalr_environments.go b/internal/provider/data_source_scalr_environments.go similarity index 94% rename from scalr/data_source_scalr_environments.go rename to internal/provider/data_source_scalr_environments.go index d5a955bd..ae3775e7 100644 --- a/scalr/data_source_scalr_environments.go +++ b/internal/provider/data_source_scalr_environments.go @@ -1,12 +1,13 @@ -package scalr +package provider import ( "context" "fmt" + "strings" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/scalr/go-scalr" - "strings" ) func dataSourceScalrEnvironments() *schema.Resource { @@ -58,7 +59,7 @@ func dataSourceScalrEnvironmentsRead(ctx context.Context, d *schema.ResourceData if name, ok := d.GetOk("name"); ok { id.WriteString(name.(string)) - options.Filter.Name = scalr.String(name.(string)) + options.Filter.Name = ptr(name.(string)) } if tagIDsI, ok := d.GetOk("tag_ids"); ok { @@ -68,7 +69,7 @@ func dataSourceScalrEnvironmentsRead(ctx context.Context, d *schema.ResourceData tagIDs = append(tagIDs, t.(string)) } if len(tagIDs) > 0 { - options.Filter.Tag = scalr.String("in:" + strings.Join(tagIDs, ",")) + options.Filter.Tag = ptr("in:" + strings.Join(tagIDs, ",")) } } diff --git a/scalr/data_source_scalr_environments_test.go b/internal/provider/data_source_scalr_environments_test.go similarity index 90% rename from scalr/data_source_scalr_environments_test.go rename to internal/provider/data_source_scalr_environments_test.go index 7bb24520..aae3965c 100644 --- a/scalr/data_source_scalr_environments_test.go +++ b/internal/provider/data_source_scalr_environments_test.go @@ -1,18 +1,18 @@ -package scalr +package provider import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func TestAccScalrEnvironmentsDataSource_basic(t *testing.T) { rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: testAccScalrEnvironmentsDataSourceConfigBasic(rInt), diff --git a/scalr/data_source_scalr_event_bridge_integration.go b/internal/provider/data_source_scalr_event_bridge_integration.go similarity index 99% rename from scalr/data_source_scalr_event_bridge_integration.go rename to internal/provider/data_source_scalr_event_bridge_integration.go index 8e40e3f6..b049c0ec 100644 --- a/scalr/data_source_scalr_event_bridge_integration.go +++ b/internal/provider/data_source_scalr_event_bridge_integration.go @@ -1,11 +1,12 @@ -package scalr +package provider import ( "context" "errors" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "log" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/scalr/go-scalr" diff --git a/scalr/data_source_scalr_event_bridge_integration_test.go b/internal/provider/data_source_scalr_event_bridge_integration_test.go similarity index 94% rename from scalr/data_source_scalr_event_bridge_integration_test.go rename to internal/provider/data_source_scalr_event_bridge_integration_test.go index 728e7ece..210562be 100644 --- a/scalr/data_source_scalr_event_bridge_integration_test.go +++ b/internal/provider/data_source_scalr_event_bridge_integration_test.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "fmt" @@ -6,7 +6,7 @@ import ( "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func TestAccScalrEventBridgeIntegrationDataSource_basic(t *testing.T) { @@ -16,8 +16,8 @@ func TestAccScalrEventBridgeIntegrationDataSource_basic(t *testing.T) { t.Skip("Please set AWS_EVENT_BRIDGE_ACCOUNT_ID, AWS_EVENT_BRIDGE_REGION env variables to run this test.") } resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: `data scalr_event_bridge test {}`, diff --git a/scalr/data_source_scalr_iam_team.go b/internal/provider/data_source_scalr_iam_team.go similarity index 95% rename from scalr/data_source_scalr_iam_team.go rename to internal/provider/data_source_scalr_iam_team.go index 7823e823..1322bef4 100644 --- a/scalr/data_source_scalr_iam_team.go +++ b/internal/provider/data_source_scalr_iam_team.go @@ -1,7 +1,8 @@ -package scalr +package provider import ( "context" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" @@ -65,15 +66,15 @@ func dataSourceScalrIamTeamRead(ctx context.Context, d *schema.ResourceData, met accountID := d.Get("account_id").(string) options := scalr.TeamListOptions{ - Account: scalr.String("in:null," + accountID), + Account: ptr("in:null," + accountID), } if teamID != "" { - options.Team = scalr.String(teamID) + options.Team = ptr(teamID) } if name != "" { - options.Name = scalr.String(name) + options.Name = ptr(name) } teams, err := scalrClient.Teams.List(ctx, options) diff --git a/scalr/data_source_scalr_iam_team_test.go b/internal/provider/data_source_scalr_iam_team_test.go similarity index 94% rename from scalr/data_source_scalr_iam_team_test.go rename to internal/provider/data_source_scalr_iam_team_test.go index c25e7711..160e11f8 100644 --- a/scalr/data_source_scalr_iam_team_test.go +++ b/internal/provider/data_source_scalr_iam_team_test.go @@ -1,19 +1,19 @@ -package scalr +package provider import ( "fmt" "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func TestAccScalrIamTeamDataSource_basic(t *testing.T) { rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: `data scalr_iam_team test {}`, diff --git a/scalr/data_source_scalr_iam_user.go b/internal/provider/data_source_scalr_iam_user.go similarity index 97% rename from scalr/data_source_scalr_iam_user.go rename to internal/provider/data_source_scalr_iam_user.go index 61c69509..207fc394 100644 --- a/scalr/data_source_scalr_iam_user.go +++ b/internal/provider/data_source_scalr_iam_user.go @@ -1,10 +1,11 @@ -package scalr +package provider import ( "context" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "log" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/scalr/go-scalr" @@ -72,10 +73,10 @@ func dataSourceScalrIamUserRead(ctx context.Context, d *schema.ResourceData, met options := scalr.UserListOptions{} if uID != "" { - options.User = scalr.String(uID) + options.User = ptr(uID) } if email != "" { - options.Email = scalr.String(email) + options.Email = ptr(email) } log.Printf("[DEBUG] Read configuration of iam user: email '%s', ID '%s'", email, uID) diff --git a/scalr/data_source_scalr_iam_user_test.go b/internal/provider/data_source_scalr_iam_user_test.go similarity index 92% rename from scalr/data_source_scalr_iam_user_test.go rename to internal/provider/data_source_scalr_iam_user_test.go index 509eb218..2f956a6a 100644 --- a/scalr/data_source_scalr_iam_user_test.go +++ b/internal/provider/data_source_scalr_iam_user_test.go @@ -1,18 +1,18 @@ -package scalr +package provider import ( "fmt" "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/scalr/go-scalr" ) func TestAccScalrIamUserDataSource_basic(t *testing.T) { resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: `data scalr_iam_user test {}`, diff --git a/scalr/data_source_scalr_module_version.go b/internal/provider/data_source_scalr_module_version.go similarity index 99% rename from scalr/data_source_scalr_module_version.go rename to internal/provider/data_source_scalr_module_version.go index bc5c7cd3..0e3a95f3 100644 --- a/scalr/data_source_scalr_module_version.go +++ b/internal/provider/data_source_scalr_module_version.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "context" diff --git a/scalr/data_source_scalr_module_version_test.go b/internal/provider/data_source_scalr_module_version_test.go similarity index 94% rename from scalr/data_source_scalr_module_version_test.go rename to internal/provider/data_source_scalr_module_version_test.go index d6857663..e482d824 100644 --- a/scalr/data_source_scalr_module_version_test.go +++ b/internal/provider/data_source_scalr_module_version_test.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "fmt" @@ -6,7 +6,7 @@ import ( "testing" "time" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/scalr/go-scalr" ) @@ -17,7 +17,7 @@ func TestAccModuleVersionDataSource_basic(t *testing.T) { PreCheck: func() { testVcsAccGithubTokenPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: testAccScalrAccountModule(rInt), @@ -55,7 +55,7 @@ func TestAccModuleVersionDataSource_basic(t *testing.T) { func waitForModuleVersions(environmentName string) func() { return func() { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) options := GetEnvironmentByNameOptions{ Name: &environmentName, diff --git a/scalr/data_source_scalr_module_versions.go b/internal/provider/data_source_scalr_module_versions.go similarity index 99% rename from scalr/data_source_scalr_module_versions.go rename to internal/provider/data_source_scalr_module_versions.go index 1a279631..5d5b8d97 100644 --- a/scalr/data_source_scalr_module_versions.go +++ b/internal/provider/data_source_scalr_module_versions.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "context" diff --git a/scalr/data_source_scalr_module_versions_test.go b/internal/provider/data_source_scalr_module_versions_test.go similarity index 97% rename from scalr/data_source_scalr_module_versions_test.go rename to internal/provider/data_source_scalr_module_versions_test.go index ba418c84..e3d4070a 100644 --- a/scalr/data_source_scalr_module_versions_test.go +++ b/internal/provider/data_source_scalr_module_versions_test.go @@ -1,11 +1,11 @@ -package scalr +package provider import ( "fmt" "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/scalr/go-scalr" ) @@ -16,7 +16,7 @@ func TestAccModuleVersionsDataSource_basic(t *testing.T) { PreCheck: func() { testVcsAccGithubTokenPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: `data scalr_module_versions all_by_none {}`, diff --git a/scalr/data_source_scalr_policy_group.go b/internal/provider/data_source_scalr_policy_group.go similarity index 99% rename from scalr/data_source_scalr_policy_group.go rename to internal/provider/data_source_scalr_policy_group.go index ee157e36..02c9c67f 100644 --- a/scalr/data_source_scalr_policy_group.go +++ b/internal/provider/data_source_scalr_policy_group.go @@ -1,10 +1,11 @@ -package scalr +package provider import ( "context" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "log" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/scalr/go-scalr" diff --git a/scalr/data_source_scalr_policy_group_test.go b/internal/provider/data_source_scalr_policy_group_test.go similarity index 95% rename from scalr/data_source_scalr_policy_group_test.go rename to internal/provider/data_source_scalr_policy_group_test.go index aa671f21..7101e961 100644 --- a/scalr/data_source_scalr_policy_group_test.go +++ b/internal/provider/data_source_scalr_policy_group_test.go @@ -1,13 +1,14 @@ -package scalr +package provider import ( "fmt" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/scalr/go-scalr" "log" "regexp" "testing" "time" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/scalr/go-scalr" ) func TestAccPolicyGroupDataSource_basic(t *testing.T) { @@ -19,7 +20,7 @@ func TestAccPolicyGroupDataSource_basic(t *testing.T) { t.Skip("Works with personal token but does not work with github action token.") testVcsAccGithubTokenPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: testAccPolicyGroupConfig(rInt), @@ -102,7 +103,7 @@ func TestAccPolicyGroupDataSource_basic(t *testing.T) { func waitForPolicyGroupFetch(name string) func() { return func() { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) pgl, err := scalrClient.PolicyGroups.List(ctx, scalr.PolicyGroupListOptions{ Account: defaultAccount, diff --git a/scalr/data_source_scalr_provider_configuration.go b/internal/provider/data_source_scalr_provider_configuration.go similarity index 99% rename from scalr/data_source_scalr_provider_configuration.go rename to internal/provider/data_source_scalr_provider_configuration.go index 7df2e95b..beb637cc 100644 --- a/scalr/data_source_scalr_provider_configuration.go +++ b/internal/provider/data_source_scalr_provider_configuration.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "context" diff --git a/scalr/data_source_scalr_provider_configuration_test.go b/internal/provider/data_source_scalr_provider_configuration_test.go similarity index 93% rename from scalr/data_source_scalr_provider_configuration_test.go rename to internal/provider/data_source_scalr_provider_configuration_test.go index 557ac59a..a1c6ecb9 100644 --- a/scalr/data_source_scalr_provider_configuration_test.go +++ b/internal/provider/data_source_scalr_provider_configuration_test.go @@ -1,19 +1,18 @@ -package scalr +package provider import ( "fmt" "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/helper/acctest" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func TestAccScalrProviderConfigurationDataSource(t *testing.T) { resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: testAccScalrProviderConfigurationDataSourceInitConfig, // depends_on works improperly with data sources diff --git a/scalr/data_source_scalr_provider_configurations.go b/internal/provider/data_source_scalr_provider_configurations.go similarity index 99% rename from scalr/data_source_scalr_provider_configurations.go rename to internal/provider/data_source_scalr_provider_configurations.go index 1dd4951b..b2bea8b8 100644 --- a/scalr/data_source_scalr_provider_configurations.go +++ b/internal/provider/data_source_scalr_provider_configurations.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "context" diff --git a/scalr/data_source_scalr_provider_configurations_test.go b/internal/provider/data_source_scalr_provider_configurations_test.go similarity index 94% rename from scalr/data_source_scalr_provider_configurations_test.go rename to internal/provider/data_source_scalr_provider_configurations_test.go index 346d4bc5..f5428453 100644 --- a/scalr/data_source_scalr_provider_configurations_test.go +++ b/internal/provider/data_source_scalr_provider_configurations_test.go @@ -1,17 +1,17 @@ -package scalr +package provider import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" ) func TestAccScalrProviderConfigurationsDataSource(t *testing.T) { resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: testAccScalrProviderConfigurationsDataSourceInitConfig, // depends_on works improperly with data sources diff --git a/scalr/data_source_scalr_role.go b/internal/provider/data_source_scalr_role.go similarity index 97% rename from scalr/data_source_scalr_role.go rename to internal/provider/data_source_scalr_role.go index 28f175c2..23455fe5 100644 --- a/scalr/data_source_scalr_role.go +++ b/internal/provider/data_source_scalr_role.go @@ -1,10 +1,11 @@ -package scalr +package provider import ( "context" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "log" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/scalr/go-scalr" @@ -70,7 +71,7 @@ func dataSourceScalrRoleRead(ctx context.Context, d *schema.ResourceData, meta i accountID := d.Get("account_id").(string) options := scalr.RoleListOptions{ - Account: scalr.String("in:null," + accountID), + Account: ptr("in:null," + accountID), } if roleID != "" { diff --git a/scalr/data_source_scalr_role_test.go b/internal/provider/data_source_scalr_role_test.go similarity index 94% rename from scalr/data_source_scalr_role_test.go rename to internal/provider/data_source_scalr_role_test.go index 79748919..5c92eb0e 100644 --- a/scalr/data_source_scalr_role_test.go +++ b/internal/provider/data_source_scalr_role_test.go @@ -1,18 +1,18 @@ -package scalr +package provider import ( "fmt" "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" ) func TestAccScalrRoleDataSource_basic(t *testing.T) { resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: `data scalr_role test_role {}`, diff --git a/scalr/data_source_scalr_service_account.go b/internal/provider/data_source_scalr_service_account.go similarity index 95% rename from scalr/data_source_scalr_service_account.go rename to internal/provider/data_source_scalr_service_account.go index 08d5edc6..2fca9108 100644 --- a/scalr/data_source_scalr_service_account.go +++ b/internal/provider/data_source_scalr_service_account.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "context" @@ -94,16 +94,16 @@ func dataSourceScalrServiceAccountRead(ctx context.Context, d *schema.ResourceDa accountID := d.Get("account_id").(string) options := scalr.ServiceAccountListOptions{ - Account: scalr.String(accountID), - Include: scalr.String("created-by"), + Account: ptr(accountID), + Include: ptr("created-by"), } if saID != "" { - options.ServiceAccount = scalr.String(saID) + options.ServiceAccount = ptr(saID) } if email != "" { - options.Email = scalr.String(email) + options.Email = ptr(email) } log.Printf("[DEBUG] Read service account with ID '%s', email '%s', and account_id '%s'", saID, email, accountID) diff --git a/scalr/data_source_scalr_service_account_test.go b/internal/provider/data_source_scalr_service_account_test.go similarity index 96% rename from scalr/data_source_scalr_service_account_test.go rename to internal/provider/data_source_scalr_service_account_test.go index 4739b8e9..6a2d30b4 100644 --- a/scalr/data_source_scalr_service_account_test.go +++ b/internal/provider/data_source_scalr_service_account_test.go @@ -1,11 +1,11 @@ -package scalr +package provider import ( "fmt" "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/scalr/go-scalr" ) @@ -13,8 +13,8 @@ func TestAccScalrServiceAccountDataSource_basic(t *testing.T) { rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: `data scalr_service_account test {}`, diff --git a/scalr/data_source_scalr_ssh_key.go b/internal/provider/data_source_scalr_ssh_key.go similarity index 99% rename from scalr/data_source_scalr_ssh_key.go rename to internal/provider/data_source_scalr_ssh_key.go index 599bbc9d..eaa05b63 100644 --- a/scalr/data_source_scalr_ssh_key.go +++ b/internal/provider/data_source_scalr_ssh_key.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "context" diff --git a/scalr/data_source_scalr_ssh_key_test.go b/internal/provider/data_source_scalr_ssh_key_test.go similarity index 93% rename from scalr/data_source_scalr_ssh_key_test.go rename to internal/provider/data_source_scalr_ssh_key_test.go index 9e7cad3c..974b94f4 100644 --- a/scalr/data_source_scalr_ssh_key_test.go +++ b/internal/provider/data_source_scalr_ssh_key_test.go @@ -1,20 +1,20 @@ -package scalr +package provider import ( "fmt" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/helper/acctest" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func TestAccScalrSSHKeyDataSource_basic(t *testing.T) { rInt := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: `data scalr_ssh_key test {}`, diff --git a/scalr/data_source_scalr_variable.go b/internal/provider/data_source_scalr_variable.go similarity index 94% rename from scalr/data_source_scalr_variable.go rename to internal/provider/data_source_scalr_variable.go index cb75444d..14e96d1a 100644 --- a/scalr/data_source_scalr_variable.go +++ b/internal/provider/data_source_scalr_variable.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "context" @@ -121,27 +121,27 @@ func dataSourceScalrVariable() *schema.Resource { func dataSourceScalrVariableRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { scalrClient := meta.(*scalr.Client) filters := scalr.VariableFilter{} - options := scalr.VariableListOptions{Filter: &filters, Include: scalr.String("updated-by")} + options := scalr.VariableListOptions{Filter: &filters, Include: ptr("updated-by")} variableID := d.Get("id").(string) key := d.Get("key").(string) - filters.Account = scalr.String(d.Get("account_id").(string)) + filters.Account = ptr(d.Get("account_id").(string)) if variableID != "" { - filters.Var = scalr.String(variableID) + filters.Var = ptr(variableID) } if key != "" { - filters.Key = scalr.String(key) + filters.Key = ptr(key) } if categoryI, ok := d.GetOk("category"); ok { - filters.Category = scalr.String(categoryI.(string)) + filters.Category = ptr(categoryI.(string)) } if envIdI, ok := d.GetOk("environment_id"); ok { - filters.Environment = scalr.String(envIdI.(string)) + filters.Environment = ptr(envIdI.(string)) } if workspaceIDI, ok := d.GetOk("workspace_id"); ok { - filters.Workspace = scalr.String(workspaceIDI.(string)) + filters.Workspace = ptr(workspaceIDI.(string)) } variables, err := scalrClient.Variables.List(ctx, options) diff --git a/scalr/data_source_scalr_variable_test.go b/internal/provider/data_source_scalr_variable_test.go similarity index 96% rename from scalr/data_source_scalr_variable_test.go rename to internal/provider/data_source_scalr_variable_test.go index 78191924..08c30edd 100644 --- a/scalr/data_source_scalr_variable_test.go +++ b/internal/provider/data_source_scalr_variable_test.go @@ -1,18 +1,18 @@ -package scalr +package provider import ( "fmt" "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func TestAccScalrVariableDataSource(t *testing.T) { resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: `data scalr_variable test {}`, diff --git a/scalr/data_source_scalr_variables.go b/internal/provider/data_source_scalr_variables.go similarity index 95% rename from scalr/data_source_scalr_variables.go rename to internal/provider/data_source_scalr_variables.go index aae9d610..7c67bd16 100644 --- a/scalr/data_source_scalr_variables.go +++ b/internal/provider/data_source_scalr_variables.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "context" @@ -155,9 +155,9 @@ func dataSourceScalrVariables() *schema.Resource { func dataSourceScalrVariablesRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { scalrClient := meta.(*scalr.Client) filters := scalr.VariableFilter{} - options := scalr.VariableListOptions{Filter: &filters, Include: scalr.String("updated-by")} + options := scalr.VariableListOptions{Filter: &filters, Include: ptr("updated-by")} - filters.Account = scalr.String(d.Get("account_id").(string)) + filters.Account = ptr(d.Get("account_id").(string)) if keysI, ok := d.GetOk("keys"); ok { keys := make([]string, 0) @@ -165,11 +165,11 @@ func dataSourceScalrVariablesRead(ctx context.Context, d *schema.ResourceData, m keys = append(keys, keyI.(string)) } if len(keys) > 0 { - filters.Key = scalr.String("in:" + strings.Join(keys, ",")) + filters.Key = ptr("in:" + strings.Join(keys, ",")) } } if categoryI, ok := d.GetOk("category"); ok { - filters.Category = scalr.String(categoryI.(string)) + filters.Category = ptr(categoryI.(string)) } if envIdsI, ok := d.GetOk("environment_ids"); ok { envIds := make([]string, 0) @@ -177,7 +177,7 @@ func dataSourceScalrVariablesRead(ctx context.Context, d *schema.ResourceData, m envIds = append(envIds, envIdI.(string)) } if len(envIds) > 0 { - filters.Environment = scalr.String("in:" + strings.Join(envIds, ",")) + filters.Environment = ptr("in:" + strings.Join(envIds, ",")) } } if wsIdsI, ok := d.GetOk("workspace_ids"); ok { @@ -186,7 +186,7 @@ func dataSourceScalrVariablesRead(ctx context.Context, d *schema.ResourceData, m wsIds = append(wsIds, wsIdI.(string)) } if len(wsIds) > 0 { - filters.Workspace = scalr.String("in:" + strings.Join(wsIds, ",")) + filters.Workspace = ptr("in:" + strings.Join(wsIds, ",")) } } diff --git a/scalr/data_source_scalr_variables_test.go b/internal/provider/data_source_scalr_variables_test.go similarity index 95% rename from scalr/data_source_scalr_variables_test.go rename to internal/provider/data_source_scalr_variables_test.go index 35e8a50f..bb256918 100644 --- a/scalr/data_source_scalr_variables_test.go +++ b/internal/provider/data_source_scalr_variables_test.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "fmt" @@ -6,16 +6,16 @@ import ( "strconv" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/scalr/go-scalr" ) func TestAccScalrVariablesDataSource(t *testing.T) { resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: testAccScalrVariablesDataSourceInitConfig, // depends_on works improperly with data sources diff --git a/scalr/data_source_scalr_vcs_provider.go b/internal/provider/data_source_scalr_vcs_provider.go similarity index 93% rename from scalr/data_source_scalr_vcs_provider.go rename to internal/provider/data_source_scalr_vcs_provider.go index f22594de..984452c8 100644 --- a/scalr/data_source_scalr_vcs_provider.go +++ b/internal/provider/data_source_scalr_vcs_provider.go @@ -1,7 +1,8 @@ -package scalr +package provider import ( "context" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" @@ -73,23 +74,23 @@ func dataSourceScalrVcsProvider() *schema.Resource { func dataSourceScalrVcsProviderRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { scalrClient := meta.(*scalr.Client) options := scalr.VcsProvidersListOptions{ - Account: scalr.String(d.Get("account_id").(string)), + Account: ptr(d.Get("account_id").(string)), } if vcsProviderID, ok := d.GetOk("id"); ok { - options.ID = scalr.String(vcsProviderID.(string)) + options.ID = ptr(vcsProviderID.(string)) } if name, ok := d.GetOk("name"); ok { - options.Query = scalr.String(name.(string)) + options.Query = ptr(name.(string)) } if envId, ok := d.GetOk("environment_id"); ok { - options.Environment = scalr.String(envId.(string)) + options.Environment = ptr(envId.(string)) } if agentPoolID, ok := d.GetOk("agent_pool_id"); ok { - options.AgentPool = scalr.String(agentPoolID.(string)) + options.AgentPool = ptr(agentPoolID.(string)) } if vcsType, ok := d.GetOk("vcs_type"); ok { diff --git a/scalr/data_source_scalr_vcs_provider_test.go b/internal/provider/data_source_scalr_vcs_provider_test.go similarity index 94% rename from scalr/data_source_scalr_vcs_provider_test.go rename to internal/provider/data_source_scalr_vcs_provider_test.go index 6e0fe54e..c662452a 100644 --- a/scalr/data_source_scalr_vcs_provider_test.go +++ b/internal/provider/data_source_scalr_vcs_provider_test.go @@ -1,19 +1,19 @@ -package scalr +package provider import ( "fmt" "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func TestAccScalrVcsProviderDataSource_basic(t *testing.T) { rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testVcsAccGithubTokenPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + PreCheck: func() { testVcsAccGithubTokenPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: testAccScalrVcsProviderDataSourceConfigAllFilters(rInt, githubToken), diff --git a/scalr/data_source_scalr_webhook.go b/internal/provider/data_source_scalr_webhook.go similarity index 99% rename from scalr/data_source_scalr_webhook.go rename to internal/provider/data_source_scalr_webhook.go index 72fc7e25..257d59fe 100644 --- a/scalr/data_source_scalr_webhook.go +++ b/internal/provider/data_source_scalr_webhook.go @@ -1,10 +1,11 @@ -package scalr +package provider import ( "context" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "log" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/scalr/go-scalr" diff --git a/scalr/data_source_scalr_webhook_test.go b/internal/provider/data_source_scalr_webhook_test.go similarity index 96% rename from scalr/data_source_scalr_webhook_test.go rename to internal/provider/data_source_scalr_webhook_test.go index b3d42628..4710e56f 100644 --- a/scalr/data_source_scalr_webhook_test.go +++ b/internal/provider/data_source_scalr_webhook_test.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "fmt" @@ -7,7 +7,7 @@ import ( "strconv" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func TestAccWebhookDataSource_basic(t *testing.T) { @@ -16,8 +16,8 @@ func TestAccWebhookDataSource_basic(t *testing.T) { cutRInt := strconv.Itoa(rInt)[:len(strconv.Itoa(rInt))-1] resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: `data scalr_webhook test {}`, diff --git a/scalr/data_source_scalr_workspace.go b/internal/provider/data_source_scalr_workspace.go similarity index 98% rename from scalr/data_source_scalr_workspace.go rename to internal/provider/data_source_scalr_workspace.go index 1ef0a58f..3866ca0d 100644 --- a/scalr/data_source_scalr_workspace.go +++ b/internal/provider/data_source_scalr_workspace.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "context" @@ -241,15 +241,15 @@ func dataSourceScalrWorkspaceRead(ctx context.Context, d *schema.ResourceData, m options := scalr.WorkspaceListOptions{ Include: "created-by", - Filter: &scalr.WorkspaceFilter{Environment: scalr.String(environmentID)}, + Filter: &scalr.WorkspaceFilter{Environment: ptr(environmentID)}, } if workspaceID != "" { - options.Filter.Id = scalr.String(workspaceID) + options.Filter.Id = ptr(workspaceID) } if name != "" { - options.Filter.Name = scalr.String(name) + options.Filter.Name = ptr(name) } log.Printf("[DEBUG] Read configuration of workspace with ID '%s', name '%s', and environment_id '%s'", workspaceID, name, environmentID) diff --git a/scalr/data_source_scalr_workspace_ids.go b/internal/provider/data_source_scalr_workspace_ids.go similarity index 99% rename from scalr/data_source_scalr_workspace_ids.go rename to internal/provider/data_source_scalr_workspace_ids.go index 957cb34d..d45cdb48 100644 --- a/scalr/data_source_scalr_workspace_ids.go +++ b/internal/provider/data_source_scalr_workspace_ids.go @@ -1,8 +1,9 @@ -package scalr +package provider import ( "context" "fmt" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" diff --git a/scalr/data_source_scalr_workspace_ids_test.go b/internal/provider/data_source_scalr_workspace_ids_test.go similarity index 92% rename from scalr/data_source_scalr_workspace_ids_test.go rename to internal/provider/data_source_scalr_workspace_ids_test.go index 90c6b5af..b4af7440 100644 --- a/scalr/data_source_scalr_workspace_ids_test.go +++ b/internal/provider/data_source_scalr_workspace_ids_test.go @@ -1,18 +1,18 @@ -package scalr +package provider import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func TestAccScalrWorkspaceIDsDataSource_basic(t *testing.T) { rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: testAccScalrWorkspaceIDsDataSourceConfigBasic(rInt), @@ -43,8 +43,8 @@ func TestAccScalrWorkspaceIDsDataSource_wildcard(t *testing.T) { rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: testAccScalrWorkspaceIDsDataSourceConfigWildcard(rInt), diff --git a/scalr/data_source_scalr_workspace_test.go b/internal/provider/data_source_scalr_workspace_test.go similarity index 96% rename from scalr/data_source_scalr_workspace_test.go rename to internal/provider/data_source_scalr_workspace_test.go index 4bcc5b72..1697bf20 100644 --- a/scalr/data_source_scalr_workspace_test.go +++ b/internal/provider/data_source_scalr_workspace_test.go @@ -1,19 +1,19 @@ -package scalr +package provider import ( "fmt" "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func TestAccScalrWorkspaceDataSource_basic(t *testing.T) { rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: testAccScalrWorkspaceDataSourceMissingRequiredConfig, diff --git a/scalr/data_source_scalr_workspaces.go b/internal/provider/data_source_scalr_workspaces.go similarity index 93% rename from scalr/data_source_scalr_workspaces.go rename to internal/provider/data_source_scalr_workspaces.go index a5888e8c..a9095c6b 100644 --- a/scalr/data_source_scalr_workspaces.go +++ b/internal/provider/data_source_scalr_workspaces.go @@ -1,12 +1,13 @@ -package scalr +package provider import ( "context" "fmt" + "strings" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/scalr/go-scalr" - "strings" ) func dataSourceScalrWorkspaces() *schema.Resource { @@ -63,12 +64,12 @@ func dataSourceScalrWorkspacesRead(ctx context.Context, d *schema.ResourceData, if env, ok := d.GetOk("environment_id"); ok { id.WriteString(env.(string)) - options.Filter.Environment = scalr.String(env.(string)) + options.Filter.Environment = ptr(env.(string)) } if name, ok := d.GetOk("name"); ok { id.WriteString(name.(string)) - options.Filter.Name = scalr.String(name.(string)) + options.Filter.Name = ptr(name.(string)) } if tagIDsI, ok := d.GetOk("tag_ids"); ok { @@ -78,7 +79,7 @@ func dataSourceScalrWorkspacesRead(ctx context.Context, d *schema.ResourceData, tagIDs = append(tagIDs, t.(string)) } if len(tagIDs) > 0 { - options.Filter.Tag = scalr.String("in:" + strings.Join(tagIDs, ",")) + options.Filter.Tag = ptr("in:" + strings.Join(tagIDs, ",")) } } diff --git a/scalr/data_source_scalr_workspaces_test.go b/internal/provider/data_source_scalr_workspaces_test.go similarity index 91% rename from scalr/data_source_scalr_workspaces_test.go rename to internal/provider/data_source_scalr_workspaces_test.go index e53b15b7..b432d37a 100644 --- a/scalr/data_source_scalr_workspaces_test.go +++ b/internal/provider/data_source_scalr_workspaces_test.go @@ -1,18 +1,18 @@ -package scalr +package provider import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func TestAccScalrWorkspacesDataSource_basic(t *testing.T) { rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: testAccScalrWorkspacesDataSourceConfigBasic(rInt), diff --git a/scalr/helpers.go b/internal/provider/helpers.go similarity index 93% rename from scalr/helpers.go rename to internal/provider/helpers.go index 25d02b14..a10d3916 100644 --- a/scalr/helpers.go +++ b/internal/provider/helpers.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "context" @@ -8,11 +8,12 @@ import ( "os" "github.com/scalr/go-scalr" + + "github.com/scalr/terraform-provider-scalr/internal/framework/defaults" ) const ( - currentAccountIDEnvVar = "SCALR_ACCOUNT_ID" - dummyIdentifier = "-" + dummyIdentifier = "-" ) type GetEnvironmentByNameOptions struct { @@ -108,7 +109,7 @@ func InterfaceArrToTagRelationArr(arr []interface{}) []*scalr.TagRelation { } func getDefaultScalrAccountID() (string, bool) { - if v := os.Getenv(currentAccountIDEnvVar); v != "" { + if v := os.Getenv(defaults.CurrentAccountIDEnvVar); v != "" { return v, true } return "", false @@ -132,3 +133,8 @@ func scalrAccountIDOptionalDefaultFunc() (interface{}, error) { accID, _ := getDefaultScalrAccountID() return accID, nil } + +// ptr returns a pointer to the value passed. +func ptr[T any](v T) *T { + return &v +} diff --git a/internal/provider/provider.go b/internal/provider/provider.go index b302737a..596ca6cc 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -148,9 +148,13 @@ func (p *scalrProvider) Configure(ctx context.Context, req provider.ConfigureReq } func (p *scalrProvider) Resources(_ context.Context) []func() resource.Resource { - return []func() resource.Resource{} + return []func() resource.Resource{ + newTagResource, + } } func (p *scalrProvider) DataSources(_ context.Context) []func() datasource.DataSource { - return []func() datasource.DataSource{} + return []func() datasource.DataSource{ + newTagDataSource, + } } diff --git a/scalr/provider.go b/internal/provider/provider_sdk.go similarity index 87% rename from scalr/provider.go rename to internal/provider/provider_sdk.go index a865aabb..f0574d44 100644 --- a/scalr/provider.go +++ b/internal/provider/provider_sdk.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "context" @@ -8,11 +8,10 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/scalr/terraform-provider-scalr/internal/client" - "github.com/scalr/terraform-provider-scalr/version" ) -// Provider returns a terraform.ResourceProvider. -func Provider() *schema.Provider { +// Provider returns a terraform.ResourceProvider with version v. +func Provider(v string) *schema.Provider { return &schema.Provider{ Schema: map[string]*schema.Schema{ "hostname": { @@ -52,7 +51,6 @@ func Provider() *schema.Provider { "scalr_provider_configurations": dataSourceScalrProviderConfigurations(), "scalr_role": dataSourceScalrRole(), "scalr_service_account": dataSourceScalrServiceAccount(), - "scalr_tag": dataSourceScalrTag(), "scalr_variable": dataSourceScalrVariable(), "scalr_variables": dataSourceScalrVariables(), "scalr_vcs_provider": dataSourceScalrVcsProvider(), @@ -81,7 +79,6 @@ func Provider() *schema.Provider { "scalr_service_account": resourceScalrServiceAccount(), "scalr_service_account_token": resourceScalrServiceAccountToken(), "scalr_slack_integration": resourceScalrSlackIntegration(), - "scalr_tag": resourceScalrTag(), "scalr_variable": resourceScalrVariable(), "scalr_vcs_provider": resourceScalrVcsProvider(), "scalr_webhook": resourceScalrWebhook(), @@ -92,18 +89,20 @@ func Provider() *schema.Provider { "scalr_ssh_key": resourceScalrSSHKey(), }, - ConfigureContextFunc: providerConfigure, + ConfigureContextFunc: providerConfigure(v), } } -func providerConfigure(_ context.Context, d *schema.ResourceData) (interface{}, diag.Diagnostics) { - h := d.Get("hostname").(string) - t := d.Get("token").(string) +func providerConfigure(v string) func(ctx context.Context, d *schema.ResourceData) (interface{}, diag.Diagnostics) { + return func(_ context.Context, d *schema.ResourceData) (interface{}, diag.Diagnostics) { + h := d.Get("hostname").(string) + t := d.Get("token").(string) - scalrClient, err := client.Configure(h, t, version.ProviderVersion) - if err != nil { - return nil, diag.FromErr(err) - } + scalrClient, err := client.Configure(h, t, v) + if err != nil { + return nil, diag.FromErr(err) + } - return scalrClient, nil + return scalrClient, nil + } } diff --git a/scalr/provider_test.go b/internal/provider/provider_sdk_test.go similarity index 64% rename from scalr/provider_test.go rename to internal/provider/provider_sdk_test.go index 971b8d70..e52a28f5 100644 --- a/scalr/provider_test.go +++ b/internal/provider/provider_sdk_test.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "context" @@ -9,10 +9,11 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + + "github.com/scalr/terraform-provider-scalr/internal/framework/defaults" ) -var testAccProvider *schema.Provider -var testAccProviderFactories map[string]func() (*schema.Provider, error) +var testAccProviderSDK *schema.Provider var noInstanceIdErr = fmt.Errorf("No instance ID is set") var githubToken = os.Getenv("githubToken") @@ -20,27 +21,22 @@ var githubToken = os.Getenv("githubToken") var ctx = context.Background() func init() { - testAccProvider = Provider() - testAccProviderFactories = map[string]func() (*schema.Provider, error){ - "scalr": func() (*schema.Provider, error) { - return testAccProvider, nil - }, - } + testAccProviderSDK = Provider(testProviderVersion) } func TestProvider(t *testing.T) { - if err := Provider().InternalValidate(); err != nil { + if err := Provider(testProviderVersion).InternalValidate(); err != nil { t.Fatalf("err: %s", err) } } func TestProvider_impl(t *testing.T) { - var _ = Provider() + var _ = Provider(testProviderVersion) } func testAccPreCheck(t *testing.T) { // The credentials must be provided by the CLI config file for testing. - if diags := Provider().Configure(context.Background(), &terraform.ResourceConfig{}); diags.HasError() { + if diags := Provider(testProviderVersion).Configure(context.Background(), &terraform.ResourceConfig{}); diags.HasError() { for _, d := range diags { if d.Severity == diag.Error { t.Fatalf("err: %s", d.Summary) @@ -48,7 +44,7 @@ func testAccPreCheck(t *testing.T) { } } // Set env variable to allow `account_id` compute the default value - _ = os.Setenv(currentAccountIDEnvVar, defaultAccount) + _ = os.Setenv(defaults.CurrentAccountIDEnvVar, defaultAccount) } func testVcsAccGithubTokenPreCheck(t *testing.T) { diff --git a/internal/provider/provider_test.go b/internal/provider/provider_test.go new file mode 100644 index 00000000..d799553c --- /dev/null +++ b/internal/provider/provider_test.go @@ -0,0 +1,39 @@ +package provider + +import ( + "context" + "testing" + + "github.com/hashicorp/terraform-plugin-framework/provider" + "github.com/hashicorp/terraform-plugin-framework/providerserver" + "github.com/hashicorp/terraform-plugin-go/tfprotov5" + "github.com/hashicorp/terraform-plugin-mux/tf5muxserver" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +const testProviderVersion = "test" + +var testAccProvider provider.Provider + +func init() { + schema.DescriptionKind = schema.StringMarkdown + testAccProvider = New(testProviderVersion)() +} + +func protoV5ProviderFactories(t *testing.T) map[string]func() (tfprotov5.ProviderServer, error) { + ctx := context.Background() + + providers := []func() tfprotov5.ProviderServer{ + providerserver.NewProtocol5(testAccProvider), + testAccProviderSDK.GRPCProvider, + } + + muxServer, err := tf5muxserver.NewMuxServer(ctx, providers...) + if err != nil { + t.Fatal(err.Error()) + } + + return map[string]func() (tfprotov5.ProviderServer, error){ + "scalr": func() (tfprotov5.ProviderServer, error) { return muxServer.ProviderServer(), nil }, + } +} diff --git a/scalr/resource_scalr_access_policy.go b/internal/provider/resource_scalr_access_policy.go similarity index 99% rename from scalr/resource_scalr_access_policy.go rename to internal/provider/resource_scalr_access_policy.go index ec135208..0fb45819 100644 --- a/scalr/resource_scalr_access_policy.go +++ b/internal/provider/resource_scalr_access_policy.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "context" diff --git a/scalr/resource_scalr_access_policy_test.go b/internal/provider/resource_scalr_access_policy_test.go similarity index 62% rename from scalr/resource_scalr_access_policy_test.go rename to internal/provider/resource_scalr_access_policy_test.go index 787a8d07..dadcd0ff 100644 --- a/scalr/resource_scalr_access_policy_test.go +++ b/internal/provider/resource_scalr_access_policy_test.go @@ -1,16 +1,14 @@ -package scalr +package provider import ( - "context" "fmt" - "log" "math/rand" "regexp" "testing" "time" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/scalr/go-scalr" ) @@ -19,9 +17,9 @@ func TestAccScalrAccessPolicy_basic(t *testing.T) { rInt := rand.New(rand.NewSource(time.Now().UnixNano())).Int() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrAccessPolicyDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrAccessPolicyDestroy, Steps: []resource.TestStep{ { Config: testAccScalrAccessPolicyBasic(rInt), @@ -44,8 +42,8 @@ func TestAccScalrAccessPolicy_bad_scope(t *testing.T) { rg, _ := regexp.Compile(`scope.0.type must be one of \[workspace, environment, account], got: universe`) resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: testAccScalrAccessPolicyBadScope(), @@ -59,8 +57,8 @@ func TestAccScalrAccessPolicy_bad_subject(t *testing.T) { rg, _ := regexp.Compile(`subject.0.type must be one of \[user, team, service_account], got: grandpa`) resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: testAccScalrAccessPolicyBadSubject(), @@ -70,53 +68,14 @@ func TestAccScalrAccessPolicy_bad_subject(t *testing.T) { }) } -func TestAccScalrAccessPolicy_changed_outside(t *testing.T) { - ap := &scalr.AccessPolicy{} - rInt := rand.New(rand.NewSource(time.Now().UnixNano())).Int() - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrAccessPolicyDestroy, - Steps: []resource.TestStep{ - { - Config: testAccScalrAccessPolicyBasic(rInt), - Check: resource.ComposeTestCheckFunc( - testAccCheckScalrAccessPolicyExists("scalr_access_policy.test", ap), - resource.TestCheckResourceAttrSet("scalr_access_policy.test", "id"), - resource.TestCheckResourceAttr("scalr_access_policy.test", "subject.0.type", "user"), - resource.TestCheckResourceAttr("scalr_access_policy.test", "subject.0.id", testUser), - resource.TestCheckResourceAttr("scalr_access_policy.test", "is_system", "false"), - resource.TestCheckResourceAttr("scalr_access_policy.test", "scope.0.type", "environment"), - resource.TestCheckResourceAttr("scalr_access_policy.test", "role_ids.0", readOnlyRole), - resource.TestCheckResourceAttr("scalr_access_policy.test", "role_ids.#", "1"), - ), - }, - { - PreConfig: testAccCheckScalrAccessPolicyChangedOutside(ap), - Config: testAccScalrAccessPolicyChangedOutside(rInt), - PlanOnly: true, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrSet("scalr_access_policy.test", "id"), - resource.TestCheckResourceAttr("scalr_access_policy.test", "subject.0.type", "user"), - resource.TestCheckResourceAttr("scalr_access_policy.test", "subject.0.id", testUser), - resource.TestCheckResourceAttr("scalr_access_policy.test", "is_system", "false"), - resource.TestCheckResourceAttr("scalr_access_policy.test", "scope.0.type", "environment"), - resource.TestCheckResourceAttr("scalr_access_policy.test", "role_ids.0", userRole), - resource.TestCheckResourceAttr("scalr_access_policy.test", "role_ids.#", "1"), - ), - }, - }, - }) -} func TestAccScalrAccessPolicy_update(t *testing.T) { ap := &scalr.AccessPolicy{} rInt := rand.New(rand.NewSource(time.Now().UnixNano())).Int() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrAccessPolicyDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrAccessPolicyDestroy, Steps: []resource.TestStep{ { Config: testAccScalrAccessPolicyBasic(rInt), @@ -158,9 +117,9 @@ func TestAccScalrAccessPolicy_import(t *testing.T) { rInt := rand.New(rand.NewSource(time.Now().UnixNano())).Int() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrAccessPolicyDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrAccessPolicyDestroy, Steps: []resource.TestStep{ { Config: testAccScalrAccessPolicyBasic(rInt), @@ -177,7 +136,7 @@ func TestAccScalrAccessPolicy_import(t *testing.T) { func testAccCheckScalrAccessPolicyExists(resId string, ap *scalr.AccessPolicy) resource.TestCheckFunc { return func(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) rs, ok := s.RootModule().Resources[resId] if !ok { @@ -200,33 +159,8 @@ func testAccCheckScalrAccessPolicyExists(resId string, ap *scalr.AccessPolicy) r } } -func testAccCheckScalrAccessPolicyChangedOutside(ap *scalr.AccessPolicy) func() { - return func() { - scalrClient := testAccProvider.Meta().(*scalr.Client) - - r, err := scalrClient.AccessPolicies.Read(ctx, ap.ID) - - if err != nil { - log.Fatalf("Error retrieving access policy: %v", err) - } - - r, err = scalrClient.AccessPolicies.Update( - context.Background(), - r.ID, - scalr.AccessPolicyUpdateOptions{Roles: []*scalr.Role{{ID: userRole}}}, - ) - if err != nil { - log.Fatalf("Could not change the access policy outside of terraform: %v", err) - } - - if r.Roles[0].ID != userRole { - log.Fatalf("Failed to change the access policy outside of terraform: %v", err) - } - } -} - func testAccCheckScalrAccessPolicyDestroy(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) for _, rs := range s.RootModule().Resources { if rs.Type != "scalr_access_policy" { @@ -313,10 +247,6 @@ func testAccScalrAccessPolicyEmptyRoleId(rInt int) string { return fmt.Sprintf(iamPolicyTemplate, rInt, defaultAccount, testUser, "") } -func testAccScalrAccessPolicyChangedOutside(rInt int) string { - return fmt.Sprintf(iamPolicyTemplate, rInt, defaultAccount, testUser, userRole) -} - func testAccScalrAccessPolicyUpdate(rInt int) string { return fmt.Sprintf(iamPolicyTemplate, rInt, defaultAccount, testUser, fmt.Sprintf("%s\", \"%s", readOnlyRole, userRole)) } diff --git a/scalr/resource_scalr_account_allowed_ips.go b/internal/provider/resource_scalr_account_allowed_ips.go similarity index 99% rename from scalr/resource_scalr_account_allowed_ips.go rename to internal/provider/resource_scalr_account_allowed_ips.go index 8027e404..35536ccf 100644 --- a/scalr/resource_scalr_account_allowed_ips.go +++ b/internal/provider/resource_scalr_account_allowed_ips.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "context" diff --git a/scalr/resource_scalr_account_allowed_ips_test.go b/internal/provider/resource_scalr_account_allowed_ips_test.go similarity index 82% rename from scalr/resource_scalr_account_allowed_ips_test.go rename to internal/provider/resource_scalr_account_allowed_ips_test.go index ad271184..f060414f 100644 --- a/scalr/resource_scalr_account_allowed_ips_test.go +++ b/internal/provider/resource_scalr_account_allowed_ips_test.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "encoding/json" @@ -6,13 +6,13 @@ import ( "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func TestAccScalrAccountAllowedIps_basic(t *testing.T) { resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: testAccScalrAccountAllowedIps([]string{"192.168.0.12", "0.0.0.0/0", "192.168.0.0/32"}), @@ -30,8 +30,8 @@ func TestAccScalrAccountAllowedIps_basic(t *testing.T) { func TestAccScalrAccountAllowedIps_update(t *testing.T) { resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: testAccScalrAccountAllowedIps([]string{"192.168.0.12", "0.0.0.0/0"}), @@ -56,8 +56,8 @@ func TestAccScalrAccountAllowedIps_update(t *testing.T) { func TestAccScalrAccountAllowedIps_import(t *testing.T) { resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: testAccScalrAccountAllowedIps([]string{"192.168.0.12", "0.0.0.0/0"}), @@ -75,8 +75,8 @@ func TestAccScalrAccountAllowedIps_import(t *testing.T) { func TestAccScalrAccountAllowedIps_empty(t *testing.T) { rg, _ := regexp.Compile(`Attribute allowed_ips requires 1 item minimum, but config has only 0`) resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: testAccScalrAccountAllowedIps([]string{}), @@ -89,8 +89,8 @@ func TestAccScalrAccountAllowedIps_empty(t *testing.T) { func TestAccScalrAccountAllowedIps_invalid_CIDR(t *testing.T) { rg, _ := regexp.Compile(`value is not a valid IPv4 network`) resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: testAccScalrAccountAllowedIps([]string{"192.168.0.12/24"}), diff --git a/scalr/resource_scalr_agent_pool.go b/internal/provider/resource_scalr_agent_pool.go similarity index 97% rename from scalr/resource_scalr_agent_pool.go rename to internal/provider/resource_scalr_agent_pool.go index d4e93f01..c5a8efef 100644 --- a/scalr/resource_scalr_agent_pool.go +++ b/internal/provider/resource_scalr_agent_pool.go @@ -1,11 +1,12 @@ -package scalr +package provider import ( "context" "errors" - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "log" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/scalr/go-scalr" ) @@ -63,9 +64,9 @@ func resourceScalrAgentPoolCreate(ctx context.Context, d *schema.ResourceData, m // Create a new options struct options := scalr.AgentPoolCreateOptions{ - Name: scalr.String(name), + Name: ptr(name), Account: &scalr.Account{ID: accountID}, - VcsEnabled: scalr.Bool(vcsEnabled), + VcsEnabled: ptr(vcsEnabled), } if envID, ok := d.GetOk("environment_id"); ok { @@ -123,7 +124,7 @@ func resourceScalrAgentPoolUpdate(ctx context.Context, d *schema.ResourceData, m if d.HasChange("name") { // Create a new options struct options := scalr.AgentPoolUpdateOptions{ - Name: scalr.String(d.Get("name").(string)), + Name: ptr(d.Get("name").(string)), } log.Printf("[DEBUG] Update agent pool %s", id) diff --git a/scalr/resource_scalr_agent_pool_test.go b/internal/provider/resource_scalr_agent_pool_test.go similarity index 52% rename from scalr/resource_scalr_agent_pool_test.go rename to internal/provider/resource_scalr_agent_pool_test.go index 8ed30ecd..b13460bd 100644 --- a/scalr/resource_scalr_agent_pool_test.go +++ b/internal/provider/resource_scalr_agent_pool_test.go @@ -1,13 +1,11 @@ -package scalr +package provider import ( - "context" "fmt" - "log" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/scalr/go-scalr" ) @@ -16,9 +14,9 @@ func TestAccScalrAgentPool_basic(t *testing.T) { rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrAgentPoolDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrAgentPoolDestroy, Steps: []resource.TestStep{ { Config: testAccScalrAgentPoolBasic(rInt), @@ -34,46 +32,14 @@ func TestAccScalrAgentPool_basic(t *testing.T) { }) } -func TestAccScalrAgentPool_renamed(t *testing.T) { - pool := &scalr.AgentPool{} - rInt := GetRandomInteger() - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrAgentPoolDestroy, - Steps: []resource.TestStep{ - { - Config: testAccScalrAgentPoolBasic(rInt), - Check: resource.ComposeTestCheckFunc( - testAccCheckScalrAgentPoolExists("scalr_agent_pool.test", pool), - resource.TestCheckResourceAttr( - "scalr_agent_pool.test", "name", fmt.Sprintf("agent_pool-test-%d", rInt), - ), - resource.TestCheckResourceAttr("scalr_agent_pool.test", "account_id", defaultAccount), - ), - }, - - { - PreConfig: testAccCheckScalrAgentPoolRename(pool), - Config: testAccScalrAgentPoolRenamed(rInt), - PlanOnly: true, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("scalr_agent_pool.test", "name", "renamed-outside-of-terraform"), - resource.TestCheckResourceAttr("scalr_agent_pool.test", "account_id", defaultAccount), - ), - }, - }, - }) -} func TestAccScalrAgentPool_update(t *testing.T) { pool := &scalr.AgentPool{} rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrAgentPoolDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrAgentPoolDestroy, Steps: []resource.TestStep{ { Config: testAccScalrAgentPoolBasic(rInt), @@ -100,9 +66,9 @@ func TestAccScalrAgentPool_import(t *testing.T) { rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrAgentPoolDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrAgentPoolDestroy, Steps: []resource.TestStep{ { Config: testAccScalrAgentPoolBasic(rInt), @@ -119,7 +85,7 @@ func TestAccScalrAgentPool_import(t *testing.T) { func testAccCheckScalrAgentPoolExists(resId string, pool *scalr.AgentPool) resource.TestCheckFunc { return func(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) rs, ok := s.RootModule().Resources[resId] if !ok { @@ -142,33 +108,8 @@ func testAccCheckScalrAgentPoolExists(resId string, pool *scalr.AgentPool) resou } } -func testAccCheckScalrAgentPoolRename(pool *scalr.AgentPool) func() { - return func() { - scalrClient := testAccProvider.Meta().(*scalr.Client) - - r, err := scalrClient.AgentPools.Read(ctx, pool.ID) - - if err != nil { - log.Fatalf("Error retrieving agent pool: %v", err) - } - - r, err = scalrClient.AgentPools.Update( - context.Background(), - r.ID, - scalr.AgentPoolUpdateOptions{Name: scalr.String("renamed-outside-of-terraform")}, - ) - if err != nil { - log.Fatalf("Could not rename the agent pool outside of terraform: %v", err) - } - - if r.Name != "renamed-outside-of-terraform" { - log.Fatalf("Failed to rename the agent pool outside of terraform: %v", err) - } - } -} - func testAccCheckScalrAgentPoolDestroy(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) for _, rs := range s.RootModule().Resources { if rs.Type != "scalr_agent_pool" { @@ -203,20 +144,6 @@ resource "scalr_agent_pool" "test" { }`, rInt, defaultAccount, rInt, defaultAccount) } -func testAccScalrAgentPoolRenamed(rInt int) string { - return fmt.Sprintf(` -resource "scalr_environment" "test" { - name = "agent_pool-test-%d" - account_id = "%s" - -} -resource "scalr_agent_pool" "test" { - name = "renamed-outside-of-terraform" - account_id = "%s" - environment_id = scalr_environment.test.id -}`, rInt, defaultAccount, defaultAccount) -} - func testAccScalrAgentPoolUpdate() string { return fmt.Sprintf(` resource "scalr_agent_pool" "test" { diff --git a/scalr/resource_scalr_agent_pool_token.go b/internal/provider/resource_scalr_agent_pool_token.go similarity index 97% rename from scalr/resource_scalr_agent_pool_token.go rename to internal/provider/resource_scalr_agent_pool_token.go index 27becff1..974c7b3b 100644 --- a/scalr/resource_scalr_agent_pool_token.go +++ b/internal/provider/resource_scalr_agent_pool_token.go @@ -1,11 +1,12 @@ -package scalr +package provider import ( "context" "errors" - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "log" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/scalr/go-scalr" ) @@ -50,7 +51,7 @@ func resourceScalrAgentPoolTokenCreate(ctx context.Context, d *schema.ResourceDa options := scalr.AccessTokenCreateOptions{} if desc, ok := d.GetOk("description"); ok { - options.Description = scalr.String(desc.(string)) + options.Description = ptr(desc.(string)) } log.Printf("[DEBUG] Create token for agent pool: %s", poolID) @@ -122,7 +123,7 @@ func resourceScalrAgentPoolTokenUpdate(ctx context.Context, d *schema.ResourceDa desc := d.Get("description").(string) // Create a new options struct options := scalr.AccessTokenUpdateOptions{ - Description: scalr.String(desc), + Description: ptr(desc), } log.Printf("[DEBUG] Update agent pool token %s", id) diff --git a/scalr/resource_scalr_agent_pool_token_test.go b/internal/provider/resource_scalr_agent_pool_token_test.go similarity index 60% rename from scalr/resource_scalr_agent_pool_token_test.go rename to internal/provider/resource_scalr_agent_pool_token_test.go index a4c12f65..db3dcf9f 100644 --- a/scalr/resource_scalr_agent_pool_token_test.go +++ b/internal/provider/resource_scalr_agent_pool_token_test.go @@ -1,13 +1,11 @@ -package scalr +package provider import ( - "context" "fmt" - "log" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/scalr/go-scalr" ) @@ -21,9 +19,9 @@ func TestAccScalrAgentPoolToken_basic(t *testing.T) { } resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrAgentPoolTokenDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrAgentPoolTokenDestroy, Steps: []resource.TestStep{ { Config: testAccScalrAgentPoolTokenBasic(pool), @@ -37,41 +35,6 @@ func TestAccScalrAgentPoolToken_basic(t *testing.T) { }) } -func TestAccScalrAgentPoolToken_changed_outside(t *testing.T) { - - var pool scalr.AgentPool - if isAccTest() { - pool = createPool(t) - defer deletePool(t, pool) - } - token := &scalr.AccessToken{} - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrAgentPoolTokenDestroy, - Steps: []resource.TestStep{ - { - Config: testAccScalrAgentPoolTokenBasic(pool), - Check: resource.ComposeTestCheckFunc( - testAccCheckScalrAgentPoolTokenExists("scalr_agent_pool_token.test", pool, token), - resource.TestCheckResourceAttr("scalr_agent_pool_token.test", "description", "agent_pool_token-test"), - resource.TestCheckResourceAttr("scalr_agent_pool_token.test", "agent_pool_id", pool.ID), - ), - }, - - { - PreConfig: testAccCheckScalrAgentPoolTokenChangedOutside(token), - Config: testAccScalrAgentPoolTokenChangedOutside(pool), - PlanOnly: true, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("scalr_agent_pool_token.test", "description", "changed-outside-of-terraform"), - resource.TestCheckResourceAttr("scalr_agent_pool_token.test", "agent_pool_id", pool.ID), - ), - }, - }, - }) -} func TestAccScalrAgentPoolToken_update(t *testing.T) { var pool scalr.AgentPool if isAccTest() { @@ -81,9 +44,9 @@ func TestAccScalrAgentPoolToken_update(t *testing.T) { token := &scalr.AccessToken{} resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrAgentPoolTokenDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrAgentPoolTokenDestroy, Steps: []resource.TestStep{ { Config: testAccScalrAgentPoolTokenBasic(pool), @@ -106,7 +69,7 @@ func TestAccScalrAgentPoolToken_update(t *testing.T) { func testAccCheckScalrAgentPoolTokenExists(resId string, pool scalr.AgentPool, token *scalr.AccessToken) resource.TestCheckFunc { return func(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) rs, ok := s.RootModule().Resources[resId] if !ok { @@ -136,25 +99,6 @@ func testAccCheckScalrAgentPoolTokenExists(resId string, pool scalr.AgentPool, t } } -func testAccCheckScalrAgentPoolTokenChangedOutside(token *scalr.AccessToken) func() { - return func() { - scalrClient := testAccProvider.Meta().(*scalr.Client) - - r, err := scalrClient.AccessTokens.Update( - context.Background(), - token.ID, - scalr.AccessTokenUpdateOptions{Description: scalr.String("changed-outside-of-terraform")}, - ) - if err != nil { - log.Fatalf("Could not update the agent pool outside of terraform: %v", err) - } - - if r.Description != "changed-outside-of-terraform" { - log.Fatalf("Failed to update the agent pool outside of terraform: %v", err) - } - } -} - func deletePool(t *testing.T, pool scalr.AgentPool) { scalrClient, err := createScalrClient() if err != nil { @@ -176,7 +120,7 @@ func createPool(t *testing.T) scalr.AgentPool { } r, err := scalrClient.AgentPools.Create(ctx, scalr.AgentPoolCreateOptions{ - Name: scalr.String(name), + Name: ptr(name), Account: &scalr.Account{ID: defaultAccount}, }) @@ -187,7 +131,7 @@ func createPool(t *testing.T) scalr.AgentPool { } func testAccCheckScalrAgentPoolTokenDestroy(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) for _, rs := range s.RootModule().Resources { if rs.Type != "scalr_agent_pool_token" { @@ -215,14 +159,6 @@ resource "scalr_agent_pool_token" "test" { }`, pool.ID) } -func testAccScalrAgentPoolTokenChangedOutside(pool scalr.AgentPool) string { - return fmt.Sprintf(` -resource "scalr_agent_pool_token" "test" { - description = "changed-outside-of-terraform" - agent_pool_id = "%s" -}`, pool.ID) -} - func testAccScalrAgentPoolTokenUpdate(pool scalr.AgentPool) string { return fmt.Sprintf(` resource "scalr_agent_pool_token" "test" { diff --git a/scalr/resource_scalr_environment.go b/internal/provider/resource_scalr_environment.go similarity index 97% rename from scalr/resource_scalr_environment.go rename to internal/provider/resource_scalr_environment.go index f049c362..cb1350c4 100644 --- a/scalr/resource_scalr_environment.go +++ b/internal/provider/resource_scalr_environment.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "context" @@ -127,12 +127,12 @@ func resourceScalrEnvironmentCreate(ctx context.Context, d *schema.ResourceData, } options := scalr.EnvironmentCreateOptions{ - Name: scalr.String(name), + Name: ptr(name), Account: &scalr.Account{ID: accountID}, PolicyGroups: policyGroups, } if costEstimationEnabled, ok := d.GetOkExists("cost_estimation_enabled"); ok { //nolint:staticcheck - options.CostEstimationEnabled = scalr.Bool(costEstimationEnabled.(bool)) + options.CostEstimationEnabled = ptr(costEstimationEnabled.(bool)) } if defaultProviderConfigurationsI, ok := d.GetOk("default_provider_configurations"); ok { defaultProviderConfigurations := defaultProviderConfigurationsI.(*schema.Set).List() @@ -231,11 +231,11 @@ func resourceScalrEnvironmentUpdate(ctx context.Context, d *schema.ResourceData, // Create a new options struct. options := scalr.EnvironmentUpdateOptions{ - Name: scalr.String(d.Get("name").(string)), + Name: ptr(d.Get("name").(string)), PolicyGroups: policyGroups, } if costEstimationEnabled, ok := d.GetOkExists("cost_estimation_enabled"); ok { //nolint:staticcheck - options.CostEstimationEnabled = scalr.Bool(costEstimationEnabled.(bool)) + options.CostEstimationEnabled = ptr(costEstimationEnabled.(bool)) } if defaultProviderConfigurationsI, ok := d.GetOk("default_provider_configurations"); ok { diff --git a/scalr/resource_scalr_environment_test.go b/internal/provider/resource_scalr_environment_test.go similarity index 91% rename from scalr/resource_scalr_environment_test.go rename to internal/provider/resource_scalr_environment_test.go index 7643e17e..962db8bf 100644 --- a/scalr/resource_scalr_environment_test.go +++ b/internal/provider/resource_scalr_environment_test.go @@ -1,11 +1,11 @@ -package scalr +package provider import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/scalr/go-scalr" ) @@ -14,9 +14,9 @@ func TestAccEnvironment_basic(t *testing.T) { rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrEnvironmentDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrEnvironmentDestroy, Steps: []resource.TestStep{ { Config: testAccEnvironmentConfig(rInt), @@ -42,9 +42,9 @@ func TestAccEnvironment_update(t *testing.T) { rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrEnvironmentDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrEnvironmentDestroy, Steps: []resource.TestStep{ { Config: testAccEnvironmentConfig(rInt), @@ -79,9 +79,9 @@ func TestAccEnvironmentWithProviderConfigurations_update(t *testing.T) { rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrEnvironmentDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrEnvironmentDestroy, Steps: []resource.TestStep{ { Config: testAccEnvironmentWithProviderConfigurationsConfig(rInt), @@ -109,7 +109,7 @@ func TestAccEnvironmentWithProviderConfigurations_update(t *testing.T) { } func testAccCheckScalrEnvironmentDestroy(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) for _, rs := range s.RootModule().Resources { if rs.Type != "scalr_environment" { @@ -131,7 +131,7 @@ func testAccCheckScalrEnvironmentDestroy(s *terraform.State) error { func testAccCheckScalrEnvironmentExists(n string, environment *scalr.Environment) resource.TestCheckFunc { return func(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) rs, ok := s.RootModule().Resources[n] if !ok { @@ -185,7 +185,7 @@ func testAccCheckScalrEnvironmentAttributesUpdate(environment *scalr.Environment func testAccCheckScalrEnvironmentProviderConfigurations(environment *scalr.Environment) resource.TestCheckFunc { return func(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) if len(environment.DefaultProviderConfigurations) != 1 { return fmt.Errorf("Bad default provider configurations: %v", environment.DefaultProviderConfigurations) @@ -202,7 +202,7 @@ func testAccCheckScalrEnvironmentProviderConfigurations(environment *scalr.Envir } func testAccCheckScalrEnvironmentProviderConfigurationsUpdate(environment *scalr.Environment) resource.TestCheckFunc { return func(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) if len(environment.DefaultProviderConfigurations) != 1 { return fmt.Errorf("Bad default provider configurations: %v", environment.DefaultProviderConfigurations) diff --git a/scalr/resource_scalr_event_bridge_integration.go b/internal/provider/resource_scalr_event_bridge_integration.go similarity index 99% rename from scalr/resource_scalr_event_bridge_integration.go rename to internal/provider/resource_scalr_event_bridge_integration.go index 65a73014..5a1982f7 100644 --- a/scalr/resource_scalr_event_bridge_integration.go +++ b/internal/provider/resource_scalr_event_bridge_integration.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "context" diff --git a/scalr/resource_scalr_event_bridge_integration_test.go b/internal/provider/resource_scalr_event_bridge_integration_test.go similarity index 88% rename from scalr/resource_scalr_event_bridge_integration_test.go rename to internal/provider/resource_scalr_event_bridge_integration_test.go index 11152287..bd78640c 100644 --- a/scalr/resource_scalr_event_bridge_integration_test.go +++ b/internal/provider/resource_scalr_event_bridge_integration_test.go @@ -1,11 +1,11 @@ -package scalr +package provider import ( "fmt" "os" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func TestAccEventBridgeIntegration_basic(t *testing.T) { @@ -15,8 +15,8 @@ func TestAccEventBridgeIntegration_basic(t *testing.T) { t.Skip("Please set AWS_EVENT_BRIDGE_ACCOUNT_ID, AWS_EVENT_BRIDGE_REGION env variables to run this test.") } resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: testAccScalrEventBridgeIntegrationConfig(AWSAccountId, region), diff --git a/scalr/resource_scalr_iam_team.go b/internal/provider/resource_scalr_iam_team.go similarity index 97% rename from scalr/resource_scalr_iam_team.go rename to internal/provider/resource_scalr_iam_team.go index ae4e6b60..c88ef362 100644 --- a/scalr/resource_scalr_iam_team.go +++ b/internal/provider/resource_scalr_iam_team.go @@ -1,12 +1,13 @@ -package scalr +package provider import ( "context" "errors" "fmt" - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "log" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/scalr/go-scalr" ) @@ -94,7 +95,7 @@ func resourceScalrIamTeamCreate(ctx context.Context, d *schema.ResourceData, met // Optional attributes if desc, ok := d.GetOk("description"); ok { - opts.Description = scalr.String(desc.(string)) + opts.Description = ptr(desc.(string)) } if idpID, ok := d.GetOk("identity_provider_id"); ok { opts.IdentityProvider = &scalr.IdentityProvider{ID: idpID.(string)} @@ -158,8 +159,8 @@ func resourceScalrIamTeamUpdate(ctx context.Context, d *schema.ResourceData, met } opts := scalr.TeamUpdateOptions{ - Name: scalr.String(name), - Description: scalr.String(desc), + Name: ptr(name), + Description: ptr(desc), Users: users, } diff --git a/scalr/resource_scalr_iam_team_test.go b/internal/provider/resource_scalr_iam_team_test.go similarity index 57% rename from scalr/resource_scalr_iam_team_test.go rename to internal/provider/resource_scalr_iam_team_test.go index bab8602c..535f2ee5 100644 --- a/scalr/resource_scalr_iam_team_test.go +++ b/internal/provider/resource_scalr_iam_team_test.go @@ -1,14 +1,12 @@ -package scalr +package provider import ( - "context" "fmt" - "log" "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/scalr/go-scalr" ) @@ -17,9 +15,9 @@ func TestAccScalrIamTeam_basic(t *testing.T) { team := &scalr.Team{} resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrIamTeamDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrIamTeamDestroy, Steps: []resource.TestStep{ { Config: testAccScalrIamTeamBasic(rInt), @@ -39,52 +37,14 @@ func TestAccScalrIamTeam_basic(t *testing.T) { }) } -func TestAccScalrIamTeam_renamed(t *testing.T) { - rInt := GetRandomInteger() - team := &scalr.Team{} - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrIamTeamDestroy, - Steps: []resource.TestStep{ - { - Config: testAccScalrIamTeamBasic(rInt), - Check: resource.ComposeTestCheckFunc( - testAccCheckScalrIamTeamExists("scalr_iam_team.test", team), - resource.TestCheckResourceAttr( - "scalr_iam_team.test", - "name", - fmt.Sprintf("test-team-%d", rInt), - ), - resource.TestCheckResourceAttr("scalr_iam_team.test", "description", "Test team"), - resource.TestCheckResourceAttr("scalr_iam_team.test", "account_id", defaultAccount), - resource.TestCheckResourceAttr("scalr_iam_team.test", "users.0", testUser), - ), - }, - { - PreConfig: testAccCheckScalrIamTeamRename(team), - Config: testAccScalrIamTeamRenamed(), - PlanOnly: true, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("scalr_iam_team.test", "name", "renamed-outside-of-terraform"), - resource.TestCheckResourceAttr("scalr_iam_team.test", "description", "Test team"), - resource.TestCheckResourceAttr("scalr_iam_team.test", "account_id", defaultAccount), - resource.TestCheckResourceAttr("scalr_iam_team.test", "users.0", testUser), - ), - }, - }, - }) -} - func TestAccScalrIamTeam_update(t *testing.T) { rInt := GetRandomInteger() team := &scalr.Team{} resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrIamTeamDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrIamTeamDestroy, Steps: []resource.TestStep{ { Config: testAccScalrIamTeamBasic(rInt), @@ -122,9 +82,9 @@ func TestAccScalrIamTeam_import(t *testing.T) { rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrIamTeamDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrIamTeamDestroy, Steps: []resource.TestStep{ { Config: testAccScalrIamTeamBasic(rInt), @@ -140,7 +100,7 @@ func TestAccScalrIamTeam_import(t *testing.T) { func testAccCheckScalrIamTeamExists(resId string, team *scalr.Team) resource.TestCheckFunc { return func(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) rs, ok := s.RootModule().Resources[resId] if !ok { @@ -162,34 +122,8 @@ func testAccCheckScalrIamTeamExists(resId string, team *scalr.Team) resource.Tes } } -func testAccCheckScalrIamTeamRename(team *scalr.Team) func() { - return func() { - scalrClient := testAccProvider.Meta().(*scalr.Client) - - t, err := scalrClient.Teams.Read(ctx, team.ID) - if err != nil { - log.Fatalf("Error retrieving team: %v", err) - } - - t, err = scalrClient.Teams.Update( - context.Background(), - team.ID, - scalr.TeamUpdateOptions{ - Name: scalr.String("renamed-outside-of-terraform"), - Users: t.Users, - }, - ) - if err != nil { - log.Fatalf("Could not rename team outside of terraform: %v", err) - } - if t.Name != "renamed-outside-of-terraform" { - log.Fatalf("Failed to rename the team outside of terraform: %v", err) - } - } -} - func testAccCheckScalrIamTeamDestroy(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) for _, rs := range s.RootModule().Resources { if rs.Type != "scalr_iam_team" { @@ -219,16 +153,6 @@ resource "scalr_iam_team" "test" { }`, rInt, defaultAccount, testUser) } -func testAccScalrIamTeamRenamed() string { - return fmt.Sprintf(` -resource "scalr_iam_team" "test" { - name = "renamed-outside-of-terraform" - description = "Test team" - account_id = "%s" - users = ["%s"] -}`, defaultAccount, testUser) -} - func testAccScalrIamTeamUpdate() string { return fmt.Sprintf(` resource "scalr_iam_team" "test" { diff --git a/scalr/resource_scalr_module.go b/internal/provider/resource_scalr_module.go similarity index 97% rename from scalr/resource_scalr_module.go rename to internal/provider/resource_scalr_module.go index 6f607ddf..df602eed 100644 --- a/scalr/resource_scalr_module.go +++ b/internal/provider/resource_scalr_module.go @@ -1,11 +1,12 @@ -package scalr +package provider import ( "context" "errors" - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "log" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/scalr/go-scalr" ) @@ -99,13 +100,13 @@ func resourceScalrModuleCreate(ctx context.Context, d *schema.ResourceData, meta vcsRepo := d.Get("vcs_repo").([]interface{})[0].(map[string]interface{}) vcsOpt := &scalr.ModuleVCSRepo{ - Identifier: *scalr.String(vcsRepo["identifier"].(string)), + Identifier: vcsRepo["identifier"].(string), } if path, ok := vcsRepo["path"].(string); ok && path != "" { - vcsOpt.Path = scalr.String(path) + vcsOpt.Path = ptr(path) } if prefix, ok := vcsRepo["tag_prefix"].(string); ok && prefix != "" { - vcsOpt.TagPrefix = scalr.String(prefix) + vcsOpt.TagPrefix = ptr(prefix) } opt := scalr.ModuleCreateOptions{ diff --git a/scalr/resource_scalr_module_test.go b/internal/provider/resource_scalr_module_test.go similarity index 90% rename from scalr/resource_scalr_module_test.go rename to internal/provider/resource_scalr_module_test.go index 23d3fa5b..6bcddc36 100644 --- a/scalr/resource_scalr_module_test.go +++ b/internal/provider/resource_scalr_module_test.go @@ -1,12 +1,12 @@ -package scalr +package provider import ( "fmt" "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/scalr/go-scalr" ) @@ -17,8 +17,8 @@ func TestAccScalrModule_basic(t *testing.T) { t.Skip("Working on personal token but not working with github action token.") testVcsAccGithubTokenPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrModuleDestroy, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrModuleDestroy, Steps: []resource.TestStep{ { Config: testAccScalrModulesOnAllScopes(), @@ -68,8 +68,8 @@ func TestAccScalrModule_import(t *testing.T) { PreCheck: func() { testVcsAccGithubTokenPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrModuleDestroy, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrModuleDestroy, Steps: []resource.TestStep{ { Config: testAccScalrModule(), @@ -85,7 +85,7 @@ func TestAccScalrModule_import(t *testing.T) { func testAccCheckScalrModuleExists(moduleId string, module *scalr.Module) resource.TestCheckFunc { return func(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) rs, ok := s.RootModule().Resources[moduleId] if !ok { @@ -109,7 +109,7 @@ func testAccCheckScalrModuleExists(moduleId string, module *scalr.Module) resour } func testAccCheckScalrModuleDestroy(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) for _, rs := range s.RootModule().Resources { if rs.Type != "scalr_module" { diff --git a/scalr/resource_scalr_policy_group.go b/internal/provider/resource_scalr_policy_group.go similarity index 94% rename from scalr/resource_scalr_policy_group.go rename to internal/provider/resource_scalr_policy_group.go index 01d88ae4..19823163 100644 --- a/scalr/resource_scalr_policy_group.go +++ b/internal/provider/resource_scalr_policy_group.go @@ -1,12 +1,13 @@ -package scalr +package provider import ( "context" "errors" + "log" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/scalr/go-scalr" - "log" ) func resourceScalrPolicyGroup() *schema.Resource { @@ -128,28 +129,28 @@ func resourceScalrPolicyGroupCreate(ctx context.Context, d *schema.ResourceData, vcsRepo := d.Get("vcs_repo").([]interface{})[0].(map[string]interface{}) vcsOpt := &scalr.PolicyGroupVCSRepoOptions{ - Identifier: scalr.String(vcsRepo["identifier"].(string)), + Identifier: ptr(vcsRepo["identifier"].(string)), } if branch, ok := vcsRepo["branch"].(string); ok && branch != "" { - vcsOpt.Branch = scalr.String(branch) + vcsOpt.Branch = ptr(branch) } if path, ok := vcsRepo["path"].(string); ok && path != "" { - vcsOpt.Path = scalr.String(path) + vcsOpt.Path = ptr(path) } opts := scalr.PolicyGroupCreateOptions{ - Name: scalr.String(name), + Name: ptr(name), VCSRepo: vcsOpt, Account: &scalr.Account{ID: accountID}, VcsProvider: &scalr.VcsProvider{ID: vcsProviderID}, - IsEnforced: scalr.Bool(false), + IsEnforced: ptr(false), } environments := make([]*scalr.Environment, 0) if environmentsI, ok := d.GetOk("environments"); ok { environmentsIDs := environmentsI.([]interface{}) if (len(environmentsIDs) == 1) && environmentsIDs[0].(string) == "*" { - opts.IsEnforced = scalr.Bool(true) + opts.IsEnforced = ptr(true) } else if len(environmentsIDs) > 0 { for _, env := range environmentsIDs { if env.(string) == "*" { @@ -164,7 +165,7 @@ func resourceScalrPolicyGroupCreate(ctx context.Context, d *schema.ResourceData, // Optional attributes if opaVersion, ok := d.GetOk("opa_version"); ok { - opts.OpaVersion = scalr.String(opaVersion.(string)) + opts.OpaVersion = ptr(opaVersion.(string)) } pg, err := scalrClient.PolicyGroups.Create(ctx, opts) @@ -263,30 +264,30 @@ func resourceScalrPolicyGroupUpdate(ctx context.Context, d *schema.ResourceData, vcsRepo := d.Get("vcs_repo").([]interface{})[0].(map[string]interface{}) vcsOpt := &scalr.PolicyGroupVCSRepoOptions{ - Identifier: scalr.String(vcsRepo["identifier"].(string)), + Identifier: ptr(vcsRepo["identifier"].(string)), } if branch, ok := vcsRepo["branch"].(string); ok && branch != "" { - vcsOpt.Branch = scalr.String(branch) + vcsOpt.Branch = ptr(branch) } if path, ok := vcsRepo["path"].(string); ok && path != "" { - vcsOpt.Path = scalr.String(path) + vcsOpt.Path = ptr(path) } opts := scalr.PolicyGroupUpdateOptions{ - Name: scalr.String(name), + Name: ptr(name), VCSRepo: vcsOpt, VcsProvider: &scalr.VcsProvider{ID: vcsProviderID}, - IsEnforced: scalr.Bool(false), + IsEnforced: ptr(false), } if opaVersion, ok := d.GetOk("opa_version"); ok { - opts.OpaVersion = scalr.String(opaVersion.(string)) + opts.OpaVersion = ptr(opaVersion.(string)) } environments := make([]*scalr.Environment, 0) if environmentsI, ok := d.GetOk("environments"); ok { environmentsIDs := environmentsI.([]interface{}) if (len(environmentsIDs) == 1) && environmentsIDs[0].(string) == "*" { - opts.IsEnforced = scalr.Bool(true) + opts.IsEnforced = ptr(true) } else if len(environmentsIDs) > 0 { for _, env := range environmentsIDs { if env.(string) == "*" { diff --git a/scalr/resource_scalr_policy_group_linkage.go b/internal/provider/resource_scalr_policy_group_linkage.go similarity index 99% rename from scalr/resource_scalr_policy_group_linkage.go rename to internal/provider/resource_scalr_policy_group_linkage.go index 3d2de885..d0cea965 100644 --- a/scalr/resource_scalr_policy_group_linkage.go +++ b/internal/provider/resource_scalr_policy_group_linkage.go @@ -1,13 +1,14 @@ -package scalr +package provider import ( "context" "errors" "fmt" - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "log" "strings" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/scalr/go-scalr" ) diff --git a/scalr/resource_scalr_policy_group_linkage_test.go b/internal/provider/resource_scalr_policy_group_linkage_test.go similarity index 86% rename from scalr/resource_scalr_policy_group_linkage_test.go rename to internal/provider/resource_scalr_policy_group_linkage_test.go index 14038dc1..6aacb36f 100644 --- a/scalr/resource_scalr_policy_group_linkage_test.go +++ b/internal/provider/resource_scalr_policy_group_linkage_test.go @@ -1,11 +1,11 @@ -package scalr +package provider import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/scalr/go-scalr" ) @@ -20,8 +20,8 @@ func TestAccPolicyGroupLinkage_basic(t *testing.T) { t.Skip("Works with personal token but does not work with github action token.") testVcsAccGithubTokenPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckPolicyGroupLinkageDestroy, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckPolicyGroupLinkageDestroy, Steps: []resource.TestStep{ { Config: testAccPolicyGroupLinkageBasicConfig(rInt), @@ -56,8 +56,8 @@ func TestAccPolicyGroupLinkage_import(t *testing.T) { t.Skip("Works with personal token but does not work with github action token.") testVcsAccGithubTokenPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckPolicyGroupLinkageDestroy, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckPolicyGroupLinkageDestroy, Steps: []resource.TestStep{ { Config: testAccPolicyGroupLinkageBasicConfig(rInt), @@ -77,7 +77,7 @@ func testAccCheckPolicyGroupLinkageExists( environment *scalr.Environment, ) resource.TestCheckFunc { return func(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) rs, ok := s.RootModule().Resources[resID] if !ok { @@ -101,7 +101,7 @@ func testAccCheckPolicyGroupLinkageExists( } func testAccCheckPolicyGroupLinkageDestroy(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) for _, rs := range s.RootModule().Resources { if rs.Type != "scalr_policy_group_linkage" { diff --git a/scalr/resource_scalr_policy_group_test.go b/internal/provider/resource_scalr_policy_group_test.go similarity index 92% rename from scalr/resource_scalr_policy_group_test.go rename to internal/provider/resource_scalr_policy_group_test.go index 5b2ab247..c81f81b9 100644 --- a/scalr/resource_scalr_policy_group_test.go +++ b/internal/provider/resource_scalr_policy_group_test.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "context" @@ -6,8 +6,8 @@ import ( "log" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/scalr/go-scalr" ) @@ -25,8 +25,8 @@ func TestAccPolicyGroup_basic(t *testing.T) { t.Skip("Works with personal token but does not work with github action token.") testVcsAccGithubTokenPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckPolicyGroupDestroy, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckPolicyGroupDestroy, Steps: []resource.TestStep{ { Config: testAccPolicyGroupBasicConfig(rInt), @@ -78,8 +78,8 @@ func TestAccPolicyGroup_update(t *testing.T) { t.Skip("Works with personal token but does not work with github action token.") testVcsAccGithubTokenPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckPolicyGroupDestroy, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckPolicyGroupDestroy, Steps: []resource.TestStep{ { Config: testAccPolicyGroupBasicConfig(rInt), @@ -169,8 +169,8 @@ func TestAccPolicyGroup_renamed(t *testing.T) { t.Skip("Works with personal token but does not work with github action token.") testVcsAccGithubTokenPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckPolicyGroupDestroy, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckPolicyGroupDestroy, Steps: []resource.TestStep{ { Config: testAccPolicyGroupBasicConfig(rInt), @@ -260,8 +260,8 @@ func TestAccPolicyGroup_import(t *testing.T) { t.Skip("Works with personal token but does not work with github action token.") testVcsAccGithubTokenPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckPolicyGroupDestroy, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckPolicyGroupDestroy, Steps: []resource.TestStep{ { Config: testAccPolicyGroupBasicConfig(rInt), @@ -277,7 +277,7 @@ func TestAccPolicyGroup_import(t *testing.T) { func testAccCheckPolicyGroupExists(resID string, policyGroup *scalr.PolicyGroup) resource.TestCheckFunc { return func(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) rs, ok := s.RootModule().Resources[resID] if !ok { @@ -299,7 +299,7 @@ func testAccCheckPolicyGroupExists(resID string, policyGroup *scalr.PolicyGroup) } func testAccCheckPolicyGroupDestroy(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) for _, rs := range s.RootModule().Resources { if rs.Type != "scalr_policy_group" { @@ -321,12 +321,12 @@ func testAccCheckPolicyGroupDestroy(s *terraform.State) error { func testAccCheckPolicyGroupRename(policyGroup *scalr.PolicyGroup) func() { return func() { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) _, err := scalrClient.PolicyGroups.Update( context.Background(), policyGroup.ID, - scalr.PolicyGroupUpdateOptions{Name: scalr.String("renamed-outside-of-terraform")}, + scalr.PolicyGroupUpdateOptions{Name: ptr("renamed-outside-of-terraform")}, ) if err != nil { log.Fatalf("Could not rename policy group outside of terraform: %v", err) diff --git a/scalr/resource_scalr_provider_configuration.go b/internal/provider/resource_scalr_provider_configuration.go similarity index 87% rename from scalr/resource_scalr_provider_configuration.go rename to internal/provider/resource_scalr_provider_configuration.go index dbebe7e9..47962a7b 100644 --- a/scalr/resource_scalr_provider_configuration.go +++ b/internal/provider/resource_scalr_provider_configuration.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "context" @@ -299,9 +299,9 @@ func resourceScalrProviderConfigurationCreate(ctx context.Context, d *schema.Res accountID := d.Get("account_id").(string) configurationOptions := scalr.ProviderConfigurationCreateOptions{ - Name: scalr.String(name), + Name: ptr(name), Account: &scalr.Account{ID: accountID}, - ExportShellVariables: scalr.Bool(d.Get("export_shell_variables").(bool)), + ExportShellVariables: ptr(d.Get("export_shell_variables").(bool)), } if owners, ok := d.GetOk("owners"); ok { @@ -315,7 +315,7 @@ func resourceScalrProviderConfigurationCreate(ctx context.Context, d *schema.Res if environmentsI, ok := d.GetOk("environments"); ok { environments := environmentsI.(*schema.Set).List() if (len(environments) == 1) && (environments[0].(string) == "*") { - configurationOptions.IsShared = scalr.Bool(true) + configurationOptions.IsShared = ptr(true) } else if len(environments) > 0 { environmentValues := make([]*scalr.Environment, 0) for _, env := range environments { @@ -328,10 +328,10 @@ func resourceScalrProviderConfigurationCreate(ctx context.Context, d *schema.Res var createArgumentOptions []scalr.ProviderConfigurationParameterCreateOptions if _, ok := d.GetOk("aws"); ok { - configurationOptions.ProviderName = scalr.String("aws") + configurationOptions.ProviderName = ptr("aws") - configurationOptions.AwsAccountType = scalr.String(d.Get("aws.0.account_type").(string)) - configurationOptions.AwsCredentialsType = scalr.String(d.Get("aws.0.credentials_type").(string)) + configurationOptions.AwsAccountType = ptr(d.Get("aws.0.account_type").(string)) + configurationOptions.AwsCredentialsType = ptr(d.Get("aws.0.credentials_type").(string)) accessKeyIdI, accessKeyIdExists := d.GetOk("aws.0.access_key") accessKeyIdExists = accessKeyIdExists && len(accessKeyIdI.(string)) > 0 @@ -339,18 +339,18 @@ func resourceScalrProviderConfigurationCreate(ctx context.Context, d *schema.Res accessSecretKeyExists = accessSecretKeyExists && len(accessSecretKeyI.(string)) > 0 if accessKeyIdExists && accessSecretKeyExists { - configurationOptions.AwsAccessKey = scalr.String(accessKeyIdI.(string)) - configurationOptions.AwsSecretKey = scalr.String(accessSecretKeyI.(string)) + configurationOptions.AwsAccessKey = ptr(accessKeyIdI.(string)) + configurationOptions.AwsSecretKey = ptr(accessSecretKeyI.(string)) } else if accessKeyIdExists || accessSecretKeyExists { return diag.Errorf("'access_key' and 'secret_key' fields can be used only together") } if *configurationOptions.AwsCredentialsType == "role_delegation" { - configurationOptions.AwsTrustedEntityType = scalr.String(d.Get("aws.0.trusted_entity_type").(string)) - configurationOptions.AwsRoleArn = scalr.String(d.Get("aws.0.role_arn").(string)) + configurationOptions.AwsTrustedEntityType = ptr(d.Get("aws.0.trusted_entity_type").(string)) + configurationOptions.AwsRoleArn = ptr(d.Get("aws.0.role_arn").(string)) externalIdI, externalIdExists := d.GetOk("aws.0.external_id") if externalIdExists { - configurationOptions.AwsExternalId = scalr.String(externalIdI.(string)) + configurationOptions.AwsExternalId = ptr(externalIdI.(string)) } if len(*configurationOptions.AwsTrustedEntityType) == 0 { return diag.Errorf("'trusted_entity_type' field is required for 'role_delegation' credentials type of aws provider configuration") @@ -362,8 +362,8 @@ func resourceScalrProviderConfigurationCreate(ctx context.Context, d *schema.Res return diag.Errorf("'external_id' field is required for 'role_delegation' credentials type with 'aws_account' trusted entity type of aws provider configuration") } } else if *configurationOptions.AwsCredentialsType == "oidc" { - configurationOptions.AwsRoleArn = scalr.String(d.Get("aws.0.role_arn").(string)) - configurationOptions.AwsAudience = scalr.String(d.Get("aws.0.audience").(string)) + configurationOptions.AwsRoleArn = ptr(d.Get("aws.0.role_arn").(string)) + configurationOptions.AwsAudience = ptr(d.Get("aws.0.audience").(string)) if len(*configurationOptions.AwsRoleArn) == 0 { return diag.Errorf("'role_arn' field is required for 'oidc' credentials type of aws provider configuration") } @@ -377,9 +377,9 @@ func resourceScalrProviderConfigurationCreate(ctx context.Context, d *schema.Res } } else if _, ok := d.GetOk("google"); ok { - configurationOptions.ProviderName = scalr.String("google") - configurationOptions.GoogleAuthType = scalr.String(d.Get("google.0.auth_type").(string)) - configurationOptions.GoogleUseDefaultProject = scalr.Bool(d.Get("google.0.use_default_project").(bool)) + configurationOptions.ProviderName = ptr("google") + configurationOptions.GoogleAuthType = ptr(d.Get("google.0.auth_type").(string)) + configurationOptions.GoogleUseDefaultProject = ptr(d.Get("google.0.use_default_project").(bool)) googleCredentials, googleCredentialsExists := d.GetOk("google.0.credentials") googleCredentialsExists = googleCredentialsExists && len(googleCredentials.(string)) > 0 @@ -395,7 +395,7 @@ func resourceScalrProviderConfigurationCreate(ctx context.Context, d *schema.Res if serviceAccountEmailExists || workloadProviderNameExists { return diag.Errorf("'service_account_email' and 'workload_provider_name' fields of google provider configuration can be used only with 'oidc' auth type") } - configurationOptions.GoogleCredentials = scalr.String(googleCredentials.(string)) + configurationOptions.GoogleCredentials = ptr(googleCredentials.(string)) } else if *configurationOptions.GoogleAuthType == "oidc" { if !serviceAccountEmailExists || !workloadProviderNameExists { return diag.Errorf("'service_account_email' and 'workload_provider_name' fields are required for 'oidc' auth type of google provider configuration") @@ -403,21 +403,21 @@ func resourceScalrProviderConfigurationCreate(ctx context.Context, d *schema.Res if googleCredentialsExists { return diag.Errorf("'credentials' field of google provider configuration can be used only with 'service-account-key' auth type") } - configurationOptions.GoogleServiceAccountEmail = scalr.String(serviceAccountEmail.(string)) - configurationOptions.GoogleWorkloadProviderName = scalr.String(workloadProviderName.(string)) + configurationOptions.GoogleServiceAccountEmail = ptr(serviceAccountEmail.(string)) + configurationOptions.GoogleWorkloadProviderName = ptr(workloadProviderName.(string)) } else { return diag.Errorf("unknown google provider configuration auth type: '%s', allowed: 'service-account-key', 'oidc'", *configurationOptions.GoogleAuthType) } if v, ok := d.GetOk("google.0.project"); ok { - configurationOptions.GoogleProject = scalr.String(v.(string)) + configurationOptions.GoogleProject = ptr(v.(string)) } } else if _, ok := d.GetOk("azurerm"); ok { - configurationOptions.ProviderName = scalr.String("azurerm") - configurationOptions.AzurermClientId = scalr.String(d.Get("azurerm.0.client_id").(string)) - configurationOptions.AzurermSubscriptionId = scalr.String(d.Get("azurerm.0.subscription_id").(string)) - configurationOptions.AzurermTenantId = scalr.String(d.Get("azurerm.0.tenant_id").(string)) + configurationOptions.ProviderName = ptr("azurerm") + configurationOptions.AzurermClientId = ptr(d.Get("azurerm.0.client_id").(string)) + configurationOptions.AzurermSubscriptionId = ptr(d.Get("azurerm.0.subscription_id").(string)) + configurationOptions.AzurermTenantId = ptr(d.Get("azurerm.0.tenant_id").(string)) authType := d.Get("azurerm.0.auth_type").(string) if authType == "oidc" { @@ -425,43 +425,43 @@ func resourceScalrProviderConfigurationCreate(ctx context.Context, d *schema.Res if !audienceExists { return diag.Errorf("'audience' field is required for 'oidc' auth type of azurerm provider configuration") } - configurationOptions.AzurermAudience = scalr.String(audience.(string)) - configurationOptions.AzurermAuthType = scalr.String("oidc") + configurationOptions.AzurermAudience = ptr(audience.(string)) + configurationOptions.AzurermAuthType = ptr("oidc") } else if authType == "client-secrets" { client_secret, secretExists := d.GetOk("azurerm.0.client_secret") if !secretExists { return diag.Errorf("'client_secret' field is required for 'client-secrets' auth type of azurerm provider configuration") } - configurationOptions.AzurermClientSecret = scalr.String(client_secret.(string)) - configurationOptions.AzurermAuthType = scalr.String("client-secrets") + configurationOptions.AzurermClientSecret = ptr(client_secret.(string)) + configurationOptions.AzurermAuthType = ptr("client-secrets") } else { return diag.Errorf("unknown azurerm provider configuration auth type: '%s', allowed: 'client-secrets', 'oidc'", authType) } } else if _, ok := d.GetOk("scalr"); ok { - configurationOptions.ProviderName = scalr.String("scalr") - configurationOptions.ScalrHostname = scalr.String(d.Get("scalr.0.hostname").(string)) - configurationOptions.ScalrToken = scalr.String(d.Get("scalr.0.token").(string)) + configurationOptions.ProviderName = ptr("scalr") + configurationOptions.ScalrHostname = ptr(d.Get("scalr.0.hostname").(string)) + configurationOptions.ScalrToken = ptr(d.Get("scalr.0.token").(string)) } else if v, ok := d.GetOk("custom"); ok { custom := v.([]interface{})[0].(map[string]interface{}) - configurationOptions.ProviderName = scalr.String(custom["provider_name"].(string)) - configurationOptions.IsCustom = scalr.Bool(true) + configurationOptions.ProviderName = ptr(custom["provider_name"].(string)) + configurationOptions.IsCustom = ptr(true) for _, v := range custom["argument"].(*schema.Set).List() { argument := v.(map[string]interface{}) createArgumentOption := scalr.ProviderConfigurationParameterCreateOptions{ - Key: scalr.String(argument["name"].(string)), + Key: ptr(argument["name"].(string)), } if v, ok := argument["value"]; ok { - createArgumentOption.Value = scalr.String(v.(string)) + createArgumentOption.Value = ptr(v.(string)) } if v, ok := argument["description"]; ok { - createArgumentOption.Description = scalr.String(v.(string)) + createArgumentOption.Description = ptr(v.(string)) } if v, ok := argument["sensitive"]; ok { - createArgumentOption.Sensitive = scalr.Bool(v.(bool)) + createArgumentOption.Sensitive = ptr(v.(bool)) } createArgumentOptions = append(createArgumentOptions, createArgumentOption) @@ -686,16 +686,16 @@ func resourceScalrProviderConfigurationUpdate(ctx context.Context, d *schema.Res d.HasChange("environments") || d.HasChange("owners") { configurationOptions := scalr.ProviderConfigurationUpdateOptions{ - Name: scalr.String(d.Get("name").(string)), - ExportShellVariables: scalr.Bool(d.Get("export_shell_variables").(bool)), + Name: ptr(d.Get("name").(string)), + ExportShellVariables: ptr(d.Get("export_shell_variables").(bool)), } if environmentsI, ok := d.GetOk("environments"); ok { environments := environmentsI.(*schema.Set).List() if (len(environments) == 1) && (environments[0].(string) == "*") { - configurationOptions.IsShared = scalr.Bool(true) + configurationOptions.IsShared = ptr(true) configurationOptions.Environments = make([]*scalr.Environment, 0) } else { - configurationOptions.IsShared = scalr.Bool(false) + configurationOptions.IsShared = ptr(false) environmentValues := make([]*scalr.Environment, 0) for _, env := range environments { environmentValues = append(environmentValues, &scalr.Environment{ID: env.(string)}) @@ -703,13 +703,13 @@ func resourceScalrProviderConfigurationUpdate(ctx context.Context, d *schema.Res configurationOptions.Environments = environmentValues } } else { - configurationOptions.IsShared = scalr.Bool(false) + configurationOptions.IsShared = ptr(false) configurationOptions.Environments = make([]*scalr.Environment, 0) } if _, ok := d.GetOk("aws"); ok { - configurationOptions.AwsAccountType = scalr.String(d.Get("aws.0.account_type").(string)) - configurationOptions.AwsCredentialsType = scalr.String(d.Get("aws.0.credentials_type").(string)) + configurationOptions.AwsAccountType = ptr(d.Get("aws.0.account_type").(string)) + configurationOptions.AwsCredentialsType = ptr(d.Get("aws.0.credentials_type").(string)) accessKeyIdI, accessKeyIdExists := d.GetOk("aws.0.access_key") accessKeyIdExists = accessKeyIdExists && len(accessKeyIdI.(string)) > 0 @@ -717,18 +717,18 @@ func resourceScalrProviderConfigurationUpdate(ctx context.Context, d *schema.Res accessSecretKeyExists = accessSecretKeyExists && len(accessSecretKeyI.(string)) > 0 if accessKeyIdExists && accessSecretKeyExists { - configurationOptions.AwsAccessKey = scalr.String(accessKeyIdI.(string)) - configurationOptions.AwsSecretKey = scalr.String(accessSecretKeyI.(string)) + configurationOptions.AwsAccessKey = ptr(accessKeyIdI.(string)) + configurationOptions.AwsSecretKey = ptr(accessSecretKeyI.(string)) } else if accessKeyIdExists || accessSecretKeyExists { return diag.Errorf("'access_key' and 'secret_key' fields can be used only together") } if *configurationOptions.AwsCredentialsType == "role_delegation" { - configurationOptions.AwsTrustedEntityType = scalr.String(d.Get("aws.0.trusted_entity_type").(string)) - configurationOptions.AwsRoleArn = scalr.String(d.Get("aws.0.role_arn").(string)) + configurationOptions.AwsTrustedEntityType = ptr(d.Get("aws.0.trusted_entity_type").(string)) + configurationOptions.AwsRoleArn = ptr(d.Get("aws.0.role_arn").(string)) externalIdI, externalIdExists := d.GetOk("aws.0.external_id") if externalIdExists { - configurationOptions.AwsExternalId = scalr.String(externalIdI.(string)) + configurationOptions.AwsExternalId = ptr(externalIdI.(string)) } if len(*configurationOptions.AwsTrustedEntityType) == 0 { return diag.Errorf("'trusted_entity_type' field is required for 'role_delegation' credentials type of aws provider configuration") @@ -740,8 +740,8 @@ func resourceScalrProviderConfigurationUpdate(ctx context.Context, d *schema.Res return diag.Errorf("'external_id' field is required for 'role_delegation' credentials type with 'aws_account' entity type of aws provider configuration") } } else if *configurationOptions.AwsCredentialsType == "oidc" { - configurationOptions.AwsRoleArn = scalr.String(d.Get("aws.0.role_arn").(string)) - configurationOptions.AwsAudience = scalr.String(d.Get("aws.0.audience").(string)) + configurationOptions.AwsRoleArn = ptr(d.Get("aws.0.role_arn").(string)) + configurationOptions.AwsAudience = ptr(d.Get("aws.0.audience").(string)) if len(*configurationOptions.AwsRoleArn) == 0 { return diag.Errorf("'role_arn' field is required for 'oidc' credentials type of aws provider configuration") } @@ -754,9 +754,9 @@ func resourceScalrProviderConfigurationUpdate(ctx context.Context, d *schema.Res return diag.Errorf("'access_key' and 'secret_key' fields are required for 'access_keys' credentials type of aws provider configuration") } } else if _, ok := d.GetOk("google"); ok { - configurationOptions.GoogleAuthType = scalr.String(d.Get("google.0.auth_type").(string)) + configurationOptions.GoogleAuthType = ptr(d.Get("google.0.auth_type").(string)) - configurationOptions.GoogleUseDefaultProject = scalr.Bool(d.Get("google.0.use_default_project").(bool)) + configurationOptions.GoogleUseDefaultProject = ptr(d.Get("google.0.use_default_project").(bool)) googleCredentials, googleCredentialsExists := d.GetOk("google.0.credentials") googleCredentialsExists = googleCredentialsExists && len(googleCredentials.(string)) > 0 serviceAccountEmail, serviceAccountEmailExists := d.GetOk("google.0.service_account_email") @@ -771,7 +771,7 @@ func resourceScalrProviderConfigurationUpdate(ctx context.Context, d *schema.Res if serviceAccountEmailExists || workloadProviderNameExists { return diag.Errorf("'service_account_email' and 'workload_provider_name' fields of google provider configuration can be used only with 'oidc' auth type") } - configurationOptions.GoogleCredentials = scalr.String(googleCredentials.(string)) + configurationOptions.GoogleCredentials = ptr(googleCredentials.(string)) } else if *configurationOptions.GoogleAuthType == "oidc" { if !serviceAccountEmailExists || !workloadProviderNameExists { return diag.Errorf("'service_account_email' and 'workload_provider_name' fields are required for 'oidc' auth type of google provider configuration") @@ -779,22 +779,22 @@ func resourceScalrProviderConfigurationUpdate(ctx context.Context, d *schema.Res if googleCredentialsExists { return diag.Errorf("'credentials' field of google provider configuration can be used only with 'service-account-key' auth type") } - configurationOptions.GoogleServiceAccountEmail = scalr.String(serviceAccountEmail.(string)) - configurationOptions.GoogleWorkloadProviderName = scalr.String(workloadProviderName.(string)) + configurationOptions.GoogleServiceAccountEmail = ptr(serviceAccountEmail.(string)) + configurationOptions.GoogleWorkloadProviderName = ptr(workloadProviderName.(string)) } else { return diag.Errorf("unknown google provider configuration auth type: '%s', allowed: 'service-account-key', 'oidc'", *configurationOptions.GoogleAuthType) } if v, ok := d.GetOk("google.0.project"); ok { - configurationOptions.GoogleProject = scalr.String(v.(string)) + configurationOptions.GoogleProject = ptr(v.(string)) } } else if _, ok := d.GetOk("scalr"); ok { - configurationOptions.ScalrHostname = scalr.String(d.Get("scalr.0.hostname").(string)) - configurationOptions.ScalrToken = scalr.String(d.Get("scalr.0.token").(string)) + configurationOptions.ScalrHostname = ptr(d.Get("scalr.0.hostname").(string)) + configurationOptions.ScalrToken = ptr(d.Get("scalr.0.token").(string)) } else if _, ok := d.GetOk("azurerm"); ok { - configurationOptions.AzurermClientId = scalr.String(d.Get("azurerm.0.client_id").(string)) - configurationOptions.AzurermSubscriptionId = scalr.String(d.Get("azurerm.0.subscription_id").(string)) - configurationOptions.AzurermTenantId = scalr.String(d.Get("azurerm.0.tenant_id").(string)) + configurationOptions.AzurermClientId = ptr(d.Get("azurerm.0.client_id").(string)) + configurationOptions.AzurermSubscriptionId = ptr(d.Get("azurerm.0.subscription_id").(string)) + configurationOptions.AzurermTenantId = ptr(d.Get("azurerm.0.tenant_id").(string)) authType := d.Get("azurerm.0.auth_type").(string) if authType == "oidc" { @@ -802,15 +802,15 @@ func resourceScalrProviderConfigurationUpdate(ctx context.Context, d *schema.Res if !audienceExists { return diag.Errorf("'audience' field is required for 'oidc' auth type of azurerm provider configuration") } - configurationOptions.AzurermAudience = scalr.String(audience.(string)) - configurationOptions.AzurermAuthType = scalr.String("oidc") + configurationOptions.AzurermAudience = ptr(audience.(string)) + configurationOptions.AzurermAuthType = ptr("oidc") } else if authType == "client-secrets" { client_secret, secretExists := d.GetOk("azurerm.0.client_secret") if !secretExists { return diag.Errorf("'client_secret' field is required for 'client-secrets' auth type of azurerm provider configuration") } - configurationOptions.AzurermClientSecret = scalr.String(client_secret.(string)) - configurationOptions.AzurermAuthType = scalr.String("client-secrets") + configurationOptions.AzurermClientSecret = ptr(client_secret.(string)) + configurationOptions.AzurermAuthType = ptr("client-secrets") } else { return diag.Errorf("unknown azurerm provider configuration auth type: '%s', allowed: 'client-secrets', 'oidc'", authType) } @@ -852,16 +852,16 @@ func syncArguments(ctx context.Context, providerConfigurationId string, custom m configArgument := v.(map[string]interface{}) name := configArgument["name"].(string) parameterCreateOption := scalr.ProviderConfigurationParameterCreateOptions{ - Key: scalr.String(name), + Key: ptr(name), } if v, ok := configArgument["value"]; ok { - parameterCreateOption.Value = scalr.String(v.(string)) + parameterCreateOption.Value = ptr(v.(string)) } if v, ok := configArgument["sensitive"]; ok { - parameterCreateOption.Sensitive = scalr.Bool(v.(bool)) + parameterCreateOption.Sensitive = ptr(v.(bool)) } if v, ok := configArgument["description"]; ok { - parameterCreateOption.Description = scalr.String(v.(string)) + parameterCreateOption.Description = ptr(v.(string)) } configArgumentsCreateOptions[name] = parameterCreateOption } diff --git a/scalr/resource_scalr_provider_configuration_default.go b/internal/provider/resource_scalr_provider_configuration_default.go similarity index 99% rename from scalr/resource_scalr_provider_configuration_default.go rename to internal/provider/resource_scalr_provider_configuration_default.go index b36f4bc1..105d1b3a 100644 --- a/scalr/resource_scalr_provider_configuration_default.go +++ b/internal/provider/resource_scalr_provider_configuration_default.go @@ -1,13 +1,14 @@ -package scalr +package provider import ( "context" "errors" "fmt" - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "strings" "sync" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/scalr/go-scalr" ) diff --git a/scalr/resource_scalr_provider_configuration_default_test.go b/internal/provider/resource_scalr_provider_configuration_default_test.go similarity index 86% rename from scalr/resource_scalr_provider_configuration_default_test.go rename to internal/provider/resource_scalr_provider_configuration_default_test.go index 8454c4c1..45432f41 100644 --- a/scalr/resource_scalr_provider_configuration_default_test.go +++ b/internal/provider/resource_scalr_provider_configuration_default_test.go @@ -1,11 +1,11 @@ -package scalr +package provider import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/scalr/go-scalr" ) @@ -16,8 +16,8 @@ func TestAccProviderConfigurationDefault_basic(t *testing.T) { PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckProviderConfigurationDefaultDestroy, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckProviderConfigurationDefaultDestroy, Steps: []resource.TestStep{ { Config: testAccProviderConfigurationDefaultBasicConfig(rInt), @@ -38,8 +38,8 @@ func TestAccProviderConfigurationDefault_import(t *testing.T) { PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckProviderConfigurationDefaultDestroy, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckProviderConfigurationDefaultDestroy, Steps: []resource.TestStep{ { Config: testAccProviderConfigurationDefaultBasicConfig(rInt), @@ -62,7 +62,7 @@ func testAccCheckProviderConfigurationDefaultExists( return fmt.Errorf("Not found: %s", rn) } - client := testAccProvider.Meta().(*scalr.Client) + client := testAccProviderSDK.Meta().(*scalr.Client) providerConfigurationID := rs.Primary.Attributes["provider_configuration_id"] environmentID := rs.Primary.Attributes["environment_id"] @@ -83,7 +83,7 @@ func testAccCheckProviderConfigurationDefaultExists( } func testAccCheckProviderConfigurationDefaultDestroy(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) for _, rs := range s.RootModule().Resources { if rs.Type != "scalr_provider_configuration_default" { diff --git a/scalr/resource_scalr_provider_configuration_test.go b/internal/provider/resource_scalr_provider_configuration_test.go similarity index 95% rename from scalr/resource_scalr_provider_configuration_test.go rename to internal/provider/resource_scalr_provider_configuration_test.go index 068416e0..a7fb9b2a 100644 --- a/scalr/resource_scalr_provider_configuration_test.go +++ b/internal/provider/resource_scalr_provider_configuration_test.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "fmt" @@ -7,9 +7,9 @@ import ( "strings" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-plugin-testing/helper/acctest" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/scalr/go-scalr" "github.com/scalr/terraform-provider-scalr/internal/client" @@ -22,8 +22,8 @@ func TestAccProviderConfiguration_import(t *testing.T) { PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckProviderConfigurationResourceDestroy, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckProviderConfigurationResourceDestroy, Steps: []resource.TestStep{ { Config: testAccScalrProviderConfigurationCustomImportConfig(rName), @@ -43,9 +43,9 @@ func TestAccProviderConfiguration_custom(t *testing.T) { rNewName := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckProviderConfigurationResourceDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckProviderConfigurationResourceDestroy, Steps: []resource.TestStep{ { Config: testAccScalrProviderConfigurationCustomConfig(rName), @@ -165,9 +165,9 @@ func TestAccProviderConfiguration_aws_custom(t *testing.T) { rName := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckProviderConfigurationResourceDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckProviderConfigurationResourceDestroy, Steps: []resource.TestStep{ { Config: testAccScalrProviderConfigurationCustomConfigAws(rName), @@ -187,9 +187,9 @@ func TestAccProviderConfiguration_aws(t *testing.T) { accessKeyId, secretAccessKey, roleArn, externalId := getAwsTestingCreds(t) resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckProviderConfigurationResourceDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckProviderConfigurationResourceDestroy, Steps: []resource.TestStep{ { Config: testAccScalrProviderConfigurationAwsConfig(rName, accessKeyId, secretAccessKey, roleArn, externalId), @@ -234,9 +234,9 @@ func TestAccProviderConfiguration_scalr(t *testing.T) { rNewName := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckProviderConfigurationResourceDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckProviderConfigurationResourceDestroy, Steps: []resource.TestStep{ { Config: testAccScalrProviderConfigurationScalrConfig(rName), @@ -279,9 +279,9 @@ func TestAccProviderConfiguration_google(t *testing.T) { credentials, project := getGoogleTestingCreds(t) resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckProviderConfigurationResourceDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckProviderConfigurationResourceDestroy, Steps: []resource.TestStep{ { Config: testAccScalrProviderConfigurationGoogleConfig(rName, credentials, project), @@ -325,9 +325,9 @@ func TestAccProviderConfiguration_google_oidc(t *testing.T) { _, project := getGoogleTestingCreds(t) resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckProviderConfigurationResourceDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckProviderConfigurationResourceDestroy, Steps: []resource.TestStep{ { Config: testAccScalrProviderConfigurationGoogleOidcConfig(rName, project), @@ -372,9 +372,9 @@ func TestAccProviderConfiguration_aws_oidc(t *testing.T) { rNewName := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckProviderConfigurationResourceDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckProviderConfigurationResourceDestroy, Steps: []resource.TestStep{ { Config: testAccScalrProviderConfigurationAWSOidcConfig(rName), @@ -414,9 +414,9 @@ func TestAccProviderConfiguration_azurerm(t *testing.T) { armClientId, armClientSecret, armSubscription, armTenantId := getAzureTestingCreds(t) resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckProviderConfigurationResourceDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckProviderConfigurationResourceDestroy, Steps: []resource.TestStep{ { Config: testAccScalrProviderConfigurationAzurermConfig(rName, armClientId, armClientSecret, armSubscription, armTenantId), @@ -694,7 +694,7 @@ func testAccCheckProviderConfigurationExists(n string, providerConfiguration *sc return fmt.Errorf("Not found: %s", n) } - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) providerConfigurationResource, err := scalrClient.ProviderConfigurations.Read(ctx, rs.Primary.ID) @@ -709,7 +709,7 @@ func testAccCheckProviderConfigurationExists(n string, providerConfiguration *sc } func testAccCheckProviderConfigurationResourceDestroy(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) for _, rs := range s.RootModule().Resources { if rs.Type != "scalr_provider_configuration" { diff --git a/scalr/resource_scalr_role.go b/internal/provider/resource_scalr_role.go similarity index 96% rename from scalr/resource_scalr_role.go rename to internal/provider/resource_scalr_role.go index c633d81f..051f2d61 100644 --- a/scalr/resource_scalr_role.go +++ b/internal/provider/resource_scalr_role.go @@ -1,14 +1,15 @@ -package scalr +package provider import ( "context" "errors" "fmt" - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "log" "reflect" "sort" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/scalr/go-scalr" ) @@ -102,9 +103,9 @@ func resourceScalrRoleCreate(ctx context.Context, d *schema.ResourceData, meta i // Create a new options struct options := scalr.RoleCreateOptions{ - Name: scalr.String(name), + Name: ptr(name), Account: &scalr.Account{ID: accountID}, - Description: scalr.String(description), + Description: ptr(description), Permissions: permissions, } @@ -181,8 +182,8 @@ func resourceScalrRoleUpdate(ctx context.Context, d *schema.ResourceData, meta i // Create a new options struct options := scalr.RoleUpdateOptions{ - Name: scalr.String(d.Get("name").(string)), - Description: scalr.String(d.Get("description").(string)), + Name: ptr(d.Get("name").(string)), + Description: ptr(d.Get("description").(string)), Permissions: permissions, } diff --git a/scalr/resource_scalr_role_migrate.go b/internal/provider/resource_scalr_role_migrate.go similarity index 98% rename from scalr/resource_scalr_role_migrate.go rename to internal/provider/resource_scalr_role_migrate.go index 3c21725a..8057b6ec 100644 --- a/scalr/resource_scalr_role_migrate.go +++ b/internal/provider/resource_scalr_role_migrate.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "context" diff --git a/scalr/resource_scalr_role_migrate_test.go b/internal/provider/resource_scalr_role_migrate_test.go similarity index 99% rename from scalr/resource_scalr_role_migrate_test.go rename to internal/provider/resource_scalr_role_migrate_test.go index f19db4cc..1f8a2f93 100644 --- a/scalr/resource_scalr_role_migrate_test.go +++ b/internal/provider/resource_scalr_role_migrate_test.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "testing" diff --git a/scalr/resource_scalr_role_test.go b/internal/provider/resource_scalr_role_test.go similarity index 57% rename from scalr/resource_scalr_role_test.go rename to internal/provider/resource_scalr_role_test.go index 0f2fc3e3..2e56e3ec 100644 --- a/scalr/resource_scalr_role_test.go +++ b/internal/provider/resource_scalr_role_test.go @@ -1,14 +1,12 @@ -package scalr +package provider import ( - "context" "fmt" - "log" "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/scalr/go-scalr" ) @@ -16,9 +14,9 @@ func TestAccScalrRole_basic(t *testing.T) { role := &scalr.Role{} resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrRoleDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrRoleDestroy, Steps: []resource.TestStep{ { Config: testAccScalrRoleBasic(), @@ -36,50 +34,13 @@ func TestAccScalrRole_basic(t *testing.T) { }) } -func TestAccScalrRole_renamed(t *testing.T) { - role := &scalr.Role{} - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrRoleDestroy, - Steps: []resource.TestStep{ - { - Config: testAccScalrRoleBasic(), - Check: resource.ComposeTestCheckFunc( - testAccCheckScalrRoleExists("scalr_role.test", role), - resource.TestCheckResourceAttr("scalr_role.test", "name", "role-test"), - resource.TestCheckResourceAttr("scalr_role.test", "description", "test basic"), - resource.TestCheckResourceAttr("scalr_role.test", "is_system", "false"), - resource.TestCheckResourceAttr("scalr_role.test", "account_id", defaultAccount), - resource.TestCheckResourceAttr("scalr_role.test", "permissions.0", "*:read"), - resource.TestCheckResourceAttr("scalr_role.test", "permissions.1", "*:update"), - ), - }, - - { - PreConfig: testAccCheckScalrRoleRename(role), - Config: testAccScalrRoleRenamed(), - PlanOnly: true, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("scalr_role.test", "name", "renamed-outside-of-terraform"), - resource.TestCheckResourceAttr("scalr_role.test", "description", "test basic"), - resource.TestCheckResourceAttr("scalr_role.test", "is_system", "false"), - resource.TestCheckResourceAttr("scalr_role.test", "account_id", defaultAccount), - resource.TestCheckResourceAttr("scalr_role.test", "permissions.0", "*:read"), - resource.TestCheckResourceAttr("scalr_role.test", "permissions.1", "*:update"), - ), - }, - }, - }) -} func TestAccScalrRole_update(t *testing.T) { role := &scalr.Role{} resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrRoleDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrRoleDestroy, Steps: []resource.TestStep{ { Config: testAccScalrRoleBasic(), @@ -117,9 +78,9 @@ func TestAccScalrRole_update(t *testing.T) { func TestAccScalrRole_import(t *testing.T) { resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrRoleDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrRoleDestroy, Steps: []resource.TestStep{ { Config: testAccScalrRoleBasic(), @@ -136,7 +97,7 @@ func TestAccScalrRole_import(t *testing.T) { func testAccCheckScalrRoleExists(resId string, role *scalr.Role) resource.TestCheckFunc { return func(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) rs, ok := s.RootModule().Resources[resId] if !ok { @@ -159,33 +120,8 @@ func testAccCheckScalrRoleExists(resId string, role *scalr.Role) resource.TestCh } } -func testAccCheckScalrRoleRename(role *scalr.Role) func() { - return func() { - scalrClient := testAccProvider.Meta().(*scalr.Client) - - r, err := scalrClient.Roles.Read(ctx, role.ID) - - if err != nil { - log.Fatalf("Error retrieving role: %v", err) - } - - r, err = scalrClient.Roles.Update( - context.Background(), - r.ID, - scalr.RoleUpdateOptions{Name: scalr.String("renamed-outside-of-terraform")}, - ) - if err != nil { - log.Fatalf("Could not rename the role outside of terraform: %v", err) - } - - if r.Name != "renamed-outside-of-terraform" { - log.Fatalf("Failed to rename the role outside of terraform: %v", err) - } - } -} - func testAccCheckScalrRoleDestroy(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) for _, rs := range s.RootModule().Resources { if rs.Type != "scalr_role" { @@ -218,19 +154,6 @@ resource "scalr_role" "test" { }`, defaultAccount) } -func testAccScalrRoleRenamed() string { - return fmt.Sprintf(` -resource "scalr_role" "test" { - name = "renamed-outside-of-terraform" - description = "test basic" - account_id = "%s" - permissions = [ - "*:read", - "*:update" - ] -}`, defaultAccount) -} - func testAccScalrRoleUpdate() string { return fmt.Sprintf(` resource "scalr_role" "test" { diff --git a/scalr/resource_scalr_run_schedule_rule.go b/internal/provider/resource_scalr_run_schedule_rule.go similarity index 98% rename from scalr/resource_scalr_run_schedule_rule.go rename to internal/provider/resource_scalr_run_schedule_rule.go index 01989924..b4b24112 100644 --- a/scalr/resource_scalr_run_schedule_rule.go +++ b/internal/provider/resource_scalr_run_schedule_rule.go @@ -1,13 +1,14 @@ -package scalr +package provider import ( "context" "errors" + "log" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/scalr/go-scalr" - "log" ) func resourceScalrRunScheduleRule() *schema.Resource { @@ -99,7 +100,7 @@ func resourceScalrRunScheduleRuleUpdate(ctx context.Context, d *schema.ResourceD opts := scalr.RunScheduleRuleUpdateOptions{} if v, ok := d.GetOk("schedule"); ok { - opts.Schedule = scalr.String(v.(string)) + opts.Schedule = ptr(v.(string)) } if v, ok := d.GetOk("schedule_mode"); ok { diff --git a/scalr/resource_scalr_run_schedule_rule_test.go b/internal/provider/resource_scalr_run_schedule_rule_test.go similarity index 83% rename from scalr/resource_scalr_run_schedule_rule_test.go rename to internal/provider/resource_scalr_run_schedule_rule_test.go index 323896cf..7092eb83 100644 --- a/scalr/resource_scalr_run_schedule_rule_test.go +++ b/internal/provider/resource_scalr_run_schedule_rule_test.go @@ -1,11 +1,11 @@ -package scalr +package provider import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/scalr/go-scalr" ) @@ -13,9 +13,9 @@ func TestAccScalrRunScheduleRule_basic(t *testing.T) { rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrRunScheduleRuleDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrRunScheduleRuleDestroy, Steps: []resource.TestStep{ { Config: testAccScalrRunScheduleRuleBasic(rInt), @@ -37,9 +37,9 @@ func TestAccScalrRunScheduleRule_update(t *testing.T) { rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrRunScheduleRuleDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrRunScheduleRuleDestroy, Steps: []resource.TestStep{ { Config: testAccScalrRunScheduleRuleBasic(rInt), @@ -69,9 +69,9 @@ func TestAccScalrRunScheduleRule_import(t *testing.T) { rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrRunScheduleRuleDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrRunScheduleRuleDestroy, Steps: []resource.TestStep{ { Config: testAccScalrRunScheduleRuleBasic(rInt), @@ -96,7 +96,7 @@ func testAccCheckScalrRunScheduleRuleExists(resId string, rule *scalr.RunSchedul return fmt.Errorf("No Run Schedule Rule ID is set") } - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) r, err := scalrClient.RunScheduleRules.Read(ctx, rs.Primary.ID) if err != nil { return fmt.Errorf("Error reading run schedule rule: %v", err) @@ -109,7 +109,7 @@ func testAccCheckScalrRunScheduleRuleExists(resId string, rule *scalr.RunSchedul } func testAccCheckScalrRunScheduleRuleDestroy(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) for _, rs := range s.RootModule().Resources { if rs.Type != "scalr_run_schedule_rule" { diff --git a/scalr/resource_scalr_run_triggers.go b/internal/provider/resource_scalr_run_triggers.go similarity index 99% rename from scalr/resource_scalr_run_triggers.go rename to internal/provider/resource_scalr_run_triggers.go index 258b90b3..b9588f8c 100644 --- a/scalr/resource_scalr_run_triggers.go +++ b/internal/provider/resource_scalr_run_triggers.go @@ -1,11 +1,12 @@ -package scalr +package provider import ( "context" "errors" - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "log" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/scalr/go-scalr" ) diff --git a/scalr/resource_scalr_run_triggers_test.go b/internal/provider/resource_scalr_run_triggers_test.go similarity index 86% rename from scalr/resource_scalr_run_triggers_test.go rename to internal/provider/resource_scalr_run_triggers_test.go index 513a85be..a32916b7 100644 --- a/scalr/resource_scalr_run_triggers_test.go +++ b/internal/provider/resource_scalr_run_triggers_test.go @@ -1,11 +1,11 @@ -package scalr +package provider import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/scalr/go-scalr" ) @@ -14,9 +14,9 @@ func TestAccScalrRunTriggersDataSource_basic(t *testing.T) { rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckRunTriggerDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckRunTriggerDestroy, Steps: []resource.TestStep{ { Config: testAccRunTriggerConfig(rInt), @@ -30,7 +30,7 @@ func TestAccScalrRunTriggersDataSource_basic(t *testing.T) { } func testAccCheckRunTriggerDestroy(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) for _, rs := range s.RootModule().Resources { if rs.Type != "scalr_run_trigger" { @@ -77,7 +77,7 @@ resource "scalr_run_trigger" "foobar" { func testAccCheckRunTriggerExists(n string, runTrigger *scalr.RunTrigger) resource.TestCheckFunc { return func(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) rs, ok := s.RootModule().Resources[n] if !ok { @@ -101,7 +101,7 @@ func testAccCheckRunTriggerExists(n string, runTrigger *scalr.RunTrigger) resour func testAccCheckRunTriggerAttributes(runTrigger *scalr.RunTrigger, environmentName string) resource.TestCheckFunc { return func(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) environment, ok := s.RootModule().Resources[environmentName] if !ok { diff --git a/scalr/resource_scalr_service_account.go b/internal/provider/resource_scalr_service_account.go similarity index 96% rename from scalr/resource_scalr_service_account.go rename to internal/provider/resource_scalr_service_account.go index e17a5d89..adf6601d 100644 --- a/scalr/resource_scalr_service_account.go +++ b/internal/provider/resource_scalr_service_account.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "context" @@ -143,17 +143,17 @@ func resourceScalrServiceAccountCreate(ctx context.Context, d *schema.ResourceDa accountID := d.Get("account_id").(string) options := scalr.ServiceAccountCreateOptions{ - Name: scalr.String(name), + Name: ptr(name), Account: &scalr.Account{ID: accountID}, } if desc, ok := d.GetOk("description"); ok { - options.Description = scalr.String(desc.(string)) + options.Description = ptr(desc.(string)) } if status, ok := d.GetOk("status"); ok { saStatus := scalr.ServiceAccountStatus(status.(string)) - options.Status = scalr.ServiceAccountStatusPtr(saStatus) + options.Status = ptr(saStatus) } if owners, ok := d.GetOk("owners"); ok { @@ -184,12 +184,12 @@ func resourceScalrServiceAccountUpdate(ctx context.Context, d *schema.ResourceDa if d.HasChange("description") { desc := d.Get("description").(string) - options.Description = scalr.String(desc) + options.Description = ptr(desc) } if d.HasChange("status") { status := scalr.ServiceAccountStatus(d.Get("status").(string)) - options.Status = scalr.ServiceAccountStatusPtr(status) + options.Status = ptr(status) } if d.HasChange("owners") { diff --git a/scalr/resource_scalr_service_account_test.go b/internal/provider/resource_scalr_service_account_test.go similarity index 82% rename from scalr/resource_scalr_service_account_test.go rename to internal/provider/resource_scalr_service_account_test.go index 9755e911..75bfb888 100644 --- a/scalr/resource_scalr_service_account_test.go +++ b/internal/provider/resource_scalr_service_account_test.go @@ -1,11 +1,11 @@ -package scalr +package provider import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/scalr/go-scalr" ) @@ -13,9 +13,9 @@ func TestAccScalrServiceAccount_basic(t *testing.T) { rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrServiceAccountDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrServiceAccountDestroy, Steps: []resource.TestStep{ { Config: testAccScalrServiceAccountBasic(rInt), @@ -50,9 +50,9 @@ func TestAccScalrServiceAccount_import(t *testing.T) { rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrServiceAccountDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrServiceAccountDestroy, Steps: []resource.TestStep{ { Config: testAccScalrServiceAccountBasic(rInt), @@ -70,9 +70,9 @@ func TestAccScalrServiceAccount_update(t *testing.T) { rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrServiceAccountDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrServiceAccountDestroy, Steps: []resource.TestStep{ { Config: testAccScalrServiceAccountBasic(rInt), @@ -127,7 +127,7 @@ resource scalr_service_account test { } func testAccCheckScalrServiceAccountDestroy(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) for _, rs := range s.RootModule().Resources { if rs.Type != "scalr_service_account" { diff --git a/scalr/resource_scalr_service_account_token.go b/internal/provider/resource_scalr_service_account_token.go similarity index 97% rename from scalr/resource_scalr_service_account_token.go rename to internal/provider/resource_scalr_service_account_token.go index 7a85b82c..da2bbf3b 100644 --- a/scalr/resource_scalr_service_account_token.go +++ b/internal/provider/resource_scalr_service_account_token.go @@ -1,11 +1,12 @@ -package scalr +package provider import ( "context" "errors" - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "log" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/scalr/go-scalr" ) @@ -46,7 +47,7 @@ func resourceScalrServiceAccountTokenCreate(ctx context.Context, d *schema.Resou options := scalr.AccessTokenCreateOptions{} if desc, ok := d.GetOk("description"); ok { - options.Description = scalr.String(desc.(string)) + options.Description = ptr(desc.(string)) } log.Printf("[DEBUG] Create access token for service account: %s", saID) @@ -118,7 +119,7 @@ func resourceScalrServiceAccountTokenUpdate(ctx context.Context, d *schema.Resou desc := d.Get("description").(string) options := scalr.AccessTokenUpdateOptions{ - Description: scalr.String(desc), + Description: ptr(desc), } log.Printf("[DEBUG] Update service account access token %s", id) diff --git a/scalr/resource_scalr_service_account_token_test.go b/internal/provider/resource_scalr_service_account_token_test.go similarity index 80% rename from scalr/resource_scalr_service_account_token_test.go rename to internal/provider/resource_scalr_service_account_token_test.go index 3daceec2..99a6b4bc 100644 --- a/scalr/resource_scalr_service_account_token_test.go +++ b/internal/provider/resource_scalr_service_account_token_test.go @@ -1,11 +1,11 @@ -package scalr +package provider import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/scalr/go-scalr" ) @@ -13,9 +13,9 @@ func TestAccScalrServiceAccountToken_basic(t *testing.T) { rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrServiceAccountTokenDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrServiceAccountTokenDestroy, Steps: []resource.TestStep{ { Config: testAccScalrServiceAccountTokenBasicConfig(rInt), @@ -38,9 +38,9 @@ func TestAccScalrServiceAccountToken_update(t *testing.T) { rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrServiceAccountTokenDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrServiceAccountTokenDestroy, Steps: []resource.TestStep{ { Config: testAccScalrServiceAccountTokenBasicConfig(rInt), @@ -59,7 +59,7 @@ func TestAccScalrServiceAccountToken_update(t *testing.T) { } func testAccCheckScalrServiceAccountTokenDestroy(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) for _, rs := range s.RootModule().Resources { if rs.Type != "scalr_service_account_token" { diff --git a/scalr/resource_scalr_slack_integration.go b/internal/provider/resource_scalr_slack_integration.go similarity index 96% rename from scalr/resource_scalr_slack_integration.go rename to internal/provider/resource_scalr_slack_integration.go index cb23b9cf..54857f0a 100644 --- a/scalr/resource_scalr_slack_integration.go +++ b/internal/provider/resource_scalr_slack_integration.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "context" @@ -143,9 +143,9 @@ func resourceScalrSlackIntegrationCreate(ctx context.Context, d *schema.Resource options := scalr.SlackIntegrationCreateOptions{ Name: &name, - ChannelId: scalr.String(d.Get("channel_id").(string)), + ChannelId: ptr(d.Get("channel_id").(string)), Events: parseEvents(d), - RunMode: scalr.String(d.Get("run_mode").(string)), + RunMode: ptr(d.Get("run_mode").(string)), Account: &scalr.Account{ID: accountID}, Environments: parseEnvironments(d), } @@ -217,11 +217,11 @@ func resourceScalrSlackIntegrationUpdate(ctx context.Context, d *schema.Resource options := scalr.SlackIntegrationUpdateOptions{} if d.HasChange("name") { - options.Name = scalr.String(d.Get("name").(string)) + options.Name = ptr(d.Get("name").(string)) } if d.HasChange("channel_id") { - options.ChannelId = scalr.String(d.Get("channel_id").(string)) + options.ChannelId = ptr(d.Get("channel_id").(string)) } if d.HasChange("events") { @@ -230,7 +230,7 @@ func resourceScalrSlackIntegrationUpdate(ctx context.Context, d *schema.Resource } if d.HasChange("run_mode") { - options.RunMode = scalr.String(d.Get("run_mode").(string)) + options.RunMode = ptr(d.Get("run_mode").(string)) } if d.HasChange("environments") { diff --git a/scalr/resource_scalr_slack_integration_test.go b/internal/provider/resource_scalr_slack_integration_test.go similarity index 95% rename from scalr/resource_scalr_slack_integration_test.go rename to internal/provider/resource_scalr_slack_integration_test.go index 85658ea0..4732625a 100644 --- a/scalr/resource_scalr_slack_integration_test.go +++ b/internal/provider/resource_scalr_slack_integration_test.go @@ -1,10 +1,10 @@ -package scalr +package provider import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func TestAccSlackIntegration_basic(t *testing.T) { @@ -23,7 +23,7 @@ func TestAccSlackIntegration_basic(t *testing.T) { t.Skip("Scalr instance doesn't have working slack connection.") } }, - ProviderFactories: testAccProviderFactories, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: testAccScalrSlackIntegrationConfig(), diff --git a/scalr/resource_scalr_ssh_key.go b/internal/provider/resource_scalr_ssh_key.go similarity index 92% rename from scalr/resource_scalr_ssh_key.go rename to internal/provider/resource_scalr_ssh_key.go index d6e50d69..70469733 100644 --- a/scalr/resource_scalr_ssh_key.go +++ b/internal/provider/resource_scalr_ssh_key.go @@ -1,8 +1,9 @@ -package scalr +package provider import ( "context" "errors" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/scalr/go-scalr" @@ -58,14 +59,14 @@ func resourceScalrSSHKeyCreate(ctx context.Context, d *schema.ResourceData, meta sshKeyOptions := scalr.SSHKeyCreateOptions{ Account: &scalr.Account{ID: accountID}, - Name: scalr.String(name), - PrivateKey: scalr.String(privateKey), + Name: ptr(name), + PrivateKey: ptr(privateKey), } if environmentsI, ok := d.GetOk("environments"); ok { environments := environmentsI.(*schema.Set).List() if (len(environments) == 1) && (environments[0].(string) == "*") { - sshKeyOptions.IsShared = scalr.Bool(true) + sshKeyOptions.IsShared = ptr(true) } else if len(environments) > 0 { environmentValues := make([]*scalr.Environment, 0) for _, env := range environments { @@ -120,17 +121,17 @@ func resourceScalrSSHKeyUpdate(ctx context.Context, d *schema.ResourceData, meta if d.HasChange("name") || d.HasChange("private_key") || d.HasChange("environments") { sshKeyUpdateOptions := scalr.SSHKeyUpdateOptions{ - Name: scalr.String(d.Get("name").(string)), - PrivateKey: scalr.String(d.Get("private_key").(string)), + Name: ptr(d.Get("name").(string)), + PrivateKey: ptr(d.Get("private_key").(string)), } if environmentsI, ok := d.GetOk("environments"); ok { environments := environmentsI.(*schema.Set).List() if (len(environments) == 1) && (environments[0].(string) == "*") { - sshKeyUpdateOptions.IsShared = scalr.Bool(true) + sshKeyUpdateOptions.IsShared = ptr(true) sshKeyUpdateOptions.Environments = make([]*scalr.Environment, 0) } else { - sshKeyUpdateOptions.IsShared = scalr.Bool(false) + sshKeyUpdateOptions.IsShared = ptr(false) environmentValues := make([]*scalr.Environment, 0) for _, env := range environments { environmentValues = append(environmentValues, &scalr.Environment{ID: env.(string)}) @@ -138,7 +139,7 @@ func resourceScalrSSHKeyUpdate(ctx context.Context, d *schema.ResourceData, meta sshKeyUpdateOptions.Environments = environmentValues } } else { - sshKeyUpdateOptions.IsShared = scalr.Bool(false) + sshKeyUpdateOptions.IsShared = ptr(false) sshKeyUpdateOptions.Environments = make([]*scalr.Environment, 0) } diff --git a/scalr/resource_scalr_ssh_key_test.go b/internal/provider/resource_scalr_ssh_key_test.go similarity index 81% rename from scalr/resource_scalr_ssh_key_test.go rename to internal/provider/resource_scalr_ssh_key_test.go index 6d3385c7..8a88a3ba 100644 --- a/scalr/resource_scalr_ssh_key_test.go +++ b/internal/provider/resource_scalr_ssh_key_test.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "context" @@ -6,9 +6,9 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-plugin-testing/helper/acctest" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/scalr/go-scalr" ) @@ -17,9 +17,9 @@ func TestAccScalrSSHKey_basic(t *testing.T) { var sshKey scalr.SSHKey resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckSSHKeyDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckSSHKeyDestroy, Steps: []resource.TestStep{ { Config: testAccScalrSSHKeyConfig(rName), @@ -38,9 +38,9 @@ func TestAccScalrSSHKey_update(t *testing.T) { var sshKey scalr.SSHKey resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckSSHKeyDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckSSHKeyDestroy, Steps: []resource.TestStep{ { Config: testAccScalrSSHKeyConfig(rName), @@ -64,9 +64,9 @@ func TestAccScalrSSHKey_import(t *testing.T) { rName := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckSSHKeyDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckSSHKeyDestroy, Steps: []resource.TestStep{ { Config: testAccScalrSSHKeyConfig(rName), @@ -112,7 +112,7 @@ EOF } func testAccCheckSSHKeyDestroy(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) for _, rs := range s.RootModule().Resources { if rs.Type != "scalr_ssh_key" { @@ -139,7 +139,7 @@ func testAccCheckSSHKeyIsShared(resourceName string, expectedIsShared bool, sshK return fmt.Errorf("Not found: %s", resourceName) } - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) readKey, err := scalrClient.SSHKeys.Read(context.Background(), rs.Primary.ID) if err != nil { return fmt.Errorf("Error reading SSH key: %s", err) diff --git a/scalr/resource_scalr_variable.go b/internal/provider/resource_scalr_variable.go similarity index 92% rename from scalr/resource_scalr_variable.go rename to internal/provider/resource_scalr_variable.go index dc7bdae2..1790b9b3 100644 --- a/scalr/resource_scalr_variable.go +++ b/internal/provider/resource_scalr_variable.go @@ -1,8 +1,9 @@ -package scalr +package provider import ( "context" "errors" + "log" "time" "github.com/hashicorp/go-cty/cty" @@ -11,8 +12,6 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/scalr/go-scalr" - - "log" ) func resourceScalrVariable() *schema.Resource { @@ -205,14 +204,14 @@ func resourceScalrVariableCreate(ctx context.Context, d *schema.ResourceData, me // Create a new options struct. options := scalr.VariableCreateOptions{ - Key: scalr.String(key), - Value: scalr.String(d.Get("value").(string)), - Description: scalr.String(d.Get("description").(string)), - Category: scalr.Category(category), - HCL: scalr.Bool(hcl), - Sensitive: scalr.Bool(d.Get("sensitive").(bool)), - Final: scalr.Bool(d.Get("final").(bool)), - QueryOptions: &scalr.VariableWriteQueryOptions{Force: scalr.Bool(d.Get("force").(bool))}, + Key: ptr(key), + Value: ptr(d.Get("value").(string)), + Description: ptr(d.Get("description").(string)), + Category: ptr(category), + HCL: ptr(hcl), + Sensitive: ptr(d.Get("sensitive").(bool)), + Final: ptr(d.Get("final").(bool)), + QueryOptions: &scalr.VariableWriteQueryOptions{Force: ptr(d.Get("force").(bool))}, Account: &scalr.Account{ID: d.Get("account_id").(string)}, } @@ -320,13 +319,13 @@ func resourceScalrVariableUpdate(ctx context.Context, d *schema.ResourceData, me // Create a new options struct. options := scalr.VariableUpdateOptions{ - Key: scalr.String(d.Get("key").(string)), - Value: scalr.String(d.Get("value").(string)), - HCL: scalr.Bool(hcl), - Sensitive: scalr.Bool(d.Get("sensitive").(bool)), - Description: scalr.String(d.Get("description").(string)), - Final: scalr.Bool(d.Get("final").(bool)), - QueryOptions: &scalr.VariableWriteQueryOptions{Force: scalr.Bool(d.Get("force").(bool))}, + Key: ptr(d.Get("key").(string)), + Value: ptr(d.Get("value").(string)), + HCL: ptr(hcl), + Sensitive: ptr(d.Get("sensitive").(bool)), + Description: ptr(d.Get("description").(string)), + Final: ptr(d.Get("final").(bool)), + QueryOptions: &scalr.VariableWriteQueryOptions{Force: ptr(d.Get("force").(bool))}, } log.Printf("[DEBUG] Update variable: %s", d.Id()) diff --git a/scalr/resource_scalr_variable_migrate.go b/internal/provider/resource_scalr_variable_migrate.go similarity index 99% rename from scalr/resource_scalr_variable_migrate.go rename to internal/provider/resource_scalr_variable_migrate.go index f690f9c2..183bcd79 100644 --- a/scalr/resource_scalr_variable_migrate.go +++ b/internal/provider/resource_scalr_variable_migrate.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "context" diff --git a/scalr/resource_scalr_variable_migrate_test.go b/internal/provider/resource_scalr_variable_migrate_test.go similarity index 99% rename from scalr/resource_scalr_variable_migrate_test.go rename to internal/provider/resource_scalr_variable_migrate_test.go index fdf99178..297fbb2c 100644 --- a/scalr/resource_scalr_variable_migrate_test.go +++ b/internal/provider/resource_scalr_variable_migrate_test.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "context" diff --git a/scalr/resource_scalr_variable_test.go b/internal/provider/resource_scalr_variable_test.go similarity index 91% rename from scalr/resource_scalr_variable_test.go rename to internal/provider/resource_scalr_variable_test.go index 98d0b2b5..8fc6dee7 100644 --- a/scalr/resource_scalr_variable_test.go +++ b/internal/provider/resource_scalr_variable_test.go @@ -1,11 +1,11 @@ -package scalr +package provider import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/scalr/go-scalr" ) @@ -26,9 +26,9 @@ func TestAccScalrVariable_basic(t *testing.T) { rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrVariableDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrVariableDestroy, Steps: []resource.TestStep{ { Config: testAccScalrVariableOnAccountScopeImplicit(rInt), @@ -84,9 +84,9 @@ func TestAccScalrVariable_basic(t *testing.T) { func TestAccScalrVariable_defaults(t *testing.T) { rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrVariableDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrVariableDestroy, Steps: []resource.TestStep{ { Config: testAccScalrVariableOnAccountScopeImplicit(rInt), @@ -111,9 +111,9 @@ func TestAccScalrVariable_scopes(t *testing.T) { variable := &scalr.Variable{} resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrVariableDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrVariableDestroy, Steps: []resource.TestStep{ { Config: testAccScalrVariableOnAllScopes(rInt), @@ -128,9 +128,9 @@ func TestAccScalrVariable_update(t *testing.T) { variable := &scalr.Variable{} resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrVariableDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrVariableDestroy, Steps: []resource.TestStep{ { Config: testAccScalrVariableOnWorkspaceScope(rInt), @@ -188,9 +188,9 @@ func TestAccScalrVariable_update(t *testing.T) { func TestAccScalrVariable_import(t *testing.T) { rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrVariableDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrVariableDestroy, Steps: []resource.TestStep{ { Config: testAccScalrVariableOnWorkspaceScope(rInt), @@ -205,7 +205,7 @@ func TestAccScalrVariable_import(t *testing.T) { } func variableFromState(s *terraform.State, n string, v *scalr.Variable) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) rs, ok := s.RootModule().Resources[n] if !ok { @@ -333,7 +333,7 @@ func testAccCheckScalrVariableAttributesUpdate( } func testAccCheckScalrVariableDestroy(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) for _, rs := range s.RootModule().Resources { if rs.Type != "scalr_variable" { diff --git a/scalr/resource_scalr_vcs_provider.go b/internal/provider/resource_scalr_vcs_provider.go similarity index 92% rename from scalr/resource_scalr_vcs_provider.go rename to internal/provider/resource_scalr_vcs_provider.go index d38eca27..ee4c4460 100644 --- a/scalr/resource_scalr_vcs_provider.go +++ b/internal/provider/resource_scalr_vcs_provider.go @@ -1,11 +1,12 @@ -package scalr +package provider import ( "context" "errors" - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "log" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/scalr/go-scalr" @@ -116,12 +117,12 @@ func resourceScalrVcsProviderCreate(ctx context.Context, d *schema.ResourceData, // Get the url if url, ok := d.GetOk("url"); ok { - options.Url = scalr.String(url.(string)) + options.Url = ptr(url.(string)) } // Get the username if username, ok := d.GetOk("username"); ok { - options.Username = scalr.String(username.(string)) + options.Username = ptr(username.(string)) } if agentPoolID, ok := d.GetOk("agent_pool_id"); ok { @@ -131,15 +132,15 @@ func resourceScalrVcsProviderCreate(ctx context.Context, d *schema.ResourceData, } if draftPRsRunEnabled, ok := d.GetOk("draft_pr_runs_enabled"); ok { - options.DraftPrRunsEnabled = scalr.Bool(draftPRsRunEnabled.(bool)) + options.DraftPrRunsEnabled = ptr(draftPRsRunEnabled.(bool)) } if environmentsI, ok := d.GetOk("environments"); ok { environments := environmentsI.(*schema.Set).List() if (len(environments) == 1) && (environments[0].(string) == "*") { - options.IsShared = scalr.Bool(true) + options.IsShared = ptr(true) } else if len(environments) > 0 { - options.IsShared = scalr.Bool(false) + options.IsShared = ptr(false) environmentValues := make([]*scalr.Environment, 0) for _, env := range environments { if env.(string) == "*" { @@ -205,17 +206,17 @@ func resourceScalrVcsProviderUpdate(ctx context.Context, d *schema.ResourceData, scalrClient := meta.(*scalr.Client) // Create a new options' struct. options := scalr.VcsProviderUpdateOptions{ - Name: scalr.String(d.Get("name").(string)), - Token: scalr.String(d.Get("token").(string)), + Name: ptr(d.Get("name").(string)), + Token: ptr(d.Get("token").(string)), } if url, ok := d.GetOk("url"); ok { - options.Url = scalr.String(url.(string)) + options.Url = ptr(url.(string)) } // Get the username if username, ok := d.GetOk("username"); ok { - options.Username = scalr.String(username.(string)) + options.Username = ptr(username.(string)) } if agentPoolID, ok := d.GetOk("agent_pool_id"); ok { @@ -225,16 +226,16 @@ func resourceScalrVcsProviderUpdate(ctx context.Context, d *schema.ResourceData, } if d.HasChange("draft_pr_runs_enabled") { - options.DraftPrRunsEnabled = scalr.Bool(d.Get("draft_pr_runs_enabled").(bool)) + options.DraftPrRunsEnabled = ptr(d.Get("draft_pr_runs_enabled").(bool)) } if environmentsI, ok := d.GetOk("environments"); ok { environments := environmentsI.(*schema.Set).List() if (len(environments) == 1) && (environments[0].(string) == "*") { - options.IsShared = scalr.Bool(true) + options.IsShared = ptr(true) options.Environments = make([]*scalr.Environment, 0) } else { - options.IsShared = scalr.Bool(false) + options.IsShared = ptr(false) environmentValues := make([]*scalr.Environment, 0) for _, env := range environments { if env.(string) == "*" { @@ -247,7 +248,7 @@ func resourceScalrVcsProviderUpdate(ctx context.Context, d *schema.ResourceData, options.Environments = environmentValues } } else { - options.IsShared = scalr.Bool(true) + options.IsShared = ptr(true) options.Environments = make([]*scalr.Environment, 0) } diff --git a/scalr/resource_scalr_vcs_provider_migrate.go b/internal/provider/resource_scalr_vcs_provider_migrate.go similarity index 98% rename from scalr/resource_scalr_vcs_provider_migrate.go rename to internal/provider/resource_scalr_vcs_provider_migrate.go index 3ffd3c86..3554408e 100644 --- a/scalr/resource_scalr_vcs_provider_migrate.go +++ b/internal/provider/resource_scalr_vcs_provider_migrate.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "context" diff --git a/scalr/resource_scalr_vcs_provider_migrate_test.go b/internal/provider/resource_scalr_vcs_provider_migrate_test.go similarity index 97% rename from scalr/resource_scalr_vcs_provider_migrate_test.go rename to internal/provider/resource_scalr_vcs_provider_migrate_test.go index 79731445..7970ec46 100644 --- a/scalr/resource_scalr_vcs_provider_migrate_test.go +++ b/internal/provider/resource_scalr_vcs_provider_migrate_test.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "testing" diff --git a/scalr/resource_scalr_vcs_provider_test.go b/internal/provider/resource_scalr_vcs_provider_test.go similarity index 85% rename from scalr/resource_scalr_vcs_provider_test.go rename to internal/provider/resource_scalr_vcs_provider_test.go index 7ad75623..522b1d6c 100644 --- a/scalr/resource_scalr_vcs_provider_test.go +++ b/internal/provider/resource_scalr_vcs_provider_test.go @@ -1,12 +1,12 @@ -package scalr +package provider import ( "fmt" "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/scalr/go-scalr" ) @@ -14,8 +14,8 @@ func TestAccVcsProvider_basic(t *testing.T) { provider := &scalr.VcsProvider{} resource.Test(t, resource.TestCase{ - PreCheck: func() { testVcsAccGithubTokenPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + PreCheck: func() { testVcsAccGithubTokenPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: testAccScalrVcsProviderConfig(), @@ -55,9 +55,9 @@ func TestAccVcsProvider_basic(t *testing.T) { func TestAccVcsProvider_globalScope(t *testing.T) { provider := &scalr.VcsProvider{} resource.Test(t, resource.TestCase{ - PreCheck: func() { testVcsAccGithubTokenPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrVcsProviderDestroy, + PreCheck: func() { testVcsAccGithubTokenPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrVcsProviderDestroy, Steps: []resource.TestStep{ { Config: fmt.Sprintf(` @@ -80,9 +80,9 @@ func TestAccVcsProvider_globalScope(t *testing.T) { func TestAccScalrVcsProvider_import(t *testing.T) { resource.Test(t, resource.TestCase{ - PreCheck: func() { testVcsAccGithubTokenPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrVcsProviderDestroy, + PreCheck: func() { testVcsAccGithubTokenPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrVcsProviderDestroy, Steps: []resource.TestStep{ { Config: testAccScalrVcsProviderConfig(), @@ -99,7 +99,7 @@ func TestAccScalrVcsProvider_import(t *testing.T) { func testAccCheckScalrVcsProviderExists(resId string, vcsProvider *scalr.VcsProvider) resource.TestCheckFunc { return func(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) rs, ok := s.RootModule().Resources[resId] if !ok { @@ -123,7 +123,7 @@ func testAccCheckScalrVcsProviderExists(resId string, vcsProvider *scalr.VcsProv } func testAccCheckScalrVcsProviderDestroy(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) for _, rs := range s.RootModule().Resources { if rs.Type != "scalr_vcs_provider" { diff --git a/scalr/resource_scalr_webhook.go b/internal/provider/resource_scalr_webhook.go similarity index 93% rename from scalr/resource_scalr_webhook.go rename to internal/provider/resource_scalr_webhook.go index d8b37b98..c914db29 100644 --- a/scalr/resource_scalr_webhook.go +++ b/internal/provider/resource_scalr_webhook.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "context" @@ -185,22 +185,22 @@ func createWebhook(ctx context.Context, d *schema.ResourceData, scalrClient *sca options := scalr.WebhookIntegrationCreateOptions{ Name: &name, - Url: scalr.String(d.Get("url").(string)), + Url: ptr(d.Get("url").(string)), Account: &scalr.Account{ID: accountId}, Events: eventDefinitions, - Enabled: scalr.Bool(d.Get("enabled").(bool)), - Timeout: scalr.Int(d.Get("timeout").(int)), - MaxAttempts: scalr.Int(d.Get("max_attempts").(int)), + Enabled: ptr(d.Get("enabled").(bool)), + Timeout: ptr(d.Get("timeout").(int)), + MaxAttempts: ptr(d.Get("max_attempts").(int)), } if secretKey, ok := d.GetOk("secret_key"); ok { - options.SecretKey = scalr.String(secretKey.(string)) + options.SecretKey = ptr(secretKey.(string)) } if environmentsI, ok := d.GetOk("environments"); ok { environments := environmentsI.(*schema.Set).List() if (len(environments) == 1) && (environments[0].(string) == "*") { - options.IsShared = scalr.Bool(true) + options.IsShared = ptr(true) } else if len(environments) > 0 { environmentValues := make([]*scalr.Environment, 0) for _, env := range environments { @@ -309,27 +309,27 @@ func updateWebhook(ctx context.Context, d *schema.ResourceData, scalrClient *sca options := scalr.WebhookIntegrationUpdateOptions{} if d.HasChange("name") { - options.Name = scalr.String(d.Get("name").(string)) + options.Name = ptr(d.Get("name").(string)) } if d.HasChange("url") { - options.Url = scalr.String(d.Get("url").(string)) + options.Url = ptr(d.Get("url").(string)) } if d.HasChange("enabled") { - options.Enabled = scalr.Bool(d.Get("enabled").(bool)) + options.Enabled = ptr(d.Get("enabled").(bool)) } if d.HasChange("secret_key") { - options.SecretKey = scalr.String(d.Get("secret_key").(string)) + options.SecretKey = ptr(d.Get("secret_key").(string)) } if d.HasChange("timeout") { - options.Timeout = scalr.Int(d.Get("timeout").(int)) + options.Timeout = ptr(d.Get("timeout").(int)) } if d.HasChange("max_attempts") { - options.MaxAttempts = scalr.Int(d.Get("max_attempts").(int)) + options.MaxAttempts = ptr(d.Get("max_attempts").(int)) } if d.HasChange("header") { @@ -345,10 +345,10 @@ func updateWebhook(ctx context.Context, d *schema.ResourceData, scalrClient *sca if environmentsI, ok := d.GetOk("environments"); ok { environments := environmentsI.(*schema.Set).List() if (len(environments) == 1) && (environments[0].(string) == "*") { - options.IsShared = scalr.Bool(true) + options.IsShared = ptr(true) options.Environments = make([]*scalr.Environment, 0) } else { - options.IsShared = scalr.Bool(false) + options.IsShared = ptr(false) environmentValues := make([]*scalr.Environment, 0) for _, env := range environments { if env.(string) == "*" { @@ -361,7 +361,7 @@ func updateWebhook(ctx context.Context, d *schema.ResourceData, scalrClient *sca options.Environments = environmentValues } } else { - options.IsShared = scalr.Bool(false) + options.IsShared = ptr(false) options.Environments = make([]*scalr.Environment, 0) } diff --git a/scalr/resource_scalr_webhook_migrate.go b/internal/provider/resource_scalr_webhook_migrate.go similarity index 99% rename from scalr/resource_scalr_webhook_migrate.go rename to internal/provider/resource_scalr_webhook_migrate.go index 661f459c..45eacde1 100644 --- a/scalr/resource_scalr_webhook_migrate.go +++ b/internal/provider/resource_scalr_webhook_migrate.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "context" diff --git a/scalr/resource_scalr_webhook_test.go b/internal/provider/resource_scalr_webhook_test.go similarity index 89% rename from scalr/resource_scalr_webhook_test.go rename to internal/provider/resource_scalr_webhook_test.go index 79cc76b2..e0ff3da5 100644 --- a/scalr/resource_scalr_webhook_test.go +++ b/internal/provider/resource_scalr_webhook_test.go @@ -1,19 +1,19 @@ -package scalr +package provider import ( "fmt" "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func TestAccWebhook_basic(t *testing.T) { rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: testAccWebhookConfig(rInt), @@ -32,8 +32,8 @@ func TestAccWebhook_update(t *testing.T) { rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: testAccWebhookConfigUpdateEmptyEvent(rInt), diff --git a/scalr/resource_scalr_workspace.go b/internal/provider/resource_scalr_workspace.go similarity index 89% rename from scalr/resource_scalr_workspace.go rename to internal/provider/resource_scalr_workspace.go index de66e9b8..3e5cf486 100644 --- a/scalr/resource_scalr_workspace.go +++ b/internal/provider/resource_scalr_workspace.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "context" @@ -400,51 +400,51 @@ func resourceScalrWorkspaceCreate(ctx context.Context, d *schema.ResourceData, m // Create a new options struct. options := scalr.WorkspaceCreateOptions{ - Name: scalr.String(name), - AutoApply: scalr.Bool(d.Get("auto_apply").(bool)), - ForceLatestRun: scalr.Bool(d.Get("force_latest_run").(bool)), - DeletionProtectionEnabled: scalr.Bool(d.Get("deletion_protection_enabled").(bool)), + Name: ptr(name), + AutoApply: ptr(d.Get("auto_apply").(bool)), + ForceLatestRun: ptr(d.Get("force_latest_run").(bool)), + DeletionProtectionEnabled: ptr(d.Get("deletion_protection_enabled").(bool)), Environment: &scalr.Environment{ID: environmentID}, Hooks: &scalr.HooksOptions{}, } // Process all configured options. if operations, ok := d.GetOk("operations"); ok { - options.Operations = scalr.Bool(operations.(bool)) + options.Operations = ptr(operations.(bool)) } if executionMode, ok := d.GetOk("execution_mode"); ok { - options.ExecutionMode = scalr.WorkspaceExecutionModePtr( + options.ExecutionMode = ptr( scalr.WorkspaceExecutionMode(executionMode.(string)), ) } if autoQueueRunsI, ok := d.GetOk("auto_queue_runs"); ok { - options.AutoQueueRuns = scalr.AutoQueueRunsModePtr( + options.AutoQueueRuns = ptr( scalr.WorkspaceAutoQueueRuns(autoQueueRunsI.(string)), ) } if workspaceEnvironmentTypeI, ok := d.GetOk("type"); ok { - options.EnvironmentType = scalr.WorkspaceEnvironmentTypePtr( + options.EnvironmentType = ptr( scalr.WorkspaceEnvironmentType(workspaceEnvironmentTypeI.(string)), ) } if tfVersion, ok := d.GetOk("terraform_version"); ok { - options.TerraformVersion = scalr.String(tfVersion.(string)) + options.TerraformVersion = ptr(tfVersion.(string)) } if iacPlatform, ok := d.GetOk("iac_platform"); ok { - options.IacPlatform = scalr.WorkspaceIaCPlatformPtr(scalr.WorkspaceIaCPlatform(iacPlatform.(string))) + options.IacPlatform = ptr(scalr.WorkspaceIaCPlatform(iacPlatform.(string))) } if workingDir, ok := d.GetOk("working_directory"); ok { - options.WorkingDirectory = scalr.String(workingDir.(string)) + options.WorkingDirectory = ptr(workingDir.(string)) } if runOperationTimeout, ok := d.GetOk("run_operation_timeout"); ok { - options.RunOperationTimeout = scalr.Int(runOperationTimeout.(int)) + options.RunOperationTimeout = ptr(runOperationTimeout.(int)) } if v, ok := d.GetOk("module_version_id"); ok { @@ -472,17 +472,17 @@ func resourceScalrWorkspaceCreate(ctx context.Context, d *schema.ResourceData, m } options.VCSRepo = &scalr.WorkspaceVCSRepoOptions{ - Identifier: scalr.String(vcsRepo["identifier"].(string)), - Path: scalr.String(vcsRepo["path"].(string)), + Identifier: ptr(vcsRepo["identifier"].(string)), + Path: ptr(vcsRepo["path"].(string)), TriggerPrefixes: &triggerPrefixes, - TriggerPatterns: scalr.String(vcsRepo["trigger_patterns"].(string)), - DryRunsEnabled: scalr.Bool(vcsRepo["dry_runs_enabled"].(bool)), - IngressSubmodules: scalr.Bool(vcsRepo["ingress_submodules"].(bool)), + TriggerPatterns: ptr(vcsRepo["trigger_patterns"].(string)), + DryRunsEnabled: ptr(vcsRepo["dry_runs_enabled"].(bool)), + IngressSubmodules: ptr(vcsRepo["ingress_submodules"].(bool)), } // Only set the branch if one is configured. if branch, ok := vcsRepo["branch"].(string); ok && branch != "" { - options.VCSRepo.Branch = scalr.String(branch) + options.VCSRepo.Branch = ptr(branch) } } @@ -492,11 +492,11 @@ func resourceScalrWorkspaceCreate(ctx context.Context, d *schema.ResourceData, m hooks := v.([]interface{})[0].(map[string]interface{}) options.Hooks = &scalr.HooksOptions{ - PreInit: scalr.String(hooks["pre_init"].(string)), - PrePlan: scalr.String(hooks["pre_plan"].(string)), - PostPlan: scalr.String(hooks["post_plan"].(string)), - PreApply: scalr.String(hooks["pre_apply"].(string)), - PostApply: scalr.String(hooks["post_apply"].(string)), + PreInit: ptr(hooks["pre_init"].(string)), + PrePlan: ptr(hooks["pre_plan"].(string)), + PostPlan: ptr(hooks["post_plan"].(string)), + PreApply: ptr(hooks["pre_apply"].(string)), + PostApply: ptr(hooks["post_apply"].(string)), } } } @@ -534,7 +534,7 @@ func resourceScalrWorkspaceCreate(ctx context.Context, d *schema.ResourceData, m ProviderConfiguration: &scalr.ProviderConfiguration{ID: pcfg["id"].(string)}, } if alias, ok := pcfg["alias"]; ok && len(alias.(string)) > 0 { - createLinkOption.Alias = scalr.String(alias.(string)) + createLinkOption.Alias = ptr(alias.(string)) } _, err := scalrClient.ProviderConfigurationLinks.Create( ctx, workspace.ID, createLinkOption, @@ -692,48 +692,48 @@ func resourceScalrWorkspaceUpdate(ctx context.Context, d *schema.ResourceData, m d.HasChange("type") { // Create a new options struct. options := scalr.WorkspaceUpdateOptions{ - Name: scalr.String(d.Get("name").(string)), - AutoApply: scalr.Bool(d.Get("auto_apply").(bool)), - ForceLatestRun: scalr.Bool(d.Get("force_latest_run").(bool)), - DeletionProtectionEnabled: scalr.Bool(d.Get("deletion_protection_enabled").(bool)), + Name: ptr(d.Get("name").(string)), + AutoApply: ptr(d.Get("auto_apply").(bool)), + ForceLatestRun: ptr(d.Get("force_latest_run").(bool)), + DeletionProtectionEnabled: ptr(d.Get("deletion_protection_enabled").(bool)), Hooks: &scalr.HooksOptions{ - PreInit: scalr.String(""), - PrePlan: scalr.String(""), - PostPlan: scalr.String(""), - PreApply: scalr.String(""), - PostApply: scalr.String(""), + PreInit: ptr(""), + PrePlan: ptr(""), + PostPlan: ptr(""), + PreApply: ptr(""), + PostApply: ptr(""), }, } // Process all configured options. if operations, ok := d.GetOk("operations"); ok { - options.Operations = scalr.Bool(operations.(bool)) + options.Operations = ptr(operations.(bool)) } if executionMode, ok := d.GetOk("execution_mode"); ok { - options.ExecutionMode = scalr.WorkspaceExecutionModePtr( + options.ExecutionMode = ptr( scalr.WorkspaceExecutionMode(executionMode.(string)), ) } if autoQueueRunsI, ok := d.GetOk("auto_queue_runs"); ok { - options.AutoQueueRuns = scalr.AutoQueueRunsModePtr( + options.AutoQueueRuns = ptr( scalr.WorkspaceAutoQueueRuns(autoQueueRunsI.(string)), ) } if workspaceEnvironmentTypeI, ok := d.GetOk("type"); ok { - options.EnvironmentType = scalr.WorkspaceEnvironmentTypePtr( + options.EnvironmentType = ptr( scalr.WorkspaceEnvironmentType(workspaceEnvironmentTypeI.(string)), ) } if tfVersion, ok := d.GetOk("terraform_version"); ok { - options.TerraformVersion = scalr.String(tfVersion.(string)) + options.TerraformVersion = ptr(tfVersion.(string)) } if iacPlatform, ok := d.GetOk("iac_platform"); ok { - options.IacPlatform = scalr.WorkspaceIaCPlatformPtr(scalr.WorkspaceIaCPlatform(iacPlatform.(string))) + options.IacPlatform = ptr(scalr.WorkspaceIaCPlatform(iacPlatform.(string))) } if v, ok := d.Get("var_files").([]interface{}); ok { @@ -744,10 +744,10 @@ func resourceScalrWorkspaceUpdate(ctx context.Context, d *schema.ResourceData, m options.VarFiles = varFiles } - options.WorkingDirectory = scalr.String(d.Get("working_directory").(string)) + options.WorkingDirectory = ptr(d.Get("working_directory").(string)) if runOperationTimeout, ok := d.GetOk("run_operation_timeout"); ok { - options.RunOperationTimeout = scalr.Int(runOperationTimeout.(int)) + options.RunOperationTimeout = ptr(runOperationTimeout.(int)) } if vcsProviderId, ok := d.GetOk("vcs_provider_id"); ok { @@ -771,13 +771,13 @@ func resourceScalrWorkspaceUpdate(ctx context.Context, d *schema.ResourceData, m } options.VCSRepo = &scalr.WorkspaceVCSRepoOptions{ - Identifier: scalr.String(vcsRepo["identifier"].(string)), - Branch: scalr.String(vcsRepo["branch"].(string)), - Path: scalr.String(vcsRepo["path"].(string)), + Identifier: ptr(vcsRepo["identifier"].(string)), + Branch: ptr(vcsRepo["branch"].(string)), + Path: ptr(vcsRepo["path"].(string)), TriggerPrefixes: &triggerPrefixes, - TriggerPatterns: scalr.String(vcsRepo["trigger_patterns"].(string)), - DryRunsEnabled: scalr.Bool(vcsRepo["dry_runs_enabled"].(bool)), - IngressSubmodules: scalr.Bool(vcsRepo["ingress_submodules"].(bool)), + TriggerPatterns: ptr(vcsRepo["trigger_patterns"].(string)), + DryRunsEnabled: ptr(vcsRepo["dry_runs_enabled"].(bool)), + IngressSubmodules: ptr(vcsRepo["ingress_submodules"].(bool)), } } @@ -787,11 +787,11 @@ func resourceScalrWorkspaceUpdate(ctx context.Context, d *schema.ResourceData, m hooks := v.([]interface{})[0].(map[string]interface{}) options.Hooks = &scalr.HooksOptions{ - PreInit: scalr.String(hooks["pre_init"].(string)), - PrePlan: scalr.String(hooks["pre_plan"].(string)), - PostPlan: scalr.String(hooks["post_plan"].(string)), - PreApply: scalr.String(hooks["pre_apply"].(string)), - PostApply: scalr.String(hooks["post_apply"].(string)), + PreInit: ptr(hooks["pre_init"].(string)), + PrePlan: ptr(hooks["pre_plan"].(string)), + PostPlan: ptr(hooks["post_plan"].(string)), + PreApply: ptr(hooks["pre_apply"].(string)), + PostApply: ptr(hooks["post_apply"].(string)), } } } @@ -838,7 +838,7 @@ func resourceScalrWorkspaceUpdate(ctx context.Context, d *schema.ResourceData, m ProviderConfiguration: &scalr.ProviderConfiguration{ID: configLink["id"].(string)}, } if v, ok := configLink["alias"]; ok && len(v.(string)) > 0 { - linkCreateOption.Alias = scalr.String(v.(string)) + linkCreateOption.Alias = ptr(v.(string)) mapID = mapID + v.(string) } expectedLinks[mapID] = linkCreateOption diff --git a/scalr/resource_scalr_workspace_migrate.go b/internal/provider/resource_scalr_workspace_migrate.go similarity index 99% rename from scalr/resource_scalr_workspace_migrate.go rename to internal/provider/resource_scalr_workspace_migrate.go index 8a91f338..4fb5f741 100644 --- a/scalr/resource_scalr_workspace_migrate.go +++ b/internal/provider/resource_scalr_workspace_migrate.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "context" diff --git a/scalr/resource_scalr_workspace_migrate_test.go b/internal/provider/resource_scalr_workspace_migrate_test.go similarity index 99% rename from scalr/resource_scalr_workspace_migrate_test.go rename to internal/provider/resource_scalr_workspace_migrate_test.go index 6b63ce9c..c93f17bc 100644 --- a/scalr/resource_scalr_workspace_migrate_test.go +++ b/internal/provider/resource_scalr_workspace_migrate_test.go @@ -1,8 +1,9 @@ -package scalr +package provider import ( - "github.com/scalr/go-scalr" "testing" + + "github.com/scalr/go-scalr" ) func testResourceScalrWorkspaceStateDataV0() map[string]interface{} { diff --git a/scalr/resource_scalr_workspace_run_schedule.go b/internal/provider/resource_scalr_workspace_run_schedule.go similarity index 94% rename from scalr/resource_scalr_workspace_run_schedule.go rename to internal/provider/resource_scalr_workspace_run_schedule.go index e80e2ace..311f3d69 100644 --- a/scalr/resource_scalr_workspace_run_schedule.go +++ b/internal/provider/resource_scalr_workspace_run_schedule.go @@ -1,13 +1,14 @@ -package scalr +package provider import ( "context" "errors" "fmt" + "log" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/scalr/go-scalr" - "log" ) func resourceScalrWorkspaceRunSchedule() *schema.Resource { @@ -57,10 +58,10 @@ func resourceScalrWorkspaceRunScheduleCreate(ctx context.Context, d *schema.Reso options := scalr.WorkspaceRunScheduleOptions{} if applySchedule, ok := d.GetOk("apply_schedule"); ok { - options.ApplySchedule = scalr.String(applySchedule.(string)) + options.ApplySchedule = ptr(applySchedule.(string)) } if destroySchedule, ok := d.GetOk("destroy_schedule"); ok { - options.DestroySchedule = scalr.String(destroySchedule.(string)) + options.DestroySchedule = ptr(destroySchedule.(string)) } applySchedule := "" @@ -123,10 +124,10 @@ func resourceScalrWorkspaceRunScheduleUpdate(ctx context.Context, d *schema.Reso options := scalr.WorkspaceRunScheduleOptions{} if applySchedule, ok := d.GetOk("apply_schedule"); ok { - options.ApplySchedule = scalr.String(applySchedule.(string)) + options.ApplySchedule = ptr(applySchedule.(string)) } if destroySchedule, ok := d.GetOk("destroy_schedule"); ok { - options.DestroySchedule = scalr.String(destroySchedule.(string)) + options.DestroySchedule = ptr(destroySchedule.(string)) } applySchedule := "" diff --git a/scalr/resource_scalr_workspace_run_schedule_test.go b/internal/provider/resource_scalr_workspace_run_schedule_test.go similarity index 83% rename from scalr/resource_scalr_workspace_run_schedule_test.go rename to internal/provider/resource_scalr_workspace_run_schedule_test.go index 4ab6a583..9449c758 100644 --- a/scalr/resource_scalr_workspace_run_schedule_test.go +++ b/internal/provider/resource_scalr_workspace_run_schedule_test.go @@ -1,18 +1,19 @@ -package scalr +package provider import ( "fmt" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func TestScalrWorkspaceRunSchedule_basic(t *testing.T) { rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrWorkspaceDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrWorkspaceDestroy, Steps: []resource.TestStep{ { Config: testAccScalrWorkspaceRunSchedule(rInt), @@ -31,9 +32,9 @@ func TestScalrWorkspaceRunSchedule_default(t *testing.T) { rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrWorkspaceDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrWorkspaceDestroy, Steps: []resource.TestStep{ { Config: testAccScalrWorkspaceRunScheduleDefaultValue(rInt), diff --git a/scalr/resource_scalr_workspace_test.go b/internal/provider/resource_scalr_workspace_test.go similarity index 79% rename from scalr/resource_scalr_workspace_test.go rename to internal/provider/resource_scalr_workspace_test.go index 121d5f90..c8df2227 100644 --- a/scalr/resource_scalr_workspace_test.go +++ b/internal/provider/resource_scalr_workspace_test.go @@ -1,14 +1,13 @@ -package scalr +package provider import ( "context" "fmt" - "log" "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/scalr/go-scalr" ) @@ -17,9 +16,9 @@ func TestAccScalrWorkspace_basic(t *testing.T) { rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrWorkspaceDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrWorkspaceDestroy, Steps: []resource.TestStep{ { Config: testAccScalrWorkspaceBasic(rInt), @@ -72,8 +71,8 @@ func TestAccScalrWorkspace_create_missed_vcs_attr(t *testing.T) { rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), Steps: []resource.TestStep{ { Config: testAccScalrWorkspaceMissedVcsProvider(rInt), @@ -92,9 +91,9 @@ func TestAccScalrWorkspace_monorepo(t *testing.T) { rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrWorkspaceDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrWorkspaceDestroy, Steps: []resource.TestStep{ { Config: testAccScalrWorkspaceMonorepo(rInt), @@ -119,89 +118,14 @@ func TestAccScalrWorkspace_monorepo(t *testing.T) { }) } -func TestAccScalrWorkspace_renamed(t *testing.T) { - workspace := &scalr.Workspace{} - rInt := GetRandomInteger() - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrWorkspaceDestroy, - Steps: []resource.TestStep{ - { - Config: testAccScalrWorkspaceBasic(rInt), - Check: resource.ComposeTestCheckFunc( - testAccCheckScalrWorkspaceExists( - "scalr_workspace.test", workspace), - testAccCheckScalrWorkspaceAttributes(workspace), - resource.TestCheckResourceAttr( - "scalr_workspace.test", "name", "workspace-test"), - resource.TestCheckResourceAttr( - "scalr_workspace.test", "auto_apply", "true"), - resource.TestCheckResourceAttr( - "scalr_workspace.test", "operations", "true"), - resource.TestCheckResourceAttr( - "scalr_workspace.test", "execution_mode", string(scalr.WorkspaceExecutionModeRemote)), - resource.TestCheckResourceAttr( - "scalr_workspace.test", "auto_queue_runs", string(scalr.AutoQueueRunsModeAlways)), - resource.TestCheckResourceAttr( - "scalr_workspace.test", "working_directory", ""), - resource.TestCheckResourceAttr( - "scalr_workspace.test", "hooks.0.pre_init", "./scripts/pre-init.sh"), - resource.TestCheckResourceAttr( - "scalr_workspace.test", "hooks.0.pre_plan", "./scripts/pre-plan.sh"), - resource.TestCheckResourceAttr( - "scalr_workspace.test", "hooks.0.post_plan", "./scripts/post-plan.sh"), - resource.TestCheckResourceAttr( - "scalr_workspace.test", "hooks.0.pre_apply", "./scripts/pre-apply.sh"), - resource.TestCheckResourceAttr( - "scalr_workspace.test", "hooks.0.post_apply", "./scripts/post-apply.sh"), - ), - }, - - { - PreConfig: testAccCheckScalrWorkspaceRename(fmt.Sprintf("test-env-%d", rInt), "workspace-test"), - Config: testAccScalrWorkspaceRenamed(rInt), - PlanOnly: true, - Check: resource.ComposeTestCheckFunc( - testAccCheckScalrWorkspaceExists( - "scalr_workspace.test", workspace), - testAccCheckScalrWorkspaceAttributes(workspace), - resource.TestCheckResourceAttr( - "scalr_workspace.test", "name", "workspace-test"), - resource.TestCheckResourceAttr( - "scalr_workspace.test", "auto_apply", "true"), - resource.TestCheckResourceAttr( - "scalr_workspace.test", "operations", "true"), - resource.TestCheckResourceAttr( - "scalr_workspace.test", "execution_mode", string(scalr.WorkspaceExecutionModeRemote)), - resource.TestCheckResourceAttr( - "scalr_workspace.test", "auto_queue_runs", string(scalr.AutoQueueRunsModeAlways)), - resource.TestCheckResourceAttr( - "scalr_workspace.test", "working_directory", ""), - resource.TestCheckResourceAttr( - "scalr_workspace.test", "hooks.0.pre_init", "./scripts/pre-init.sh"), - resource.TestCheckResourceAttr( - "scalr_workspace.test", "hooks.0.pre_plan", "./scripts/pre-plan.sh"), - resource.TestCheckResourceAttr( - "scalr_workspace.test", "hooks.0.post_plan", "./scripts/post-plan.sh"), - resource.TestCheckResourceAttr( - "scalr_workspace.test", "hooks.0.pre_apply", "./scripts/pre-apply.sh"), - resource.TestCheckResourceAttr( - "scalr_workspace.test", "hooks.0.post_apply", "./scripts/post-apply.sh"), - ), - }, - }, - }) -} func TestAccScalrWorkspace_update(t *testing.T) { workspace := &scalr.Workspace{} rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrWorkspaceDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrWorkspaceDestroy, Steps: []resource.TestStep{ { Config: testAccScalrWorkspaceBasic(rInt), @@ -320,9 +244,9 @@ func TestAccScalrWorkspace_import(t *testing.T) { rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrWorkspaceDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrWorkspaceDestroy, Steps: []resource.TestStep{ { Config: testAccScalrWorkspaceBasic(rInt), @@ -342,9 +266,9 @@ func TestAccScalrWorkspace_providerConfiguration(t *testing.T) { rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrWorkspaceDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrWorkspaceDestroy, Steps: []resource.TestStep{ { Config: testAccScalrWorkspaceProviderConfiguration(rInt), @@ -377,9 +301,9 @@ func TestAccScalrWorkspaceSSHKey(t *testing.T) { sshKeyName := fmt.Sprintf("ssh-key-test-%d", rInt) resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrWorkspaceDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrWorkspaceDestroy, Steps: []resource.TestStep{ { Config: testAccScalrWorkspaceWithSSHKeyConfig(rInt, sshKeyName), @@ -397,7 +321,7 @@ func TestAccScalrWorkspaceSSHKey(t *testing.T) { func testAccCheckScalrSSHKeyExists(n string, sshKey *scalr.SSHKey) resource.TestCheckFunc { return func(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) rs, ok := s.RootModule().Resources[n] if !ok { @@ -422,9 +346,9 @@ func TestAccScalrWorkspace_emptyHooks(t *testing.T) { rInt := GetRandomInteger() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrWorkspaceDestroy, + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrWorkspaceDestroy, Steps: []resource.TestStep{ { Config: testAccScalrWorkspaceEmptyHooks(rInt), @@ -436,7 +360,7 @@ func TestAccScalrWorkspace_emptyHooks(t *testing.T) { func testAccCheckScalrWorkspaceExists( n string, workspace *scalr.Workspace) resource.TestCheckFunc { return func(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) rs, ok := s.RootModule().Resources[n] if !ok { @@ -497,49 +421,6 @@ func testAccCheckScalrWorkspaceMonorepoAttributes( } } -func testAccCheckScalrWorkspaceRename(environmentName, workspaceName string) func() { - return func() { - var environmentID *string - scalrClient := testAccProvider.Meta().(*scalr.Client) - - listOptions := scalr.EnvironmentListOptions{} - envl, err := scalrClient.Environments.List(ctx, listOptions) - if err != nil { - log.Fatalf("Error retrieving environments: %v", err) - } - - for _, env := range envl.Items { - if env.Name == environmentName { - environmentID = &env.ID - break - } - } - if environmentID == nil { - log.Fatalf("Could not find environment with name: %s", environmentName) - return - } - - ws, err := scalrClient.Workspaces.Read(ctx, *environmentID, workspaceName) - - if err != nil { - log.Fatalf("Error retrieving workspace: %v", err) - } - - w, err := scalrClient.Workspaces.Update( - context.Background(), - ws.ID, - scalr.WorkspaceUpdateOptions{Name: scalr.String("renamed-out-of-band")}, - ) - if err != nil { - log.Fatalf("Could not rename the workspace out of band: %v", err) - } - - if w.Name != "renamed-out-of-band" { - log.Fatalf("Failed to rename the workspace out of band: %v", err) - } - } -} - func testAccCheckScalrWorkspaceAttributesUpdated( workspace *scalr.Workspace) resource.TestCheckFunc { return func(s *terraform.State) error { @@ -570,7 +451,7 @@ func testAccCheckScalrWorkspaceAttributesUpdated( func testAccCheckScalrWorkspaceProviderConfigurations( workspace *scalr.Workspace) resource.TestCheckFunc { return func(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) links, err := getProviderConfigurationWorkspaceLinks(ctx, scalrClient, workspace.ID) if err != nil { @@ -624,7 +505,7 @@ func testAccCheckScalrWorkspaceProviderConfigurations( func testAccCheckScalrWorkspaceProviderConfigurationsUpdated( workspace *scalr.Workspace) resource.TestCheckFunc { return func(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) links, err := getProviderConfigurationWorkspaceLinks(ctx, scalrClient, workspace.ID) if err != nil { @@ -677,7 +558,7 @@ func testAccCheckScalrWorkspaceProviderConfigurationsUpdated( } func testAccCheckScalrWorkspaceDestroy(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) for _, rs := range s.RootModule().Resources { if rs.Type != "scalr_workspace" { @@ -751,25 +632,6 @@ resource "scalr_workspace" "test" { }`) } -func testAccScalrWorkspaceRenamed(rInt int) string { - return fmt.Sprintf(testAccScalrWorkspaceCommonConfig, rInt, defaultAccount, ` -resource "scalr_workspace" "test" { - name = "renamed-out-of-band" - environment_id = scalr_environment.test.id - auto_apply = true - run_operation_timeout = 18 - auto_queue_runs = "always" - deletion_protection_enabled = false - hooks { - pre_init = "./scripts/pre-init.sh" - pre_plan = "./scripts/pre-plan.sh" - post_plan = "./scripts/post-plan.sh" - pre_apply = "./scripts/pre-apply.sh" - post_apply = "./scripts/post-apply.sh" - } -}`) -} - func testAccScalrWorkspaceUpdate(rInt int) string { return fmt.Sprintf(testAccScalrWorkspaceCommonConfig, rInt, defaultAccount, fmt.Sprintf(` diff --git a/internal/provider/tag_data_source.go b/internal/provider/tag_data_source.go new file mode 100644 index 00000000..d5767b3b --- /dev/null +++ b/internal/provider/tag_data_source.go @@ -0,0 +1,132 @@ +package provider + +import ( + "context" + "fmt" + + "github.com/hashicorp/terraform-plugin-framework-validators/datasourcevalidator" + "github.com/hashicorp/terraform-plugin-framework/datasource" + "github.com/hashicorp/terraform-plugin-framework/datasource/schema" + "github.com/hashicorp/terraform-plugin-framework/path" + "github.com/hashicorp/terraform-plugin-framework/schema/validator" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/scalr/go-scalr" + + "github.com/scalr/terraform-provider-scalr/internal/framework" + "github.com/scalr/terraform-provider-scalr/internal/framework/validation" +) + +// Compile-time interface checks +var ( + _ datasource.DataSource = &tagDataSource{} + _ datasource.DataSourceWithConfigure = &tagDataSource{} + _ datasource.DataSourceWithConfigValidators = &tagDataSource{} +) + +func newTagDataSource() datasource.DataSource { + return &tagDataSource{} +} + +// tagDataSource defines the data source implementation. +type tagDataSource struct { + framework.DataSourceWithScalrClient +} + +// tagDataSourceModel describes the data source data model. +type tagDataSourceModel struct { + Id types.String `tfsdk:"id"` + Name types.String `tfsdk:"name"` + AccountID types.String `tfsdk:"account_id"` +} + +func (d *tagDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_tag" +} + +func (d *tagDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) { + resp.Schema = schema.Schema{ + MarkdownDescription: "Retrieves information about a tag.", + + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + MarkdownDescription: "The identifier of the tag in the format `tag-`.", + Optional: true, + Computed: true, + Validators: []validator.String{ + validation.StringIsNotWhiteSpace(), + }, + }, + "name": schema.StringAttribute{ + MarkdownDescription: "The name of the tag.", + Optional: true, + Computed: true, + Validators: []validator.String{ + validation.StringIsNotWhiteSpace(), + }, + }, + "account_id": schema.StringAttribute{ + MarkdownDescription: "The ID of the Scalr account, in the format `acc-`.", + Optional: true, + Computed: true, + }, + }, + } +} + +func (d *tagDataSource) ConfigValidators(_ context.Context) []datasource.ConfigValidator { + return []datasource.ConfigValidator{ + datasourcevalidator.AtLeastOneOf( + path.MatchRoot("id"), + path.MatchRoot("name"), + ), + } +} + +func (d *tagDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { + var cfg tagDataSourceModel + + // Read Terraform configuration data into the model + resp.Diagnostics.Append(req.Config.Get(ctx, &cfg)...) + if resp.Diagnostics.HasError() { + return + } + + opts := scalr.TagListOptions{} + if !cfg.Id.IsNull() { + opts.Tag = cfg.Id.ValueStringPointer() + } + if !cfg.Name.IsNull() { + opts.Name = cfg.Name.ValueStringPointer() + } + + tags, err := d.Client.Tags.List(ctx, opts) + if err != nil { + resp.Diagnostics.AddError("Error retrieving tag", err.Error()) + return + } + + // Unlikely + if tags.TotalCount > 1 { + resp.Diagnostics.AddError( + "Error retrieving tag", + "Your query returned more than one result. Please try a more specific search criteria.", + ) + return + } + + if tags.TotalCount == 0 { + resp.Diagnostics.AddError( + "Error retrieving tag", + fmt.Sprintf("Could not find tag with ID '%s', name '%s'.", cfg.Id.ValueString(), cfg.Name.ValueString()), + ) + return + } + + tag := tags.Items[0] + + cfg.Id = types.StringValue(tag.ID) + cfg.Name = types.StringValue(tag.Name) + cfg.AccountID = types.StringValue(tag.Account.ID) + + resp.Diagnostics.Append(resp.State.Set(ctx, &cfg)...) +} diff --git a/internal/provider/tag_data_source_test.go b/internal/provider/tag_data_source_test.go new file mode 100644 index 00000000..84177355 --- /dev/null +++ b/internal/provider/tag_data_source_test.go @@ -0,0 +1,129 @@ +package provider + +import ( + "fmt" + "regexp" + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/acctest" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" +) + +func TestAccScalrTagDataSource_basic(t *testing.T) { + tagName := acctest.RandomWithPrefix("test-tag") + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + Steps: []resource.TestStep{ + { + Config: `data scalr_tag test {}`, + ExpectError: regexp.MustCompile(`At least one of these attributes must be configured: \[id,name]`), + }, + { + Config: `data scalr_tag test {id = ""}`, + ExpectError: regexp.MustCompile("Attribute id must not be empty"), + }, + { + Config: `data scalr_tag test {name = ""}`, + ExpectError: regexp.MustCompile("Attribute name must not be empty"), + }, + { + Config: testAccScalrTagDataSourceByIDConfig(tagName), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.scalr_tag.test", "id"), + resource.TestCheckResourceAttr("data.scalr_tag.test", "name", tagName), + resource.TestCheckResourceAttr("data.scalr_tag.test", "account_id", defaultAccount), + ), + }, + { + Config: testAccScalrTagDataSourceByNameConfig(tagName), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.scalr_tag.test", "id"), + resource.TestCheckResourceAttr("data.scalr_tag.test", "name", tagName), + resource.TestCheckResourceAttr("data.scalr_tag.test", "account_id", defaultAccount), + ), + }, + { + Config: testAccScalrTagDataSourceByIDAndNameConfig(tagName), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.scalr_tag.test", "id"), + resource.TestCheckResourceAttr("data.scalr_tag.test", "name", tagName), + resource.TestCheckResourceAttr("data.scalr_tag.test", "account_id", defaultAccount), + ), + }, + }, + }) +} + +func testAccScalrTagDataSourceByIDConfig(name string) string { + return fmt.Sprintf(` +resource scalr_tag test { + name = "%[1]s" + account_id = "%[2]s" +} + +data scalr_tag test { + id = scalr_tag.test.id + account_id = "%[2]s" +}`, name, defaultAccount) +} + +func testAccScalrTagDataSourceByNameConfig(name string) string { + return fmt.Sprintf(` +resource scalr_tag test { + name = "%[1]s" + account_id = "%[2]s" +} + +data scalr_tag test { + name = scalr_tag.test.name + account_id = "%[2]s" +}`, name, defaultAccount) +} + +func testAccScalrTagDataSourceByIDAndNameConfig(name string) string { + return fmt.Sprintf(` +resource scalr_tag test { + name = "%[1]s" + account_id = "%[2]s" +} + +data scalr_tag test { + id = scalr_tag.test.id + name = scalr_tag.test.name + account_id = "%[2]s" +}`, name, defaultAccount) +} + +func TestAccScalrTagDataSource_UpgradeFromSDK(t *testing.T) { + tagName := acctest.RandomWithPrefix("test-tag") + + resource.Test(t, resource.TestCase{ + Steps: []resource.TestStep{ + { + ExternalProviders: map[string]resource.ExternalProvider{ + "scalr": { + Source: "registry.scalr.io/scalr/scalr", + VersionConstraint: "<=2.2.0", + }, + }, + Config: testAccScalrTagDataSourceByIDConfig(tagName), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.scalr_tag.test", "id"), + resource.TestCheckResourceAttr("data.scalr_tag.test", "name", tagName), + resource.TestCheckResourceAttr("data.scalr_tag.test", "account_id", defaultAccount), + ), + }, + { + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + Config: testAccScalrTagDataSourceByIDConfig(tagName), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.scalr_tag.test", "id"), + resource.TestCheckResourceAttr("data.scalr_tag.test", "name", tagName), + resource.TestCheckResourceAttr("data.scalr_tag.test", "account_id", defaultAccount), + ), + }, + }, + }) +} diff --git a/internal/provider/tag_resource.go b/internal/provider/tag_resource.go new file mode 100644 index 00000000..93dce349 --- /dev/null +++ b/internal/provider/tag_resource.go @@ -0,0 +1,192 @@ +package provider + +import ( + "context" + "errors" + + "github.com/hashicorp/terraform-plugin-framework/path" + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" + "github.com/hashicorp/terraform-plugin-framework/schema/validator" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/scalr/go-scalr" + + "github.com/scalr/terraform-provider-scalr/internal/framework" + "github.com/scalr/terraform-provider-scalr/internal/framework/defaults" + "github.com/scalr/terraform-provider-scalr/internal/framework/validation" +) + +// Compile-time interface checks +var ( + _ resource.Resource = &tagResource{} + _ resource.ResourceWithConfigure = &tagResource{} + _ resource.ResourceWithConfigValidators = &tagResource{} + _ resource.ResourceWithImportState = &tagResource{} +) + +func newTagResource() resource.Resource { + return &tagResource{} +} + +// tagResource defines the resource implementation. +type tagResource struct { + framework.ResourceWithScalrClient +} + +// tagResourceModel describes the resource data model. +type tagResourceModel struct { + Id types.String `tfsdk:"id"` + Name types.String `tfsdk:"name"` + AccountID types.String `tfsdk:"account_id"` +} + +func (r *tagResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_tag" +} + +func (r *tagResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) { + resp.Schema = schema.Schema{ + MarkdownDescription: "Manages the state of tags in Scalr.", + + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + MarkdownDescription: "The ID of this resource.", + Computed: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.UseStateForUnknown(), + }, + }, + "name": schema.StringAttribute{ + MarkdownDescription: "Name of the tag.", + Required: true, + Validators: []validator.String{ + validation.StringIsNotWhiteSpace(), + }, + }, + "account_id": schema.StringAttribute{ + MarkdownDescription: "ID of the account, in the format `acc-`.", + Optional: true, + Computed: true, + Default: defaults.AccountIDRequired(), + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplace(), + }, + }, + }, + } +} + +func (r *tagResource) ConfigValidators(_ context.Context) []resource.ConfigValidator { + return []resource.ConfigValidator{} +} + +func (r *tagResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var plan tagResourceModel + + // Read plan data + resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) + if resp.Diagnostics.HasError() { + return + } + + opts := scalr.TagCreateOptions{ + Name: plan.Name.ValueStringPointer(), + Account: &scalr.Account{ID: plan.AccountID.ValueString()}, + } + tag, err := r.Client.Tags.Create(ctx, opts) + if err != nil { + resp.Diagnostics.AddError("Error creating tag", err.Error()) + return + } + + plan.Id = types.StringValue(tag.ID) + plan.Name = types.StringValue(tag.Name) + plan.AccountID = types.StringValue(tag.Account.ID) + + // Set state to fully populated data + resp.Diagnostics.Append(resp.State.Set(ctx, plan)...) + if resp.Diagnostics.HasError() { + return + } +} + +func (r *tagResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + // Get current state + var state tagResourceModel + resp.Diagnostics.Append(req.State.Get(ctx, &state)...) + if resp.Diagnostics.HasError() { + return + } + + // Get refreshed resource state from API + tag, err := r.Client.Tags.Read(ctx, state.Id.ValueString()) + if err != nil { + if errors.Is(err, scalr.ErrResourceNotFound) { + resp.State.RemoveResource(ctx) + return + } + resp.Diagnostics.AddError("Error retrieving tag", err.Error()) + return + } + + // Overwrite attributes with refreshed values + state.Name = types.StringValue(tag.Name) + state.AccountID = types.StringValue(tag.Account.ID) + + // Set refreshed state + resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) + if resp.Diagnostics.HasError() { + return + } +} + +func (r *tagResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + // Read plan data + var plan tagResourceModel + resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) + if resp.Diagnostics.HasError() { + return + } + + opts := scalr.TagUpdateOptions{ + Name: plan.Name.ValueStringPointer(), + } + + // Update existing resource + tag, err := r.Client.Tags.Update(ctx, plan.Id.ValueString(), opts) + if err != nil { + resp.Diagnostics.AddError("Error updating tag", err.Error()) + return + } + + // Overwrite attributes with refreshed values + plan.Name = types.StringValue(tag.Name) + plan.AccountID = types.StringValue(tag.Account.ID) + + // Set refreshed state + resp.Diagnostics.Append(resp.State.Set(ctx, plan)...) + if resp.Diagnostics.HasError() { + return + } +} + +func (r *tagResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + // Get current state + var state tagResourceModel + resp.Diagnostics.Append(req.State.Get(ctx, &state)...) + if resp.Diagnostics.HasError() { + return + } + + err := r.Client.Tags.Delete(ctx, state.Id.ValueString()) + if err != nil && !errors.Is(err, scalr.ErrResourceNotFound) { + resp.Diagnostics.AddError("Error deleting tag", err.Error()) + return + } +} + +func (r *tagResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { + resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp) +} diff --git a/internal/provider/tag_resource_test.go b/internal/provider/tag_resource_test.go new file mode 100644 index 00000000..ee3b30e5 --- /dev/null +++ b/internal/provider/tag_resource_test.go @@ -0,0 +1,179 @@ +package provider + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/acctest" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/plancheck" + "github.com/hashicorp/terraform-plugin-testing/terraform" + "github.com/scalr/go-scalr" +) + +func TestAccScalrTag_basic(t *testing.T) { + tagName := acctest.RandomWithPrefix("test-tag") + tag := &scalr.Tag{} + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrTagDestroy, + Steps: []resource.TestStep{ + { + Config: testAccScalrTagBasic(tagName), + Check: resource.ComposeTestCheckFunc( + testAccCheckScalrTagExists("scalr_tag.test", tag), + resource.TestCheckResourceAttr("scalr_tag.test", "name", tagName), + resource.TestCheckResourceAttr("scalr_tag.test", "account_id", defaultAccount), + ), + }, + }, + }) +} + +func TestAccScalrTag_import(t *testing.T) { + tagName := acctest.RandomWithPrefix("test-tag") + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrTagDestroy, + Steps: []resource.TestStep{ + { + Config: testAccScalrTagBasic(tagName), + }, + + { + ResourceName: "scalr_tag.test", + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccScalrTag_update(t *testing.T) { + tagName := acctest.RandomWithPrefix("test-tag") + tagNameUpdated := acctest.RandomWithPrefix("test-tag") + tag := &scalr.Tag{} + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + CheckDestroy: testAccCheckScalrTagDestroy, + Steps: []resource.TestStep{ + { + Config: testAccScalrTagBasic(tagName), + Check: resource.ComposeTestCheckFunc( + testAccCheckScalrTagExists("scalr_tag.test", tag), + resource.TestCheckResourceAttr("scalr_tag.test", "name", tagName), + resource.TestCheckResourceAttr("scalr_tag.test", "account_id", defaultAccount), + ), + }, + + { + Config: testAccScalrTagUpdate(tagNameUpdated), + Check: resource.ComposeTestCheckFunc( + testAccCheckScalrTagExists("scalr_tag.test", tag), + resource.TestCheckResourceAttr("scalr_tag.test", "name", tagNameUpdated), + resource.TestCheckResourceAttr("scalr_tag.test", "account_id", defaultAccount), + ), + }, + }, + }) +} + +func testAccScalrTagBasic(name string) string { + return fmt.Sprintf(` +resource scalr_tag test { + name = "%[1]s" + account_id = "%[2]s" +}`, name, defaultAccount) +} + +func testAccScalrTagUpdate(name string) string { + return fmt.Sprintf(` +resource scalr_tag test { + name = "%[1]s" + account_id = "%[2]s" +}`, name, defaultAccount) +} + +func testAccCheckScalrTagExists(resId string, tag *scalr.Tag) resource.TestCheckFunc { + return func(s *terraform.State) error { + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) + + rs, ok := s.RootModule().Resources[resId] + if !ok { + return fmt.Errorf("Not found: %s", resId) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No instance ID is set") + } + + // Get the tag + t, err := scalrClient.Tags.Read(ctx, rs.Primary.ID) + if err != nil { + return err + } + + *tag = *t + + return nil + } +} + +func testAccCheckScalrTagDestroy(s *terraform.State) error { + scalrClient := testAccProviderSDK.Meta().(*scalr.Client) + + for _, rs := range s.RootModule().Resources { + if rs.Type != "scalr_tag" { + continue + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No instance ID is set") + } + + _, err := scalrClient.Tags.Read(ctx, rs.Primary.ID) + if err == nil { + return fmt.Errorf("Tag %s still exists", rs.Primary.ID) + } + } + + return nil +} + +func TestAccScalrTag_UpgradeFromSDK(t *testing.T) { + tagName := acctest.RandomWithPrefix("test-tag") + + resource.Test(t, resource.TestCase{ + Steps: []resource.TestStep{ + { + ExternalProviders: map[string]resource.ExternalProvider{ + "scalr": { + Source: "registry.scalr.io/scalr/scalr", + VersionConstraint: "<=2.2.0", + }, + }, + Config: testAccScalrTagBasic(tagName), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("scalr_tag.test", "id"), + resource.TestCheckResourceAttr("scalr_tag.test", "name", tagName), + resource.TestCheckResourceAttr("scalr_tag.test", "account_id", defaultAccount), + ), + }, + { + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + Config: testAccScalrTagBasic(tagName), + ConfigPlanChecks: resource.ConfigPlanChecks{ + PreApply: []plancheck.PlanCheck{ + plancheck.ExpectEmptyPlan(), + }, + }, + }, + }, + }) +} diff --git a/scalr/testing.go b/internal/provider/testing.go similarity index 98% rename from scalr/testing.go rename to internal/provider/testing.go index 172c710c..1d5bc515 100644 --- a/scalr/testing.go +++ b/internal/provider/testing.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "fmt" diff --git a/scalr/workspace_helpers.go b/internal/provider/workspace_helpers.go similarity index 98% rename from scalr/workspace_helpers.go rename to internal/provider/workspace_helpers.go index 878122d6..3efef315 100644 --- a/scalr/workspace_helpers.go +++ b/internal/provider/workspace_helpers.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "context" diff --git a/scalr/workspace_helpers_test.go b/internal/provider/workspace_helpers_test.go similarity index 99% rename from scalr/workspace_helpers_test.go rename to internal/provider/workspace_helpers_test.go index 3d69b80c..5cf18a3c 100644 --- a/scalr/workspace_helpers_test.go +++ b/internal/provider/workspace_helpers_test.go @@ -1,4 +1,4 @@ -package scalr +package provider import ( "context" diff --git a/main.go b/main.go index 03f30665..94979324 100644 --- a/main.go +++ b/main.go @@ -12,7 +12,6 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/scalr/terraform-provider-scalr/internal/provider" - "github.com/scalr/terraform-provider-scalr/scalr" "github.com/scalr/terraform-provider-scalr/version" ) @@ -46,7 +45,7 @@ func main() { // New provider implementation with Terraform Plugin Framework providerserver.NewProtocol5(provider.New(version.ProviderVersion)()), // Classic provider implementation with Terraform Plugin SDK - scalr.Provider().GRPCProvider, + provider.Provider(version.ProviderVersion).GRPCProvider, } muxServer, err := tf5muxserver.NewMuxServer(ctx, providers...) diff --git a/scalr/data_source_scalr_tag.go b/scalr/data_source_scalr_tag.go deleted file mode 100644 index ee214c21..00000000 --- a/scalr/data_source_scalr_tag.go +++ /dev/null @@ -1,83 +0,0 @@ -package scalr - -import ( - "context" - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" - "github.com/scalr/go-scalr" - "log" -) - -func dataSourceScalrTag() *schema.Resource { - return &schema.Resource{ - Description: "Retrieves information about a tag.", - ReadContext: dataSourceScalrTagRead, - Schema: map[string]*schema.Schema{ - "id": { - Description: "The identifier of the tag in the format `tag-`.", - Type: schema.TypeString, - Optional: true, - Computed: true, - ValidateFunc: validation.StringIsNotWhiteSpace, - AtLeastOneOf: []string{"name"}, - }, - "name": { - Description: "The name of the tag.", - Type: schema.TypeString, - Optional: true, - Computed: true, - ValidateFunc: validation.StringIsNotWhiteSpace, - }, - "account_id": { - Description: "The ID of the Scalr account, in the format `acc-`.", - Type: schema.TypeString, - Optional: true, - Computed: true, - DefaultFunc: scalrAccountIDDefaultFunc, - }, - }, - } -} - -func dataSourceScalrTagRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - scalrClient := meta.(*scalr.Client) - - tagID := d.Get("id").(string) - name := d.Get("name").(string) - accountID := d.Get("account_id").(string) - - options := scalr.TagListOptions{ - Account: scalr.String(accountID), - } - - if tagID != "" { - options.Tag = scalr.String(tagID) - } - - if name != "" { - options.Name = scalr.String(name) - } - - log.Printf("[DEBUG] Read tag with ID '%s', name '%s', and account_id '%s'", tagID, name, accountID) - tags, err := scalrClient.Tags.List(ctx, options) - if err != nil { - return diag.Errorf("Error retrieving tag: %v", err) - } - - // Unlikely - if tags.TotalCount > 1 { - return diag.Errorf("Your query returned more than one result. Please try a more specific search criteria.") - } - - if tags.TotalCount == 0 { - return diag.Errorf("Could not find tag with ID '%s', name '%s', and account_id '%s'", tagID, name, accountID) - } - - tag := tags.Items[0] - - _ = d.Set("name", tag.Name) - d.SetId(tag.ID) - - return nil -} diff --git a/scalr/data_source_scalr_tag_test.go b/scalr/data_source_scalr_tag_test.go deleted file mode 100644 index 0ba93c07..00000000 --- a/scalr/data_source_scalr_tag_test.go +++ /dev/null @@ -1,98 +0,0 @@ -package scalr - -import ( - "fmt" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "regexp" - "testing" -) - -func TestAccScalrTagDataSource_basic(t *testing.T) { - rInt := GetRandomInteger() - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - Steps: []resource.TestStep{ - { - Config: `data scalr_tag test {}`, - ExpectError: regexp.MustCompile("\"id\": one of `id,name` must be specified"), - PlanOnly: true, - }, - { - Config: `data scalr_tag test {id = ""}`, - ExpectError: regexp.MustCompile("expected \"id\" to not be an empty string or whitespace"), - PlanOnly: true, - }, - { - Config: `data scalr_tag test {name = ""}`, - ExpectError: regexp.MustCompile("expected \"name\" to not be an empty string or whitespace"), - PlanOnly: true, - }, - { - Config: testAccScalrTagDataSourceByIDConfig(rInt), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrSet("data.scalr_tag.test", "id"), - resource.TestCheckResourceAttr("data.scalr_tag.test", "name", fmt.Sprintf("test-tag-%d", rInt)), - resource.TestCheckResourceAttr("data.scalr_tag.test", "account_id", defaultAccount), - ), - }, - { - Config: testAccScalrTagDataSourceByNameConfig(rInt), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrSet("data.scalr_tag.test", "id"), - resource.TestCheckResourceAttr("data.scalr_tag.test", "name", fmt.Sprintf("test-tag-%d", rInt)), - resource.TestCheckResourceAttr("data.scalr_tag.test", "account_id", defaultAccount), - ), - }, - { - Config: testAccScalrTagDataSourceByIDAndNameConfig(rInt), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrSet("data.scalr_tag.test", "id"), - resource.TestCheckResourceAttr("data.scalr_tag.test", "name", fmt.Sprintf("test-tag-%d", rInt)), - resource.TestCheckResourceAttr("data.scalr_tag.test", "account_id", defaultAccount), - ), - }, - }, - }) -} - -func testAccScalrTagDataSourceByIDConfig(rInt int) string { - return fmt.Sprintf(` -resource scalr_tag test { - name = "test-tag-%[1]d" - account_id = "%[2]s" -} - -data scalr_tag test { - id = scalr_tag.test.id - account_id = "%[2]s" -}`, rInt, defaultAccount) -} - -func testAccScalrTagDataSourceByNameConfig(rInt int) string { - return fmt.Sprintf(` -resource scalr_tag test { - name = "test-tag-%[1]d" - account_id = "%[2]s" -} - -data scalr_tag test { - name = scalr_tag.test.name - account_id = "%[2]s" -}`, rInt, defaultAccount) -} - -func testAccScalrTagDataSourceByIDAndNameConfig(rInt int) string { - return fmt.Sprintf(` -resource scalr_tag test { - name = "test-tag-%[1]d" - account_id = "%[2]s" -} - -data scalr_tag test { - id = scalr_tag.test.id - name = scalr_tag.test.name - account_id = "%[2]s" -}`, rInt, defaultAccount) -} diff --git a/scalr/resource_scalr_tag.go b/scalr/resource_scalr_tag.go deleted file mode 100644 index 487272ba..00000000 --- a/scalr/resource_scalr_tag.go +++ /dev/null @@ -1,119 +0,0 @@ -package scalr - -import ( - "context" - "errors" - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/scalr/go-scalr" - "log" -) - -func resourceScalrTag() *schema.Resource { - return &schema.Resource{ - Description: "Manages the state of tags in Scalr.", - CreateContext: resourceScalrTagCreate, - ReadContext: resourceScalrTagRead, - UpdateContext: resourceScalrTagUpdate, - DeleteContext: resourceScalrTagDelete, - Importer: &schema.ResourceImporter{ - StateContext: schema.ImportStatePassthroughContext, - }, - - Schema: map[string]*schema.Schema{ - "name": { - Description: "Name of the tag.", - Type: schema.TypeString, - Required: true, - }, - "account_id": { - Description: "ID of the account, in the format `acc-`.", - Type: schema.TypeString, - Optional: true, - Computed: true, - DefaultFunc: scalrAccountIDDefaultFunc, - ForceNew: true, - }, - }, - } -} - -func resourceScalrTagRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - scalrClient := meta.(*scalr.Client) - id := d.Id() - - log.Printf("[DEBUG] Read tag: %s", id) - tag, err := scalrClient.Tags.Read(ctx, id) - if err != nil { - if errors.Is(err, scalr.ErrResourceNotFound) { - log.Printf("[DEBUG] Tag %s not found", id) - d.SetId("") - return nil - } - return diag.Errorf("Error reading tag %s: %v", id, err) - } - - // Update config. - _ = d.Set("name", tag.Name) - _ = d.Set("account_id", tag.Account.ID) - - return nil -} - -func resourceScalrTagCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - scalrClient := meta.(*scalr.Client) - - // Get the name and account_id. - name := d.Get("name").(string) - accountID := d.Get("account_id").(string) - - options := scalr.TagCreateOptions{ - Name: scalr.String(name), - Account: &scalr.Account{ID: accountID}, - } - - log.Printf("[DEBUG] Create tag %s for account %s", name, accountID) - tag, err := scalrClient.Tags.Create(ctx, options) - if err != nil { - return diag.Errorf( - "Error creating tag %s for account %s: %v", name, accountID, err) - } - d.SetId(tag.ID) - - return resourceScalrTagRead(ctx, d, meta) -} - -func resourceScalrTagUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - scalrClient := meta.(*scalr.Client) - - id := d.Id() - if d.HasChange("name") { - name := d.Get("name").(string) - opts := scalr.TagUpdateOptions{ - Name: scalr.String(name), - } - log.Printf("[DEBUG] Update tag %s", id) - _, err := scalrClient.Tags.Update(ctx, id, opts) - if err != nil { - return diag.Errorf("error updating tag %s: %v", id, err) - } - } - - return resourceScalrTagRead(ctx, d, meta) -} - -func resourceScalrTagDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - scalrClient := meta.(*scalr.Client) - id := d.Id() - - log.Printf("[DEBUG] Delete tag %s", id) - err := scalrClient.Tags.Delete(ctx, id) - if err != nil { - if errors.Is(err, scalr.ErrResourceNotFound) { - return nil - } - return diag.Errorf("Error deleting tag %s: %v", id, err) - } - - return nil -} diff --git a/scalr/resource_scalr_tag_test.go b/scalr/resource_scalr_tag_test.go deleted file mode 100644 index 00fd3b16..00000000 --- a/scalr/resource_scalr_tag_test.go +++ /dev/null @@ -1,206 +0,0 @@ -package scalr - -import ( - "context" - "fmt" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" - "github.com/scalr/go-scalr" - "log" - "testing" -) - -func TestAccScalrTag_basic(t *testing.T) { - tag := &scalr.Tag{} - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrTagDestroy, - Steps: []resource.TestStep{ - { - Config: testAccScalrTagBasic(), - Check: resource.ComposeTestCheckFunc( - testAccCheckScalrTagExists("scalr_tag.test", tag), - resource.TestCheckResourceAttr("scalr_tag.test", "name", "test-tag-name"), - resource.TestCheckResourceAttr("scalr_tag.test", "account_id", defaultAccount), - ), - }, - }, - }) -} - -func TestAccScalrTag_import(t *testing.T) { - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrTagDestroy, - Steps: []resource.TestStep{ - { - Config: testAccScalrTagBasic(), - }, - - { - ResourceName: "scalr_tag.test", - ImportState: true, - ImportStateVerify: true, - }, - }, - }) -} - -func TestAccScalrTag_update(t *testing.T) { - tag := &scalr.Tag{} - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrTagDestroy, - Steps: []resource.TestStep{ - { - Config: testAccScalrTagBasic(), - Check: resource.ComposeTestCheckFunc( - testAccCheckScalrTagExists("scalr_tag.test", tag), - resource.TestCheckResourceAttr("scalr_tag.test", "name", "test-tag-name"), - resource.TestCheckResourceAttr("scalr_tag.test", "account_id", defaultAccount), - ), - }, - - { - Config: testAccScalrTagUpdate(), - Check: resource.ComposeTestCheckFunc( - testAccCheckScalrTagExists("scalr_tag.test", tag), - resource.TestCheckResourceAttr("scalr_tag.test", "name", "test-tag-name-updated"), - resource.TestCheckResourceAttr("scalr_tag.test", "account_id", defaultAccount), - ), - }, - }, - }) -} - -func TestAccScalrTag_renamed(t *testing.T) { - tag := &scalr.Tag{} - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckScalrTagDestroy, - Steps: []resource.TestStep{ - { - Config: testAccScalrTagBasic(), - Check: resource.ComposeTestCheckFunc( - testAccCheckScalrTagExists("scalr_tag.test", tag), - resource.TestCheckResourceAttr("scalr_tag.test", "name", "test-tag-name"), - resource.TestCheckResourceAttr("scalr_tag.test", "account_id", defaultAccount), - ), - }, - - { - PreConfig: testAccCheckScalrTagRename(tag), - Config: testAccScalrTagRenamed(), - PlanOnly: true, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("scalr_tag.test", "name", "renamed-outside-terraform"), - resource.TestCheckResourceAttr("scalr_tag.test", "account_id", defaultAccount), - ), - }, - }, - }) -} - -func testAccScalrTagBasic() string { - return fmt.Sprintf(` -resource scalr_tag test { - name = "test-tag-name" - account_id = "%s" -}`, defaultAccount) -} - -func testAccScalrTagUpdate() string { - return fmt.Sprintf(` -resource scalr_tag test { - name = "test-tag-name-updated" - account_id = "%s" -}`, defaultAccount) -} - -func testAccScalrTagRenamed() string { - return fmt.Sprintf(` -resource scalr_tag test { - name = "renamed-outside-terraform" - account_id = "%s" -}`, defaultAccount) -} - -func testAccCheckScalrTagRename(tag *scalr.Tag) func() { - return func() { - scalrClient := testAccProvider.Meta().(*scalr.Client) - - t, err := scalrClient.Tags.Read(ctx, tag.ID) - - if err != nil { - log.Fatalf("Error retrieving tag: %v", err) - } - - t, err = scalrClient.Tags.Update( - context.Background(), - t.ID, - scalr.TagUpdateOptions{Name: scalr.String("renamed-outside-terraform")}, - ) - - if err != nil { - log.Fatalf("Could not rename the tag outside of terraform: %v", err) - } - - if t.Name != "renamed-outside-terraform" { - log.Fatalf("Failed to rename the tag outside of terraform: %v", err) - } - } -} - -func testAccCheckScalrTagExists(resId string, tag *scalr.Tag) resource.TestCheckFunc { - return func(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) - - rs, ok := s.RootModule().Resources[resId] - if !ok { - return fmt.Errorf("Not found: %s", resId) - } - - if rs.Primary.ID == "" { - return fmt.Errorf("No instance ID is set") - } - - // Get the tag - t, err := scalrClient.Tags.Read(ctx, rs.Primary.ID) - if err != nil { - return err - } - - *tag = *t - - return nil - } -} - -func testAccCheckScalrTagDestroy(s *terraform.State) error { - scalrClient := testAccProvider.Meta().(*scalr.Client) - - for _, rs := range s.RootModule().Resources { - if rs.Type != "scalr_tag" { - continue - } - - if rs.Primary.ID == "" { - return fmt.Errorf("No instance ID is set") - } - - _, err := scalrClient.Tags.Read(ctx, rs.Primary.ID) - if err == nil { - return fmt.Errorf("Tag %s still exists", rs.Primary.ID) - } - } - - return nil -} diff --git a/skaff/README.md b/skaff/README.md new file mode 100644 index 00000000..931f6e0e --- /dev/null +++ b/skaff/README.md @@ -0,0 +1,46 @@ +# skaff + +A tool that helps to add new resources and data sources to the provider. +Generates the necessary boilerplate code from templates. + +## Usage + +The name for new resource or data source should be given in snake_case, lowercase, +as it will appear in Terraform configuration (without 'scalr_' provider prefix). + +For example: `agent_pool`. + +### From project's makefile + +Makefile contains convenient targets to skaff: + +```bash +make resource name=agent_pool +``` + +```bash +make datasource name=agent_pool +``` + +### Run the tool directly + +```bash +cd skaff +go run cmd/main.go -type=resource -name=agent_pool +``` + +```bash +cd skaff +go run cmd/main.go -type=data_source -name=agent_pool +``` + +## What's next + +Review the generated code carefully and make necessary adjustments. +The tool gives a minimal, simple but full-featured code to start with. +Templates may be updated and improved in the future. + +Please note that the generated code is based on the terraform-provider-framework library only, +no SDKv2 imports should be used. + +Don't forget to add new resource or data source to the provider's `Resources` or `DataSources` functions respectively. diff --git a/skaff/cmd/main.go b/skaff/cmd/main.go new file mode 100644 index 00000000..80e55d6c --- /dev/null +++ b/skaff/cmd/main.go @@ -0,0 +1,21 @@ +package main + +import ( + "flag" + "log" + + "github.com/scalr/terraform-provider-scalr/skaff" +) + +func main() { + t := flag.String("type", "", "Type of scaffolding to create.") + n := flag.String( + "name", "", "A name in snake case as it will appear in configuration (e.g., agent_pool).", + ) + flag.Parse() + + err := skaff.Generate(*t, *n) + if err != nil { + log.Fatal(err) + } +} diff --git a/skaff/generator.go b/skaff/generator.go new file mode 100644 index 00000000..34270015 --- /dev/null +++ b/skaff/generator.go @@ -0,0 +1,73 @@ +package skaff + +import ( + "errors" + "fmt" + "log" + "os" + "path/filepath" + "strings" + "text/template" + + "github.com/iancoleman/strcase" +) + +const ( + typeResource = "resource" + typeDatasource = "data_source" +) + +var funcMap = template.FuncMap{ + "camel": strcase.ToCamel, + "lowerCamel": strcase.ToLowerCamel, + "kebab": strcase.ToKebab, +} + +func Generate(t, n string) error { + if t != typeResource && t != typeDatasource { + return fmt.Errorf("invalid type. Must be one of: %s, %s", typeResource, typeDatasource) + } + + if n == "" { + return errors.New("name cannot be empty") + } + + if strings.ToLower(strcase.ToSnake(n)) != n { + return errors.New("name must be in snake_case lowercase") + } + + data := struct { + Name string + }{ + Name: n, + } + + err := writeTemplate(t+".tmpl", fmt.Sprintf("%s_%s.go", n, t), data) + if err != nil { + return err + } + + return writeTemplate(t+"_test.tmpl", fmt.Sprintf("%s_%s_test.go", n, t), data) +} + +func writeTemplate(tmplName, fileName string, data any) error { + tmpl, err := template.New(tmplName).Funcs(funcMap).ParseFiles("templates/" + tmplName) + if err != nil { + return err + } + + out := filepath.Join("../internal/provider", fileName) + f, err := os.Create(out) + if err != nil { + return err + } + defer f.Close() + + err = tmpl.Execute(f, data) + if err != nil { + return err + } + + log.Println("Created", fileName) + return nil +} diff --git a/skaff/go.mod b/skaff/go.mod new file mode 100644 index 00000000..7d65362c --- /dev/null +++ b/skaff/go.mod @@ -0,0 +1,5 @@ +go 1.23.3 + +module github.com/scalr/terraform-provider-scalr/skaff + +require github.com/iancoleman/strcase v0.3.0 diff --git a/skaff/go.sum b/skaff/go.sum new file mode 100644 index 00000000..6261b6ac --- /dev/null +++ b/skaff/go.sum @@ -0,0 +1,2 @@ +github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI= +github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho= diff --git a/skaff/templates/data_source.tmpl b/skaff/templates/data_source.tmpl new file mode 100644 index 00000000..a6ca8d98 --- /dev/null +++ b/skaff/templates/data_source.tmpl @@ -0,0 +1,132 @@ +package provider + +import ( + "context" + "fmt" + + "github.com/hashicorp/terraform-plugin-framework-validators/datasourcevalidator" + "github.com/hashicorp/terraform-plugin-framework/datasource" + "github.com/hashicorp/terraform-plugin-framework/datasource/schema" + "github.com/hashicorp/terraform-plugin-framework/path" + "github.com/hashicorp/terraform-plugin-framework/schema/validator" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/scalr/go-scalr" + + "github.com/scalr/terraform-provider-scalr/internal/framework" + "github.com/scalr/terraform-provider-scalr/internal/framework/validation" +) + +// Compile-time interface checks +var ( + _ datasource.DataSource = &{{ .Name | lowerCamel }}DataSource{} + _ datasource.DataSourceWithConfigure = &{{ .Name | lowerCamel }}DataSource{} + _ datasource.DataSourceWithConfigValidators = &{{ .Name | lowerCamel }}DataSource{} +) + +func new{{ .Name | camel }}DataSource() datasource.DataSource { + return &{{ .Name | lowerCamel }}DataSource{} +} + +// {{ .Name | lowerCamel }}DataSource defines the data source implementation. +type {{ .Name | lowerCamel }}DataSource struct { + framework.DataSourceWithScalrClient +} + +// {{ .Name | lowerCamel }}DataSourceModel describes the data source data model. +type {{ .Name | lowerCamel }}DataSourceModel struct { + Id types.String `tfsdk:"id"` + Name types.String `tfsdk:"name"` + AccountID types.String `tfsdk:"account_id"` +} + +func (d *{{ .Name | lowerCamel }}DataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_{{ .Name }}" +} + +func (d *{{ .Name | lowerCamel }}DataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) { + resp.Schema = schema.Schema{ + MarkdownDescription: "Retrieves information about {{ .Name }}.", + + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + MarkdownDescription: "The identifier of the {{ .Name }}.", + Optional: true, + Computed: true, + Validators: []validator.String{ + validation.StringIsNotWhiteSpace(), + }, + }, + "name": schema.StringAttribute{ + MarkdownDescription: "The name of the {{ .Name }}.", + Optional: true, + Computed: true, + Validators: []validator.String{ + validation.StringIsNotWhiteSpace(), + }, + }, + "account_id": schema.StringAttribute{ + MarkdownDescription: "The ID of the Scalr account, in the format `acc-`.", + Optional: true, + Computed: true, + }, + }, + } +} + +func (d *{{ .Name | lowerCamel }}DataSource) ConfigValidators(_ context.Context) []datasource.ConfigValidator { + return []datasource.ConfigValidator{ + datasourcevalidator.AtLeastOneOf( + path.MatchRoot("id"), + path.MatchRoot("name"), + ), + } +} + +func (d *{{ .Name | lowerCamel }}DataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { + var cfg {{ .Name | lowerCamel }}DataSourceModel + + // Read Terraform configuration data into the model + resp.Diagnostics.Append(req.Config.Get(ctx, &cfg)...) + if resp.Diagnostics.HasError() { + return + } + + opts := scalr.{{ .Name | camel }}ListOptions{} + if !cfg.Id.IsNull() { + opts.{{ .Name | camel }} = cfg.Id.ValueStringPointer() + } + if !cfg.Name.IsNull() { + opts.Name = cfg.Name.ValueStringPointer() + } + + {{ .Name | lowerCamel }}s, err := d.Client.{{ .Name | camel }}s.List(ctx, opts) + if err != nil { + resp.Diagnostics.AddError("Error retrieving {{ .Name }}", err.Error()) + return + } + + // Unlikely + if {{ .Name | lowerCamel }}s.TotalCount > 1 { + resp.Diagnostics.AddError( + "Error retrieving {{ .Name }}", + "Your query returned more than one result. Please try a more specific search criteria.", + ) + return + } + + if {{ .Name | lowerCamel }}s.TotalCount == 0 { + resp.Diagnostics.AddError( + "Error retrieving {{ .Name }}", + fmt.Sprintf("Could not find {{ .Name }} with ID '%s', name '%s'.", cfg.Id.ValueString(), cfg.Name.ValueString()), + ) + return + } + + {{ .Name | lowerCamel }} := {{ .Name | lowerCamel }}s.Items[0] + + cfg.Id = types.StringValue({{ .Name | lowerCamel }}.ID) + cfg.Name = types.StringValue({{ .Name | lowerCamel }}.Name) + cfg.AccountID = types.StringValue({{ .Name | lowerCamel }}.Account.ID) + + resp.Diagnostics.Append(resp.State.Set(ctx, &cfg)...) +} diff --git a/skaff/templates/data_source_test.tmpl b/skaff/templates/data_source_test.tmpl new file mode 100644 index 00000000..d331f081 --- /dev/null +++ b/skaff/templates/data_source_test.tmpl @@ -0,0 +1,97 @@ +package provider + +import ( + "fmt" + "regexp" + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/acctest" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" +) + +func TestAccScalr{{ .Name | camel }}DataSource_basic(t *testing.T) { + {{ .Name | lowerCamel }}Name := acctest.RandomWithPrefix("test-{{ .Name | kebab }}") + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV5ProviderFactories: protoV5ProviderFactories(t), + Steps: []resource.TestStep{ + { + Config: `data scalr_{{ .Name }} test {}`, + ExpectError: regexp.MustCompile(`At least one of these attributes must be configured: \[id,name]`), + }, + { + Config: `data scalr_{{ .Name }} test {id = ""}`, + ExpectError: regexp.MustCompile("Attribute id must not be empty"), + }, + { + Config: `data scalr_{{ .Name }} test {name = ""}`, + ExpectError: regexp.MustCompile("Attribute name must not be empty"), + }, + { + Config: testAccScalr{{ .Name | camel }}DataSourceByIDConfig({{ .Name | lowerCamel }}Name), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.scalr_{{ .Name }}.test", "id"), + resource.TestCheckResourceAttr("data.scalr_{{ .Name }}.test", "name", {{ .Name | lowerCamel }}Name), + resource.TestCheckResourceAttr("data.scalr_{{ .Name }}.test", "account_id", defaultAccount), + ), + }, + { + Config: testAccScalr{{ .Name | camel }}DataSourceByNameConfig({{ .Name | lowerCamel }}Name), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.scalr_{{ .Name }}.test", "id"), + resource.TestCheckResourceAttr("data.scalr_{{ .Name }}.test", "name", {{ .Name | lowerCamel }}Name), + resource.TestCheckResourceAttr("data.scalr_{{ .Name }}.test", "account_id", defaultAccount), + ), + }, + { + Config: testAccScalr{{ .Name | camel }}DataSourceByIDAndNameConfig({{ .Name | lowerCamel }}Name), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.scalr_{{ .Name }}.test", "id"), + resource.TestCheckResourceAttr("data.scalr_{{ .Name }}.test", "name", {{ .Name | lowerCamel }}Name), + resource.TestCheckResourceAttr("data.scalr_{{ .Name }}.test", "account_id", defaultAccount), + ), + }, + }, + }) +} + +func testAccScalr{{ .Name | camel }}DataSourceByIDConfig(name string) string { + return fmt.Sprintf(` +resource scalr_{{ .Name }} test { + name = "%[1]s" + account_id = "%[2]s" +} + +data scalr_{{ .Name }} test { + id = scalr_{{ .Name }}.test.id + account_id = "%[2]s" +}`, name, defaultAccount) +} + +func testAccScalr{{ .Name | camel }}DataSourceByNameConfig(name string) string { + return fmt.Sprintf(` +resource scalr_{{ .Name }} test { + name = "%[1]s" + account_id = "%[2]s" +} + +data scalr_{{ .Name }} test { + name = scalr_{{ .Name }}.test.name + account_id = "%[2]s" +}`, name, defaultAccount) +} + +func testAccScalr{{ .Name | camel }}DataSourceByIDAndNameConfig(name string) string { + return fmt.Sprintf(` +resource scalr_{{ .Name }} test { + name = "%[1]s" + account_id = "%[2]s" +} + +data scalr_{{ .Name }} test { + id = scalr_{{ .Name }}.test.id + name = scalr_{{ .Name }}.test.name + account_id = "%[2]s" +}`, name, defaultAccount) +} diff --git a/skaff/templates/resource.tmpl b/skaff/templates/resource.tmpl new file mode 100644 index 00000000..1a8bc0d9 --- /dev/null +++ b/skaff/templates/resource.tmpl @@ -0,0 +1,194 @@ +package provider + +import ( + "context" + "errors" + + "github.com/hashicorp/terraform-plugin-framework/path" + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" + "github.com/hashicorp/terraform-plugin-framework/schema/validator" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/scalr/go-scalr" + + "github.com/scalr/terraform-provider-scalr/internal/framework" + "github.com/scalr/terraform-provider-scalr/internal/framework/defaults" + "github.com/scalr/terraform-provider-scalr/internal/framework/validation" +) + +// Compile-time interface checks +var ( + _ resource.Resource = &{{ .Name | lowerCamel }}Resource{} + _ resource.ResourceWithConfigure = &{{ .Name | lowerCamel }}Resource{} + _ resource.ResourceWithConfigValidators = &{{ .Name | lowerCamel }}Resource{} + _ resource.ResourceWithImportState = &{{ .Name | lowerCamel }}Resource{} +) + +func new{{ .Name | camel }}Resource() resource.Resource { + return &{{ .Name | lowerCamel }}Resource{} +} + +// {{ .Name | lowerCamel }}Resource defines the resource implementation. +type {{ .Name | lowerCamel }}Resource struct { + framework.ResourceWithScalrClient +} + +// {{ .Name | lowerCamel }}ResourceModel describes the resource data model. +type {{ .Name | lowerCamel }}ResourceModel struct { + Id types.String `tfsdk:"id"` + Name types.String `tfsdk:"name"` + AccountID types.String `tfsdk:"account_id"` +} + +func (r *{{ .Name | lowerCamel }}Resource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_{{ .Name }}" +} + +func (r *{{ .Name | lowerCamel }}Resource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) { + resp.Schema = schema.Schema{ + MarkdownDescription: "Manages the state of {{ .Name }}s in Scalr.", + + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + MarkdownDescription: "The ID of this resource.", + Computed: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.UseStateForUnknown(), + }, + }, + "name": schema.StringAttribute{ + MarkdownDescription: "Name of the {{ .Name }}.", + Required: true, + Validators: []validator.String{ + validation.StringIsNotWhiteSpace(), + }, + }, + "account_id": schema.StringAttribute{ + MarkdownDescription: "ID of the account, in the format `acc-`.", + Optional: true, + Computed: true, + Default: defaults.AccountIDRequired(), + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplace(), + }, + }, + }, + } +} + +func (r *{{ .Name | lowerCamel }}Resource) ConfigValidators(_ context.Context) []resource.ConfigValidator { + // If needed, add config validation logic here, + // or remove this method if no additional validation is needed. + return []resource.ConfigValidator{} +} + +func (r *{{ .Name | lowerCamel }}Resource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var plan {{ .Name | lowerCamel }}ResourceModel + + // Read plan data + resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) + if resp.Diagnostics.HasError() { + return + } + + opts := scalr.{{ .Name | camel }}CreateOptions{ + Name: plan.Name.ValueStringPointer(), + Account: &scalr.Account{ID: plan.AccountID.ValueString()}, + } + {{ .Name | lowerCamel }}, err := r.Client.{{ .Name | camel }}s.Create(ctx, opts) + if err != nil { + resp.Diagnostics.AddError("Error creating {{ .Name }}", err.Error()) + return + } + + plan.Id = types.StringValue({{ .Name | lowerCamel }}.ID) + plan.Name = types.StringValue({{ .Name | lowerCamel }}.Name) + plan.AccountID = types.StringValue({{ .Name | lowerCamel }}.Account.ID) + + // Set state to fully populated data + resp.Diagnostics.Append(resp.State.Set(ctx, plan)...) + if resp.Diagnostics.HasError() { + return + } +} + +func (r *{{ .Name | lowerCamel }}Resource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + // Get current state + var state {{ .Name | lowerCamel }}ResourceModel + resp.Diagnostics.Append(req.State.Get(ctx, &state)...) + if resp.Diagnostics.HasError() { + return + } + + // Get refreshed resource state from API + {{ .Name | lowerCamel }}, err := r.Client.{{ .Name | camel }}s.Read(ctx, state.Id.ValueString()) + if err != nil { + if errors.Is(err, scalr.ErrResourceNotFound) { + resp.State.RemoveResource(ctx) + return + } + resp.Diagnostics.AddError("Error retrieving {{ .Name }}", err.Error()) + return + } + + // Overwrite attributes with refreshed values + state.Name = types.StringValue({{ .Name | lowerCamel }}.Name) + state.AccountID = types.StringValue({{ .Name | lowerCamel }}.Account.ID) + + // Set refreshed state + resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) + if resp.Diagnostics.HasError() { + return + } +} + +func (r *{{ .Name | lowerCamel }}Resource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + // Read plan data + var plan {{ .Name | lowerCamel }}ResourceModel + resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) + if resp.Diagnostics.HasError() { + return + } + + opts := scalr.{{ .Name | camel }}UpdateOptions{ + Name: plan.Name.ValueStringPointer(), + } + + // Update existing resource + {{ .Name | lowerCamel }}, err := r.Client.{{ .Name | camel }}s.Update(ctx, plan.Id.ValueString(), opts) + if err != nil { + resp.Diagnostics.AddError("Error updating {{ .Name }}", err.Error()) + return + } + + // Overwrite attributes with refreshed values + plan.Name = types.StringValue({{ .Name | lowerCamel }}.Name) + plan.AccountID = types.StringValue({{ .Name | lowerCamel }}.Account.ID) + + // Set refreshed state + resp.Diagnostics.Append(resp.State.Set(ctx, plan)...) + if resp.Diagnostics.HasError() { + return + } +} + +func (r *{{ .Name | lowerCamel }}Resource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + // Get current state + var state {{ .Name | lowerCamel }}ResourceModel + resp.Diagnostics.Append(req.State.Get(ctx, &state)...) + if resp.Diagnostics.HasError() { + return + } + + err := r.Client.{{ .Name | camel }}s.Delete(ctx, state.Id.ValueString()) + if err != nil && !errors.Is(err, scalr.ErrResourceNotFound) { + resp.Diagnostics.AddError("Error deleting {{ .Name }}", err.Error()) + return + } +} + +func (r *{{ .Name | lowerCamel }}Resource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { + resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp) +} diff --git a/skaff/templates/resource_test.tmpl b/skaff/templates/resource_test.tmpl new file mode 100644 index 00000000..d9c3db30 --- /dev/null +++ b/skaff/templates/resource_test.tmpl @@ -0,0 +1,5 @@ +package provider + +// Please write the tests for the resource manually, as typical tests set is yet to be established later. +// While migrating to the new framework, the existing tests will be reviewed and updated, +// and the skaffolded examples will be added here.