2021-03-29 16:10:50 +00:00
|
|
|
package terraform
|
|
|
|
|
|
|
|
import (
|
2021-04-29 15:17:55 +00:00
|
|
|
"github.com/cloudskiff/driftctl/pkg/resource"
|
2021-03-29 16:10:50 +00:00
|
|
|
"github.com/pkg/errors"
|
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
"github.com/zclconf/go-cty/cty"
|
|
|
|
"github.com/zclconf/go-cty/cty/gocty"
|
|
|
|
)
|
|
|
|
|
|
|
|
type TerraformResourceFactory struct {
|
2021-04-29 15:17:55 +00:00
|
|
|
providerLibrary *ProviderLibrary
|
2021-05-04 13:03:17 +00:00
|
|
|
resourceSchemaRepository resource.SchemaRepositoryInterface
|
2021-03-29 16:10:50 +00:00
|
|
|
}
|
|
|
|
|
2021-05-04 13:03:17 +00:00
|
|
|
func NewTerraformResourceFactory(providerLibrary *ProviderLibrary, resourceSchemaRepository resource.SchemaRepositoryInterface) *TerraformResourceFactory {
|
2021-04-29 15:17:55 +00:00
|
|
|
return &TerraformResourceFactory{
|
|
|
|
providerLibrary: providerLibrary,
|
|
|
|
resourceSchemaRepository: resourceSchemaRepository,
|
|
|
|
}
|
2021-03-29 16:10:50 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (r *TerraformResourceFactory) resolveType(ty string) (cty.Type, error) {
|
|
|
|
provider, err := r.providerLibrary.GetProviderForResourceType(ty)
|
|
|
|
if err != nil {
|
|
|
|
return cty.NilType, err
|
|
|
|
}
|
|
|
|
if schemas, exist := provider.Schema()[ty]; exist {
|
|
|
|
return schemas.Block.ImpliedType(), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return cty.NilType, errors.New("Unable to find ")
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *TerraformResourceFactory) CreateResource(data interface{}, ty string) (*cty.Value, error) {
|
|
|
|
ctyType, err := r.resolveType(ty)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
logrus.WithFields(logrus.Fields{
|
|
|
|
"type": ty,
|
|
|
|
}).Debug("Found cty type for resource")
|
|
|
|
|
|
|
|
val, err := gocty.ToCtyValue(data, ctyType)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return &val, nil
|
|
|
|
}
|
2021-04-29 15:17:55 +00:00
|
|
|
|
2021-05-04 13:03:17 +00:00
|
|
|
func (r *TerraformResourceFactory) CreateAbstractResource(ty, id string, data map[string]interface{}) *resource.AbstractResource {
|
|
|
|
attributes := resource.Attributes(data)
|
2021-05-11 08:53:39 +00:00
|
|
|
attributes.SanitizeDefaults()
|
2021-04-29 15:17:55 +00:00
|
|
|
|
2021-05-04 13:03:17 +00:00
|
|
|
schema, exist := r.resourceSchemaRepository.(*resource.SchemaRepository).GetSchema(ty)
|
2021-04-29 15:17:55 +00:00
|
|
|
if exist && schema.NormalizeFunc != nil {
|
2021-05-04 13:03:17 +00:00
|
|
|
schema.NormalizeFunc(&attributes)
|
2021-04-29 15:17:55 +00:00
|
|
|
}
|
|
|
|
|
2021-05-04 13:03:17 +00:00
|
|
|
return &resource.AbstractResource{
|
2021-04-29 15:17:55 +00:00
|
|
|
Id: id,
|
|
|
|
Type: ty,
|
2021-05-04 13:03:17 +00:00
|
|
|
Attrs: &attributes,
|
2021-04-29 15:17:55 +00:00
|
|
|
}
|
|
|
|
}
|