MCPcopy
hub / github.com/serverless/serverless / writeAwsCredentialsToFile

Function writeAwsCredentialsToFile

packages/sf-core/src/utils/fs/index.js:658–735  ·  view source on GitHub ↗
({
  accessKeyId,
  secretAccessKey,
  profileName = 'default',
  region = 'us-east-1',
})

Source from the content-addressed store, hash-verified

656 * @param secretAccessKey The AWS secret access key.
657 */
658const writeAwsCredentialsToFile = async ({
659 accessKeyId,
660 secretAccessKey,
661 profileName = 'default',
662 region = 'us-east-1',
663}) => {
664 const awsDirectoryPath = path.join(os.homedir(), '.aws')
665 const awsCredentialsFilePath = path.join(awsDirectoryPath, 'credentials')
666
667 // Create the .aws directory if it doesn't exist
668 if (!(await dirExists(awsDirectoryPath))) {
669 try {
670 await fsp.mkdir(awsDirectoryPath)
671 } catch (error) {
672 /* Ignore */
673 }
674 }
675
676 // Check if the credentials file exists
677 const credentialsFileExists = await fileExists(awsCredentialsFilePath)
678
679 // Read the credentials file if it doesn't exist
680 let credentialsFileContents = ''
681 if (credentialsFileExists) {
682 try {
683 credentialsFileContents = await readFile(awsCredentialsFilePath)
684 } catch (error) {
685 /* Ignore error */
686 }
687 }
688
689 const profile = `[${profileName}]`
690
691 // Check if the profile already exists in the credentials file
692 const profileExists = credentialsFileContents
693 ? credentialsFileContents.includes(profile)
694 : false
695
696 const newProfile = `${profile}\naws_access_key_id = ${accessKeyId}\naws_secret_access_key = ${secretAccessKey}\nregion = ${region}\n`
697
698 // If the profile exists, replace it and the aws_access_key_id and aws_secret_access_key
699 if (profileExists) {
700 // Convert the credentials file to an array of lines
701 const credentialsFileLines = credentialsFileContents.split('\n')
702 // Find the index of the profile in the credentials file
703 const profileIndex = credentialsFileLines.indexOf(profile)
704 /**
705 * Iterate through the lines after the profile index,
706 * until the next profile line that is enclosed in [] is found.
707 * If a line contains "aws_access_key_id" or "aws_secret_access_key" or "region",
708 * replace it with the new value.
709 */
710 for (let i = profileIndex + 1; i < credentialsFileLines.length; i++) {
711 if (credentialsFileLines[i].includes('aws_access_key_id')) {
712 credentialsFileLines[i] = `aws_access_key_id = ${accessKeyId}`
713 } else if (credentialsFileLines[i].includes('aws_secret_access_key')) {
714 credentialsFileLines[i] = `aws_secret_access_key = ${secretAccessKey}`
715 } else if (credentialsFileLines[i].includes('region')) {

Callers 1

createAwsCredentialsFunction · 0.90

Calls 4

dirExistsFunction · 0.70
fileExistsFunction · 0.70
readFileFunction · 0.70
writeFileFunction · 0.70

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…