Repository: localstack/localstack

Issue:
bug: KeyError: 'Parameters' after deploying cloudformation template again
### Is there an existing issue for this?

- [X] I have searched the existing issues

### Current Behavior

I'm receiving this error after call `samlocal deploy --guided` and filled all options

And this just occur after the first time (creation)

```
Traceback (most recent call last):
  File "/opt/homebrew/bin/samlocal", line 81, in <module>
    main.cli()
  File "/opt/homebrew/lib/python3.10/site-packages/click/core.py", line 829, in __call__
    return self.main(*args, **kwargs)
  File "/opt/homebrew/lib/python3.10/site-packages/click/core.py", line 782, in main
    rv = self.invoke(ctx)
  File "/opt/homebrew/lib/python3.10/site-packages/click/core.py", line 1259, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/opt/homebrew/lib/python3.10/site-packages/click/core.py", line 1066, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/opt/homebrew/lib/python3.10/site-packages/click/core.py", line 610, in invoke
    return callback(*args, **kwargs)
  File "/opt/homebrew/lib/python3.10/site-packages/samcli/lib/cli_validation/image_repository_validation.py", line 92, in wrapped
    return func(*args, **kwargs)
  File "/opt/homebrew/lib/python3.10/site-packages/click/decorators.py", line 73, in new_func
    return ctx.invoke(f, obj, *args, **kwargs)
  File "/opt/homebrew/lib/python3.10/site-packages/click/core.py", line 610, in invoke
    return callback(*args, **kwargs)
  File "/opt/homebrew/lib/python3.10/site-packages/samcli/lib/telemetry/metric.py", line 176, in wrapped
    raise exception  # pylint: disable=raising-bad-type
  File "/opt/homebrew/lib/python3.10/site-packages/samcli/lib/telemetry/metric.py", line 126, in wrapped
    return_value = func(*args, **kwargs)
  File "/opt/homebrew/lib/python3.10/site-packages/samcli/lib/utils/version_checker.py", line 41, in wrapped
    actual_result = func(*args, **kwargs)
  File "/opt/homebrew/lib/python3.10/site-packages/samcli/cli/main.py", line 86, in wrapper
    return func(*args, **kwargs)
  File "/opt/homebrew/lib/python3.10/site-packages/samcli/commands/_utils/cdk_support_decorators.py", line 38, in wrapped
    return func(*args, **kwargs)
  File "/opt/homebrew/lib/python3.10/site-packages/samcli/commands/deploy/command.py", line 192, in cli
    do_cli(
  File "/opt/homebrew/lib/python3.10/site-packages/samcli/commands/deploy/command.py", line 359, in do_cli
    deploy_context.run()
  File "/opt/homebrew/lib/python3.10/site-packages/samcli/commands/deploy/deploy_context.py", line 166, in run
    return self.deploy(
  File "/opt/homebrew/lib/python3.10/site-packages/samcli/commands/deploy/deploy_context.py", line 249, in deploy
    result, changeset_type = self.deployer.create_and_wait_for_changeset(
  File "/opt/homebrew/lib/python3.10/site-packages/samcli/lib/deploy/deployer.py", line 525, in create_and_wait_for_changeset
    result, changeset_type = self.create_changeset(
  File "/opt/homebrew/lib/python3.10/site-packages/samcli/lib/deploy/deployer.py", line 166, in create_changeset
    existing_parameters = [parameter["ParameterKey"] for parameter in summary["Parameters"]]
KeyError: 'Parameters'
```

### Expected Behavior

Update the stack already deployed to localstack

### How are you starting LocalStack?

With a docker-compose file

### Steps To Reproduce

#### How are you starting localstack (e.g., `bin/localstack` command, arguments, or `docker-compose.yml`)

    docker-compose up localstack

#### Client commands (e.g., AWS SDK code snippet, or sequence of "awslocal" commands)

    samlocal deploy --guided


### Environment

```markdown
- OS: MacOS 12.3.1
- LocalStack: latest
```


### Anything else?

No


Discussion:
Welcome to LocalStack! Thanks for reporting your first issue and our team will be working towards fixing the issue for you or reach out for more background information. We recommend joining our [Slack Community](https://localstack.cloud/contact/) for real-time help and drop a message to LocalStack Pro Support if you are a Pro user! If you are willing to contribute towards fixing this issue, please have a look at our [contributing guidelines](https://github.com/localstack/.github/blob/main/CONTRIBUTING.md) and our [developer guide](https://docs.localstack.cloud/developer-guide/).
Thanks for reporting @samuelhgf . Can you please share the version of the SAM CLI you're using (via `sam --version` or `samlocal --version`). Also, do you think you could share a copy of your SAM application / template, so we can replicate this more easily..? Thanks for your help!
I'm having the same issue. Just started with a sample app.

`SAM CLI, version 1.59.0`

Deployed with samlocal --guided, first deployment always works, but second one fails with the same error.

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Sample Lambda Function in Typescript
Globals:
  Function:
    Timeout: 10
Resources:
  TypescriptFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: lambdas/sayHello/built
      Handler: index.lambdaHandler
      Runtime: nodejs16.x
      Events:
        Typescript:
          Type: Api
          Properties:
            Path: /hello
            Method: get
```

```
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.lambdaHandler = void 0;
const lambdaHandler = async (event) => {
    const queries = JSON.stringify(event.queryStringParameters);
    return {
        statusCode: 200,
        body: `Queries: ${queries}`
    };
};
exports.lambdaHandler = lambdaHandler;
//# sourceMappingURL=index.js.map
```
I have exactly the same error, using 'samlocal init' to create a Python 'Hello World Lambda', 'build', and 'deploy --guided' to localstack.  It only worked in the first deployment.   After I changed the string in Lambda function, rebuild, and 'samlocal deploy' with or without '--guided' to localstack, samlocal report the following error:

File "/Users/UID/aws/sam_env/lib/python3.9/site-packages/samcli/lib/deploy/deployer.py", line 166, in create_changeset
    existing_parameters = [parameter["ParameterKey"] for parameter in summary["Parameters"]]
KeyError: 'Parameters'

I already upgraded to localstack v1.2.0 container image, samlocal is v1.60.0, and Python 3.9.   There are two way to work around.
1. Restart localstack container, so everything is refreshed, and recreated by CloudFormation.
2. Enter different stack name. The first time uses 'sam-app', the second deployment uses 'sam-app2', etc, then it works since samlocal create another stack.

For AWS, sam cli "init 'Hello World', build, deploy, change something, build, and deploy again" is a simple Hello World demo.  Should this also work with "samlocal and localstack" too?

I'm facing the same issue. Any resolution? The work around is annoying.

Resolving patch:
diff --git a/localstack/services/cloudformation/provider.py b/localstack/services/cloudformation/provider.py
--- a/localstack/services/cloudformation/provider.py
+++ b/localstack/services/cloudformation/provider.py
@@ -1,6 +1,7 @@
 import json
 import logging
 import re
+from collections import defaultdict
 from copy import deepcopy
 from typing import Any, Dict, List, Optional
 
@@ -719,10 +720,10 @@ def get_template_summary(
             stack = Stack(request, template)
 
         result: GetTemplateSummaryOutput = stack.describe_details()
-        id_summaries = {}
+        result["Parameters"] = result.get("Parameters") or []
+        id_summaries = defaultdict(list)
         for resource_id, resource in stack.template_resources.items():
             res_type = resource["Type"]
-            id_summaries[res_type] = id_summaries.get(res_type) or []
             id_summaries[res_type].append(resource_id)
 
         result["ResourceTypes"] = list(id_summaries.keys())
@@ -730,6 +731,9 @@ def get_template_summary(
             {"ResourceType": key, "LogicalResourceIds": values}
             for key, values in id_summaries.items()
         ]
+        result["Version"] = stack.template.get("AWSTemplateFormatVersion", "2010-09-09")
+        # these do not appear in the output
+        result.pop("Capabilities", None)
         return result
 
     @handler("ValidateTemplate", expand=False)


Test patch:
diff --git a/tests/integration/cloudformation/api/test_get_template_summary.py b/tests/integration/cloudformation/api/test_get_template_summary.py
new file mode 100644
--- /dev/null
+++ b/tests/integration/cloudformation/api/test_get_template_summary.py
@@ -0,0 +1,22 @@
+import os
+
+import pytest
+
+
+@pytest.mark.aws_validated
+@pytest.mark.skip_snapshot_verify(paths=["$..ResourceIdentifierSummaries..ResourceIdentifiers"])
+def test_get_template_summary(deploy_cfn_template, cfn_client, snapshot):
+    snapshot.add_transformer(snapshot.transform.cloudformation_api())
+    snapshot.add_transformer(snapshot.transform.sns_api())
+
+    deployment = deploy_cfn_template(
+        template_path=os.path.join(
+            # This template has no parameters, and so shows the issue
+            os.path.dirname(__file__),
+            "../../templates/sns_topic_simple.yaml",
+        )
+    )
+
+    res = cfn_client.get_template_summary(StackName=deployment.stack_name)
+
+    snapshot.match("template-summary", res)
diff --git a/tests/integration/cloudformation/api/test_get_template_summary.snapshot.json b/tests/integration/cloudformation/api/test_get_template_summary.snapshot.json
new file mode 100644
--- /dev/null
+++ b/tests/integration/cloudformation/api/test_get_template_summary.snapshot.json
@@ -0,0 +1,29 @@
+{
+  "tests/integration/cloudformation/api/test_get_template_summary.py::test_get_template_summary": {
+    "recorded-date": "30-11-2022, 14:27:17",
+    "recorded-content": {
+      "template-summary": {
+        "Parameters": [],
+        "ResourceIdentifierSummaries": [
+          {
+            "LogicalResourceIds": [
+              "topic123"
+            ],
+            "ResourceIdentifiers": [
+              "TopicArn"
+            ],
+            "ResourceType": "AWS::SNS::Topic"
+          }
+        ],
+        "ResourceTypes": [
+          "AWS::SNS::Topic"
+        ],
+        "Version": "2010-09-09",
+        "ResponseMetadata": {
+          "HTTPHeaders": {},
+          "HTTPStatusCode": 200
+        }
+      }
+    }
+  }
+}