gruntwork-io/cloud-nuke

Querying for global resources in library mode uses the default AWS Session instead of the externalcreds configuration

Closed this issue · 0 comments

Hi,

I am building some tooling around this project, to clean up automatically some AWS account in our AWS Organization. For this, I used aws-go-sdk and this project as a library to

  1. Connect using an IAM user in our organization root account , let's call this account ROOT
  2. Using OrganizationAccountAccessRole role in children AWS account, I assume one by one this role in all children AWS accounts (A, B, C...)
  3. Then I run cloud-nuke as a library into sub account one by one. Since the library uses aws-go-sdk v1, I manually create the AWS configuration for this sub account from the result of sts.AssumeRole function.

Here a simplified example code:

roleARN := fmt.Sprintf("arn:aws:iam::%s:role/OrganizationAccountAccessRole", *account.Id)
sessionName := "cloud-nuker"
fmt.Printf("Assuming role %s in account %s\n", roleARN, *account.Name)
result, err := stsClient.AssumeRole(context.TODO(), &sts.AssumeRoleInput{
	RoleArn:         &roleARN,
	RoleSessionName: &sessionName,
})
// ...
myCustomConfig := &aws_v1.Config{}
myCustomConfig.WithMaxRetries(3)
myCustomConfig.WithLogLevel(aws_v1.LogDebugWithRequestErrors)
myCustomConfig.WithCredentials(credentials_v1.NewStaticCredentials(
	*result.Credentials.AccessKeyId,
	*result.Credentials.SecretAccessKey,
	*result.Credentials.SessionToken,
))

externalcreds.Set(myCustomConfig)
// ....
accountResources, err := nuke_aws.GetAllResources(
  regions,
  excludeAfter,
  resourceTypes,
  configObj,
  allowDeleteUnaliasedKeys,
)
// ...

nukableResources := nuke_aws.ExtractResourcesForPrinting(accountResources)

fmt.Printf("The following %d AWS resources will be nuked:\n", len(nukableResources))

for _, resource := range nukableResources {
  fmt.Printf("  - %s\n", resource)
}

While debugging it, I noticed that

  • for regional resources (S3, EC2, etc...) the resources from children account A are listed ✔️
  • for global resouces such as IAM, the resources from root account ROOT are listed ❎

I have investigated into this project source code and I think I found the bug (I'll link a PR). It seems that #326 partially implemented the support for custom config in AWS Sessions:

  • Uses session from external-creds for regional resources ✔️
    cloudNukeSession := newSession(region)
  • Uses another function for global resources, which dot not use the externalcreds config ❎
    session, err := newAWSSession(sessionRegion)

Therefore, for global resources, cloud-nuke uses my local creds (for the root account) instead of supplied config for children accounts.

I fixed this bug on my fork, I'll send a PR right away