2020-12-09 15:31:34 +00:00
|
|
|
package terraform
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
"path"
|
|
|
|
"runtime"
|
|
|
|
|
|
|
|
"github.com/mitchellh/go-homedir"
|
2021-02-09 18:43:39 +00:00
|
|
|
"github.com/pkg/errors"
|
2020-12-09 15:31:34 +00:00
|
|
|
"github.com/sirupsen/logrus"
|
2021-03-03 16:20:25 +00:00
|
|
|
|
|
|
|
"github.com/cloudskiff/driftctl/pkg/output"
|
2020-12-09 15:31:34 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type HomeDirInterface interface {
|
|
|
|
Dir() (string, error)
|
|
|
|
}
|
|
|
|
|
|
|
|
type ProviderInstaller struct {
|
|
|
|
downloader ProviderDownloaderInterface
|
2021-02-08 15:42:35 +00:00
|
|
|
config ProviderConfig
|
2020-12-09 15:31:34 +00:00
|
|
|
homeDir string
|
|
|
|
}
|
|
|
|
|
2021-02-08 15:42:35 +00:00
|
|
|
func NewProviderInstaller(config ProviderConfig) (*ProviderInstaller, error) {
|
2020-12-09 15:31:34 +00:00
|
|
|
homedir, err := homedir.Dir()
|
|
|
|
if err != nil {
|
|
|
|
homedir = ""
|
|
|
|
}
|
|
|
|
return &ProviderInstaller{
|
|
|
|
NewProviderDownloader(),
|
2021-02-08 15:42:35 +00:00
|
|
|
config,
|
2020-12-09 15:31:34 +00:00
|
|
|
homedir,
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
2021-02-08 15:42:35 +00:00
|
|
|
func (p *ProviderInstaller) Install() (string, error) {
|
2020-12-09 15:31:34 +00:00
|
|
|
if p.homeDir == "" {
|
|
|
|
p.homeDir = os.TempDir()
|
|
|
|
}
|
|
|
|
providerDir := path.Join(p.homeDir, fmt.Sprintf("/.driftctl/plugins/%s_%s/", runtime.GOOS, runtime.GOARCH))
|
2021-02-08 15:42:35 +00:00
|
|
|
providerPath := path.Join(providerDir, p.config.GetBinaryName())
|
2020-12-09 15:31:34 +00:00
|
|
|
|
|
|
|
info, err := os.Stat(providerPath)
|
|
|
|
if err != nil && os.IsNotExist(err) {
|
|
|
|
logrus.WithFields(logrus.Fields{
|
|
|
|
"path": providerPath,
|
2021-02-08 15:42:35 +00:00
|
|
|
}).Debug("provider not found, downloading ...")
|
2021-03-03 16:20:25 +00:00
|
|
|
output.Printf("Downloading terraform provider: %s\n", p.config.Key)
|
2020-12-09 15:31:34 +00:00
|
|
|
err := p.downloader.Download(
|
2021-02-08 15:42:35 +00:00
|
|
|
p.config.GetDownloadUrl(),
|
2020-12-09 15:31:34 +00:00
|
|
|
providerDir,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
logrus.Debug("Download successful")
|
|
|
|
}
|
|
|
|
|
|
|
|
if info != nil && info.IsDir() {
|
2021-02-10 13:37:59 +00:00
|
|
|
return "", errors.Errorf(
|
|
|
|
"found directory instead of provider binary in %s",
|
|
|
|
providerPath,
|
2021-02-09 18:43:39 +00:00
|
|
|
)
|
2020-12-09 15:31:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if info != nil {
|
|
|
|
logrus.WithFields(logrus.Fields{
|
|
|
|
"path": providerPath,
|
2021-02-08 15:42:35 +00:00
|
|
|
}).Debug("Found existing provider")
|
2020-12-09 15:31:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return providerPath, nil
|
|
|
|
}
|