driftctl/pkg/remote/aws/iam_user_policy_attachment_...

78 lines
2.5 KiB
Go
Raw Normal View History

package aws
import (
2021-05-21 14:09:45 +00:00
"fmt"
"github.com/cloudskiff/driftctl/pkg/remote/aws/repository"
remoteerror "github.com/cloudskiff/driftctl/pkg/remote/error"
"github.com/cloudskiff/driftctl/pkg/resource"
resourceaws "github.com/cloudskiff/driftctl/pkg/resource/aws"
2021-05-21 14:09:45 +00:00
"github.com/cloudskiff/driftctl/pkg/terraform"
"github.com/sirupsen/logrus"
"github.com/zclconf/go-cty/cty"
)
type IamUserPolicyAttachmentSupplier struct {
reader terraform.ResourceReader
2021-05-21 14:09:45 +00:00
deserializer *resource.Deserializer
repository repository.IAMRepository
runner *terraform.ParallelResourceReader
}
func NewIamUserPolicyAttachmentSupplier(provider *AWSTerraformProvider, deserializer *resource.Deserializer, repository repository.IAMRepository) *IamUserPolicyAttachmentSupplier {
return &IamUserPolicyAttachmentSupplier{
provider,
2021-05-21 14:09:45 +00:00
deserializer,
repository,
terraform.NewParallelResourceReader(provider.Runner().SubRunner()),
}
}
func (s *IamUserPolicyAttachmentSupplier) Resources() ([]resource.Resource, error) {
users, err := s.repository.ListAllUsers()
if err != nil {
return nil, remoteerror.NewResourceEnumerationErrorWithType(err, resourceaws.AwsIamUserPolicyAttachmentResourceType, resourceaws.AwsIamUserResourceType)
}
policyAttachments, err := s.repository.ListAllUserPolicyAttachments(users)
if err != nil {
return nil, remoteerror.NewResourceEnumerationError(err, resourceaws.AwsIamUserPolicyAttachmentResourceType)
}
results := make([]cty.Value, 0)
if len(policyAttachments) > 0 {
for _, attachedPolicy := range policyAttachments {
attached := *attachedPolicy
s.runner.Run(func() (cty.Value, error) {
return s.readUserPolicyAttachment(&attached)
})
}
results, err = s.runner.Wait()
if err != nil {
return nil, err
}
}
2021-05-21 14:09:45 +00:00
return s.deserializer.Deserialize(resourceaws.AwsIamUserPolicyAttachmentResourceType, results)
}
func (s *IamUserPolicyAttachmentSupplier) readUserPolicyAttachment(attachedPol *repository.AttachedUserPolicy) (cty.Value, error) {
res, err := s.reader.ReadResource(
terraform.ReadResourceArgs{
Ty: resourceaws.AwsIamUserPolicyAttachmentResourceType,
ID: fmt.Sprintf("%s-%s", *attachedPol.PolicyName, attachedPol.UserName),
Attributes: map[string]string{
"user": attachedPol.UserName,
"policy_arn": *attachedPol.PolicyArn,
},
},
)
if err != nil {
logrus.Warnf("Error reading iam user policy attachment %s[%s]: %+v", attachedPol, resourceaws.AwsIamUserPolicyAttachmentResourceType, err)
return cty.NilVal, err
}
return *res, nil
}