

# Step 3: Deploy the CloudFormation stack

Deploy the template that includes the account and case guide, in the AWS account and Region of your Connect Customer instance. Launch Stack installs the latest 1.x template version; the stack's `TemplateVersion` output shows which. The stack creates:
+ The gateway, with its Salesforce target and token refresh function, and its registration with your instance.
+ Change alerts, a health dashboard and four alarms.
+ The account and case guide: an inbound flow, a guide flow, nine flow modules, and, in two nested stacks, 15 views and the Create a case with details module. With **Wrap-up flow and form** set to `Enabled`, also the wrap-up flow and two more views.
+ An AI self-service flow with a knowledge agent, an account agent and an agent assist AI agent. It receives no contacts until you route contacts to it.

For what each part does, every parameter, the gateway-only template and deploying with the AWS CLI, see [CloudFormation template reference](real-time-data-integration-deployment.md).

You need the values from Step 2 (the My Domain URL, the consumer key and the consumer secret) and the output of the check in [Check the instance](real-time-data-integration-instance.md#real-time-data-integration-instance-check) (the instance's ARN, its access URL, the test queue's ARN and the Connect assistant line). To print the instance values again, run that check again.

**To store the consumer secret in AWS Secrets Manager**
+ In the Region of your Connect Customer instance, expand the following block, copy it, paste it and press Enter. It asks for these, in order:
  + The Region.
  + Whether to store the secret in the AWS account it shows, the account the AWS CLI is signed in to. Type **y** if it's the account of your Connect Customer instance.
  + A name for the secret, and the consumer secret, which doesn't appear on screen.

  It stores the consumer secret under the key `clientSecret`, where the stack reads it, encrypted with the default `aws/secretsmanager` key, and never puts it in the command's arguments.

## The script that stores the consumer secret
<a name="real-time-data-integration-code-script-that-stores-the-consumer-secret"></a>

```
(
  umask 077; D=$(mktemp -d); trap 'rm -rf "$D"' EXIT
  R=${AWS_REGION:-us-east-1}
  printf 'Region of your Connect Customer instance [%s]: ' "$R"; read -r REGION; REGION=${REGION:-$R}
  ACCOUNT=$(aws sts get-caller-identity --region "$REGION" --query Account --output text) \
    || { echo "The AWS CLI isn't signed in. Sign in, then run this again; nothing was stored."; exit 1; }
  printf 'Store the secret in AWS account %s? [y/N]: ' "$ACCOUNT"; read -r OK
  case "$OK" in y|Y|yes|Yes) ;; *) echo "Nothing was stored."; exit 0 ;; esac
  printf 'Secret name [connect-sf-real-time/client]: '; read -r NAME; NAME=${NAME:-connect-sf-real-time/client}
  printf 'Consumer secret (input hidden: paste and press Enter): '; read -rs SF_SECRET; echo
  printf '%s' "$SF_SECRET" > "$D/secret"; unset SF_SECRET
  [ -s "$D/secret" ] || { echo "No consumer secret entered; nothing was stored."; exit 1; }
  python3 -I -c 'import json, sys; print(json.dumps({"clientSecret": open(sys.argv[1]).read().strip()}))' "$D/secret" > "$D/value.json"
  ARN=$(aws secretsmanager create-secret --region "$REGION" --name "$NAME" \
    --secret-string "file://$D/value.json" --query ARN --output text) || exit 1
  echo "Consumer secret (Secrets Manager ARN): $ARN"
)
```

It prints `Consumer secret (Secrets Manager ARN):` and the secret's ARN. Copy the ARN. If it prints something else:
+ `ResourceExistsException`: a secret with that name exists. If it holds this consumer secret, use its ARN, which the Secrets Manager console shows. Otherwise run the block again with another name.
+ `InvalidRequestException` with `already scheduled for deletion`: a deleted secret with that name is waiting out its recovery window. Run the block again with another name, or restore the secret: in the Secrets Manager console, choose **Preferences**, select **Show secrets scheduled for deletion** and choose **Save**, open the secret, and choose **Cancel deletion** twice. A restored secret keeps its old value; store the new consumer secret in it as [Rotate the credentials](real-time-data-integration-maintain.md#real-time-data-integration-rotate) describes.
+ `AccessDeniedException`: your IAM identity can't create secrets. Ask your AWS administrator for `secretsmanager:CreateSecret`.

To deploy with the deployer policy and a role that only CloudFormation assumes, instead of your own permissions, use the AWS CLI, not Launch Stack; see [CloudFormation template reference](real-time-data-integration-deployment.md).

This installs the current template version. To move a deployed stack to a newer version later, see [Upgrade the template](real-time-data-integration-update.md).

**To deploy the stack with Launch Stack**

1. Sign in to the AWS Management Console in the account of your Connect Customer instance, then choose **Launch Stack** for your instance's Region in the following table. The button opens the template with the account and case guide in that Region.


**Launch the template with the account and case guide**  

<table>
<thead>
  <tr><th>Connect Customer Region of your instance</th><th>Template</th></tr>
</thead>
<tbody>
  <tr><td>US West (Oregon) (<code>us-west-2</code>)</td><td><a href="https://console.aws.amazon.com/cloudformation/home?region=us-west-2#/stacks/create/review?templateURL=https%3A%2F%2Fac-sf-headless360-cfn-template.s3.us-west-2.amazonaws.com%2Fconnect-sf-real-time-data-integration.template.json&amp;stackName=connect-sf-real-time">https://console.aws.amazon.com/cloudformation/home?region=us-west-2#/stacks/create/review?templateURL=https%3A%2F%2Fac-sf-headless360-cfn-template.s3.us-west-2.amazonaws.com%2Fconnect-sf-real-time-data-integration.template.json&amp;stackName=connect-sf-real-time</a></td></tr>
  <tr><td>US East (N. Virginia) (<code>us-east-1</code>)</td><td><a href="https://console.aws.amazon.com/cloudformation/home?region=us-east-1#/stacks/create/review?templateURL=https%3A%2F%2Fac-sf-headless360-cfn-template.s3.us-west-2.amazonaws.com%2Fconnect-sf-real-time-data-integration.template.json&amp;stackName=connect-sf-real-time">https://console.aws.amazon.com/cloudformation/home?region=us-east-1#/stacks/create/review?templateURL=https%3A%2F%2Fac-sf-headless360-cfn-template.s3.us-west-2.amazonaws.com%2Fconnect-sf-real-time-data-integration.template.json&amp;stackName=connect-sf-real-time</a></td></tr>
</tbody>
</table>


   For the other Regions, see [Launch Stack by Region](real-time-data-integration-deployment.md#real-time-data-integration-launch-regions).

1. In **Stack name**, keep **connect-sf-real-time** or enter another name. The stack name names the gateway, the integration in Connect Customer and the guide's flows and views, and can't change later. Use lowercase letters, digits and single hyphens, and a name no other stack in this account and Region uses. Use at most 50 characters, or 24 if you deploy with the deployer policy.

1. Under **Parameters**, fill in the fields. The page groups them under seven headings, in this order. Keep the default of every field that the table says to keep:


**Launch Stack fields**  

<table>
<thead>
  <tr><th>Group</th><th>Field (parameter)</th><th>What to enter</th></tr>
</thead>
<tbody>
  <tr><td><b>Amazon Connect</b></td><td><b>Connect instance ARN</b> (<code>InstanceArn</code>)</td><td>The <code>Connect instance ARN</code> line of the instance check, for example <code>arn:aws:connect:us-west-2:111122223333:instance/a1b2c3d4-5678-90ab-cdef-111111111111</code>.</td></tr>
  <tr><td><b>Amazon Connect</b></td><td><b>Connect instance access URL</b> (<code>ConnectInstanceUrl</code>)</td><td>The <code>Connect instance access URL</code> line, with no trailing slash, for example <code>https://my-instance.my.connect.aws</code>.</td></tr>
  <tr><td><b>Amazon Connect</b></td><td><b>Test queue ARN</b> (<code>TestQueueArn</code>)</td><td>The <code>Test queue ARN</code> line that the test setup script prints in Step 1. If you created the test agent in the admin website, the ARN of the queue your test agent serves, from the check's list of queues. The stack's inbound flow sends test chats and test calls there.</td></tr>
  <tr><td><b>Salesforce External Client App</b></td><td><b>My Domain URL</b> (<code>SalesforceMyDomainUrl</code>)</td><td>Your org's My Domain URL from Step 2, with <code>https://</code> and no trailing slash, for example <code>https://mycompany--uat.sandbox.my.salesforce.com</code> for a sandbox.</td></tr>
  <tr><td><b>Salesforce External Client App</b></td><td><b>Consumer key</b> (<code>SalesforceClientId</code>)</td><td>The External Client App's consumer key from Step 2.</td></tr>
  <tr><td><b>Salesforce External Client App</b></td><td><b>Consumer secret (Secrets Manager ARN)</b> (<code>SalesforceClientSecretArn</code>)</td><td>The ARN that the secret block printed, ending in a hyphen and six characters.</td></tr>
  <tr><td><b>Salesforce External Client App</b></td><td><b>Optional: integration username (Run As user)</b> (<code>SalesforceIntegrationUsername</code>)</td><td>The integration user's Salesforce username from Step 2, for example <b>integration@example.com</b>. Set it to lock the stack to that user. With it set, these fail if the app's <b>Run As</b> user is someone else:<ul><li>a create;</li><li>an update, if the <b>Run As</b> user changed since the last deploy;</li><li>scheduled token refreshes, so tool calls stop once the stored token expires.</li></ul><br />Leave it empty to keep calls running. The <code>RunAsUserChanged</code> alarm then alerts you to a change.</td></tr>
  <tr><td><b>Customer lookup</b></td><td><b>Find the record module</b> (<code>FindRecordModuleArn</code>)</td><td>Leave it empty to use the built-in module, which finds the record by the contact attributes in <a href="real-time-data-integration-start.md#real-time-data-integration-find-record">How the guide finds the record</a>. Later, to have your own flow module pick the record a contact is about, enter its alias ARN; the module must be published in the instance that <b>Connect instance ARN</b> names. See <a href="real-time-data-integration-modules.md">Extend the guide with flow modules</a>.</td></tr>
  <tr><td><b>Optional: your own Salesforce operations</b></td><td><b>Custom operations file (S3 URI)</b> (<code>CustomOperationsS3Uri</code>)</td><td>Leave it empty. See <a href="real-time-data-integration-salesforce.md#real-time-data-integration-custom-operations">Add your own Salesforce operations</a>.</td></tr>
  <tr><td><b>Optional: AI self-service</b></td><td><b>Existing Connect assistant (ARN)</b> (<code>ExistingAssistantArn</code>)</td><td>Use the <code>Connect assistant</code> line of the instance check script:<ul><li>If it prints an ARN, paste it.</li><li>If it prints <code>none</code>, leave the field empty. The stack then creates a Connect assistant, <code>stack-name-assistant</code>, and associates it with the instance.</li><li>The stack keeps the assistant and its association when the stack is deleted.</li><li>An instance can have only one assistant. An empty field on an instance that has one makes the create fail and roll back.</li></ul></td></tr>
  <tr><td><b>Optional: AI self-service</b></td><td><b>Account agent for verified contacts</b> (<code>SelfServiceAccountTool</code>)</td><td>Keep <b>true</b>, the default. The stack then also creates the account agent, which reads only the account in the contact's <code>accountId</code>, and which self-service contacts use only if you make it the assistant's default <b>Self service</b> AI agent. <b>false</b> creates no account agent. See <a href="real-time-data-integration-ai-data.md">Let self-service read the verified account</a>.</td></tr>
  <tr><td><b>Optional: AI self-service</b></td><td><b>Knowledge base to associate (ARN)</b> (<code>ConnectAssistantKnowledgeBaseArn</code>)</td><td>Leave it empty. See <a href="real-time-data-integration-ai-setup.md">Choose the assistant and the knowledge base</a>.</td></tr>
  <tr><td><b>Optional: after contact work</b></td><td><b>Wrap-up flow and form</b> (<code>WrapUp</code>)</td><td>Keep <b>Disabled</b>, the default, for no wrap-up flow. Choose <b>Enabled</b> to show agents the wrap-up form when a contact ends.</td></tr>
  <tr><td><b>Optional: your own copy of the release files</b></td><td><b>Release files URL (views template)</b> (<code>NestedTemplateBaseUrl</code>)</td><td>Keep the default. The stack reads the templates for the guide's views and the Create a case with details module from there. See <a href="real-time-data-integration-deployment.md">CloudFormation template reference</a>.</td></tr>
</tbody>
</table>


   If a value isn't in the form the template expects, the console names the parameter and the form it must have when you choose **Create stack**, and creates nothing. Correct the field and choose **Create stack** again.

1. At the bottom of the page, select both acknowledgments, **I acknowledge that AWS CloudFormation might create IAM resources with custom names** and **I acknowledge that AWS CloudFormation might require the following capability: CAPABILITY\_AUTO\_EXPAND**, and choose **Create stack**.

1. Wait for the stack's status to change from `CREATE_IN_PROGRESS`. `CREATE_COMPLETE` means the stack is ready: go on to checking the stack. `ROLLBACK_IN_PROGRESS`, `ROLLBACK_COMPLETE`, `ROLLBACK_FAILED` or `CREATE_FAILED` means the create failed: follow *If the stack fails*.<a name="real-time-data-integration-stack-fails"></a>

**If the stack fails**
+ Find the cause. In the CloudFormation console, open the stack's **Events** tab and find the oldest event whose status ends in `_FAILED`; the later ones only report that CloudFormation cancelled the rest. Or expand the block that follows, copy it, and paste it at the prompt, which prints the stack's status and that first failure:

## The script that prints the first failure
<a name="real-time-data-integration-code-script-that-prints-the-first-failure"></a>

```
(
  R=${AWS_REGION:-us-east-1}
  printf 'Region of the stack [%s]: ' "$R"; read -r REGION; REGION=${REGION:-$R}
  printf 'Stack name [connect-sf-real-time]: '; read -r STACK; STACK=${STACK:-connect-sf-real-time}
  STATUS=$(aws cloudformation describe-stacks --region "$REGION" --stack-name "$STACK" --query 'Stacks[0].StackStatus' --output text) \
    || { echo "No stack named $STACK in $REGION. Check the stack name and the Region."; exit 1; }
  echo "Stack status: $STATUS"
  echo "First failure:"
  aws cloudformation describe-stack-events --region "$REGION" --stack-name "$STACK" \
    --query "reverse(StackEvents)[?ends_with(ResourceStatus, '_FAILED')] | [0].[LogicalResourceId, ResourceStatusReason]" --output text
)
```

If the block prints `No stack named`, run it again with the stack name and Region you used. The common first failures and their fixes:
+ A flow or flow module, such as `GuideFlow`, with `InvalidContactFlowException: Invalid Action type. Type: InvokeExternalTool`: the instance is on Connect Customer Basic. Enable Connect Customer on the instance, as [Enable Connect Customer on the instance](real-time-data-integration-instance.md#real-time-data-integration-instance-enable) describes.
+ `SalesforceInitialTokenRefresh` followed by letters and digits, with Salesforce's HTTP status and error code: Salesforce refused the first token. Run the token check from Step 2 again, and fix what it reports.
+ A queue or instance error: **Test queue ARN** isn't a queue of the instance in **Connect instance ARN**, or **Connect instance access URL** isn't that instance's URL. Copy both again from the instance check.
+ `AiAssistantAssociation`: **Existing Connect assistant (ARN)** was empty, and the instance already has an assistant. Run the instance check again, and try again with its `Connect assistant` line in **Existing Connect assistant (ARN)**. Keep the existing assistant: the stack uses it. To replace it, see [Self-service and the Connect assistant](real-time-data-integration-troubleshoot.md#real-time-data-integration-troubleshoot-assistant).

For other messages, see [Deploying and updating the stack](real-time-data-integration-troubleshoot.md#real-time-data-integration-troubleshoot-deploy).

**To retry the stack**

1. Keep the Secrets Manager secret, the External Client App and the integration user. They are outside the stack, and the next attempt uses them again. A failed create removes what the stack created, except a Connect assistant: when **Existing Connect assistant (ARN)** was empty, the stack's assistant, `{{stack-name}}-assistant`, stays, and so does its association with the instance if the stack created one. Before you retry, run the instance check again, and paste its `Connect assistant` line into **Existing Connect assistant (ARN)**.

1. A stack whose create failed stays in `ROLLBACK_COMPLETE` or `ROLLBACK_FAILED` and can't be updated. Select it, choose **Delete**, and wait until it disappears from the list. Then choose **Launch Stack** again, and enter the same stack name and the same values, with the fix and the **Existing Connect assistant (ARN)** from the check. See [Delete a stack from the CloudFormation console](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-delete-stack.html).

1. To have your next attempt keep what the stack created and retry from the failure, choose **Preserve successfully provisioned resources** before you create the stack; see *Retry a failed stack without deleting it* in [Deploying and updating the stack](real-time-data-integration-troubleshoot.md#real-time-data-integration-troubleshoot-deploy).

1. A failed update, for example to a new template version, rolls the stack back to `UPDATE_ROLLBACK_COMPLETE`, and the stack keeps working as it did before the update. Find the first `UPDATE_FAILED` event on the **Events** tab, fix the cause, and update again. If the stack shows `UPDATE_ROLLBACK_FAILED`, the rollback itself failed: fix the cause the events name, then choose **Stack actions**, **Continue update rollback**. See [Continue rolling back an update](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-continueupdaterollback.html).

**To check the stack**

1. In the CloudFormation console, open the stack's **Outputs** tab.

1. At the prompt, run the command in the `VerifyRegistration` output. It lists one association: the gateway is connected to your instance. If it prints `[]`, the stack's integration association with the instance is missing, for example because someone removed it outside the stack. Delete the stack and deploy it again with the same values.

1. Run the command in the `VerifyAudience` output. It prints the value of the `GatewayId` output. If it prints anything else, see [Deploying and updating the stack](real-time-data-integration-troubleshoot.md#real-time-data-integration-troubleshoot-deploy).

1. Check the `SalesforceRunAsUsername` output: it names the External Client App's **Run As** user, whom every tool call runs as in Salesforce. It must be the integration user from Step 2. Then check `SalesforceRunAsBroadAccess`: `no` is what you want. `yes` means the user has Modify All Data or View All Data, so every tool call can read every record in the org; give the integration user narrower access. For a user the setup script in Step 2 created, `unknown` is expected: the user has no View Setup, so it can't have either permission. For another user, `unknown` means Salesforce didn't let the user read its permission fields, which usually means it lacks View Setup and so can't have either permission. It also reads `unknown` when the lookup failed; the token refresh function's log names the reason. To confirm, in Salesforce Setup, open **Users**, open the integration user, and check that neither its profile nor any of its permission sets grants Modify All Data or View All Data.

1. Check that the stack gets a Salesforce token. Expand this block, copy it, and paste it at the prompt; it asks for the Region and the stack name, and runs the stack's token refresh function once:

## The stack's token check script
<a name="real-time-data-integration-code-stacks-token-check-script"></a>

```
(
  umask 077; D=$(mktemp -d); trap 'rm -rf "$D"' EXIT
  R=${AWS_REGION:-us-east-1}
  printf 'Region of the stack [%s]: ' "$R"; read -r REGION; REGION=${REGION:-$R}
  printf 'Stack name [connect-sf-real-time]: '; read -r STACK; STACK=${STACK:-connect-sf-real-time}
  aws cloudformation describe-stacks --region "$REGION" --stack-name "$STACK" --query 'Stacks[0].StackStatus' --output text > /dev/null \
    || { echo "No stack named $STACK in $REGION. Check the stack name and the Region."; exit 1; }
  FUNCTION=$(aws cloudformation describe-stacks --region "$REGION" --stack-name "$STACK" \
    --query "Stacks[0].Outputs[?OutputKey=='TokenRefreshFunctionName'].OutputValue | [0]" --output text) || exit 1
  aws lambda invoke --region "$REGION" --function-name "$FUNCTION" "$D/out.json" > /dev/null || exit 1
  python3 -I - "$D/out.json" <<'PY'
import json, sys
r = json.load(open(sys.argv[1]))
if isinstance(r, dict) and r.get("token") in ("updated", "unchanged"):
    print("OK: the stack got a Salesforce token (%s)." % r["token"])
else:
    print("FAILED: %s" % (r.get("errorMessage") if isinstance(r, dict) else r))
PY
)
```

It prints `OK: the stack got a Salesforce token`, and no token. If it prints `FAILED:`, the message says what failed, and for a Salesforce refusal it names Salesforce's error code; run the token check from Step 2 again and fix what it reports. If it prints `No stack named`, run it again with the stack name and Region you used. This check shows that the stack gets a token; the test in Step 4 shows that the gateway reads Salesforce.

Before you go live, subscribe your team to the stack's alerts and check that change alerts can reach you; see [Monitor the integration](real-time-data-integration-maintain.md#real-time-data-integration-monitor).

The stack's AI self-service flow and AI agents need two more steps in the Connect Customer console before you use them, after each create or update. The guide doesn't need them. See [Finish the AI setup after each create or update](real-time-data-integration-ai-console.md).