github.com/Cloud-Foundations/Dominator@v0.3.4/lib/awsutil/accounts.go (about)

     1  package awsutil
     2  
     3  import (
     4  	"bufio"
     5  	"os"
     6  	"strings"
     7  )
     8  
     9  const (
    10  	kDefault = "default"
    11  )
    12  
    13  func listAccountNames(options *CredentialsOptions) ([]string, error) {
    14  	var accountNames []string
    15  	if names, err := listFile(options.CredentialsPath, "aws_access_key_id"); err != nil {
    16  		return nil, err
    17  	} else {
    18  		for _, name := range names {
    19  			if name != kDefault {
    20  				accountNames = append(accountNames, name)
    21  			}
    22  		}
    23  	}
    24  	if names, err := listFile(options.ConfigPath, "role_arn"); err != nil {
    25  		return nil, err
    26  	} else {
    27  		for _, name := range names {
    28  			if name != kDefault {
    29  				accountNames = append(accountNames, name)
    30  			}
    31  		}
    32  	}
    33  	return accountNames, nil
    34  }
    35  
    36  func listFile(pathname string, identifierKeyName string) ([]string, error) {
    37  	file, err := os.Open(pathname)
    38  	if err != nil {
    39  		if os.IsNotExist(err) {
    40  			return nil, nil
    41  		}
    42  		return nil, err
    43  	}
    44  	defer file.Close()
    45  	scanner := bufio.NewScanner(file)
    46  	accountNames := make([]string, 0)
    47  	accessKeyIds := make(map[string]struct{})
    48  	lastAccountName := ""
    49  	for scanner.Scan() {
    50  		line := scanner.Text()
    51  		if len(line) < 3 {
    52  			continue
    53  		}
    54  		if line[0] == '#' {
    55  			continue
    56  		}
    57  		if line[0] == '[' && line[len(line)-1] == ']' {
    58  			fields := strings.Fields(line[1 : len(line)-1])
    59  			if len(fields) == 1 {
    60  				lastAccountName = fields[0]
    61  			} else if len(fields) == 2 && fields[0] == "profile" {
    62  				lastAccountName = fields[1]
    63  			}
    64  			continue
    65  		}
    66  		if lastAccountName == "" {
    67  			continue
    68  		}
    69  		splitString := strings.Split(line, "=")
    70  		if len(splitString) != 2 {
    71  			continue
    72  		}
    73  		key := strings.TrimSpace(splitString[0])
    74  		value := strings.TrimSpace(splitString[1])
    75  		if key != identifierKeyName {
    76  			continue
    77  		}
    78  		if _, ok := accessKeyIds[value]; !ok {
    79  			accountNames = append(accountNames, lastAccountName)
    80  			accessKeyIds[value] = struct{}{}
    81  			lastAccountName = ""
    82  		}
    83  	}
    84  	return accountNames, scanner.Err()
    85  }