Packaging and deploying your serverless stack

Once the IAM role with policies, the ZIP package with the Lambda code, and SAM template are all created, you just need to run two CloudFormation commands to package and deploy your serverless stack.

The first command packages the Lambda code with the SAM template and pushes it to S3:

$ aws cloudformation package --template-file $template.yaml 
    --output-template-file ../../package/$template-output.yaml 
    --s3-bucket $bucket --s3-prefix backend 
    --region $region --profile $profile

Successfully packaged artifacts and wrote output template to file ../../package/lambda-dynamo-data-api-output.yaml.
Execute the following command to deploy the packaged template
aws cloudformation deploy --template-file /mnt/c/serverless-microservice-data-api/package/lambda-dynamo-data-api-output.yaml --stack-name <YOUR STACK NAME>

The second command deploys it to AWS:

$ aws cloudformation deploy --template-file ../../package/$template-output.yaml 
    --stack-name $template --capabilities CAPABILITY_IAM 
    --parameter-overrides AccountId=${aws_account_id} 
    --region $region --profile $profile

Waiting for changeset to be created..
Waiting for stack create/update to complete
Successfully created/updated stack - lambda-dynamo-data-api

One of the great features in SAM is the ability to use parameters. Here, this is done when we deploy the stack with --parameter-overrides AccountId=${aws_account_id}. The benefit is that we can reuse the same SAM template for multiple environments, such as AWS Accounts and Regions, and any other parameters.

You can check that the stack has been deployed to AWS correctly by checking the AWS Management Console:

  1. Sign into the AWS Management Console at https://console.aws.amazon.com/cloudformation/.
  2. Choose Management & Governance | CloudFormation or search for CloudFormation under Find services.
  3. In the CloudFormation pane, choose lambda-dynamo-data-api.
  4. Choose Events. This shows the different events and is very useful for diagnosing any issues you get when deploying a stack. Usually, it will be a naming conflict (for example, a DynamoDB table with the same name exists) or an IAM-related issue (for example, a role does not exist).
  1. Choose Resources. This shows the resources that are managed by this CloudFormation stack:

You can also check the AWS Management Console directly if the API Gateway, Lambda function, and DynamoDB table have been created correctly.

For example, here is the same Lambda we created using Python, but deployed and managed by SAM. Unless you are doing a proof of concept, it is recommended that any further changes are managed by configuration changes rather than changes in the AWS Management Console, as this would break the infrastructure as code and automation:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset