8

Looking at the AWS sdk for Javascript, it appears we can only create stacks but i'm looking of a way to deploy a stack. How would I do that with the provided sdk; this is what they currently have:

cloudformation.createStack(params, function(err, data) {
  if (err) console.log(err, err.stack); // an error occurred
  else     console.log(data);           // successful response
});

I was hoping for something like this:

cloudformation.deployStack(params, function(err, data) {
  if (err) console.log(err, err.stack); // an error occurred
  else     console.log(data);           // successful response
});

Basically, I would like to recreate this command using the sdk instead of the cli:

aws cloudformation deploy --template-file /path_to_template/template.json --stack-name my-new-stack --parameter-overrides Key1=Value1 Key2=Value2 --tags Key1=Value1 Key2=Value2

And this is because I use Linux and can put this in a shell script while most of the people I work with all use Windows and I don't want to use Windows Batch but instead a cross platform solution like npm and thus the aws-sdk for javascript approach.

How would you perform the cloudformation.deployStack using the SDK and NOT the CLI ?

kichik
  • 33,220
  • 7
  • 94
  • 114
pelican
  • 5,846
  • 9
  • 43
  • 67

1 Answers1

9

The current AWS sdk for Javascript does not currently have a deploy method, however, the AWS CLI's deploy command is a wrapper:

Deploys the specified AWS CloudFormation template by creating and then executing a change set

With that in mind, I wrote the following code:

const CloudformationInstance = new Cloudformation(accessParams)

CloudformationInstance.createChangeSet(changeSetParams, (err, data) => {
  if (err) throw new Error(err, err.stack)
  console.info('Succesfully created the ChangeSet: ', data)

  CloudformationInstance.waitFor('changeSetCreateComplete', {ChangeSetName: config.changeSetName}, (err, data) => {
  if (err) throw new Error(err, err.stack)
  const { StackName } = data.Stacks[0]

    CloudformationInstance.executeChangeSet({ StackName, ChangeSetName }, (err, data) => {
        if (err) throw new Error(err, err.stack)
        console.info('Succesfully finished creating the set: ', data)
    })
  })
})

Note: changeSetType(part of the changeSetParams) needs to be explicitly defined as either "Create or Update". So using something like:

const upsertParam = await CloudformationInstance.describeStacks(params, (err, data) => {
  if(err) return 'CREATE'
  return 'UPDATE'
}
Globolobo
  • 101
  • 5
  • 3
    Thanks, this helped a lot!! A few notes are `waitFor` should be inside of callback of `createChangeSet`, otherwise, it gets 'Resource not in the stack' error. Also, `waitFor('changeCreateComplete')` should pass `ChangeSetName` as params instead of `StackName`. – Emma Oct 12 '18 at 23:36
  • @Emma Good call-outs, Updated! – Globolobo Oct 14 '18 at 19:49