Add --env option that sets environment variables in the launched command (not in the container)

This commit is contained in:
Adrian Kuschelyagi Malacoda 2020-08-19 02:48:47 -05:00
parent 2aec5cfc3b
commit 77935b49e8
2 changed files with 16 additions and 3 deletions

View File

@ -38,6 +38,9 @@ Path to build context to build the image from. This overrides `--image`/`OW_IMAG
### --volume=<volume>
Volume to map to the container. `~` is expanded automatically. If the directory exists in the user's home directory it will be created to ensure it has the correct ownership and permissions.
### --env=<key>=<value>
Set the environment variable `key` to `value` in the command. **Note that this does not set environment variables in the container itself**.
## Environment variables
### OW_IMAGE
Image to create the container with (default: `debian:stable`)

View File

@ -1,6 +1,7 @@
#!/usr/bin/env python3
from subprocess import call, check_call, check_output
from time import sleep
from itertools import chain
import os
import sys
import json
@ -60,8 +61,10 @@ def docker_create_user (container, user, uid=None):
def docker_start (container):
call(["docker", "start", container])
def docker_exec (container, command, user):
call(["docker", "exec", "--user", user, "-ti", container] + command)
def docker_exec (container, command, user, env={}):
call(["docker", "exec", "--user", user, "-ti"] + \
list(chain.from_iterable([["--env", f"{kv[0]}={kv[1]}"] for kv in env.items()])) + \
[container] + command)
def docker_commit (container, image_name):
call(["docker", "commit", container, image_name])
@ -116,6 +119,8 @@ command_user = user
user_volumes = USER_VOLUMES
pull = False
command_env = {}
quiet = False
while len(command) > 0:
arg = command[0]
@ -151,6 +156,11 @@ while len(command) > 0:
elif arg.startswith("--volume="):
user_volumes.append(arg[len("--volume="):])
command = command[1:]
elif arg.startswith("--env="):
env_pair = arg[len("--env="):]
(key, value) = env_pair.split("=", 1)
command_env[key] = value
command = command[1:]
elif arg == "--pull":
command = command[1:]
pull = True
@ -195,4 +205,4 @@ except Exception:
if not quiet:
print(f">> Welcome to {container_name} (IP {container['NetworkSettings']['IPAddress']})")
docker_exec(container_name, command, command_user)
docker_exec(container_name, command, command_user, command_env)