|
| 1 | +/** |
| 2 | + * Simple script that deploys the zipped package to AWS Lambda. |
| 3 | + */ |
| 4 | + |
| 5 | +import AWS from 'aws-sdk'; |
| 6 | +import dotenv from 'dotenv'; |
| 7 | +import fs from 'fs-extra'; |
| 8 | +import path from 'path'; |
| 9 | +import print from './utils/print'; |
| 10 | + |
| 11 | +const errorExit = msg => { |
| 12 | + print.error(msg); |
| 13 | + return process.exit(1); |
| 14 | +}; |
| 15 | + |
| 16 | +(async function() { |
| 17 | + // Fetches AWS credentials and Lambda details from the .env file. |
| 18 | + dotenv.config(); |
| 19 | + |
| 20 | + // Validate if required environment variables are provided. |
| 21 | + const requiredEnv = [ |
| 22 | + 'AWS_ACCESS_KEY_ID', |
| 23 | + 'AWS_SECRET_ACCESS_KEY', |
| 24 | + 'AWS_REGION', |
| 25 | + 'LAMBDA_FUNCTION_NAME', |
| 26 | + ]; |
| 27 | + |
| 28 | + for (let env of requiredEnv) { |
| 29 | + if (!process.env[env]) { |
| 30 | + errorExit(`Missing environment variable: ${env}`); |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + const { |
| 35 | + AWS_REGION: region, |
| 36 | + AWS_ACCESS_KEY_ID: accessKeyId, |
| 37 | + AWS_SECRET_ACCESS_KEY: secretAccessKey, |
| 38 | + LAMBDA_FUNCTION_NAME: functionName, |
| 39 | + } = process.env; |
| 40 | + |
| 41 | + // Update the AWS credentials and region. |
| 42 | + AWS.config.update({ region, accessKeyId, secretAccessKey }); |
| 43 | + |
| 44 | + const artifactZipPath = path.join(__dirname, '../artifact.zip'); |
| 45 | + let artifactZipBuf; |
| 46 | + |
| 47 | + try { |
| 48 | + artifactZipBuf = await fs.readFile(artifactZipPath); |
| 49 | + } catch (err) { |
| 50 | + errorExit(err.message); |
| 51 | + } |
| 52 | + |
| 53 | + const Lambda = new AWS.Lambda(); |
| 54 | + const params = { |
| 55 | + FunctionName: functionName, |
| 56 | + ZipFile: artifactZipBuf, |
| 57 | + }; |
| 58 | + |
| 59 | + // Update the Lambda function code. |
| 60 | + try { |
| 61 | + await Lambda.updateFunctionCode(params).promise(); |
| 62 | + } catch (err) { |
| 63 | + errorExit(err.message); |
| 64 | + } |
| 65 | + |
| 66 | + print.success('Successfully uploaded to AWS Lambda!'); |
| 67 | +})(); |
0 commit comments