I'm using the docker-py SDK and I need to pass some variables inside the containers.run
.
What I need:
MYDIR = '/variable/dir'
MYURL = 'https://example.com'
client = docker.from_env()
container = client.containers.run(image="alpine:latest", name="container", user="1000", volumes=['MYDIR:/tmp'], command=["/bin/sh", "echo MYURL"])
What I get: One error after other.
As you can see I need to put the variables inside the quotes of volumes and command.
I tried various combinations without any luck: with quotes, without them, using str concatenation, etc...
Any idea how to solve this?
Thanks in advance.
CodePudding user response:
You want to combine a string from a variable with another string. There are many ways to do this in Python. The latest way is called f-strings, which are very close to your "pass a variable inside quotes" in terms of syntax (although that's an oversimplification of what's actually happening).
For example:
container = client.containers.run(image="alpine:latest",
name="container", user="1000", volumes=[f'{MYDIR}/tmp'],
command=["/bin/sh", f"echo {MYURL}"])
Note that each string into which we have inserted a variable 1) begins with an f
before the opening quote marks (hence "f-strings"—the f
is for formatted) and 2) places the variable in {...}
brackets. You can actually use any expression inside the brackets, not just a single variable name.
CodePudding user response:
The key to solving your problem is understanding why this error occurred:
Bad Request ("create MYDIR/resources: "MYDIR/resources" includes invalid characters for a local volume name, only "[a-zA-Z0-9][a-zA-Z0-9_.-]" are allowed. If you intended to pass a host directory, use absolute path")
No where in this error actually requires you to "put the variables inside the quotes of volumes and command". What you actually need to do is to fix the path string (which you call 'quotes') to contain a valid volume name as specified by the regular expression in your error message.
Because you censored MYDIR, I cannot provide you further assistance as to why you might be getting the invalid volume name error. Perhaps you might have a path with unescaped spaces, etc...