func GetNewCredentialsFileContents()

in aws_signing_helper/update.go [121:182]


func GetNewCredentialsFileContents(profileName string, readLines []string, cred *TemporaryCredential) []string {
	var profileExist = false
	var profileSection = "[" + profileName + "]"
	// A variable that checks whether or not required fields are written to the destination file
	newCredVisit := map[string]bool{"aws_access_key_id": false, "aws_secret_access_key": false, "aws_session_token": false}
	accessKey := "aws_access_key_id = " + cred.AccessKeyId + "\n"
	secretKey := "aws_secret_access_key = " + cred.SecretAccessKey + "\n"
	sessionToken := "aws_session_token = " + cred.SessionToken + "\n"
	var writeLines = make([]string, 0)
	for readLinesIndex := 0; readLinesIndex < len(readLines); readLinesIndex++ {
		if !profileExist && readLines[readLinesIndex] == profileSection {
			writeLines = append(writeLines[:], profileSection+"\n")
			readLinesIndex += 1
			for ; readLinesIndex < len(readLines); readLinesIndex++ {
				// If the last line of the credentials file is reached
				// OR the next profile section is reached
				if readLinesIndex == len(readLines)-1 || strings.HasPrefix(readLines[readLinesIndex], "[") {
					if !newCredVisit["aws_access_key_id"] {
						writeLines = append(writeLines[:], accessKey)
					}
					if !newCredVisit["aws_secret_access_key"] {
						writeLines = append(writeLines[:], secretKey)
					}
					if !newCredVisit["aws_session_token"] {
						writeLines = append(writeLines[:], sessionToken)

					}
					if readLinesIndex != len(readLines)-1 {
						readLinesIndex -= 1
					}
					profileExist = true
					break
				} else if strings.HasPrefix(readLines[readLinesIndex], "aws_access_key_id") {
					// replace "aws_access_key_id"
					writeLines = append(writeLines[:], accessKey)
					newCredVisit["aws_access_key_id"] = true
				} else if strings.HasPrefix(readLines[readLinesIndex], "aws_secret_access_key") {
					// replace "aws_secret_access_key"
					writeLines = append(writeLines[:], secretKey)
					newCredVisit["aws_secret_access_key"] = true
				} else if strings.HasPrefix(readLines[readLinesIndex], "aws_session_token") {
					// replace "aws_session_token"
					writeLines = append(writeLines[:], sessionToken)
					newCredVisit["aws_session_token"] = true
				} else {
					// write other keys
					writeLines = append(writeLines[:], readLines[readLinesIndex]+"\n")
				}
			}
		} else {
			writeLines = append(writeLines[:], readLines[readLinesIndex]+"\n")
		}
	}

	// If the chosen profile does not exist
	if !profileExist {
		writeCredential := profileSection + "\n" + accessKey + secretKey + sessionToken
		writeLines = append(writeLines[:], writeCredential+"\n")
	}

	return writeLines
}