From ff3a7e76aa67ebf286163f56319c832e65601758 Mon Sep 17 00:00:00 2001
From: Nirmal Thacker <nirmalthacker@gmail.com>
Date: Thu, 14 May 2020 11:04:41 -0700
Subject: [PATCH 01/31] First commit, updated READMEs

---
 .../example-with-consul-connect/README.md     | 33 +++++++++
 modules/run-consul/README.md                  | 69 ++++++++++---------
 variables.tf                                  |  5 +-
 3 files changed, 70 insertions(+), 37 deletions(-)
 create mode 100644 examples/example-with-consul-connect/README.md

diff --git a/examples/example-with-consul-connect/README.md b/examples/example-with-consul-connect/README.md
new file mode 100644
index 00000000..3e6bfd02
--- /dev/null
+++ b/examples/example-with-consul-connect/README.md
@@ -0,0 +1,33 @@
+# Consul Cluster with Connect service mesh
+
+This folder shows an example of Terraform code that uses the [run-consul module](https://github.com/hashicorp/terraform-aws-consul/tree/master/modules/consul-cluster) to deploy
+a [Consul](https://www.consul.io/) cluster in [AWS](https://aws.amazon.com/) with the Consul Connect Service Mesh turned on. The cluster consists of three Services with
+side-proxies and Intentions that enable secure service mesh connections.
+
+You will need to create an [Amazon Machine Image (AMI)](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html)
+that has Consul installed, which you can do using the [consul-ami example](https://github.com/hashicorp/terraform-aws-consul/tree/master/examples/consul-ami)). Note that to keep
+this example simple, both the server ASG and client ASG are running the exact same AMI. In real-world usage, you'd
+probably have multiple client ASGs, and each of those ASGs would run a different AMI that has the Consul agent
+installed alongside your apps.
+
+For more info on how the Consul cluster works, check out the [consul-cluster](https://github.com/hashicorp/terraform-aws-consul/tree/master/modules/consul-cluster) documentation.
+
+
+
+## Quick start
+
+To deploy a Consul Cluster:
+
+1. `git clone` this repo to your computer.
+1. Optional: build a Consul AMI. See the [consul-ami example](https://github.com/hashicorp/terraform-aws-consul/tree/master/examples/consul-ami) documentation for instructions. Make sure to
+   note down the ID of the AMI.
+1. Install [Terraform](https://www.terraform.io/).
+1. Open `variables.tf`, set the environment variables specified at the top of the file, and fill in any other variables that
+   don't have a default. If you built a custom AMI, put the AMI ID into the `ami_id` variable. Otherwise, one of our
+   public example AMIs will be used by default. These AMIs are great for learning/experimenting, but are NOT
+   recommended for production use.
+1. Run `terraform init`.
+1. Run `terraform apply`.
+1. Run the [consul-examples-helper.sh script](https://github.com/hashicorp/terraform-aws-consul/tree/master/examples/consul-examples-helper/consul-examples-helper.sh) to
+   print out the IP addresses of the Consul servers and some example commands you can run to interact with the cluster:
+   `../consul-examples-helper/consul-examples-helper.sh`.
diff --git a/modules/run-consul/README.md b/modules/run-consul/README.md
index 0b990a78..87ed95d2 100644
--- a/modules/run-consul/README.md
+++ b/modules/run-consul/README.md
@@ -1,6 +1,6 @@
 # Consul Run Script
 
-This folder contains a script for configuring and running Consul on an [AWS](https://aws.amazon.com/) server. This 
+This folder contains a script for configuring and running Consul on an [AWS](https://aws.amazon.com/) server. This
 script has been tested on the following operating systems:
 
 * Ubuntu 16.04
@@ -14,8 +14,8 @@ There is a good chance it will work on other flavors of Debian, CentOS, and RHEL
 
 ## Quick start
 
-This script assumes you installed it, plus all of its dependencies (including Consul itself), using the [install-consul 
-module](https://github.com/hashicorp/terraform-aws-consul/tree/master/modules/install-consul). The default install path is `/opt/consul/bin`, so to start Consul in server mode, 
+This script assumes you installed it, plus all of its dependencies (including Consul itself), using the [install-consul
+module](https://github.com/hashicorp/terraform-aws-consul/tree/master/modules/install-consul). The default install path is `/opt/consul/bin`, so to start Consul in server mode,
 you run:
 
 ```
@@ -33,22 +33,22 @@ This will:
 1. Generate a Consul configuration file called `default.json` in the Consul config dir (default: `/opt/consul/config`).
    See [Consul configuration](#consul-configuration) for details on what this configuration file will contain and how
    to override it with your own configuration.
-   
+
 1. Generate a [systemd](https://www.freedesktop.org/wiki/Software/systemd/) configuration file called `consul.service` in the systemd
    config dir (default: `/etc/systemd/system`) with a command that will run Consul:  
    `consul agent -config-dir=/opt/consul/config -data-dir=/opt/consul/data`.
 
 1. Tell systemd to load the new configuration file, thereby starting Consul.
 
-We recommend using the `run-consul` command as part of [User 
+We recommend using the `run-consul` command as part of [User
 Data](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html#user-data-shell-scripts), so that it executes
-when the EC2 Instance is first booting. After runing `run-consul` on that initial boot, the `systemd` configuration 
+when the EC2 Instance is first booting. After runing `run-consul` on that initial boot, the `systemd` configuration
 will automatically restart Consul if it crashes or the EC2 instance reboots.
 
 Note that `systemd` logs to its own journal by default.  To view the Consul logs, run `journalctl -u consul.service`.  To change
 the log output location, you can specify the `StandardOutput` and `StandardError` options by using the `--systemd-stdout` and `--systemd-stderr`
 options.  See the [`systemd.exec` man pages](https://www.freedesktop.org/software/systemd/man/systemd.exec.html#StandardOutput=) for available
-options, but note that the `file:path` option requires [systemd version >= 236](https://stackoverflow.com/a/48052152), which is not provided 
+options, but note that the `file:path` option requires [systemd version >= 236](https://stackoverflow.com/a/48052152), which is not provided
 in the base Ubuntu 16.04 and Amazon Linux 2 images.
 
 See the [consul-cluster example](https://github.com/hashicorp/terraform-aws-consul/tree/master/examples/root-example) for fully-working sample code.
@@ -80,6 +80,7 @@ The `run-consul` script accepts the following arguments:
 * `ca-file-path` (optional): Path to the CA file used to verify outgoing connections. Must be specified with `enable-rpc-encryption`, `cert-file-path` and `key-file-path`.
 * `cert-file-path` (optional): Path to the certificate file used to verify incoming connections. Must be specified with `enable-rpc-encryption`, `ca-file-path`, and `key-file-path`.
 * `key-file-path` (optional): Path to the certificate key used to verify incoming connections. Must be specified with `enable-rpc-encryption`, `ca-file-path` and `cert-file-path`.
+* `enable-connect` (optional): If this flag is set, turn on Consul Connect when bootstrapping a cluster. To specify your own CA, specify an override config as outlined below.
 * `skip-consul-config` (optional): If this flag is set, don't generate a Consul configuration file. This is useful if
   you have a custom configuration file and don't want to use any of of the default settings from `run-consul`.
 
@@ -106,38 +107,38 @@ Example:
 
 ## Consul configuration
 
-`run-consul` generates a configuration file for Consul called `default.json` that tries to figure out reasonable 
-defaults for a Consul cluster in AWS. Check out the [Consul Configuration Files 
+`run-consul` generates a configuration file for Consul called `default.json` that tries to figure out reasonable
+defaults for a Consul cluster in AWS. Check out the [Consul Configuration Files
 documentation](https://www.consul.io/docs/agent/options.html#configuration-files) for what configuration settings are
 available.
-  
-  
+
+
 ### Default configuration
 
 `run-consul` sets the following configuration values by default:
-  
-* [advertise_addr](https://www.consul.io/docs/agent/options.html#advertise_addr): Set to the EC2 Instance's private IP 
+
+* [advertise_addr](https://www.consul.io/docs/agent/options.html#advertise_addr): Set to the EC2 Instance's private IP
   address, as fetched from [Metadata](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html).
 
-* [bind_addr](https://www.consul.io/docs/agent/options.html#bind_addr): Set to the EC2 Instance's private IP address, 
+* [bind_addr](https://www.consul.io/docs/agent/options.html#bind_addr): Set to the EC2 Instance's private IP address,
   as fetched from [Metadata](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html).
 
-* [bootstrap_expect](https://www.consul.io/docs/agent/options.html#bootstrap_expect): If `--server` is set, 
-  set this config based on the EC2 Instance's tags (using the 
-  [describe-tags API](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-tags.html)): 
-    * If there is a `aws:autoscaling:groupName` tag, that means this EC2 Instance is part of an Auto Scaling Group 
-      (ASG), so set this config to the desired capacity of the ASG (fetched via the [describe-auto-scaling-groups 
-      API](https://docs.aws.amazon.com/cli/latest/reference/autoscaling/describe-auto-scaling-groups.html)). 
+* [bootstrap_expect](https://www.consul.io/docs/agent/options.html#bootstrap_expect): If `--server` is set,
+  set this config based on the EC2 Instance's tags (using the
+  [describe-tags API](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-tags.html)):
+    * If there is a `aws:autoscaling:groupName` tag, that means this EC2 Instance is part of an Auto Scaling Group
+      (ASG), so set this config to the desired capacity of the ASG (fetched via the [describe-auto-scaling-groups
+      API](https://docs.aws.amazon.com/cli/latest/reference/autoscaling/describe-auto-scaling-groups.html)).
     * Otherwise, log a warning, and set this to 1. This fallback is not recommended!     
 
 * [client_addr](https://www.consul.io/docs/agent/options.html#client_addr): Set to 0.0.0.0 so you can access the client
   and UI endpoint on each EC2 Instance from the outside.
 
-* [datacenter](https://www.consul.io/docs/agent/options.html#datacenter): Set to the current AWS region (e.g. 
+* [datacenter](https://www.consul.io/docs/agent/options.html#datacenter): Set to the current AWS region (e.g.
   `us-east-1`), as fetched from [Metadata](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html).
   If the `--datacenter` flag is provided, then that value is used instead.
 
-* [node_name](https://www.consul.io/docs/agent/options.html#node_name): Set to the instance id, as fetched from 
+* [node_name](https://www.consul.io/docs/agent/options.html#node_name): Set to the instance id, as fetched from
   [Metadata](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html).
 
 * [retry_join_ec2](https://www.consul.io/docs/agent/options.html#retry_join_ec2): Look up the EC2 Instances tags
@@ -147,9 +148,9 @@ available.
       argument.
     * [tag_value](https://www.consul.io/docs/agent/options.html#tag_value): Set to the value this EC2 Instance has for
       the `tag_key`. If the key is not set, then the `retry_join_ec2` setting will NOT be included in the config file.
-    * [region](https://www.consul.io/docs/agent/options.html#region): Set to the current AWS region (e.g. `us-east-1`), 
+    * [region](https://www.consul.io/docs/agent/options.html#region): Set to the current AWS region (e.g. `us-east-1`),
       as fetched from [Metadata](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html).
-      
+
 * [server](https://www.consul.io/docs/agent/options.html#server): Set to true if `--server` is set.
 
 * [ui](https://www.consul.io/docs/agent/options.html#ui): Set to true.
@@ -157,11 +158,11 @@ available.
 
 ### Overriding the configuration
 
-To override the default configuration, simply put your own configuration file in the Consul config folder (default: 
-`/opt/consul/config`), but with a name that comes later in the alphabet than `default.json` (e.g. 
-`my-custom-config.json`). Consul will load all the `.json` configuration files in the config dir and 
-[merge them together in alphabetical order](https://www.consul.io/docs/agent/options.html#_config_dir), so that 
-settings in files that come later in the alphabet will override the earlier ones. 
+To override the default configuration, simply put your own configuration file in the Consul config folder (default:
+`/opt/consul/config`), but with a name that comes later in the alphabet than `default.json` (e.g.
+`my-custom-config.json`). Consul will load all the `.json` configuration files in the config dir and
+[merge them together in alphabetical order](https://www.consul.io/docs/agent/options.html#_config_dir), so that
+settings in files that come later in the alphabet will override the earlier ones.
 
 For example, to override the default `retry_join_ec2` settings, you could create a file called `tags.json` with the
 contents:
@@ -186,7 +187,7 @@ at all using the `--skip-consul-config` flag:
 
 ### Required permissions
 
-The `run-consul` script assumes it is running on an EC2 Instance with an [IAM 
+The `run-consul` script assumes it is running on an EC2 Instance with an [IAM
 Role](http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) that has the following permissions:
 
 * `ec2:DescribeInstances`
@@ -200,8 +201,8 @@ These permissions are automatically added by the [consul-cluster module](https:/
 
 ## How do you handle encryption?
 
-Consul can encrypt all of its network traffic (see the [encryption docs for 
-details](https://www.consul.io/docs/agent/encryption.html)), but by default, encryption is not enabled in this 
+Consul can encrypt all of its network traffic (see the [encryption docs for
+details](https://www.consul.io/docs/agent/encryption.html)), but by default, encryption is not enabled in this
 Module. To enable encryption, you need to do the following:
 
 1. [Gossip encryption: provide an encryption key](#gossip-encryption-provide-an-encryption-key)
@@ -247,7 +248,7 @@ dir (default location: `/opt/consul/config`):
 ```
 
 You will also want to set the [verify_incoming](https://www.consul.io/docs/agent/options.html#verify_incoming) and
-[verify_outgoing](https://www.consul.io/docs/agent/options.html#verify_outgoing) settings to verify TLS certs on 
+[verify_outgoing](https://www.consul.io/docs/agent/options.html#verify_outgoing) settings to verify TLS certs on
 incoming and outgoing connections, respectively:
 
 ```json
@@ -276,4 +277,4 @@ track other servers. A server is considered healthy when:
 There are Autopilot settings called [upgrade migrations](https://www.consul.io/docs/guides/autopilot.html#upgrade-migrations)
 that are useful when adding new members to the cluster either with newer configurations or using
 newer versions of Consul. These configurations manage how Consul will promote new servers and demote
-old ones. These settings, however, are only available at the Consul Enterprise version. 
+old ones. These settings, however, are only available at the Consul Enterprise version.
diff --git a/variables.tf b/variables.tf
index a2ab5424..116f1b69 100644
--- a/variables.tf
+++ b/variables.tf
@@ -15,7 +15,7 @@
 variable "ami_id" {
   description = "The ID of the AMI to run in the cluster. This should be an AMI built from the Packer template under examples/consul-ami/consul.json. To keep this example simple, we run the same AMI on both server and client nodes, but in real-world usage, your client nodes would also run your apps. If the default value is used, Terraform will look up the latest AMI build automatically."
   type        = string
-  default     = null
+  default     = "ami-0d2cef6a8db479d82"
 }
 
 variable "cluster_name" {
@@ -45,7 +45,7 @@ variable "cluster_tag_key" {
 variable "ssh_key_name" {
   description = "The name of an EC2 Key Pair that can be used to SSH to the EC2 Instances in this cluster. Set to an empty string to not associate a Key Pair."
   type        = string
-  default     = null
+  default     = "nt-trial"
 }
 
 variable "vpc_id" {
@@ -59,4 +59,3 @@ variable "spot_price" {
   type        = number
   default     = null
 }
-

From 09b16ddb341f4965d3500131884cca2a5390a0fc Mon Sep 17 00:00:00 2001
From: Nirmal Thacker <nirmalthacker@gmail.com>
Date: Thu, 14 May 2020 11:08:24 -0700
Subject: [PATCH 02/31] Is Atom snipping off ws?

---
 modules/run-consul/README.md | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/modules/run-consul/README.md b/modules/run-consul/README.md
index 87ed95d2..5efcfa1e 100644
--- a/modules/run-consul/README.md
+++ b/modules/run-consul/README.md
@@ -277,4 +277,4 @@ track other servers. A server is considered healthy when:
 There are Autopilot settings called [upgrade migrations](https://www.consul.io/docs/guides/autopilot.html#upgrade-migrations)
 that are useful when adding new members to the cluster either with newer configurations or using
 newer versions of Consul. These configurations manage how Consul will promote new servers and demote
-old ones. These settings, however, are only available at the Consul Enterprise version.
+old ones. These settings, however, are only available at the Consul Enterprise version. 

From 16781ed13d84dea77eda5f0bc38375d41b56ccca Mon Sep 17 00:00:00 2001
From: Nirmal Thacker <nirmalthacker@gmail.com>
Date: Thu, 14 May 2020 11:13:19 -0700
Subject: [PATCH 03/31] Is Atom snipping off ws?

---
 modules/run-consul/README.md | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/modules/run-consul/README.md b/modules/run-consul/README.md
index 5efcfa1e..e39f2b1b 100644
--- a/modules/run-consul/README.md
+++ b/modules/run-consul/README.md
@@ -117,7 +117,7 @@ available.
 
 `run-consul` sets the following configuration values by default:
 
-* [advertise_addr](https://www.consul.io/docs/agent/options.html#advertise_addr): Set to the EC2 Instance's private IP
+* [advertise_addr](https://www.consul.io/docs/agent/options.html#advertise_addr): Set to the EC2 Instance's private IP 
   address, as fetched from [Metadata](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html).
 
 * [bind_addr](https://www.consul.io/docs/agent/options.html#bind_addr): Set to the EC2 Instance's private IP address,
@@ -277,4 +277,4 @@ track other servers. A server is considered healthy when:
 There are Autopilot settings called [upgrade migrations](https://www.consul.io/docs/guides/autopilot.html#upgrade-migrations)
 that are useful when adding new members to the cluster either with newer configurations or using
 newer versions of Consul. These configurations manage how Consul will promote new servers and demote
-old ones. These settings, however, are only available at the Consul Enterprise version. 
+old ones. These settings, however, are only available at the Consul Enterprise version.

From 02a4c57dfc70d0cbe45aeaceaf810194441e749d Mon Sep 17 00:00:00 2001
From: Nirmal Thacker <nirmalthacker@gmail.com>
Date: Thu, 14 May 2020 11:16:35 -0700
Subject: [PATCH 04/31] revert it works?

---
 modules/run-consul/README.md | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/modules/run-consul/README.md b/modules/run-consul/README.md
index e39f2b1b..87ed95d2 100644
--- a/modules/run-consul/README.md
+++ b/modules/run-consul/README.md
@@ -117,7 +117,7 @@ available.
 
 `run-consul` sets the following configuration values by default:
 
-* [advertise_addr](https://www.consul.io/docs/agent/options.html#advertise_addr): Set to the EC2 Instance's private IP 
+* [advertise_addr](https://www.consul.io/docs/agent/options.html#advertise_addr): Set to the EC2 Instance's private IP
   address, as fetched from [Metadata](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html).
 
 * [bind_addr](https://www.consul.io/docs/agent/options.html#bind_addr): Set to the EC2 Instance's private IP address,

From 09656be75dac880389d7d1281da112c4b4fda2b5 Mon Sep 17 00:00:00 2001
From: Nirmal Thacker <nirmalthacker@gmail.com>
Date: Thu, 14 May 2020 11:19:46 -0700
Subject: [PATCH 05/31] disabled ws package

---
 modules/run-consul/README.md | 68 ++++++++++++++++++------------------
 1 file changed, 34 insertions(+), 34 deletions(-)

diff --git a/modules/run-consul/README.md b/modules/run-consul/README.md
index 87ed95d2..0129964d 100644
--- a/modules/run-consul/README.md
+++ b/modules/run-consul/README.md
@@ -1,6 +1,6 @@
 # Consul Run Script
 
-This folder contains a script for configuring and running Consul on an [AWS](https://aws.amazon.com/) server. This
+This folder contains a script for configuring and running Consul on an [AWS](https://aws.amazon.com/) server. This 
 script has been tested on the following operating systems:
 
 * Ubuntu 16.04
@@ -14,8 +14,8 @@ There is a good chance it will work on other flavors of Debian, CentOS, and RHEL
 
 ## Quick start
 
-This script assumes you installed it, plus all of its dependencies (including Consul itself), using the [install-consul
-module](https://github.com/hashicorp/terraform-aws-consul/tree/master/modules/install-consul). The default install path is `/opt/consul/bin`, so to start Consul in server mode,
+This script assumes you installed it, plus all of its dependencies (including Consul itself), using the [install-consul 
+module](https://github.com/hashicorp/terraform-aws-consul/tree/master/modules/install-consul). The default install path is `/opt/consul/bin`, so to start Consul in server mode, 
 you run:
 
 ```
@@ -33,22 +33,22 @@ This will:
 1. Generate a Consul configuration file called `default.json` in the Consul config dir (default: `/opt/consul/config`).
    See [Consul configuration](#consul-configuration) for details on what this configuration file will contain and how
    to override it with your own configuration.
-
+   
 1. Generate a [systemd](https://www.freedesktop.org/wiki/Software/systemd/) configuration file called `consul.service` in the systemd
    config dir (default: `/etc/systemd/system`) with a command that will run Consul:  
    `consul agent -config-dir=/opt/consul/config -data-dir=/opt/consul/data`.
 
 1. Tell systemd to load the new configuration file, thereby starting Consul.
 
-We recommend using the `run-consul` command as part of [User
+We recommend using the `run-consul` command as part of [User 
 Data](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html#user-data-shell-scripts), so that it executes
-when the EC2 Instance is first booting. After runing `run-consul` on that initial boot, the `systemd` configuration
+when the EC2 Instance is first booting. After runing `run-consul` on that initial boot, the `systemd` configuration 
 will automatically restart Consul if it crashes or the EC2 instance reboots.
 
 Note that `systemd` logs to its own journal by default.  To view the Consul logs, run `journalctl -u consul.service`.  To change
 the log output location, you can specify the `StandardOutput` and `StandardError` options by using the `--systemd-stdout` and `--systemd-stderr`
 options.  See the [`systemd.exec` man pages](https://www.freedesktop.org/software/systemd/man/systemd.exec.html#StandardOutput=) for available
-options, but note that the `file:path` option requires [systemd version >= 236](https://stackoverflow.com/a/48052152), which is not provided
+options, but note that the `file:path` option requires [systemd version >= 236](https://stackoverflow.com/a/48052152), which is not provided 
 in the base Ubuntu 16.04 and Amazon Linux 2 images.
 
 See the [consul-cluster example](https://github.com/hashicorp/terraform-aws-consul/tree/master/examples/root-example) for fully-working sample code.
@@ -107,38 +107,38 @@ Example:
 
 ## Consul configuration
 
-`run-consul` generates a configuration file for Consul called `default.json` that tries to figure out reasonable
-defaults for a Consul cluster in AWS. Check out the [Consul Configuration Files
+`run-consul` generates a configuration file for Consul called `default.json` that tries to figure out reasonable 
+defaults for a Consul cluster in AWS. Check out the [Consul Configuration Files 
 documentation](https://www.consul.io/docs/agent/options.html#configuration-files) for what configuration settings are
 available.
-
-
+  
+  
 ### Default configuration
 
 `run-consul` sets the following configuration values by default:
-
-* [advertise_addr](https://www.consul.io/docs/agent/options.html#advertise_addr): Set to the EC2 Instance's private IP
+  
+* [advertise_addr](https://www.consul.io/docs/agent/options.html#advertise_addr): Set to the EC2 Instance's private IP 
   address, as fetched from [Metadata](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html).
 
-* [bind_addr](https://www.consul.io/docs/agent/options.html#bind_addr): Set to the EC2 Instance's private IP address,
+* [bind_addr](https://www.consul.io/docs/agent/options.html#bind_addr): Set to the EC2 Instance's private IP address, 
   as fetched from [Metadata](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html).
 
-* [bootstrap_expect](https://www.consul.io/docs/agent/options.html#bootstrap_expect): If `--server` is set,
-  set this config based on the EC2 Instance's tags (using the
-  [describe-tags API](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-tags.html)):
-    * If there is a `aws:autoscaling:groupName` tag, that means this EC2 Instance is part of an Auto Scaling Group
-      (ASG), so set this config to the desired capacity of the ASG (fetched via the [describe-auto-scaling-groups
-      API](https://docs.aws.amazon.com/cli/latest/reference/autoscaling/describe-auto-scaling-groups.html)).
+* [bootstrap_expect](https://www.consul.io/docs/agent/options.html#bootstrap_expect): If `--server` is set, 
+  set this config based on the EC2 Instance's tags (using the 
+  [describe-tags API](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-tags.html)): 
+    * If there is a `aws:autoscaling:groupName` tag, that means this EC2 Instance is part of an Auto Scaling Group 
+      (ASG), so set this config to the desired capacity of the ASG (fetched via the [describe-auto-scaling-groups 
+      API](https://docs.aws.amazon.com/cli/latest/reference/autoscaling/describe-auto-scaling-groups.html)). 
     * Otherwise, log a warning, and set this to 1. This fallback is not recommended!     
 
 * [client_addr](https://www.consul.io/docs/agent/options.html#client_addr): Set to 0.0.0.0 so you can access the client
   and UI endpoint on each EC2 Instance from the outside.
 
-* [datacenter](https://www.consul.io/docs/agent/options.html#datacenter): Set to the current AWS region (e.g.
+* [datacenter](https://www.consul.io/docs/agent/options.html#datacenter): Set to the current AWS region (e.g. 
   `us-east-1`), as fetched from [Metadata](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html).
   If the `--datacenter` flag is provided, then that value is used instead.
 
-* [node_name](https://www.consul.io/docs/agent/options.html#node_name): Set to the instance id, as fetched from
+* [node_name](https://www.consul.io/docs/agent/options.html#node_name): Set to the instance id, as fetched from 
   [Metadata](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html).
 
 * [retry_join_ec2](https://www.consul.io/docs/agent/options.html#retry_join_ec2): Look up the EC2 Instances tags
@@ -148,9 +148,9 @@ available.
       argument.
     * [tag_value](https://www.consul.io/docs/agent/options.html#tag_value): Set to the value this EC2 Instance has for
       the `tag_key`. If the key is not set, then the `retry_join_ec2` setting will NOT be included in the config file.
-    * [region](https://www.consul.io/docs/agent/options.html#region): Set to the current AWS region (e.g. `us-east-1`),
+    * [region](https://www.consul.io/docs/agent/options.html#region): Set to the current AWS region (e.g. `us-east-1`), 
       as fetched from [Metadata](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html).
-
+      
 * [server](https://www.consul.io/docs/agent/options.html#server): Set to true if `--server` is set.
 
 * [ui](https://www.consul.io/docs/agent/options.html#ui): Set to true.
@@ -158,11 +158,11 @@ available.
 
 ### Overriding the configuration
 
-To override the default configuration, simply put your own configuration file in the Consul config folder (default:
-`/opt/consul/config`), but with a name that comes later in the alphabet than `default.json` (e.g.
-`my-custom-config.json`). Consul will load all the `.json` configuration files in the config dir and
-[merge them together in alphabetical order](https://www.consul.io/docs/agent/options.html#_config_dir), so that
-settings in files that come later in the alphabet will override the earlier ones.
+To override the default configuration, simply put your own configuration file in the Consul config folder (default: 
+`/opt/consul/config`), but with a name that comes later in the alphabet than `default.json` (e.g. 
+`my-custom-config.json`). Consul will load all the `.json` configuration files in the config dir and 
+[merge them together in alphabetical order](https://www.consul.io/docs/agent/options.html#_config_dir), so that 
+settings in files that come later in the alphabet will override the earlier ones. 
 
 For example, to override the default `retry_join_ec2` settings, you could create a file called `tags.json` with the
 contents:
@@ -187,7 +187,7 @@ at all using the `--skip-consul-config` flag:
 
 ### Required permissions
 
-The `run-consul` script assumes it is running on an EC2 Instance with an [IAM
+The `run-consul` script assumes it is running on an EC2 Instance with an [IAM 
 Role](http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) that has the following permissions:
 
 * `ec2:DescribeInstances`
@@ -201,8 +201,8 @@ These permissions are automatically added by the [consul-cluster module](https:/
 
 ## How do you handle encryption?
 
-Consul can encrypt all of its network traffic (see the [encryption docs for
-details](https://www.consul.io/docs/agent/encryption.html)), but by default, encryption is not enabled in this
+Consul can encrypt all of its network traffic (see the [encryption docs for 
+details](https://www.consul.io/docs/agent/encryption.html)), but by default, encryption is not enabled in this 
 Module. To enable encryption, you need to do the following:
 
 1. [Gossip encryption: provide an encryption key](#gossip-encryption-provide-an-encryption-key)
@@ -248,7 +248,7 @@ dir (default location: `/opt/consul/config`):
 ```
 
 You will also want to set the [verify_incoming](https://www.consul.io/docs/agent/options.html#verify_incoming) and
-[verify_outgoing](https://www.consul.io/docs/agent/options.html#verify_outgoing) settings to verify TLS certs on
+[verify_outgoing](https://www.consul.io/docs/agent/options.html#verify_outgoing) settings to verify TLS certs on 
 incoming and outgoing connections, respectively:
 
 ```json
@@ -277,4 +277,4 @@ track other servers. A server is considered healthy when:
 There are Autopilot settings called [upgrade migrations](https://www.consul.io/docs/guides/autopilot.html#upgrade-migrations)
 that are useful when adding new members to the cluster either with newer configurations or using
 newer versions of Consul. These configurations manage how Consul will promote new servers and demote
-old ones. These settings, however, are only available at the Consul Enterprise version.
+old ones. These settings, however, are only available at the Consul Enterprise version. 
\ No newline at end of file

From 995b63edcb0cde874031b4067c43a3e1e4c667a6 Mon Sep 17 00:00:00 2001
From: Nirmal Thacker <nirmalthacker@gmail.com>
Date: Thu, 14 May 2020 12:49:42 -0700
Subject: [PATCH 06/31] set up connect

---
 modules/run-consul/README.md  |  1 +
 modules/run-consul/run-consul | 19 +++++++++++++++++++
 variables.tf                  |  2 +-
 3 files changed, 21 insertions(+), 1 deletion(-)

diff --git a/modules/run-consul/README.md b/modules/run-consul/README.md
index 0129964d..347082fa 100644
--- a/modules/run-consul/README.md
+++ b/modules/run-consul/README.md
@@ -81,6 +81,7 @@ The `run-consul` script accepts the following arguments:
 * `cert-file-path` (optional): Path to the certificate file used to verify incoming connections. Must be specified with `enable-rpc-encryption`, `ca-file-path`, and `key-file-path`.
 * `key-file-path` (optional): Path to the certificate key used to verify incoming connections. Must be specified with `enable-rpc-encryption`, `ca-file-path` and `cert-file-path`.
 * `enable-connect` (optional): If this flag is set, turn on Consul Connect when bootstrapping a cluster. To specify your own CA, specify an override config as outlined below.
+* `services-config-dir` (optional): Path to dir of one or many service configurations. Services can be further configured to set Consul Connect Proxies, Sidecar registrations & upstream service dependencies for a Service Mesh
 * `skip-consul-config` (optional): If this flag is set, don't generate a Consul configuration file. This is useful if
   you have a custom configuration file and don't want to use any of of the default settings from `run-consul`.
 
diff --git a/modules/run-consul/run-consul b/modules/run-consul/run-consul
index 56c5054f..c54c7818 100755
--- a/modules/run-consul/run-consul
+++ b/modules/run-consul/run-consul
@@ -65,6 +65,10 @@ function print_usage {
   echo -e "  --autopilot-disable-upgrade-migration\t(Enterprise-only) If this flag is set, this will disable Autopilot's upgrade migration strategy in Consul Enterprise of waiting until enough newer-versioned servers have been added to the cluster before promoting any of them to voters. Defaults to $DEFAULT_AUTOPILOT_DISABLE_UPGRADE_MIGRATION. Optional."
   echo -e "  --autopilot-upgrade-version-tag\t\t(Enterprise-only) That tag to be used to override the version information used during a migration. Optional."
   echo
+  echo "Options for Consul Connect:"
+  echo
+  echo -e "  --enable-connect\tIf set, turn on Consul Connect(only Server Mode)"
+  echo
   echo
   echo "Example:"
   echo
@@ -309,6 +313,17 @@ EOF
 )
   fi
 
+  local connect_configuration=""
+  if [[ "$enable_connect" == "true" && "$server" == "true" ]]; then
+    log_info "Creating Consul Connect configuration"
+    connect_configuration=$(cat <<EOF
+"connect" : {
+  "enabled" : true
+},
+EOF
+)
+  fi
+
   log_info "Creating default Consul configuration"
   local default_config_json=$(cat <<EOF
 {
@@ -324,6 +339,7 @@ EOF
   $gossip_encryption_configuration
   $rpc_encryption_configuration
   $autopilot_configuration
+  $connect_configuration
   "ui": $ui
 }
 EOF
@@ -530,6 +546,9 @@ function run {
       --enable-gossip-encryption)
         enable_gossip_encryption="true"
         ;;
+      --enable-connect)
+        enable_connect="true"
+        ;;
       --gossip-encryption-key)
         assert_not_empty "$key" "$2"
         gossip_encryption_key="$2"
diff --git a/variables.tf b/variables.tf
index 116f1b69..6a43c172 100644
--- a/variables.tf
+++ b/variables.tf
@@ -15,7 +15,7 @@
 variable "ami_id" {
   description = "The ID of the AMI to run in the cluster. This should be an AMI built from the Packer template under examples/consul-ami/consul.json. To keep this example simple, we run the same AMI on both server and client nodes, but in real-world usage, your client nodes would also run your apps. If the default value is used, Terraform will look up the latest AMI build automatically."
   type        = string
-  default     = "ami-0d2cef6a8db479d82"
+  default     = "ami-0fce111d3bd9490e1"
 }
 
 variable "cluster_name" {

From 893e24c09fc6c1bffe11121c2e704abec3bd79f8 Mon Sep 17 00:00:00 2001
From: Nirmal Thacker <nirmalthacker@gmail.com>
Date: Thu, 14 May 2020 13:13:34 -0700
Subject: [PATCH 07/31] Example scripts

---
 .../user-data-client.sh                           | 15 +++++++++++++++
 .../user-data-server.sh                           | 13 +++++++++++++
 2 files changed, 28 insertions(+)
 create mode 100644 examples/example-with-consul-connect/user-data-client.sh
 create mode 100755 examples/example-with-consul-connect/user-data-server.sh

diff --git a/examples/example-with-consul-connect/user-data-client.sh b/examples/example-with-consul-connect/user-data-client.sh
new file mode 100644
index 00000000..fd0158b0
--- /dev/null
+++ b/examples/example-with-consul-connect/user-data-client.sh
@@ -0,0 +1,15 @@
+#!/bin/bash
+# This script is meant to be run in the User Data of each EC2 Instance while it's booting. The script uses the
+# run-consul script to configure and start Consul in client mode. Note that this script assumes it's running in an AMI
+# built from the Packer template in examples/consul-ami/consul.json.
+
+set -e
+
+# Send the log output from this script to user-data.log, syslog, and the console
+# From: https://alestic.com/2010/12/ec2-user-data-output/
+exec > >(tee /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1
+
+# These variables are passed in via Terraform template interplation
+/opt/consul/bin/run-consul --client --cluster-tag-key "${cluster_tag_key}" --cluster-tag-value "${cluster_tag_value}"
+
+# You could add commands to boot your other apps here
\ No newline at end of file
diff --git a/examples/example-with-consul-connect/user-data-server.sh b/examples/example-with-consul-connect/user-data-server.sh
new file mode 100755
index 00000000..d966deb7
--- /dev/null
+++ b/examples/example-with-consul-connect/user-data-server.sh
@@ -0,0 +1,13 @@
+#!/bin/bash
+# This script is meant to be run in the User Data of each EC2 Instance while it's booting. The script uses the
+# run-consul script to configure and start Consul in server mode. Note that this script assumes it's running in an AMI
+# built from the Packer template in examples/consul-ami/consul.json.
+
+set -e
+
+# Send the log output from this script to user-data.log, syslog, and the console
+# From: https://alestic.com/2010/12/ec2-user-data-output/
+exec > >(tee /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1
+
+# These variables are passed in via Terraform template interplation
+/opt/consul/bin/run-consul --server --cluster-tag-key "${cluster_tag_key}" --cluster-tag-value "${cluster_tag_value}" --enable-connect
\ No newline at end of file

From 22cb4d969c39f01a35c24dbaf86cd93cd2c9830b Mon Sep 17 00:00:00 2001
From: Nirmal Thacker <nirmalthacker@gmail.com>
Date: Thu, 14 May 2020 13:44:29 -0700
Subject: [PATCH 08/31] Basic test that only verifies that a consul cluster
 with connect turned on, works as expected

---
 test/consul_cluster_with_connect_test.go | 26 ++++++++++++++++++++++++
 test/consul_helpers.go                   |  4 ++--
 2 files changed, 28 insertions(+), 2 deletions(-)
 create mode 100644 test/consul_cluster_with_connect_test.go

diff --git a/test/consul_cluster_with_connect_test.go b/test/consul_cluster_with_connect_test.go
new file mode 100644
index 00000000..fe9de995
--- /dev/null
+++ b/test/consul_cluster_with_connect_test.go
@@ -0,0 +1,26 @@
+package test
+
+import (
+	"testing"
+)
+
+/*
+// Test the example in the example-with-consul-connect folder
+func TestConsulClusterWithUbuntu16Ami(t *testing.T) {
+	t.Parallel()
+	runConsulClusterTest(t, "ubuntu16-ami", ".", "../examples/consul-ami/consul.json", "ubuntu", "")
+}*/
+
+// Test the example in the example-with-consul-connect folder
+func TestConsulConnectWithUbuntu18Ami(t *testing.T) {
+	t.Parallel()
+	runConsulClusterTest(t, "ubuntu18-ami", ".", "../examples/consul-ami/consul.json", "ubuntu", "")
+}
+
+/*
+// Test the example in the example-with-consul-connect folder
+func TestConsulClusterWithAmazonLinuxAmi(t *testing.T) {
+	t.Parallel()
+	runConsulClusterTest(t, "amazon-linux-2-ami", ".", "../examples/consul-ami/consul.json", "ec2-user", "")
+}
+*/
\ No newline at end of file
diff --git a/test/consul_helpers.go b/test/consul_helpers.go
index da283d18..6a815759 100644
--- a/test/consul_helpers.go
+++ b/test/consul_helpers.go
@@ -6,7 +6,7 @@ import (
 	"strings"
 	"testing"
 	"time"
-
+	"os"
 	"github.com/gruntwork-io/terratest/modules/aws"
 	"github.com/gruntwork-io/terratest/modules/logger"
 	"github.com/gruntwork-io/terratest/modules/random"
@@ -56,7 +56,7 @@ func runConsulClusterTestWithVars(t *testing.T, packerBuildName string, examples
 	//os.Setenv("SKIP_setup_ami", "true")
 	//os.Setenv("SKIP_deploy", "true")
 	//os.Setenv("SKIP_validate", "true")
-	//os.Setenv("SKIP_teardown", "true")
+	os.Setenv("SKIP_teardown", "true")
 
 	exampleFolder := test_structure.CopyTerraformFolderToTemp(t, REPO_ROOT, examplesFolder)
 

From 548eda74aca44692bcaba30535f30e040d09824d Mon Sep 17 00:00:00 2001
From: Nirmal Thacker <nirmalthacker@gmail.com>
Date: Thu, 14 May 2020 14:36:38 -0700
Subject: [PATCH 09/31] testing if a CA comes up

---
 examples/example-with-consul-connect/main.tf  | 174 ++++++++++++++++++
 .../example-with-consul-connect/outputs.tf    |  60 ++++++
 .../example-with-consul-connect/variables.tf  |  61 ++++++
 test/consul_cluster_with_connect_test.go      |   8 +-
 test/consul_helpers.go                        |  35 +++-
 5 files changed, 332 insertions(+), 6 deletions(-)
 create mode 100644 examples/example-with-consul-connect/main.tf
 create mode 100644 examples/example-with-consul-connect/outputs.tf
 create mode 100644 examples/example-with-consul-connect/variables.tf

diff --git a/examples/example-with-consul-connect/main.tf b/examples/example-with-consul-connect/main.tf
new file mode 100644
index 00000000..7a90e5c1
--- /dev/null
+++ b/examples/example-with-consul-connect/main.tf
@@ -0,0 +1,174 @@
+# ---------------------------------------------------------------------------------------------------------------------
+# DEPLOY A CONSUL CLUSTER IN AWS
+# These templates show an example of how to use the consul-cluster module to deploy Consul in AWS. We deploy two Auto
+# Scaling Groups (ASGs): one with a small number of Consul server nodes and one with a larger number of Consul client
+# nodes. Note that these templates assume that the AMI you provide via the ami_id input variable is built from
+# the examples/consul-ami/consul.json Packer template.
+# ---------------------------------------------------------------------------------------------------------------------
+
+# ----------------------------------------------------------------------------------------------------------------------
+# REQUIRE A SPECIFIC TERRAFORM VERSION OR HIGHER
+# This module has been updated with 0.12 syntax, which means it is no longer compatible with any versions below 0.12.
+# ----------------------------------------------------------------------------------------------------------------------
+terraform {
+  required_version = ">= 0.12"
+}
+
+# ---------------------------------------------------------------------------------------------------------------------
+# AUTOMATICALLY LOOK UP THE LATEST PRE-BUILT AMI
+# This repo contains a CircleCI job that automatically builds and publishes the latest AMI by building the Packer
+# template at /examples/consul-ami upon every new release. The Terraform data source below automatically looks up the
+# latest AMI so that a simple "terraform apply" will just work without the user needing to manually build an AMI and
+# fill in the right value.
+#
+# !! WARNING !! These exmaple AMIs are meant only convenience when initially testing this repo. Do NOT use these example
+# AMIs in a production setting because it is important that you consciously think through the configuration you want
+# in your own production AMI.
+#
+# NOTE: This Terraform data source must return at least one AMI result or the entire template will fail. See
+# /_ci/publish-amis-in-new-account.md for more information.
+# ---------------------------------------------------------------------------------------------------------------------
+data "aws_ami" "consul" {
+  most_recent = true
+
+  # If we change the AWS Account in which test are run, update this value.
+  owners = ["562637147889"]
+
+  filter {
+    name   = "virtualization-type"
+    values = ["hvm"]
+  }
+
+  filter {
+    name   = "is-public"
+    values = ["true"]
+  }
+
+  filter {
+    name   = "name"
+    values = ["consul-ubuntu-*"]
+  }
+}
+
+# ---------------------------------------------------------------------------------------------------------------------
+# DEPLOY THE CONSUL SERVER NODES
+# ---------------------------------------------------------------------------------------------------------------------
+
+module "consul_servers" {
+  # When using these modules in your own templates, you will need to use a Git URL with a ref attribute that pins you
+  # to a specific version of the modules, such as the following example:
+  # source = "git::git@github.com:hashicorp/terraform-aws-consul.git//modules/consul-cluster?ref=v0.0.1"
+  source = "../../modules/consul-cluster"
+
+  cluster_name  = "${var.cluster_name}-server"
+  cluster_size  = var.num_servers
+  instance_type = "t2.micro"
+  spot_price    = var.spot_price
+
+  # The EC2 Instances will use these tags to automatically discover each other and form a cluster
+  cluster_tag_key   = var.cluster_tag_key
+  cluster_tag_value = var.cluster_name
+
+  ami_id    = "${var.ami_id == null ? data.aws_ami.consul.image_id : var.ami_id}"
+  user_data = "${data.template_file.user_data_server.rendered}"
+
+  vpc_id     = data.aws_vpc.default.id
+  subnet_ids = data.aws_subnet_ids.default.ids
+
+  # To make testing easier, we allow Consul and SSH requests from any IP address here but in a production
+  # deployment, we strongly recommend you limit this to the IP address ranges of known, trusted servers inside your VPC.
+  allowed_ssh_cidr_blocks = ["0.0.0.0/0"]
+
+  allowed_inbound_cidr_blocks = ["0.0.0.0/0"]
+  ssh_key_name                = var.ssh_key_name
+
+  tags = [
+    {
+      key                 = "Environment"
+      value               = "development"
+      propagate_at_launch = true
+    }
+  ]
+}
+
+# ---------------------------------------------------------------------------------------------------------------------
+# THE USER DATA SCRIPT THAT WILL RUN ON EACH CONSUL SERVER EC2 INSTANCE WHEN IT'S BOOTING
+# This script will configure and start Consul
+# ---------------------------------------------------------------------------------------------------------------------
+
+data "template_file" "user_data_server" {
+  template = file("${path.module}/examples/example-with-consul-connect/user-data-server.sh")
+
+  vars = {
+    cluster_tag_key   = var.cluster_tag_key
+    cluster_tag_value = var.cluster_name
+  }
+}
+
+# ---------------------------------------------------------------------------------------------------------------------
+# DEPLOY THE CONSUL CLIENT NODES
+# Note that you do not have to use the consul-cluster module to deploy your clients. We do so simply because it
+# provides a convenient way to deploy an Auto Scaling Group with the necessary IAM and security group permissions for
+# Consul, but feel free to deploy those clients however you choose (e.g. a single EC2 Instance, a Docker cluster, etc).
+# ---------------------------------------------------------------------------------------------------------------------
+
+module "consul_clients" {
+  # When using these modules in your own templates, you will need to use a Git URL with a ref attribute that pins you
+  # to a specific version of the modules, such as the following example:
+  # source = "git::git@github.com:hashicorp/terraform-aws-consul.git//modules/consul-cluster?ref=v0.0.1"
+  source = "../../modules/consul-cluster"
+
+  cluster_name  = "${var.cluster_name}-client"
+  cluster_size  = var.num_clients
+  instance_type = "t2.micro"
+  spot_price    = var.spot_price
+
+  cluster_tag_key   = "consul-clients"
+  cluster_tag_value = var.cluster_name
+
+  ami_id    = "${var.ami_id == null ? data.aws_ami.consul.image_id : var.ami_id}"
+  user_data = "${data.template_file.user_data_client.rendered}"
+
+  vpc_id     = data.aws_vpc.default.id
+  subnet_ids = data.aws_subnet_ids.default.ids
+
+  # To make testing easier, we allow Consul and SSH requests from any IP address here but in a production
+  # deployment, we strongly recommend you limit this to the IP address ranges of known, trusted servers inside your VPC.
+  allowed_ssh_cidr_blocks = ["0.0.0.0/0"]
+
+  allowed_inbound_cidr_blocks = ["0.0.0.0/0"]
+  ssh_key_name                = var.ssh_key_name
+}
+
+# ---------------------------------------------------------------------------------------------------------------------
+# THE USER DATA SCRIPT THAT WILL RUN ON EACH CONSUL CLIENT EC2 INSTANCE WHEN IT'S BOOTING
+# This script will configure and start Consul
+# ---------------------------------------------------------------------------------------------------------------------
+
+data "template_file" "user_data_client" {
+  template = file("${path.module}/examples/example-with-consul-connect/user-data-client.sh")
+
+  vars = {
+    cluster_tag_key   = var.cluster_tag_key
+    cluster_tag_value = var.cluster_name
+  }
+}
+
+# ---------------------------------------------------------------------------------------------------------------------
+# DEPLOY CONSUL IN THE DEFAULT VPC AND SUBNETS
+# Using the default VPC and subnets makes this example easy to run and test, but it means Consul is accessible from the
+# public Internet. For a production deployment, we strongly recommend deploying into a custom VPC with private subnets.
+# ---------------------------------------------------------------------------------------------------------------------
+
+data "aws_vpc" "default" {
+  default = var.vpc_id == null ? true : false
+  id      = "${var.vpc_id}"
+}
+
+data "aws_subnet_ids" "default" {
+  vpc_id = data.aws_vpc.default.id
+}
+
+data "aws_region" "current" {
+}
+
diff --git a/examples/example-with-consul-connect/outputs.tf b/examples/example-with-consul-connect/outputs.tf
new file mode 100644
index 00000000..347e1219
--- /dev/null
+++ b/examples/example-with-consul-connect/outputs.tf
@@ -0,0 +1,60 @@
+output "num_servers" {
+  value = module.consul_servers.cluster_size
+}
+
+output "asg_name_servers" {
+  value = module.consul_servers.asg_name
+}
+
+output "launch_config_name_servers" {
+  value = module.consul_servers.launch_config_name
+}
+
+output "iam_role_arn_servers" {
+  value = module.consul_servers.iam_role_arn
+}
+
+output "iam_role_id_servers" {
+  value = module.consul_servers.iam_role_id
+}
+
+output "security_group_id_servers" {
+  value = module.consul_servers.security_group_id
+}
+
+output "num_clients" {
+  value = module.consul_clients.cluster_size
+}
+
+output "asg_name_clients" {
+  value = module.consul_clients.asg_name
+}
+
+output "launch_config_name_clients" {
+  value = module.consul_clients.launch_config_name
+}
+
+output "iam_role_arn_clients" {
+  value = module.consul_clients.iam_role_arn
+}
+
+output "iam_role_id_clients" {
+  value = module.consul_clients.iam_role_id
+}
+
+output "security_group_id_clients" {
+  value = module.consul_clients.security_group_id
+}
+
+output "aws_region" {
+  value = data.aws_region.current.name
+}
+
+output "consul_servers_cluster_tag_key" {
+  value = module.consul_servers.cluster_tag_key
+}
+
+output "consul_servers_cluster_tag_value" {
+  value = module.consul_servers.cluster_tag_value
+}
+
diff --git a/examples/example-with-consul-connect/variables.tf b/examples/example-with-consul-connect/variables.tf
new file mode 100644
index 00000000..6a43c172
--- /dev/null
+++ b/examples/example-with-consul-connect/variables.tf
@@ -0,0 +1,61 @@
+# ---------------------------------------------------------------------------------------------------------------------
+# ENVIRONMENT VARIABLES
+# Define these secrets as environment variables
+# ---------------------------------------------------------------------------------------------------------------------
+
+# AWS_ACCESS_KEY_ID
+# AWS_SECRET_ACCESS_KEY
+# AWS_DEFAULT_REGION
+
+# ---------------------------------------------------------------------------------------------------------------------
+# OPTIONAL PARAMETERS
+# These parameters have reasonable defaults.
+# ---------------------------------------------------------------------------------------------------------------------
+
+variable "ami_id" {
+  description = "The ID of the AMI to run in the cluster. This should be an AMI built from the Packer template under examples/consul-ami/consul.json. To keep this example simple, we run the same AMI on both server and client nodes, but in real-world usage, your client nodes would also run your apps. If the default value is used, Terraform will look up the latest AMI build automatically."
+  type        = string
+  default     = "ami-0fce111d3bd9490e1"
+}
+
+variable "cluster_name" {
+  description = "What to name the Consul cluster and all of its associated resources"
+  type        = string
+  default     = "consul-example"
+}
+
+variable "num_servers" {
+  description = "The number of Consul server nodes to deploy. We strongly recommend using 3 or 5."
+  type        = number
+  default     = 3
+}
+
+variable "num_clients" {
+  description = "The number of Consul client nodes to deploy. You typically run the Consul client alongside your apps, so set this value to however many Instances make sense for your app code."
+  type        = number
+  default     = 6
+}
+
+variable "cluster_tag_key" {
+  description = "The tag the EC2 Instances will look for to automatically discover each other and form a cluster."
+  type        = string
+  default     = "consul-servers"
+}
+
+variable "ssh_key_name" {
+  description = "The name of an EC2 Key Pair that can be used to SSH to the EC2 Instances in this cluster. Set to an empty string to not associate a Key Pair."
+  type        = string
+  default     = "nt-trial"
+}
+
+variable "vpc_id" {
+  description = "The ID of the VPC in which the nodes will be deployed.  Uses default VPC if not supplied."
+  type        = string
+  default     = null
+}
+
+variable "spot_price" {
+  description = "The maximum hourly price to pay for EC2 Spot Instances."
+  type        = number
+  default     = null
+}
diff --git a/test/consul_cluster_with_connect_test.go b/test/consul_cluster_with_connect_test.go
index fe9de995..93cd62d0 100644
--- a/test/consul_cluster_with_connect_test.go
+++ b/test/consul_cluster_with_connect_test.go
@@ -8,19 +8,19 @@ import (
 // Test the example in the example-with-consul-connect folder
 func TestConsulClusterWithUbuntu16Ami(t *testing.T) {
 	t.Parallel()
-	runConsulClusterTest(t, "ubuntu16-ami", ".", "../examples/consul-ami/consul.json", "ubuntu", "")
+	runConsulClusterTest(t, "ubuntu16-ami", "examples/example-with-consul-connect", "../examples/consul-ami/consul.json", "ubuntu", "")
 }*/
 
 // Test the example in the example-with-consul-connect folder
 func TestConsulConnectWithUbuntu18Ami(t *testing.T) {
 	t.Parallel()
-	runConsulClusterTest(t, "ubuntu18-ami", ".", "../examples/consul-ami/consul.json", "ubuntu", "")
+	runConsulClusterTest(t, "ubuntu18-ami", "examples/example-with-consul-connect", "../examples/consul-ami/consul.json", "ubuntu", "")
 }
 
 /*
 // Test the example in the example-with-consul-connect folder
 func TestConsulClusterWithAmazonLinuxAmi(t *testing.T) {
 	t.Parallel()
-	runConsulClusterTest(t, "amazon-linux-2-ami", ".", "../examples/consul-ami/consul.json", "ec2-user", "")
+	runConsulClusterTest(t, "amazon-linux-2-ami", "examples/example-with-consul-connect", "../examples/consul-ami/consul.json", "ec2-user", "")
 }
-*/
\ No newline at end of file
+*/
diff --git a/test/consul_helpers.go b/test/consul_helpers.go
index 6a815759..98e53e66 100644
--- a/test/consul_helpers.go
+++ b/test/consul_helpers.go
@@ -6,7 +6,6 @@ import (
 	"strings"
 	"testing"
 	"time"
-	"os"
 	"github.com/gruntwork-io/terratest/modules/aws"
 	"github.com/gruntwork-io/terratest/modules/logger"
 	"github.com/gruntwork-io/terratest/modules/random"
@@ -56,7 +55,7 @@ func runConsulClusterTestWithVars(t *testing.T, packerBuildName string, examples
 	//os.Setenv("SKIP_setup_ami", "true")
 	//os.Setenv("SKIP_deploy", "true")
 	//os.Setenv("SKIP_validate", "true")
-	os.Setenv("SKIP_teardown", "true")
+	//os.Setenv("SKIP_teardown", "true")
 
 	exampleFolder := test_structure.CopyTerraformFolderToTemp(t, REPO_ROOT, examplesFolder)
 
@@ -126,6 +125,9 @@ func runConsulClusterTestWithVars(t *testing.T, packerBuildName string, examples
 
 		// Check the Consul clients
 		checkConsulClusterIsWorking(t, CONSUL_CLUSTER_EXAMPLE_OUTPUT_CLIENT_ASG_NAME, terraformOptions, awsRegion)
+		
+		// Check the Consul CA
+		checkConsulCA(t, CONSUL_CLUSTER_EXAMPLE_OUTPUT_SERVER_ASG_NAME, terraformOptions, awsRegion, sshUser, keyPair)
 	})
 }
 
@@ -213,3 +215,32 @@ func checkEnterpriseInstall(t *testing.T, asgNameOutputVar string, terratestOpti
 		t.Fatalf("This consul package is not the enterprise version.\n")
 	}
 }
+
+
+func checkConsulCA(t *testing.T, asgNameOutputVar string, terratestOptions *terraform.Options, awsRegion string, sshUser string, keyPair *aws.Ec2Keypair) {
+	asgName := terraform.OutputRequired(t, terratestOptions, asgNameOutputVar)
+	nodeIpAddress := getIpAddressOfAsgInstance(t, asgName, awsRegion)
+	
+	host := ssh.Host{
+		Hostname:    nodeIpAddress,
+		SshUserName: sshUser,
+		SshKeyPair:  keyPair.KeyPair,
+	}
+
+	maxRetries := 10
+	sleepBetweenRetries := 10 * time.Second
+	
+	output := retry.DoWithRetry(t, "Check Consul Built-in Certificate Authority", maxRetries, sleepBetweenRetries, func() (string, error) {
+		out, err := ssh.CheckSshCommandE(t, host, "consul connect ca get-config")
+		if err != nil {
+			return "", fmt.Errorf("Error running consul command: %s\n", err)
+		}
+
+		return out, nil
+	})
+
+	if !strings.Contains(output, "Config") {
+		t.Fatalf("Consul CA does not have a Config\n")
+	}
+}
+

From cef1e036575e2e6064fdedb7ddf671a2046c622a Mon Sep 17 00:00:00 2001
From: Nirmal Thacker <nirmalthacker@gmail.com>
Date: Thu, 14 May 2020 14:57:40 -0700
Subject: [PATCH 10/31] fix tests

---
 examples/example-with-consul-connect/main.tf |   6 +-
 test/consul_cluster_with_connect_test.go     |   6 +-
 test/consul_connect_tests.go                 | 214 +++++++++++++++++++
 3 files changed, 221 insertions(+), 5 deletions(-)
 create mode 100644 test/consul_connect_tests.go

diff --git a/examples/example-with-consul-connect/main.tf b/examples/example-with-consul-connect/main.tf
index 7a90e5c1..b14ad1ed 100644
--- a/examples/example-with-consul-connect/main.tf
+++ b/examples/example-with-consul-connect/main.tf
@@ -97,7 +97,8 @@ module "consul_servers" {
 # ---------------------------------------------------------------------------------------------------------------------
 
 data "template_file" "user_data_server" {
-  template = file("${path.module}/examples/example-with-consul-connect/user-data-server.sh")
+  template = file("${path.module}/user-data-server.sh")
+
 
   vars = {
     cluster_tag_key   = var.cluster_tag_key
@@ -146,7 +147,8 @@ module "consul_clients" {
 # ---------------------------------------------------------------------------------------------------------------------
 
 data "template_file" "user_data_client" {
-  template = file("${path.module}/examples/example-with-consul-connect/user-data-client.sh")
+  template = file("${path.module}/user-data-client.sh")
+
 
   vars = {
     cluster_tag_key   = var.cluster_tag_key
diff --git a/test/consul_cluster_with_connect_test.go b/test/consul_cluster_with_connect_test.go
index 93cd62d0..3313cb7d 100644
--- a/test/consul_cluster_with_connect_test.go
+++ b/test/consul_cluster_with_connect_test.go
@@ -8,19 +8,19 @@ import (
 // Test the example in the example-with-consul-connect folder
 func TestConsulClusterWithUbuntu16Ami(t *testing.T) {
 	t.Parallel()
-	runConsulClusterTest(t, "ubuntu16-ami", "examples/example-with-consul-connect", "../examples/consul-ami/consul.json", "ubuntu", "")
+	runConsulConnectTest(t, "ubuntu16-ami", "examples/example-with-consul-connect", "../examples/consul-ami/consul.json", "ubuntu")
 }*/
 
 // Test the example in the example-with-consul-connect folder
 func TestConsulConnectWithUbuntu18Ami(t *testing.T) {
 	t.Parallel()
-	runConsulClusterTest(t, "ubuntu18-ami", "examples/example-with-consul-connect", "../examples/consul-ami/consul.json", "ubuntu", "")
+	runConsulConnectTest(t, "ubuntu18-ami", "examples/example-with-consul-connect", "../examples/consul-ami/consul.json", "ubuntu")
 }
 
 /*
 // Test the example in the example-with-consul-connect folder
 func TestConsulClusterWithAmazonLinuxAmi(t *testing.T) {
 	t.Parallel()
-	runConsulClusterTest(t, "amazon-linux-2-ami", "examples/example-with-consul-connect", "../examples/consul-ami/consul.json", "ec2-user", "")
+	runConsulConnectTest(t, "amazon-linux-2-ami", "examples/example-with-consul-connect", "../examples/consul-ami/consul.json", "ec2-user")
 }
 */
diff --git a/test/consul_connect_tests.go b/test/consul_connect_tests.go
new file mode 100644
index 00000000..824ae3a5
--- /dev/null
+++ b/test/consul_connect_tests.go
@@ -0,0 +1,214 @@
+package test
+
+import (
+	"errors"
+	"fmt"
+	"strings"
+	"testing"
+	"time"
+	"github.com/gruntwork-io/terratest/modules/aws"
+	"github.com/gruntwork-io/terratest/modules/logger"
+	"github.com/gruntwork-io/terratest/modules/random"
+	"github.com/gruntwork-io/terratest/modules/retry"
+	"github.com/gruntwork-io/terratest/modules/ssh"
+	"github.com/gruntwork-io/terratest/modules/terraform"
+	test_structure "github.com/gruntwork-io/terratest/modules/test-structure"
+	"github.com/hashicorp/consul/api"
+)
+
+const REPO_ROOT = "../"
+const CONSUL_CLUSTER_EXAMPLE_VAR_AMI_ID = "ami_id"
+const CONSUL_CLUSTER_EXAMPLE_VAR_SSH_KEY_NAME = "ssh_key_name"
+const CONSUL_CLUSTER_EXAMPLE_VAR_CLUSTER_NAME = "cluster_name"
+const CONSUL_CLUSTER_EXAMPLE_VAR_NUM_SERVERS = "num_servers"
+const CONSUL_CLUSTER_EXAMPLE_VAR_NUM_CLIENTS = "num_clients"
+
+const CONSUL_CLUSTER_EXAMPLE_DEFAULT_NUM_SERVERS = 3
+const CONSUL_CLUSTER_EXAMPLE_DEFAULT_NUM_CLIENTS = 6
+
+const CONSUL_CLUSTER_EXAMPLE_OUTPUT_SERVER_ASG_NAME = "asg_name_servers"
+const CONSUL_CLUSTER_EXAMPLE_OUTPUT_CLIENT_ASG_NAME = "asg_name_clients"
+
+const SAVED_AWS_REGION = "AwsRegion"
+
+const AWS_DEFAULT_REGION_ENV_VAR = "AWS_DEFAULT_REGION"
+
+// Test the consul-cluster example by:
+//
+// 1. Copying the code in this repo to a temp folder so tests on the Terraform code can run in parallel without the
+//    state files overwriting each other.
+// 2. Building the AMI in the consul-ami example with the given build name
+// 3. Deploying that AMI using the consul-cluster Terraform code
+// 4. Checking that the Consul cluster comes up within a reasonable time period and can respond to requests
+func runConsulConnectTest(t *testing.T, packerBuildName string, examplesFolder string, packerTemplatePath string, sshUser string) {
+	runConsulConnectTestWithVars(t,
+		packerBuildName,
+		examplesFolder,
+		packerTemplatePath,
+		sshUser,
+		map[string]interface{}{})
+}
+
+func runConsulConnectTestWithVars(t *testing.T, packerBuildName string, examplesFolder string, packerTemplatePath string, sshUser string, terraformVarsMerge map[string]interface{}) {
+	// Uncomment any of the following to skip that section during the test
+	//os.Setenv("SKIP_setup_ami", "true")
+	//os.Setenv("SKIP_deploy", "true")
+	//os.Setenv("SKIP_validate", "true")
+	//os.Setenv("SKIP_teardown", "true")
+
+	exampleFolder := test_structure.CopyTerraformFolderToTemp(t, REPO_ROOT, examplesFolder)
+
+	test_structure.RunTestStage(t, "setup_ami", func() {
+		awsRegion := aws.GetRandomRegion(t, nil, []string{"eu-north-1"})
+		test_structure.SaveString(t, exampleFolder, SAVED_AWS_REGION, awsRegion)
+
+		amiId := buildAmi(t, packerTemplatePath, packerBuildName, awsRegion)
+		test_structure.SaveAmiId(t, exampleFolder, amiId)
+	})
+
+	defer test_structure.RunTestStage(t, "teardown", func() {
+		terraformOptions := test_structure.LoadTerraformOptions(t, exampleFolder)
+		terraform.Destroy(t, terraformOptions)
+
+		keyPair := test_structure.LoadEc2KeyPair(t, exampleFolder)
+		aws.DeleteEC2KeyPair(t, keyPair)
+
+		amiId := test_structure.LoadAmiId(t, exampleFolder)
+		awsRegion := test_structure.LoadString(t, exampleFolder, SAVED_AWS_REGION)
+		aws.DeleteAmi(t, awsRegion, amiId)
+	})
+
+	test_structure.RunTestStage(t, "deploy", func() {
+		uniqueId := random.UniqueId()
+		awsRegion := test_structure.LoadString(t, exampleFolder, SAVED_AWS_REGION)
+		amiId := test_structure.LoadAmiId(t, exampleFolder)
+
+		keyPair := aws.CreateAndImportEC2KeyPair(t, awsRegion, uniqueId)
+		test_structure.SaveEc2KeyPair(t, exampleFolder, keyPair)
+
+		terraformVars := map[string]interface{}{
+			CONSUL_CLUSTER_EXAMPLE_VAR_CLUSTER_NAME: uniqueId,
+			CONSUL_CLUSTER_EXAMPLE_VAR_NUM_SERVERS:  CONSUL_CLUSTER_EXAMPLE_DEFAULT_NUM_SERVERS,
+			CONSUL_CLUSTER_EXAMPLE_VAR_NUM_CLIENTS:  CONSUL_CLUSTER_EXAMPLE_DEFAULT_NUM_CLIENTS,
+			CONSUL_CLUSTER_EXAMPLE_VAR_AMI_ID:       amiId,
+			CONSUL_CLUSTER_EXAMPLE_VAR_SSH_KEY_NAME: keyPair.Name,
+		}
+
+		for k, v := range terraformVarsMerge {
+			terraformVars[k] = v
+		}
+
+		terraformOptions := &terraform.Options{
+			TerraformDir: exampleFolder,
+			Vars:         terraformVars,
+			EnvVars: map[string]string{
+				AWS_DEFAULT_REGION_ENV_VAR: awsRegion,
+			},
+		}
+		test_structure.SaveTerraformOptions(t, exampleFolder, terraformOptions)
+
+		terraform.InitAndApply(t, terraformOptions)
+	})
+
+	test_structure.RunTestStage(t, "validate", func() {
+		awsRegion := test_structure.LoadString(t, exampleFolder, SAVED_AWS_REGION)
+		terraformOptions := test_structure.LoadTerraformOptions(t, exampleFolder)
+		keyPair := test_structure.LoadEc2KeyPair(t, exampleFolder)
+
+		// Check the Consul servers
+		checkConsulClusterIsWorking(t, CONSUL_CLUSTER_EXAMPLE_OUTPUT_SERVER_ASG_NAME, terraformOptions, awsRegion)
+
+		// Check the Consul clients
+		checkConsulClusterIsWorking(t, CONSUL_CLUSTER_EXAMPLE_OUTPUT_CLIENT_ASG_NAME, terraformOptions, awsRegion)
+		
+		// Check the Consul CA
+		checkConsulCA(t, CONSUL_CLUSTER_EXAMPLE_OUTPUT_SERVER_ASG_NAME, terraformOptions, awsRegion, sshUser, keyPair)
+	})
+}
+
+// Check that the Consul cluster comes up within a reasonable time period and can respond to requests
+func checkConsulClusterIsWorking(t *testing.T, asgNameOutputVar string, terratestOptions *terraform.Options, awsRegion string) {
+	asgName := terraform.OutputRequired(t, terratestOptions, asgNameOutputVar)
+	nodeIpAddress := getIpAddressOfAsgInstance(t, asgName, awsRegion)
+	testConsulCluster(t, nodeIpAddress)
+}
+
+// Use a Consul client to connect to the given node and use it to verify that:
+//
+// 1. The Consul cluster has deployed
+// 2. The cluster has the expected number of members
+// 3. The cluster has elected a leader
+func testConsulCluster(t *testing.T, nodeIpAddress string) {
+	consulClient := createConsulClient(t, nodeIpAddress)
+	maxRetries := 60
+	sleepBetweenRetries := 10 * time.Second
+	expectedMembers := CONSUL_CLUSTER_EXAMPLE_DEFAULT_NUM_CLIENTS + CONSUL_CLUSTER_EXAMPLE_DEFAULT_NUM_SERVERS
+
+	leader := retry.DoWithRetry(t, "Check Consul members", maxRetries, sleepBetweenRetries, func() (string, error) {
+		members, err := consulClient.Agent().Members(false)
+		if err != nil {
+			return "", err
+		}
+
+		if len(members) != expectedMembers {
+			return "", fmt.Errorf("Expected the cluster to have %d members, but found %d", expectedMembers, len(members))
+		}
+
+		leader, err := consulClient.Status().Leader()
+		if err != nil {
+			return "", err
+		}
+
+		if leader == "" {
+			return "", errors.New("Consul cluster returned an empty leader response, so a leader must not have been elected yet.")
+		}
+
+		return leader, nil
+	})
+
+	logger.Logf(t, "Consul cluster is properly deployed and has elected leader %s", leader)
+}
+
+// Create a Consul client
+func createConsulClient(t *testing.T, ipAddress string) *api.Client {
+	config := api.DefaultConfig()
+	config.Address = fmt.Sprintf("%s:8500", ipAddress)
+
+	client, err := api.NewClient(config)
+	if err != nil {
+		t.Fatalf("Failed to create Consul client due to error: %v", err)
+	}
+
+	config.HttpClient.Timeout = 5 * time.Second
+
+	return client
+}
+
+
+func checkConsulCA(t *testing.T, asgNameOutputVar string, terratestOptions *terraform.Options, awsRegion string, sshUser string, keyPair *aws.Ec2Keypair) {
+	asgName := terraform.OutputRequired(t, terratestOptions, asgNameOutputVar)
+	nodeIpAddress := getIpAddressOfAsgInstance(t, asgName, awsRegion)
+	
+	host := ssh.Host{
+		Hostname:    nodeIpAddress,
+		SshUserName: sshUser,
+		SshKeyPair:  keyPair.KeyPair,
+	}
+
+	maxRetries := 10
+	sleepBetweenRetries := 10 * time.Second
+	
+	output := retry.DoWithRetry(t, "Check Consul Built-in Certificate Authority", maxRetries, sleepBetweenRetries, func() (string, error) {
+		out, err := ssh.CheckSshCommandE(t, host, "consul connect ca get-config")
+		if err != nil {
+			return "", fmt.Errorf("Error running consul command: %s\n", err)
+		}
+
+		return out, nil
+	})
+
+	if !strings.Contains(output, "Config") {
+		t.Fatalf("Consul CA does not have a Config\n")
+	}
+}
+

From 05fa6ed2e693cbe746d18091b6f5b01e017897f9 Mon Sep 17 00:00:00 2001
From: Nirmal Thacker <nirmalthacker@gmail.com>
Date: Thu, 14 May 2020 15:15:38 -0700
Subject: [PATCH 11/31] I think this is a good first refactor to tease out the
 connect tests. can be better

---
 test/consul_connect_tests.go | 79 +-----------------------------------
 test/consul_helpers.go       | 29 -------------
 2 files changed, 1 insertion(+), 107 deletions(-)

diff --git a/test/consul_connect_tests.go b/test/consul_connect_tests.go
index 824ae3a5..3735d537 100644
--- a/test/consul_connect_tests.go
+++ b/test/consul_connect_tests.go
@@ -1,37 +1,19 @@
 package test
 
 import (
-	"errors"
 	"fmt"
 	"strings"
 	"testing"
 	"time"
 	"github.com/gruntwork-io/terratest/modules/aws"
-	"github.com/gruntwork-io/terratest/modules/logger"
 	"github.com/gruntwork-io/terratest/modules/random"
 	"github.com/gruntwork-io/terratest/modules/retry"
 	"github.com/gruntwork-io/terratest/modules/ssh"
 	"github.com/gruntwork-io/terratest/modules/terraform"
 	test_structure "github.com/gruntwork-io/terratest/modules/test-structure"
-	"github.com/hashicorp/consul/api"
 )
 
-const REPO_ROOT = "../"
-const CONSUL_CLUSTER_EXAMPLE_VAR_AMI_ID = "ami_id"
-const CONSUL_CLUSTER_EXAMPLE_VAR_SSH_KEY_NAME = "ssh_key_name"
-const CONSUL_CLUSTER_EXAMPLE_VAR_CLUSTER_NAME = "cluster_name"
-const CONSUL_CLUSTER_EXAMPLE_VAR_NUM_SERVERS = "num_servers"
-const CONSUL_CLUSTER_EXAMPLE_VAR_NUM_CLIENTS = "num_clients"
 
-const CONSUL_CLUSTER_EXAMPLE_DEFAULT_NUM_SERVERS = 3
-const CONSUL_CLUSTER_EXAMPLE_DEFAULT_NUM_CLIENTS = 6
-
-const CONSUL_CLUSTER_EXAMPLE_OUTPUT_SERVER_ASG_NAME = "asg_name_servers"
-const CONSUL_CLUSTER_EXAMPLE_OUTPUT_CLIENT_ASG_NAME = "asg_name_clients"
-
-const SAVED_AWS_REGION = "AwsRegion"
-
-const AWS_DEFAULT_REGION_ENV_VAR = "AWS_DEFAULT_REGION"
 
 // Test the consul-cluster example by:
 //
@@ -62,7 +44,7 @@ func runConsulConnectTestWithVars(t *testing.T, packerBuildName string, examples
 		awsRegion := aws.GetRandomRegion(t, nil, []string{"eu-north-1"})
 		test_structure.SaveString(t, exampleFolder, SAVED_AWS_REGION, awsRegion)
 
-		amiId := buildAmi(t, packerTemplatePath, packerBuildName, awsRegion)
+		amiId := buildAmi(t, packerTemplatePath, packerBuildName, awsRegion, "")
 		test_structure.SaveAmiId(t, exampleFolder, amiId)
 	})
 
@@ -126,65 +108,6 @@ func runConsulConnectTestWithVars(t *testing.T, packerBuildName string, examples
 	})
 }
 
-// Check that the Consul cluster comes up within a reasonable time period and can respond to requests
-func checkConsulClusterIsWorking(t *testing.T, asgNameOutputVar string, terratestOptions *terraform.Options, awsRegion string) {
-	asgName := terraform.OutputRequired(t, terratestOptions, asgNameOutputVar)
-	nodeIpAddress := getIpAddressOfAsgInstance(t, asgName, awsRegion)
-	testConsulCluster(t, nodeIpAddress)
-}
-
-// Use a Consul client to connect to the given node and use it to verify that:
-//
-// 1. The Consul cluster has deployed
-// 2. The cluster has the expected number of members
-// 3. The cluster has elected a leader
-func testConsulCluster(t *testing.T, nodeIpAddress string) {
-	consulClient := createConsulClient(t, nodeIpAddress)
-	maxRetries := 60
-	sleepBetweenRetries := 10 * time.Second
-	expectedMembers := CONSUL_CLUSTER_EXAMPLE_DEFAULT_NUM_CLIENTS + CONSUL_CLUSTER_EXAMPLE_DEFAULT_NUM_SERVERS
-
-	leader := retry.DoWithRetry(t, "Check Consul members", maxRetries, sleepBetweenRetries, func() (string, error) {
-		members, err := consulClient.Agent().Members(false)
-		if err != nil {
-			return "", err
-		}
-
-		if len(members) != expectedMembers {
-			return "", fmt.Errorf("Expected the cluster to have %d members, but found %d", expectedMembers, len(members))
-		}
-
-		leader, err := consulClient.Status().Leader()
-		if err != nil {
-			return "", err
-		}
-
-		if leader == "" {
-			return "", errors.New("Consul cluster returned an empty leader response, so a leader must not have been elected yet.")
-		}
-
-		return leader, nil
-	})
-
-	logger.Logf(t, "Consul cluster is properly deployed and has elected leader %s", leader)
-}
-
-// Create a Consul client
-func createConsulClient(t *testing.T, ipAddress string) *api.Client {
-	config := api.DefaultConfig()
-	config.Address = fmt.Sprintf("%s:8500", ipAddress)
-
-	client, err := api.NewClient(config)
-	if err != nil {
-		t.Fatalf("Failed to create Consul client due to error: %v", err)
-	}
-
-	config.HttpClient.Timeout = 5 * time.Second
-
-	return client
-}
-
-
 func checkConsulCA(t *testing.T, asgNameOutputVar string, terratestOptions *terraform.Options, awsRegion string, sshUser string, keyPair *aws.Ec2Keypair) {
 	asgName := terraform.OutputRequired(t, terratestOptions, asgNameOutputVar)
 	nodeIpAddress := getIpAddressOfAsgInstance(t, asgName, awsRegion)
diff --git a/test/consul_helpers.go b/test/consul_helpers.go
index 98e53e66..8f7ddf74 100644
--- a/test/consul_helpers.go
+++ b/test/consul_helpers.go
@@ -215,32 +215,3 @@ func checkEnterpriseInstall(t *testing.T, asgNameOutputVar string, terratestOpti
 		t.Fatalf("This consul package is not the enterprise version.\n")
 	}
 }
-
-
-func checkConsulCA(t *testing.T, asgNameOutputVar string, terratestOptions *terraform.Options, awsRegion string, sshUser string, keyPair *aws.Ec2Keypair) {
-	asgName := terraform.OutputRequired(t, terratestOptions, asgNameOutputVar)
-	nodeIpAddress := getIpAddressOfAsgInstance(t, asgName, awsRegion)
-	
-	host := ssh.Host{
-		Hostname:    nodeIpAddress,
-		SshUserName: sshUser,
-		SshKeyPair:  keyPair.KeyPair,
-	}
-
-	maxRetries := 10
-	sleepBetweenRetries := 10 * time.Second
-	
-	output := retry.DoWithRetry(t, "Check Consul Built-in Certificate Authority", maxRetries, sleepBetweenRetries, func() (string, error) {
-		out, err := ssh.CheckSshCommandE(t, host, "consul connect ca get-config")
-		if err != nil {
-			return "", fmt.Errorf("Error running consul command: %s\n", err)
-		}
-
-		return out, nil
-	})
-
-	if !strings.Contains(output, "Config") {
-		t.Fatalf("Consul CA does not have a Config\n")
-	}
-}
-

From 042ec0ac4e30f47828fb162226a05d71e9f62da1 Mon Sep 17 00:00:00 2001
From: Nirmal Thacker <nirmalthacker@gmail.com>
Date: Thu, 14 May 2020 15:19:57 -0700
Subject: [PATCH 12/31] clean up names

---
 modules/run-consul/README.md                       | 14 +++++++++++++-
 ..._connect_tests.go => consul_connect_helpers.go} |  0
 test/consul_helpers.go                             |  5 +----
 3 files changed, 14 insertions(+), 5 deletions(-)
 rename test/{consul_connect_tests.go => consul_connect_helpers.go} (100%)

diff --git a/modules/run-consul/README.md b/modules/run-consul/README.md
index 347082fa..ddd58846 100644
--- a/modules/run-consul/README.md
+++ b/modules/run-consul/README.md
@@ -278,4 +278,16 @@ track other servers. A server is considered healthy when:
 There are Autopilot settings called [upgrade migrations](https://www.consul.io/docs/guides/autopilot.html#upgrade-migrations)
 that are useful when adding new members to the cluster either with newer configurations or using
 newer versions of Consul. These configurations manage how Consul will promote new servers and demote
-old ones. These settings, however, are only available at the Consul Enterprise version. 
\ No newline at end of file
+old ones. These settings, however, are only available at the Consul Enterprise version. 
+
+### Consul Connect
+[Consul Connect](https://www.consul.io/docs/connect) provides service-to-service connection authorization and encryption using mutual Transport Layer Security (TLS). 
+Applications can use sidecar proxies in a service mesh configuration to establish TLS connections for inbound and outbound connections. 
+Connect can help you secure your services and provide data about service-to-service communications.
+
+The following are supported in this Terraform module to enable Consul Connect in your environment:
+
+* Enabling Connect on cluster bootstrap
+* Specify a set of services with their sidecar proxies and upstream service dependences in a directory of config files
+* The `run-consul` script accepts the above and registers and turns on these services
+
diff --git a/test/consul_connect_tests.go b/test/consul_connect_helpers.go
similarity index 100%
rename from test/consul_connect_tests.go
rename to test/consul_connect_helpers.go
diff --git a/test/consul_helpers.go b/test/consul_helpers.go
index 8f7ddf74..eb94aaff 100644
--- a/test/consul_helpers.go
+++ b/test/consul_helpers.go
@@ -124,10 +124,7 @@ func runConsulClusterTestWithVars(t *testing.T, packerBuildName string, examples
 		checkConsulClusterIsWorking(t, CONSUL_CLUSTER_EXAMPLE_OUTPUT_SERVER_ASG_NAME, terraformOptions, awsRegion)
 
 		// Check the Consul clients
-		checkConsulClusterIsWorking(t, CONSUL_CLUSTER_EXAMPLE_OUTPUT_CLIENT_ASG_NAME, terraformOptions, awsRegion)
-		
-		// Check the Consul CA
-		checkConsulCA(t, CONSUL_CLUSTER_EXAMPLE_OUTPUT_SERVER_ASG_NAME, terraformOptions, awsRegion, sshUser, keyPair)
+		checkConsulClusterIsWorking(t, CONSUL_CLUSTER_EXAMPLE_OUTPUT_CLIENT_ASG_NAME, terraformOptions, awsRegion)		
 	})
 }
 

From 351283fed35e3151e325eaebd50655a3edcf8849 Mon Sep 17 00:00:00 2001
From: Nirmal Thacker <nirmalthacker@gmail.com>
Date: Thu, 14 May 2020 15:44:16 -0700
Subject: [PATCH 13/31] start 2 servies and their proxies in a user-data client

---
 .../user-data-client.sh                       | 42 ++++++++++++++++++-
 .../example-with-consul-connect/variables.tf  |  2 +-
 2 files changed, 42 insertions(+), 2 deletions(-)

diff --git a/examples/example-with-consul-connect/user-data-client.sh b/examples/example-with-consul-connect/user-data-client.sh
index fd0158b0..8a8111e4 100644
--- a/examples/example-with-consul-connect/user-data-client.sh
+++ b/examples/example-with-consul-connect/user-data-client.sh
@@ -12,4 +12,44 @@ exec > >(tee /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1
 # These variables are passed in via Terraform template interplation
 /opt/consul/bin/run-consul --client --cluster-tag-key "${cluster_tag_key}" --cluster-tag-value "${cluster_tag_value}"
 
-# You could add commands to boot your other apps here
\ No newline at end of file
+# Create service foo
+cat << 'EOF' >> /opt/consul/config/serv_foo.json
+{
+ "service": {
+    "name": "foo",
+    "port": 8181,
+    "connect": {
+      "sidecar_service": {}
+    }
+  }
+}
+EOF
+
+# Start a proxy sidecar for service foo
+nohup consul connect proxy -sidecar-for foo &>/dev/null &
+
+
+# Create service bar that is upstream to foo
+cat << 'EOF' >> /opt/consul/config/serv_bar.json
+{
+ "service": {
+    "name": "bar",
+    "port": 8080,
+    "connect": {
+      "sidecar_service": {
+        "proxy": {
+          "upstreams": [
+            {
+              "destination_name": "foo",
+              "local_bind_port": 9191
+            }
+          ]
+        }  
+      }
+    }
+  }
+}
+EOF
+
+# Start a proxy sidecar for service bar
+nohup consul connect proxy -sidecar-for bar &>/dev/null &
\ No newline at end of file
diff --git a/examples/example-with-consul-connect/variables.tf b/examples/example-with-consul-connect/variables.tf
index 6a43c172..f952b0e6 100644
--- a/examples/example-with-consul-connect/variables.tf
+++ b/examples/example-with-consul-connect/variables.tf
@@ -33,7 +33,7 @@ variable "num_servers" {
 variable "num_clients" {
   description = "The number of Consul client nodes to deploy. You typically run the Consul client alongside your apps, so set this value to however many Instances make sense for your app code."
   type        = number
-  default     = 6
+  default     = 1
 }
 
 variable "cluster_tag_key" {

From 4b618cab0cc15223df3a7e63dca079d36e261fb6 Mon Sep 17 00:00:00 2001
From: Nirmal Thacker <nirmalthacker@gmail.com>
Date: Thu, 14 May 2020 16:02:31 -0700
Subject: [PATCH 14/31] need to register services before starting the proxies

---
 .../example-with-consul-connect/user-data-client.sh   | 11 +++++++----
 examples/example-with-consul-connect/variables.tf     |  2 +-
 2 files changed, 8 insertions(+), 5 deletions(-)

diff --git a/examples/example-with-consul-connect/user-data-client.sh b/examples/example-with-consul-connect/user-data-client.sh
index 8a8111e4..d936deec 100644
--- a/examples/example-with-consul-connect/user-data-client.sh
+++ b/examples/example-with-consul-connect/user-data-client.sh
@@ -25,10 +25,6 @@ cat << 'EOF' >> /opt/consul/config/serv_foo.json
 }
 EOF
 
-# Start a proxy sidecar for service foo
-nohup consul connect proxy -sidecar-for foo &>/dev/null &
-
-
 # Create service bar that is upstream to foo
 cat << 'EOF' >> /opt/consul/config/serv_bar.json
 {
@@ -51,5 +47,12 @@ cat << 'EOF' >> /opt/consul/config/serv_bar.json
 }
 EOF
 
+# Register boths services foo & bar
+consul services register /opt/consul/config/serv_foo.json
+consul services register /opt/consul/config/serv_bar.json
+
+# Start a proxy sidecar for service foo
+nohup consul connect proxy -sidecar-for foo &>/dev/null &
+
 # Start a proxy sidecar for service bar
 nohup consul connect proxy -sidecar-for bar &>/dev/null &
\ No newline at end of file
diff --git a/examples/example-with-consul-connect/variables.tf b/examples/example-with-consul-connect/variables.tf
index f952b0e6..c72496d3 100644
--- a/examples/example-with-consul-connect/variables.tf
+++ b/examples/example-with-consul-connect/variables.tf
@@ -15,7 +15,7 @@
 variable "ami_id" {
   description = "The ID of the AMI to run in the cluster. This should be an AMI built from the Packer template under examples/consul-ami/consul.json. To keep this example simple, we run the same AMI on both server and client nodes, but in real-world usage, your client nodes would also run your apps. If the default value is used, Terraform will look up the latest AMI build automatically."
   type        = string
-  default     = "ami-0fce111d3bd9490e1"
+  default     = "ami-0935be9afc7b545a2"
 }
 
 variable "cluster_name" {

From aee822c0d2302acbf81c848c272d2a567bc13d7c Mon Sep 17 00:00:00 2001
From: Nirmal Thacker <nirmalthacker@gmail.com>
Date: Thu, 14 May 2020 16:28:18 -0700
Subject: [PATCH 15/31] addressing some comments in PR

---
 examples/example-with-consul-connect/variables.tf | 2 +-
 modules/run-consul/README.md                      | 2 +-
 test/consul_cluster_with_connect_test.go          | 6 ++----
 3 files changed, 4 insertions(+), 6 deletions(-)

diff --git a/examples/example-with-consul-connect/variables.tf b/examples/example-with-consul-connect/variables.tf
index c72496d3..2e659583 100644
--- a/examples/example-with-consul-connect/variables.tf
+++ b/examples/example-with-consul-connect/variables.tf
@@ -15,7 +15,7 @@
 variable "ami_id" {
   description = "The ID of the AMI to run in the cluster. This should be an AMI built from the Packer template under examples/consul-ami/consul.json. To keep this example simple, we run the same AMI on both server and client nodes, but in real-world usage, your client nodes would also run your apps. If the default value is used, Terraform will look up the latest AMI build automatically."
   type        = string
-  default     = "ami-0935be9afc7b545a2"
+  default     = "ami-0e88469641d5f2d24"
 }
 
 variable "cluster_name" {
diff --git a/modules/run-consul/README.md b/modules/run-consul/README.md
index ddd58846..bf1752b3 100644
--- a/modules/run-consul/README.md
+++ b/modules/run-consul/README.md
@@ -80,7 +80,7 @@ The `run-consul` script accepts the following arguments:
 * `ca-file-path` (optional): Path to the CA file used to verify outgoing connections. Must be specified with `enable-rpc-encryption`, `cert-file-path` and `key-file-path`.
 * `cert-file-path` (optional): Path to the certificate file used to verify incoming connections. Must be specified with `enable-rpc-encryption`, `ca-file-path`, and `key-file-path`.
 * `key-file-path` (optional): Path to the certificate key used to verify incoming connections. Must be specified with `enable-rpc-encryption`, `ca-file-path` and `cert-file-path`.
-* `enable-connect` (optional): If this flag is set, turn on Consul Connect when bootstrapping a cluster. To specify your own CA, specify an override config as outlined below.
+* `enable-connect` (optional): If this flag is set, turn on Consul Connect, when bootstrapping a cluster. Requires the server flag. To specify your own CA, specify an override config as outlined below.
 * `services-config-dir` (optional): Path to dir of one or many service configurations. Services can be further configured to set Consul Connect Proxies, Sidecar registrations & upstream service dependencies for a Service Mesh
 * `skip-consul-config` (optional): If this flag is set, don't generate a Consul configuration file. This is useful if
   you have a custom configuration file and don't want to use any of of the default settings from `run-consul`.
diff --git a/test/consul_cluster_with_connect_test.go b/test/consul_cluster_with_connect_test.go
index 3313cb7d..6e683b8a 100644
--- a/test/consul_cluster_with_connect_test.go
+++ b/test/consul_cluster_with_connect_test.go
@@ -4,12 +4,11 @@ import (
 	"testing"
 )
 
-/*
 // Test the example in the example-with-consul-connect folder
 func TestConsulClusterWithUbuntu16Ami(t *testing.T) {
 	t.Parallel()
 	runConsulConnectTest(t, "ubuntu16-ami", "examples/example-with-consul-connect", "../examples/consul-ami/consul.json", "ubuntu")
-}*/
+}
 
 // Test the example in the example-with-consul-connect folder
 func TestConsulConnectWithUbuntu18Ami(t *testing.T) {
@@ -17,10 +16,9 @@ func TestConsulConnectWithUbuntu18Ami(t *testing.T) {
 	runConsulConnectTest(t, "ubuntu18-ami", "examples/example-with-consul-connect", "../examples/consul-ami/consul.json", "ubuntu")
 }
 
-/*
 // Test the example in the example-with-consul-connect folder
 func TestConsulClusterWithAmazonLinuxAmi(t *testing.T) {
 	t.Parallel()
 	runConsulConnectTest(t, "amazon-linux-2-ami", "examples/example-with-consul-connect", "../examples/consul-ami/consul.json", "ec2-user")
 }
-*/
+

From 4bf413289f4479aa5ae589397e9f5bd768765bb7 Mon Sep 17 00:00:00 2001
From: Nirmal Thacker <nirmalthacker@gmail.com>
Date: Thu, 14 May 2020 16:40:28 -0700
Subject: [PATCH 16/31] Updated the readme with production notes

---
 modules/run-consul/README.md | 16 +++++++++++-----
 1 file changed, 11 insertions(+), 5 deletions(-)

diff --git a/modules/run-consul/README.md b/modules/run-consul/README.md
index bf1752b3..7002631d 100644
--- a/modules/run-consul/README.md
+++ b/modules/run-consul/README.md
@@ -81,7 +81,6 @@ The `run-consul` script accepts the following arguments:
 * `cert-file-path` (optional): Path to the certificate file used to verify incoming connections. Must be specified with `enable-rpc-encryption`, `ca-file-path`, and `key-file-path`.
 * `key-file-path` (optional): Path to the certificate key used to verify incoming connections. Must be specified with `enable-rpc-encryption`, `ca-file-path` and `cert-file-path`.
 * `enable-connect` (optional): If this flag is set, turn on Consul Connect, when bootstrapping a cluster. Requires the server flag. To specify your own CA, specify an override config as outlined below.
-* `services-config-dir` (optional): Path to dir of one or many service configurations. Services can be further configured to set Consul Connect Proxies, Sidecar registrations & upstream service dependencies for a Service Mesh
 * `skip-consul-config` (optional): If this flag is set, don't generate a Consul configuration file. This is useful if
   you have a custom configuration file and don't want to use any of of the default settings from `run-consul`.
 
@@ -285,9 +284,16 @@ old ones. These settings, however, are only available at the Consul Enterprise v
 Applications can use sidecar proxies in a service mesh configuration to establish TLS connections for inbound and outbound connections. 
 Connect can help you secure your services and provide data about service-to-service communications.
 
-The following are supported in this Terraform module to enable Consul Connect in your environment:
+#### Enabling Connect on cluster bootstrap. 
+Connect is enabled only on Consul servers, so your run-consul command must issue a server flag if it also issues a enable-connect flag
 
-* Enabling Connect on cluster bootstrap
-* Specify a set of services with their sidecar proxies and upstream service dependences in a directory of config files
-* The `run-consul` script accepts the above and registers and turns on these services
+#### Examples
+The examples/example-with-consul-connect directory shows a working Terraform implementation of deploying a Consul Cluster with 3 servers, 1 client, 2 Services with their sidecar proxies respectively where one service is an upstream dependent for the other
+
+To run Consul in production, ensure the following:
+* ACL's should be set to deny and RPC communications must be encrypted. [More information can be found here](https://learn.hashicorp.com/consul/developer-mesh/connect-production)
+* You can choose to deploy Vault as a CA. By default Consul will run an in-built CA. [More information on running your own CA can be found here](https://www.consul.io/docs/connect/ca)
+* [You can choose to use Envoy as a proxy](https://www.consul.io/docs/connect/proxies/envoy)
+
+For all of the above your Consul server configuration should override the default configuration as specified above in Section "Overriding the configuration"
 

From ea11497653f602d7bb1d8c4b00b33a39fa1bf83f Mon Sep 17 00:00:00 2001
From: Nirmal Thacker <nirmalthacker@gmail.com>
Date: Thu, 14 May 2020 16:48:28 -0700
Subject: [PATCH 17/31] clean up my keys/amis

---
 examples/example-with-consul-connect/README.md    | 4 ++--
 examples/example-with-consul-connect/variables.tf | 4 ++--
 test/consul_helpers.go                            | 2 +-
 variables.tf                                      | 4 ++--
 4 files changed, 7 insertions(+), 7 deletions(-)

diff --git a/examples/example-with-consul-connect/README.md b/examples/example-with-consul-connect/README.md
index 3e6bfd02..81d34422 100644
--- a/examples/example-with-consul-connect/README.md
+++ b/examples/example-with-consul-connect/README.md
@@ -1,8 +1,8 @@
 # Consul Cluster with Connect service mesh
 
 This folder shows an example of Terraform code that uses the [run-consul module](https://github.com/hashicorp/terraform-aws-consul/tree/master/modules/consul-cluster) to deploy
-a [Consul](https://www.consul.io/) cluster in [AWS](https://aws.amazon.com/) with the Consul Connect Service Mesh turned on. The cluster consists of three Services with
-side-proxies and Intentions that enable secure service mesh connections.
+a [Consul](https://www.consul.io/) cluster in [AWS](https://aws.amazon.com/) with the Consul Connect Service Mesh turned on. The cluster consists of 2 Services with
+side-proxies and upstream dependencies between them
 
 You will need to create an [Amazon Machine Image (AMI)](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html)
 that has Consul installed, which you can do using the [consul-ami example](https://github.com/hashicorp/terraform-aws-consul/tree/master/examples/consul-ami)). Note that to keep
diff --git a/examples/example-with-consul-connect/variables.tf b/examples/example-with-consul-connect/variables.tf
index 2e659583..e2714a49 100644
--- a/examples/example-with-consul-connect/variables.tf
+++ b/examples/example-with-consul-connect/variables.tf
@@ -15,7 +15,7 @@
 variable "ami_id" {
   description = "The ID of the AMI to run in the cluster. This should be an AMI built from the Packer template under examples/consul-ami/consul.json. To keep this example simple, we run the same AMI on both server and client nodes, but in real-world usage, your client nodes would also run your apps. If the default value is used, Terraform will look up the latest AMI build automatically."
   type        = string
-  default     = "ami-0e88469641d5f2d24"
+  default     = null
 }
 
 variable "cluster_name" {
@@ -45,7 +45,7 @@ variable "cluster_tag_key" {
 variable "ssh_key_name" {
   description = "The name of an EC2 Key Pair that can be used to SSH to the EC2 Instances in this cluster. Set to an empty string to not associate a Key Pair."
   type        = string
-  default     = "nt-trial"
+  default     = nt-trial
 }
 
 variable "vpc_id" {
diff --git a/test/consul_helpers.go b/test/consul_helpers.go
index eb94aaff..c1f31a25 100644
--- a/test/consul_helpers.go
+++ b/test/consul_helpers.go
@@ -124,7 +124,7 @@ func runConsulClusterTestWithVars(t *testing.T, packerBuildName string, examples
 		checkConsulClusterIsWorking(t, CONSUL_CLUSTER_EXAMPLE_OUTPUT_SERVER_ASG_NAME, terraformOptions, awsRegion)
 
 		// Check the Consul clients
-		checkConsulClusterIsWorking(t, CONSUL_CLUSTER_EXAMPLE_OUTPUT_CLIENT_ASG_NAME, terraformOptions, awsRegion)		
+		checkConsulClusterIsWorking(t, CONSUL_CLUSTER_EXAMPLE_OUTPUT_CLIENT_ASG_NAME, terraformOptions, awsRegion)
 	})
 }
 
diff --git a/variables.tf b/variables.tf
index 6a43c172..83821d9d 100644
--- a/variables.tf
+++ b/variables.tf
@@ -15,7 +15,7 @@
 variable "ami_id" {
   description = "The ID of the AMI to run in the cluster. This should be an AMI built from the Packer template under examples/consul-ami/consul.json. To keep this example simple, we run the same AMI on both server and client nodes, but in real-world usage, your client nodes would also run your apps. If the default value is used, Terraform will look up the latest AMI build automatically."
   type        = string
-  default     = "ami-0fce111d3bd9490e1"
+  default     = null
 }
 
 variable "cluster_name" {
@@ -45,7 +45,7 @@ variable "cluster_tag_key" {
 variable "ssh_key_name" {
   description = "The name of an EC2 Key Pair that can be used to SSH to the EC2 Instances in this cluster. Set to an empty string to not associate a Key Pair."
   type        = string
-  default     = "nt-trial"
+  default     = null
 }
 
 variable "vpc_id" {

From 6bb88de3fc9184775a4ee0a1fb64324b806b548b Mon Sep 17 00:00:00 2001
From: Nirmal Thacker <nirmalthacker@gmail.com>
Date: Thu, 14 May 2020 16:50:04 -0700
Subject: [PATCH 18/31] more cleanup

---
 test/consul_helpers.go | 1 +
 variables.tf           | 2 +-
 2 files changed, 2 insertions(+), 1 deletion(-)

diff --git a/test/consul_helpers.go b/test/consul_helpers.go
index c1f31a25..da283d18 100644
--- a/test/consul_helpers.go
+++ b/test/consul_helpers.go
@@ -6,6 +6,7 @@ import (
 	"strings"
 	"testing"
 	"time"
+
 	"github.com/gruntwork-io/terratest/modules/aws"
 	"github.com/gruntwork-io/terratest/modules/logger"
 	"github.com/gruntwork-io/terratest/modules/random"
diff --git a/variables.tf b/variables.tf
index 83821d9d..9c725019 100644
--- a/variables.tf
+++ b/variables.tf
@@ -58,4 +58,4 @@ variable "spot_price" {
   description = "The maximum hourly price to pay for EC2 Spot Instances."
   type        = number
   default     = null
-}
+}
\ No newline at end of file

From b80d7891493a107e411f6a007f97f3f463fafaa9 Mon Sep 17 00:00:00 2001
From: 7hacker <nirmalthacker@gmail.com>
Date: Thu, 14 May 2020 17:02:33 -0700
Subject: [PATCH 19/31] Update modules/run-consul/README.md

Co-authored-by: Yoriyasu Yano <430092+yorinasub17@users.noreply.github.com>
---
 modules/run-consul/README.md | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

diff --git a/modules/run-consul/README.md b/modules/run-consul/README.md
index 7002631d..01bc9039 100644
--- a/modules/run-consul/README.md
+++ b/modules/run-consul/README.md
@@ -285,7 +285,7 @@ Applications can use sidecar proxies in a service mesh configuration to establis
 Connect can help you secure your services and provide data about service-to-service communications.
 
 #### Enabling Connect on cluster bootstrap. 
-Connect is enabled only on Consul servers, so your run-consul command must issue a server flag if it also issues a enable-connect flag
+To enable Consul Connect on your servers, pass in the `--enable-connect` flag to the `run-consul` command used to start the consul service on the server.
 
 #### Examples
 The examples/example-with-consul-connect directory shows a working Terraform implementation of deploying a Consul Cluster with 3 servers, 1 client, 2 Services with their sidecar proxies respectively where one service is an upstream dependent for the other
@@ -296,4 +296,3 @@ To run Consul in production, ensure the following:
 * [You can choose to use Envoy as a proxy](https://www.consul.io/docs/connect/proxies/envoy)
 
 For all of the above your Consul server configuration should override the default configuration as specified above in Section "Overriding the configuration"
-

From 943b3ddeff27a2ac5f5cbb6177dcac13a130196c Mon Sep 17 00:00:00 2001
From: 7hacker <nirmalthacker@gmail.com>
Date: Thu, 14 May 2020 17:02:51 -0700
Subject: [PATCH 20/31] Update
 examples/example-with-consul-connect/user-data-client.sh

Co-authored-by: Yoriyasu Yano <430092+yorinasub17@users.noreply.github.com>
---
 examples/example-with-consul-connect/user-data-client.sh | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/examples/example-with-consul-connect/user-data-client.sh b/examples/example-with-consul-connect/user-data-client.sh
index d936deec..93c9b80e 100644
--- a/examples/example-with-consul-connect/user-data-client.sh
+++ b/examples/example-with-consul-connect/user-data-client.sh
@@ -47,7 +47,7 @@ cat << 'EOF' >> /opt/consul/config/serv_bar.json
 }
 EOF
 
-# Register boths services foo & bar
+# Register both services foo & bar
 consul services register /opt/consul/config/serv_foo.json
 consul services register /opt/consul/config/serv_bar.json
 
@@ -55,4 +55,4 @@ consul services register /opt/consul/config/serv_bar.json
 nohup consul connect proxy -sidecar-for foo &>/dev/null &
 
 # Start a proxy sidecar for service bar
-nohup consul connect proxy -sidecar-for bar &>/dev/null &
\ No newline at end of file
+nohup consul connect proxy -sidecar-for bar &>/dev/null &

From 4a3a9823476cd257887c27d334823c6c5a590fea Mon Sep 17 00:00:00 2001
From: Nirmal Thacker <nirmalthacker@gmail.com>
Date: Thu, 14 May 2020 17:08:11 -0700
Subject: [PATCH 21/31] added a paragraph on running services and proxies in
 the run-consul readme

---
 modules/run-consul/README.md | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/modules/run-consul/README.md b/modules/run-consul/README.md
index 01bc9039..6f5f1e67 100644
--- a/modules/run-consul/README.md
+++ b/modules/run-consul/README.md
@@ -287,6 +287,9 @@ Connect can help you secure your services and provide data about service-to-serv
 #### Enabling Connect on cluster bootstrap. 
 To enable Consul Connect on your servers, pass in the `--enable-connect` flag to the `run-consul` command used to start the consul service on the server.
 
+#### Declaring Services and Sidecar Proxies on cluster bootstrap. 
+A simple way to declare services and sidecar proxies is to include these in the user-data-client scripts that call run-consul. We have shown this in our example. A word of caution: if you have multiple Consul Clients this rudimentary approach will have the services and sidecar proxies duplicated on each client node.
+
 #### Examples
 The examples/example-with-consul-connect directory shows a working Terraform implementation of deploying a Consul Cluster with 3 servers, 1 client, 2 Services with their sidecar proxies respectively where one service is an upstream dependent for the other
 

From 6156505d7fecbaf9bc44b140eb4b967b72631e7d Mon Sep 17 00:00:00 2001
From: 7hacker <nirmalthacker@gmail.com>
Date: Fri, 15 May 2020 09:02:02 -0700
Subject: [PATCH 22/31] Update examples/example-with-consul-connect/main.tf

Co-authored-by: Yevgeniy Brikman <brikis98@users.noreply.github.com>
---
 examples/example-with-consul-connect/main.tf | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

diff --git a/examples/example-with-consul-connect/main.tf b/examples/example-with-consul-connect/main.tf
index b14ad1ed..28c6a1ce 100644
--- a/examples/example-with-consul-connect/main.tf
+++ b/examples/example-with-consul-connect/main.tf
@@ -21,7 +21,7 @@ terraform {
 # latest AMI so that a simple "terraform apply" will just work without the user needing to manually build an AMI and
 # fill in the right value.
 #
-# !! WARNING !! These exmaple AMIs are meant only convenience when initially testing this repo. Do NOT use these example
+# !! WARNING !! These example AMIs are meant only convenience when initially testing this repo. Do NOT use these example
 # AMIs in a production setting because it is important that you consciously think through the configuration you want
 # in your own production AMI.
 #
@@ -173,4 +173,3 @@ data "aws_subnet_ids" "default" {
 
 data "aws_region" "current" {
 }
-

From 7be86c127aba8c04849cfcc7a8ec0d0fb351aa83 Mon Sep 17 00:00:00 2001
From: 7hacker <nirmalthacker@gmail.com>
Date: Fri, 15 May 2020 09:02:16 -0700
Subject: [PATCH 23/31] Update examples/example-with-consul-connect/README.md

Co-authored-by: Yevgeniy Brikman <brikis98@users.noreply.github.com>
---
 examples/example-with-consul-connect/README.md | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/examples/example-with-consul-connect/README.md b/examples/example-with-consul-connect/README.md
index 81d34422..bc82d324 100644
--- a/examples/example-with-consul-connect/README.md
+++ b/examples/example-with-consul-connect/README.md
@@ -2,7 +2,7 @@
 
 This folder shows an example of Terraform code that uses the [run-consul module](https://github.com/hashicorp/terraform-aws-consul/tree/master/modules/consul-cluster) to deploy
 a [Consul](https://www.consul.io/) cluster in [AWS](https://aws.amazon.com/) with the Consul Connect Service Mesh turned on. The cluster consists of 2 Services with
-side-proxies and upstream dependencies between them
+side-proxies and upstream dependencies between them.
 
 You will need to create an [Amazon Machine Image (AMI)](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html)
 that has Consul installed, which you can do using the [consul-ami example](https://github.com/hashicorp/terraform-aws-consul/tree/master/examples/consul-ami)). Note that to keep

From ff16c3a2b24014d92df6598fb4e1acee9908f037 Mon Sep 17 00:00:00 2001
From: Matthias Scholz <matthias.scholz@thoughtworks.com>
Date: Tue, 12 Jan 2021 20:25:24 +0100
Subject: [PATCH 24/31] :recycle: making enable_connect local

---
 modules/run-consul/run-consul | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/modules/run-consul/run-consul b/modules/run-consul/run-consul
index 61f99a23..d8aef86d 100755
--- a/modules/run-consul/run-consul
+++ b/modules/run-consul/run-consul
@@ -235,6 +235,7 @@ function generate_consul_config {
   local -r redundancy_zone_tag="${18}"
   local -r disable_upgrade_migration="${19}"
   local -r upgrade_version_tag=${20}
+  local -r enable_connect="${21}"
   local -r config_path="$config_dir/$CONSUL_CONFIG_FILE"
 
   shift 20
@@ -456,6 +457,7 @@ function run {
   local server_stabilization_time="$DEFAULT_AUTOPILOT_SERVER_STABILIZATION_TIME"
   local redundancy_zone_tag="$DEFAULT_AUTOPILOT_REDUNDANCY_ZONE_TAG"
   local disable_upgrade_migration="$DEFAULT_AUTOPILOT_DISABLE_UPGRADE_MIGRATION"
+  local enable_connect="false"
 
   while [[ $# -gt 0 ]]; do
     local key="$1"
@@ -669,6 +671,7 @@ function run {
       "$redundancy_zone_tag" \
       "$disable_upgrade_migration" \
       "$upgrade_version_tag" \
+      "$enable_connect" \
       "${recursors[@]}"
   fi
 

From 494ec73e871d4a7a4aada26bf7b8e7463372cd2e Mon Sep 17 00:00:00 2001
From: Matthias Scholz <matthias.scholz@thoughtworks.com>
Date: Tue, 12 Jan 2021 20:33:34 +0100
Subject: [PATCH 25/31] :wastebasket: cleanup default ssh key

---
 examples/example-with-consul-connect/variables.tf | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/examples/example-with-consul-connect/variables.tf b/examples/example-with-consul-connect/variables.tf
index e2714a49..1c40f3c3 100644
--- a/examples/example-with-consul-connect/variables.tf
+++ b/examples/example-with-consul-connect/variables.tf
@@ -45,7 +45,7 @@ variable "cluster_tag_key" {
 variable "ssh_key_name" {
   description = "The name of an EC2 Key Pair that can be used to SSH to the EC2 Instances in this cluster. Set to an empty string to not associate a Key Pair."
   type        = string
-  default     = nt-trial
+  default     = null
 }
 
 variable "vpc_id" {

From d8dff713ed767334de8777353a944d0a6be2378c Mon Sep 17 00:00:00 2001
From: Matthias Scholz <matthias.scholz@thoughtworks.com>
Date: Tue, 12 Jan 2021 23:17:04 +0100
Subject: [PATCH 26/31] :recycle: complete tf 0.12 migration

---
 examples/example-with-consul-connect/main.tf    | 10 +++++-----
 examples/example-with-consul-connect/outputs.tf |  1 -
 main.tf                                         | 11 +++++------
 3 files changed, 10 insertions(+), 12 deletions(-)

diff --git a/examples/example-with-consul-connect/main.tf b/examples/example-with-consul-connect/main.tf
index 28c6a1ce..8ed26301 100644
--- a/examples/example-with-consul-connect/main.tf
+++ b/examples/example-with-consul-connect/main.tf
@@ -69,8 +69,8 @@ module "consul_servers" {
   cluster_tag_key   = var.cluster_tag_key
   cluster_tag_value = var.cluster_name
 
-  ami_id    = "${var.ami_id == null ? data.aws_ami.consul.image_id : var.ami_id}"
-  user_data = "${data.template_file.user_data_server.rendered}"
+  ami_id    = var.ami_id == null ? data.aws_ami.consul.image_id : var.ami_id
+  user_data = data.template_file.user_data_server.rendered
 
   vpc_id     = data.aws_vpc.default.id
   subnet_ids = data.aws_subnet_ids.default.ids
@@ -127,8 +127,8 @@ module "consul_clients" {
   cluster_tag_key   = "consul-clients"
   cluster_tag_value = var.cluster_name
 
-  ami_id    = "${var.ami_id == null ? data.aws_ami.consul.image_id : var.ami_id}"
-  user_data = "${data.template_file.user_data_client.rendered}"
+  ami_id    = var.ami_id == null ? data.aws_ami.consul.image_id : var.ami_id
+  user_data = data.template_file.user_data_client.rendered
 
   vpc_id     = data.aws_vpc.default.id
   subnet_ids = data.aws_subnet_ids.default.ids
@@ -164,7 +164,7 @@ data "template_file" "user_data_client" {
 
 data "aws_vpc" "default" {
   default = var.vpc_id == null ? true : false
-  id      = "${var.vpc_id}"
+  id      = var.vpc_id
 }
 
 data "aws_subnet_ids" "default" {
diff --git a/examples/example-with-consul-connect/outputs.tf b/examples/example-with-consul-connect/outputs.tf
index 347e1219..493b36c2 100644
--- a/examples/example-with-consul-connect/outputs.tf
+++ b/examples/example-with-consul-connect/outputs.tf
@@ -57,4 +57,3 @@ output "consul_servers_cluster_tag_key" {
 output "consul_servers_cluster_tag_value" {
   value = module.consul_servers.cluster_tag_value
 }
-
diff --git a/main.tf b/main.tf
index b2d1ef3d..ec118d88 100644
--- a/main.tf
+++ b/main.tf
@@ -71,8 +71,8 @@ module "consul_servers" {
   cluster_tag_key   = var.cluster_tag_key
   cluster_tag_value = var.cluster_name
 
-  ami_id    = "${var.ami_id == null ? data.aws_ami.consul.image_id : var.ami_id}"
-  user_data = "${data.template_file.user_data_server.rendered}"
+  ami_id    = var.ami_id == null ? data.aws_ami.consul.image_id : var.ami_id
+  user_data = data.template_file.user_data_server.rendered
 
   vpc_id     = data.aws_vpc.default.id
   subnet_ids = data.aws_subnet_ids.default.ids
@@ -131,8 +131,8 @@ module "consul_clients" {
   cluster_tag_key   = "consul-clients"
   cluster_tag_value = var.cluster_name
 
-  ami_id    = "${var.ami_id == null ? data.aws_ami.consul.image_id : var.ami_id}"
-  user_data = "${data.template_file.user_data_client.rendered}"
+  ami_id    = var.ami_id == null ? data.aws_ami.consul.image_id : var.ami_id
+  user_data = data.template_file.user_data_client.rendered
 
   vpc_id     = data.aws_vpc.default.id
   subnet_ids = data.aws_subnet_ids.default.ids
@@ -167,7 +167,7 @@ data "template_file" "user_data_client" {
 
 data "aws_vpc" "default" {
   default = var.vpc_id == null ? true : false
-  id      = "${var.vpc_id}"
+  id      = var.vpc_id
 }
 
 data "aws_subnet_ids" "default" {
@@ -176,4 +176,3 @@ data "aws_subnet_ids" "default" {
 
 data "aws_region" "current" {
 }
-

From 539b5211eeeba1b04228385f44facb45ccd5b257 Mon Sep 17 00:00:00 2001
From: Matthias Scholz <matthias.scholz@thoughtworks.com>
Date: Tue, 12 Jan 2021 23:18:17 +0100
Subject: [PATCH 27/31] :art: removed trailing space

---
 test/consul_connect_helpers.go | 7 +++----
 1 file changed, 3 insertions(+), 4 deletions(-)

diff --git a/test/consul_connect_helpers.go b/test/consul_connect_helpers.go
index 3735d537..f4f9c86b 100644
--- a/test/consul_connect_helpers.go
+++ b/test/consul_connect_helpers.go
@@ -102,7 +102,7 @@ func runConsulConnectTestWithVars(t *testing.T, packerBuildName string, examples
 
 		// Check the Consul clients
 		checkConsulClusterIsWorking(t, CONSUL_CLUSTER_EXAMPLE_OUTPUT_CLIENT_ASG_NAME, terraformOptions, awsRegion)
-		
+
 		// Check the Consul CA
 		checkConsulCA(t, CONSUL_CLUSTER_EXAMPLE_OUTPUT_SERVER_ASG_NAME, terraformOptions, awsRegion, sshUser, keyPair)
 	})
@@ -111,7 +111,7 @@ func runConsulConnectTestWithVars(t *testing.T, packerBuildName string, examples
 func checkConsulCA(t *testing.T, asgNameOutputVar string, terratestOptions *terraform.Options, awsRegion string, sshUser string, keyPair *aws.Ec2Keypair) {
 	asgName := terraform.OutputRequired(t, terratestOptions, asgNameOutputVar)
 	nodeIpAddress := getIpAddressOfAsgInstance(t, asgName, awsRegion)
-	
+
 	host := ssh.Host{
 		Hostname:    nodeIpAddress,
 		SshUserName: sshUser,
@@ -120,7 +120,7 @@ func checkConsulCA(t *testing.T, asgNameOutputVar string, terratestOptions *terr
 
 	maxRetries := 10
 	sleepBetweenRetries := 10 * time.Second
-	
+
 	output := retry.DoWithRetry(t, "Check Consul Built-in Certificate Authority", maxRetries, sleepBetweenRetries, func() (string, error) {
 		out, err := ssh.CheckSshCommandE(t, host, "consul connect ca get-config")
 		if err != nil {
@@ -134,4 +134,3 @@ func checkConsulCA(t *testing.T, asgNameOutputVar string, terratestOptions *terr
 		t.Fatalf("Consul CA does not have a Config\n")
 	}
 }
-

From 35b324c4361c44c1c7b08ae07798829b6a6b8dc8 Mon Sep 17 00:00:00 2001
From: Matthias Scholz <matthias.scholz@thoughtworks.com>
Date: Tue, 12 Jan 2021 23:19:43 +0100
Subject: [PATCH 28/31] :art: minor beautification

---
 examples/example-with-consul-connect/main.tf | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

diff --git a/examples/example-with-consul-connect/main.tf b/examples/example-with-consul-connect/main.tf
index 8ed26301..07a5401a 100644
--- a/examples/example-with-consul-connect/main.tf
+++ b/examples/example-with-consul-connect/main.tf
@@ -171,5 +171,4 @@ data "aws_subnet_ids" "default" {
   vpc_id = data.aws_vpc.default.id
 }
 
-data "aws_region" "current" {
-}
+data "aws_region" "current" {}

From a7c21e9e88ad484a17671d5beebf074ef541f978 Mon Sep 17 00:00:00 2001
From: Matthias Scholz <matthias.scholz@thoughtworks.com>
Date: Tue, 12 Jan 2021 23:20:04 +0100
Subject: [PATCH 29/31] :bug: copy and paste error - test naming

---
 test/consul_cluster_with_connect_test.go | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/test/consul_cluster_with_connect_test.go b/test/consul_cluster_with_connect_test.go
index 6e683b8a..1bf2a047 100644
--- a/test/consul_cluster_with_connect_test.go
+++ b/test/consul_cluster_with_connect_test.go
@@ -5,7 +5,7 @@ import (
 )
 
 // Test the example in the example-with-consul-connect folder
-func TestConsulClusterWithUbuntu16Ami(t *testing.T) {
+func TestConsulConnectWithUbuntu16Ami(t *testing.T) {
 	t.Parallel()
 	runConsulConnectTest(t, "ubuntu16-ami", "examples/example-with-consul-connect", "../examples/consul-ami/consul.json", "ubuntu")
 }
@@ -17,7 +17,7 @@ func TestConsulConnectWithUbuntu18Ami(t *testing.T) {
 }
 
 // Test the example in the example-with-consul-connect folder
-func TestConsulClusterWithAmazonLinuxAmi(t *testing.T) {
+func TestConsulConnectWithAmazonLinuxAmi(t *testing.T) {
 	t.Parallel()
 	runConsulConnectTest(t, "amazon-linux-2-ami", "examples/example-with-consul-connect", "../examples/consul-ami/consul.json", "ec2-user")
 }

From a4295b8c3580e100396960fd2e673df21b9d8385 Mon Sep 17 00:00:00 2001
From: Matthias Scholz <matthias.scholz@thoughtworks.com>
Date: Sat, 17 Apr 2021 19:21:19 +0200
Subject: [PATCH 30/31] :white_check_mark: test consul connect configuration
 creation

---
 modules/run-consul/run-consul        |   7 +-
 test/run-consul/test_run-consul.bats | 124 +++++++++++++++++++++++++++
 2 files changed, 129 insertions(+), 2 deletions(-)
 create mode 100644 test/run-consul/test_run-consul.bats

diff --git a/modules/run-consul/run-consul b/modules/run-consul/run-consul
index d8aef86d..44353e3e 100755
--- a/modules/run-consul/run-consul
+++ b/modules/run-consul/run-consul
@@ -428,7 +428,7 @@ function get_owner_of_path {
   ls -ld "$path" | awk '{print $3}'
 }
 
-function run {
+function execute {
   local server="false"
   local client="false"
   local config_dir=""
@@ -679,4 +679,7 @@ function run {
   start_consul
 }
 
-run "$@"
+# Support sourcing of this script
+if [ "$0" = "$BASH_SOURCE" ] ; then
+    execute "$@"
+fi
diff --git a/test/run-consul/test_run-consul.bats b/test/run-consul/test_run-consul.bats
new file mode 100644
index 00000000..ff847e4d
--- /dev/null
+++ b/test/run-consul/test_run-consul.bats
@@ -0,0 +1,124 @@
+#!/usr/bin/env bats
+# Execute via: `bats --tap test_run-consul.bats`
+
+command -v brew >/dev/null 2>&1 || ENVIRONMENT_LOCAL=false
+if [[ "${ENVIRONMENT_LOCAL}" == "false" ]]; then
+    load "/test/test_helper/bats-support/load.bash"
+    load "/test/test_helper/bats-assert/load.bash"
+    load "/test/test_helper/bats-file/load.bash"
+else
+    TEST_BREW_PREFIX="$(brew --prefix)"
+    load "${TEST_BREW_PREFIX}/lib/bats-support/load.bash"
+    load "${TEST_BREW_PREFIX}/lib/bats-assert/load.bash"
+    load "${TEST_BREW_PREFIX}/lib/bats-file/load.bash"
+fi
+
+readonly RUN_CONSUL="${BATS_CWD}/../../modules/run-consul/run-consul"
+readonly TEST_DIR_BASE="${BATS_TMPDIR}"
+readonly CONSUL_CONFIG="${TEST_DIR_BASE}/default.json"
+
+setup_mocks() {
+    # It is important to source the tested script or library
+    # before the function is stubbed or mocked.
+    # shellcheck source=../../modules/run-consul/run-consul
+    source "${RUN_CONSUL}"
+
+    function chown() { echo "chown: mocked, but unneeded."; }
+    export -f chown
+
+    function sudo() { echo "sudo: mocked, but unneeded."; }
+    export -f sudo
+
+    function systemctl() { echo "systemctl: mocked, but unneeded."; }
+    export -f systemctl
+
+    function lookup_path_in_instance_metadata() { echo "lookup_path_in_instance_metadata: mocked, but unneeded.";}
+    export -f lookup_path_in_instance_metadata
+
+    function get_instance_tags() { echo "get_instance_tags: mocked, but unneeded."; }
+    export -f get_instance_tags
+
+    function get_instance_region() { echo "get_instance_region: mocked, but unneeded."; }
+    export -f get_instance_region
+}
+
+call_generate_consul_config() {
+    local -r server="true"
+    local -r config_dir="${TEST_DIR_BASE}"
+    local -r enable_connect="${1}"
+
+    generate_consul_config \
+       "${server}" \
+       "${config_dir}" \
+       "test" "test" "test" "test" "test" "test" "test" "test" \
+       "test" "test" "test" 0 "test" 0 "test" "test" 0 "test" \
+       "${enable_connect}"
+}
+
+@test "Consul Connect: activated" {
+    # Prepare
+    setup_mocks
+
+    # Execute
+    run execute --config-dir "${TEST_DIR_BASE}" --server --cluster-tag-key "test" --cluster-tag-value "test" --enable-connect
+
+    # Verify
+    assert_success
+    assert_file_exist "${CONSUL_CONFIG}"
+    run awk '/connect/,/}/' "${CONSUL_CONFIG}"
+    assert_success
+    assert_output --partial "connect"
+    assert_output --partial "enabled"
+    assert_output --partial "true"
+}
+
+@test "Consul Connect: deactivated" {
+    # Prepare
+    setup_mocks
+
+    # Execute
+    run execute --config-dir "${TEST_DIR_BASE}" --server --cluster-tag-key "test" --cluster-tag-value "test"
+
+    # Verify
+    assert_success
+    assert_file_exist "${CONSUL_CONFIG}"
+    run awk '/connect/,/}/' "${CONSUL_CONFIG}"
+    assert_success
+    refute_output --partial "connect"
+    refute_output --partial "enabled"
+    refute_output --partial "true"
+}
+
+@test "Consul Connect Configuration Generation: activated" {
+    # Prepare
+    setup_mocks
+
+    # Execute
+    run call_generate_consul_config "true"
+
+    # Verify
+    assert_success
+    assert_file_exist "${CONSUL_CONFIG}"
+    run awk '/connect/,/}/' "${CONSUL_CONFIG}"
+    assert_success
+    assert_output --partial "connect"
+    assert_output --partial "enabled"
+    assert_output --partial "true"
+}
+
+@test "Consul Connect Configuration Generation: deactivated" {
+    # Prepare
+    setup_mocks
+
+    # Execute
+    run call_generate_consul_config
+
+    # Verify
+    assert_success
+    assert_file_exist "${CONSUL_CONFIG}"
+    run awk '/connect/,/}/' "${CONSUL_CONFIG}"
+    assert_success
+    refute_output --partial "connect"
+    refute_output --partial "enabled"
+    refute_output --partial "true"
+}

From 8c9759139437d1be8cdc854cbe3b18cdec1163fb Mon Sep 17 00:00:00 2001
From: Matthias Scholz <matthias.scholz@thoughtworks.com>
Date: Sun, 18 Apr 2021 22:13:34 +0200
Subject: [PATCH 31/31] :bug: missing parameter shifting

---
 modules/run-consul/run-consul        |  2 +-
 test/run-consul/test_run-consul.bats | 21 +++++++++++++++++++++
 2 files changed, 22 insertions(+), 1 deletion(-)

diff --git a/modules/run-consul/run-consul b/modules/run-consul/run-consul
index 4297b99f..e5696202 100755
--- a/modules/run-consul/run-consul
+++ b/modules/run-consul/run-consul
@@ -238,7 +238,7 @@ function generate_consul_config {
   local -r enable_connect="${21}"
   local -r config_path="$config_dir/$CONSUL_CONFIG_FILE"
 
-  shift 20
+  shift 21
   local -r recursors=("$@")
 
   local instance_id=""
diff --git a/test/run-consul/test_run-consul.bats b/test/run-consul/test_run-consul.bats
index ff847e4d..f19a7b19 100644
--- a/test/run-consul/test_run-consul.bats
+++ b/test/run-consul/test_run-consul.bats
@@ -55,6 +55,7 @@ call_generate_consul_config() {
        "${enable_connect}"
 }
 
+
 @test "Consul Connect: activated" {
     # Prepare
     setup_mocks
@@ -70,6 +71,11 @@ call_generate_consul_config() {
     assert_output --partial "connect"
     assert_output --partial "enabled"
     assert_output --partial "true"
+
+    # recursors should be unset - command which follows enable-connect
+    run awk '/recursors/,/}/' "${CONSUL_CONFIG}"
+    assert_success
+    refute_output --partial "recursors"
 }
 
 @test "Consul Connect: deactivated" {
@@ -87,6 +93,11 @@ call_generate_consul_config() {
     refute_output --partial "connect"
     refute_output --partial "enabled"
     refute_output --partial "true"
+
+    # recursors should be unset - command which follows enable-connect
+    run awk '/recursors/,/}/' "${CONSUL_CONFIG}"
+    assert_success
+    refute_output --partial "recursors"
 }
 
 @test "Consul Connect Configuration Generation: activated" {
@@ -104,6 +115,11 @@ call_generate_consul_config() {
     assert_output --partial "connect"
     assert_output --partial "enabled"
     assert_output --partial "true"
+
+    # recursors should be unset - command which follows enable-connect
+    run awk '/recursors/,/}/' "${CONSUL_CONFIG}"
+    assert_success
+    refute_output --partial "recursors"
 }
 
 @test "Consul Connect Configuration Generation: deactivated" {
@@ -121,4 +137,9 @@ call_generate_consul_config() {
     refute_output --partial "connect"
     refute_output --partial "enabled"
     refute_output --partial "true"
+
+    # recursors should be unset - command which follows enable-connect
+    run awk '/recursors/,/}/' "${CONSUL_CONFIG}"
+    assert_success
+    refute_output --partial "recursors"
 }