-
Notifications
You must be signed in to change notification settings - Fork 5.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Interpolate environment variables #1765
Merged
mnowster
merged 4 commits into
docker:master
from
aanand:interpolate-environment-variables
Aug 6, 2015
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
from .config import ( | ||
DOCKER_CONFIG_KEYS, | ||
ConfigDetails, | ||
ConfigurationError, | ||
find, | ||
load, | ||
parse_environment, | ||
merge_environment, | ||
get_service_name_from_net, | ||
) # flake8: noqa |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
class ConfigurationError(Exception): | ||
def __init__(self, msg): | ||
self.msg = msg | ||
|
||
def __str__(self): | ||
return self.msg | ||
|
||
|
||
class CircularReference(ConfigurationError): | ||
def __init__(self, trail): | ||
self.trail = trail | ||
|
||
@property | ||
def msg(self): | ||
lines = [ | ||
"{} in {}".format(service_name, filename) | ||
for (filename, service_name) in self.trail | ||
] | ||
return "Circular reference:\n {}".format("\n extends ".join(lines)) | ||
|
||
|
||
class ComposeFileNotFound(ConfigurationError): | ||
def __init__(self, supported_filenames): | ||
super(ComposeFileNotFound, self).__init__(""" | ||
Can't find a suitable configuration file in this directory or any parent. Are you in the right directory? | ||
|
||
Supported filenames: %s | ||
""" % ", ".join(supported_filenames)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,86 @@ | ||
import os | ||
from string import Template | ||
|
||
import six | ||
|
||
from .errors import ConfigurationError | ||
|
||
import logging | ||
log = logging.getLogger(__name__) | ||
|
||
|
||
def interpolate_environment_variables(config): | ||
return dict( | ||
(service_name, process_service(service_name, service_dict)) | ||
for (service_name, service_dict) in config.items() | ||
) | ||
|
||
|
||
def process_service(service_name, service_dict): | ||
if not isinstance(service_dict, dict): | ||
raise ConfigurationError( | ||
'Service "%s" doesn\'t have any configuration options. ' | ||
'All top level keys in your docker-compose.yml must map ' | ||
'to a dictionary of configuration options.' % service_name | ||
) | ||
|
||
return dict( | ||
(key, interpolate_value(service_name, key, val)) | ||
for (key, val) in service_dict.items() | ||
) | ||
|
||
|
||
def interpolate_value(service_name, config_key, value): | ||
try: | ||
return recursive_interpolate(value) | ||
except InvalidInterpolation as e: | ||
raise ConfigurationError( | ||
'Invalid interpolation format for "{config_key}" option ' | ||
'in service "{service_name}": "{string}"' | ||
.format( | ||
config_key=config_key, | ||
service_name=service_name, | ||
string=e.string, | ||
) | ||
) | ||
|
||
|
||
def recursive_interpolate(obj): | ||
if isinstance(obj, six.string_types): | ||
return interpolate(obj, os.environ) | ||
elif isinstance(obj, dict): | ||
return dict( | ||
(key, recursive_interpolate(val)) | ||
for (key, val) in obj.items() | ||
) | ||
elif isinstance(obj, list): | ||
return map(recursive_interpolate, obj) | ||
else: | ||
return obj | ||
|
||
|
||
def interpolate(string, mapping): | ||
try: | ||
return Template(string).substitute(BlankDefaultDict(mapping)) | ||
except ValueError: | ||
raise InvalidInterpolation(string) | ||
|
||
|
||
class BlankDefaultDict(dict): | ||
def __init__(self, mapping): | ||
super(BlankDefaultDict, self).__init__(mapping) | ||
|
||
def __getitem__(self, key): | ||
try: | ||
return super(BlankDefaultDict, self).__getitem__(key) | ||
except KeyError: | ||
log.warn( | ||
"The {} variable is not set. Substituting a blank string." | ||
.format(key) | ||
) | ||
return "" | ||
|
||
|
||
class InvalidInterpolation(Exception): | ||
def __init__(self, string): | ||
self.string = string |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
17 changes: 17 additions & 0 deletions
17
tests/fixtures/environment-interpolation/docker-compose.yml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
web: | ||
# unbracketed name | ||
image: $IMAGE | ||
|
||
# array element | ||
ports: | ||
- "${HOST_PORT}:8000" | ||
|
||
# dictionary item value | ||
labels: | ||
mylabel: "${LABEL_VALUE}" | ||
|
||
# unset value | ||
hostname: "host-${UNSET_VALUE}" | ||
|
||
# escaped interpolation | ||
command: "$${ESCAPED}" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
test: | ||
image: busybox | ||
command: top | ||
volumes: | ||
- "~/${VOLUME_NAME}:/container-path" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@aanand a few tweaks:
Variable substitution
Your configuration options can contain environment variables. Compose uses the variable values from the shell environment in which
docker-compose
is run. Forexample, suppose the shell contains
POSTGRES_VERSION=9.3
and you supply this configuration:When you run
docker-compose up
with this configuration, Compose looks for thePOSTGRES_VERSION
environment variable in the shell and substitutes its value in. For this example, Compose resolves theimage
topostgres:9.3
before running the configuration.If an environment variable is not set, Compose substitutes with an empty
string. In the example above, if
POSTGRES_VERSION
is not set, the value forthe
image
option ispostgres:
.Both
$VARIABLE
and${VARIABLE}
syntax are supported. Extended shell-stylefeatures, such as
${VARIABLE-default}
and${VARIABLE/foo/bar}
, are notsupported.
If you need to put a literal dollar sign in a configuration value, use a double
dollar sign (
$$
).There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Updated.