Repository: schickling/docker-hook Branch: master Commit: 64d2794bdb32 Files: 3 Total size: 8.0 KB Directory structure: gitextract_safltl9e/ ├── LICENSE ├── README.md └── docker-hook ================================================ FILE CONTENTS ================================================ ================================================ FILE: LICENSE ================================================ The MIT License (MIT) Copyright (c) 2015 Johannes Schickling Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # docker-hook > Automatic Docker Deployment via [Webhooks](https://docs.docker.com/docker-hub/repos/#webhooks) `docker-hook` listens to incoming HTTP requests and triggers your specified command. ## Features * No dependencies * Super lightweight * Dead **simple setup process** * Authentification support ## Setup ### 1. Prepare Your Server #### Download `docker-hook` No worries - it just downloads a Python script. There won't be anything installed or written elsewhere. ```sh $ curl https://raw.githubusercontent.com/schickling/docker-hook/master/docker-hook > /usr/local/bin/docker-hook; chmod +x /usr/local/bin/docker-hook ``` #### Start `docker-hook` ```sh $ docker-hook -t -c ``` ##### Auth-Token Please choose a secure `auth-token` string or generate one with `$ uuidgen`. Keep it safe or otherwise other people might be able to trigger the specified command. You can pass the `auth-token` as a command line argument, or set it as an environment variable. ##### Command The `command` can be any bash command of your choice. See the following [example](#example). This command will be triggered each time someone makes a HTTP request. ### 2. Configuration On Docker Hub Add a webhook like on the following image. `example.com` can be the domain of your server or its ip address. `docker-hook` listens to port `8555`. Please replace `my-super-safe-token` with your `auth-token`. ![](http://i.imgur.com/B6QyfmC.png) ## Example This example will stop the current running `yourname/app` container, pull the newest version and start a new container. ```sh $ docker-hook -t my-super-safe-token -c sh ./deploy.sh ``` If you want to store the authentication token as an environment variable, then run ```sh # Make sure there is no space before or after the `=` sign $ export DOCKER_AUTH_TOKEN= $ docker-hook -c sh ./deploy.sh ``` #### `deploy.sh` ```sh #! /bin/bash IMAGE="yourname/app" docker ps | grep $IMAGE | awk '{print $1}' | xargs docker stop docker pull $IMAGE docker run -d $IMAGE ``` You can now test it by pushing something to `yourname/app` or by running the following command where `yourdomain.com` is either a domain pointing to your server or just its ip address. ```sh $ curl -X POST yourdomain.com:8555/my-super-safe-token ``` ## How it works `docker-hook` is written in plain Python and does have **no further dependencies**. It uses `BaseHTTPRequestHandler` to listen for incoming HTTP requests from Docker Hub and then executes the provided [command](#command) if the [authentification](#auth-token) was successful. ## Caveat This tool was built as a proof-of-concept and might not be completly secure. If you have any improvement suggestions please open up an issue. ## License [MIT License](http://opensource.org/licenses/MIT) ================================================ FILE: docker-hook ================================================ #! /usr/bin/env python # -*- coding: utf-8 -*- """Automatic Docker Deployment via Webhooks.""" import json import os from subprocess import Popen from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter try: # For Python 3.0 and later from http.server import HTTPServer from http.server import BaseHTTPRequestHandler except ImportError: # Fall back to Python 2 from BaseHTTPServer import BaseHTTPRequestHandler from BaseHTTPServer import HTTPServer as HTTPServer import sys import logging import requests logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s', level=logging.DEBUG, stream=sys.stdout) class RequestHandler(BaseHTTPRequestHandler): """A POST request handler which expects a token in its path.""" def do_POST(self): logging.info("Path: %s", self.path) header_length = int(self.headers.getheader('content-length', "0")) json_payload = self.rfile.read(header_length) env = dict(os.environ) json_params = {} if len(json_payload) > 0: json_params = json.loads(json_payload) env.update(('REPOSITORY_' + var.upper(), str(val)) for var, val in json_params['repository'].items()) # Check if the secret URL was called token = args.token or os.environ.get("DOCKER_AUTH_TOKEN") if token == self.path[1:]: logging.info("Start executing '%s'" % args.cmd) try: Popen(args.cmd, env=env).wait() self.send_response(200, "OK") if 'callback_url' in json_params: # Make a callback to Docker Hub data = {'state': 'success'} headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} requests.post(json_params['callback_url'], data=json.dumps(data), headers=headers) except OSError as err: self.send_response(500, "OSError") logging.error("You probably didn't use 'sh ./script.sh'.") logging.error(err) if 'callback_url' in json_params: # Make a callback to Docker Hub data = {'state': 'failure', 'description': str(err)} headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} requests.post(json_params['callback_url'], data=json.dumps(data), headers=headers) else: self.send_response(401, "Not authorized") self.end_headers() def get_parser(): """Get a command line parser for docker-hook.""" parser = ArgumentParser(description=__doc__, formatter_class=ArgumentDefaultsHelpFormatter) parser.add_argument("-t", "--token", dest="token", required=False, help=("Secure auth token (can be choosen " "arbitrarily)")) parser.add_argument("-c", "--cmd", dest="cmd", required=True, nargs="*", help="Command to execute when triggered") parser.add_argument("--addr", dest="addr", default="0.0.0.0", help="address where it listens") parser.add_argument("--port", dest="port", type=int, default=8555, metavar="PORT", help="port where it listens") return parser def main(addr, port): """Start a HTTPServer which waits for requests.""" httpd = HTTPServer((addr, port), RequestHandler) httpd.serve_forever() if __name__ == '__main__': parser = get_parser() if len(sys.argv) == 1: parser.print_help() sys.exit(1) args = parser.parse_args() main(args.addr, args.port)