我正在尝试针对docker-machine云提供程序运行命令,因此我需要获取命令docker-machine env digitalocean
的内容,这通常如下所示:
export DOCKER_TLS_VERIFY="1"
export DOCKER_HOST="tcp://1.2.3.4:2376"
export DOCKER_CERT_PATH="/Users/danh/.docker/machine/machines/digitalocean"
export DOCKER_MACHINE_NAME="digitalocean"
# Run this command to configure your shell:
# eval "$(docker-machine env digitalocean)"
并使用上面的shell前缀,例如:
print 'outside with:' + local('echo $DOCKER_HOST')
with prefix(local('docker-machine env digitalocean', capture=True)):
print 'inside with:' + local('echo $DOCKER_HOST')
with prefix('DOCKER_HOST="tcp://1.2.3.4:2376"'):
print 'inside with (manual):' + local('echo $DOCKER_HOST')
然而,这会返回:
outside with:tcp://192.168.99.100:2376
inside with:
inside with (manual):tcp://1.2.3.4:2376
我能看到的唯一方法就是手动分开local('docker-machine env digitalocean')
的结果。当然,还有更多的面料风格呢?
答案 0 :(得分:1)
嗯,这是我到目前为止的解决方案,虽然感觉有点hacky:
def dm_env(machine):
"""
Sets the environment to use a given docker machine.
"""
_env = local('docker-machine env {}'.format(machine), capture=True)
# Reorganize into a string that could be used with prefix().
_env = re.sub(r'^#.*$', '', _env, flags=re.MULTILINE) # Remove comments
_env = re.sub(r'^export ', '', _env, flags=re.MULTILINE) # Remove `export `
_env = re.sub(r'\n', ' ', _env, flags=re.MULTILINE) # Merge to a single line
return _env
@task
def blah():
print 'outside with: ' + local('echo $DOCKER_HOST')
with prefix(dm_env('digitalocean')):
print 'inside with: ' + local('echo $DOCKER_HOST')
输出:
outside with: tcp://192.168.99.100:2376
inside with: tcp://1.2.3.4:2376
答案 1 :(得分:1)
获取所需信息的另一种方法是使用格式化模板来输出docker-machine inspect
命令,以及shown in the documentation。
请注意,Python字符串中的花括号需要通过加倍来转义,因此每次最终都会有四个开始和结束括号。
machine_name = dev
machine_ip = local("docker-machine inspect --format='{{{{.Driver.IPAddress}}}}' {0}".format(machine_name), capture=True)
machine_port = local("docker-machine inspect --format='{{{{.Driver.EnginePort}}}}' {0}".format(machine_name), capture=True)
machine_cert_path = local("docker-machine inspect --format='{{{{.HostOptions.AuthOptions.StorePath}}}}' {0}".format(machine), capture=True)
现在,您可以使用shell_env context manager通过设置相应的环境变量暂时将Docker守护程序指向远程计算机:
from fabric.api import shell_env
with shell_env(DOCKER_TLS_VERIFY='1',
DOCKER_HOST='tcp://{0}:{1}'.format(machine_ip, machine_port),
DOCKER_CERT_PATH=machine_cert_path,
DOCKER_MACHINE_NAME=machine_name):
# will print containers on the remote machine
local('docker ps -a')
# will print containers on your local machine
# since environment switch is only valid within the context manager
local('docker ps -a')