Skip to content

Instantly share code, notes, and snippets.

@hairyhenderson
Last active April 19, 2019 15:09
Show Gist options
  • Save hairyhenderson/568ff7fb3e1a36b2ea196e2e11ea15c8 to your computer and use it in GitHub Desktop.
Save hairyhenderson/568ff7fb3e1a36b2ea196e2e11ea15c8 to your computer and use it in GitHub Desktop.
A helper script to connect to a Docker for AWS manager node for running `docker` commands
#!/bin/bash
#
# A helper script to connect to a Docker for AWS manager node for running `docker` commands
#
# There's a few things going on here:
# 1. it figures out a swarm manager's address using the AWS API
# 2. it controls an SSH tunnel to Docker's API socket on that manager node, so that `docker` commands (such as `docker stack deploy`)
# can be directed at that node
#
# Prerequisites:
# - the `aws` cli must be installed and configured
# - `jq` must be installed
#
set -e
cfn_stack_name="NAME OF YOUR D4AWS STACK"
ssh_key_loc="/path/to/private/ssh/key/for/d4aws/stack"
# Generates random filenames for the SSH configuration and the SSH control socket, not entirely necessary ;)
export _sshconfig=$(mktemp -u)
export _ssh_ctrl_socket=$(mktemp -u)
# use aws cli and jq to choose a manager node to communciate with
jqScript=".AutoScalingGroups[] | select(.Tags[].Value == \"${cfn_stack_name}-Manager\").Instances[] | select(.HealthStatus == \"Healthy\").InstanceId"
manager_id=$(aws autoscaling describe-auto-scaling-groups | jq -r "${jqScript}" | head -n1)
manager=$(aws ec2 describe-instances --instance-ids ${manager_id} | jq -r '.Reservations[].Instances[].PublicDnsName')
# Create a temporary SSH configuration for this session
cat <<EOF > ${_sshconfig}
User docker
LogLevel error
StrictHostKeyChecking no
UserKnownHostsFile=/dev/null
IdentityFile ${ssh_key_loc}
ControlPath ${_ssh_ctrl_socket}
EOF
# Set up an SSH control socket for tunneling, so that we can cleanly close it when we're done
ssh -M -F ${_sshconfig} \
-fnNT -L localhost:2374:/var/run/docker.sock ${manager}
# configure all `docker` commands to communicate through the SSH tunnel instead of any local docker engine
export DOCKER_HOST=localhost:2374
# now run `docker` commands as normal, for example:
docker info
docker node ls
docker stack deploy -c docker-compose.yml foo
# Close the tunnel
ssh -F ${_sshconfig} -O exit -
# remove the temporary SSH-related files
rm -f ${_sshconfig} ${_ssh_ctrl_socket}
unset DOCKER_HOST
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment