Skip to content

Commit

Permalink
fixes ported from Fugue
Browse files Browse the repository at this point in the history
  • Loading branch information
Evan Nemerson committed Apr 25, 2024
1 parent 83da351 commit 948d2e8
Show file tree
Hide file tree
Showing 20 changed files with 326 additions and 73 deletions.
4 changes: 3 additions & 1 deletion internal/service/account/alternate_contact.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,9 @@ func resourceAlternateContactRead(ctx context.Context, d *schema.ResourceData, m
return sdkdiag.AppendFromErr(diags, err)
}

output, err := findAlternateContactByTwoPartKey(ctx, conn, accountID, contactType)
// AccountID is replaced by empty string because it must be a member account in the org if used
// See https://docs.aws.amazon.com/accounts/latest/reference/API_GetAlternateContact.html#API_GetAlternateContact_RequestSyntax
output, err := findAlternateContactByTwoPartKey(ctx, conn, "", contactType)

if !d.IsNewResource() && tfresource.NotFound(err) {
log.Printf("[WARN] Account Alternate Contact (%s) not found, removing from state", d.Id())
Expand Down
2 changes: 0 additions & 2 deletions internal/service/apigateway/domain_name.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,6 @@ func resourceDomainName() *schema.Resource {
Type: schema.TypeList,
Required: true,
MinItems: 1,
// BadRequestException: Cannot create an api with multiple Endpoint Types
MaxItems: 1,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice(enum.Slice(types.EndpointTypeEdge, types.EndpointTypeRegional), false),
Expand Down
4 changes: 3 additions & 1 deletion internal/service/cloudfront/forge.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ func sortInterfaceSlice(in []interface{}) []interface{} {
a := []string{}
b := []interface{}{}
for _, v := range in {
a = append(a, v.(string))
if v != nil {
a = append(a, v.(string))
}
}

sort.Strings(a)
Expand Down
7 changes: 4 additions & 3 deletions internal/service/cloudtrail/cloudtrail.go
Original file line number Diff line number Diff line change
Expand Up @@ -706,10 +706,11 @@ func expandEventSelectorDataResource(configured []interface{}) []types.DataResou
func flattenEventSelector(configured []types.EventSelector) []map[string]interface{} {
eventSelectors := make([]map[string]interface{}, 0, len(configured))

// We want to output all the selectors (note for advanced event selectors this is empty)
// Prevent default configurations shows differences
if len(configured) == 1 && len(configured[0].DataResources) == 0 && configured[0].ReadWriteType == types.ReadWriteTypeAll && len(configured[0].ExcludeManagementEventSources) == 0 {
return eventSelectors
}
// if len(configured) == 1 && len(configured[0].DataResources) == 0 && configured[0].ReadWriteType == types.ReadWriteTypeAll && len(configured[0].ExcludeManagementEventSources) == 0 {
// return eventSelectors
// }

for _, raw := range configured {
item := make(map[string]interface{})
Expand Down
8 changes: 8 additions & 0 deletions internal/service/cognitoidp/user_pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -896,6 +896,14 @@ func resourceUserPoolRead(ctx context.Context, d *schema.ResourceData, meta inte

setTagsOut(ctx, userPool.UserPoolTags)

// Set mfa_configuration the existing way if available
if userPool.MfaConfiguration != nil {
d.Set("mfa_configuration", *userPool.MfaConfiguration)
}

// Try to fetch it via the new operation and set mfa_configuration / software_token_mfa_configuration
// This requires new permissions to succeed

input := &cognitoidentityprovider.GetUserPoolMfaConfigInput{
UserPoolId: aws.String(d.Id()),
}
Expand Down
3 changes: 2 additions & 1 deletion internal/service/ds/directory.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,8 @@ func ResourceDirectory() *schema.Resource {
},
"password": {
Type: schema.TypeString,
Required: true,
Optional: true,
Computed: true,
ForceNew: true,
Sensitive: true,
},
Expand Down
93 changes: 92 additions & 1 deletion internal/service/ec2/ec2_instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,31 @@ func ResourceInstance() *schema.Resource {
Optional: true,
AtLeastOneOf: []string{"ami", "launch_template"},
},

// Snyk: custom attributes begin

"ami_owner_id": {
Type: schema.TypeString,
Computed: true,
},

"ami_creation_date": {
Type: schema.TypeString,
Computed: true,
},

"ami_platform_details": {
Type: schema.TypeString,
Computed: true,
},

"launch_time": {
Type: schema.TypeString,
Computed: true,
},

// Snyk: custom attributes end

"arn": {
Type: schema.TypeString,
Computed: true,
Expand Down Expand Up @@ -1211,6 +1236,13 @@ func resourceInstanceRead(ctx context.Context, d *schema.ResourceData, meta inte
d.Set("iam_instance_profile", nil)
}

if err := readImageAttributes(d, conn); err != nil {
return sdkdiag.AppendErrorf(diags, "unable to read image attributes: %s", err)
}
if instance.LaunchTime != nil {
d.Set("launch_time", instance.LaunchTime.Format(time.RFC3339))
}

{
launchTemplate, err := flattenInstanceLaunchTemplate(ctx, conn, d.Id(), d.Get("launch_template.0.version").(string))

Expand Down Expand Up @@ -2192,12 +2224,64 @@ func disableInstanceAPIStop(ctx context.Context, conn *ec2.EC2, id string, disab
return nil
}

func readImageAttributes(d *schema.ResourceData, conn *ec2.EC2) error {

imageID := d.Get("ami").(string)
var image *ec2.Image

err := retry.Retry(1*time.Minute, func() *retry.RetryError {
res, err := conn.DescribeImages(&ec2.DescribeImagesInput{
ImageIds: []*string{aws.String(imageID)},
})
if isResourceTimeoutError(err) {
return retry.RetryableError(err)
}
if tfawserr.ErrCodeEquals(err, "InvalidAMIID.Unavailable") || tfawserr.ErrCodeEquals(err, "InvalidAMIID.NotFound") {
return nil
}
if err != nil {
return retry.NonRetryableError(err)
}
if len(res.Images) == 0 {
return nil
}
image = res.Images[0]
return nil
})
if err != nil {
return fmt.Errorf("Unable to describe AMI after retries: %s", err)
}
// Don't fail the refresh if the AMI was not found
if image == nil {
return nil
}

if image.OwnerId != nil {
d.Set("ami_owner_id", image.OwnerId)
}
if image.PlatformDetails != nil {
d.Set("ami_platform_details", image.PlatformDetails)
}
if image.CreationDate != nil {
d.Set("ami_creation_date", image.CreationDate)
}
return nil
}

func isResourceTimeoutError(err error) bool {
timeoutErr, ok := err.(*retry.TimeoutError)
return ok && timeoutErr.LastError == nil
}

func disableInstanceAPITermination(ctx context.Context, conn *ec2.EC2, id string, disableAPITermination bool) error {
// false = enable api termination
// true = disable api termination (protected)

input := &ec2.ModifyInstanceAttributeInput{
InstanceId: aws.String(id),
DisableApiTermination: &ec2.AttributeBooleanValue{
Value: aws.Bool(disableAPITermination),
},
InstanceId: aws.String(id),
}

_, err := conn.ModifyInstanceAttributeWithContext(ctx, input)
Expand Down Expand Up @@ -2317,6 +2401,10 @@ func readBlockDevicesFromInstance(ctx context.Context, d *schema.ResourceData, m
VolumeIds: volIDs,
})
if err != nil {
if tfawserr.ErrMessageContains(err, errCodeInvalidVolumeNotFound, "does not exist") {
log.Print("[WARN] Unable to describe volumes attached to instance")
return blockDevices, nil
}
return nil, err
}

Expand Down Expand Up @@ -2433,6 +2521,9 @@ func FetchRootDeviceName(ctx context.Context, conn *ec2.EC2, amiID string) (*str

image, err := FindImageByID(ctx, conn, amiID)

if tfawserr.ErrCodeEquals(err, errCodeInvalidAMIIDUnavailable) || tfawserr.ErrCodeEquals(err, "InvalidAMIID.NotFound") {
return nil, nil
}
if err != nil {
return nil, err
}
Expand Down
20 changes: 13 additions & 7 deletions internal/service/ec2/ec2_spot_fleet_request.go
Original file line number Diff line number Diff line change
Expand Up @@ -2092,15 +2092,21 @@ func hashRootBlockDevice(v interface{}) int {
func hashLaunchSpecification(v interface{}) int {
var buf bytes.Buffer
m := v.(map[string]interface{})
buf.WriteString(fmt.Sprintf("%s-", m["ami"].(string)))
if v, ok := m["availability_zone"].(string); ok && v != "" {
buf.WriteString(fmt.Sprintf("%s-", v))
if _, ok := m["ami"]; ok {
buf.WriteString(fmt.Sprintf("%s-", m["ami"].(string)))
}
if v, ok := m["subnet_id"].(string); ok && v != "" {
buf.WriteString(fmt.Sprintf("%s-", v))
if _, ok := m["availability_zone"]; ok {
buf.WriteString(fmt.Sprintf("%s-", m["availability_zone"].(string)))
}
if _, ok := m["subnet_id"]; ok {
buf.WriteString(fmt.Sprintf("%s-", m["subnet_id"].(string)))
}
if _, ok := m["instance_type"]; ok {
buf.WriteString(fmt.Sprintf("%s-", m["instance_type"].(string)))
}
if _, ok := m["spot_price"]; ok {
buf.WriteString(fmt.Sprintf("%s-", m["spot_price"].(string)))
}
buf.WriteString(fmt.Sprintf("%s-", m["instance_type"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["spot_price"].(string)))
return create.StringHashcode(buf.String())
}

Expand Down
5 changes: 5 additions & 0 deletions internal/service/ec2/vpc_.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,10 @@ func ResourceVPC() *schema.Resource {
ConflictsWith: []string{"ipv6_cidr_block"},
RequiredWith: []string{"ipv6_ipam_pool_id"},
},
"is_default": {
Type: schema.TypeBool,
Computed: true,
},
"main_route_table_id": {
Type: schema.TypeString,
Computed: true,
Expand Down Expand Up @@ -287,6 +291,7 @@ func resourceVPCRead(ctx context.Context, d *schema.ResourceData, meta interface
d.Set("dhcp_options_id", vpc.DhcpOptionsId)
d.Set("instance_tenancy", vpc.InstanceTenancy)
d.Set("owner_id", ownerID)
d.Set("is_default", vpc.IsDefault)

if v, err := tfresource.RetryWhenNewResourceNotFound(ctx, ec2PropagationTimeout, func() (interface{}, error) {
return findVPCAttributeV2(ctx, conn, d.Id(), types.VpcAttributeNameEnableDnsHostnames)
Expand Down
2 changes: 1 addition & 1 deletion internal/service/ec2/vpc_endpoint_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ func ResourceVPCEndpointService() *schema.Resource {
"network_load_balancer_arns": {
Type: schema.TypeSet,
Optional: true,
MinItems: 1,
// MinItems: 1,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: verify.ValidARN,
Expand Down
2 changes: 1 addition & 1 deletion internal/service/ec2/vpc_network_interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -517,7 +517,7 @@ func resourceNetworkInterfaceRead(ctx context.Context, d *schema.ResourceData, m
Resource: "network-interface/" + d.Id(),
}.String()
d.Set("arn", arn)
if eni.Attachment != nil {
if eni.Attachment != nil && eni.Attachment.DeviceIndex != nil && eni.Attachment.AttachmentId != nil {
if err := d.Set("attachment", []interface{}{flattenNetworkInterfaceAttachment(eni.Attachment)}); err != nil {
return sdkdiag.AppendErrorf(diags, "setting attachment: %s", err)
}
Expand Down
96 changes: 48 additions & 48 deletions internal/service/organizations/organization.go
Original file line number Diff line number Diff line change
Expand Up @@ -253,67 +253,67 @@ func resourceOrganizationRead(ctx context.Context, d *schema.ResourceData, meta
return sdkdiag.AppendErrorf(diags, "reading Organization: %s", err)
}

accounts, err := findAccounts(ctx, conn)

if err != nil {
return sdkdiag.AppendErrorf(diags, "reading Organization (%s) accounts: %s", d.Id(), err)
}

managementAccountID := aws.StringValue(org.MasterAccountId)
managementAccountName := ""
for _, v := range accounts {
if aws.StringValue(v.Id) == managementAccountID {
managementAccountName = aws.StringValue(v.Name)
}
}
nonManagementAccounts := tfslices.Filter(accounts, func(v *organizations.Account) bool {
return aws.StringValue(v.Id) != managementAccountID
})

roots, err := findRoots(ctx, conn)

if err != nil {
return sdkdiag.AppendErrorf(diags, "reading Organization (%s) roots: %s", d.Id(), err)
}

if err := d.Set("accounts", flattenAccounts(accounts)); err != nil {
return sdkdiag.AppendErrorf(diags, "setting accounts: %s", err)
}
// accounts, err := findAccounts(ctx, conn)

// if err != nil {
// return sdkdiag.AppendErrorf(diags, "reading Organization (%s) accounts: %s", d.Id(), err)
// }

// managementAccountID := aws.StringValue(org.MasterAccountId)
// managementAccountName := ""
// for _, v := range accounts {
// if aws.StringValue(v.Id) == managementAccountID {
// managementAccountName = aws.StringValue(v.Name)
// }
// }
// nonManagementAccounts := tfslices.Filter(accounts, func(v *organizations.Account) bool {
// return aws.StringValue(v.Id) != managementAccountID
// })

// roots, err := findRoots(ctx, conn)

// if err != nil {
// return sdkdiag.AppendErrorf(diags, "reading Organization (%s) roots: %s", d.Id(), err)
// }

// if err := d.Set("accounts", flattenAccounts(accounts)); err != nil {
// return sdkdiag.AppendErrorf(diags, "setting accounts: %s", err)
// }
d.Set("arn", org.Arn)
d.Set("feature_set", org.FeatureSet)
d.Set("master_account_arn", org.MasterAccountArn)
d.Set("master_account_email", org.MasterAccountEmail)
d.Set("master_account_id", org.MasterAccountId)
d.Set("master_account_name", managementAccountName)
if err := d.Set("non_master_accounts", flattenAccounts(nonManagementAccounts)); err != nil {
return sdkdiag.AppendErrorf(diags, "setting non_master_accounts: %s", err)
}
if err := d.Set("roots", flattenRoots(roots)); err != nil {
return sdkdiag.AppendErrorf(diags, "setting roots: %s", err)
}
// d.Set("master_account_name", managementAccountName)
// if err := d.Set("non_master_accounts", flattenAccounts(nonManagementAccounts)); err != nil {
// return sdkdiag.AppendErrorf(diags, "setting non_master_accounts: %s", err)
// }
// if err := d.Set("roots", flattenRoots(roots)); err != nil {
// return sdkdiag.AppendErrorf(diags, "setting roots: %s", err)
// }

var awsServiceAccessPrincipals []string
// var awsServiceAccessPrincipals []string

// ConstraintViolationException: The request failed because the organization does not have all features enabled. Please enable all features in your organization and then retry.
if aws.StringValue(org.FeatureSet) == organizations.OrganizationFeatureSetAll {
awsServiceAccessPrincipals, err = FindEnabledServicePrincipalNames(ctx, conn)
// if aws.StringValue(org.FeatureSet) == organizations.OrganizationFeatureSetAll {
// awsServiceAccessPrincipals, err = FindEnabledServicePrincipalNames(ctx, conn)

if err != nil {
return sdkdiag.AppendErrorf(diags, "reading Organization (%s) service principals: %s", d.Id(), err)
}
}
// if err != nil {
// return sdkdiag.AppendErrorf(diags, "reading Organization (%s) service principals: %s", d.Id(), err)
// }
// }

d.Set("aws_service_access_principals", awsServiceAccessPrincipals)
// d.Set("aws_service_access_principals", awsServiceAccessPrincipals)

var enabledPolicyTypes []string
// var enabledPolicyTypes []string

for _, policyType := range roots[0].PolicyTypes {
if aws.StringValue(policyType.Status) == organizations.PolicyTypeStatusEnabled {
enabledPolicyTypes = append(enabledPolicyTypes, aws.StringValue(policyType.Type))
}
}
// for _, policyType := range roots[0].PolicyTypes {
// if aws.StringValue(policyType.Status) == organizations.PolicyTypeStatusEnabled {
// enabledPolicyTypes = append(enabledPolicyTypes, aws.StringValue(policyType.Type))
// }
// }

d.Set("enabled_policy_types", enabledPolicyTypes)
// d.Set("enabled_policy_types", enabledPolicyTypes)

return diags
}
Expand Down
Loading

0 comments on commit 948d2e8

Please sign in to comment.