Search code examples
bashdockerdocker-machine

How do I write a bash script to automate setting up ufw rules using docker-machine?


I have a shell script that looks like this:

echo "======> setting up firewall rules for $1 ..."   
docker-machine ssh $1 \
echo "y" | sudo ufw --force enable \
&& sudo ufw default deny incoming \
&& sudo ufw allow 22/tcp \
&& sudo ufw allow 2376/tcp \
&& sudo ufw allow 2377/tcp \
&& sudo ufw allow 7946/tcp \
&& sudo ufw allow 7946/udp \
&& sudo ufw allow 4789/udp \
&& sudo ufw reload \
&& sudo systemctl restart docker

The logging info after running each ufw command says "Skipping adding existing rule" even though this is a brand new instance. I am able to manually ssh into the Docker machine instance and run the same command with no trouble. How do I write a bash script to automate setting up ufw rules using docker-machine?


Solution

  • The docker-machine ssh command behaves similarly to the standard ssh command, namely it accepts the commands to run remotely.

    In your example, however, shell operators like | and && take precedence, i.e. they terminate the list of commands/arguments that the docker-machine ssh receives.

    One way of fixing this is to quote the list of commands you wish for docker-machine ssh to receive, for example like this:

    $ docker-machine ssh $1 \
    'echo "y" | sudo ufw --force enable \
    && sudo ufw default deny incoming \
    && sudo ufw allow 22/tcp ... '
    

    Another option is to escape all shell operators (\| and \&\&, even \(, \{, \;, etc).