Skip to content

Commit

Permalink
Update to use AWS SDK v3
Browse files Browse the repository at this point in the history
  • Loading branch information
brunomorency committed Jun 24, 2023
1 parent 87a6ef2 commit ee18e79
Show file tree
Hide file tree
Showing 11 changed files with 2,063 additions and 743 deletions.
29 changes: 7 additions & 22 deletions cli.js → cli.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

const packageInfo = require('./package.json')
const chalk = require('chalk')
const commandLineCommands = require('command-line-commands')
const commandLineArgs = require('command-line-args')

let commands = [
'help',
Expand All @@ -15,7 +17,7 @@ let commands = [
]

try {
var { command, argv } = require('command-line-commands')([null].concat(commands))
var { command, argv } = commandLineCommands([null].concat(commands))
} catch (e) {
if (e.name == 'INVALID_COMMAND') {
console.log(`Unknown command '${e.command}'`)
Expand Down Expand Up @@ -62,14 +64,6 @@ const OPTIONS = [
defaultValue: false,
description: 'Run command for all paths in parallel. Faster but output doesn\'t have as much info',
group: ['deps-install','deps-update']
},
{
name: 'execution-name',
type: String,
defaultValue: null,
defaultOption: true,
description: 'Unique identification of execution to fetch logs for.',
group: 'logs'
}
]

Expand All @@ -90,7 +84,7 @@ if (commands.indexOf(command) >= 0) {
})
let options
try {
options = require('command-line-args')(supportedOptions, { argv, camelCase: true })
options = commandLineArgs(supportedOptions, { argv, camelCase: true })
} catch (e) {
switch (e.name) {
case 'UNKNOWN_OPTION':
Expand All @@ -114,16 +108,6 @@ if (commands.indexOf(command) >= 0) {
require(`./commands/${command}`)(options._all, core)
.then(output => {
if (output && output.message) core.utils.stdout(output.message,{mode:core.utils.STDOUT_MODES.PARAGRAPH})
if (['deploy','deps-install','deps-outdated','deps-update'].indexOf(command) != -1) {
let timeForRepeat = 45*24*60*60*1000
let delayUntilFirst = 10*24*60*60*1000
core.utils.announce(
'feedback',
`${String.fromCodePoint(128075)} Hi! Thanks for using sampic, I'm curious to learn more about the type\n of project you use it for as well as things you wish sampic could do.\n You can email me at [email protected].\n (Don't worry, this won't show up every time)`,
timeForRepeat,
delayUntilFirst
)
}
})
.catch(err => {
if (err.message) {
Expand All @@ -135,10 +119,11 @@ if (commands.indexOf(command) >= 0) {
})

} else {
let options = require('command-line-args')(OPTIONS.filter(opt => (opt.group == 'nocmd' || opt.group.indexOf('nocmd') >= 0)), { argv })
let options = commandLineArgs(OPTIONS.filter(opt => (opt.group == 'nocmd' || opt.group.indexOf('nocmd') >= 0)), { argv })
if (command === null && options._all.version) {
console.log(require('./package.json').version)
} else {
console.log(`Usage:\t${packageInfo.name} [<options>] [<command>] [<command-options>]\n\nTo see help text, you can run:\n\tsampic help`)
let cmdName = Object.keys(packageInfo.bin)[0]
console.log(`Usage:\t${cmdName} [<options>] [<command>] [<command-options>]\n\nTo see help text, you can run:\n\t${cmdName} help`)
}
}
39 changes: 20 additions & 19 deletions commands/deploy.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
'use strict'

const AWS = require('aws-sdk')
const path = require('path')
const { LambdaClient, UpdateFunctionCodeCommand } = require('@aws-sdk/client-lambda')
const { CloudFormationClient, ListStackResourcesCommand, UpdateStackCommand } = require("@aws-sdk/client-cloudformation")
const { fromIni } = require("@aws-sdk/credential-providers")
const fs = require('fs')
const yaml = require('js-yaml')
const chalk = require('chalk')
Expand All @@ -19,11 +20,11 @@ module.exports = function run(cmdOpts, core) {
let cfConfig = {
region: config.region
}
if (config._awsCredentialsObject) {
cfConfig.credentials = config._awsCredentialsObject
if (config.profile) {
cfConfig.credentials = fromIni({profile: config.profile})
}
core.utils.stdout(`Retrieving template currently deployed on stack ${chalk.bold(config.stackName)}`)
let awsCF = new AWS.CloudFormation(cfConfig)
let awsCF = new CloudFormationClient(cfConfig)
return core.utils.getCurrentStackTemplate(awsCF, config)
.then(template => {
return { awsCF, config, template }
Expand All @@ -40,7 +41,7 @@ module.exports = function run(cmdOpts, core) {
config,
templates: {
current: template,
packaged: yaml.safeLoad(
packaged: yaml.load(
fs.readFileSync(config._packagedTemplateFile, 'utf8'),
{ schema: require('cloudformation-schema-js-yaml') }
)
Expand Down Expand Up @@ -138,11 +139,11 @@ module.exports = function run(cmdOpts, core) {
core.utils.stdout(`Updating Lambda functions`,{level:1})
core.utils.stdout(`Retrieving information on stack resources`,{level:2})

let params = {
let cfCmd = new ListStackResourcesCommand({
StackName: config.stackName
}
return awsCF.listStackResources(params).promise()
.then(data => {
})
return awsCF.send(cfCmd)
.then((data) => {
let fnsToUpdate = data.StackResourceSummaries.filter(r =>
stackChanges.findIndex(chg => chg.path[1] === r.LogicalResourceId) >= 0
)
Expand All @@ -156,20 +157,20 @@ module.exports = function run(cmdOpts, core) {
let lambdaConfig = {
region: config.region
}
if (config._awsCredentialsObject) {
lambdaConfig.credentials = config._awsCredentialsObject
if (config.profile) {
lambdaConfig.credentials = fromIni({profile: config.profile})
}
let lambda = new AWS.Lambda(lambdaConfig)
let lambda = new LambdaClient(lambdaConfig)
return Promise.all(fnsToUpdate.map(fn => {
let [str, bucket, key] = stackChanges.find(chg => chg.path[1] === fn.LogicalResourceId).rhs.match(/^s3:\/\/(.*)\/(.*)$/)
let params = {
let lambdaCmd = new UpdateFunctionCodeCommand({
FunctionName: fn.PhysicalResourceId,
Publish: false,
S3Bucket: bucket,
S3Key: key
}
})
core.utils.stdout(`Setting ${chalk.yellow(`s3://${bucket}/${key}`)} as code bundle for lambda function ${chalk.cyan(fn.PhysicalResourceId)}`,{level:2})
return lambda.updateFunctionCode(params).promise()
return lambda.send(lambdaCmd)
}))
.then(results => {
return [
Expand All @@ -194,7 +195,7 @@ module.exports = function run(cmdOpts, core) {

core.utils.stdout(`Updating stack with new values for parameters: ${updatedStackParams.join(' ')}`, {level:1})

let updateParams = {
let cfCmd = new UpdateStackCommand({
StackName: config.stackName,
Capabilities: config.capabilities,
UsePreviousTemplate: true,
Expand All @@ -211,9 +212,9 @@ module.exports = function run(cmdOpts, core) {
}
}
})
}
})

return awsCF.updateStack(updateParams).promise()
return awsCF.send(cfCmd)
.then(data => core.utils.getStackStatus(awsCF, config.stackName))
.then(status => {
core.utils.stdout(`Stack status: ${status}`,{level:2})
Expand Down
7 changes: 3 additions & 4 deletions commands/help.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
'use strict'

const prompt = require('prompt')
const chalk = require('chalk')
const getUsage = require('command-line-usage')

module.exports = function run(cmdOpts, core) {

const packageInfo = require('../package.json')
let cmdName = Object.keys(packageInfo.bin)[0]

console.log(getUsage([
{
header: 'SAMPIC CLI',
header: 'SAMPIC',
content: packageInfo.description
},
{
header: 'Synopsis',
content: `$ ${packageInfo.name} [<command>] [<command-options>]`
content: `$ ${cmdName} [<command>] [<command-options>]`
},
{
header: 'Commands',
Expand Down
2 changes: 0 additions & 2 deletions commands/init.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
'use strict'

const AWS = require('aws-sdk')
const path = require('path')
const fs = require('fs')

module.exports = function run(cliOpts, core) {
Expand Down
3 changes: 1 addition & 2 deletions commands/show-config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
'use strict'

const prompt = require('prompt')
const chalk = require('chalk')

module.exports = function run(cmdOpts, core) {
Expand All @@ -9,7 +8,7 @@ module.exports = function run(cmdOpts, core) {
return core.utils.getConfig(cmdOpts)
.then(config => {
Object.keys(config).forEach(k => {
if (k.substr(0,1) == '_') return false
if (k.substring(0,1) == '_') return false
let spacer = Array.from(Array(Math.ceil((NUM_TABS_TO_VALUE*8 - k.length - 1)/8)), elm => '\t').join('')
let paramName = chalk.gray(k + ':')
switch (k) {
Expand Down
14 changes: 7 additions & 7 deletions core/analyseChanges.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
'use strict'

const utils = require('./utils')
const fs = require('fs')
const { diff } = require('deep-diff')
const AWS = require('aws-sdk')
const { CloudFormationClient } = require("@aws-sdk/client-cloudformation")
const { fromIni } = require("@aws-sdk/credential-providers")

module.exports = function run(config, templates) {

Expand All @@ -12,11 +12,11 @@ module.exports = function run(config, templates) {
let cfConfig = {
region: config.region
}
if (config._awsCredentialsObject) {
cfConfig.credentials = config._awsCredentialsObject
if (config.profile) {
cfConfig.credentials = fromIni({profile: config.profile})
}

let cf = new AWS.CloudFormation(cfConfig)
let cf = new CloudFormationClient(cfConfig)

function _getUpdatedStackParams() {
utils.stdout('Retrieving current stack parameters', {level:2})
Expand Down Expand Up @@ -52,7 +52,7 @@ module.exports = function run(config, templates) {
if (notJustLambdas) {
// Need to do a full stack deploy because there have been changes
// other than lambda code bundles
utils.stdout(`Result: full cloudformation deploy required`,{level:2})
utils.stdout(`Result: changes in stack, full cloudformation update required`,{level:2})
resolve({
updateType: utils.UPDATE_TYPES.STACK_UPDATE,
stackChanges
Expand All @@ -65,7 +65,7 @@ module.exports = function run(config, templates) {
_getUpdatedStackParams().then(updatedStackParams => {
let updateType = null
if (updatedStackParams.length > 0) {
utils.stdout(`Result: changes limited to lambda functions and stack parameters`,{level:2})
utils.stdout(`Result: changes in lambda functions and stack parameters`,{level:2})
updateType = utils.UPDATE_TYPES.LAMBDA_AND_STACK_PARAMS
} else {
utils.stdout(`Result: changes limited to lambda functions`,{level:2})
Expand Down
1 change: 0 additions & 1 deletion core/deps.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

const path = require('path')
const utils = require('./utils')
const fs = require('fs')
const chalk = require('chalk')

function _deps(cmdArgs, template, hooks={}, parallel=false, onError=null, stdioMode=null) {
Expand Down
16 changes: 10 additions & 6 deletions core/package.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict'

const AWS = require('aws-sdk')
const { S3Client, PutObjectCommand } = require("@aws-sdk/client-s3");
const { fromIni } = require("@aws-sdk/credential-providers")
const path = require('path')
const fs = require('fs')
const utils = require('./utils')
Expand Down Expand Up @@ -70,12 +71,14 @@ module.exports = function run(config) {

// upload deployable template to S3 bucket

let s3Config = {}
if (config._awsCredentialsObject) {
s3Config.credentials = config._awsCredentialsObject
let s3Config = {
region: config.region
}
if (config.profile) {
s3Config.credentials = fromIni({profile: config.profile})
}

let s3 = new AWS.S3(s3Config)
let s3 = new S3Client(s3Config)
let params = {
Bucket: config.s3Bucket,
Key: `templates/${(new Date()).toISOString().replace(/[^\d]/gi,'')}-${path.basename(config.template)}`,
Expand All @@ -84,7 +87,8 @@ module.exports = function run(config) {

utils.stdout(`Uploading deployable template to ${chalk.yellow(`s3://${params.Bucket}/${params.Key}`)}`, {level:2})

return s3.putObject(params).promise()
let s3Cmd = new PutObjectCommand(params)
return s3.send(s3Cmd)
.then(s3Response => ({
bucket: params.Bucket,
key: params.Key
Expand Down
Loading

0 comments on commit ee18e79

Please sign in to comment.