{"id":28442024,"url":"https://github.com/ratulbasak/deploy-docker-swarm-using-terraform-ansible","last_synced_at":"2026-03-07T18:01:12.850Z","repository":{"id":181085828,"uuid":"107040324","full_name":"ratulbasak/deploy-docker-swarm-using-terraform-ansible","owner":"ratulbasak","description":null,"archived":false,"fork":false,"pushed_at":"2017-11-01T08:18:26.000Z","size":11819,"stargazers_count":23,"open_issues_count":1,"forks_count":19,"subscribers_count":4,"default_branch":"master","last_synced_at":"2025-06-29T03:43:49.601Z","etag":null,"topics":["ansible","automation","deployment","docker","docker-swarm","swarm-cluster","terraform"],"latest_commit_sha":null,"homepage":null,"language":"HCL","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ratulbasak.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"security-groups.tf","support":null,"governance":null}},"created_at":"2017-10-15T19:01:23.000Z","updated_at":"2023-11-14T22:31:10.000Z","dependencies_parsed_at":"2023-07-14T01:35:07.771Z","dependency_job_id":null,"html_url":"https://github.com/ratulbasak/deploy-docker-swarm-using-terraform-ansible","commit_stats":null,"previous_names":["ratulbasak/deploy-docker-swarm-using-terraform-ansible"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/ratulbasak/deploy-docker-swarm-using-terraform-ansible","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ratulbasak%2Fdeploy-docker-swarm-using-terraform-ansible","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ratulbasak%2Fdeploy-docker-swarm-using-terraform-ansible/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ratulbasak%2Fdeploy-docker-swarm-using-terraform-ansible/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ratulbasak%2Fdeploy-docker-swarm-using-terraform-ansible/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ratulbasak","download_url":"https://codeload.github.com/ratulbasak/deploy-docker-swarm-using-terraform-ansible/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ratulbasak%2Fdeploy-docker-swarm-using-terraform-ansible/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":30225404,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-03-07T17:00:40.062Z","status":"ssl_error","status_checked_at":"2026-03-07T17:00:39.026Z","response_time":53,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ansible","automation","deployment","docker","docker-swarm","swarm-cluster","terraform"],"created_at":"2025-06-06T05:39:31.517Z","updated_at":"2026-03-07T18:01:12.845Z","avatar_url":"https://github.com/ratulbasak.png","language":"HCL","funding_links":[],"categories":[],"sub_categories":[],"readme":"**docker-swarm-using-terraform-ansible**\n\nA node in a swarm cluster is any machine with docker engine installed and capable of hosting containers/services (When we run docker engine under swarm mode we often call applications as services). This is also referred as Docker node. A Docker node can be a physical machine or one or more virtual machines running on a physical host or cloud server. It is recommended to spread your docker nodes across multiple physical machines to provide availability and reliability for the applications running on the hosts. Docker Swarm environment consists of one or more manager nodes. To deploy an application on Docker Swarm we submit a request in the form of service definition to a manager node. Manager node performs orchestration and cluster management functions required to maintain the desired state of the farm. If there are multiple manager nodes in a swarm, the nodes elect a leader to conduct orchestration which implements leader election strategy.\n\nStep-1\nIn this post we can see how to install Terraform and how to setup the AWS account for working ahead. After installing Terraform and setting up AWS account go to the next step.\nNOTE: You need to create and download a key-pair using aws management console. Mine is : docker-key.pem\n\nStep-2\nCreate a directory named swarm-deploy. create three files named variable.tf, security-groups.tf, main.tf and output.tf. In variable.tf file add the following\n\n```\n### variable.tf\nvariable \"aws_region\" {\n  description = \"AWS region on which we will setup the swarm cluster\"\n  default = \"eu-west-1\"\n}\nvariable \"ami\" {\n  description = \"Amazon Linux AMI\"\n  default = \"ami-04d10c7d\"\n}\nvariable \"instance_type\" {\n  description = \"Instance type\"\n  default = \"t2.micro\"\n}\nvariable \"key_path\" {\n  description = \"SSH Public Key path\"\n  default = \"/path-to-keyfile/docker-key.pem\"\n}\nvariable \"key_name\" {\n  description = \"Desired name of Keypair...\"\n  default = \"docker-key\"\n}\nvariable \"bootstrap_path\" {\n  description = \"Script to install Docker Engine\"\n  default = \"install_docker_machine_compose.sh\"\n}\n```\n\nIn this file I’m using region eu-west-1 and Ubuntu-16.04 amazon machine image. You can set yours… :)\nIn security-groups.tf file add the following\n\n```\n### security-groups.tf\nresource \"aws_security_group\" \"sgswarm\" {\n  name = \"sgswarm\"\n  tags {\n        Name = \"sgswarm\"\n  }\n# Allow all inbound\n  ingress {\n    from_port   = 0\n    to_port     = 65535\n    protocol    = \"tcp\"\n    cidr_blocks = [\"0.0.0.0/0\"]\n  }\negress {\n    from_port   = 0\n    to_port     = 65535\n    protocol    = \"tcp\"\n    cidr_blocks = [\"0.0.0.0/0\"]\n  }\n# Enable ICMP\n  ingress {\n    from_port = -1\n    to_port = -1\n    protocol = \"icmp\"\n    cidr_blocks = [\"0.0.0.0/0\"]\n  }\n}\n```\n\nIn main.tf add the following\n\n```\n### main.tf\n# Specify the provider and access details\nprovider \"aws\" {\n  access_key = \"your-aws-access-key\"\n  secret_key = \"your-aws-secret-access-key\"\n  region = \"${var.aws_region}\"\n}\nresource \"aws_instance\" \"master\" {\n  ami = \"${var.ami}\"\n  instance_type = \"${var.instance_type}\"\n  key_name = \"${var.key_name}\"\n  user_data = \"${file(\"${var.bootstrap_path}\")}\"\n  vpc_security_group_ids = [\"${aws_security_group.sgswarm.id}\"]\ntags {\n    Name  = \"master\"\n  }\n}\nresource \"aws_instance\" \"worker1\" {\n  ami = \"${var.ami}\"\n  instance_type = \"${var.instance_type}\"\n  key_name = \"${var.key_name}\"\n  user_data = \"${file(\"${var.bootstrap_path}\")}\"\n  vpc_security_group_ids = [\"${aws_security_group.sgswarm.id}\"]\ntags {\n    Name  = \"worker 1\"\n  }\n}\nresource \"aws_instance\" \"worker2\" {\n  ami = \"${var.ami}\"\n  instance_type = \"${var.instance_type}\"\n  key_name = \"${var.key_name}\"\n  user_data = \"${file(\"${var.bootstrap_path}\")}\"\n  vpc_security_group_ids = [\"${aws_security_group.sgswarm.id}\"]\ntags {\n    Name  = \"worker 2\"\n  }\n}\n```\n\nIn output.tf file add the following\n\n```\n### output.tf\noutput \"master_public_ip\" {\n    value = [\"${aws_instance.master.public_ip}\"]\n}\noutput \"worker1_public_ip\" {\n    value = [\"${aws_instance.worker1.public_ip}\"]\n}\noutput \"worker2_public_ip\" {\n    value = [\"${aws_instance.worker2.public_ip}\"]\n}\n```\n\nStep-3\nCreate a shell script named install_docker_machine_compose.sh which will install docker. This script will execute in the provision time of EC2…\n\n```\n#!/bin/bash\nexport LC_ALL=C\nsudo apt-get update -y\n#sudo apt-get upgrade -y\n### install python-minimal\nsudo apt-get install python-minimal -y\n# install docker-engine\ncurl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -\nsudo add-apt-repository \"deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable\"\nsudo apt-get update\nsudo apt-get install -y docker-ce\necho \"Docker installed...\"\nsudo usermod -aG docker ${whoami}\nsudo systemctl enable docker\nsudo systemctl start docker\necho \"########################################\"\necho \"########################################\"\necho \"##################### install docker-compose ########################\"\nsudo curl -L https://github.com/docker/compose/releases/download/1.16.1/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose\nsudo chmod +x /usr/local/bin/docker-compose\ndocker-compose --version\necho \"docker-compose installed...\"\necho \"########################################\"\necho \"########################################\"\necho \"#################### install docker-machine #########################\"\ncurl -L https://github.com/docker/machine/releases/download/v0.12.2/docker-machine-`uname -s`-`uname -m` \u003e/tmp/docker-machine\nchmod +x /tmp/docker-machine\nsudo cp /tmp/docker-machine /usr/local/bin/docker-machine\necho \"docker-machine installed...\"\n```\n\nStep-4\nInstall Ansible\n\n```\n$ sudo apt-add-repository ppa:ansible/ansible\nPress ENTER to accept the PPA addition.\n$ sudo apt-get update\n$ sudo apt-get install ansible\n```\n\nStep-5\nThere are a couple of ways of setting up a swarm cluster. You can create a cluster using any virtualized environments like Hyper-V, virtual box. The number of hosts running in a swarm cluster will be restricted to the host’s CPU and memory capacity. Traditionally on premise environments are setup using multiple physical nodes. The second way of setting up swarm environment is by using hosted environments like Azure or AWS.\n\nWe’ll create ansible script for creating swarm cluster(a manager node and two worker nodes). Create a file named playbook.yml in the same swarm-deploy directory and add the following\n\n```\n### playbook.yml\n---\n  - name: Init Swarm Master\n    hosts: masters\n    become: true\n    gather_facts: False\n    remote_user: ubuntu\n    tasks:\n      - name: Swarm Init\n        command: sudo usermod -aG docker {{remote_user}}\n        command: docker swarm init --advertise-addr {{ inventory_hostname }}\n- name: Get Worker Token\n        command: docker swarm join-token worker -q\n        register: worker_token\n- name: Show Worker Token\n        debug: var=worker_token.stdout\n- name: Master Token\n        command: docker swarm join-token manager -q\n        register: master_token\n- name: Show Master Token\n        debug: var=master_token.stdout\n- name: Join Swarm Cluster\n    hosts: workers\n    become: true\n    remote_user: ubuntu\n    gather_facts: False\n    vars:\n      token: \"{{ hostvars[groups['masters'][0]]['worker_token']['stdout'] }}\"\n      master: \"{{ hostvars[groups['masters'][0]]['inventory_hostname'] }}\"\n    tasks:\n      - name: Join Swarm Cluster as a Worker\n        command: sudo usermod -aG docker {{remote_user}}\n        command: sudo docker swarm join --token {{ token }} {{ master }}:2377\n        register: worker\n- name: Show Results\n        debug: var=worker.stdout\n- name: Show Errors\n        debug: var=worker.stderr\n```\n        \n        \nCreate a directory named inventory and a file named hosts under inventory folder. Change the public ip and key-file-path which you’ll get after running the terraform apply command.\n\n```\n[masters]\n52.51.138.1 ansible_user=ubuntu ansible_private_key_file=/path-to-your-keyfile/docker-key.pem\n[workers]\n34.240.19.111 ansible_user=ubuntu ansible_private_key_file=/path-to-your-keyfile/docker-key.pem\n52.208.83.236 ansible_user=ubuntu ansible_private_key_file=/path-to-your-keyfile/docker-key.pem\n```\n\n\nStep-6\nAll the configuration files and scripts are now set. Run the following commands to deploy three instances using terraform and to create swarm cluser using ansible in those intances.\n\n```\n$ terraform init\n$ terraform plan\n$ terraform apply\n```\n```\n$ ansible-playbook -i inventory/hosts playbook.yml\n```\n\nOur swarm cluster is ready. Let’s check the cluster using ssh in manager node.\n\n```\n$ ssh -i your_key_file.pem ubuntu@manager_public_ip\n\n$ sudo docker node ls\n```\n\nThat’s all.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fratulbasak%2Fdeploy-docker-swarm-using-terraform-ansible","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fratulbasak%2Fdeploy-docker-swarm-using-terraform-ansible","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fratulbasak%2Fdeploy-docker-swarm-using-terraform-ansible/lists"}