-3

I'm trying OS env variables to be used in python code. Below is example.

Env Variable


    export DOCKER_HOST=10.0.0.5
    export PORT=1002

Python code


    import os 
    import docker 
    host = os.environ['DOCKER_HOST']
    port = os.environ['PORT']
    client = docker.APIClient(base_url='tcp://host:port')

It is supposed to inject the variables of host and port but its not working. I tried to add .format which is helpless

Error

raceback (most recent call last):
  File "./update.py", line 24, in 
    client = docker.APIClient(base_url="tcp://docker_host:docker_port")
  File "/usr/local/lib/python2.7/dist-packages/docker/api/client.py", line 109, in __init__
    base_url, IS_WINDOWS_PLATFORM, tls=bool(tls)
  File "/usr/local/lib/python2.7/dist-packages/docker/utils/utils.py", line 363, in parse_host
    "Invalid port: {0}".format(addr)
docker.errors.DockerException: Invalid port: docker_host:docker_port
Swaroop Kundeti
  • 515
  • 4
  • 11
  • 25
  • 1
    Possible duplicate of [Access environment variables from Python](https://stackoverflow.com/questions/4906977/access-environment-variables-from-python) – skrrgwasme Sep 15 '17 at 20:49
  • I know - the possible duplicate I flagged recommends that you do exactly what you're already doing. But you didn't give us any information that would tell us why "it's not working." What exactly is happening? Do you know for sure the variables exist? – skrrgwasme Sep 15 '17 at 20:51
  • You have to do the string formatting for example like this: `base_url='tcp://{host}:{port}'.format(host=host, port=port)` – code_onkel Sep 15 '17 at 21:26

1 Answers1

2

Your issue is below

client = docker.APIClient(base_url='tcp://host:port')

You are using host:port as literal strings. Python doesn't have string interpolation until Python 3.6. You can use one of below ways

client = docker.APIClient(base_url='tcp://' + host + ':' + port)
client = docker.APIClient(base_url='tcp://{}:{}'.format(host,port))
client = docker.APIClient(base_url='tcp://{0}:{1}'.format(host,port))
client = docker.APIClient(base_url='tcp://{host}:{port}'.format(host=host,port=port))
client = docker.APIClient(base_url='tcp://%s:%s' % (host,port))

Edit-1

Thanks to @code_onkel for pointing out the string interpolation in Python 3.6 (had not used it earlier). You can also use below if you are using Python 3.6.X

client = docker.APIClient(base_url=f'tcp://{host}:{port}')

The f before the string is important. Please refer to PEP 498 for more details

Tarun Lalwani
  • 142,312
  • 9
  • 204
  • 265