Skip to content

Commit

Permalink
Merge pull request #266 from StarpTech/feature/add_commercetools_prov…
Browse files Browse the repository at this point in the history
…ider

Add commercetools provider
  • Loading branch information
sergeylanzman committed Nov 9, 2019
2 parents 00c7503 + 76e7e33 commit 7caeb7b
Show file tree
Hide file tree
Showing 20 changed files with 902 additions and 0 deletions.
34 changes: 34 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ A CLI tool that generates `tf` and `tfstate` files based on existing infrastruct
* [New Relic](#use-with-new-relic)
* Community
* [Logz.io](#use-with-logzio)
* [Commercetools](#use-with-commercetools)
- [Contributing](#contributing)
- [Developing](#developing)
- [Infrastructure](#infrastructure)
Expand Down Expand Up @@ -182,6 +183,7 @@ Links to download Terraform Providers:
* New Relic provider >1.5.0 - [here](https://releases.hashicorp.com/terraform-provider-newrelic/)
* Community
* Logz.io provider >=1.1.1 - [here](https://github.com/jonboydell/logzio_terraform_provider/)
* Commercetools provider >= 0.19.0 - [here](https://github.com/labd/terraform-provider-commercetools)

Information on provider plugins:
https://www.terraform.io/docs/configuration/providers.html
Expand Down Expand Up @@ -930,6 +932,38 @@ List of supported Logz.io resources:
* `alert_notification_endpoints`
* `logzio_endpoint`

### Use with [Commercetools](https://commercetools.com/de/)

This provider use the [terraform-provider-commercetools](https://github.com/labd/terraform-provider-commercetools). The terraformer provider was build by [Dustin Deus](https://github.com/StarpTech).

Example:

```
CTP_CLIENT_ID=foo CTP_CLIENT_SCOPE=scope CTP_CLIENT_SECRET=bar CTP_PROJECT_KEY=key ./terraformer plan commercetools -r=types // Only planning
CTP_CLIENT_ID=foo CTP_CLIENT_SCOPE=scope CTP_CLIENT_SECRET=bar CTP_PROJECT_KEY=key ./terraformer import commercetools -r=types // Import commercetools types
```

List of supported [commercetools](https://commercetools.com/de/) resources:

* `types`
* `commercetools_type`
* `product_type`
* `commercetools_product_type`
* `store`
* `commercetools_store`
* `api_extension`
* `commercetools_api_extension`
* `channel`
* `commercetools_channel`
* `subscription`
* `commercetools_subscription`
* `shipping_zone`
* `commercetools_shipping_zone`
* `state`
* `commercetools_state`
* `tax_category`
* `commercetools_tax_category`

## Contributing

If you have improvements or fixes, we would love to have your contributions.
Expand Down
81 changes: 81 additions & 0 deletions cmd/provider_cmd_commercetools.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// Copyright 2018 The Terraformer Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmd

import (
"errors"
"os"

commercetools_terraforming "github.com/GoogleCloudPlatform/terraformer/providers/commercetools"
"github.com/GoogleCloudPlatform/terraformer/terraform_utils"
"github.com/spf13/cobra"
)

const (
defaultCommercetoolsBaseURL = "https://api.sphere.io"
defaultCommercetoolsTokenURL = "https://auth.sphere.io"
)

func newCmdCommercetoolsImporter(options ImportOptions) *cobra.Command {
cmd := &cobra.Command{
Use: "commercetools",
Short: "Import current state to Terraform configuration from Commercetools",
Long: "Import current state to Terraform configuration from Commercetools",
RunE: func(cmd *cobra.Command, args []string) error {
clientID := os.Getenv("CTP_CLIENT_ID")
if len(clientID) == 0 {
return errors.New("API client ID for commercetools must be set through `CTP_CLIENT_ID` env var")
}
clientScope := os.Getenv("CTP_CLIENT_SCOPE")
if len(clientScope) == 0 {
return errors.New("API client scope for comercetools must be set through `CTP_CLIENT_SCOPE` env var")
}
clientSecret := os.Getenv("CTP_CLIENT_SECRET")
if len(clientSecret) == 0 {
return errors.New("API client secret for comercetools must be set through `CTP_CLIENT_SECRET` env var")
}
projectKey := os.Getenv("CTP_PROJECT_KEY")
if len(projectKey) == 0 {
return errors.New("API project key for comercetools must be set through `CTP_PROJECT_KEY` env var")
}
baseURL := os.Getenv("CTP_BASE_URL")
if len(baseURL) == 0 {
baseURL = defaultCommercetoolsBaseURL
}
tokenURL := os.Getenv("CTP_TOKEN_URL")
if len(tokenURL) == 0 {
tokenURL = defaultCommercetoolsTokenURL
}
provider := newCommercetoolsProvider()
err := Import(provider, options, []string{clientID, clientScope, clientSecret, projectKey, baseURL, tokenURL})
if err != nil {
return err
}
return nil
},
}
cmd.AddCommand(listCmd(newCommercetoolsProvider()))
cmd.PersistentFlags().BoolVarP(&options.Connect, "connect", "c", true, "")
cmd.PersistentFlags().StringSliceVarP(&options.Resources, "resources", "r", []string{}, "types")
cmd.PersistentFlags().StringVarP(&options.PathPattern, "path-pattern", "p", DefaultPathPattern, "{output}/{provider}/custom/{service}/")
cmd.PersistentFlags().StringVarP(&options.PathOutput, "path-output", "o", DefaultPathOutput, "")
cmd.PersistentFlags().StringVarP(&options.State, "state", "s", DefaultState, "local or bucket")
cmd.PersistentFlags().StringVarP(&options.Bucket, "bucket", "b", "", "gs://terraform-state")
cmd.PersistentFlags().StringSliceVarP(&options.Filter, "filter", "f", []string{}, "commercetools_type=id1:id2:id4")
return cmd
}

func newCommercetoolsProvider() terraform_utils.ProviderGenerator {
return &commercetools_terraforming.CommercetoolsProvider{}
}
2 changes: 2 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ func providerImporterSubcommands() []func(options ImportOptions) *cobra.Command
newCmdNewRelicImporter,
// Community
newCmdLogzioImporter,
newCmdCommercetoolsImporter,
}
}

Expand Down Expand Up @@ -90,6 +91,7 @@ func providerGenerators() map[string]func() terraform_utils.ProviderGenerator {
newNewRelicProvider,
// Community
newLogzioProvider,
newCommercetoolsProvider,
} {
list[providerGen().GetName()] = providerGen
}
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ require (
github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af
github.com/jonboydell/logzio_client v1.2.0
github.com/jstemmer/go-junit-report v0.9.1 // indirect
github.com/labd/commercetools-go-sdk v0.0.0-20190722144546-80b2ca71bd4d
github.com/linode/linodego v0.12.0
github.com/mattn/go-colorable v0.1.4 // indirect
github.com/mattn/go-isatty v0.0.10 // indirect
Expand Down
3 changes: 3 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@ github.com/dimchansky/utfbom v1.0.0/go.mod h1:rO41eb7gLfo8SF1jd9F8HplJm1Fewwi4mQ
github.com/dimchansky/utfbom v1.1.0 h1:FcM3g+nofKgUteL8dm/UpdRXNC9KmADgTpLKsu0TRo4=
github.com/dimchansky/utfbom v1.1.0/go.mod h1:rO41eb7gLfo8SF1jd9F8HplJm1Fewwi4mQvIirEdv+8=
github.com/dnaeon/go-vcr v0.0.0-20180814043457-aafff18a5cc2/go.mod h1:aBB1+wY4s93YsC3HHjMBMrwTj2R9FHDzUr9KyGc8n1E=
github.com/dnaeon/go-vcr v0.0.0-20180920040454-5637cf3d8a31 h1:Dzuw9GtbmllUqEcoHfScT9YpKFUssSiZ5PgZkIGf/YQ=
github.com/dnaeon/go-vcr v0.0.0-20180920040454-5637cf3d8a31/go.mod h1:aBB1+wY4s93YsC3HHjMBMrwTj2R9FHDzUr9KyGc8n1E=
github.com/docker/spdystream v0.0.0-20160310174837-449fdfce4d96/go.mod h1:Qh8CwZgvJUkLughtfhJv5dyTYa91l1fOUCrgjqmcifM=
github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815/go.mod h1:WwZ+bS3ebgob9U8Nd0kOddGdZWjyMGR8Wziv+TBNwSE=
Expand Down Expand Up @@ -347,6 +348,8 @@ github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348/go.mod h1:B69LEHPfb2qLo0BaaOLcbitczOKLWTsrBG9LczfCD4k=
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/labd/commercetools-go-sdk v0.0.0-20190722144546-80b2ca71bd4d h1:tQPiC54Y3Eebi5G8jIQlVVIh9cqlaIQIuhlW82Yvqgg=
github.com/labd/commercetools-go-sdk v0.0.0-20190722144546-80b2ca71bd4d/go.mod h1:4IG4Fi2139S7HAjJlaL2Z9kcyKdbIjUTdqd4l4pPXdw=
github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
github.com/linode/linodego v0.12.0 h1:xFjPwUOiBB9l+dTqjwnYlQ4c9mRXMiaXln20BVD/Z4U=
github.com/linode/linodego v0.12.0/go.mod h1:cQFzVqVu5KeFy2ZSTWTA/qVNYYa9ZY8uePJZsFG7EYs=
Expand Down
55 changes: 55 additions & 0 deletions providers/commercetools/api_extension.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Copyright 2018 The Terraformer Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package commercetools

import (
"github.com/GoogleCloudPlatform/terraformer/providers/commercetools/connectivity"
"github.com/GoogleCloudPlatform/terraformer/terraform_utils"
"github.com/labd/commercetools-go-sdk/commercetools"
)

type ApiExtensionGenerator struct {
CommercetoolsService
}

// InitResources generates Terraform Resources from Commercetools API
func (g *ApiExtensionGenerator) InitResources() error {
cfg := connectivity.Config{
ClientId: g.GetArgs()["client_id"].(string),
ClientSecret: g.GetArgs()["client_secret"].(string),
ClientScope: g.GetArgs()["client_scope"].(string),
TokenURL: g.GetArgs()["token_url"].(string) + "/oauth/token",
BaseURL: g.GetArgs()["base_url"].(string),
}

client := cfg.NewClient()

extensions, err := client.ExtensionQuery(&commercetools.QueryInput{})
if err != nil {
return err
}
for _, extension := range extensions.Results {
g.Resources = append(g.Resources, terraform_utils.NewResource(
extension.ID,
extension.Key,
"commercetools_api_extension",
"commercetools",
map[string]string{},
[]string{},
map[string]interface{}{},
))
}
return nil
}
55 changes: 55 additions & 0 deletions providers/commercetools/channel.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Copyright 2018 The Terraformer Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package commercetools

import (
"github.com/GoogleCloudPlatform/terraformer/providers/commercetools/connectivity"
"github.com/GoogleCloudPlatform/terraformer/terraform_utils"
"github.com/labd/commercetools-go-sdk/commercetools"
)

type ChannelGenerator struct {
CommercetoolsService
}

// InitResources generates Terraform Resources from Commercetools API
func (g *ChannelGenerator) InitResources() error {
cfg := connectivity.Config{
ClientId: g.GetArgs()["client_id"].(string),
ClientSecret: g.GetArgs()["client_secret"].(string),
ClientScope: g.GetArgs()["client_scope"].(string),
TokenURL: g.GetArgs()["token_url"].(string) + "/oauth/token",
BaseURL: g.GetArgs()["base_url"].(string),
}

client := cfg.NewClient()

channels, err := client.ChannelQuery(&commercetools.QueryInput{})
if err != nil {
return err
}
for _, channel := range channels.Results {
g.Resources = append(g.Resources, terraform_utils.NewResource(
channel.ID,
channel.Key,
"commercetools_channel",
"commercetools",
map[string]string{},
[]string{},
map[string]interface{}{},
))
}
return nil
}
94 changes: 94 additions & 0 deletions providers/commercetools/commercetools_provider.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
// Copyright 2018 The Terraformer Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package commercetools

import (
"github.com/GoogleCloudPlatform/terraformer/terraform_utils"
"github.com/GoogleCloudPlatform/terraformer/terraform_utils/provider_wrapper"
"github.com/pkg/errors"
)

type CommercetoolsProvider struct {
terraform_utils.Provider
clientID string
clientSecret string
clientScope string
projectKey string
baseURL string
tokenURL string
}

func (p CommercetoolsProvider) GetResourceConnections() map[string]map[string][]string {
return map[string]map[string][]string{}
}

func (p CommercetoolsProvider) GetProviderData(arg ...string) map[string]interface{} {
return map[string]interface{}{
"provider": map[string]interface{}{
"commercetools": map[string]interface{}{
"version": provider_wrapper.GetProviderVersion(p.GetName()),
},
},
}
}

// Init CommerectoolsProvider
func (p *CommercetoolsProvider) Init(args []string) error {
p.clientID = args[0]
p.clientScope = args[1]
p.clientSecret = args[2]
p.projectKey = args[3]
p.baseURL = args[4]
p.tokenURL = args[5]
return nil
}

func (p *CommercetoolsProvider) GetName() string {
return "commercetools"
}

func (p *CommercetoolsProvider) InitService(serviceName string) error {
var isSupported bool
if _, isSupported = p.GetSupportedService()[serviceName]; !isSupported {
return errors.New(p.GetName() + ": " + serviceName + " not supported service")
}
p.Service = p.GetSupportedService()[serviceName]
p.Service.SetName(serviceName)
p.Service.SetProviderName(p.GetName())
p.Service.SetArgs(map[string]interface{}{
"client_id": p.clientID,
"client_secret": p.clientSecret,
"client_scope": p.clientScope,
"project_key": p.projectKey,
"base_url": p.baseURL,
"token_url": p.tokenURL,
})
return nil
}

// GetSupportedService return map of support service for Logzio
func (p *CommercetoolsProvider) GetSupportedService() map[string]terraform_utils.ServiceGenerator {
return map[string]terraform_utils.ServiceGenerator{
"types": &TypesGenerator{},
"product_type": &ProductTypeGenerator{},
"store": &StoreGenerator{},
"api_extension": &ApiExtensionGenerator{},
"channel": &ChannelGenerator{},
"subscription": &SubscriptionGenerator{},
"shipping_zone": &ShippingZoneGenerator{},
"state": &StateGenerator{},
"tax_category": &TaxCategoryGenerator{},
}
}

0 comments on commit 7caeb7b

Please sign in to comment.