Skip to content

Commit

Permalink
go-staticcheck
Browse files Browse the repository at this point in the history
  • Loading branch information
omerh committed Mar 31, 2024
1 parent d88a52f commit 7ed26a1
Show file tree
Hide file tree
Showing 11 changed files with 69 additions and 78 deletions.
1 change: 1 addition & 0 deletions cmd/awsctl/cmd/delete_ecr_images.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ func getEcrImagesAndDeleteOld(repos []*ecr.Repository, region string, keep int,
for _, imageDetail := range imageDetails {
digest = append(digest, *imageDetail.ImageDigest)
}
// log.Printf("%v", digest)
helpers.DeleteEcrImages(*repo.RepositoryName, digest, region, apply)
}
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/awsctl/cmd/scan_s3.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ var scanS3 = &cobra.Command{
// get s3 server side encryption
encryptioSet := helpers.CheckBucketEncryption(*bucket.Name, region)
// get s3 public access
helpers.GetS3PuclicAccess(*bucket.Name, region)
helpers.GetS3PublicAccess(*bucket.Name, region)
bucket := s3bucket{
name: *bucket.Name,
region: region,
Expand Down
32 changes: 16 additions & 16 deletions pkg/helpers/cost.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,23 @@ import (
"github.com/aws/aws-sdk-go/service/pricing"
)

type rawAmazonCloudWatch struct {
FormatVersion string
Disclaimer string
OfferCode string
Version string
PublicationDate string
Products map[string]string
Terms map[string]map[string]map[string]rawAmazonCloudWatchTerm
}
// type rawAmazonCloudWatch struct {
// FormatVersion string
// Disclaimer string
// OfferCode string
// Version string
// PublicationDate string
// Products map[string]string
// Terms map[string]map[string]map[string]rawAmazonCloudWatchTerm
// }

type rawAmazonCloudWatchTerm struct {
OfferTermCode string
Sku string
EffectiveDate string
PriceDimensions map[string]string
TermAttributes map[string]string
}
// type rawAmazonCloudWatchTerm struct {
// OfferTermCode string
// Sku string
// EffectiveDate string
// PriceDimensions map[string]string
// TermAttributes map[string]string
// }

// GetAwsServiceCost use to get a product code for getting price
//
Expand Down
53 changes: 23 additions & 30 deletions pkg/helpers/ecr.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,19 +30,17 @@ func GetECRRepositories(region string) []*ecr.Repository {
input := &ecr.DescribeRepositoriesInput{}
result, _ := svc.DescribeRepositories(input)

registeriesSlice := result.Repositories
registriesSlice := result.Repositories

// iterate over NextToken to retrive all repositories from Ecr in the region
for result.NextToken != nil {
input := &ecr.DescribeRepositoriesInput{
NextToken: result.NextToken,
}
result, _ = svc.DescribeRepositories(input)
for _, registry := range result.Repositories {
registeriesSlice = append(registeriesSlice, registry)
}
registriesSlice = append(registriesSlice, result.Repositories...)
}
return registeriesSlice
return registriesSlice
}

// CheckECRRepositoryLifecyclePolicy for a repository in a region
Expand All @@ -55,11 +53,9 @@ func CheckECRRepositoryLifecyclePolicy(repositoryName string, region string) boo
_, err := svc.GetLifecyclePolicy(input)
if err != nil {
// Ecr lifecyclePolicy is not set
// log.Printf("error: %v", err)
return false
log.Printf("error: %v", err)
}

return true
return err == nil
}

// SetEcrRepositoryLifecyclePolicy set the life time policy
Expand Down Expand Up @@ -127,47 +123,44 @@ func EcrDescribeImages(repositoryName string, region string, keep int) ([]*ecr.I
}
result, _ := svc.DescribeImages(input)

iamgesDetailsSlice := result.ImageDetails
imagesDetailsSlice := result.ImageDetails

// iterate over NextToken to retrive all repositories from Ecr in the region
// iterate over NextToken to retrieve all repositories from Ecr in the region
for result.NextToken != nil {
input := &ecr.DescribeImagesInput{
RepositoryName: aws.String(repositoryName),
NextToken: result.NextToken,
}
result, _ = svc.DescribeImages(input)
for _, imageDetails := range result.ImageDetails {
iamgesDetailsSlice = append(iamgesDetailsSlice, imageDetails)
}
imagesDetailsSlice = append(imagesDetailsSlice, result.ImageDetails...)
}
sortedImagesToDelete := sortEcrRepos(iamgesDetailsSlice, keep)
return sortedImagesToDelete, len(iamgesDetailsSlice) - len(sortedImagesToDelete)
sortedImagesToDelete := sortEcrRepos(imagesDetailsSlice, keep)
return sortedImagesToDelete, len(imagesDetailsSlice) - len(sortedImagesToDelete)
}

func sortEcrRepos(imagesDetail []*ecr.ImageDetail, keep int) []*ecr.ImageDetail {
iarr := ImageArr{}
iarr = imagesDetail
sort.Stable(iarr)
if len(iarr) > keep {
iarr = iarr[keep:]
var imageArray ImageArr = imagesDetail
sort.Stable(imageArray)
if len(imageArray) > keep {
imageArray = imageArray[keep:]
}
return iarr
return imageArray
}

// DeleteEcrImages delete according to image digest
func DeleteEcrImages(repo string, digest []string, region string, apply bool) {
imgs := make([]*ecr.ImageIdentifier, len(digest))
images := make([]*ecr.ImageIdentifier, len(digest))

for k, v := range digest {
t := &ecr.ImageIdentifier{}
t.ImageDigest = aws.String(v)
imgs[k] = t
images[k] = t
}

bulk := 100

for i := 0; i < len(imgs); i += bulk {
batch := imgs[i:min(i+bulk, len(imgs))]
for i := 0; i < len(images); i += bulk {
batch := images[i:min(i+bulk, len(images))]
deleteImagesBatch(repo, region, batch, apply)
}
}
Expand All @@ -179,21 +172,21 @@ func min(a, b int) int {
return b
}

func deleteImagesBatch(repo string, region string, imgs []*ecr.ImageIdentifier, apply bool) {
func deleteImagesBatch(repo string, region string, images []*ecr.ImageIdentifier, apply bool) {
awsSession, _ := InitAwsSession(region)
svc := ecr.New(awsSession)
input := &ecr.BatchDeleteImageInput{
RepositoryName: aws.String(repo),
ImageIds: imgs,
ImageIds: images,
}

if apply {
fmt.Printf("Deleting bulk of %v images from repo %v\n", len(imgs), repo)
log.Printf("Repo: %v, deleting bulk of %v images\n", repo, len(images))
_, err := svc.BatchDeleteImage(input)
if err != nil {
log.Fatal(err)
}
} else {
fmt.Printf("Should delete %v images from repo %v, pass --yes to apply\n", len(imgs), repo)
log.Printf("Repo: %v, should delete %v images, pass --yes to apply\n", repo, len(images))
}
}
6 changes: 2 additions & 4 deletions pkg/helpers/elasticNetworkInterface.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,7 @@ func GetAllElasticNetworkInterfaces(region string, filter string) []*ec2.Network
Filters: networkInterfaceFilter,
}
result, _ = svc.DescribeNetworkInterfaces(input)
for _, n := range result.NetworkInterfaces {
networkInterfacesSlice = append(networkInterfacesSlice, n)
}
networkInterfacesSlice = append(networkInterfacesSlice, result.NetworkInterfaces...)
}

return networkInterfacesSlice
Expand All @@ -60,7 +58,7 @@ func DeleteNetworkInterface(region string, networkInterfaceID string, apply bool
}
_, err = svc.DeleteNetworkInterface(input)
if err != nil {
log.Printf("There was a problme deleting network interface\n%v", err)
log.Printf("There was a problem deleting network interface\n%v", err)
return false
}
}
Expand Down
4 changes: 1 addition & 3 deletions pkg/helpers/lambda.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,7 @@ func GetAllLambdaInRegion(region string, arn string) []*lambda.FunctionConfigura
Marker: result.NextMarker,
}
result, _ = svc.ListFunctions(input)
for _, l := range result.Functions {
lambdas = append(lambdas, l)
}
lambdas = append(lambdas, result.Functions...)
}

// Filter out lambda
Expand Down
10 changes: 5 additions & 5 deletions pkg/helpers/rds.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,13 +94,13 @@ func GetRDSSnapshots(resourceName string, rdsType string, region string, out str
switch rdsType {
case "instance":
var response []*rds.DBSnapshot
rdsSnapshotInfoSlice, response = getRdsInstanceSnapshot(resourceName, region, out)
rdsSnapshotInfoSlice, response = getRdsInstanceSnapshot(resourceName, region)
if out == "json" {
outputs.PrintGenericJSONOutput(response, region)
}
case "cluster":
var response []*rds.DBClusterSnapshot
rdsSnapshotInfoSlice, response = getRdsDBClusterSnapshot(resourceName, region, out)
rdsSnapshotInfoSlice, response = getRdsDBClusterSnapshot(resourceName, region)
if out == "json" {
outputs.PrintGenericJSONOutput(response, region)
}
Expand All @@ -110,7 +110,7 @@ func GetRDSSnapshots(resourceName string, rdsType string, region string, out str
return rdsSnapshotInfoSlice
}

func getRdsDBClusterSnapshot(resourceName string, region string, out string) ([]RdsSnapshotInfo, []*rds.DBClusterSnapshot) {
func getRdsDBClusterSnapshot(resourceName string, region string) ([]RdsSnapshotInfo, []*rds.DBClusterSnapshot) {
awsSession, _ := InitAwsSession(region)
svc := rds.New(awsSession)
var input *rds.DescribeDBClusterSnapshotsInput
Expand Down Expand Up @@ -155,7 +155,7 @@ func PrintRdsSnapshotInformation(rdsSnapshotInformation []RdsSnapshotInfo, regio
log.Println("==============================================")
}

func getRdsInstanceSnapshot(resourceName string, region string, out string) ([]RdsSnapshotInfo, []*rds.DBSnapshot) {
func getRdsInstanceSnapshot(resourceName string, region string) ([]RdsSnapshotInfo, []*rds.DBSnapshot) {
awsSession, _ := InitAwsSession(region)
svc := rds.New(awsSession)
var input *rds.DescribeDBSnapshotsInput
Expand Down Expand Up @@ -225,7 +225,7 @@ func DeleteRdsSnapshots(rdsSnapshots []RdsSnapshotInfo, older int, region string
for _, s := range rdsSnapshots {
if s.snapshotCreatedTime.Before(deleteDate) {
log.Printf("Deleting %v that was created at %v for db %v", s.dbSnapshotIdentifier, s.snapshotCreatedTime, s.dbIdentifier)
if apply == true {
if apply {
deleteSnapshot(s.dbSnapshotIdentifier, region, rdsType)
} else {
log.Println("Add -y/--yes to confirm delete")
Expand Down
8 changes: 4 additions & 4 deletions pkg/helpers/regions.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (

var allRegions []string

// GetAllAwsRegions will retrive all aws regions
// GetAllAwsRegions will retrieve all aws regions
//
func GetAllAwsRegions() ([]string, error) {
// log.Println("Getting all regions...")
Expand All @@ -24,14 +24,14 @@ func GetAllAwsRegions() ([]string, error) {
config := aws.NewConfig().WithRegion(awsRegion)
sess, err := session.NewSession(config)
if err != nil {
return allRegions, fmt.Errorf("Error starting a new AWS session: %v", err)
return allRegions, fmt.Errorf("error starting a new AWS session: %v", err)
}

client := ec2.New(sess, config)

response, err := client.DescribeRegions(request)
if err != nil {
return allRegions, fmt.Errorf("Got an error while querying for valid regions (verify your AWS credentials?): %v", err)
return allRegions, fmt.Errorf("got an error while querying for valid regions (verify your AWS credentials?): %v", err)
}

for _, region := range response.Regions {
Expand All @@ -41,7 +41,7 @@ func GetAllAwsRegions() ([]string, error) {
return allRegions, nil
}

// GetDefaultAwsRegion resolve deafult region
// GetDefaultAwsRegion resolve default region
//
func GetDefaultAwsRegion() (region string) {
region = os.Getenv("AWS_REGION")
Expand Down
14 changes: 7 additions & 7 deletions pkg/helpers/reservations.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ import (
"github.com/aws/aws-sdk-go/service/ec2"
)

type riSummary struct {
instanceType string
instanceCount int
}
// type riSummary struct {
// instanceType string
// instanceCount int
// }

// GetAllReservations retrive all reservations
// GetAllReservations retrieve all reservations
func GetAllReservations(region string, state string) map[string]int64 {
awsSession, _ := InitAwsSession(region)
svc := ec2.New(awsSession)
Expand All @@ -28,11 +28,11 @@ func GetAllReservations(region string, state string) map[string]int64 {
}

result, _ := svc.DescribeReservedInstances(input)
summaryResult := summeriesRI(result)
summaryResult := summariesRI(result)
return summaryResult
}

func summeriesRI(ri *ec2.DescribeReservedInstancesOutput) map[string]int64 {
func summariesRI(ri *ec2.DescribeReservedInstancesOutput) map[string]int64 {
summary := make(map[string]int64, len(ri.ReservedInstances))
for _, r := range ri.ReservedInstances {
i := summary[*r.InstanceType]
Expand Down
15 changes: 8 additions & 7 deletions pkg/helpers/s3.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
"github.com/aws/aws-sdk-go/service/s3"
)

// GetAllS3Buckets retrives all the buckets in a region
// GetAllS3Buckets retrieves all the buckets in a region
func GetAllS3Buckets() []*s3.Bucket {
awsSession, _ := InitAwsSession("us-east-1")
svc := s3.New(awsSession)
Expand All @@ -17,7 +17,7 @@ func GetAllS3Buckets() []*s3.Bucket {
return result.Buckets
}

// CheckBucketEncryption check if bucket encription is set
// CheckBucketEncryption check if bucket encryption is set
func CheckBucketEncryption(bucket string, region string) bool {
awsSession, _ := InitAwsSession(region)
svc := s3.New(awsSession)
Expand All @@ -28,11 +28,12 @@ func CheckBucketEncryption(bucket string, region string) bool {
_, err := svc.GetBucketEncryption(input)
if err != nil {
// The server side encryption configuration was not found
// log.Printf("Error getting bucket encryption\n%v\n", err)
return false
log.Printf("Error getting bucket encryption\n%v\n", err)
// return false
}
// fmt.Println(result)
return true
return err == nil

}

// GetS3BucketLocation get a bucket region
Expand All @@ -54,8 +55,8 @@ func GetS3BucketLocation(bucket string) string {
return *result.LocationConstraint
}

// GetS3PuclicAccess get public access to s3 bucket
func GetS3PuclicAccess(bucket string, region string) {
// GetS3PublicAccess get public access to s3 bucket
func GetS3PublicAccess(bucket string, region string) {
awsSession, _ := InitAwsSession(region)
svc := s3.New(awsSession)
input := &s3.GetBucketAclInput{
Expand Down
2 changes: 1 addition & 1 deletion pkg/helpers/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
"github.com/aws/aws-sdk-go/aws/session"
)

var awsSession *session.Session
// var awsSession *session.Session

// InitAwsSession initialize aws session
func InitAwsSession(region string) (*session.Session, error) {
Expand Down

0 comments on commit 7ed26a1

Please sign in to comment.