Skip to content

Commit

Permalink
Completed provider ready for review
Browse files Browse the repository at this point in the history
  • Loading branch information
PCloughster committed Sep 12, 2024
1 parent 1798dd7 commit a3c6845
Show file tree
Hide file tree
Showing 14 changed files with 992 additions and 211 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ terraform.tfstate
bin/
dist/
modules-dev/
terraform-provider-accounts
website/.vagrant
website/.bundle
website/build
Expand Down
29 changes: 21 additions & 8 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
module terraform-provider-accounts
module terraform-provider-account

go 1.21

require (
github.com/ans-group/sdk-go v1.20.2
github.com/ans-group/sdk-go v1.20.4
github.com/hashicorp/terraform-plugin-docs v0.19.4
github.com/hashicorp/terraform-plugin-framework v1.10.0
github.com/hashicorp/terraform-plugin-go v0.23.0
github.com/hashicorp/terraform-plugin-log v0.9.0
github.com/hashicorp/terraform-plugin-sdk/v2 v2.34.0
github.com/hashicorp/terraform-plugin-testing v1.10.0
)

require (
Expand All @@ -17,6 +19,7 @@ require (
github.com/Masterminds/semver/v3 v3.2.0 // indirect
github.com/Masterminds/sprig/v3 v3.2.3 // indirect
github.com/ProtonMail/go-crypto v1.1.0-alpha.2 // indirect
github.com/agext/levenshtein v1.2.2 // indirect
github.com/ans-group/go-durationstring v1.2.0 // indirect
github.com/apparentlymart/go-textseg/v15 v15.0.0 // indirect
github.com/armon/go-radix v1.0.0 // indirect
Expand All @@ -28,18 +31,23 @@ require (
github.com/go-playground/locales v0.12.1 // indirect
github.com/go-playground/universal-translator v0.16.0 // indirect
github.com/golang/protobuf v1.5.4 // indirect
github.com/google/go-cmp v0.6.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/hashicorp/cli v1.1.6 // indirect
github.com/hashicorp/errwrap v1.1.0 // indirect
github.com/hashicorp/go-checkpoint v0.5.0 // indirect
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
github.com/hashicorp/go-cty v1.4.1-0.20200414143053-d3edf31b6320 // indirect
github.com/hashicorp/go-hclog v1.6.3 // indirect
github.com/hashicorp/go-multierror v1.1.1 // indirect
github.com/hashicorp/go-plugin v1.6.0 // indirect
github.com/hashicorp/go-retryablehttp v0.7.7 // indirect
github.com/hashicorp/go-uuid v1.0.3 // indirect
github.com/hashicorp/go-version v1.7.0 // indirect
github.com/hashicorp/hc-install v0.7.0 // indirect
github.com/hashicorp/hc-install v0.8.0 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/hashicorp/hcl/v2 v2.21.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.22.1 // indirect
github.com/hashicorp/terraform-registry-address v0.2.3 // indirect
Expand All @@ -55,6 +63,7 @@ require (
github.com/mitchellh/copystructure v1.2.0 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/mitchellh/go-testing-interface v1.14.1 // indirect
github.com/mitchellh/go-wordwrap v1.0.0 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/mitchellh/reflectwalk v1.0.2 // indirect
github.com/oklog/run v1.0.0 // indirect
Expand All @@ -70,20 +79,24 @@ require (
github.com/spf13/viper v1.17.0 // indirect
github.com/stretchr/testify v1.9.0 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
github.com/vmihailenco/msgpack v4.0.4+incompatible // indirect
github.com/vmihailenco/msgpack/v5 v5.4.1 // indirect
github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect
github.com/yuin/goldmark v1.7.1 // indirect
github.com/yuin/goldmark-meta v1.1.0 // indirect
github.com/zclconf/go-cty v1.14.4 // indirect
github.com/zclconf/go-cty v1.15.0 // indirect
go.abhg.dev/goldmark/frontmatter v0.2.0 // indirect
go.uber.org/atomic v1.9.0 // indirect
go.uber.org/multierr v1.9.0 // indirect
golang.org/x/crypto v0.25.0 // indirect
golang.org/x/crypto v0.26.0 // indirect
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect
golang.org/x/mod v0.17.0 // indirect
golang.org/x/mod v0.19.0 // indirect
golang.org/x/net v0.26.0 // indirect
golang.org/x/sys v0.22.0 // indirect
golang.org/x/text v0.16.0 // indirect
golang.org/x/sync v0.8.0 // indirect
golang.org/x/sys v0.23.0 // indirect
golang.org/x/text v0.17.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/googleapis/rpc v0.0.0-20240701130421-f6361c86f094 // indirect
google.golang.org/grpc v1.64.0 // indirect
google.golang.org/protobuf v1.34.2 // indirect
Expand Down
67 changes: 51 additions & 16 deletions go.sum

Large diffs are not rendered by default.

42 changes: 25 additions & 17 deletions internal/provider/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ package provider

import (
"context"
"terraform-provider-accounts/pkg/logger"
"fmt"
"terraform-provider-account/pkg/logger"

"github.com/ans-group/sdk-go/pkg/client"
"github.com/ans-group/sdk-go/pkg/config"
Expand All @@ -17,37 +18,38 @@ import (
"github.com/hashicorp/terraform-plugin-framework/provider/schema"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
)

const userAgent = "terraform-provider-accounts"
const userAgent = "terraform-provider-account"

var (
_ provider.Provider = &accountsProvider{}
_ provider.Provider = &accountProvider{}
)

func New(version string) func() provider.Provider {
return func() provider.Provider {
return &accountsProvider{
return &accountProvider{
version: version,
}
}
}

type accountsProvider struct {
type accountProvider struct {
version string
}

type accountsProviderModel struct {
type accountProviderModel struct {
Context types.String `tfsdk:"context"`
APIKey types.String `tfsdk:"api_key"`
}

func (p *accountsProvider) Metadata(_ context.Context, _ provider.MetadataRequest, resp *provider.MetadataResponse) {
resp.TypeName = "accounts"
func (p *accountProvider) Metadata(_ context.Context, _ provider.MetadataRequest, resp *provider.MetadataResponse) {
resp.TypeName = "account"
resp.Version = p.version
}

func (p *accountsProvider) Schema(_ context.Context, _ provider.SchemaRequest, resp *provider.SchemaResponse) {
func (p *accountProvider) Schema(_ context.Context, _ provider.SchemaRequest, resp *provider.SchemaResponse) {
resp.Schema = schema.Schema{
Attributes: map[string]schema.Attribute{
"context": schema.StringAttribute{
Expand All @@ -63,7 +65,11 @@ func (p *accountsProvider) Schema(_ context.Context, _ provider.SchemaRequest, r
}
}

func (p *accountsProvider) Configure(ctx context.Context, req provider.ConfigureRequest, resp *provider.ConfigureResponse) {
func (p *accountProvider) Configure(ctx context.Context, req provider.ConfigureRequest, resp *provider.ConfigureResponse) {
var configuration accountProviderModel

resp.Diagnostics.Append(req.Config.Get(ctx, &configuration)...)

err := config.Init("")
if err != nil {
resp.Diagnostics.AddAttributeError(
Expand All @@ -75,7 +81,7 @@ func (p *accountsProvider) Configure(ctx context.Context, req provider.Configure
logging.SetLogger(&logger.ProviderLogger{})
}

var configuration accountsProviderModel
tflog.Debug(ctx, fmt.Sprintf("Created config model: %+v", configuration))

context := configuration.Context.ValueString()
if len(context) > 0 {
Expand Down Expand Up @@ -108,10 +114,10 @@ func (p *accountsProvider) Configure(ctx context.Context, req provider.Configure
client := client.NewClient(conn).AccountService()
if err != nil {
resp.Diagnostics.AddError(
"Unable to Create Accounts API Client",
"An unexpected error occurred when creating the Accounts API client. "+
"Unable to Create Account API Client",
"An unexpected error occurred when creating the Account API client. "+
"If the error is not clear, please contact the provider developers.\n\n"+
"Accounts Client Error: "+err.Error(),
"Account Client Error: "+err.Error(),
)
return
}
Expand All @@ -129,13 +135,15 @@ func getConnection() (connection.Connection, error) {
}

// DataSources defines the data sources implemented in the provider.
func (p *accountsProvider) DataSources(_ context.Context) []func() datasource.DataSource {
func (p *accountProvider) DataSources(_ context.Context) []func() datasource.DataSource {
return nil
}

// Resources defines the resources implemented in the provider.
func (p *accountsProvider) Resources(_ context.Context) []func() resource.Resource {
func (p *accountProvider) Resources(_ context.Context) []func() resource.Resource {
return []func() resource.Resource{
NewAccountsApplication,
NewAccountApplication,
NewApplicationIPRestriction,
NewApplicationServiceMapping,
}
}
116 changes: 116 additions & 0 deletions internal/provider/provider_application_restriction_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
package provider

import (
"fmt"
"testing"

accountservice "github.com/ans-group/sdk-go/pkg/service/account"
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/hashicorp/terraform-plugin-testing/terraform"
)

func TestAccApplicationRestriction_basic(t *testing.T) {
resourceName := "account_application_restriction.test-application-restriction"

service := AccTestingClient{}
service.Configure()
restrictionType := "allowlist"
ipRange := "1.1.1.1/24"

resource.Test(t, resource.TestCase{
ProtoV6ProviderFactories: testAccProtoV6ProviderFactories,
CheckDestroy: service.testAccCheckApplicationRestrictionDestroy,
Steps: []resource.TestStep{
{
Config: providerConfig + testAccResourceApplicationRestrictionConfig_basic(restrictionType, ipRange),
Check: resource.ComposeTestCheckFunc(
service.testAccCheckApplicationRestrictionExists(t, resourceName),
resource.TestCheckResourceAttr(resourceName, "type", restrictionType),
resource.TestCheckResourceAttr(resourceName, "ranges.0", ipRange),
),
},
},
})

restrictionType = "denylist"
ipRange = "1.1.1.1"

resource.Test(t, resource.TestCase{
ProtoV6ProviderFactories: testAccProtoV6ProviderFactories,
CheckDestroy: service.testAccCheckApplicationRestrictionDestroy,
Steps: []resource.TestStep{
{
Config: providerConfig + testAccResourceApplicationRestrictionConfig_basic(restrictionType, ipRange),
Check: resource.ComposeTestCheckFunc(
service.testAccCheckApplicationRestrictionExists(t, resourceName),
resource.TestCheckResourceAttr(resourceName, "type", restrictionType),
resource.TestCheckResourceAttr(resourceName, "ranges.0", ipRange),
),
},
},
})

}

func (r *AccTestingClient) testAccCheckApplicationRestrictionExists(t *testing.T, n string) resource.TestCheckFunc {
service := r.client
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
t.Fatalf("Application not found: %s", n)
}

if rs.Primary.ID == "" {
t.Fatal("")
}

_, err := service.GetApplicationRestrictions(rs.Primary.Attributes["application_id"])
if err != nil {
if _, ok := err.(*accountservice.ApplicationNotFoundError); ok {
t.Fatal("Application Not found")
}
t.Fatal(err)
}

return nil
}
}

func (r *AccTestingClient) testAccCheckApplicationRestrictionDestroy(s *terraform.State) error {
service := r.client
for _, rs := range s.RootModule().Resources {
if rs.Type != "account_application" {
continue
}
if rs.Primary.Attributes["application_id"] != "" {
_, err := service.GetApplicationRestrictions(rs.Primary.Attributes["application_id"])
if err == nil {
return fmt.Errorf("Application with ID [%s] still exists", rs.Primary.ID)
}

if _, ok := err.(*accountservice.ApplicationNotFoundError); ok {
return nil
}

return fmt.Errorf("Application with ID [%s] still exists", rs.Primary.ID)
}
}

return nil
}

func testAccResourceApplicationRestrictionConfig_basic(restrictionType string, ipRange string) string {
return fmt.Sprintf(`
resource "account_application" "test-application"{
name = "tftest-application-restriction"
description = "test"
}
resource "account_application_restriction" "test-application-restriction"{
application_id = account_application.test-application.id
type = "%[1]s"
ranges = ["%[2]s"]
}
`, restrictionType, ipRange,
)
}
36 changes: 32 additions & 4 deletions internal/provider/provider_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,50 @@
package provider

import (
"os"
"testing"

"github.com/ans-group/sdk-go/pkg/client"
"github.com/ans-group/sdk-go/pkg/connection"
accountservice "github.com/ans-group/sdk-go/pkg/service/account"
"github.com/hashicorp/terraform-plugin-framework/providerserver"
"github.com/hashicorp/terraform-plugin-go/tfprotov6"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

const (
providerConfig = (`
provider "account" {}
`)
)

type AccTestingClient struct {
client accountservice.AccountService
}

func (r *AccTestingClient) Configure() {
apioToken := os.Getenv("APIO_TOKEN_ADMIN")
conn := connection.NewAPIKeyCredentialsAPIConnection(apioToken)
c := client.NewClient(conn)

r.client = c.AccountService()
}

// testAccProtoV6ProviderFactories are used to instantiate a provider during
// acceptance testing. The factory function will be invoked for every Terraform
// CLI command executed to create a provider server to which the CLI can
// reattach.
var testAccProvider *schema.Provider

Check failure on line 40 in internal/provider/provider_test.go

View workflow job for this annotation

GitHub Actions / Build

var `testAccProvider` is unused (unused)
var testAccProtoV6ProviderFactories = map[string]func() (tfprotov6.ProviderServer, error){
"scaffolding": providerserver.NewProtocol6WithError(New("test")()),
"account": providerserver.NewProtocol6WithError(New("test")()),
}

func testAccPreCheck(t *testing.T) {

Check failure on line 45 in internal/provider/provider_test.go

View workflow job for this annotation

GitHub Actions / Build

func `testAccPreCheck` is unused (unused)
// You can add code here to run prior to any test case execution, for example assertions
// about the appropriate environment variables being set are common to see in a pre-check
// function.
testAccPreCheckRequiredEnvVars(t)
}

func testAccPreCheckRequiredEnvVars(t *testing.T) {

Check failure on line 49 in internal/provider/provider_test.go

View workflow job for this annotation

GitHub Actions / Build

func `testAccPreCheckRequiredEnvVars` is unused (unused)
if os.Getenv("APIO_TOKEN_ADMIN") == "" {
t.Fatal("APIO_TOKEN_ADMIN must be set for acceptance tests")
}
}
Loading

0 comments on commit a3c6845

Please sign in to comment.