Question: I have the Docker Swarm cluster setup in my preprod servers(3 manager node and 7 worker nodes); however I would like to replicate the same in Production servers but rather than using commands I prefer using a script.

At present I am using "docker swarm init" to initialize the swarm and then adding the workers and managers with the generated key.

I would have 30 servers and planning for 7 manager and 23 worker nodes.
I have searched the net; but could not find any script which can initialize the docker swarm automatically with a script in all the servers.

Any help would really appreciated.

Answer: 
The way I approached this was to have a common build script for all nodes, and to use [Consul](https://www.consul.io) for sharing the docker swarm manager token with the rest of the cluster. 

The first node (at `10.0.0.51`) calls `docker swarm init` and places the token in the key value store, and the remaining nodes (at `10.0.0.52` onwards) read the token back and use it to call `docker swarm join`. 

The bash looked something like this -

```
# Get the node id of this machine from the local IP address
privateNetworkIP=`hostname -I | grep -o 10.0.0.5.`
nodeId=`(echo $privateNetworkIP | tail -c 2)`

if [ $nodeId -eq 1 ]; then

    sudo docker swarm init
    MANAGER_KEY_IN=`sudo docker swarm join-token manager -q`
    curl --request PUT --data $MANAGER_KEY_IN http://10.0.0.51:8500/v1/kv/docker-manager-key

else 

    MANAGER_KEY_OUT=`curl -s http://10.0.0.51:8500/v1/kv/docker-manager-key?raw`
    sudo docker swarm join --token $MANAGER_KEY_OUT 10.0.0.51:2377

fi

```

... and works fine provided that `node 1` is built first.
There is nothing like in-built utilities for that you can use the command like this :

You can create your custom script like this :

```
for i in `cat app_server.txt` ; do echo $i ; ssh -i /path/to/your_key.pem  $i "sudo docker swarm join --token your-token-here ip-address-of-manager:port" ; done

```

Here `app_server.txt` is the ip address of your worker node that you want to add in your swarm.

`--token` : your token generated by manager on `docker swarm init`

Hope this may help.

You can also use ansible for the same but that require ansible docker modules installed on all the worker nodes.
Thank you!