Creating a Basic HA Architecture by Using Horizontal Scaling
local graph
Chapter 19 — Creating a Basic HA Architecture by Using Horizontal Scaling
Section titled “Chapter 19 — Creating a Basic HA Architecture by Using Horizontal Scaling”GitLab is an application that consists of many components. The GitLab omnibus package makes it easy to run all these components on one physical server; however, there comes a time when one server is no longer enough to run GitLab. On a typical 4-CPU core machine with 16 GB of RAM, you can support about 2,000 users. Once you run an application on virtual hardware, it scales better (it is cheaper to reproduce virtual hardware); however, using more than 32 cores is still quite expensive and there comes a time when it is more economical to split up the functionality and scale horizontally. In this chapter, we will try to achieve this using Terraform and Ansible DevOps tools to deploy infrastructure as code. We will be using the Amazon Web Services (AWS) cloud offering as a backend.
You can build entire virtual infrastructures with Terraform and configure them using Ansible. These infrastructures can leverage the scaling features that cloud providers such as Amazon provide.
In this chapter, we will cover the following topics:
- The underlying architecture of the high available and scalable GitLab setup
- Setting up the bastion hosts
- Configuring the database nodes
- The Redis configuration
- Connecting the shared filesystem
- Setting up the application servers
For managing omnibus installations, there is one central configuration file called gitlab.rb. You need to create it or copy an example. There is a template available from https://gitlab.com/gitlab-org/omnibus-gitlab/blob/master/files/gitlab-config-template/gitlab.rb.template. Upgrades don’t replace or edit this file. In large parts of this chapter, I quote and discuss parts of this file.
For creating our virtual infrastructure, we are going to use Terraform (≥ v0.11.12). You can download it from https://www.terraform.io. Terraform is a multiplatform binary.
Terraform providers use the following:
- provider.ansible v0.0.4: Get it from https://github.com/nbering/terraform-inventory.
- provider.aws v2.1.0: Automatically downloaded with the terraform init command (see later on in Starting with the code section).
- provider.tls v1.2.0: Automatically downloaded with the terraform init command (see later on in Starting with the code section).
For automating our deployments, we use Ansible (≥ version 2.7). You can download it from https://github.com/ansible/ansible, or use a package manager such as brew or pip to install it.
To follow along with the instructions in this chapter, please download the Git repository, which contains examples and is on GitHub: https://github.com/PacktPublishing/Mastering-GitLab-12/tree/master/Chapter19.
What is the first iteration of a horizontally scaled GitLab? We not only need to scale horizontally to enable efficient growth, but also to enhance availability of the solution. Availability is usually measured in uptime, that is the percentage of the day, month, or year that your system is operational. To get this to a higher level, you need to eliminate single points of failure and make the components redundant. Also, be sure that the components can take over from each other when needed and have a good system in place that monitors and detects failures. If your system is doing this, it is said to be a high availability (HA) system.
What does it mean to scale horizontally? It means that you will split workloads into different layers. A load balancer will be placed at the front of the infrastructure. This will get one IP address and this will be the new external URL from GitLab. The traffic that enters here is distributed on the basis of the round-robin principle. One traffic flow goes to one GitLab application server, and the other goes to a second one. Because the load balancer supports sticky cookies, each web session will always choose the same route and end up at the same application server.
Because you now have two application servers, you need to share certain things to make it all work. For instance, if one of the GitLab application servers goes down, you want the other to take over the current HTTP sessions; therefore, you need a Redis server that is reachable by both application servers. The Redis server is where certain session information is kept.
Another example is the repository data. We can’t keep this confined on one GitLab server anymore, it needs to be shared! There are several options for this, but we will start with the simplest one: a Network File System (NFS).
The database can serve many clients, but it will also run several standby servers as a failover precaution. We also need a cluster mechanism to determine which database is the master and who is online.
The following is a diagram of the AWS GitLab horizontal scaling example solution, which is the basic HA solution:

On the left-hand side, you can find the clients. On the right-hand side, you can see the Amazon infrastructure. Everything is contained in a Virtual Private Cloud (VPC). Inside this VPC, you can see several security groups, which are mapped onto subnets.
The clients enter the infrastructure through the SG-loadbalancer security group. The requests for GitLab are then routed to the frontend application servers. They are connected to a shared filesystem and are connected to a Redis cluster that is also in the SG-frontendservers security group. The frontend application servers also connect to a database in the SG-backendservers zone through a pgbouncer proxy. There are three database servers: one master and two slaves. The health of the database servers is monitored through a consul cluster.
The bastion servers that are in the SG-bastion hosts security group have two special functions:
- They are accessible with SSH from the outside as jump hosts to other instances.
- They have a squid proxy server installed for the installation of packages by nodes in the SG-frontendservers and SG-backendservers zones.
We will use a cloud provider (Amazon) in our examples to build a basic scalable platform. With a little refactoring, the Terraform configuration could be rewritten to the specification of another cloud provider.
First, we will discuss the basic building blocks of this architecture.
AWS was the first big cloud offering. It started out by selling overcapacity from the Amazon server farms. In the last 10 years, it has grown rapidly and diversified its services. You can use it to virtualize your entire IT stack or create new services from the ground up. For this example, we use AWS because it performs very well and a lot of people are familiar with the concepts.
AWS has different kinds of building blocks that you can use to create your infrastructure. The basic ones are as follows.
Amazon EC2 is a popular product in AWS. It was one of the first cloud-scale virtual machine offerings on the market. You can rent virtual computers that can provide compute resources. You can run several kinds of operating systems in that virtual machine, and there are several ways to interact with this service. It is manageable through the AWS web console, and you can also use the extensive APIs to create and control EC2 instances. You can load custom applications into the virtual machines and use other Amazon services from them. It is effortless to scale up the number of machines, and security functions are available out of the box, as well as basic monitoring capabilities.
This is a public internet-facing interface with a F ully Qualified Domain Name (FQDN), and it routes requests from internet hosts to EC2 instances that have been registered with it. It has some built-in monitoring capabilities and a health check mechanism. For instance, it checks the HTTP port of the EC2 instances that are registered by default; however, in our case, that leads to trouble because the main GitLab page on the first boot always redirects. When this happens, the health check reports out of service and closes the port. We can change this to let the load balancer do a basic Transmission Control Protocol (TCP) health check only.
Amazon Virtual Private Cloud (Amazon VPC) is the highest abstraction of a group of resources within AWS. In a VPC, you can provision several AWS resources such as virtual networks and hosts. You are entirely in control of this space and can also create network route tables and gateways. There can be subnets that are accessible to the internet and ones that only communicate internally, inside your VPC. Network Access Control Lists (ACLs) and Security Groups (SGs) help defend your VPC from intruders. You have the option to use IPv4 and IPv6 as network protocol to enable communication over your networks.
SGs are a very important part of the security that you can use to control inbound and outbound network traffic. In traditional networks, you would usually place firewall appliances between networks or subnets to control network flows. In AWS, an SG takes on this role. Besides not being a physical device, the other difference is that SGs are not specified on the subnet level. In a VPC, you assign EC2 instances to these security groups, so the security rules are on an instance level. There can be a maximum of five security groups assigned. If you don’t assign anything, an instance will get the default security group for the VPC.
A useful tool for handling multicloud configurations is Terraform by HashiCorp – the folks that also gave us Vagrant and many other tools. It is a tool that can interact with a lot of APIs that are exposed by cloud providers. You tell Terraform what you want your infrastructure to look like in declarative files, and it takes care of the rest. Before it makes changes to existing infrastructure, it builds a graph of the resources that have already been deployed. It even has a dry run mode (terraform plan) where it calculates and reports the actions it will execute.
Tools such as Terraform enable the Infrastructure as code paradigm. It creates a reproducible infrastructure, and this greatly enhances the DevOps life cycle.
It is not only multi-cloud but also multiplatform, which means it can run on different operating systems, as we will see in the next section.
You can find a version of Terraform for your platform to download here: https://www.terraform.io/downloads.html. There are versions compiled for the following platforms:
- macOS
- FreeBSD
- Linux
- OpenBSD
- Solaris
- Windows
Inside the ZIP package is a single binary written in Golang that runs on your machine. After downloading and unpacking, you should put it somewhere in your path, for example, /usr/local/bin/ on Linux. After that, check your version on the command line as follows:
$terraform -vTerraform v0.11.12Make sure you have a version of at least v0.11.12. The binary is all you need. We also want the Ansible plugin for Terraform, but let's first install Ansible before this.Ansible is an agentless automation platform whose name is based on the hyperspace communication system, which features in science fiction literature. It is easy to set up, but powerful. It can play a role in configuration management, application deployment, and task automation. It is also suited for IT orchestration as a whole, where you have integrated security with the Ansible Tower backend and run tasks in sequence and create a chain of events that run on multiple different servers or devices. In our basic infrastructure example, for instance, it can run tasks for all web servers in the web group.
We are going to use Ansible to configure all the systems after they are provisioned with Terraform in the AWS infrastructure.
We mentioned that Ansible is agentless at the beginning of this section. Unlike Puppet or Chef, it doesn’t run as an agent on the remote target. Ansible uses SSH instead, so that is a requirement for all the systems you want to manage. Another dependency is Python, which needs to be installed on the remote target because Ansible itself is written in that language. To run Ansible, you do not need a dedicated server machine; instead, you can initiate the tasks from your local workstation or any other system with the basic Python runtime and SSH clients. If you need more integrated security, you can use Ansible Tower, in order to have a central place that connects with your enterprise identity management. It is technically possible to use Puppet in standalone mode, but you still need to install it on the targets.
Ansible is a free and open source product that runs on Linux, macOS, BSD, and even Windows. RedHat bought the company behind it in 2015, and, since then, Ansible has gotten more integrated with the RedHat enterprise product.
The real power of Ansible lies in its playbooks. A playbook is like a recipe or an instructions manual that tells Ansible what to do when it connects to each machine. It knows which machines to configure by checking an inventory, and which can be read from a file or passed in through a command (this is then called a dynamic inventory).
When Terraform generates the infrastructure, it keeps a local cache of the objects it has built. All information needed to generate a dynamic inventory is available from this file, but we need a plugin or provider to parse and transform the data so Ansible can understand it. We use the following Ansible provider to do that: https://github.com/nbering/terraform-inventory.
It’s easy to install. You need to download the terraform.py file, place it in your patch, and mark it as executable, as shown in the following example:
$cd /usr/local/bin && sudo wget https://raw.githubusercontent.com/nbering/terraform-inventory/master/terraform.py && sudo chmod 755 terraform.pyWhen you have cloned the code from https://github.com/PacktPublishing/Mastering-GitLab-12.git, change the current directory to the project:
cd Mastering-GitLab-12/CHP18/ha-configurationWe are going to use Terraform to create our infrastructure objects in AWS. The basic usage of Terraform is that you define the objects in files ending in .tf, and you can then start deploying them. If you have cloned the repository, the .tf files are already there, so you can then initialize Terraform (to retrieve the necessary plugins):
$ terraform initInitializing provider plugins...- Checking for available provider plugins on https://releases.hashicorp.com...- Downloading plugin for provider "tls" (2.0.1)...- Downloading plugin for provider "aws" (2.9.0)......* provider.ansible: version = "~> 0.0"* provider.aws: version = "~> 2.9"* provider.tls: version = "~> 2.0"Terraform has been successfully initialized!Now that Terraform is ready to go, you need to make sure the .tf definitions are valid. You can do that with a dry run where nothing will be installed, using the plan argument:
$ terraform planAn execution plan has been generated and is shown below.Resource actions are indicated with the following symbols: + create
Terraform will perform the following actions:...If there are no errors, you can then let Terraform create the objects for real by using the script in scripts/deploy-with-ansible.sh. To let Terraform deploy the objects manually, you can run apply, as follows:
$ terraform apply --auto-approvetls_private_key.mykey: Creating... algorithm: "" => "RSA" ecdsa_curve: "" => "P224" private_key_pem: "" => "<computed>" public_key_fingerprint_md5: "" => "<computed>" public_key_openssh: "" => "<computed>" public_key_pem: "" => "<computed>" rsa_bits: "" => "4096"aws_vpc.gitlabha: Creating...In the next sections, we describe each .tf file and give an example of its use.
In the Virtual private cloud and subnets section, we explained that a VPC is the beginning of an AWS infrastructure. In the vpc.tf file, we define this:
resource "aws_vpc" "gitlabha" { cidr_block = "10.0.0.0/16" enable_dns_hostnames = true enable_dns_support = true tags{ Name = "VPC-${var.environment}" } }We assign the VPC a private network address that, again, can be divided into subnets:
cidr_block = "10.0.0.0/16"We want to enable DNS hostnames for this VPC:
enable_dns_hostnames = trueenable_dns_support = trueWe can use tags to give the VPC a name that fits with the environment we define:
tags{ Name = "VPC-${var.environment}"}Now that we have a basic VPC, we can divide it into further networks and create more objects.
In this file, the subnets that we can use to create networks are defined. We like to split frontend and backend networks, and then apply rules from SGs to them in order to allow or disallow traffic. The following example is of an entry in that file:
resource "aws_subnet" "public-frontend_az-a" { availability_zone = "eu-central-1a" cidr_block = "10.0.11.0/24" map_public_ip_on_launch = true vpc_id = "${aws_vpc.gitlabha.id}" tags { Name = "Subnet-eu-central-1a-Frontend" }}We can see that the availability zone is defined (which can be found at https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html#concepts-available-regions):
availability_zone = "eu-central-1a"The specific IP range for this subnet is defined as follows:
cidr_block = "10.0.11.0/24"It’s also possible to let Amazon create a public IP that maps onto the hosts created in this subnet. It does not mean it is reachable; that is determined by our security rules:
map_public_ip_on_launch = trueThe next setting is the VPC that this subnet belongs to:
vpc_id = "${aws_vpc.gitlabha.id}"The last setting is the tag that is given to this object, which makes it easier to search:
tags { Name = "Subnet-eu-central-1a-Frontend"}When all the subnets have been created, the frontend and backend components can communicate with each other.
In this file, we declare the Amazon EC2 instances. We have several instances, but we will start with the first frontend application server defined in this file:
resource "aws_instance" "FRONTEND_A" { ami = "${lookup(var.aws_ubuntu_amis,var.region)}" subnet_id = "${aws_subnet.public-frontend_az-a.id}" key_name = "${aws_key_pair.keypair.key_name}" vpc_security_group_ids = ["${aws_security_group.SG-frontendservers.id}"] instance_type = "t2.medium" tags { Name = "${var.environment}-FRONTEND001" Environment = "${var.environment}" sshUser = "ubuntu" }}The declaration that this block starts with constitutes an Amazon resource of aws_instance type and is called FRONTEND_A:
resource "aws_instance" "FRONTEND_A" {Next, the first line of the block defines the Amazon Machine Image (AMI) that is used as the base for this instance. In our case, we run an Ubuntu image in our region. It is defined as a variable in variable.tf:
ami = "${lookup(var.aws_ubuntu_awis,var.region)}"This machine will be part of a network. The following line describes which subnet the machine is connected to:
subnet_id = "${aws_subnet.public-frontend_az-a.id}"We need a way to connect to the machine to configure them. For this, we need an SSH connection that, in turn, needs an SSH key pair from which the public key is registered:
key_name = "${aws_key_pair.keypair.key_name}"We need to assign a security group to the machine, in order to make sure the network ACLs are applied:
vpc_security_group_ids = ["${aws_security_group.SG-frontendservers.id}"]Next is the type of instance: t2.medium. A list of these can be found at https://aws.amazon.com/ec2/instance-types/:
instance_type = "t2.medium"The next section of this block sets tags that will be associated with this machine:
Name = "${var.environment}-FRONTEND001"Environment = "${var.environment}"sshUser = "ubuntu"You can see here that the name is based on the environment variables and a string.
This information is all that is needed to create a virtual machine in the Amazon EC2 cloud. We also need a way to control it afterward with Ansible, which is done in the next section.
We are going to use the Terraform Ansible provider to translate a Terraform state file into a dynamic Ansible inventory. We are going to create resources of the ansible_host type, which are taken care of by the Ansible provider. As an example, the host that defines our frontend application server is as follows:
resource "ansible_host" "FRONTEND001" { inventory_hostname = "${aws_instance.FRONTEND_A.private_dns}" groups = ["frontend"] vars { ansible_user = "ubuntu" role = "master" ansible_ssh_private_key_file="/tmp/mykey.pem" ansible_python_interpreter="/usr/bin/python3" ansible_ssh_common_args= " -o ProxyCommand=\"ssh -o StrictHostKeyChecking=no -i /tmp/mykey.pem -W %h:%p -q ubuntu@${aws_instance.BASTIONHOST_A.public_dns}\"" proxy = "${aws_instance.BASTIONHOST_A.private_ip}" subnet = "${aws_subnet.public-frontend_az-a.cidr_block}" }}Let’s connect an EC2 instance to this resource, which will then feature as a host in the Ansible inventory:
inventory_hostname = "${aws_instance.FRONTEND_A.private_dns}"We also define an Ansible host group, which, in this case, is frontend:
groups = ["frontend"]The last part of this Ansible resource is dealing with vars, which will become Ansible facts. The SSH user that is used for executing playbooks will be “ubuntu”, and a sudo mechanism will be used afterward:
ansible_user = "ubuntu"During the deployment of software on the hosts, we need to know which role the hosts will play in the HA infrastructure:
role = "master"For the SSH connection to succeed with certificate-based authentication, we need the created private key:
ansible_ssh_private_key_file="/tmp/mykey.pem"Ansible uses Python as its interpreter, so we must specify the version:
ansible_python_interpreter="/usr/bin/python3"We are not going to connect directly to the different EC2 hosts; we have to go through our bastion hosts. We need to instruct Ansible to connect through them:
ansible_ssh_common_args= " -o ProxyCommand=\"ssh -o StrictHostKeyChecking=no -i /tmp/mykey.pem -W %h:%p -q ubuntu@${aws_instance.BASTIONHOST_A.public_dns}\""To install the software and updates, we need a proxy server, because, by default, the machines in the backend cannot connect to the internet:
proxy = "${aws_instance.BASTIONHOST_A.private_ip}"Because we are going to configure some software on the machines, we need the subnets of the instances. They are already defined in Terraform, so we can just pass them through as Ansible facts, in order to use them in our templates and playbooks. What follows is the defined subnet in which the frontend application server resides:
subnet = "${aws_subnet.public-frontend_az-a.cidr_block}"Here, all the different nodes that are created in instance.tf are coupled to an Ansible host, which will be exposed via the dynamic inventory script when called**.**
Now that we have hosts and networks, we have to find a way to make them communicate with each other. When they live in the same subnet, that is fine, but we need to route some traffic because we have multiple networks. Here is an example of such an AWS resource, which is called a aws_route_table resource:
resource "aws_route_table" "default" { vpc_id = "${aws_vpc.gitlabha.id}"
route { cidr_block = "0.0.0.0/0" gateway_id = "${aws_internet_gateway.internet_gateway.id}" }
tags { Name = "Default route table" }}The first property is the VPC it belongs to:
vpc_id = "${aws_vpc.gitlabha.id}"Then, a route is defined. In this example, it is the default route, 0.0.0.0/0:
cidr_block = "0.0.0.0/0"The gateway in this block is the internet gateway for this VPC:
gateway_id = "${aws_internet_gateway.internet_gateway.id}"There are several other routes defined for enabling traffic between the subnets that were created.
In this file, we define the security groups that are in use for this VPC. A security group consists of ingress (incoming) and eggress (outgoing) traffic definitions:
resource "aws_security_group" "SG-frontendservers"{ name = "SG-frontendservers" vpc_id = "${aws_vpc.gitlabha.id}" description = "Security group for frontendservers" ingress { from_port = 22 to_port = 22 protocol = "TCP" security_groups = ["${aws_security_group.SG-bastionhosts.id}"] description = "Allow incoming SSH traffic from bastion hosts"}The first two attributes define the name for the group, as well as the ID of the VPC to which this group belongs:
name = "SG-frontendservers"vpc_id = "${aws_vpc.gitlabha.id}"description = "Security group for frontendservers"The last attribute is a description of this group. Then, the first ingress traffic definition follows:
from_port = 22to_port = 22protocol = "TCP"It states the source, the destination port, and the protocol (in this case, it is TCP).
The last parts of the ingress definition mention the security group IDs and the description of this ingress rule:
security_groups = ["${aws_security_group.SG-bastionhosts.id}"]description = "Allow incoming SSH traffic from bastion hosts"Several other rules are defined as well, but they follow the same specification.
We have used a special file to declare some high-level variables – in this case, the region where the infrastructure will be run:
variable "region"{ default = "eu-central-1"}If the variables are not declared, the scripts will either fail or ask for an input.
During the Terraform deployment, a custom SSH key pair will be created; in this file, we define some properties for it:
resource "tls_private_key" "mykey"{ algorithm = "RSA" rsa_bits = 4096}resource "aws_key_pair" "keypair"{ key_name = "${var.key_name}" public_key = "${tls_private_key.mykey.public_key_openssh}"}output "mykey" { value = "${tls_private_key.mykey.private_key_pem}}" sensitive = true}The resource type we first define is an SSH private key:
resource "tls_private_key" "privkey"{ algorithm = "RSA" rsa_bits = 4096}We determine what kind of algorithm will be used and the key size in bits.
The next resource is the key pair as a bundle:
resource "aws_key_pair" "keypair"{ key_name = "${var.key_name}" public_key = "${tls_private_key.privkey.public_key_openssh}"}Here, we define the name of the key and the public key accompanying it.
The last part of the file is to make sure we can dump the contents of the private key to a file, so we can use it to connect from our Ansible host:
output "mykey" { value = "${tls_private_key.mykey.private_key_pem}}" sensitive = true}After being generated, the key can be extracted with the terraform output command.
This file holds the declaration of the load balancer we use in front of the GitLab application hosts, in order to distribute network traffic:
resource "aws_elb" "lb" { name_prefix = "${var.environment}-" subnets = ["${aws_subnet.public-frontend_az-a.id}", "${aws_subnet.public-frontend_az-b.id}"] health_check { healthy_threshold = 2 unhealthy_threshold = 2 timeout = 3 target = "TCP:80" interval = 30 } listener { instance_port = 80 instance_protocol = "http" lb_port = 80 lb_protocol = "http" } cross_zone_load_balancing = true instances = ["${aws_instance.FRONTEND_A.id}", "${aws_instance.FRONTEND_B.id}"] security_groups = ["${aws_security_group.SG-loadbalancer.id}"]}
resource "aws_lb_cookie_stickiness_policy" "gitlab" { name = "gitlab-policy" load_balancer = "${aws_elb.lb.id}" lb_port = 80 cookie_expiration_period = 600}The first part of the resource block contains a name prefix (such as dev-) and the subnets that this load balancer is connected to:
name_prefix = "${var.environment}-"subnets = ["${aws_subnet.public-frontend_az-a.id}", "${aws_subnet.public-frontend_az-b.id}"]Then, there is a definition of the health check the load balancer performs, in order to determine whether an upstream destination is still running:
health_check { healthy_threshold = 2 unhealthy_threshold = 2 timeout = 3 target = "TCP:80" interval = 30}As mentioned before, we are changing this from the default HTTP check to a TCP check because of the redirect mechanism of GitLab’s default page. After two consecutive failures to check whether TCP port 80 is open, the load balancer will set an upstream target to OutOfService and stop using it. With an interval of 30 seconds and a timeout of 3, the upstream target will take about 2 minutes to go in to service or out of service.
You also have to define a listener block, where you register which ports the load balancer should open at the front, and to which ports on the backend instances it should connect:
listener { instance_port = 80 instance_protocol = "http" lb_port = 80 lb_protocol = "http"}Finally, the last part of the lb block is used to check whether it is possible to load balance across zones, and whether there are instances defined that will be used by the load balancer:
cross_zone_load_balancing = trueinstances = ["${aws_instance.FRONTEND_A.id}", "${aws_instance.FRONTEND_B.id}"]security_groups = ["${aws_security_group.SG-loadbalancer.id}"]The preceding final attribute is the specific security group this load balancer is part of.
We keep a providers.tf file to define some basic variables for the AWS provider. We already defined region as a variable, so we are going to reuse it (${var/region}):
provider "aws" {region = "${var.region}"}To summarize, we have a number of .tf files in the directory here that all describe Amazon resources. They are named after the functions that can be recognized in them. Here is the list of files containing Terraform definitions:
- ansible.tf: Where we define our Ansible hosts to be
- instances.tf: Which defines the EC2 instances (in our case, 14)
- keys.tf: Where we define generated SSH key properties
- lb.tf: Where we define our classic load balancer (such as stickiness and health checks)
- networking.tf: Where we define the VPC and subnets
- providers.tf: Where we put provider-specific information
- routes.tf: Where we put our routing between subnets
- security.tf: Where we define the security groups
- variables.tf: Where we define global variables
Now that we have our infrastructure definitions, it’s time to test our declarations, and, after that, deploy the code.
Before Terraform executes the API calls to AWS that create or delete resources, it first parses your .tf files and generates a graph of the resources it is going to change. It then checks what is already in Amazon and compares the two. It will then ask for confirmation. It is always a good plan to do a dry run first, which can be done with the plan feature:
$ terraform planRefreshing Terraform state in-memory prior to plan...The refreshed state will be used to calculate this plan, but will not bepersisted to local or remote state storage.tls_private_key.privkey:Refreshing state... (ID: 874768c0573f85ee35688f91b96793940376786c)...After building graphs and doing a comparison, Terraform will report how much it will change when executed for real:
Plan: 51 to add, 0 to change, 0 to destroy.---As you can see, we don’t have anything in there yet, and we will proceed in running the provisioning.
You can run the deployment with the following command:
terraform applyYou can also add the —auto-approve argument; then, it will not ask for confirmation.
Running the apply command will start and produce a lot of output, as follows:
tls_private_key.privkey: Refreshing state... (ID: 874768c0573f85ee35688f91b96793940376786c)aws_key_pair.keypair: Refreshing state... (ID: ec2key)aws_vpc.gitlabha: Refreshing state... (ID: vpc-0d623120e0d5401f9)aws_subnet.pub-web-az-b: Refreshing state... (ID: subnet-03908026eb72659e1)aws_subnet.priv-db-az-a: Refreshing state... (ID: subnet-0e65b8cb35e8ef116)In the end, if all goes well, you should receive a message to say that the application is complete:
Apply complete! Resources: 51 added, 0 changed, 0 destroyed.Outputs:private_key = <sensitive>It also tells you whether it has outputs, which means there is a variable saved in the Terraform state. This is actually the private key we defined in the keys.tf file. After deployment, we should now save this in a file somewhere so we can configure Ansible, in order to use it to set up SSH connections to AWS hosts.
You can do this as follows:
terraform output -json|jq .private_key.value -r >/tmp/privkey.pem && chmod 600 /tmp/privkey.pemIf you log in to the AWS web console, you can view your created resources. Here is a list of created EC2 instances:

Before we start using Ansible to deploy to the machines, let’s walk through the files that Ansible uses. We keep our playbooks in the main Git project directory: https://github.com/PacktPublishing/Mastering-GitLab-12/tree/master/Chapter18/ha-configuration:
├── files│ └── .ansible.cfg├── install-consul.yml├── install-gitlab.yml├── install-nfs.yml├── install-pgbouncer.yml├── install-postgres-core.yml├── install-postgres-slaves.yml├── install-redis.yml├── install-bastion-hosts.yml└── templates ├── databases.ini.j2 ├── gitlab.rb.consul.j2 ├── gitlab.rb.j2 ├── gitlab.rb.pgbouncer.j2 ├── gitlab.rb.postgres.j2 ├── gitlab.rb.redis.j2 ├── nfs_exports.j2 └── pgpass.j2First, you see playbooks with the .yml extension. Then, there is a files directory, which is intended to accommodate files that must be copied without modification. We also have a templates directory, which holds Jinja2 (Python templating engine) templates that are copied and modified in some playbooks.
An important thing to remember is that this example uses fairly simple playbooks. Every playbook does what the name implies, and we don’t use Ansible roles or error handling. This makes the code easier to understand, but it also makes it a bit less robust.
Before you run the ansible-playbook commands, have a look at the playbooks in order to understand what they do. Further on, we will discuss the Jinja2 templates that are used. Most of the nodes are configured with the GitLab omnibus installer, which relies heavily on a gitlab.rb file as a parameter file, and runs all kinds of configuration actions based on the file.
The bastion hosts are the first two machines in the VPC and are used as jumphosts to connect to other instances in your VPN. That is why they are installed first. They will be provided with a squid cache and function as a proxy for the other hosts to install packages and such:
- Script: install.yml
- Jinja template: None
- Run command: ansible-playbook -i /usr/local/bin/terraform.py deploy/install.yml
After installation, you can connect using the following script:
connect_ssh.sh bastion0Or, if you want to connect to the second bastion host, use the following script:
connect_ssh.sh bastion1The hosts will be used by the Ansible scripts as jumphosts for deployments.
The installation of the database nodes is done through two Ansible scripts. The master database is installed through install-postgres-core.yml and the slave databases through install-postgres-slave.yml. They both share the same Jinja template (gitlab.rb.postgres.j2); however, inside the template, there are some conditionals where values are replaced based on whether a host is a database master or slave:
- Script: install-postgres-core.yml and install-postgres-slaves.yml
- Jinja template: gitlab.rb.postgres.j2
- Run the following commands:
- For master databases: ansible-playbook -i /usr/local/bin/terraform.py deploy/install-postgres-core.yml
- For slave databases: ansible-playbook -i /usr/local/bin/terraform.py deploy/install-postgres-slaves.yml
- For master databases: ansible-playbook -i /usr/local/bin/terraform.py deploy/install-postgres-core.yml
The first declaration in the gitlab.rb.postgres.j2 template is which role the instance will play in our infrastructure:
roles ['postgres_role']The next setting is to determine whether a database should be initialized as a master database, which should only be performed on the master node:
# Only the master database should become master {% if hostvars[inventory_hostname].role == "slave" %} repmgr['master_on_initialization'] = false {% endif %}The general database properties are the same for the master and the slaves. The database should listen on all interfaces and be prepared to sync their data:
# Database propertiespostgresql['listen_address'] = '0.0.0.0'postgresql['hot_standby'] = 'on'postgresql['wal_level'] = 'replica'postgresql['shared_preload_libraries'] = 'repmgr_funcs'We are going to use PgBouncer to create sessions to the database. For this, it needs an account password, which is configured here:
# Replace pgbouncer_user_password with a generated md5 value :packtpub# gitlab-ctl pg-password-md5 pgbouncer packtpubpostgresql['pgbouncer_user_password'] = '5da810d253b27c0a30ce8a19c4361659'The default postgres password is configured next. We need to get the hash value of the password. You can generate it by running gitlab-ctl pg-password in a Docker container:
$ docker run -ti gitlab/gitlab-ee:latest --name gitlab-ee$ docker exec -ti gitlab-ee gitlab-ctl pg-password-md5 gitlabEnter password:Confirm password:319e2283a175820cc15a0c7ed742f336In the template, replace POSTGRESQL_PASSWORD_HASH with the generated md5 value (for example, you entered packtpub):
postgresql['sql_user_password'] = '319e2283a175820cc15a0c7ed742f336'None of the database installations should run Rails migrations, which means no data is loaded into the database. That job is left to the backend application servers:
# Disable automatic database migrationsgitlab_rails['auto_migrate'] = falseThe database saves changes to the logs before writing them into the database files. This is called Write-Ahead Logging (WAL). An important part of the database’s HA mechanism is that the master database sends these database logs to the slaves and lets them replay these logs against their databases. This setting determines how many WAL sender processes are allowed (to make sure there are not too many connections, which would slow things down):
#Set the number of wal senders to how many postgresql servers +1postgresql['max_wal_senders'] = 4By default, connections to the database are not allowed. We specify a whitelist of allowed networks and hosts for different services. The variables that begin with hostvars are Ansible-specific and refer to the dynamic inventory that is created by terraform-ansible.py.
The master and slave databases are allowed to connect for replication purposes without a password:
postgresql['trust_auth_cidr_addresses'] = %w({{ hostvars[groups['db'][0]]['subnet'] }} {{ hostvars[groups['db'][1]]['subnet'] }} {{ hostvars[groups['db'][2]]['subnet'] }})The application servers are allowed to connect with a password:
postgresql['md5_auth_cidr_addresses'] = %w({{ hostvars[groups['web'][0]]['inventory_hostname'] }} {{ hostvars[groups['web'][1]]['inventory_hostname'] }})The repmgr service is also allowed to connect without a password, in order to manage replication:
repmgr['trust_auth_cidr_addresses'] = %w({{ hostvars[groups['db'][0]]['subnet'] }} {{ hostvars[groups['db'][1]]['subnet'] }} {{ hostvars[groups['db'][2]]['subnet'] }})The databases should all have the consul agent installed, which is used to signal whether the database is available:
# Configure the consul agentconsul['services'] = %w(postgresql)The consul agent has to know where to connect to, in order to report about cluster health, which is done where the consul nodes are inserted:
Consul nodesconsul['configuration'] = {retry_join: %w({{ hostvars[groups['consul'][0]]['inventory_hostname'] }} {{ hostvars[groups['consul'][1]]['inventory_hostname'] }} {{ hostvars[groups['consul'][2]]['inventory_hostname'] }})}When the Ansible jobs for the database master and slaves have run, you should have an operations PostgreSQL database cluster with failover capabilities.
The deployment of consul is necessary to keep track of the database service. When consul detects that one of the agents in the database is reporting a failure or not answering, it will let PGBouncer know and make sure the application servers will use the working database. If the master database is offline, it failover to a standby node:
- Script: install-consul.yml
- Jinja template: gitlab.rb.consul.j2
- Run command: ansible-playbook -i /usr/local/bin/terraform.py deploy/install-consul.yml
The first declaration in this file is which role the instance will play in our infrastructure:
# Disable all components except Consul roles ['consul_role']The second set of declarations disables all other functions for this host. GitLab omnibus will only configure services for running consul:
## Disable all other services sidekiq['enable'] = false gitlab_workhorse['enable'] = false unicorn['enable'] = false postgresql['enable'] = false nginx['enable'] = false prometheus['enable'] = false alertmanager['enable'] = false pgbouncer_exporter['enable'] = false gitlab_monitor['enable'] = false gitaly['enable'] = falseIn the next section, the nodes that will be part of the consul cluster are defined:
# Consul nodesconsul['configuration'] = {server: true,retry_join: %w( {{ hostvars[groups['consul'][0]]['inventory_hostname'] }} {{ hostvars[groups['consul'][1]]['inventory_hostname'] }} {{ hostvars[groups['consul'][2]]['inventory_hostname'] }})}As with disabling the other functions, we must also prohibit omnibus from trying to run Rails database migration actions:
# Disable db auto migrations gitlab_rails['auto_migrate'] = falseAfter running the deployment script, you will have a running consul cluster that can communicate between nodes. The consul agents are installed via other roles in gitlab.rb.
The PgBouncer component is used to multiplex database connections and switch between active and passive database nodes:
- Script: install-pgbouncer.yml
- Jinja template: gitlab.rb.pgbouncer.j2, databases.ini.j2, pgpass.j2
- Run command: ansible-playbook -i /usr/local/bin/terraform.py deploy/install-pgbouncer.yml
The first declaration in this file is which role the instance will play in our infrastructure:
# Disable all components except Pgbouncer and Consul agentroles ['pgbouncer_role']Again, we want omnibus to disable all other functions for this host:
# Disable all other servicessidekiq['enable'] = falsegitlab_workhorse['enable'] = falseunicorn['enable'] = falsepostgresql['enable'] = falsenginx['enable'] = falseprometheus['enable'] = falsealertmanager['enable'] = falsegitlab_monitor['enable'] = falsegitaly['enable'] = falseWe must set the usernames that will be used through PgBouncer:
# Configure Pgbouncerpgbouncer['admin_users'] = %w(pgbouncer gitlab-consul)The consul agent that runs on this machine must keep an eye on the PostgreSQL service:
# Configure Consul agentconsul['watchers'] = %w(postgresql)We need to set the application password for the gitlab-consul and PgBouncer users:
# Setup application passwordspgbouncer['users'] = {'gitlab-consul': {password: '46ae9788c600a7d8483796466f64033a'},'pgbouncer': {password: '5da810d253b27c0a30ce8a19c4361659'}}The consul agent has to know which consul nodes are around:
# Consul nodes consul['configuration'] = { retry_join: %w({{ hostvars[groups['consul'][0]]['inventory_hostname'] }} {{ hostvars[groups['consul'][1]]['inventory_hostname'] }} {{ hostvars[groups['consul'][2]]['inventory_hostname'] }}) }There are two more Jinja templates that are used in this Ansible script:
- databases.ini.j2: In this file, the connection string for the initial database connection is set:
[databases]gitlabhq_production = host={{ hostvars[groups['db'][2]]['inventory_hostname'] }} auth_user=pgbouncer- pgpass.j2: This contains the plaintext password for PgBouncer:
127.0.0.1:*:pgbouncer:pgbouncer:packtpubOn completion of running the install-pgbouncer.yml script, there should be a single PgBouncer node connected to the databases and consul.
One of the most important components of GitLab Redis is installed as a master/slave cluster in this setup:
- Script: install-redis.yml
- Jinja template: gitlab.rb.redis.j2
- Run command: ansible-playbook -i /usr/local/bin/terraform.py deploy/install-redis.yml
The first declaration in this file is which role the instance will play in our infrastructure:
# Enable Redisredis['enable'] = trueAgain, all other functions are disabled:
# Disable all other servicessidekiq['enable'] = falsegitlab_workhorse['enable'] = falseunicorn['enable'] = falsepostgresql['enable'] = falsenginx['enable'] = falseprometheus['enable'] = falsealertmanager['enable'] = falsepgbouncer_exporter['enable'] = falsegitlab_monitor['enable'] = falsegitaly['enable'] = falseIn this part, we also check the role of the Redis node, which is passed through by Terraform to Ansible via the dynamic inventory:
# Check the role of the redis server{% if hostvars[inventory_hostname].role == "master" %}roles ['redis_master_role']{% else %}roles ['redis_slave_role']redis['master_ip'] = '{{ hostvars[groups['redis'][1]]['ansible_eth0']['ipv4']['address'] }}'{% endif %}We specify that Redis should listen on all network interfaces:
redis['bind'] = '0.0.0.0'Then, we specify which TCP port it will listen on:
# Define a port so Redis can listen for TCP requests which will allow other# machines to connect to it.redis['port'] = 6379For this example, we use a very simple password in order for the slave Redis instance to connect:
# Set up password authentication for Redis (use the same password in all nodes).redis['password'] = 'packtpub'Like some other machines, we don’t want this one to run Rails database migrations, so we specify this:
#Don't run database migrationsgitlab_rails['auto_migrate'] = falseAfter running install-redis.yml, there should be two extra nodes that have a master and a slave Redis node, respectively.
The creation of a shared filesystem in this basic architecture is done without the GitLab omnibus package. We just configure a basic Linux node with NFS functionality:
- Script: install-nfs.yml
- Jinja template: nfs_exports.j2
- Run command: ansible-playbook -i /usr/local/bin/terraform.py deploy/install-nfs.yml
The NFS server is a server that is not configured through omnibus, so there is no gitlab.rb template file. Most of the installation is through the install-nfs.yml file and the only template is the NFS exports file, which is placed in /etc and transformed.
The NFS exports file is used read by the NFS server at startup to determine which folders should be shared on the network and to which addresses this export is allowed. In the case of our example we want the root folder /nfs to be shared to our GitLab application servers in the ‘frontend’ Ansible hostgroup. In the Jinja template a for loop is used to iterate through the hostnames of the ‘frontend’ hostgroup:
/nfs {% for host in groups['frontend'] %} {{ hostvars[host]['inventory_hostname'] }}(rw,sync,no_root_squash,no_subtree_check) {% endfor %}After processing, the resulting NFS shared filesystem can only be mounted by the application servers.
The most important pieces of this infrastructure are the application servers themselves. They are also installed with Ansible, but they have slightly bigger template files than the other components because a lot has to be configured:
- Script: install-gitlab.yml
- Template: gitlab.rb.j2
- Run command: ansible-playbook -i /usr/local/bin/terraform.py deploy/install-gitlab.yml
The first declaration in this file is which role the instance will play in our infrastructure:
# Disable components that will not be on the GitLab application serverroles ['application_role']nginx['enable'] = trueAlong with the role, another function (nginx) is activated, which acts as an auxiliary function to the application role. NGINX is the reverse proxy in front of the Unicorn web server.
An important setting is the external URL that is going to be used to reach GitLab via HTTP. For our example, we use HTTP, but you can also use HTTPS. The URL is pulled again from the dynamic inventory:
# The URL GitLab is available onexternal_url 'http://{{ hostvars[groups['lb'][0]]['inventory_hostname'] }}'We are going to use NFS as a shared filesystem, so we need to indicate that we use a high-availability mount point. The application check in the filesystem is mounted; otherwise, it won’t start its services:
# Indicate that nfs mountpoint is usedhigh_availability['mountpoint'] = '/var/opt/gitlab/git-data'We specify the PgBouncer node as the database for GitLab, and the node will talk to the active master database. The hostname is pulled from the dynamic inventory again:
# PostgreSQL connection attributesgitlab_rails['db_adapter'] = 'postgresql'gitlab_rails['db_encoding'] = 'unicode'gitlab_rails['db_password'] = 'packtpub'gitlab_rails['db_host'] = '{{ hostvars[groups['pgbouncer'][0]]['inventory_hostname'] }}'# IP/hostname of database servergitlab_rails['db_port'] = 6432We specify the Redis host we find in the dynamic inventory:
# Redis connection detailsgitlab_rails['redis_port'] = '6379'gitlab_rails['redis_host'] = '{{ hostvars[groups['redis'][1]]['inventory_hostname'] }}'# IP/hostname of Redis servergitlab_rails['redis_password'] = 'packtpub'Because we are using a shared filesystem, it makes sense to keep the UIDs and GIDs the same:
# Ensure UIDs and GIDs match between servers for permissions via NFSuser['uid'] = 9000user['gid'] = 9000web_server['uid'] = 9001web_server['gid'] = 9001registry['uid'] = 9002registry['gid'] = 9002Next, we use a control flow to test whether the server is a master or a slave to make sure that only one GitLab application server executes Rails database migrations:
# Make sure only 1 GitLab server executes migrations{% if hostvars[inventory_hostname].role == "slave" %}gitlab_rails['auto_migrate'] = false{% endif %}Again, the information attribute that determines this is pulled from the dynamic inventory. In this example, we don’t use HTTPS, so we disable the autogeneration of certificates:
#disable letsencrypt for demo purposesletsencrypt['enable'] = falseNow that we have looked at all the files, let’s try to run them.
I have created a shell script that runs all steps sequentially, and when one fails, it will stop processing. It is called deploy-with-ansible.sh. You can run it like this in the HA configuration directory of your project:
../deploy-with-ansible.shtls_private_key.privkey: Refreshing state... (ID: 874768c0573f85ee35688f91b96793940376786c)aws_key_pair.keypair: Refreshing state... (ID: ec2key)aws_vpc.gitlabha: Refreshing state... (ID: vpc-0d623120e0d5401f9)aws_subnet.pub-web-az-b: Refreshing state... (ID: subnet-03908026eb72659e1)aws_subnet.priv-db-az-a: Refreshing state... (ID: subnet-0e65b8cb35e8ef116)aws_security_group.bastionhostSG: Refreshing state... (ID: sg-0c9043cd8f71becab)aws_internet_gateway.inetgw: Refreshing state... (ID: igw-05a45a3163391b294)aws_subnet.priv-db-az-b: Refreshing state... (ID: subnet-023c4157ba90f1805)You can also run the individual playbooks manually. But before you run any playbooks, the following environment variable will prohibit SSH connection errors:
export ANSIBLE_HOST_KEY_CHECKING=falseWhen you run the playbooks, please perform these steps in the following order:
- Install the bastion hosts as follows:
ansible-playbook -i /usr/local/bin/terraform.py deploy/install.yml- Install the master PostgreSQL database as follows:
ansible-playbook -i /usr/local/bin/terraform.py deploy/install-postgres-core.yml- Install the slave PostgreSQL databases as follows:
ansible-playbook -i /usr/local/bin/terraform.py deploy/install-postgres-slaves.yml- Install the consul nodes as follows:
ansible-playbook -i /usr/local/bin/terraform.py deploy/install-consul.yml- Install the PgBouncer nodes as follows:
ansible-playbook -i /usr/local/bin/terraform.py deploy/install-pgbouncer.yml- Install the Redis nodes as follows:
ansible-playbook -i /usr/local/bin/terraform.py deploy/install-redis.yml- Install the NFS server as follows:
ansible-playbook -i /usr/local/bin/terraform.py deploy/install-nfs.yml- Install the GitLab application servers as follows:
ansible-playbook -i /usr/local/bin/terraform.py deploy/install-gitlab.ymlAfter all the operations are executed successfully, you will end up with a working GitLab cluster. You can verify whether it works by looking at the properties of your classic load balancer and looking for the DNS name, as shown in the following screenshot:

If you copy and paste this URL into your browser, a clean GitLab instance that asks for a password is installed, as shown in the following screenshot:

If this isn’t working, then check whether the instance is set to InService in the Instances tab of your load balancer, as follows:

If the status entry says Outofservice, then you need to check whether all instances are green.
You can log in to all your services with my special connect_ssh.sh script. First, check whether the hosts are available:
$ ./connect_ssh.sh show_host_codeshostcode: pg0 -- hostname: "ip-10-0-2-18.eu-west-1.compute.internal"hostcode: db1 -- hostname: "ip-10-0-2-125.eu-west-1.compute.internal"hostcode: db0 -- hostname: "ip-10-0-2-83.eu-west-1.compute.internal"hostcode: db2 -- hostname: "ip-10-0-1-217.eu-west-1.compute.internal"hostcode: red0 -- hostname: "ip-10-0-12-18.eu-west-1.compute.internal"hostcode: red1 -- hostname: "ip-10-0-11-224.eu-west-1.compute.internal"hostcode: frontend1 -- hostname: "ip-10-0-12-25.eu-west-1.compute.internal"hostcode: frontend0 -- hostname: "ip-10-0-11-43.eu-west-1.compute.internal"hostcode: nfs0 -- hostname: "ip-10-0-11-69.eu-west-1.compute.internal"hostcode: cs1 -- hostname: "ip-10-0-2-165.eu-west-1.compute.internal"hostcode: cs0 -- hostname: "ip-10-0-1-145.eu-west-1.compute.internal"hostcode: cs2 -- hostname: "ip-10-0-1-99.eu-west-1.compute.internal"hostcode: bastion0 -- hostname: "ec2-34-245-42-209.eu-west-1.compute.amazonaws.com"hostcode: bastion1 -- hostname: "ec2-54-229-146-28.eu-west-1.compute.amazonaws.com"You can then connect to the first database server like so:
$ ./connect_ssh.sh db0Once connected, you can switch to root with the sudo -i command, check all log files, and inspect things on the virtual machines.
Hopefully, there were no errors and you have a running GitLab instance, and, if not, you are able to debug the problem.
In this chapter, we first looked at what a basic HA architecture of GitLab should look like, and we determined the minimum amount of infrastructure that should be built. We then explained how we could do this through AWS. With Terraform, Ansible, and some scripting, we showed how you can create an HA environment with 14 hosts.
In the next chapter, we will further split the nodes and functionalities to eliminate even more single points of failure. This will grow your HA capability. Secondly, you prepare your GitLab system for serving more users because you can scale your system much more easily to accommodate the higher load.
- What does HA stand for?
- What language is Terraform written in?
- What does EC2 stand for?
- How many consul nodes are defined in our example?
- What templating engine is used in Ansible?
- What script can run all deployment actions at once?
- If all is OK in the health check, what does the load balancer say?
- What script can you use to connect to the Amazon hosts with SSH?
- Mastering Ansible – Third Edition by James Freeman and Jesse Keating:
- Getting Started with Terraform – Second Edition by Kirill Shirinkin:
- AWS Certified Developer – Associate Guide – Second Edition by Vipul Tankariya and Bhavin Parmar:
- Learn Linux Shell Scripting – Fundamentals of Bash 4.4 by Sebastiaan Tammer: