driftctl/pkg/middlewares/aws_default_internet_gatewa...

70 lines
2.3 KiB
Go
Raw Normal View History

2021-01-20 21:54:41 +00:00
package middlewares
import (
"github.com/cloudskiff/driftctl/pkg/resource"
"github.com/cloudskiff/driftctl/pkg/resource/aws"
"github.com/sirupsen/logrus"
)
// Each default vpc has an internet gateway attached that should not be seen as unmanaged if not managed by IaC
// This middleware ignores default internet gateway from unmanaged resources if not managed by IaC
type AwsDefaultInternetGateway struct{}
func NewAwsDefaultInternetGateway() AwsDefaultInternetGateway {
return AwsDefaultInternetGateway{}
}
2021-08-09 14:03:04 +00:00
func (m AwsDefaultInternetGateway) Execute(remoteResources, resourcesFromState *[]*resource.Resource) error {
newRemoteResources := make([]*resource.Resource, 0)
2021-01-20 21:54:41 +00:00
for _, remoteResource := range *remoteResources {
// Ignore all resources other than internet gateways
if remoteResource.TerraformType() != aws.AwsInternetGatewayResourceType {
newRemoteResources = append(newRemoteResources, remoteResource)
continue
}
// Ignore all non-default internet gateways
2021-08-09 14:03:04 +00:00
if !isDefaultInternetGateway(remoteResource, remoteResources) {
2021-01-20 21:54:41 +00:00
newRemoteResources = append(newRemoteResources, remoteResource)
continue
}
// Check if internet gateway is managed by IaC
existInState := false
for _, stateResource := range *resourcesFromState {
2021-08-09 14:03:04 +00:00
if remoteResource.Equal(stateResource) {
2021-01-20 21:54:41 +00:00
existInState = true
break
}
}
// Include resource if it's managed in IaC
if existInState {
newRemoteResources = append(newRemoteResources, remoteResource)
continue
}
// Else, resource is not added to newRemoteResources slice so it will be ignored
logrus.WithFields(logrus.Fields{
2021-08-09 14:03:04 +00:00
"id": remoteResource.TerraformId(),
"type": remoteResource.TerraformType(),
2021-01-20 21:54:41 +00:00
}).Debug("Ignoring default internet gateway as it is not managed by IaC")
}
*remoteResources = newRemoteResources
return nil
}
// Return true if the internet gateway is the default one (e.g. attached to the default vpc)
2021-08-09 14:03:04 +00:00
func isDefaultInternetGateway(internetGateway *resource.Resource, remoteResources *[]*resource.Resource) bool {
2021-01-20 21:54:41 +00:00
for _, remoteResource := range *remoteResources {
if remoteResource.TerraformType() == aws.AwsDefaultVpcResourceType {
2021-05-17 11:24:58 +00:00
vpcId, exist := internetGateway.Attrs.Get("vpc_id")
return exist && vpcId == remoteResource.TerraformId()
2021-01-20 21:54:41 +00:00
}
}
return false
}