Skip to content

Instantly share code, notes, and snippets.

@AndreLouisCaron
Created July 7, 2017 17:22
Show Gist options
  • Select an option

  • Save AndreLouisCaron/a6f9654b7001e0747e205ccf930f23f2 to your computer and use it in GitHub Desktop.

Select an option

Save AndreLouisCaron/a6f9654b7001e0747e205ccf930f23f2 to your computer and use it in GitHub Desktop.
Find IDs of containers that we can network to.
# -*- coding: utf-8 -*-
import docker
import os
import re
def readfile(path):
"""Read a UTF-8 encoded text file from disk."""
with open(path, 'rb') as stream:
return stream.read().decode('utf-8')
def container_id():
"""Find the ID of the current container."""
# TODO: switch to the "CID file" when the compose file syntax supports it.
mountinfo = readfile('/proc/self/mountinfo')
mountinfo = [line.strip() for line in mountinfo.split('\n')]
for line in mountinfo:
match = re.search(r'/docker/(\w{64})\s+', line)
if match:
return match.group(1)
raise ValueError('Could not detect container ID!')
def reachable_networks(container_id):
"""Find the IDs of networks the container is attached to."""
# We need to use the low-level API because the "high-level" API doesn't
# allow us to query the networks accessible to a container.
client = docker.APIClient(
base_url='unix://var/run/docker.sock',
version=os.environ.get('DOCKER_API_VERSION', 'auto'),
)
container = client.inspect_container(container_id)
return set(
network['NetworkID']
for network in container['NetworkSettings']['Networks'].values()
)
container = container_id()
print('Container ID:', container)
print('Network IDs:', sorted(reachable_networks(container)))
client = docker.from_env(
version=os.environ.get('DOCKER_API_VERSION', 'auto')
)
# Locate all containers in our networks.
reachable_containers = {}
for network_id in reachable_networks(container):
network = client.networks.get(network_id)
for container in network.containers:
reachable_containers[container.id] = container
print('Reachable containers:', reachable_containers.keys())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment