driftctl/pkg/resource/resource.go

290 lines
6.5 KiB
Go
Raw Normal View History

package resource
import (
"encoding/json"
2021-03-26 08:44:55 +00:00
"reflect"
"sort"
2021-03-26 08:44:55 +00:00
"strconv"
"strings"
2021-03-25 11:13:52 +00:00
2021-03-26 08:44:55 +00:00
"github.com/pkg/errors"
2021-03-25 11:13:52 +00:00
"github.com/zclconf/go-cty/cty"
2021-03-26 08:44:55 +00:00
ctyjson "github.com/zclconf/go-cty/cty/json"
)
type Resource interface {
TerraformId() string
TerraformType() string
2021-03-25 11:13:52 +00:00
CtyValue() *cty.Value
}
2021-03-26 08:44:55 +00:00
var refactoredResources = []string{
2021-04-26 13:36:12 +00:00
"aws_ami",
2021-03-26 08:44:55 +00:00
"aws_cloudfront_distribution",
2021-04-26 13:42:14 +00:00
"aws_db_instance",
2021-04-26 13:56:13 +00:00
"aws_db_subnet_group",
2021-04-26 14:08:25 +00:00
"aws_default_route_table",
2021-04-26 15:24:57 +00:00
"aws_default_security_group",
2021-04-26 15:43:37 +00:00
"aws_default_subnet",
2021-04-26 16:00:51 +00:00
"aws_default_vpc",
2021-04-27 09:36:45 +00:00
"aws_dynamodb_table",
2021-04-27 13:55:26 +00:00
"aws_ebs_snapshot",
2021-04-29 15:17:55 +00:00
"aws_ebs_volume",
2021-05-07 09:01:38 +00:00
"aws_ecr_repository",
// "aws_eip",
// "aws_eip_association",
// "aws_iam_access_key",
2021-05-07 15:47:53 +00:00
"aws_iam_policy",
"aws_iam_policy_attachment",
"aws_iam_role",
"aws_iam_role_policy",
"aws_iam_role_policy_attachment",
"aws_iam_user",
"aws_iam_user_policy",
"aws_iam_user_policy_attachment",
"aws_instance",
// "aws_internet_gateway",
2021-05-07 15:47:53 +00:00
"aws_key_pair",
// "aws_kms_alias",
// "aws_kms_key",
// "aws_lambda_event_source_mapping",
// "aws_lambda_function",
// "aws_nat_gateway",
"aws_route",
// "aws_route53_health_check",
// "aws_route53_record",
// "aws_route53_zone",
"aws_route_table",
// "aws_route_table_association",
"aws_s3_bucket",
"aws_s3_bucket_analytics_configuration",
"aws_s3_bucket_inventory",
"aws_s3_bucket_metric",
"aws_s3_bucket_notification",
"aws_s3_bucket_policy",
// "aws_security_group",
// "aws_security_group_rule",
"aws_sns_topic",
"aws_sns_topic_policy",
"aws_sns_topic_subscription",
// "aws_sqs_queue",
// "aws_sqs_queue_policy",
// "aws_subnet",
// "aws_vpc",
2021-03-26 08:44:55 +00:00
}
func IsRefactoredResource(typ string) bool {
for _, refactoredResource := range refactoredResources {
if typ == refactoredResource {
return true
}
}
return false
}
type AbstractResource struct {
Id string
Type string
Attrs *Attributes
}
func (a *AbstractResource) TerraformId() string {
return a.Id
}
func (a *AbstractResource) TerraformType() string {
return a.Type
}
func (a *AbstractResource) CtyValue() *cty.Value {
return nil
}
2021-03-29 16:10:50 +00:00
type ResourceFactory interface {
CreateResource(data interface{}, ty string) (*cty.Value, error)
2021-05-04 13:03:17 +00:00
CreateAbstractResource(ty, id string, data map[string]interface{}) *AbstractResource
2021-03-29 16:10:50 +00:00
}
type SerializableResource struct {
Resource
}
type SerializedResource struct {
Id string `json:"id"`
Type string `json:"type"`
}
func (u SerializedResource) TerraformId() string {
return u.Id
}
func (u SerializedResource) TerraformType() string {
return u.Type
}
2021-03-25 11:13:52 +00:00
func (u SerializedResource) CtyValue() *cty.Value {
return &cty.NilVal
}
func (s *SerializableResource) UnmarshalJSON(bytes []byte) error {
var res SerializedResource
if err := json.Unmarshal(bytes, &res); err != nil {
return err
}
s.Resource = res
return nil
}
func (s SerializableResource) MarshalJSON() ([]byte, error) {
return json.Marshal(SerializedResource{Id: s.TerraformId(), Type: s.TerraformType()})
}
type NormalizedResource interface {
NormalizeForState() (Resource, error)
NormalizeForProvider() (Resource, error)
}
func IsSameResource(rRs, lRs Resource) bool {
return rRs.TerraformType() == lRs.TerraformType() && rRs.TerraformId() == lRs.TerraformId()
}
func Sort(res []Resource) []Resource {
2021-03-22 10:17:50 +00:00
sort.SliceStable(res, func(i, j int) bool {
2021-03-22 10:59:09 +00:00
if res[i].TerraformType() != res[j].TerraformType() {
return res[i].TerraformType() < res[j].TerraformType()
}
return res[i].TerraformId() < res[j].TerraformId()
2021-03-22 10:17:50 +00:00
})
return res
}
2021-03-26 08:44:55 +00:00
func ToResourceAttributes(val *cty.Value) *Attributes {
if val == nil {
return nil
}
bytes, _ := ctyjson.Marshal(*val, val.Type())
var attrs Attributes
err := json.Unmarshal(bytes, &attrs)
if err != nil {
panic(err)
}
return &attrs
}
type Attributes map[string]interface{}
func (a *Attributes) Get(path string) (interface{}, bool) {
val, exist := (*a)[path]
return val, exist
}
func (a *Attributes) SafeDelete(path []string) {
for i, key := range path {
if i == len(path)-1 {
delete(*a, key)
return
}
v, exists := (*a)[key]
if !exists {
return
}
m, ok := v.(Attributes)
if !ok {
return
}
*a = m
}
}
func (a *Attributes) SafeSet(path []string, value interface{}) error {
for i, key := range path {
if i == len(path)-1 {
(*a)[key] = value
return nil
}
v, exists := (*a)[key]
if !exists {
(*a)[key] = map[string]interface{}{}
v = (*a)[key]
}
m, ok := v.(Attributes)
if !ok {
return errors.Errorf("Path %s cannot be set: %s is not a nested struct", strings.Join(path, "."), key)
}
*a = m
}
return errors.New("Error setting value") // should not happen ?
}
func concatenatePath(path, next string) string {
if path == "" {
return next
}
return strings.Join([]string{path, next}, ".")
}
2021-05-11 08:53:39 +00:00
func (a *Attributes) SanitizeDefaults() {
2021-03-26 08:44:55 +00:00
original := reflect.ValueOf(*a)
copy := reflect.New(original.Type()).Elem()
2021-05-11 08:53:39 +00:00
a.sanitize("", original, copy)
2021-03-26 08:44:55 +00:00
*a = copy.Interface().(Attributes)
}
2021-05-11 08:53:39 +00:00
func (a *Attributes) sanitize(path string, original, copy reflect.Value) bool {
2021-03-26 08:44:55 +00:00
switch original.Kind() {
case reflect.Ptr:
originalValue := original.Elem()
if !originalValue.IsValid() {
return false
}
copy.Set(reflect.New(originalValue.Type()))
2021-05-11 08:53:39 +00:00
a.sanitize(path, originalValue, copy.Elem())
2021-03-26 08:44:55 +00:00
case reflect.Interface:
// Get rid of the wrapping interface
originalValue := original.Elem()
if !originalValue.IsValid() {
return false
}
if originalValue.Kind() == reflect.Slice || originalValue.Kind() == reflect.Map {
if originalValue.Len() == 0 {
return false
}
}
// Create a new object. Now new gives us a pointer, but we want the value it
// points to, so we have to call Elem() to unwrap it
copyValue := reflect.New(originalValue.Type()).Elem()
2021-05-11 08:53:39 +00:00
a.sanitize(path, originalValue, copyValue)
2021-03-26 08:44:55 +00:00
copy.Set(copyValue)
case reflect.Struct:
for i := 0; i < original.NumField(); i += 1 {
field := original.Field(i)
2021-05-11 08:53:39 +00:00
a.sanitize(concatenatePath(path, field.String()), field, copy.Field(i))
2021-03-26 08:44:55 +00:00
}
case reflect.Slice:
copy.Set(reflect.MakeSlice(original.Type(), original.Len(), original.Cap()))
for i := 0; i < original.Len(); i += 1 {
2021-05-11 08:53:39 +00:00
a.sanitize(concatenatePath(path, strconv.Itoa(i)), original.Index(i), copy.Index(i))
2021-03-26 08:44:55 +00:00
}
case reflect.Map:
copy.Set(reflect.MakeMap(original.Type()))
for _, key := range original.MapKeys() {
originalValue := original.MapIndex(key)
copyValue := reflect.New(originalValue.Type()).Elem()
2021-05-11 08:53:39 +00:00
created := a.sanitize(concatenatePath(path, key.String()), originalValue, copyValue)
2021-03-26 08:44:55 +00:00
if created {
copy.SetMapIndex(key, copyValue)
}
}
default:
copy.Set(original)
}
return true
}