diff --git a/CHANGES/811.feature b/CHANGES/811.feature new file mode 100644 index 00000000..47c6e321 --- /dev/null +++ b/CHANGES/811.feature @@ -0,0 +1,3 @@ +Add support for Docker context endpoints. +Read files such as ~/.docker/context/meta.json and set the socket. +DOCKER_CONTEXT will be prioritized if it is set. diff --git a/aiodocker/docker.py b/aiodocker/docker.py index a07499ad..46d2fff2 100644 --- a/aiodocker/docker.py +++ b/aiodocker/docker.py @@ -76,6 +76,8 @@ def __init__( docker_host = url # rename if docker_host is None: docker_host = os.environ.get("DOCKER_HOST", None) + if docker_host is None: + docker_host = self._get_docker_context_host() if docker_host is None: for sockpath in _sock_search_paths: if sockpath.is_socket(): @@ -380,3 +382,22 @@ def _docker_machine_ssl_context() -> ssl.SSLContext: certfile=str(certs_path2 / "cert.pem"), keyfile=str(certs_path2 / "key.pem") ) return context + + @staticmethod + def _get_docker_context_host() -> Optional[str]: + current_context_name = os.environ.get("DOCKER_CONTEXT", None) + if current_context_name is None: + try: + docker_config_path = Path.home() / ".docker" / "config.json" + docker_config = json.loads(docker_config_path.read_bytes()) + except IOError: + return None + current_context_name = docker_config.get("currentContext", "default") + + for meta_path in (Path.home() / ".docker" / "contexts" / "meta").glob( + "*/meta.json" + ): + context_data = json.loads(meta_path.read_bytes()) + if context_data["Name"] == current_context_name: + return context_data["Endpoints"]["docker"]["Host"] + return None