Last active
July 5, 2020 20:44
-
-
Save maurocen/fdb70e72b2c3da8744c7553da7c3f653 to your computer and use it in GitHub Desktop.
Deploy build directory to S3 bucket using aws-cli and environment variables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs'); | |
const path = require('path'); | |
const chalk = require('chalk'); | |
const appDirectory = fs.realpathSync(process.cwd()); | |
const resolveApp = relativePath => path.resolve(appDirectory, relativePath); | |
const cmd = (command) => { | |
const { exec } = require('child_process'); | |
return new Promise((resolve, reject) => { | |
exec(command, (error, stdout, stderr) => { | |
if (error) { | |
reject(stderr); | |
} else { | |
resolve(stdout); | |
} | |
}); | |
}); | |
} | |
const wait = (seconds) => new Promise((resolve) => { | |
setTimeout(() => resolve(), seconds * 1000); | |
}); | |
const s3deploy = async () => { | |
require('dotenv').config({ | |
path: `.${process.env.DEPLOY_ENVIRONMENT}.env`, | |
}); | |
const waitTimeInSeconds = 5; | |
console.log('\n%s %s\n\n', chalk.bold.underline('DEPLOYING TO:'), chalk.blue(process.env.DEPLOY_ENVIRONMENT)); | |
console.log('Giving you %s seconds to change your mind\n', chalk.blue.bold(waitTimeInSeconds)); | |
await wait(waitTimeInSeconds); | |
const buildPath = resolveApp('build'); | |
const awsAccessKey = `AWS_ACCESS_KEY_ID=${process.env.AWS_ACCESS_KEY}`; | |
const awsSecretAccessKey = `AWS_SECRET_ACCESS=${process.env.AWS_SECRET_ACCESS_KEY}`; | |
const awsCredentials = `${awsAccessKey} ${awsSecretAccessKey}`; | |
const awsRegion = `REGION=${process.env.AWS_REGION}`; | |
const awsBucket = `s3://${process.env.AWS_BUCKET_NAME}`; | |
const syncCommand = 'aws s3 sync'; | |
const awsCommand = `${syncCommand} ${buildPath} ${awsBucket}`; | |
const awsEnv = `${awsCredentials} ${awsRegion}`; | |
const command = `${awsEnv} ${awsCommand}`; | |
try { | |
const output = await cmd(command); | |
console.log(output); | |
console.log('%s', chalk.green.bold('SUCCESS!')); | |
} catch(error) { | |
console.log(error); | |
console.log('%s An error has occurred.', chalk.red.bold('ERROR:')); | |
} | |
} | |
module.exports = () => s3deploy(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment