Setup Docker Swarm on AWS using Ansible & Terraform

This post is part of “IaC” series explaining how to use Infrastracture as Code concepts with Terraform. In this part, I will show you how to setup a Swarm cluster on AWS using Ansible & Terraform as shown in the diagram below (1 Master and 2 Workers) in less than 1 min ⏱:

 

All the templates and playbooks used in this tutorial, can be found on my Github. 😎

Note: I did some tutorials about how to get started with Terraform on AWS, so make sure you read it before you go through this post.

1 – Setup EC2 Cluster using Terraform

1.1 – Global Variables

This file contains environment specific configuration like region name, instance type …

1.2 – Config AWS as Provider

1.3 – Security Group

This SG allows all the inbound/outbound traffic:

1.4 – EC2 Instances

Bootstrap script to install latest version of Docker:

2 – Transform to Swarm Cluster with Ansible

The playbook is self explanatory:

Now we defined all the required templates and playbook, we only need to type 2 commands to bring up the swarm cluster:

Note: Make sure to update the hosts file with the public ip of each EC2 instance.

Setting up the Swarm cluster in action is show below 😃 :