2020-12-09 15:31:34 +00:00
|
|
|
package terraform
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
"path"
|
|
|
|
"runtime"
|
|
|
|
|
|
|
|
"github.com/mitchellh/go-homedir"
|
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
|
|
|
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 ...")
|
|
|
|
fmt.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() {
|
|
|
|
return "", fmt.Errorf("found directory instead of provider binary in %s", providerPath)
|
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|