repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
cloudtools/stacker | stacker/hooks/ecs.py | create_clusters | def create_clusters(provider, context, **kwargs):
"""Creates ECS clusters.
Expects a "clusters" argument, which should contain a list of cluster
names to create.
Args:
provider (:class:`stacker.providers.base.BaseProvider`): provider
instance
context (:class:`stacker.context.Context`): context instance
Returns: boolean for whether or not the hook succeeded.
"""
conn = get_session(provider.region).client('ecs')
try:
clusters = kwargs["clusters"]
except KeyError:
logger.error("setup_clusters hook missing \"clusters\" argument")
return False
if isinstance(clusters, basestring):
clusters = [clusters]
cluster_info = {}
for cluster in clusters:
logger.debug("Creating ECS cluster: %s", cluster)
r = conn.create_cluster(clusterName=cluster)
cluster_info[r["cluster"]["clusterName"]] = r
return {"clusters": cluster_info} | python | def create_clusters(provider, context, **kwargs):
"""Creates ECS clusters.
Expects a "clusters" argument, which should contain a list of cluster
names to create.
Args:
provider (:class:`stacker.providers.base.BaseProvider`): provider
instance
context (:class:`stacker.context.Context`): context instance
Returns: boolean for whether or not the hook succeeded.
"""
conn = get_session(provider.region).client('ecs')
try:
clusters = kwargs["clusters"]
except KeyError:
logger.error("setup_clusters hook missing \"clusters\" argument")
return False
if isinstance(clusters, basestring):
clusters = [clusters]
cluster_info = {}
for cluster in clusters:
logger.debug("Creating ECS cluster: %s", cluster)
r = conn.create_cluster(clusterName=cluster)
cluster_info[r["cluster"]["clusterName"]] = r
return {"clusters": cluster_info} | [
"def",
"create_clusters",
"(",
"provider",
",",
"context",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"get_session",
"(",
"provider",
".",
"region",
")",
".",
"client",
"(",
"'ecs'",
")",
"try",
":",
"clusters",
"=",
"kwargs",
"[",
"\"clusters\"",
... | Creates ECS clusters.
Expects a "clusters" argument, which should contain a list of cluster
names to create.
Args:
provider (:class:`stacker.providers.base.BaseProvider`): provider
instance
context (:class:`stacker.context.Context`): context instance
Returns: boolean for whether or not the hook succeeded. | [
"Creates",
"ECS",
"clusters",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/hooks/ecs.py#L15-L45 | train | 214,600 |
cloudtools/stacker | stacker/blueprints/base.py | build_parameter | def build_parameter(name, properties):
"""Builds a troposphere Parameter with the given properties.
Args:
name (string): The name of the parameter.
properties (dict): Contains the properties that will be applied to the
parameter. See:
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html
Returns:
:class:`troposphere.Parameter`: The created parameter object.
"""
p = Parameter(name, Type=properties.get("type"))
for name, attr in PARAMETER_PROPERTIES.items():
if name in properties:
setattr(p, attr, properties[name])
return p | python | def build_parameter(name, properties):
"""Builds a troposphere Parameter with the given properties.
Args:
name (string): The name of the parameter.
properties (dict): Contains the properties that will be applied to the
parameter. See:
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html
Returns:
:class:`troposphere.Parameter`: The created parameter object.
"""
p = Parameter(name, Type=properties.get("type"))
for name, attr in PARAMETER_PROPERTIES.items():
if name in properties:
setattr(p, attr, properties[name])
return p | [
"def",
"build_parameter",
"(",
"name",
",",
"properties",
")",
":",
"p",
"=",
"Parameter",
"(",
"name",
",",
"Type",
"=",
"properties",
".",
"get",
"(",
"\"type\"",
")",
")",
"for",
"name",
",",
"attr",
"in",
"PARAMETER_PROPERTIES",
".",
"items",
"(",
... | Builds a troposphere Parameter with the given properties.
Args:
name (string): The name of the parameter.
properties (dict): Contains the properties that will be applied to the
parameter. See:
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html
Returns:
:class:`troposphere.Parameter`: The created parameter object. | [
"Builds",
"a",
"troposphere",
"Parameter",
"with",
"the",
"given",
"properties",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/blueprints/base.py#L98-L114 | train | 214,601 |
cloudtools/stacker | stacker/blueprints/base.py | validate_variable_type | def validate_variable_type(var_name, var_type, value):
"""Ensures the value is the correct variable type.
Args:
var_name (str): The name of the defined variable on a blueprint.
var_type (type): The type that the value should be.
value (obj): The object representing the value provided for the
variable
Returns:
object: Returns the appropriate value object. If the original value
was of CFNType, the returned value will be wrapped in CFNParameter.
Raises:
ValueError: If the `value` isn't of `var_type` and can't be cast as
that type, this is raised.
"""
if isinstance(var_type, CFNType):
value = CFNParameter(name=var_name, value=value)
elif isinstance(var_type, TroposphereType):
try:
value = var_type.create(value)
except Exception as exc:
name = "{}.create".format(var_type.resource_name)
raise ValidatorError(var_name, name, value, exc)
else:
if not isinstance(value, var_type):
raise ValueError(
"Value for variable %s must be of type %s. Actual "
"type: %s." % (var_name, var_type, type(value))
)
return value | python | def validate_variable_type(var_name, var_type, value):
"""Ensures the value is the correct variable type.
Args:
var_name (str): The name of the defined variable on a blueprint.
var_type (type): The type that the value should be.
value (obj): The object representing the value provided for the
variable
Returns:
object: Returns the appropriate value object. If the original value
was of CFNType, the returned value will be wrapped in CFNParameter.
Raises:
ValueError: If the `value` isn't of `var_type` and can't be cast as
that type, this is raised.
"""
if isinstance(var_type, CFNType):
value = CFNParameter(name=var_name, value=value)
elif isinstance(var_type, TroposphereType):
try:
value = var_type.create(value)
except Exception as exc:
name = "{}.create".format(var_type.resource_name)
raise ValidatorError(var_name, name, value, exc)
else:
if not isinstance(value, var_type):
raise ValueError(
"Value for variable %s must be of type %s. Actual "
"type: %s." % (var_name, var_type, type(value))
)
return value | [
"def",
"validate_variable_type",
"(",
"var_name",
",",
"var_type",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"var_type",
",",
"CFNType",
")",
":",
"value",
"=",
"CFNParameter",
"(",
"name",
"=",
"var_name",
",",
"value",
"=",
"value",
")",
"elif",
... | Ensures the value is the correct variable type.
Args:
var_name (str): The name of the defined variable on a blueprint.
var_type (type): The type that the value should be.
value (obj): The object representing the value provided for the
variable
Returns:
object: Returns the appropriate value object. If the original value
was of CFNType, the returned value will be wrapped in CFNParameter.
Raises:
ValueError: If the `value` isn't of `var_type` and can't be cast as
that type, this is raised. | [
"Ensures",
"the",
"value",
"is",
"the",
"correct",
"variable",
"type",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/blueprints/base.py#L117-L150 | train | 214,602 |
cloudtools/stacker | stacker/blueprints/base.py | validate_allowed_values | def validate_allowed_values(allowed_values, value):
"""Support a variable defining which values it allows.
Args:
allowed_values (Optional[list]): A list of allowed values from the
variable definition
value (obj): The object representing the value provided for the
variable
Returns:
bool: Boolean for whether or not the value is valid.
"""
# ignore CFNParameter, troposphere handles these for us
if not allowed_values or isinstance(value, CFNParameter):
return True
return value in allowed_values | python | def validate_allowed_values(allowed_values, value):
"""Support a variable defining which values it allows.
Args:
allowed_values (Optional[list]): A list of allowed values from the
variable definition
value (obj): The object representing the value provided for the
variable
Returns:
bool: Boolean for whether or not the value is valid.
"""
# ignore CFNParameter, troposphere handles these for us
if not allowed_values or isinstance(value, CFNParameter):
return True
return value in allowed_values | [
"def",
"validate_allowed_values",
"(",
"allowed_values",
",",
"value",
")",
":",
"# ignore CFNParameter, troposphere handles these for us",
"if",
"not",
"allowed_values",
"or",
"isinstance",
"(",
"value",
",",
"CFNParameter",
")",
":",
"return",
"True",
"return",
"value... | Support a variable defining which values it allows.
Args:
allowed_values (Optional[list]): A list of allowed values from the
variable definition
value (obj): The object representing the value provided for the
variable
Returns:
bool: Boolean for whether or not the value is valid. | [
"Support",
"a",
"variable",
"defining",
"which",
"values",
"it",
"allows",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/blueprints/base.py#L153-L170 | train | 214,603 |
cloudtools/stacker | stacker/blueprints/base.py | parse_user_data | def parse_user_data(variables, raw_user_data, blueprint_name):
"""Parse the given user data and renders it as a template
It supports referencing template variables to create userdata
that's supplemented with information from the stack, as commonly
required when creating EC2 userdata files.
For example:
Given a raw_user_data string: 'open file ${file}'
And a variables dictionary with: {'file': 'test.txt'}
parse_user_data would output: open file test.txt
Args:
variables (dict): variables available to the template
raw_user_data (str): the user_data to be parsed
blueprint_name (str): the name of the blueprint
Returns:
str: The parsed user data, with all the variables values and
refs replaced with their resolved values.
Raises:
InvalidUserdataPlaceholder: Raised when a placeholder name in
raw_user_data is not valid.
E.g ${100} would raise this.
MissingVariable: Raised when a variable is in the raw_user_data that
is not given in the blueprint
"""
variable_values = {}
for key, value in variables.items():
if type(value) is CFNParameter:
variable_values[key] = value.to_parameter_value()
else:
variable_values[key] = value
template = string.Template(raw_user_data)
res = ""
try:
res = template.substitute(variable_values)
except ValueError as exp:
raise InvalidUserdataPlaceholder(blueprint_name, exp.args[0])
except KeyError as key:
raise MissingVariable(blueprint_name, key)
return res | python | def parse_user_data(variables, raw_user_data, blueprint_name):
"""Parse the given user data and renders it as a template
It supports referencing template variables to create userdata
that's supplemented with information from the stack, as commonly
required when creating EC2 userdata files.
For example:
Given a raw_user_data string: 'open file ${file}'
And a variables dictionary with: {'file': 'test.txt'}
parse_user_data would output: open file test.txt
Args:
variables (dict): variables available to the template
raw_user_data (str): the user_data to be parsed
blueprint_name (str): the name of the blueprint
Returns:
str: The parsed user data, with all the variables values and
refs replaced with their resolved values.
Raises:
InvalidUserdataPlaceholder: Raised when a placeholder name in
raw_user_data is not valid.
E.g ${100} would raise this.
MissingVariable: Raised when a variable is in the raw_user_data that
is not given in the blueprint
"""
variable_values = {}
for key, value in variables.items():
if type(value) is CFNParameter:
variable_values[key] = value.to_parameter_value()
else:
variable_values[key] = value
template = string.Template(raw_user_data)
res = ""
try:
res = template.substitute(variable_values)
except ValueError as exp:
raise InvalidUserdataPlaceholder(blueprint_name, exp.args[0])
except KeyError as key:
raise MissingVariable(blueprint_name, key)
return res | [
"def",
"parse_user_data",
"(",
"variables",
",",
"raw_user_data",
",",
"blueprint_name",
")",
":",
"variable_values",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"variables",
".",
"items",
"(",
")",
":",
"if",
"type",
"(",
"value",
")",
"is",
"CFNPa... | Parse the given user data and renders it as a template
It supports referencing template variables to create userdata
that's supplemented with information from the stack, as commonly
required when creating EC2 userdata files.
For example:
Given a raw_user_data string: 'open file ${file}'
And a variables dictionary with: {'file': 'test.txt'}
parse_user_data would output: open file test.txt
Args:
variables (dict): variables available to the template
raw_user_data (str): the user_data to be parsed
blueprint_name (str): the name of the blueprint
Returns:
str: The parsed user data, with all the variables values and
refs replaced with their resolved values.
Raises:
InvalidUserdataPlaceholder: Raised when a placeholder name in
raw_user_data is not valid.
E.g ${100} would raise this.
MissingVariable: Raised when a variable is in the raw_user_data that
is not given in the blueprint | [
"Parse",
"the",
"given",
"user",
"data",
"and",
"renders",
"it",
"as",
"a",
"template"
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/blueprints/base.py#L239-L287 | train | 214,604 |
cloudtools/stacker | stacker/blueprints/base.py | Blueprint.get_parameter_definitions | def get_parameter_definitions(self):
"""Get the parameter definitions to submit to CloudFormation.
Any variable definition whose `type` is an instance of `CFNType` will
be returned as a CloudFormation Parameter.
Returns:
dict: parameter definitions. Keys are parameter names, the values
are dicts containing key/values for various parameter
properties.
"""
output = {}
for var_name, attrs in self.defined_variables().items():
var_type = attrs.get("type")
if isinstance(var_type, CFNType):
cfn_attrs = copy.deepcopy(attrs)
cfn_attrs["type"] = var_type.parameter_type
output[var_name] = cfn_attrs
return output | python | def get_parameter_definitions(self):
"""Get the parameter definitions to submit to CloudFormation.
Any variable definition whose `type` is an instance of `CFNType` will
be returned as a CloudFormation Parameter.
Returns:
dict: parameter definitions. Keys are parameter names, the values
are dicts containing key/values for various parameter
properties.
"""
output = {}
for var_name, attrs in self.defined_variables().items():
var_type = attrs.get("type")
if isinstance(var_type, CFNType):
cfn_attrs = copy.deepcopy(attrs)
cfn_attrs["type"] = var_type.parameter_type
output[var_name] = cfn_attrs
return output | [
"def",
"get_parameter_definitions",
"(",
"self",
")",
":",
"output",
"=",
"{",
"}",
"for",
"var_name",
",",
"attrs",
"in",
"self",
".",
"defined_variables",
"(",
")",
".",
"items",
"(",
")",
":",
"var_type",
"=",
"attrs",
".",
"get",
"(",
"\"type\"",
"... | Get the parameter definitions to submit to CloudFormation.
Any variable definition whose `type` is an instance of `CFNType` will
be returned as a CloudFormation Parameter.
Returns:
dict: parameter definitions. Keys are parameter names, the values
are dicts containing key/values for various parameter
properties. | [
"Get",
"the",
"parameter",
"definitions",
"to",
"submit",
"to",
"CloudFormation",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/blueprints/base.py#L321-L340 | train | 214,605 |
cloudtools/stacker | stacker/blueprints/base.py | Blueprint.get_required_parameter_definitions | def get_required_parameter_definitions(self):
"""Returns all template parameters that do not have a default value.
Returns:
dict: dict of required CloudFormation Parameters for the blueprint.
Will be a dictionary of <parameter name>: <parameter
attributes>.
"""
required = {}
for name, attrs in self.get_parameter_definitions().items():
if "Default" not in attrs:
required[name] = attrs
return required | python | def get_required_parameter_definitions(self):
"""Returns all template parameters that do not have a default value.
Returns:
dict: dict of required CloudFormation Parameters for the blueprint.
Will be a dictionary of <parameter name>: <parameter
attributes>.
"""
required = {}
for name, attrs in self.get_parameter_definitions().items():
if "Default" not in attrs:
required[name] = attrs
return required | [
"def",
"get_required_parameter_definitions",
"(",
"self",
")",
":",
"required",
"=",
"{",
"}",
"for",
"name",
",",
"attrs",
"in",
"self",
".",
"get_parameter_definitions",
"(",
")",
".",
"items",
"(",
")",
":",
"if",
"\"Default\"",
"not",
"in",
"attrs",
":... | Returns all template parameters that do not have a default value.
Returns:
dict: dict of required CloudFormation Parameters for the blueprint.
Will be a dictionary of <parameter name>: <parameter
attributes>. | [
"Returns",
"all",
"template",
"parameters",
"that",
"do",
"not",
"have",
"a",
"default",
"value",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/blueprints/base.py#L342-L355 | train | 214,606 |
cloudtools/stacker | stacker/blueprints/base.py | Blueprint.setup_parameters | def setup_parameters(self):
"""Add any CloudFormation parameters to the template"""
t = self.template
parameters = self.get_parameter_definitions()
if not parameters:
logger.debug("No parameters defined.")
return
for name, attrs in parameters.items():
p = build_parameter(name, attrs)
t.add_parameter(p) | python | def setup_parameters(self):
"""Add any CloudFormation parameters to the template"""
t = self.template
parameters = self.get_parameter_definitions()
if not parameters:
logger.debug("No parameters defined.")
return
for name, attrs in parameters.items():
p = build_parameter(name, attrs)
t.add_parameter(p) | [
"def",
"setup_parameters",
"(",
"self",
")",
":",
"t",
"=",
"self",
".",
"template",
"parameters",
"=",
"self",
".",
"get_parameter_definitions",
"(",
")",
"if",
"not",
"parameters",
":",
"logger",
".",
"debug",
"(",
"\"No parameters defined.\"",
")",
"return"... | Add any CloudFormation parameters to the template | [
"Add",
"any",
"CloudFormation",
"parameters",
"to",
"the",
"template"
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/blueprints/base.py#L376-L387 | train | 214,607 |
cloudtools/stacker | stacker/blueprints/base.py | Blueprint.render_template | def render_template(self):
"""Render the Blueprint to a CloudFormation template"""
self.import_mappings()
self.create_template()
if self.description:
self.set_template_description(self.description)
self.setup_parameters()
rendered = self.template.to_json(indent=self.context.template_indent)
version = hashlib.md5(rendered.encode()).hexdigest()[:8]
return (version, rendered) | python | def render_template(self):
"""Render the Blueprint to a CloudFormation template"""
self.import_mappings()
self.create_template()
if self.description:
self.set_template_description(self.description)
self.setup_parameters()
rendered = self.template.to_json(indent=self.context.template_indent)
version = hashlib.md5(rendered.encode()).hexdigest()[:8]
return (version, rendered) | [
"def",
"render_template",
"(",
"self",
")",
":",
"self",
".",
"import_mappings",
"(",
")",
"self",
".",
"create_template",
"(",
")",
"if",
"self",
".",
"description",
":",
"self",
".",
"set_template_description",
"(",
"self",
".",
"description",
")",
"self",... | Render the Blueprint to a CloudFormation template | [
"Render",
"the",
"Blueprint",
"to",
"a",
"CloudFormation",
"template"
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/blueprints/base.py#L469-L478 | train | 214,608 |
cloudtools/stacker | stacker/blueprints/base.py | Blueprint.to_json | def to_json(self, variables=None):
"""Render the blueprint and return the template in json form.
Args:
variables (dict):
Optional dictionary providing/overriding variable values.
Returns:
str: the rendered CFN JSON template
"""
variables_to_resolve = []
if variables:
for key, value in variables.items():
variables_to_resolve.append(Variable(key, value))
for k in self.get_parameter_definitions():
if not variables or k not in variables:
# The provided value for a CFN parameter has no effect in this
# context (generating the CFN template), so any string can be
# provided for its value - just needs to be something
variables_to_resolve.append(Variable(k, 'unused_value'))
self.resolve_variables(variables_to_resolve)
return self.render_template()[1] | python | def to_json(self, variables=None):
"""Render the blueprint and return the template in json form.
Args:
variables (dict):
Optional dictionary providing/overriding variable values.
Returns:
str: the rendered CFN JSON template
"""
variables_to_resolve = []
if variables:
for key, value in variables.items():
variables_to_resolve.append(Variable(key, value))
for k in self.get_parameter_definitions():
if not variables or k not in variables:
# The provided value for a CFN parameter has no effect in this
# context (generating the CFN template), so any string can be
# provided for its value - just needs to be something
variables_to_resolve.append(Variable(k, 'unused_value'))
self.resolve_variables(variables_to_resolve)
return self.render_template()[1] | [
"def",
"to_json",
"(",
"self",
",",
"variables",
"=",
"None",
")",
":",
"variables_to_resolve",
"=",
"[",
"]",
"if",
"variables",
":",
"for",
"key",
",",
"value",
"in",
"variables",
".",
"items",
"(",
")",
":",
"variables_to_resolve",
".",
"append",
"(",... | Render the blueprint and return the template in json form.
Args:
variables (dict):
Optional dictionary providing/overriding variable values.
Returns:
str: the rendered CFN JSON template | [
"Render",
"the",
"blueprint",
"and",
"return",
"the",
"template",
"in",
"json",
"form",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/blueprints/base.py#L480-L503 | train | 214,609 |
cloudtools/stacker | stacker/blueprints/base.py | Blueprint.read_user_data | def read_user_data(self, user_data_path):
"""Reads and parses a user_data file.
Args:
user_data_path (str):
path to the userdata file
Returns:
str: the parsed user data file
"""
raw_user_data = read_value_from_path(user_data_path)
variables = self.get_variables()
return parse_user_data(variables, raw_user_data, self.name) | python | def read_user_data(self, user_data_path):
"""Reads and parses a user_data file.
Args:
user_data_path (str):
path to the userdata file
Returns:
str: the parsed user data file
"""
raw_user_data = read_value_from_path(user_data_path)
variables = self.get_variables()
return parse_user_data(variables, raw_user_data, self.name) | [
"def",
"read_user_data",
"(",
"self",
",",
"user_data_path",
")",
":",
"raw_user_data",
"=",
"read_value_from_path",
"(",
"user_data_path",
")",
"variables",
"=",
"self",
".",
"get_variables",
"(",
")",
"return",
"parse_user_data",
"(",
"variables",
",",
"raw_user... | Reads and parses a user_data file.
Args:
user_data_path (str):
path to the userdata file
Returns:
str: the parsed user data file | [
"Reads",
"and",
"parses",
"a",
"user_data",
"file",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/blueprints/base.py#L505-L520 | train | 214,610 |
cloudtools/stacker | stacker/blueprints/base.py | Blueprint.add_output | def add_output(self, name, value):
"""Simple helper for adding outputs.
Args:
name (str): The name of the output to create.
value (str): The value to put in the output.
"""
self.template.add_output(Output(name, Value=value)) | python | def add_output(self, name, value):
"""Simple helper for adding outputs.
Args:
name (str): The name of the output to create.
value (str): The value to put in the output.
"""
self.template.add_output(Output(name, Value=value)) | [
"def",
"add_output",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"self",
".",
"template",
".",
"add_output",
"(",
"Output",
"(",
"name",
",",
"Value",
"=",
"value",
")",
")"
] | Simple helper for adding outputs.
Args:
name (str): The name of the output to create.
value (str): The value to put in the output. | [
"Simple",
"helper",
"for",
"adding",
"outputs",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/blueprints/base.py#L532-L539 | train | 214,611 |
cloudtools/stacker | stacker/logger/__init__.py | setup_logging | def setup_logging(verbosity, formats=None):
"""
Configure a proper logger based on verbosity and optional log formats.
Args:
verbosity (int): 0, 1, 2
formats (dict): Optional, looks for `info`, `color`, and `debug` keys
which may override the associated default log formats.
"""
if formats is None:
formats = {}
log_level = logging.INFO
log_format = formats.get("info", INFO_FORMAT)
if sys.stdout.isatty():
log_format = formats.get("color", COLOR_FORMAT)
if verbosity > 0:
log_level = logging.DEBUG
log_format = formats.get("debug", DEBUG_FORMAT)
if verbosity < 2:
logging.getLogger("botocore").setLevel(logging.CRITICAL)
hdlr = logging.StreamHandler()
hdlr.setFormatter(ColorFormatter(log_format, ISO_8601))
logging.root.addHandler(hdlr)
logging.root.setLevel(log_level) | python | def setup_logging(verbosity, formats=None):
"""
Configure a proper logger based on verbosity and optional log formats.
Args:
verbosity (int): 0, 1, 2
formats (dict): Optional, looks for `info`, `color`, and `debug` keys
which may override the associated default log formats.
"""
if formats is None:
formats = {}
log_level = logging.INFO
log_format = formats.get("info", INFO_FORMAT)
if sys.stdout.isatty():
log_format = formats.get("color", COLOR_FORMAT)
if verbosity > 0:
log_level = logging.DEBUG
log_format = formats.get("debug", DEBUG_FORMAT)
if verbosity < 2:
logging.getLogger("botocore").setLevel(logging.CRITICAL)
hdlr = logging.StreamHandler()
hdlr.setFormatter(ColorFormatter(log_format, ISO_8601))
logging.root.addHandler(hdlr)
logging.root.setLevel(log_level) | [
"def",
"setup_logging",
"(",
"verbosity",
",",
"formats",
"=",
"None",
")",
":",
"if",
"formats",
"is",
"None",
":",
"formats",
"=",
"{",
"}",
"log_level",
"=",
"logging",
".",
"INFO",
"log_format",
"=",
"formats",
".",
"get",
"(",
"\"info\"",
",",
"IN... | Configure a proper logger based on verbosity and optional log formats.
Args:
verbosity (int): 0, 1, 2
formats (dict): Optional, looks for `info`, `color`, and `debug` keys
which may override the associated default log formats. | [
"Configure",
"a",
"proper",
"logger",
"based",
"on",
"verbosity",
"and",
"optional",
"log",
"formats",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/logger/__init__.py#L24-L53 | train | 214,612 |
cloudtools/stacker | stacker/stack.py | _gather_variables | def _gather_variables(stack_def):
"""Merges context provided & stack defined variables.
If multiple stacks have a variable with the same name, we can specify the
value for a specific stack by passing in the variable name as: `<stack
name>::<variable name>`. This variable value will only be used for that
specific stack.
Order of precedence:
- context defined stack specific variables (ie.
SomeStack::SomeVariable)
- context defined non-specific variables
- variable defined within the stack definition
Args:
stack_def (dict): The stack definition being worked on.
Returns:
dict: Contains key/value pairs of the collected variables.
Raises:
AttributeError: Raised when the stack definitition contains an invalid
attribute. Currently only when using old parameters, rather than
variables.
"""
variable_values = copy.deepcopy(stack_def.variables or {})
return [Variable(k, v) for k, v in variable_values.items()] | python | def _gather_variables(stack_def):
"""Merges context provided & stack defined variables.
If multiple stacks have a variable with the same name, we can specify the
value for a specific stack by passing in the variable name as: `<stack
name>::<variable name>`. This variable value will only be used for that
specific stack.
Order of precedence:
- context defined stack specific variables (ie.
SomeStack::SomeVariable)
- context defined non-specific variables
- variable defined within the stack definition
Args:
stack_def (dict): The stack definition being worked on.
Returns:
dict: Contains key/value pairs of the collected variables.
Raises:
AttributeError: Raised when the stack definitition contains an invalid
attribute. Currently only when using old parameters, rather than
variables.
"""
variable_values = copy.deepcopy(stack_def.variables or {})
return [Variable(k, v) for k, v in variable_values.items()] | [
"def",
"_gather_variables",
"(",
"stack_def",
")",
":",
"variable_values",
"=",
"copy",
".",
"deepcopy",
"(",
"stack_def",
".",
"variables",
"or",
"{",
"}",
")",
"return",
"[",
"Variable",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"variable_... | Merges context provided & stack defined variables.
If multiple stacks have a variable with the same name, we can specify the
value for a specific stack by passing in the variable name as: `<stack
name>::<variable name>`. This variable value will only be used for that
specific stack.
Order of precedence:
- context defined stack specific variables (ie.
SomeStack::SomeVariable)
- context defined non-specific variables
- variable defined within the stack definition
Args:
stack_def (dict): The stack definition being worked on.
Returns:
dict: Contains key/value pairs of the collected variables.
Raises:
AttributeError: Raised when the stack definitition contains an invalid
attribute. Currently only when using old parameters, rather than
variables. | [
"Merges",
"context",
"provided",
"&",
"stack",
"defined",
"variables",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/stack.py#L16-L42 | train | 214,613 |
cloudtools/stacker | stacker/stack.py | Stack.tags | def tags(self):
"""Returns the tags that should be set on this stack. Includes both the
global tags, as well as any stack specific tags or overrides.
Returns:
dict: dictionary of tags
"""
tags = self.definition.tags or {}
return dict(self.context.tags, **tags) | python | def tags(self):
"""Returns the tags that should be set on this stack. Includes both the
global tags, as well as any stack specific tags or overrides.
Returns:
dict: dictionary of tags
"""
tags = self.definition.tags or {}
return dict(self.context.tags, **tags) | [
"def",
"tags",
"(",
"self",
")",
":",
"tags",
"=",
"self",
".",
"definition",
".",
"tags",
"or",
"{",
"}",
"return",
"dict",
"(",
"self",
".",
"context",
".",
"tags",
",",
"*",
"*",
"tags",
")"
] | Returns the tags that should be set on this stack. Includes both the
global tags, as well as any stack specific tags or overrides.
Returns:
dict: dictionary of tags | [
"Returns",
"the",
"tags",
"that",
"should",
"be",
"set",
"on",
"this",
"stack",
".",
"Includes",
"both",
"the",
"global",
"tags",
"as",
"well",
"as",
"any",
"stack",
"specific",
"tags",
"or",
"overrides",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/stack.py#L146-L156 | train | 214,614 |
cloudtools/stacker | stacker/stack.py | Stack.resolve | def resolve(self, context, provider):
"""Resolve the Stack variables.
This resolves the Stack variables and then prepares the Blueprint for
rendering by passing the resolved variables to the Blueprint.
Args:
context (:class:`stacker.context.Context`): stacker context
provider (:class:`stacker.provider.base.BaseProvider`): subclass of
the base provider
"""
resolve_variables(self.variables, context, provider)
self.blueprint.resolve_variables(self.variables) | python | def resolve(self, context, provider):
"""Resolve the Stack variables.
This resolves the Stack variables and then prepares the Blueprint for
rendering by passing the resolved variables to the Blueprint.
Args:
context (:class:`stacker.context.Context`): stacker context
provider (:class:`stacker.provider.base.BaseProvider`): subclass of
the base provider
"""
resolve_variables(self.variables, context, provider)
self.blueprint.resolve_variables(self.variables) | [
"def",
"resolve",
"(",
"self",
",",
"context",
",",
"provider",
")",
":",
"resolve_variables",
"(",
"self",
".",
"variables",
",",
"context",
",",
"provider",
")",
"self",
".",
"blueprint",
".",
"resolve_variables",
"(",
"self",
".",
"variables",
")"
] | Resolve the Stack variables.
This resolves the Stack variables and then prepares the Blueprint for
rendering by passing the resolved variables to the Blueprint.
Args:
context (:class:`stacker.context.Context`): stacker context
provider (:class:`stacker.provider.base.BaseProvider`): subclass of
the base provider | [
"Resolve",
"the",
"Stack",
"variables",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/stack.py#L181-L194 | train | 214,615 |
cloudtools/stacker | stacker/lookups/handlers/file.py | _parameterize_string | def _parameterize_string(raw):
"""Substitute placeholders in a string using CloudFormation references
Args:
raw (`str`): String to be processed. Byte strings are not
supported; decode them before passing them to this function.
Returns:
`str` | :class:`troposphere.GenericHelperFn`: An expression with
placeholders from the input replaced, suitable to be passed to
Troposphere to be included in CloudFormation template. This will
be the input string without modification if no substitutions are
found, and a composition of CloudFormation calls otherwise.
"""
parts = []
s_index = 0
for match in _PARAMETER_PATTERN.finditer(raw):
parts.append(raw[s_index:match.start()])
parts.append({u"Ref": match.group(1)})
s_index = match.end()
if not parts:
return GenericHelperFn(raw)
parts.append(raw[s_index:])
return GenericHelperFn({u"Fn::Join": [u"", parts]}) | python | def _parameterize_string(raw):
"""Substitute placeholders in a string using CloudFormation references
Args:
raw (`str`): String to be processed. Byte strings are not
supported; decode them before passing them to this function.
Returns:
`str` | :class:`troposphere.GenericHelperFn`: An expression with
placeholders from the input replaced, suitable to be passed to
Troposphere to be included in CloudFormation template. This will
be the input string without modification if no substitutions are
found, and a composition of CloudFormation calls otherwise.
"""
parts = []
s_index = 0
for match in _PARAMETER_PATTERN.finditer(raw):
parts.append(raw[s_index:match.start()])
parts.append({u"Ref": match.group(1)})
s_index = match.end()
if not parts:
return GenericHelperFn(raw)
parts.append(raw[s_index:])
return GenericHelperFn({u"Fn::Join": [u"", parts]}) | [
"def",
"_parameterize_string",
"(",
"raw",
")",
":",
"parts",
"=",
"[",
"]",
"s_index",
"=",
"0",
"for",
"match",
"in",
"_PARAMETER_PATTERN",
".",
"finditer",
"(",
"raw",
")",
":",
"parts",
".",
"append",
"(",
"raw",
"[",
"s_index",
":",
"match",
".",
... | Substitute placeholders in a string using CloudFormation references
Args:
raw (`str`): String to be processed. Byte strings are not
supported; decode them before passing them to this function.
Returns:
`str` | :class:`troposphere.GenericHelperFn`: An expression with
placeholders from the input replaced, suitable to be passed to
Troposphere to be included in CloudFormation template. This will
be the input string without modification if no substitutions are
found, and a composition of CloudFormation calls otherwise. | [
"Substitute",
"placeholders",
"in",
"a",
"string",
"using",
"CloudFormation",
"references"
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/lookups/handlers/file.py#L119-L146 | train | 214,616 |
cloudtools/stacker | stacker/lookups/handlers/file.py | parameterized_codec | def parameterized_codec(raw, b64):
"""Parameterize a string, possibly encoding it as Base64 afterwards
Args:
raw (`str` | `bytes`): String to be processed. Byte strings will be
interpreted as UTF-8.
b64 (`bool`): Whether to wrap the output in a Base64 CloudFormation
call
Returns:
:class:`troposphere.AWSHelperFn`: output to be included in a
CloudFormation template.
"""
if isinstance(raw, bytes):
raw = raw.decode('utf-8')
result = _parameterize_string(raw)
# Note, since we want a raw JSON object (not a string) output in the
# template, we wrap the result in GenericHelperFn (not needed if we're
# using Base64)
return Base64(result.data) if b64 else result | python | def parameterized_codec(raw, b64):
"""Parameterize a string, possibly encoding it as Base64 afterwards
Args:
raw (`str` | `bytes`): String to be processed. Byte strings will be
interpreted as UTF-8.
b64 (`bool`): Whether to wrap the output in a Base64 CloudFormation
call
Returns:
:class:`troposphere.AWSHelperFn`: output to be included in a
CloudFormation template.
"""
if isinstance(raw, bytes):
raw = raw.decode('utf-8')
result = _parameterize_string(raw)
# Note, since we want a raw JSON object (not a string) output in the
# template, we wrap the result in GenericHelperFn (not needed if we're
# using Base64)
return Base64(result.data) if b64 else result | [
"def",
"parameterized_codec",
"(",
"raw",
",",
"b64",
")",
":",
"if",
"isinstance",
"(",
"raw",
",",
"bytes",
")",
":",
"raw",
"=",
"raw",
".",
"decode",
"(",
"'utf-8'",
")",
"result",
"=",
"_parameterize_string",
"(",
"raw",
")",
"# Note, since we want a ... | Parameterize a string, possibly encoding it as Base64 afterwards
Args:
raw (`str` | `bytes`): String to be processed. Byte strings will be
interpreted as UTF-8.
b64 (`bool`): Whether to wrap the output in a Base64 CloudFormation
call
Returns:
:class:`troposphere.AWSHelperFn`: output to be included in a
CloudFormation template. | [
"Parameterize",
"a",
"string",
"possibly",
"encoding",
"it",
"as",
"Base64",
"afterwards"
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/lookups/handlers/file.py#L149-L171 | train | 214,617 |
cloudtools/stacker | stacker/lookups/handlers/file.py | _parameterize_obj | def _parameterize_obj(obj):
"""Recursively parameterize all strings contained in an object.
Parameterizes all values of a Mapping, all items of a Sequence, an
unicode string, or pass other objects through unmodified.
Byte strings will be interpreted as UTF-8.
Args:
obj: data to parameterize
Return:
A parameterized object to be included in a CloudFormation template.
Mappings are converted to `dict`, Sequences are converted to `list`,
and strings possibly replaced by compositions of function calls.
"""
if isinstance(obj, Mapping):
return dict((key, _parameterize_obj(value))
for key, value in obj.items())
elif isinstance(obj, bytes):
return _parameterize_string(obj.decode('utf8'))
elif isinstance(obj, str):
return _parameterize_string(obj)
elif isinstance(obj, Sequence):
return list(_parameterize_obj(item) for item in obj)
else:
return obj | python | def _parameterize_obj(obj):
"""Recursively parameterize all strings contained in an object.
Parameterizes all values of a Mapping, all items of a Sequence, an
unicode string, or pass other objects through unmodified.
Byte strings will be interpreted as UTF-8.
Args:
obj: data to parameterize
Return:
A parameterized object to be included in a CloudFormation template.
Mappings are converted to `dict`, Sequences are converted to `list`,
and strings possibly replaced by compositions of function calls.
"""
if isinstance(obj, Mapping):
return dict((key, _parameterize_obj(value))
for key, value in obj.items())
elif isinstance(obj, bytes):
return _parameterize_string(obj.decode('utf8'))
elif isinstance(obj, str):
return _parameterize_string(obj)
elif isinstance(obj, Sequence):
return list(_parameterize_obj(item) for item in obj)
else:
return obj | [
"def",
"_parameterize_obj",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"Mapping",
")",
":",
"return",
"dict",
"(",
"(",
"key",
",",
"_parameterize_obj",
"(",
"value",
")",
")",
"for",
"key",
",",
"value",
"in",
"obj",
".",
"items",
"(... | Recursively parameterize all strings contained in an object.
Parameterizes all values of a Mapping, all items of a Sequence, an
unicode string, or pass other objects through unmodified.
Byte strings will be interpreted as UTF-8.
Args:
obj: data to parameterize
Return:
A parameterized object to be included in a CloudFormation template.
Mappings are converted to `dict`, Sequences are converted to `list`,
and strings possibly replaced by compositions of function calls. | [
"Recursively",
"parameterize",
"all",
"strings",
"contained",
"in",
"an",
"object",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/lookups/handlers/file.py#L174-L201 | train | 214,618 |
cloudtools/stacker | stacker/lookups/handlers/file.py | FileLookup.handle | def handle(cls, value, **kwargs):
"""Translate a filename into the file contents.
Fields should use the following format::
<codec>:<path>
For example::
# We've written a file to /some/path:
$ echo "hello there" > /some/path
# In stacker we would reference the contents of this file with the
# following
conf_key: ${file plain:file://some/path}
# The above would resolve to
conf_key: hello there
# Or, if we used wanted a base64 encoded copy of the file data
conf_key: ${file base64:file://some/path}
# The above would resolve to
conf_key: aGVsbG8gdGhlcmUK
Supported codecs:
- plain
- base64 - encode the plain text file at the given path with base64
prior to returning it
- parameterized - the same as plain, but additionally supports
referencing template parameters to create userdata that's
supplemented with information from the template, as is commonly
needed in EC2 UserData. For example, given a template parameter
of BucketName, the file could contain the following text::
#!/bin/sh
aws s3 sync s3://{{BucketName}}/somepath /somepath
and then you could use something like this in the YAML config
file::
UserData: ${file parameterized:/path/to/file}
resulting in the UserData parameter being defined as::
{ "Fn::Join" : ["", [
"#!/bin/sh\\naws s3 sync s3://",
{"Ref" : "BucketName"},
"/somepath /somepath"
]] }
- parameterized-b64 - the same as parameterized, with the results
additionally wrapped in *{ "Fn::Base64": ... }* , which is what
you actually need for EC2 UserData
When using parameterized-b64 for UserData, you should use a variable
defined as such:
.. code-block:: python
from troposphere import AWSHelperFn
"UserData": {
"type": AWSHelperFn,
"description": "Instance user data",
"default": Ref("AWS::NoValue")
}
and then assign UserData in a LaunchConfiguration or Instance to
*self.get_variables()["UserData"]*. Note that we use AWSHelperFn as the
type because the parameterized-b64 codec returns either a Base64 or a
GenericHelperFn troposphere object
"""
try:
codec, path = value.split(":", 1)
except ValueError:
raise TypeError(
"File value must be of the format"
" \"<codec>:<path>\" (got %s)" % (value)
)
value = read_value_from_path(path)
return CODECS[codec](value) | python | def handle(cls, value, **kwargs):
"""Translate a filename into the file contents.
Fields should use the following format::
<codec>:<path>
For example::
# We've written a file to /some/path:
$ echo "hello there" > /some/path
# In stacker we would reference the contents of this file with the
# following
conf_key: ${file plain:file://some/path}
# The above would resolve to
conf_key: hello there
# Or, if we used wanted a base64 encoded copy of the file data
conf_key: ${file base64:file://some/path}
# The above would resolve to
conf_key: aGVsbG8gdGhlcmUK
Supported codecs:
- plain
- base64 - encode the plain text file at the given path with base64
prior to returning it
- parameterized - the same as plain, but additionally supports
referencing template parameters to create userdata that's
supplemented with information from the template, as is commonly
needed in EC2 UserData. For example, given a template parameter
of BucketName, the file could contain the following text::
#!/bin/sh
aws s3 sync s3://{{BucketName}}/somepath /somepath
and then you could use something like this in the YAML config
file::
UserData: ${file parameterized:/path/to/file}
resulting in the UserData parameter being defined as::
{ "Fn::Join" : ["", [
"#!/bin/sh\\naws s3 sync s3://",
{"Ref" : "BucketName"},
"/somepath /somepath"
]] }
- parameterized-b64 - the same as parameterized, with the results
additionally wrapped in *{ "Fn::Base64": ... }* , which is what
you actually need for EC2 UserData
When using parameterized-b64 for UserData, you should use a variable
defined as such:
.. code-block:: python
from troposphere import AWSHelperFn
"UserData": {
"type": AWSHelperFn,
"description": "Instance user data",
"default": Ref("AWS::NoValue")
}
and then assign UserData in a LaunchConfiguration or Instance to
*self.get_variables()["UserData"]*. Note that we use AWSHelperFn as the
type because the parameterized-b64 codec returns either a Base64 or a
GenericHelperFn troposphere object
"""
try:
codec, path = value.split(":", 1)
except ValueError:
raise TypeError(
"File value must be of the format"
" \"<codec>:<path>\" (got %s)" % (value)
)
value = read_value_from_path(path)
return CODECS[codec](value) | [
"def",
"handle",
"(",
"cls",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"codec",
",",
"path",
"=",
"value",
".",
"split",
"(",
"\":\"",
",",
"1",
")",
"except",
"ValueError",
":",
"raise",
"TypeError",
"(",
"\"File value must be of th... | Translate a filename into the file contents.
Fields should use the following format::
<codec>:<path>
For example::
# We've written a file to /some/path:
$ echo "hello there" > /some/path
# In stacker we would reference the contents of this file with the
# following
conf_key: ${file plain:file://some/path}
# The above would resolve to
conf_key: hello there
# Or, if we used wanted a base64 encoded copy of the file data
conf_key: ${file base64:file://some/path}
# The above would resolve to
conf_key: aGVsbG8gdGhlcmUK
Supported codecs:
- plain
- base64 - encode the plain text file at the given path with base64
prior to returning it
- parameterized - the same as plain, but additionally supports
referencing template parameters to create userdata that's
supplemented with information from the template, as is commonly
needed in EC2 UserData. For example, given a template parameter
of BucketName, the file could contain the following text::
#!/bin/sh
aws s3 sync s3://{{BucketName}}/somepath /somepath
and then you could use something like this in the YAML config
file::
UserData: ${file parameterized:/path/to/file}
resulting in the UserData parameter being defined as::
{ "Fn::Join" : ["", [
"#!/bin/sh\\naws s3 sync s3://",
{"Ref" : "BucketName"},
"/somepath /somepath"
]] }
- parameterized-b64 - the same as parameterized, with the results
additionally wrapped in *{ "Fn::Base64": ... }* , which is what
you actually need for EC2 UserData
When using parameterized-b64 for UserData, you should use a variable
defined as such:
.. code-block:: python
from troposphere import AWSHelperFn
"UserData": {
"type": AWSHelperFn,
"description": "Instance user data",
"default": Ref("AWS::NoValue")
}
and then assign UserData in a LaunchConfiguration or Instance to
*self.get_variables()["UserData"]*. Note that we use AWSHelperFn as the
type because the parameterized-b64 codec returns either a Base64 or a
GenericHelperFn troposphere object | [
"Translate",
"a",
"filename",
"into",
"the",
"file",
"contents",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/lookups/handlers/file.py#L29-L116 | train | 214,619 |
cloudtools/stacker | stacker/lookups/handlers/envvar.py | EnvvarLookup.handle | def handle(cls, value, **kwargs):
"""Retrieve an environment variable.
For example:
# In stacker we would reference the environment variable like this:
conf_key: ${envvar ENV_VAR_NAME}
You can optionally store the value in a file, ie:
$ cat envvar_value.txt
ENV_VAR_NAME
and reference it within stacker (NOTE: the path should be relative
to the stacker config file):
conf_key: ${envvar file://envvar_value.txt}
# Both of the above would resolve to
conf_key: ENV_VALUE
"""
value = read_value_from_path(value)
try:
return os.environ[value]
except KeyError:
raise ValueError('EnvVar "{}" does not exist'.format(value)) | python | def handle(cls, value, **kwargs):
"""Retrieve an environment variable.
For example:
# In stacker we would reference the environment variable like this:
conf_key: ${envvar ENV_VAR_NAME}
You can optionally store the value in a file, ie:
$ cat envvar_value.txt
ENV_VAR_NAME
and reference it within stacker (NOTE: the path should be relative
to the stacker config file):
conf_key: ${envvar file://envvar_value.txt}
# Both of the above would resolve to
conf_key: ENV_VALUE
"""
value = read_value_from_path(value)
try:
return os.environ[value]
except KeyError:
raise ValueError('EnvVar "{}" does not exist'.format(value)) | [
"def",
"handle",
"(",
"cls",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"value",
"=",
"read_value_from_path",
"(",
"value",
")",
"try",
":",
"return",
"os",
".",
"environ",
"[",
"value",
"]",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",... | Retrieve an environment variable.
For example:
# In stacker we would reference the environment variable like this:
conf_key: ${envvar ENV_VAR_NAME}
You can optionally store the value in a file, ie:
$ cat envvar_value.txt
ENV_VAR_NAME
and reference it within stacker (NOTE: the path should be relative
to the stacker config file):
conf_key: ${envvar file://envvar_value.txt}
# Both of the above would resolve to
conf_key: ENV_VALUE | [
"Retrieve",
"an",
"environment",
"variable",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/lookups/handlers/envvar.py#L14-L40 | train | 214,620 |
cloudtools/stacker | stacker/providers/aws/default.py | ask_for_approval | def ask_for_approval(full_changeset=None, params_diff=None,
include_verbose=False):
"""Prompt the user for approval to execute a change set.
Args:
full_changeset (list, optional): A list of the full changeset that will
be output if the user specifies verbose.
params_diff (list, optional): A list of DictValue detailing the
differences between two parameters returned by
:func:`stacker.actions.diff.diff_dictionaries`
include_verbose (bool, optional): Boolean for whether or not to include
the verbose option
"""
approval_options = ['y', 'n']
if include_verbose:
approval_options.append('v')
approve = ui.ask("Execute the above changes? [{}] ".format(
'/'.join(approval_options))).lower()
if include_verbose and approve == "v":
if params_diff:
logger.info(
"Full changeset:\n\n%s\n%s",
format_params_diff(params_diff),
yaml.safe_dump(full_changeset),
)
else:
logger.info(
"Full changeset:\n%s",
yaml.safe_dump(full_changeset),
)
return ask_for_approval()
elif approve != "y":
raise exceptions.CancelExecution | python | def ask_for_approval(full_changeset=None, params_diff=None,
include_verbose=False):
"""Prompt the user for approval to execute a change set.
Args:
full_changeset (list, optional): A list of the full changeset that will
be output if the user specifies verbose.
params_diff (list, optional): A list of DictValue detailing the
differences between two parameters returned by
:func:`stacker.actions.diff.diff_dictionaries`
include_verbose (bool, optional): Boolean for whether or not to include
the verbose option
"""
approval_options = ['y', 'n']
if include_verbose:
approval_options.append('v')
approve = ui.ask("Execute the above changes? [{}] ".format(
'/'.join(approval_options))).lower()
if include_verbose and approve == "v":
if params_diff:
logger.info(
"Full changeset:\n\n%s\n%s",
format_params_diff(params_diff),
yaml.safe_dump(full_changeset),
)
else:
logger.info(
"Full changeset:\n%s",
yaml.safe_dump(full_changeset),
)
return ask_for_approval()
elif approve != "y":
raise exceptions.CancelExecution | [
"def",
"ask_for_approval",
"(",
"full_changeset",
"=",
"None",
",",
"params_diff",
"=",
"None",
",",
"include_verbose",
"=",
"False",
")",
":",
"approval_options",
"=",
"[",
"'y'",
",",
"'n'",
"]",
"if",
"include_verbose",
":",
"approval_options",
".",
"append... | Prompt the user for approval to execute a change set.
Args:
full_changeset (list, optional): A list of the full changeset that will
be output if the user specifies verbose.
params_diff (list, optional): A list of DictValue detailing the
differences between two parameters returned by
:func:`stacker.actions.diff.diff_dictionaries`
include_verbose (bool, optional): Boolean for whether or not to include
the verbose option | [
"Prompt",
"the",
"user",
"for",
"approval",
"to",
"execute",
"a",
"change",
"set",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/providers/aws/default.py#L146-L181 | train | 214,621 |
cloudtools/stacker | stacker/providers/aws/default.py | output_summary | def output_summary(fqn, action, changeset, params_diff,
replacements_only=False):
"""Log a summary of the changeset.
Args:
fqn (string): fully qualified name of the stack
action (string): action to include in the log message
changeset (list): AWS changeset
params_diff (list): A list of dictionaries detailing the differences
between two parameters returned by
:func:`stacker.actions.diff.diff_dictionaries`
replacements_only (bool, optional): boolean for whether or not we only
want to list replacements
"""
replacements = []
changes = []
for change in changeset:
resource = change['ResourceChange']
replacement = resource.get('Replacement') == 'True'
summary = '- %s %s (%s)' % (
resource['Action'],
resource['LogicalResourceId'],
resource['ResourceType'],
)
if replacement:
replacements.append(summary)
else:
changes.append(summary)
summary = ''
if params_diff:
summary += summarize_params_diff(params_diff)
if replacements:
if not replacements_only:
summary += 'Replacements:\n'
summary += '\n'.join(replacements)
if changes:
if summary:
summary += '\n'
summary += 'Changes:\n%s' % ('\n'.join(changes))
logger.info('%s %s:\n%s', fqn, action, summary) | python | def output_summary(fqn, action, changeset, params_diff,
replacements_only=False):
"""Log a summary of the changeset.
Args:
fqn (string): fully qualified name of the stack
action (string): action to include in the log message
changeset (list): AWS changeset
params_diff (list): A list of dictionaries detailing the differences
between two parameters returned by
:func:`stacker.actions.diff.diff_dictionaries`
replacements_only (bool, optional): boolean for whether or not we only
want to list replacements
"""
replacements = []
changes = []
for change in changeset:
resource = change['ResourceChange']
replacement = resource.get('Replacement') == 'True'
summary = '- %s %s (%s)' % (
resource['Action'],
resource['LogicalResourceId'],
resource['ResourceType'],
)
if replacement:
replacements.append(summary)
else:
changes.append(summary)
summary = ''
if params_diff:
summary += summarize_params_diff(params_diff)
if replacements:
if not replacements_only:
summary += 'Replacements:\n'
summary += '\n'.join(replacements)
if changes:
if summary:
summary += '\n'
summary += 'Changes:\n%s' % ('\n'.join(changes))
logger.info('%s %s:\n%s', fqn, action, summary) | [
"def",
"output_summary",
"(",
"fqn",
",",
"action",
",",
"changeset",
",",
"params_diff",
",",
"replacements_only",
"=",
"False",
")",
":",
"replacements",
"=",
"[",
"]",
"changes",
"=",
"[",
"]",
"for",
"change",
"in",
"changeset",
":",
"resource",
"=",
... | Log a summary of the changeset.
Args:
fqn (string): fully qualified name of the stack
action (string): action to include in the log message
changeset (list): AWS changeset
params_diff (list): A list of dictionaries detailing the differences
between two parameters returned by
:func:`stacker.actions.diff.diff_dictionaries`
replacements_only (bool, optional): boolean for whether or not we only
want to list replacements | [
"Log",
"a",
"summary",
"of",
"the",
"changeset",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/providers/aws/default.py#L184-L225 | train | 214,622 |
cloudtools/stacker | stacker/providers/aws/default.py | wait_till_change_set_complete | def wait_till_change_set_complete(cfn_client, change_set_id, try_count=25,
sleep_time=.5, max_sleep=3):
""" Checks state of a changeset, returning when it is in a complete state.
Since changesets can take a little bit of time to get into a complete
state, we need to poll it until it does so. This will try to get the
state `try_count` times, waiting `sleep_time` * 2 seconds between each try
up to the `max_sleep` number of seconds. If, after that time, the changeset
is not in a complete state it fails. These default settings will wait a
little over one minute.
Args:
cfn_client (:class:`botocore.client.CloudFormation`): Used to query
cloudformation.
change_set_id (str): The unique changeset id to wait for.
try_count (int): Number of times to try the call.
sleep_time (int): Time to sleep between attempts.
max_sleep (int): Max time to sleep during backoff
Return:
dict: The response from cloudformation for the describe_change_set
call.
"""
complete = False
response = None
for i in range(try_count):
response = cfn_client.describe_change_set(
ChangeSetName=change_set_id,
)
complete = response["Status"] in ("FAILED", "CREATE_COMPLETE")
if complete:
break
if sleep_time == max_sleep:
logger.debug(
"Still waiting on changeset for another %s seconds",
sleep_time
)
time.sleep(sleep_time)
# exponential backoff with max
sleep_time = min(sleep_time * 2, max_sleep)
if not complete:
raise exceptions.ChangesetDidNotStabilize(change_set_id)
return response | python | def wait_till_change_set_complete(cfn_client, change_set_id, try_count=25,
sleep_time=.5, max_sleep=3):
""" Checks state of a changeset, returning when it is in a complete state.
Since changesets can take a little bit of time to get into a complete
state, we need to poll it until it does so. This will try to get the
state `try_count` times, waiting `sleep_time` * 2 seconds between each try
up to the `max_sleep` number of seconds. If, after that time, the changeset
is not in a complete state it fails. These default settings will wait a
little over one minute.
Args:
cfn_client (:class:`botocore.client.CloudFormation`): Used to query
cloudformation.
change_set_id (str): The unique changeset id to wait for.
try_count (int): Number of times to try the call.
sleep_time (int): Time to sleep between attempts.
max_sleep (int): Max time to sleep during backoff
Return:
dict: The response from cloudformation for the describe_change_set
call.
"""
complete = False
response = None
for i in range(try_count):
response = cfn_client.describe_change_set(
ChangeSetName=change_set_id,
)
complete = response["Status"] in ("FAILED", "CREATE_COMPLETE")
if complete:
break
if sleep_time == max_sleep:
logger.debug(
"Still waiting on changeset for another %s seconds",
sleep_time
)
time.sleep(sleep_time)
# exponential backoff with max
sleep_time = min(sleep_time * 2, max_sleep)
if not complete:
raise exceptions.ChangesetDidNotStabilize(change_set_id)
return response | [
"def",
"wait_till_change_set_complete",
"(",
"cfn_client",
",",
"change_set_id",
",",
"try_count",
"=",
"25",
",",
"sleep_time",
"=",
".5",
",",
"max_sleep",
"=",
"3",
")",
":",
"complete",
"=",
"False",
"response",
"=",
"None",
"for",
"i",
"in",
"range",
... | Checks state of a changeset, returning when it is in a complete state.
Since changesets can take a little bit of time to get into a complete
state, we need to poll it until it does so. This will try to get the
state `try_count` times, waiting `sleep_time` * 2 seconds between each try
up to the `max_sleep` number of seconds. If, after that time, the changeset
is not in a complete state it fails. These default settings will wait a
little over one minute.
Args:
cfn_client (:class:`botocore.client.CloudFormation`): Used to query
cloudformation.
change_set_id (str): The unique changeset id to wait for.
try_count (int): Number of times to try the call.
sleep_time (int): Time to sleep between attempts.
max_sleep (int): Max time to sleep during backoff
Return:
dict: The response from cloudformation for the describe_change_set
call. | [
"Checks",
"state",
"of",
"a",
"changeset",
"returning",
"when",
"it",
"is",
"in",
"a",
"complete",
"state",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/providers/aws/default.py#L256-L299 | train | 214,623 |
cloudtools/stacker | stacker/providers/aws/default.py | check_tags_contain | def check_tags_contain(actual, expected):
"""Check if a set of AWS resource tags is contained in another
Every tag key in `expected` must be present in `actual`, and have the same
value. Extra keys in `actual` but not in `expected` are ignored.
Args:
actual (list): Set of tags to be verified, usually from the description
of a resource. Each item must be a `dict` containing `Key` and
`Value` items.
expected (list): Set of tags that must be present in `actual` (in the
same format).
"""
actual_set = set((item["Key"], item["Value"]) for item in actual)
expected_set = set((item["Key"], item["Value"]) for item in expected)
return actual_set >= expected_set | python | def check_tags_contain(actual, expected):
"""Check if a set of AWS resource tags is contained in another
Every tag key in `expected` must be present in `actual`, and have the same
value. Extra keys in `actual` but not in `expected` are ignored.
Args:
actual (list): Set of tags to be verified, usually from the description
of a resource. Each item must be a `dict` containing `Key` and
`Value` items.
expected (list): Set of tags that must be present in `actual` (in the
same format).
"""
actual_set = set((item["Key"], item["Value"]) for item in actual)
expected_set = set((item["Key"], item["Value"]) for item in expected)
return actual_set >= expected_set | [
"def",
"check_tags_contain",
"(",
"actual",
",",
"expected",
")",
":",
"actual_set",
"=",
"set",
"(",
"(",
"item",
"[",
"\"Key\"",
"]",
",",
"item",
"[",
"\"Value\"",
"]",
")",
"for",
"item",
"in",
"actual",
")",
"expected_set",
"=",
"set",
"(",
"(",
... | Check if a set of AWS resource tags is contained in another
Every tag key in `expected` must be present in `actual`, and have the same
value. Extra keys in `actual` but not in `expected` are ignored.
Args:
actual (list): Set of tags to be verified, usually from the description
of a resource. Each item must be a `dict` containing `Key` and
`Value` items.
expected (list): Set of tags that must be present in `actual` (in the
same format). | [
"Check",
"if",
"a",
"set",
"of",
"AWS",
"resource",
"tags",
"is",
"contained",
"in",
"another"
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/providers/aws/default.py#L362-L379 | train | 214,624 |
cloudtools/stacker | stacker/providers/aws/default.py | generate_cloudformation_args | def generate_cloudformation_args(stack_name, parameters, tags, template,
capabilities=DEFAULT_CAPABILITIES,
change_set_type=None,
service_role=None,
stack_policy=None,
change_set_name=None):
"""Used to generate the args for common cloudformation API interactions.
This is used for create_stack/update_stack/create_change_set calls in
cloudformation.
Args:
stack_name (str): The fully qualified stack name in Cloudformation.
parameters (list): A list of dictionaries that defines the
parameter list to be applied to the Cloudformation stack.
tags (list): A list of dictionaries that defines the tags
that should be applied to the Cloudformation stack.
template (:class:`stacker.provider.base.Template`): The template
object.
capabilities (list, optional): A list of capabilities to use when
updating Cloudformation.
change_set_type (str, optional): An optional change set type to use
with create_change_set.
service_role (str, optional): An optional service role to use when
interacting with Cloudformation.
stack_policy (:class:`stacker.providers.base.Template`): A template
object representing a stack policy.
change_set_name (str, optional): An optional change set name to use
with create_change_set.
Returns:
dict: A dictionary of arguments to be used in the Cloudformation API
call.
"""
args = {
"StackName": stack_name,
"Parameters": parameters,
"Tags": tags,
"Capabilities": capabilities,
}
if service_role:
args["RoleARN"] = service_role
if change_set_name:
args["ChangeSetName"] = change_set_name
if change_set_type:
args["ChangeSetType"] = change_set_type
if template.url:
args["TemplateURL"] = template.url
else:
args["TemplateBody"] = template.body
# When creating args for CreateChangeSet, don't include the stack policy,
# since ChangeSets don't support it.
if not change_set_name:
args.update(generate_stack_policy_args(stack_policy))
return args | python | def generate_cloudformation_args(stack_name, parameters, tags, template,
capabilities=DEFAULT_CAPABILITIES,
change_set_type=None,
service_role=None,
stack_policy=None,
change_set_name=None):
"""Used to generate the args for common cloudformation API interactions.
This is used for create_stack/update_stack/create_change_set calls in
cloudformation.
Args:
stack_name (str): The fully qualified stack name in Cloudformation.
parameters (list): A list of dictionaries that defines the
parameter list to be applied to the Cloudformation stack.
tags (list): A list of dictionaries that defines the tags
that should be applied to the Cloudformation stack.
template (:class:`stacker.provider.base.Template`): The template
object.
capabilities (list, optional): A list of capabilities to use when
updating Cloudformation.
change_set_type (str, optional): An optional change set type to use
with create_change_set.
service_role (str, optional): An optional service role to use when
interacting with Cloudformation.
stack_policy (:class:`stacker.providers.base.Template`): A template
object representing a stack policy.
change_set_name (str, optional): An optional change set name to use
with create_change_set.
Returns:
dict: A dictionary of arguments to be used in the Cloudformation API
call.
"""
args = {
"StackName": stack_name,
"Parameters": parameters,
"Tags": tags,
"Capabilities": capabilities,
}
if service_role:
args["RoleARN"] = service_role
if change_set_name:
args["ChangeSetName"] = change_set_name
if change_set_type:
args["ChangeSetType"] = change_set_type
if template.url:
args["TemplateURL"] = template.url
else:
args["TemplateBody"] = template.body
# When creating args for CreateChangeSet, don't include the stack policy,
# since ChangeSets don't support it.
if not change_set_name:
args.update(generate_stack_policy_args(stack_policy))
return args | [
"def",
"generate_cloudformation_args",
"(",
"stack_name",
",",
"parameters",
",",
"tags",
",",
"template",
",",
"capabilities",
"=",
"DEFAULT_CAPABILITIES",
",",
"change_set_type",
"=",
"None",
",",
"service_role",
"=",
"None",
",",
"stack_policy",
"=",
"None",
",... | Used to generate the args for common cloudformation API interactions.
This is used for create_stack/update_stack/create_change_set calls in
cloudformation.
Args:
stack_name (str): The fully qualified stack name in Cloudformation.
parameters (list): A list of dictionaries that defines the
parameter list to be applied to the Cloudformation stack.
tags (list): A list of dictionaries that defines the tags
that should be applied to the Cloudformation stack.
template (:class:`stacker.provider.base.Template`): The template
object.
capabilities (list, optional): A list of capabilities to use when
updating Cloudformation.
change_set_type (str, optional): An optional change set type to use
with create_change_set.
service_role (str, optional): An optional service role to use when
interacting with Cloudformation.
stack_policy (:class:`stacker.providers.base.Template`): A template
object representing a stack policy.
change_set_name (str, optional): An optional change set name to use
with create_change_set.
Returns:
dict: A dictionary of arguments to be used in the Cloudformation API
call. | [
"Used",
"to",
"generate",
"the",
"args",
"for",
"common",
"cloudformation",
"API",
"interactions",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/providers/aws/default.py#L382-L442 | train | 214,625 |
cloudtools/stacker | stacker/providers/aws/default.py | generate_stack_policy_args | def generate_stack_policy_args(stack_policy=None):
""" Converts a stack policy object into keyword args.
Args:
stack_policy (:class:`stacker.providers.base.Template`): A template
object representing a stack policy.
Returns:
dict: A dictionary of keyword arguments to be used elsewhere.
"""
args = {}
if stack_policy:
logger.debug("Stack has a stack policy")
if stack_policy.url:
# stacker currently does not support uploading stack policies to
# S3, so this will never get hit (unless your implementing S3
# uploads, and then you're probably reading this comment about why
# the exception below was raised :))
#
# args["StackPolicyURL"] = stack_policy.url
raise NotImplementedError
else:
args["StackPolicyBody"] = stack_policy.body
return args | python | def generate_stack_policy_args(stack_policy=None):
""" Converts a stack policy object into keyword args.
Args:
stack_policy (:class:`stacker.providers.base.Template`): A template
object representing a stack policy.
Returns:
dict: A dictionary of keyword arguments to be used elsewhere.
"""
args = {}
if stack_policy:
logger.debug("Stack has a stack policy")
if stack_policy.url:
# stacker currently does not support uploading stack policies to
# S3, so this will never get hit (unless your implementing S3
# uploads, and then you're probably reading this comment about why
# the exception below was raised :))
#
# args["StackPolicyURL"] = stack_policy.url
raise NotImplementedError
else:
args["StackPolicyBody"] = stack_policy.body
return args | [
"def",
"generate_stack_policy_args",
"(",
"stack_policy",
"=",
"None",
")",
":",
"args",
"=",
"{",
"}",
"if",
"stack_policy",
":",
"logger",
".",
"debug",
"(",
"\"Stack has a stack policy\"",
")",
"if",
"stack_policy",
".",
"url",
":",
"# stacker currently does no... | Converts a stack policy object into keyword args.
Args:
stack_policy (:class:`stacker.providers.base.Template`): A template
object representing a stack policy.
Returns:
dict: A dictionary of keyword arguments to be used elsewhere. | [
"Converts",
"a",
"stack",
"policy",
"object",
"into",
"keyword",
"args",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/providers/aws/default.py#L445-L469 | train | 214,626 |
cloudtools/stacker | stacker/providers/aws/default.py | ProviderBuilder.build | def build(self, region=None, profile=None):
"""Get or create the provider for the given region and profile."""
with self.lock:
# memoization lookup key derived from region + profile.
key = "{}-{}".format(profile, region)
try:
# assume provider is in provider dictionary.
provider = self.providers[key]
except KeyError:
msg = "Missed memoized lookup ({}), creating new AWS Provider."
logger.debug(msg.format(key))
if not region:
region = self.region
# memoize the result for later.
self.providers[key] = Provider(
get_session(region=region, profile=profile),
region=region,
**self.kwargs
)
provider = self.providers[key]
return provider | python | def build(self, region=None, profile=None):
"""Get or create the provider for the given region and profile."""
with self.lock:
# memoization lookup key derived from region + profile.
key = "{}-{}".format(profile, region)
try:
# assume provider is in provider dictionary.
provider = self.providers[key]
except KeyError:
msg = "Missed memoized lookup ({}), creating new AWS Provider."
logger.debug(msg.format(key))
if not region:
region = self.region
# memoize the result for later.
self.providers[key] = Provider(
get_session(region=region, profile=profile),
region=region,
**self.kwargs
)
provider = self.providers[key]
return provider | [
"def",
"build",
"(",
"self",
",",
"region",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"with",
"self",
".",
"lock",
":",
"# memoization lookup key derived from region + profile.",
"key",
"=",
"\"{}-{}\"",
".",
"format",
"(",
"profile",
",",
"region",
... | Get or create the provider for the given region and profile. | [
"Get",
"or",
"create",
"the",
"provider",
"for",
"the",
"given",
"region",
"and",
"profile",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/providers/aws/default.py#L481-L503 | train | 214,627 |
cloudtools/stacker | stacker/providers/aws/default.py | Provider.get_rollback_status_reason | def get_rollback_status_reason(self, stack_name):
"""Process events and returns latest roll back reason"""
event = next((item for item in self.get_events(stack_name,
False) if item["ResourceStatus"] ==
"UPDATE_ROLLBACK_IN_PROGRESS"), None)
if event:
reason = event["ResourceStatusReason"]
return reason
else:
event = next((item for item in self.get_events(stack_name)
if item["ResourceStatus"] ==
"ROLLBACK_IN_PROGRESS"), None)
reason = event["ResourceStatusReason"]
return reason | python | def get_rollback_status_reason(self, stack_name):
"""Process events and returns latest roll back reason"""
event = next((item for item in self.get_events(stack_name,
False) if item["ResourceStatus"] ==
"UPDATE_ROLLBACK_IN_PROGRESS"), None)
if event:
reason = event["ResourceStatusReason"]
return reason
else:
event = next((item for item in self.get_events(stack_name)
if item["ResourceStatus"] ==
"ROLLBACK_IN_PROGRESS"), None)
reason = event["ResourceStatusReason"]
return reason | [
"def",
"get_rollback_status_reason",
"(",
"self",
",",
"stack_name",
")",
":",
"event",
"=",
"next",
"(",
"(",
"item",
"for",
"item",
"in",
"self",
".",
"get_events",
"(",
"stack_name",
",",
"False",
")",
"if",
"item",
"[",
"\"ResourceStatus\"",
"]",
"==",... | Process events and returns latest roll back reason | [
"Process",
"events",
"and",
"returns",
"latest",
"roll",
"back",
"reason"
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/providers/aws/default.py#L650-L663 | train | 214,628 |
cloudtools/stacker | stacker/providers/aws/default.py | Provider.create_stack | def create_stack(self, fqn, template, parameters, tags,
force_change_set=False, stack_policy=None,
**kwargs):
"""Create a new Cloudformation stack.
Args:
fqn (str): The fully qualified name of the Cloudformation stack.
template (:class:`stacker.providers.base.Template`): A Template
object to use when creating the stack.
parameters (list): A list of dictionaries that defines the
parameter list to be applied to the Cloudformation stack.
tags (list): A list of dictionaries that defines the tags
that should be applied to the Cloudformation stack.
force_change_set (bool): Whether or not to force change set use.
stack_policy (:class:`stacker.providers.base.Template`): A template
object representing a stack policy.
"""
logger.debug("Attempting to create stack %s:.", fqn)
logger.debug(" parameters: %s", parameters)
logger.debug(" tags: %s", tags)
if template.url:
logger.debug(" template_url: %s", template.url)
else:
logger.debug(" no template url, uploading template "
"directly.")
if force_change_set:
logger.debug("force_change_set set to True, creating stack with "
"changeset.")
_changes, change_set_id = create_change_set(
self.cloudformation, fqn, template, parameters, tags,
'CREATE', service_role=self.service_role, **kwargs
)
self.cloudformation.execute_change_set(
ChangeSetName=change_set_id,
)
else:
args = generate_cloudformation_args(
fqn, parameters, tags, template,
service_role=self.service_role,
stack_policy=stack_policy,
)
try:
self.cloudformation.create_stack(**args)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Message'] == ('TemplateURL must '
'reference a valid S3 '
'object to which you '
'have access.'):
s3_fallback(fqn, template, parameters, tags,
self.cloudformation.create_stack,
self.service_role)
else:
raise | python | def create_stack(self, fqn, template, parameters, tags,
force_change_set=False, stack_policy=None,
**kwargs):
"""Create a new Cloudformation stack.
Args:
fqn (str): The fully qualified name of the Cloudformation stack.
template (:class:`stacker.providers.base.Template`): A Template
object to use when creating the stack.
parameters (list): A list of dictionaries that defines the
parameter list to be applied to the Cloudformation stack.
tags (list): A list of dictionaries that defines the tags
that should be applied to the Cloudformation stack.
force_change_set (bool): Whether or not to force change set use.
stack_policy (:class:`stacker.providers.base.Template`): A template
object representing a stack policy.
"""
logger.debug("Attempting to create stack %s:.", fqn)
logger.debug(" parameters: %s", parameters)
logger.debug(" tags: %s", tags)
if template.url:
logger.debug(" template_url: %s", template.url)
else:
logger.debug(" no template url, uploading template "
"directly.")
if force_change_set:
logger.debug("force_change_set set to True, creating stack with "
"changeset.")
_changes, change_set_id = create_change_set(
self.cloudformation, fqn, template, parameters, tags,
'CREATE', service_role=self.service_role, **kwargs
)
self.cloudformation.execute_change_set(
ChangeSetName=change_set_id,
)
else:
args = generate_cloudformation_args(
fqn, parameters, tags, template,
service_role=self.service_role,
stack_policy=stack_policy,
)
try:
self.cloudformation.create_stack(**args)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Message'] == ('TemplateURL must '
'reference a valid S3 '
'object to which you '
'have access.'):
s3_fallback(fqn, template, parameters, tags,
self.cloudformation.create_stack,
self.service_role)
else:
raise | [
"def",
"create_stack",
"(",
"self",
",",
"fqn",
",",
"template",
",",
"parameters",
",",
"tags",
",",
"force_change_set",
"=",
"False",
",",
"stack_policy",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"debug",
"(",
"\"Attempting to creat... | Create a new Cloudformation stack.
Args:
fqn (str): The fully qualified name of the Cloudformation stack.
template (:class:`stacker.providers.base.Template`): A Template
object to use when creating the stack.
parameters (list): A list of dictionaries that defines the
parameter list to be applied to the Cloudformation stack.
tags (list): A list of dictionaries that defines the tags
that should be applied to the Cloudformation stack.
force_change_set (bool): Whether or not to force change set use.
stack_policy (:class:`stacker.providers.base.Template`): A template
object representing a stack policy. | [
"Create",
"a",
"new",
"Cloudformation",
"stack",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/providers/aws/default.py#L696-L751 | train | 214,629 |
cloudtools/stacker | stacker/providers/aws/default.py | Provider.select_update_method | def select_update_method(self, force_interactive, force_change_set):
"""Select the correct update method when updating a stack.
Args:
force_interactive (str): Whether or not to force interactive mode
no matter what mode the provider is in.
force_change_set (bool): Whether or not to force change set use.
Returns:
function: The correct object method to use when updating.
"""
if self.interactive or force_interactive:
return self.interactive_update_stack
elif force_change_set:
return self.noninteractive_changeset_update
else:
return self.default_update_stack | python | def select_update_method(self, force_interactive, force_change_set):
"""Select the correct update method when updating a stack.
Args:
force_interactive (str): Whether or not to force interactive mode
no matter what mode the provider is in.
force_change_set (bool): Whether or not to force change set use.
Returns:
function: The correct object method to use when updating.
"""
if self.interactive or force_interactive:
return self.interactive_update_stack
elif force_change_set:
return self.noninteractive_changeset_update
else:
return self.default_update_stack | [
"def",
"select_update_method",
"(",
"self",
",",
"force_interactive",
",",
"force_change_set",
")",
":",
"if",
"self",
".",
"interactive",
"or",
"force_interactive",
":",
"return",
"self",
".",
"interactive_update_stack",
"elif",
"force_change_set",
":",
"return",
"... | Select the correct update method when updating a stack.
Args:
force_interactive (str): Whether or not to force interactive mode
no matter what mode the provider is in.
force_change_set (bool): Whether or not to force change set use.
Returns:
function: The correct object method to use when updating. | [
"Select",
"the",
"correct",
"update",
"method",
"when",
"updating",
"a",
"stack",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/providers/aws/default.py#L753-L769 | train | 214,630 |
cloudtools/stacker | stacker/providers/aws/default.py | Provider.prepare_stack_for_update | def prepare_stack_for_update(self, stack, tags):
"""Prepare a stack for updating
It may involve deleting the stack if is has failed it's initial
creation. The deletion is only allowed if:
- The stack contains all the tags configured in the current context;
- The stack is in one of the statuses considered safe to re-create
- ``recreate_failed`` is enabled, due to either being explicitly
enabled by the user, or because interactive mode is on.
Args:
stack (dict): a stack object returned from get_stack
tags (list): list of expected tags that must be present in the
stack if it must be re-created
Returns:
bool: True if the stack can be updated, False if it must be
re-created
"""
if self.is_stack_destroyed(stack):
return False
elif self.is_stack_completed(stack):
return True
stack_name = self.get_stack_name(stack)
stack_status = self.get_stack_status(stack)
if self.is_stack_in_progress(stack):
raise exceptions.StackUpdateBadStatus(
stack_name, stack_status,
'Update already in-progress')
if not self.is_stack_recreatable(stack):
raise exceptions.StackUpdateBadStatus(
stack_name, stack_status,
'Unsupported state for re-creation')
if not self.recreate_failed:
raise exceptions.StackUpdateBadStatus(
stack_name, stack_status,
'Stack re-creation is disabled. Run stacker again with the '
'--recreate-failed option to force it to be deleted and '
'created from scratch.')
stack_tags = self.get_stack_tags(stack)
if not check_tags_contain(stack_tags, tags):
raise exceptions.StackUpdateBadStatus(
stack_name, stack_status,
'Tags differ from current configuration, possibly not created '
'with stacker')
if self.interactive:
sys.stdout.write(
'The \"%s\" stack is in a failed state (%s).\n'
'It cannot be updated, but it can be deleted and re-created.\n'
'All its current resources will IRREVERSIBLY DESTROYED.\n'
'Proceed carefully!\n\n' % (stack_name, stack_status))
sys.stdout.flush()
ask_for_approval(include_verbose=False)
logger.warn('Destroying stack \"%s\" for re-creation', stack_name)
self.destroy_stack(stack)
return False | python | def prepare_stack_for_update(self, stack, tags):
"""Prepare a stack for updating
It may involve deleting the stack if is has failed it's initial
creation. The deletion is only allowed if:
- The stack contains all the tags configured in the current context;
- The stack is in one of the statuses considered safe to re-create
- ``recreate_failed`` is enabled, due to either being explicitly
enabled by the user, or because interactive mode is on.
Args:
stack (dict): a stack object returned from get_stack
tags (list): list of expected tags that must be present in the
stack if it must be re-created
Returns:
bool: True if the stack can be updated, False if it must be
re-created
"""
if self.is_stack_destroyed(stack):
return False
elif self.is_stack_completed(stack):
return True
stack_name = self.get_stack_name(stack)
stack_status = self.get_stack_status(stack)
if self.is_stack_in_progress(stack):
raise exceptions.StackUpdateBadStatus(
stack_name, stack_status,
'Update already in-progress')
if not self.is_stack_recreatable(stack):
raise exceptions.StackUpdateBadStatus(
stack_name, stack_status,
'Unsupported state for re-creation')
if not self.recreate_failed:
raise exceptions.StackUpdateBadStatus(
stack_name, stack_status,
'Stack re-creation is disabled. Run stacker again with the '
'--recreate-failed option to force it to be deleted and '
'created from scratch.')
stack_tags = self.get_stack_tags(stack)
if not check_tags_contain(stack_tags, tags):
raise exceptions.StackUpdateBadStatus(
stack_name, stack_status,
'Tags differ from current configuration, possibly not created '
'with stacker')
if self.interactive:
sys.stdout.write(
'The \"%s\" stack is in a failed state (%s).\n'
'It cannot be updated, but it can be deleted and re-created.\n'
'All its current resources will IRREVERSIBLY DESTROYED.\n'
'Proceed carefully!\n\n' % (stack_name, stack_status))
sys.stdout.flush()
ask_for_approval(include_verbose=False)
logger.warn('Destroying stack \"%s\" for re-creation', stack_name)
self.destroy_stack(stack)
return False | [
"def",
"prepare_stack_for_update",
"(",
"self",
",",
"stack",
",",
"tags",
")",
":",
"if",
"self",
".",
"is_stack_destroyed",
"(",
"stack",
")",
":",
"return",
"False",
"elif",
"self",
".",
"is_stack_completed",
"(",
"stack",
")",
":",
"return",
"True",
"s... | Prepare a stack for updating
It may involve deleting the stack if is has failed it's initial
creation. The deletion is only allowed if:
- The stack contains all the tags configured in the current context;
- The stack is in one of the statuses considered safe to re-create
- ``recreate_failed`` is enabled, due to either being explicitly
enabled by the user, or because interactive mode is on.
Args:
stack (dict): a stack object returned from get_stack
tags (list): list of expected tags that must be present in the
stack if it must be re-created
Returns:
bool: True if the stack can be updated, False if it must be
re-created | [
"Prepare",
"a",
"stack",
"for",
"updating"
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/providers/aws/default.py#L771-L836 | train | 214,631 |
cloudtools/stacker | stacker/providers/aws/default.py | Provider.update_stack | def update_stack(self, fqn, template, old_parameters, parameters, tags,
force_interactive=False, force_change_set=False,
stack_policy=None, **kwargs):
"""Update a Cloudformation stack.
Args:
fqn (str): The fully qualified name of the Cloudformation stack.
template (:class:`stacker.providers.base.Template`): A Template
object to use when updating the stack.
old_parameters (list): A list of dictionaries that defines the
parameter list on the existing Cloudformation stack.
parameters (list): A list of dictionaries that defines the
parameter list to be applied to the Cloudformation stack.
tags (list): A list of dictionaries that defines the tags
that should be applied to the Cloudformation stack.
force_interactive (bool): A flag that indicates whether the update
should be interactive. If set to True, interactive mode will
be used no matter if the provider is in interactive mode or
not. False will follow the behavior of the provider.
force_change_set (bool): A flag that indicates whether the update
must be executed with a change set.
stack_policy (:class:`stacker.providers.base.Template`): A template
object representing a stack policy.
"""
logger.debug("Attempting to update stack %s:", fqn)
logger.debug(" parameters: %s", parameters)
logger.debug(" tags: %s", tags)
if template.url:
logger.debug(" template_url: %s", template.url)
else:
logger.debug(" no template url, uploading template directly.")
update_method = self.select_update_method(force_interactive,
force_change_set)
return update_method(fqn, template, old_parameters, parameters,
stack_policy=stack_policy, tags=tags, **kwargs) | python | def update_stack(self, fqn, template, old_parameters, parameters, tags,
force_interactive=False, force_change_set=False,
stack_policy=None, **kwargs):
"""Update a Cloudformation stack.
Args:
fqn (str): The fully qualified name of the Cloudformation stack.
template (:class:`stacker.providers.base.Template`): A Template
object to use when updating the stack.
old_parameters (list): A list of dictionaries that defines the
parameter list on the existing Cloudformation stack.
parameters (list): A list of dictionaries that defines the
parameter list to be applied to the Cloudformation stack.
tags (list): A list of dictionaries that defines the tags
that should be applied to the Cloudformation stack.
force_interactive (bool): A flag that indicates whether the update
should be interactive. If set to True, interactive mode will
be used no matter if the provider is in interactive mode or
not. False will follow the behavior of the provider.
force_change_set (bool): A flag that indicates whether the update
must be executed with a change set.
stack_policy (:class:`stacker.providers.base.Template`): A template
object representing a stack policy.
"""
logger.debug("Attempting to update stack %s:", fqn)
logger.debug(" parameters: %s", parameters)
logger.debug(" tags: %s", tags)
if template.url:
logger.debug(" template_url: %s", template.url)
else:
logger.debug(" no template url, uploading template directly.")
update_method = self.select_update_method(force_interactive,
force_change_set)
return update_method(fqn, template, old_parameters, parameters,
stack_policy=stack_policy, tags=tags, **kwargs) | [
"def",
"update_stack",
"(",
"self",
",",
"fqn",
",",
"template",
",",
"old_parameters",
",",
"parameters",
",",
"tags",
",",
"force_interactive",
"=",
"False",
",",
"force_change_set",
"=",
"False",
",",
"stack_policy",
"=",
"None",
",",
"*",
"*",
"kwargs",
... | Update a Cloudformation stack.
Args:
fqn (str): The fully qualified name of the Cloudformation stack.
template (:class:`stacker.providers.base.Template`): A Template
object to use when updating the stack.
old_parameters (list): A list of dictionaries that defines the
parameter list on the existing Cloudformation stack.
parameters (list): A list of dictionaries that defines the
parameter list to be applied to the Cloudformation stack.
tags (list): A list of dictionaries that defines the tags
that should be applied to the Cloudformation stack.
force_interactive (bool): A flag that indicates whether the update
should be interactive. If set to True, interactive mode will
be used no matter if the provider is in interactive mode or
not. False will follow the behavior of the provider.
force_change_set (bool): A flag that indicates whether the update
must be executed with a change set.
stack_policy (:class:`stacker.providers.base.Template`): A template
object representing a stack policy. | [
"Update",
"a",
"Cloudformation",
"stack",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/providers/aws/default.py#L838-L873 | train | 214,632 |
cloudtools/stacker | stacker/providers/aws/default.py | Provider.deal_with_changeset_stack_policy | def deal_with_changeset_stack_policy(self, fqn, stack_policy):
""" Set a stack policy when using changesets.
ChangeSets don't allow you to set stack policies in the same call to
update them. This sets it before executing the changeset if the
stack policy is passed in.
Args:
stack_policy (:class:`stacker.providers.base.Template`): A template
object representing a stack policy.
"""
if stack_policy:
kwargs = generate_stack_policy_args(stack_policy)
kwargs["StackName"] = fqn
logger.debug("Setting stack policy on %s.", fqn)
self.cloudformation.set_stack_policy(**kwargs) | python | def deal_with_changeset_stack_policy(self, fqn, stack_policy):
""" Set a stack policy when using changesets.
ChangeSets don't allow you to set stack policies in the same call to
update them. This sets it before executing the changeset if the
stack policy is passed in.
Args:
stack_policy (:class:`stacker.providers.base.Template`): A template
object representing a stack policy.
"""
if stack_policy:
kwargs = generate_stack_policy_args(stack_policy)
kwargs["StackName"] = fqn
logger.debug("Setting stack policy on %s.", fqn)
self.cloudformation.set_stack_policy(**kwargs) | [
"def",
"deal_with_changeset_stack_policy",
"(",
"self",
",",
"fqn",
",",
"stack_policy",
")",
":",
"if",
"stack_policy",
":",
"kwargs",
"=",
"generate_stack_policy_args",
"(",
"stack_policy",
")",
"kwargs",
"[",
"\"StackName\"",
"]",
"=",
"fqn",
"logger",
".",
"... | Set a stack policy when using changesets.
ChangeSets don't allow you to set stack policies in the same call to
update them. This sets it before executing the changeset if the
stack policy is passed in.
Args:
stack_policy (:class:`stacker.providers.base.Template`): A template
object representing a stack policy. | [
"Set",
"a",
"stack",
"policy",
"when",
"using",
"changesets",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/providers/aws/default.py#L875-L890 | train | 214,633 |
cloudtools/stacker | stacker/providers/aws/default.py | Provider.interactive_update_stack | def interactive_update_stack(self, fqn, template, old_parameters,
parameters, stack_policy, tags,
**kwargs):
"""Update a Cloudformation stack in interactive mode.
Args:
fqn (str): The fully qualified name of the Cloudformation stack.
template (:class:`stacker.providers.base.Template`): A Template
object to use when updating the stack.
old_parameters (list): A list of dictionaries that defines the
parameter list on the existing Cloudformation stack.
parameters (list): A list of dictionaries that defines the
parameter list to be applied to the Cloudformation stack.
stack_policy (:class:`stacker.providers.base.Template`): A template
object representing a stack policy.
tags (list): A list of dictionaries that defines the tags
that should be applied to the Cloudformation stack.
"""
logger.debug("Using interactive provider mode for %s.", fqn)
changes, change_set_id = create_change_set(
self.cloudformation, fqn, template, parameters, tags,
'UPDATE', service_role=self.service_role, **kwargs
)
old_parameters_as_dict = self.params_as_dict(old_parameters)
new_parameters_as_dict = self.params_as_dict(
[x
if 'ParameterValue' in x
else {'ParameterKey': x['ParameterKey'],
'ParameterValue': old_parameters_as_dict[x['ParameterKey']]}
for x in parameters]
)
params_diff = diff_parameters(
old_parameters_as_dict,
new_parameters_as_dict)
action = "replacements" if self.replacements_only else "changes"
full_changeset = changes
if self.replacements_only:
changes = requires_replacement(changes)
if changes or params_diff:
ui.lock()
try:
output_summary(fqn, action, changes, params_diff,
replacements_only=self.replacements_only)
ask_for_approval(
full_changeset=full_changeset,
params_diff=params_diff,
include_verbose=True,
)
finally:
ui.unlock()
self.deal_with_changeset_stack_policy(fqn, stack_policy)
self.cloudformation.execute_change_set(
ChangeSetName=change_set_id,
) | python | def interactive_update_stack(self, fqn, template, old_parameters,
parameters, stack_policy, tags,
**kwargs):
"""Update a Cloudformation stack in interactive mode.
Args:
fqn (str): The fully qualified name of the Cloudformation stack.
template (:class:`stacker.providers.base.Template`): A Template
object to use when updating the stack.
old_parameters (list): A list of dictionaries that defines the
parameter list on the existing Cloudformation stack.
parameters (list): A list of dictionaries that defines the
parameter list to be applied to the Cloudformation stack.
stack_policy (:class:`stacker.providers.base.Template`): A template
object representing a stack policy.
tags (list): A list of dictionaries that defines the tags
that should be applied to the Cloudformation stack.
"""
logger.debug("Using interactive provider mode for %s.", fqn)
changes, change_set_id = create_change_set(
self.cloudformation, fqn, template, parameters, tags,
'UPDATE', service_role=self.service_role, **kwargs
)
old_parameters_as_dict = self.params_as_dict(old_parameters)
new_parameters_as_dict = self.params_as_dict(
[x
if 'ParameterValue' in x
else {'ParameterKey': x['ParameterKey'],
'ParameterValue': old_parameters_as_dict[x['ParameterKey']]}
for x in parameters]
)
params_diff = diff_parameters(
old_parameters_as_dict,
new_parameters_as_dict)
action = "replacements" if self.replacements_only else "changes"
full_changeset = changes
if self.replacements_only:
changes = requires_replacement(changes)
if changes or params_diff:
ui.lock()
try:
output_summary(fqn, action, changes, params_diff,
replacements_only=self.replacements_only)
ask_for_approval(
full_changeset=full_changeset,
params_diff=params_diff,
include_verbose=True,
)
finally:
ui.unlock()
self.deal_with_changeset_stack_policy(fqn, stack_policy)
self.cloudformation.execute_change_set(
ChangeSetName=change_set_id,
) | [
"def",
"interactive_update_stack",
"(",
"self",
",",
"fqn",
",",
"template",
",",
"old_parameters",
",",
"parameters",
",",
"stack_policy",
",",
"tags",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"debug",
"(",
"\"Using interactive provider mode for %s.\"",
... | Update a Cloudformation stack in interactive mode.
Args:
fqn (str): The fully qualified name of the Cloudformation stack.
template (:class:`stacker.providers.base.Template`): A Template
object to use when updating the stack.
old_parameters (list): A list of dictionaries that defines the
parameter list on the existing Cloudformation stack.
parameters (list): A list of dictionaries that defines the
parameter list to be applied to the Cloudformation stack.
stack_policy (:class:`stacker.providers.base.Template`): A template
object representing a stack policy.
tags (list): A list of dictionaries that defines the tags
that should be applied to the Cloudformation stack. | [
"Update",
"a",
"Cloudformation",
"stack",
"in",
"interactive",
"mode",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/providers/aws/default.py#L892-L949 | train | 214,634 |
cloudtools/stacker | stacker/providers/aws/default.py | Provider.noninteractive_changeset_update | def noninteractive_changeset_update(self, fqn, template, old_parameters,
parameters, stack_policy, tags,
**kwargs):
"""Update a Cloudformation stack using a change set.
This is required for stacks with a defined Transform (i.e. SAM), as the
default update_stack API cannot be used with them.
Args:
fqn (str): The fully qualified name of the Cloudformation stack.
template (:class:`stacker.providers.base.Template`): A Template
object to use when updating the stack.
old_parameters (list): A list of dictionaries that defines the
parameter list on the existing Cloudformation stack.
parameters (list): A list of dictionaries that defines the
parameter list to be applied to the Cloudformation stack.
stack_policy (:class:`stacker.providers.base.Template`): A template
object representing a stack policy.
tags (list): A list of dictionaries that defines the tags
that should be applied to the Cloudformation stack.
"""
logger.debug("Using noninterative changeset provider mode "
"for %s.", fqn)
_changes, change_set_id = create_change_set(
self.cloudformation, fqn, template, parameters, tags,
'UPDATE', service_role=self.service_role, **kwargs
)
self.deal_with_changeset_stack_policy(fqn, stack_policy)
self.cloudformation.execute_change_set(
ChangeSetName=change_set_id,
) | python | def noninteractive_changeset_update(self, fqn, template, old_parameters,
parameters, stack_policy, tags,
**kwargs):
"""Update a Cloudformation stack using a change set.
This is required for stacks with a defined Transform (i.e. SAM), as the
default update_stack API cannot be used with them.
Args:
fqn (str): The fully qualified name of the Cloudformation stack.
template (:class:`stacker.providers.base.Template`): A Template
object to use when updating the stack.
old_parameters (list): A list of dictionaries that defines the
parameter list on the existing Cloudformation stack.
parameters (list): A list of dictionaries that defines the
parameter list to be applied to the Cloudformation stack.
stack_policy (:class:`stacker.providers.base.Template`): A template
object representing a stack policy.
tags (list): A list of dictionaries that defines the tags
that should be applied to the Cloudformation stack.
"""
logger.debug("Using noninterative changeset provider mode "
"for %s.", fqn)
_changes, change_set_id = create_change_set(
self.cloudformation, fqn, template, parameters, tags,
'UPDATE', service_role=self.service_role, **kwargs
)
self.deal_with_changeset_stack_policy(fqn, stack_policy)
self.cloudformation.execute_change_set(
ChangeSetName=change_set_id,
) | [
"def",
"noninteractive_changeset_update",
"(",
"self",
",",
"fqn",
",",
"template",
",",
"old_parameters",
",",
"parameters",
",",
"stack_policy",
",",
"tags",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"debug",
"(",
"\"Using noninterative changeset provide... | Update a Cloudformation stack using a change set.
This is required for stacks with a defined Transform (i.e. SAM), as the
default update_stack API cannot be used with them.
Args:
fqn (str): The fully qualified name of the Cloudformation stack.
template (:class:`stacker.providers.base.Template`): A Template
object to use when updating the stack.
old_parameters (list): A list of dictionaries that defines the
parameter list on the existing Cloudformation stack.
parameters (list): A list of dictionaries that defines the
parameter list to be applied to the Cloudformation stack.
stack_policy (:class:`stacker.providers.base.Template`): A template
object representing a stack policy.
tags (list): A list of dictionaries that defines the tags
that should be applied to the Cloudformation stack. | [
"Update",
"a",
"Cloudformation",
"stack",
"using",
"a",
"change",
"set",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/providers/aws/default.py#L951-L983 | train | 214,635 |
cloudtools/stacker | stacker/providers/aws/default.py | Provider.default_update_stack | def default_update_stack(self, fqn, template, old_parameters, parameters,
tags, stack_policy=None, **kwargs):
"""Update a Cloudformation stack in default mode.
Args:
fqn (str): The fully qualified name of the Cloudformation stack.
template (:class:`stacker.providers.base.Template`): A Template
object to use when updating the stack.
old_parameters (list): A list of dictionaries that defines the
parameter list on the existing Cloudformation stack.
parameters (list): A list of dictionaries that defines the
parameter list to be applied to the Cloudformation stack.
tags (list): A list of dictionaries that defines the tags
that should be applied to the Cloudformation stack.
stack_policy (:class:`stacker.providers.base.Template`): A template
object representing a stack policy.
"""
logger.debug("Using default provider mode for %s.", fqn)
args = generate_cloudformation_args(
fqn, parameters, tags, template,
service_role=self.service_role,
stack_policy=stack_policy,
)
try:
self.cloudformation.update_stack(**args)
except botocore.exceptions.ClientError as e:
if "No updates are to be performed." in str(e):
logger.debug(
"Stack %s did not change, not updating.",
fqn,
)
raise exceptions.StackDidNotChange
elif e.response['Error']['Message'] == ('TemplateURL must '
'reference a valid '
'S3 object to which '
'you have access.'):
s3_fallback(fqn, template, parameters, tags,
self.cloudformation.update_stack,
self.service_role)
else:
raise | python | def default_update_stack(self, fqn, template, old_parameters, parameters,
tags, stack_policy=None, **kwargs):
"""Update a Cloudformation stack in default mode.
Args:
fqn (str): The fully qualified name of the Cloudformation stack.
template (:class:`stacker.providers.base.Template`): A Template
object to use when updating the stack.
old_parameters (list): A list of dictionaries that defines the
parameter list on the existing Cloudformation stack.
parameters (list): A list of dictionaries that defines the
parameter list to be applied to the Cloudformation stack.
tags (list): A list of dictionaries that defines the tags
that should be applied to the Cloudformation stack.
stack_policy (:class:`stacker.providers.base.Template`): A template
object representing a stack policy.
"""
logger.debug("Using default provider mode for %s.", fqn)
args = generate_cloudformation_args(
fqn, parameters, tags, template,
service_role=self.service_role,
stack_policy=stack_policy,
)
try:
self.cloudformation.update_stack(**args)
except botocore.exceptions.ClientError as e:
if "No updates are to be performed." in str(e):
logger.debug(
"Stack %s did not change, not updating.",
fqn,
)
raise exceptions.StackDidNotChange
elif e.response['Error']['Message'] == ('TemplateURL must '
'reference a valid '
'S3 object to which '
'you have access.'):
s3_fallback(fqn, template, parameters, tags,
self.cloudformation.update_stack,
self.service_role)
else:
raise | [
"def",
"default_update_stack",
"(",
"self",
",",
"fqn",
",",
"template",
",",
"old_parameters",
",",
"parameters",
",",
"tags",
",",
"stack_policy",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"debug",
"(",
"\"Using default provider mode for... | Update a Cloudformation stack in default mode.
Args:
fqn (str): The fully qualified name of the Cloudformation stack.
template (:class:`stacker.providers.base.Template`): A Template
object to use when updating the stack.
old_parameters (list): A list of dictionaries that defines the
parameter list on the existing Cloudformation stack.
parameters (list): A list of dictionaries that defines the
parameter list to be applied to the Cloudformation stack.
tags (list): A list of dictionaries that defines the tags
that should be applied to the Cloudformation stack.
stack_policy (:class:`stacker.providers.base.Template`): A template
object representing a stack policy. | [
"Update",
"a",
"Cloudformation",
"stack",
"in",
"default",
"mode",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/providers/aws/default.py#L985-L1027 | train | 214,636 |
cloudtools/stacker | stacker/providers/aws/default.py | Provider.get_stack_info | def get_stack_info(self, stack):
""" Get the template and parameters of the stack currently in AWS
Returns [ template, parameters ]
"""
stack_name = stack['StackId']
try:
template = self.cloudformation.get_template(
StackName=stack_name)['TemplateBody']
except botocore.exceptions.ClientError as e:
if "does not exist" not in str(e):
raise
raise exceptions.StackDoesNotExist(stack_name)
parameters = self.params_as_dict(stack.get('Parameters', []))
return [json.dumps(template), parameters] | python | def get_stack_info(self, stack):
""" Get the template and parameters of the stack currently in AWS
Returns [ template, parameters ]
"""
stack_name = stack['StackId']
try:
template = self.cloudformation.get_template(
StackName=stack_name)['TemplateBody']
except botocore.exceptions.ClientError as e:
if "does not exist" not in str(e):
raise
raise exceptions.StackDoesNotExist(stack_name)
parameters = self.params_as_dict(stack.get('Parameters', []))
return [json.dumps(template), parameters] | [
"def",
"get_stack_info",
"(",
"self",
",",
"stack",
")",
":",
"stack_name",
"=",
"stack",
"[",
"'StackId'",
"]",
"try",
":",
"template",
"=",
"self",
".",
"cloudformation",
".",
"get_template",
"(",
"StackName",
"=",
"stack_name",
")",
"[",
"'TemplateBody'",... | Get the template and parameters of the stack currently in AWS
Returns [ template, parameters ] | [
"Get",
"the",
"template",
"and",
"parameters",
"of",
"the",
"stack",
"currently",
"in",
"AWS"
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/providers/aws/default.py#L1044-L1061 | train | 214,637 |
cloudtools/stacker | stacker/session_cache.py | get_session | def get_session(region, profile=None):
"""Creates a boto3 session with a cache
Args:
region (str): The region for the session
profile (str): The profile for the session
Returns:
:class:`boto3.session.Session`: A boto3 session with
credential caching
"""
if profile is None:
logger.debug("No AWS profile explicitly provided. "
"Falling back to default.")
profile = default_profile
logger.debug("Building session using profile \"%s\" in region \"%s\""
% (profile, region))
session = boto3.Session(region_name=region, profile_name=profile)
c = session._session.get_component('credential_provider')
provider = c.get_provider('assume-role')
provider.cache = credential_cache
provider._prompter = ui.getpass
return session | python | def get_session(region, profile=None):
"""Creates a boto3 session with a cache
Args:
region (str): The region for the session
profile (str): The profile for the session
Returns:
:class:`boto3.session.Session`: A boto3 session with
credential caching
"""
if profile is None:
logger.debug("No AWS profile explicitly provided. "
"Falling back to default.")
profile = default_profile
logger.debug("Building session using profile \"%s\" in region \"%s\""
% (profile, region))
session = boto3.Session(region_name=region, profile_name=profile)
c = session._session.get_component('credential_provider')
provider = c.get_provider('assume-role')
provider.cache = credential_cache
provider._prompter = ui.getpass
return session | [
"def",
"get_session",
"(",
"region",
",",
"profile",
"=",
"None",
")",
":",
"if",
"profile",
"is",
"None",
":",
"logger",
".",
"debug",
"(",
"\"No AWS profile explicitly provided. \"",
"\"Falling back to default.\"",
")",
"profile",
"=",
"default_profile",
"logger",... | Creates a boto3 session with a cache
Args:
region (str): The region for the session
profile (str): The profile for the session
Returns:
:class:`boto3.session.Session`: A boto3 session with
credential caching | [
"Creates",
"a",
"boto3",
"session",
"with",
"a",
"cache"
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/session_cache.py#L20-L44 | train | 214,638 |
cloudtools/stacker | stacker/lookups/registry.py | register_lookup_handler | def register_lookup_handler(lookup_type, handler_or_path):
"""Register a lookup handler.
Args:
lookup_type (str): Name to register the handler under
handler_or_path (OneOf[func, str]): a function or a path to a handler
"""
handler = handler_or_path
if isinstance(handler_or_path, basestring):
handler = load_object_from_string(handler_or_path)
LOOKUP_HANDLERS[lookup_type] = handler
if type(handler) != type:
# Hander is a not a new-style handler
logger = logging.getLogger(__name__)
logger.warning("Registering lookup `%s`: Please upgrade to use the "
"new style of Lookups." % lookup_type)
warnings.warn(
# For some reason, this does not show up...
# Leaving it in anyway
"Lookup `%s`: Please upgrade to use the new style of Lookups"
"." % lookup_type,
DeprecationWarning,
stacklevel=2,
) | python | def register_lookup_handler(lookup_type, handler_or_path):
"""Register a lookup handler.
Args:
lookup_type (str): Name to register the handler under
handler_or_path (OneOf[func, str]): a function or a path to a handler
"""
handler = handler_or_path
if isinstance(handler_or_path, basestring):
handler = load_object_from_string(handler_or_path)
LOOKUP_HANDLERS[lookup_type] = handler
if type(handler) != type:
# Hander is a not a new-style handler
logger = logging.getLogger(__name__)
logger.warning("Registering lookup `%s`: Please upgrade to use the "
"new style of Lookups." % lookup_type)
warnings.warn(
# For some reason, this does not show up...
# Leaving it in anyway
"Lookup `%s`: Please upgrade to use the new style of Lookups"
"." % lookup_type,
DeprecationWarning,
stacklevel=2,
) | [
"def",
"register_lookup_handler",
"(",
"lookup_type",
",",
"handler_or_path",
")",
":",
"handler",
"=",
"handler_or_path",
"if",
"isinstance",
"(",
"handler_or_path",
",",
"basestring",
")",
":",
"handler",
"=",
"load_object_from_string",
"(",
"handler_or_path",
")",
... | Register a lookup handler.
Args:
lookup_type (str): Name to register the handler under
handler_or_path (OneOf[func, str]): a function or a path to a handler | [
"Register",
"a",
"lookup",
"handler",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/lookups/registry.py#L29-L53 | train | 214,639 |
cloudtools/stacker | stacker/lookups/registry.py | resolve_lookups | def resolve_lookups(variable, context, provider):
"""Resolve a set of lookups.
Args:
variable (:class:`stacker.variables.Variable`): The variable resolving
it's lookups.
context (:class:`stacker.context.Context`): stacker context
provider (:class:`stacker.provider.base.BaseProvider`): subclass of the
base provider
Returns:
dict: dict of Lookup -> resolved value
"""
resolved_lookups = {}
for lookup in variable.lookups:
try:
handler = LOOKUP_HANDLERS[lookup.type]
except KeyError:
raise UnknownLookupType(lookup)
try:
resolved_lookups[lookup] = handler(
value=lookup.input,
context=context,
provider=provider,
)
except Exception as e:
raise FailedVariableLookup(variable.name, lookup, e)
return resolved_lookups | python | def resolve_lookups(variable, context, provider):
"""Resolve a set of lookups.
Args:
variable (:class:`stacker.variables.Variable`): The variable resolving
it's lookups.
context (:class:`stacker.context.Context`): stacker context
provider (:class:`stacker.provider.base.BaseProvider`): subclass of the
base provider
Returns:
dict: dict of Lookup -> resolved value
"""
resolved_lookups = {}
for lookup in variable.lookups:
try:
handler = LOOKUP_HANDLERS[lookup.type]
except KeyError:
raise UnknownLookupType(lookup)
try:
resolved_lookups[lookup] = handler(
value=lookup.input,
context=context,
provider=provider,
)
except Exception as e:
raise FailedVariableLookup(variable.name, lookup, e)
return resolved_lookups | [
"def",
"resolve_lookups",
"(",
"variable",
",",
"context",
",",
"provider",
")",
":",
"resolved_lookups",
"=",
"{",
"}",
"for",
"lookup",
"in",
"variable",
".",
"lookups",
":",
"try",
":",
"handler",
"=",
"LOOKUP_HANDLERS",
"[",
"lookup",
".",
"type",
"]",... | Resolve a set of lookups.
Args:
variable (:class:`stacker.variables.Variable`): The variable resolving
it's lookups.
context (:class:`stacker.context.Context`): stacker context
provider (:class:`stacker.provider.base.BaseProvider`): subclass of the
base provider
Returns:
dict: dict of Lookup -> resolved value | [
"Resolve",
"a",
"set",
"of",
"lookups",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/lookups/registry.py#L69-L97 | train | 214,640 |
cloudtools/stacker | stacker/lookups/handlers/default.py | DefaultLookup.handle | def handle(cls, value, **kwargs):
"""Use a value from the environment or fall back to a default if the
environment doesn't contain the variable.
Format of value:
<env_var>::<default value>
For example:
Groups: ${default app_security_groups::sg-12345,sg-67890}
If `app_security_groups` is defined in the environment, its defined
value will be returned. Otherwise, `sg-12345,sg-67890` will be the
returned value.
This allows defaults to be set at the config file level.
"""
try:
env_var_name, default_val = value.split("::", 1)
except ValueError:
raise ValueError("Invalid value for default: %s. Must be in "
"<env_var>::<default value> format." % value)
if env_var_name in kwargs['context'].environment:
return kwargs['context'].environment[env_var_name]
else:
return default_val | python | def handle(cls, value, **kwargs):
"""Use a value from the environment or fall back to a default if the
environment doesn't contain the variable.
Format of value:
<env_var>::<default value>
For example:
Groups: ${default app_security_groups::sg-12345,sg-67890}
If `app_security_groups` is defined in the environment, its defined
value will be returned. Otherwise, `sg-12345,sg-67890` will be the
returned value.
This allows defaults to be set at the config file level.
"""
try:
env_var_name, default_val = value.split("::", 1)
except ValueError:
raise ValueError("Invalid value for default: %s. Must be in "
"<env_var>::<default value> format." % value)
if env_var_name in kwargs['context'].environment:
return kwargs['context'].environment[env_var_name]
else:
return default_val | [
"def",
"handle",
"(",
"cls",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"env_var_name",
",",
"default_val",
"=",
"value",
".",
"split",
"(",
"\"::\"",
",",
"1",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"\"Invalid ... | Use a value from the environment or fall back to a default if the
environment doesn't contain the variable.
Format of value:
<env_var>::<default value>
For example:
Groups: ${default app_security_groups::sg-12345,sg-67890}
If `app_security_groups` is defined in the environment, its defined
value will be returned. Otherwise, `sg-12345,sg-67890` will be the
returned value.
This allows defaults to be set at the config file level. | [
"Use",
"a",
"value",
"from",
"the",
"environment",
"or",
"fall",
"back",
"to",
"a",
"default",
"if",
"the",
"environment",
"doesn",
"t",
"contain",
"the",
"variable",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/lookups/handlers/default.py#L13-L41 | train | 214,641 |
cloudtools/stacker | stacker/lookups/__init__.py | extract_lookups_from_string | def extract_lookups_from_string(value):
"""Extract any lookups within a string.
Args:
value (str): string value we're extracting lookups from
Returns:
list: list of :class:`stacker.lookups.Lookup` if any
"""
lookups = set()
for match in LOOKUP_REGEX.finditer(value):
groupdict = match.groupdict()
raw = match.groups()[0]
lookup_type = groupdict["type"]
lookup_input = groupdict["input"]
lookups.add(Lookup(lookup_type, lookup_input, raw))
return lookups | python | def extract_lookups_from_string(value):
"""Extract any lookups within a string.
Args:
value (str): string value we're extracting lookups from
Returns:
list: list of :class:`stacker.lookups.Lookup` if any
"""
lookups = set()
for match in LOOKUP_REGEX.finditer(value):
groupdict = match.groupdict()
raw = match.groups()[0]
lookup_type = groupdict["type"]
lookup_input = groupdict["input"]
lookups.add(Lookup(lookup_type, lookup_input, raw))
return lookups | [
"def",
"extract_lookups_from_string",
"(",
"value",
")",
":",
"lookups",
"=",
"set",
"(",
")",
"for",
"match",
"in",
"LOOKUP_REGEX",
".",
"finditer",
"(",
"value",
")",
":",
"groupdict",
"=",
"match",
".",
"groupdict",
"(",
")",
"raw",
"=",
"match",
".",... | Extract any lookups within a string.
Args:
value (str): string value we're extracting lookups from
Returns:
list: list of :class:`stacker.lookups.Lookup` if any | [
"Extract",
"any",
"lookups",
"within",
"a",
"string",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/lookups/__init__.py#L29-L46 | train | 214,642 |
cloudtools/stacker | stacker/lookups/__init__.py | extract_lookups | def extract_lookups(value):
"""Recursively extracts any stack lookups within the data structure.
Args:
value (one of str, list, dict): a structure that contains lookups to
output values
Returns:
list: list of lookups if any
"""
lookups = set()
if isinstance(value, basestring):
lookups = lookups.union(extract_lookups_from_string(value))
elif isinstance(value, list):
for v in value:
lookups = lookups.union(extract_lookups(v))
elif isinstance(value, dict):
for v in value.values():
lookups = lookups.union(extract_lookups(v))
return lookups | python | def extract_lookups(value):
"""Recursively extracts any stack lookups within the data structure.
Args:
value (one of str, list, dict): a structure that contains lookups to
output values
Returns:
list: list of lookups if any
"""
lookups = set()
if isinstance(value, basestring):
lookups = lookups.union(extract_lookups_from_string(value))
elif isinstance(value, list):
for v in value:
lookups = lookups.union(extract_lookups(v))
elif isinstance(value, dict):
for v in value.values():
lookups = lookups.union(extract_lookups(v))
return lookups | [
"def",
"extract_lookups",
"(",
"value",
")",
":",
"lookups",
"=",
"set",
"(",
")",
"if",
"isinstance",
"(",
"value",
",",
"basestring",
")",
":",
"lookups",
"=",
"lookups",
".",
"union",
"(",
"extract_lookups_from_string",
"(",
"value",
")",
")",
"elif",
... | Recursively extracts any stack lookups within the data structure.
Args:
value (one of str, list, dict): a structure that contains lookups to
output values
Returns:
list: list of lookups if any | [
"Recursively",
"extracts",
"any",
"stack",
"lookups",
"within",
"the",
"data",
"structure",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/lookups/__init__.py#L49-L69 | train | 214,643 |
cloudtools/stacker | stacker/dag/__init__.py | DAG.add_node | def add_node(self, node_name):
""" Add a node if it does not exist yet, or error out.
Args:
node_name (str): The unique name of the node to add.
Raises:
KeyError: Raised if a node with the same name already exist in the
graph
"""
graph = self.graph
if node_name in graph:
raise KeyError('node %s already exists' % node_name)
graph[node_name] = set() | python | def add_node(self, node_name):
""" Add a node if it does not exist yet, or error out.
Args:
node_name (str): The unique name of the node to add.
Raises:
KeyError: Raised if a node with the same name already exist in the
graph
"""
graph = self.graph
if node_name in graph:
raise KeyError('node %s already exists' % node_name)
graph[node_name] = set() | [
"def",
"add_node",
"(",
"self",
",",
"node_name",
")",
":",
"graph",
"=",
"self",
".",
"graph",
"if",
"node_name",
"in",
"graph",
":",
"raise",
"KeyError",
"(",
"'node %s already exists'",
"%",
"node_name",
")",
"graph",
"[",
"node_name",
"]",
"=",
"set",
... | Add a node if it does not exist yet, or error out.
Args:
node_name (str): The unique name of the node to add.
Raises:
KeyError: Raised if a node with the same name already exist in the
graph | [
"Add",
"a",
"node",
"if",
"it",
"does",
"not",
"exist",
"yet",
"or",
"error",
"out",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/dag/__init__.py#L32-L45 | train | 214,644 |
cloudtools/stacker | stacker/dag/__init__.py | DAG.transpose | def transpose(self):
""" Builds a new graph with the edges reversed.
Returns:
:class:`stacker.dag.DAG`: The transposed graph.
"""
graph = self.graph
transposed = DAG()
for node, edges in graph.items():
transposed.add_node(node)
for node, edges in graph.items():
# for each edge A -> B, transpose it so that B -> A
for edge in edges:
transposed.add_edge(edge, node)
return transposed | python | def transpose(self):
""" Builds a new graph with the edges reversed.
Returns:
:class:`stacker.dag.DAG`: The transposed graph.
"""
graph = self.graph
transposed = DAG()
for node, edges in graph.items():
transposed.add_node(node)
for node, edges in graph.items():
# for each edge A -> B, transpose it so that B -> A
for edge in edges:
transposed.add_edge(edge, node)
return transposed | [
"def",
"transpose",
"(",
"self",
")",
":",
"graph",
"=",
"self",
".",
"graph",
"transposed",
"=",
"DAG",
"(",
")",
"for",
"node",
",",
"edges",
"in",
"graph",
".",
"items",
"(",
")",
":",
"transposed",
".",
"add_node",
"(",
"node",
")",
"for",
"nod... | Builds a new graph with the edges reversed.
Returns:
:class:`stacker.dag.DAG`: The transposed graph. | [
"Builds",
"a",
"new",
"graph",
"with",
"the",
"edges",
"reversed",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/dag/__init__.py#L136-L150 | train | 214,645 |
cloudtools/stacker | stacker/dag/__init__.py | DAG.walk | def walk(self, walk_func):
""" Walks each node of the graph in reverse topological order.
This can be used to perform a set of operations, where the next
operation depends on the previous operation. It's important to note
that walking happens serially, and is not paralellized.
Args:
walk_func (:class:`types.FunctionType`): The function to be called
on each node of the graph.
"""
nodes = self.topological_sort()
# Reverse so we start with nodes that have no dependencies.
nodes.reverse()
for n in nodes:
walk_func(n) | python | def walk(self, walk_func):
""" Walks each node of the graph in reverse topological order.
This can be used to perform a set of operations, where the next
operation depends on the previous operation. It's important to note
that walking happens serially, and is not paralellized.
Args:
walk_func (:class:`types.FunctionType`): The function to be called
on each node of the graph.
"""
nodes = self.topological_sort()
# Reverse so we start with nodes that have no dependencies.
nodes.reverse()
for n in nodes:
walk_func(n) | [
"def",
"walk",
"(",
"self",
",",
"walk_func",
")",
":",
"nodes",
"=",
"self",
".",
"topological_sort",
"(",
")",
"# Reverse so we start with nodes that have no dependencies.",
"nodes",
".",
"reverse",
"(",
")",
"for",
"n",
"in",
"nodes",
":",
"walk_func",
"(",
... | Walks each node of the graph in reverse topological order.
This can be used to perform a set of operations, where the next
operation depends on the previous operation. It's important to note
that walking happens serially, and is not paralellized.
Args:
walk_func (:class:`types.FunctionType`): The function to be called
on each node of the graph. | [
"Walks",
"each",
"node",
"of",
"the",
"graph",
"in",
"reverse",
"topological",
"order",
".",
"This",
"can",
"be",
"used",
"to",
"perform",
"a",
"set",
"of",
"operations",
"where",
"the",
"next",
"operation",
"depends",
"on",
"the",
"previous",
"operation",
... | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/dag/__init__.py#L152-L167 | train | 214,646 |
cloudtools/stacker | stacker/dag/__init__.py | DAG.transitive_reduction | def transitive_reduction(self):
""" Performs a transitive reduction on the DAG. The transitive
reduction of a graph is a graph with as few edges as possible with the
same reachability as the original graph.
See https://en.wikipedia.org/wiki/Transitive_reduction
"""
combinations = []
for node, edges in self.graph.items():
combinations += [[node, edge] for edge in edges]
while True:
new_combinations = []
for comb1 in combinations:
for comb2 in combinations:
if not comb1[-1] == comb2[0]:
continue
new_entry = comb1 + comb2[1:]
if new_entry not in combinations:
new_combinations.append(new_entry)
if not new_combinations:
break
combinations += new_combinations
constructed = {(c[0], c[-1]) for c in combinations if len(c) != 2}
for node, edges in self.graph.items():
bad_nodes = {e for n, e in constructed if node == n}
self.graph[node] = edges - bad_nodes | python | def transitive_reduction(self):
""" Performs a transitive reduction on the DAG. The transitive
reduction of a graph is a graph with as few edges as possible with the
same reachability as the original graph.
See https://en.wikipedia.org/wiki/Transitive_reduction
"""
combinations = []
for node, edges in self.graph.items():
combinations += [[node, edge] for edge in edges]
while True:
new_combinations = []
for comb1 in combinations:
for comb2 in combinations:
if not comb1[-1] == comb2[0]:
continue
new_entry = comb1 + comb2[1:]
if new_entry not in combinations:
new_combinations.append(new_entry)
if not new_combinations:
break
combinations += new_combinations
constructed = {(c[0], c[-1]) for c in combinations if len(c) != 2}
for node, edges in self.graph.items():
bad_nodes = {e for n, e in constructed if node == n}
self.graph[node] = edges - bad_nodes | [
"def",
"transitive_reduction",
"(",
"self",
")",
":",
"combinations",
"=",
"[",
"]",
"for",
"node",
",",
"edges",
"in",
"self",
".",
"graph",
".",
"items",
"(",
")",
":",
"combinations",
"+=",
"[",
"[",
"node",
",",
"edge",
"]",
"for",
"edge",
"in",
... | Performs a transitive reduction on the DAG. The transitive
reduction of a graph is a graph with as few edges as possible with the
same reachability as the original graph.
See https://en.wikipedia.org/wiki/Transitive_reduction | [
"Performs",
"a",
"transitive",
"reduction",
"on",
"the",
"DAG",
".",
"The",
"transitive",
"reduction",
"of",
"a",
"graph",
"is",
"a",
"graph",
"with",
"as",
"few",
"edges",
"as",
"possible",
"with",
"the",
"same",
"reachability",
"as",
"the",
"original",
"... | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/dag/__init__.py#L169-L196 | train | 214,647 |
cloudtools/stacker | stacker/dag/__init__.py | DAG.rename_edges | def rename_edges(self, old_node_name, new_node_name):
""" Change references to a node in existing edges.
Args:
old_node_name (str): The old name for the node.
new_node_name (str): The new name for the node.
"""
graph = self.graph
for node, edges in graph.items():
if node == old_node_name:
graph[new_node_name] = copy(edges)
del graph[old_node_name]
else:
if old_node_name in edges:
edges.remove(old_node_name)
edges.add(new_node_name) | python | def rename_edges(self, old_node_name, new_node_name):
""" Change references to a node in existing edges.
Args:
old_node_name (str): The old name for the node.
new_node_name (str): The new name for the node.
"""
graph = self.graph
for node, edges in graph.items():
if node == old_node_name:
graph[new_node_name] = copy(edges)
del graph[old_node_name]
else:
if old_node_name in edges:
edges.remove(old_node_name)
edges.add(new_node_name) | [
"def",
"rename_edges",
"(",
"self",
",",
"old_node_name",
",",
"new_node_name",
")",
":",
"graph",
"=",
"self",
".",
"graph",
"for",
"node",
",",
"edges",
"in",
"graph",
".",
"items",
"(",
")",
":",
"if",
"node",
"==",
"old_node_name",
":",
"graph",
"[... | Change references to a node in existing edges.
Args:
old_node_name (str): The old name for the node.
new_node_name (str): The new name for the node. | [
"Change",
"references",
"to",
"a",
"node",
"in",
"existing",
"edges",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/dag/__init__.py#L198-L214 | train | 214,648 |
cloudtools/stacker | stacker/dag/__init__.py | DAG.downstream | def downstream(self, node):
""" Returns a list of all nodes this node has edges towards.
Args:
node (str): The node whose downstream nodes you want to find.
Returns:
list: A list of nodes that are immediately downstream from the
node.
"""
graph = self.graph
if node not in graph:
raise KeyError('node %s is not in graph' % node)
return list(graph[node]) | python | def downstream(self, node):
""" Returns a list of all nodes this node has edges towards.
Args:
node (str): The node whose downstream nodes you want to find.
Returns:
list: A list of nodes that are immediately downstream from the
node.
"""
graph = self.graph
if node not in graph:
raise KeyError('node %s is not in graph' % node)
return list(graph[node]) | [
"def",
"downstream",
"(",
"self",
",",
"node",
")",
":",
"graph",
"=",
"self",
".",
"graph",
"if",
"node",
"not",
"in",
"graph",
":",
"raise",
"KeyError",
"(",
"'node %s is not in graph'",
"%",
"node",
")",
"return",
"list",
"(",
"graph",
"[",
"node",
... | Returns a list of all nodes this node has edges towards.
Args:
node (str): The node whose downstream nodes you want to find.
Returns:
list: A list of nodes that are immediately downstream from the
node. | [
"Returns",
"a",
"list",
"of",
"all",
"nodes",
"this",
"node",
"has",
"edges",
"towards",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/dag/__init__.py#L228-L241 | train | 214,649 |
cloudtools/stacker | stacker/dag/__init__.py | DAG.filter | def filter(self, nodes):
""" Returns a new DAG with only the given nodes and their
dependencies.
Args:
nodes (list): The nodes you are interested in.
Returns:
:class:`stacker.dag.DAG`: The filtered graph.
"""
filtered_dag = DAG()
# Add only the nodes we need.
for node in nodes:
filtered_dag.add_node_if_not_exists(node)
for edge in self.all_downstreams(node):
filtered_dag.add_node_if_not_exists(edge)
# Now, rebuild the graph for each node that's present.
for node, edges in self.graph.items():
if node in filtered_dag.graph:
filtered_dag.graph[node] = edges
return filtered_dag | python | def filter(self, nodes):
""" Returns a new DAG with only the given nodes and their
dependencies.
Args:
nodes (list): The nodes you are interested in.
Returns:
:class:`stacker.dag.DAG`: The filtered graph.
"""
filtered_dag = DAG()
# Add only the nodes we need.
for node in nodes:
filtered_dag.add_node_if_not_exists(node)
for edge in self.all_downstreams(node):
filtered_dag.add_node_if_not_exists(edge)
# Now, rebuild the graph for each node that's present.
for node, edges in self.graph.items():
if node in filtered_dag.graph:
filtered_dag.graph[node] = edges
return filtered_dag | [
"def",
"filter",
"(",
"self",
",",
"nodes",
")",
":",
"filtered_dag",
"=",
"DAG",
"(",
")",
"# Add only the nodes we need.",
"for",
"node",
"in",
"nodes",
":",
"filtered_dag",
".",
"add_node_if_not_exists",
"(",
"node",
")",
"for",
"edge",
"in",
"self",
".",... | Returns a new DAG with only the given nodes and their
dependencies.
Args:
nodes (list): The nodes you are interested in.
Returns:
:class:`stacker.dag.DAG`: The filtered graph. | [
"Returns",
"a",
"new",
"DAG",
"with",
"only",
"the",
"given",
"nodes",
"and",
"their",
"dependencies",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/dag/__init__.py#L268-L292 | train | 214,650 |
cloudtools/stacker | stacker/dag/__init__.py | DAG.topological_sort | def topological_sort(self):
""" Returns a topological ordering of the DAG.
Returns:
list: A list of topologically sorted nodes in the graph.
Raises:
ValueError: Raised if the graph is not acyclic.
"""
graph = self.graph
in_degree = {}
for u in graph:
in_degree[u] = 0
for u in graph:
for v in graph[u]:
in_degree[v] += 1
queue = deque()
for u in in_degree:
if in_degree[u] == 0:
queue.appendleft(u)
sorted_graph = []
while queue:
u = queue.pop()
sorted_graph.append(u)
for v in sorted(graph[u]):
in_degree[v] -= 1
if in_degree[v] == 0:
queue.appendleft(v)
if len(sorted_graph) == len(graph):
return sorted_graph
else:
raise ValueError('graph is not acyclic') | python | def topological_sort(self):
""" Returns a topological ordering of the DAG.
Returns:
list: A list of topologically sorted nodes in the graph.
Raises:
ValueError: Raised if the graph is not acyclic.
"""
graph = self.graph
in_degree = {}
for u in graph:
in_degree[u] = 0
for u in graph:
for v in graph[u]:
in_degree[v] += 1
queue = deque()
for u in in_degree:
if in_degree[u] == 0:
queue.appendleft(u)
sorted_graph = []
while queue:
u = queue.pop()
sorted_graph.append(u)
for v in sorted(graph[u]):
in_degree[v] -= 1
if in_degree[v] == 0:
queue.appendleft(v)
if len(sorted_graph) == len(graph):
return sorted_graph
else:
raise ValueError('graph is not acyclic') | [
"def",
"topological_sort",
"(",
"self",
")",
":",
"graph",
"=",
"self",
".",
"graph",
"in_degree",
"=",
"{",
"}",
"for",
"u",
"in",
"graph",
":",
"in_degree",
"[",
"u",
"]",
"=",
"0",
"for",
"u",
"in",
"graph",
":",
"for",
"v",
"in",
"graph",
"["... | Returns a topological ordering of the DAG.
Returns:
list: A list of topologically sorted nodes in the graph.
Raises:
ValueError: Raised if the graph is not acyclic. | [
"Returns",
"a",
"topological",
"ordering",
"of",
"the",
"DAG",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/dag/__init__.py#L351-L387 | train | 214,651 |
cloudtools/stacker | stacker/dag/__init__.py | ThreadedWalker.walk | def walk(self, dag, walk_func):
""" Walks each node of the graph, in parallel if it can.
The walk_func is only called when the nodes dependencies have been
satisfied
"""
# First, we'll topologically sort all of the nodes, with nodes that
# have no dependencies first. We do this to ensure that we don't call
# .join on a thread that hasn't yet been started.
#
# TODO(ejholmes): An alternative would be to ensure that Thread.join
# blocks if the thread has not yet been started.
nodes = dag.topological_sort()
nodes.reverse()
# This maps a node name to a thread of execution.
threads = {}
# Blocks until all of the given nodes have completed execution (whether
# successfully, or errored). Returns True if all nodes returned True.
def wait_for(nodes):
for node in nodes:
thread = threads[node]
while thread.is_alive():
threads[node].join(0.5)
# For each node in the graph, we're going to allocate a thread to
# execute. The thread will block executing walk_func, until all of the
# nodes dependencies have executed.
for node in nodes:
def fn(n, deps):
if deps:
logger.debug(
"%s waiting for %s to complete",
n,
", ".join(deps))
# Wait for all dependencies to complete.
wait_for(deps)
logger.debug("%s starting", n)
self.semaphore.acquire()
try:
return walk_func(n)
finally:
self.semaphore.release()
deps = dag.all_downstreams(node)
threads[node] = Thread(target=fn, args=(node, deps), name=node)
# Start up all of the threads.
for node in nodes:
threads[node].start()
# Wait for all threads to complete executing.
wait_for(nodes) | python | def walk(self, dag, walk_func):
""" Walks each node of the graph, in parallel if it can.
The walk_func is only called when the nodes dependencies have been
satisfied
"""
# First, we'll topologically sort all of the nodes, with nodes that
# have no dependencies first. We do this to ensure that we don't call
# .join on a thread that hasn't yet been started.
#
# TODO(ejholmes): An alternative would be to ensure that Thread.join
# blocks if the thread has not yet been started.
nodes = dag.topological_sort()
nodes.reverse()
# This maps a node name to a thread of execution.
threads = {}
# Blocks until all of the given nodes have completed execution (whether
# successfully, or errored). Returns True if all nodes returned True.
def wait_for(nodes):
for node in nodes:
thread = threads[node]
while thread.is_alive():
threads[node].join(0.5)
# For each node in the graph, we're going to allocate a thread to
# execute. The thread will block executing walk_func, until all of the
# nodes dependencies have executed.
for node in nodes:
def fn(n, deps):
if deps:
logger.debug(
"%s waiting for %s to complete",
n,
", ".join(deps))
# Wait for all dependencies to complete.
wait_for(deps)
logger.debug("%s starting", n)
self.semaphore.acquire()
try:
return walk_func(n)
finally:
self.semaphore.release()
deps = dag.all_downstreams(node)
threads[node] = Thread(target=fn, args=(node, deps), name=node)
# Start up all of the threads.
for node in nodes:
threads[node].start()
# Wait for all threads to complete executing.
wait_for(nodes) | [
"def",
"walk",
"(",
"self",
",",
"dag",
",",
"walk_func",
")",
":",
"# First, we'll topologically sort all of the nodes, with nodes that",
"# have no dependencies first. We do this to ensure that we don't call",
"# .join on a thread that hasn't yet been started.",
"#",
"# TODO(ejholmes):... | Walks each node of the graph, in parallel if it can.
The walk_func is only called when the nodes dependencies have been
satisfied | [
"Walks",
"each",
"node",
"of",
"the",
"graph",
"in",
"parallel",
"if",
"it",
"can",
".",
"The",
"walk_func",
"is",
"only",
"called",
"when",
"the",
"nodes",
"dependencies",
"have",
"been",
"satisfied"
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/dag/__init__.py#L424-L480 | train | 214,652 |
cloudtools/stacker | stacker/tokenize_userdata.py | cf_tokenize | def cf_tokenize(s):
""" Parses UserData for Cloudformation helper functions.
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference.html
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/quickref-cloudformation.html#scenario-userdata-base64
It breaks apart the given string at each recognized function (see HELPERS)
and instantiates the helper function objects in place of those.
Returns a list of parts as a result. Useful when used with Join() and
Base64() CloudFormation functions to produce user data.
ie: Base64(Join('', cf_tokenize(userdata_string)))
"""
t = []
parts = split_re.split(s)
for part in parts:
cf_func = replace_re.search(part)
if cf_func:
args = [a.strip("'\" ") for a in cf_func.group("args").split(",")]
t.append(HELPERS[cf_func.group("helper")](*args).data)
else:
t.append(part)
return t | python | def cf_tokenize(s):
""" Parses UserData for Cloudformation helper functions.
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference.html
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/quickref-cloudformation.html#scenario-userdata-base64
It breaks apart the given string at each recognized function (see HELPERS)
and instantiates the helper function objects in place of those.
Returns a list of parts as a result. Useful when used with Join() and
Base64() CloudFormation functions to produce user data.
ie: Base64(Join('', cf_tokenize(userdata_string)))
"""
t = []
parts = split_re.split(s)
for part in parts:
cf_func = replace_re.search(part)
if cf_func:
args = [a.strip("'\" ") for a in cf_func.group("args").split(",")]
t.append(HELPERS[cf_func.group("helper")](*args).data)
else:
t.append(part)
return t | [
"def",
"cf_tokenize",
"(",
"s",
")",
":",
"t",
"=",
"[",
"]",
"parts",
"=",
"split_re",
".",
"split",
"(",
"s",
")",
"for",
"part",
"in",
"parts",
":",
"cf_func",
"=",
"replace_re",
".",
"search",
"(",
"part",
")",
"if",
"cf_func",
":",
"args",
"... | Parses UserData for Cloudformation helper functions.
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference.html
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/quickref-cloudformation.html#scenario-userdata-base64
It breaks apart the given string at each recognized function (see HELPERS)
and instantiates the helper function objects in place of those.
Returns a list of parts as a result. Useful when used with Join() and
Base64() CloudFormation functions to produce user data.
ie: Base64(Join('', cf_tokenize(userdata_string))) | [
"Parses",
"UserData",
"for",
"Cloudformation",
"helper",
"functions",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/tokenize_userdata.py#L22-L46 | train | 214,653 |
cloudtools/stacker | stacker/lookups/handlers/split.py | SplitLookup.handle | def handle(cls, value, **kwargs):
"""Split the supplied string on the given delimiter, providing a list.
Format of value:
<delimiter>::<value>
For example:
Subnets: ${split ,::subnet-1,subnet-2,subnet-3}
Would result in the variable `Subnets` getting a list consisting of:
["subnet-1", "subnet-2", "subnet-3"]
This is particularly useful when getting an output from another stack
that contains a list. For example, the standard vpc blueprint outputs
the list of Subnets it creates as a pair of Outputs (PublicSubnets,
PrivateSubnets) that are comma separated, so you could use this in your
config:
Subnets: ${split ,::${output vpc::PrivateSubnets}}
"""
try:
delimiter, text = value.split("::", 1)
except ValueError:
raise ValueError("Invalid value for split: %s. Must be in "
"<delimiter>::<text> format." % value)
return text.split(delimiter) | python | def handle(cls, value, **kwargs):
"""Split the supplied string on the given delimiter, providing a list.
Format of value:
<delimiter>::<value>
For example:
Subnets: ${split ,::subnet-1,subnet-2,subnet-3}
Would result in the variable `Subnets` getting a list consisting of:
["subnet-1", "subnet-2", "subnet-3"]
This is particularly useful when getting an output from another stack
that contains a list. For example, the standard vpc blueprint outputs
the list of Subnets it creates as a pair of Outputs (PublicSubnets,
PrivateSubnets) that are comma separated, so you could use this in your
config:
Subnets: ${split ,::${output vpc::PrivateSubnets}}
"""
try:
delimiter, text = value.split("::", 1)
except ValueError:
raise ValueError("Invalid value for split: %s. Must be in "
"<delimiter>::<text> format." % value)
return text.split(delimiter) | [
"def",
"handle",
"(",
"cls",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"delimiter",
",",
"text",
"=",
"value",
".",
"split",
"(",
"\"::\"",
",",
"1",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for ... | Split the supplied string on the given delimiter, providing a list.
Format of value:
<delimiter>::<value>
For example:
Subnets: ${split ,::subnet-1,subnet-2,subnet-3}
Would result in the variable `Subnets` getting a list consisting of:
["subnet-1", "subnet-2", "subnet-3"]
This is particularly useful when getting an output from another stack
that contains a list. For example, the standard vpc blueprint outputs
the list of Subnets it creates as a pair of Outputs (PublicSubnets,
PrivateSubnets) that are comma separated, so you could use this in your
config:
Subnets: ${split ,::${output vpc::PrivateSubnets}} | [
"Split",
"the",
"supplied",
"string",
"on",
"the",
"given",
"delimiter",
"providing",
"a",
"list",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/lookups/handlers/split.py#L10-L40 | train | 214,654 |
cloudtools/stacker | stacker/actions/build.py | should_update | def should_update(stack):
"""Tests whether a stack should be submitted for updates to CF.
Args:
stack (:class:`stacker.stack.Stack`): The stack object to check.
Returns:
bool: If the stack should be updated, return True.
"""
if stack.locked:
if not stack.force:
logger.debug("Stack %s locked and not in --force list. "
"Refusing to update.", stack.name)
return False
else:
logger.debug("Stack %s locked, but is in --force "
"list.", stack.name)
return True | python | def should_update(stack):
"""Tests whether a stack should be submitted for updates to CF.
Args:
stack (:class:`stacker.stack.Stack`): The stack object to check.
Returns:
bool: If the stack should be updated, return True.
"""
if stack.locked:
if not stack.force:
logger.debug("Stack %s locked and not in --force list. "
"Refusing to update.", stack.name)
return False
else:
logger.debug("Stack %s locked, but is in --force "
"list.", stack.name)
return True | [
"def",
"should_update",
"(",
"stack",
")",
":",
"if",
"stack",
".",
"locked",
":",
"if",
"not",
"stack",
".",
"force",
":",
"logger",
".",
"debug",
"(",
"\"Stack %s locked and not in --force list. \"",
"\"Refusing to update.\"",
",",
"stack",
".",
"name",
")",
... | Tests whether a stack should be submitted for updates to CF.
Args:
stack (:class:`stacker.stack.Stack`): The stack object to check.
Returns:
bool: If the stack should be updated, return True. | [
"Tests",
"whether",
"a",
"stack",
"should",
"be",
"submitted",
"for",
"updates",
"to",
"CF",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/build.py#L41-L59 | train | 214,655 |
cloudtools/stacker | stacker/actions/build.py | _resolve_parameters | def _resolve_parameters(parameters, blueprint):
"""Resolves CloudFormation Parameters for a given blueprint.
Given a list of parameters, handles:
- discard any parameters that the blueprint does not use
- discard any empty values
- convert booleans to strings suitable for CloudFormation
Args:
parameters (dict): A dictionary of parameters provided by the
stack definition
blueprint (:class:`stacker.blueprint.base.Blueprint`): A Blueprint
object that is having the parameters applied to it.
Returns:
dict: The resolved parameters.
"""
params = {}
param_defs = blueprint.get_parameter_definitions()
for key, value in parameters.items():
if key not in param_defs:
logger.debug("Blueprint %s does not use parameter %s.",
blueprint.name, key)
continue
if value is None:
logger.debug("Got None value for parameter %s, not submitting it "
"to cloudformation, default value should be used.",
key)
continue
if isinstance(value, bool):
logger.debug("Converting parameter %s boolean \"%s\" to string.",
key, value)
value = str(value).lower()
params[key] = value
return params | python | def _resolve_parameters(parameters, blueprint):
"""Resolves CloudFormation Parameters for a given blueprint.
Given a list of parameters, handles:
- discard any parameters that the blueprint does not use
- discard any empty values
- convert booleans to strings suitable for CloudFormation
Args:
parameters (dict): A dictionary of parameters provided by the
stack definition
blueprint (:class:`stacker.blueprint.base.Blueprint`): A Blueprint
object that is having the parameters applied to it.
Returns:
dict: The resolved parameters.
"""
params = {}
param_defs = blueprint.get_parameter_definitions()
for key, value in parameters.items():
if key not in param_defs:
logger.debug("Blueprint %s does not use parameter %s.",
blueprint.name, key)
continue
if value is None:
logger.debug("Got None value for parameter %s, not submitting it "
"to cloudformation, default value should be used.",
key)
continue
if isinstance(value, bool):
logger.debug("Converting parameter %s boolean \"%s\" to string.",
key, value)
value = str(value).lower()
params[key] = value
return params | [
"def",
"_resolve_parameters",
"(",
"parameters",
",",
"blueprint",
")",
":",
"params",
"=",
"{",
"}",
"param_defs",
"=",
"blueprint",
".",
"get_parameter_definitions",
"(",
")",
"for",
"key",
",",
"value",
"in",
"parameters",
".",
"items",
"(",
")",
":",
"... | Resolves CloudFormation Parameters for a given blueprint.
Given a list of parameters, handles:
- discard any parameters that the blueprint does not use
- discard any empty values
- convert booleans to strings suitable for CloudFormation
Args:
parameters (dict): A dictionary of parameters provided by the
stack definition
blueprint (:class:`stacker.blueprint.base.Blueprint`): A Blueprint
object that is having the parameters applied to it.
Returns:
dict: The resolved parameters. | [
"Resolves",
"CloudFormation",
"Parameters",
"for",
"a",
"given",
"blueprint",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/build.py#L93-L129 | train | 214,656 |
cloudtools/stacker | stacker/actions/build.py | _handle_missing_parameters | def _handle_missing_parameters(parameter_values, all_params, required_params,
existing_stack=None):
"""Handles any missing parameters.
If an existing_stack is provided, look up missing parameters there.
Args:
parameter_values (dict): key/value dictionary of stack definition
parameters
all_params (list): A list of all the parameters used by the
template/blueprint.
required_params (list): A list of all the parameters required by the
template/blueprint.
existing_stack (dict): A dict representation of the stack. If
provided, will be searched for any missing parameters.
Returns:
list of tuples: The final list of key/value pairs returned as a
list of tuples.
Raises:
MissingParameterException: Raised if a required parameter is
still missing.
"""
missing_params = list(set(all_params) - set(parameter_values.keys()))
if existing_stack and 'Parameters' in existing_stack:
stack_parameters = [
p["ParameterKey"] for p in existing_stack["Parameters"]
]
for p in missing_params:
if p in stack_parameters:
logger.debug(
"Using previous value for parameter %s from existing "
"stack",
p
)
parameter_values[p] = UsePreviousParameterValue
final_missing = list(set(required_params) - set(parameter_values.keys()))
if final_missing:
raise MissingParameterException(final_missing)
return list(parameter_values.items()) | python | def _handle_missing_parameters(parameter_values, all_params, required_params,
existing_stack=None):
"""Handles any missing parameters.
If an existing_stack is provided, look up missing parameters there.
Args:
parameter_values (dict): key/value dictionary of stack definition
parameters
all_params (list): A list of all the parameters used by the
template/blueprint.
required_params (list): A list of all the parameters required by the
template/blueprint.
existing_stack (dict): A dict representation of the stack. If
provided, will be searched for any missing parameters.
Returns:
list of tuples: The final list of key/value pairs returned as a
list of tuples.
Raises:
MissingParameterException: Raised if a required parameter is
still missing.
"""
missing_params = list(set(all_params) - set(parameter_values.keys()))
if existing_stack and 'Parameters' in existing_stack:
stack_parameters = [
p["ParameterKey"] for p in existing_stack["Parameters"]
]
for p in missing_params:
if p in stack_parameters:
logger.debug(
"Using previous value for parameter %s from existing "
"stack",
p
)
parameter_values[p] = UsePreviousParameterValue
final_missing = list(set(required_params) - set(parameter_values.keys()))
if final_missing:
raise MissingParameterException(final_missing)
return list(parameter_values.items()) | [
"def",
"_handle_missing_parameters",
"(",
"parameter_values",
",",
"all_params",
",",
"required_params",
",",
"existing_stack",
"=",
"None",
")",
":",
"missing_params",
"=",
"list",
"(",
"set",
"(",
"all_params",
")",
"-",
"set",
"(",
"parameter_values",
".",
"k... | Handles any missing parameters.
If an existing_stack is provided, look up missing parameters there.
Args:
parameter_values (dict): key/value dictionary of stack definition
parameters
all_params (list): A list of all the parameters used by the
template/blueprint.
required_params (list): A list of all the parameters required by the
template/blueprint.
existing_stack (dict): A dict representation of the stack. If
provided, will be searched for any missing parameters.
Returns:
list of tuples: The final list of key/value pairs returned as a
list of tuples.
Raises:
MissingParameterException: Raised if a required parameter is
still missing. | [
"Handles",
"any",
"missing",
"parameters",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/build.py#L139-L181 | train | 214,657 |
cloudtools/stacker | stacker/actions/build.py | Action.build_parameters | def build_parameters(self, stack, provider_stack=None):
"""Builds the CloudFormation Parameters for our stack.
Args:
stack (:class:`stacker.stack.Stack`): A stacker stack
provider_stack (dict): An optional Stacker provider object
Returns:
dict: The parameters for the given stack
"""
resolved = _resolve_parameters(stack.parameter_values, stack.blueprint)
required_parameters = list(stack.required_parameter_definitions)
all_parameters = list(stack.all_parameter_definitions)
parameters = _handle_missing_parameters(resolved, all_parameters,
required_parameters,
provider_stack)
param_list = []
for key, value in parameters:
param_dict = {"ParameterKey": key}
if value is UsePreviousParameterValue:
param_dict["UsePreviousValue"] = True
else:
param_dict["ParameterValue"] = str(value)
param_list.append(param_dict)
return param_list | python | def build_parameters(self, stack, provider_stack=None):
"""Builds the CloudFormation Parameters for our stack.
Args:
stack (:class:`stacker.stack.Stack`): A stacker stack
provider_stack (dict): An optional Stacker provider object
Returns:
dict: The parameters for the given stack
"""
resolved = _resolve_parameters(stack.parameter_values, stack.blueprint)
required_parameters = list(stack.required_parameter_definitions)
all_parameters = list(stack.all_parameter_definitions)
parameters = _handle_missing_parameters(resolved, all_parameters,
required_parameters,
provider_stack)
param_list = []
for key, value in parameters:
param_dict = {"ParameterKey": key}
if value is UsePreviousParameterValue:
param_dict["UsePreviousValue"] = True
else:
param_dict["ParameterValue"] = str(value)
param_list.append(param_dict)
return param_list | [
"def",
"build_parameters",
"(",
"self",
",",
"stack",
",",
"provider_stack",
"=",
"None",
")",
":",
"resolved",
"=",
"_resolve_parameters",
"(",
"stack",
".",
"parameter_values",
",",
"stack",
".",
"blueprint",
")",
"required_parameters",
"=",
"list",
"(",
"st... | Builds the CloudFormation Parameters for our stack.
Args:
stack (:class:`stacker.stack.Stack`): A stacker stack
provider_stack (dict): An optional Stacker provider object
Returns:
dict: The parameters for the given stack | [
"Builds",
"the",
"CloudFormation",
"Parameters",
"for",
"our",
"stack",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/build.py#L222-L251 | train | 214,658 |
cloudtools/stacker | stacker/actions/build.py | Action._template | def _template(self, blueprint):
"""Generates a suitable template based on whether or not an S3 bucket
is set.
If an S3 bucket is set, then the template will be uploaded to S3 first,
and CreateStack/UpdateStack operations will use the uploaded template.
If not bucket is set, then the template will be inlined.
"""
if self.bucket_name:
return Template(url=self.s3_stack_push(blueprint))
else:
return Template(body=blueprint.rendered) | python | def _template(self, blueprint):
"""Generates a suitable template based on whether or not an S3 bucket
is set.
If an S3 bucket is set, then the template will be uploaded to S3 first,
and CreateStack/UpdateStack operations will use the uploaded template.
If not bucket is set, then the template will be inlined.
"""
if self.bucket_name:
return Template(url=self.s3_stack_push(blueprint))
else:
return Template(body=blueprint.rendered) | [
"def",
"_template",
"(",
"self",
",",
"blueprint",
")",
":",
"if",
"self",
".",
"bucket_name",
":",
"return",
"Template",
"(",
"url",
"=",
"self",
".",
"s3_stack_push",
"(",
"blueprint",
")",
")",
"else",
":",
"return",
"Template",
"(",
"body",
"=",
"b... | Generates a suitable template based on whether or not an S3 bucket
is set.
If an S3 bucket is set, then the template will be uploaded to S3 first,
and CreateStack/UpdateStack operations will use the uploaded template.
If not bucket is set, then the template will be inlined. | [
"Generates",
"a",
"suitable",
"template",
"based",
"on",
"whether",
"or",
"not",
"an",
"S3",
"bucket",
"is",
"set",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/build.py#L375-L386 | train | 214,659 |
cloudtools/stacker | stacker/hooks/route53.py | create_domain | def create_domain(provider, context, **kwargs):
"""Create a domain within route53.
Args:
provider (:class:`stacker.providers.base.BaseProvider`): provider
instance
context (:class:`stacker.context.Context`): context instance
Returns: boolean for whether or not the hook succeeded.
"""
session = get_session(provider.region)
client = session.client("route53")
domain = kwargs.get("domain")
if not domain:
logger.error("domain argument or BaseDomain variable not provided.")
return False
zone_id = create_route53_zone(client, domain)
return {"domain": domain, "zone_id": zone_id} | python | def create_domain(provider, context, **kwargs):
"""Create a domain within route53.
Args:
provider (:class:`stacker.providers.base.BaseProvider`): provider
instance
context (:class:`stacker.context.Context`): context instance
Returns: boolean for whether or not the hook succeeded.
"""
session = get_session(provider.region)
client = session.client("route53")
domain = kwargs.get("domain")
if not domain:
logger.error("domain argument or BaseDomain variable not provided.")
return False
zone_id = create_route53_zone(client, domain)
return {"domain": domain, "zone_id": zone_id} | [
"def",
"create_domain",
"(",
"provider",
",",
"context",
",",
"*",
"*",
"kwargs",
")",
":",
"session",
"=",
"get_session",
"(",
"provider",
".",
"region",
")",
"client",
"=",
"session",
".",
"client",
"(",
"\"route53\"",
")",
"domain",
"=",
"kwargs",
"."... | Create a domain within route53.
Args:
provider (:class:`stacker.providers.base.BaseProvider`): provider
instance
context (:class:`stacker.context.Context`): context instance
Returns: boolean for whether or not the hook succeeded. | [
"Create",
"a",
"domain",
"within",
"route53",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/hooks/route53.py#L13-L31 | train | 214,660 |
cloudtools/stacker | stacker/ui.py | UI.info | def info(self, *args, **kwargs):
"""Logs the line of the current thread owns the underlying lock, or
blocks."""
self.lock()
try:
return logger.info(*args, **kwargs)
finally:
self.unlock() | python | def info(self, *args, **kwargs):
"""Logs the line of the current thread owns the underlying lock, or
blocks."""
self.lock()
try:
return logger.info(*args, **kwargs)
finally:
self.unlock() | [
"def",
"info",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"lock",
"(",
")",
"try",
":",
"return",
"logger",
".",
"info",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"finally",
":",
"self",
".",
"unlock",
... | Logs the line of the current thread owns the underlying lock, or
blocks. | [
"Logs",
"the",
"line",
"of",
"the",
"current",
"thread",
"owns",
"the",
"underlying",
"lock",
"or",
"blocks",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/ui.py#L37-L44 | train | 214,661 |
cloudtools/stacker | stacker/util.py | camel_to_snake | def camel_to_snake(name):
"""Converts CamelCase to snake_case.
Args:
name (string): The name to convert from CamelCase to snake_case.
Returns:
string: Converted string.
"""
s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name)
return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower() | python | def camel_to_snake(name):
"""Converts CamelCase to snake_case.
Args:
name (string): The name to convert from CamelCase to snake_case.
Returns:
string: Converted string.
"""
s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name)
return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower() | [
"def",
"camel_to_snake",
"(",
"name",
")",
":",
"s1",
"=",
"re",
".",
"sub",
"(",
"\"(.)([A-Z][a-z]+)\"",
",",
"r\"\\1_\\2\"",
",",
"name",
")",
"return",
"re",
".",
"sub",
"(",
"\"([a-z0-9])([A-Z])\"",
",",
"r\"\\1_\\2\"",
",",
"s1",
")",
".",
"lower",
... | Converts CamelCase to snake_case.
Args:
name (string): The name to convert from CamelCase to snake_case.
Returns:
string: Converted string. | [
"Converts",
"CamelCase",
"to",
"snake_case",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L34-L44 | train | 214,662 |
cloudtools/stacker | stacker/util.py | get_hosted_zone_by_name | def get_hosted_zone_by_name(client, zone_name):
"""Get the zone id of an existing zone by name.
Args:
client (:class:`botocore.client.Route53`): The connection used to
interact with Route53's API.
zone_name (string): The name of the DNS hosted zone to create.
Returns:
string: The Id of the Hosted Zone.
"""
p = client.get_paginator("list_hosted_zones")
for i in p.paginate():
for zone in i["HostedZones"]:
if zone["Name"] == zone_name:
return parse_zone_id(zone["Id"])
return None | python | def get_hosted_zone_by_name(client, zone_name):
"""Get the zone id of an existing zone by name.
Args:
client (:class:`botocore.client.Route53`): The connection used to
interact with Route53's API.
zone_name (string): The name of the DNS hosted zone to create.
Returns:
string: The Id of the Hosted Zone.
"""
p = client.get_paginator("list_hosted_zones")
for i in p.paginate():
for zone in i["HostedZones"]:
if zone["Name"] == zone_name:
return parse_zone_id(zone["Id"])
return None | [
"def",
"get_hosted_zone_by_name",
"(",
"client",
",",
"zone_name",
")",
":",
"p",
"=",
"client",
".",
"get_paginator",
"(",
"\"list_hosted_zones\"",
")",
"for",
"i",
"in",
"p",
".",
"paginate",
"(",
")",
":",
"for",
"zone",
"in",
"i",
"[",
"\"HostedZones\"... | Get the zone id of an existing zone by name.
Args:
client (:class:`botocore.client.Route53`): The connection used to
interact with Route53's API.
zone_name (string): The name of the DNS hosted zone to create.
Returns:
string: The Id of the Hosted Zone. | [
"Get",
"the",
"zone",
"id",
"of",
"an",
"existing",
"zone",
"by",
"name",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L64-L81 | train | 214,663 |
cloudtools/stacker | stacker/util.py | get_or_create_hosted_zone | def get_or_create_hosted_zone(client, zone_name):
"""Get the Id of an existing zone, or create it.
Args:
client (:class:`botocore.client.Route53`): The connection used to
interact with Route53's API.
zone_name (string): The name of the DNS hosted zone to create.
Returns:
string: The Id of the Hosted Zone.
"""
zone_id = get_hosted_zone_by_name(client, zone_name)
if zone_id:
return zone_id
logger.debug("Zone %s does not exist, creating.", zone_name)
reference = uuid.uuid4().hex
response = client.create_hosted_zone(Name=zone_name,
CallerReference=reference)
return parse_zone_id(response["HostedZone"]["Id"]) | python | def get_or_create_hosted_zone(client, zone_name):
"""Get the Id of an existing zone, or create it.
Args:
client (:class:`botocore.client.Route53`): The connection used to
interact with Route53's API.
zone_name (string): The name of the DNS hosted zone to create.
Returns:
string: The Id of the Hosted Zone.
"""
zone_id = get_hosted_zone_by_name(client, zone_name)
if zone_id:
return zone_id
logger.debug("Zone %s does not exist, creating.", zone_name)
reference = uuid.uuid4().hex
response = client.create_hosted_zone(Name=zone_name,
CallerReference=reference)
return parse_zone_id(response["HostedZone"]["Id"]) | [
"def",
"get_or_create_hosted_zone",
"(",
"client",
",",
"zone_name",
")",
":",
"zone_id",
"=",
"get_hosted_zone_by_name",
"(",
"client",
",",
"zone_name",
")",
"if",
"zone_id",
":",
"return",
"zone_id",
"logger",
".",
"debug",
"(",
"\"Zone %s does not exist, creatin... | Get the Id of an existing zone, or create it.
Args:
client (:class:`botocore.client.Route53`): The connection used to
interact with Route53's API.
zone_name (string): The name of the DNS hosted zone to create.
Returns:
string: The Id of the Hosted Zone. | [
"Get",
"the",
"Id",
"of",
"an",
"existing",
"zone",
"or",
"create",
"it",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L84-L106 | train | 214,664 |
cloudtools/stacker | stacker/util.py | get_soa_record | def get_soa_record(client, zone_id, zone_name):
"""Gets the SOA record for zone_name from zone_id.
Args:
client (:class:`botocore.client.Route53`): The connection used to
interact with Route53's API.
zone_id (string): The AWS Route53 zone id of the hosted zone to query.
zone_name (string): The name of the DNS hosted zone to create.
Returns:
:class:`stacker.util.SOARecord`: An object representing the parsed SOA
record returned from AWS Route53.
"""
response = client.list_resource_record_sets(HostedZoneId=zone_id,
StartRecordName=zone_name,
StartRecordType="SOA",
MaxItems="1")
return SOARecord(response["ResourceRecordSets"][0]) | python | def get_soa_record(client, zone_id, zone_name):
"""Gets the SOA record for zone_name from zone_id.
Args:
client (:class:`botocore.client.Route53`): The connection used to
interact with Route53's API.
zone_id (string): The AWS Route53 zone id of the hosted zone to query.
zone_name (string): The name of the DNS hosted zone to create.
Returns:
:class:`stacker.util.SOARecord`: An object representing the parsed SOA
record returned from AWS Route53.
"""
response = client.list_resource_record_sets(HostedZoneId=zone_id,
StartRecordName=zone_name,
StartRecordType="SOA",
MaxItems="1")
return SOARecord(response["ResourceRecordSets"][0]) | [
"def",
"get_soa_record",
"(",
"client",
",",
"zone_id",
",",
"zone_name",
")",
":",
"response",
"=",
"client",
".",
"list_resource_record_sets",
"(",
"HostedZoneId",
"=",
"zone_id",
",",
"StartRecordName",
"=",
"zone_name",
",",
"StartRecordType",
"=",
"\"SOA\"",
... | Gets the SOA record for zone_name from zone_id.
Args:
client (:class:`botocore.client.Route53`): The connection used to
interact with Route53's API.
zone_id (string): The AWS Route53 zone id of the hosted zone to query.
zone_name (string): The name of the DNS hosted zone to create.
Returns:
:class:`stacker.util.SOARecord`: An object representing the parsed SOA
record returned from AWS Route53. | [
"Gets",
"the",
"SOA",
"record",
"for",
"zone_name",
"from",
"zone_id",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L130-L148 | train | 214,665 |
cloudtools/stacker | stacker/util.py | create_route53_zone | def create_route53_zone(client, zone_name):
"""Creates the given zone_name if it doesn't already exists.
Also sets the SOA negative caching TTL to something short (300 seconds).
Args:
client (:class:`botocore.client.Route53`): The connection used to
interact with Route53's API.
zone_name (string): The name of the DNS hosted zone to create.
Returns:
string: The zone id returned from AWS for the existing, or newly
created zone.
"""
if not zone_name.endswith("."):
zone_name += "."
zone_id = get_or_create_hosted_zone(client, zone_name)
old_soa = get_soa_record(client, zone_id, zone_name)
# If the negative cache value is already 300, don't update it.
if old_soa.text.min_ttl == "300":
return zone_id
new_soa = copy.deepcopy(old_soa)
logger.debug("Updating negative caching value on zone %s to 300.",
zone_name)
new_soa.text.min_ttl = "300"
client.change_resource_record_sets(
HostedZoneId=zone_id,
ChangeBatch={
"Comment": "Update SOA min_ttl to 300.",
"Changes": [
{
"Action": "UPSERT",
"ResourceRecordSet": {
"Name": zone_name,
"Type": "SOA",
"TTL": old_soa.ttl,
"ResourceRecords": [
{
"Value": str(new_soa.text)
}
]
}
},
]
}
)
return zone_id | python | def create_route53_zone(client, zone_name):
"""Creates the given zone_name if it doesn't already exists.
Also sets the SOA negative caching TTL to something short (300 seconds).
Args:
client (:class:`botocore.client.Route53`): The connection used to
interact with Route53's API.
zone_name (string): The name of the DNS hosted zone to create.
Returns:
string: The zone id returned from AWS for the existing, or newly
created zone.
"""
if not zone_name.endswith("."):
zone_name += "."
zone_id = get_or_create_hosted_zone(client, zone_name)
old_soa = get_soa_record(client, zone_id, zone_name)
# If the negative cache value is already 300, don't update it.
if old_soa.text.min_ttl == "300":
return zone_id
new_soa = copy.deepcopy(old_soa)
logger.debug("Updating negative caching value on zone %s to 300.",
zone_name)
new_soa.text.min_ttl = "300"
client.change_resource_record_sets(
HostedZoneId=zone_id,
ChangeBatch={
"Comment": "Update SOA min_ttl to 300.",
"Changes": [
{
"Action": "UPSERT",
"ResourceRecordSet": {
"Name": zone_name,
"Type": "SOA",
"TTL": old_soa.ttl,
"ResourceRecords": [
{
"Value": str(new_soa.text)
}
]
}
},
]
}
)
return zone_id | [
"def",
"create_route53_zone",
"(",
"client",
",",
"zone_name",
")",
":",
"if",
"not",
"zone_name",
".",
"endswith",
"(",
"\".\"",
")",
":",
"zone_name",
"+=",
"\".\"",
"zone_id",
"=",
"get_or_create_hosted_zone",
"(",
"client",
",",
"zone_name",
")",
"old_soa"... | Creates the given zone_name if it doesn't already exists.
Also sets the SOA negative caching TTL to something short (300 seconds).
Args:
client (:class:`botocore.client.Route53`): The connection used to
interact with Route53's API.
zone_name (string): The name of the DNS hosted zone to create.
Returns:
string: The zone id returned from AWS for the existing, or newly
created zone. | [
"Creates",
"the",
"given",
"zone_name",
"if",
"it",
"doesn",
"t",
"already",
"exists",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L151-L199 | train | 214,666 |
cloudtools/stacker | stacker/util.py | load_object_from_string | def load_object_from_string(fqcn):
"""Converts "." delimited strings to a python object.
Given a "." delimited string representing the full path to an object
(function, class, variable) inside a module, return that object. Example:
load_object_from_string("os.path.basename")
load_object_from_string("logging.Logger")
load_object_from_string("LocalClassName")
"""
module_path = "__main__"
object_name = fqcn
if "." in fqcn:
module_path, object_name = fqcn.rsplit(".", 1)
importlib.import_module(module_path)
return getattr(sys.modules[module_path], object_name) | python | def load_object_from_string(fqcn):
"""Converts "." delimited strings to a python object.
Given a "." delimited string representing the full path to an object
(function, class, variable) inside a module, return that object. Example:
load_object_from_string("os.path.basename")
load_object_from_string("logging.Logger")
load_object_from_string("LocalClassName")
"""
module_path = "__main__"
object_name = fqcn
if "." in fqcn:
module_path, object_name = fqcn.rsplit(".", 1)
importlib.import_module(module_path)
return getattr(sys.modules[module_path], object_name) | [
"def",
"load_object_from_string",
"(",
"fqcn",
")",
":",
"module_path",
"=",
"\"__main__\"",
"object_name",
"=",
"fqcn",
"if",
"\".\"",
"in",
"fqcn",
":",
"module_path",
",",
"object_name",
"=",
"fqcn",
".",
"rsplit",
"(",
"\".\"",
",",
"1",
")",
"importlib"... | Converts "." delimited strings to a python object.
Given a "." delimited string representing the full path to an object
(function, class, variable) inside a module, return that object. Example:
load_object_from_string("os.path.basename")
load_object_from_string("logging.Logger")
load_object_from_string("LocalClassName") | [
"Converts",
".",
"delimited",
"strings",
"to",
"a",
"python",
"object",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L202-L217 | train | 214,667 |
cloudtools/stacker | stacker/util.py | merge_map | def merge_map(a, b):
"""Recursively merge elements of argument b into argument a.
Primarly used for merging two dictionaries together, where dict b takes
precedence over dict a. If 2 lists are provided, they are concatenated.
"""
if isinstance(a, list) and isinstance(b, list):
return a + b
if not isinstance(a, dict) or not isinstance(b, dict):
return b
for key in b:
a[key] = merge_map(a[key], b[key]) if key in a else b[key]
return a | python | def merge_map(a, b):
"""Recursively merge elements of argument b into argument a.
Primarly used for merging two dictionaries together, where dict b takes
precedence over dict a. If 2 lists are provided, they are concatenated.
"""
if isinstance(a, list) and isinstance(b, list):
return a + b
if not isinstance(a, dict) or not isinstance(b, dict):
return b
for key in b:
a[key] = merge_map(a[key], b[key]) if key in a else b[key]
return a | [
"def",
"merge_map",
"(",
"a",
",",
"b",
")",
":",
"if",
"isinstance",
"(",
"a",
",",
"list",
")",
"and",
"isinstance",
"(",
"b",
",",
"list",
")",
":",
"return",
"a",
"+",
"b",
"if",
"not",
"isinstance",
"(",
"a",
",",
"dict",
")",
"or",
"not",... | Recursively merge elements of argument b into argument a.
Primarly used for merging two dictionaries together, where dict b takes
precedence over dict a. If 2 lists are provided, they are concatenated. | [
"Recursively",
"merge",
"elements",
"of",
"argument",
"b",
"into",
"argument",
"a",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L220-L234 | train | 214,668 |
cloudtools/stacker | stacker/util.py | yaml_to_ordered_dict | def yaml_to_ordered_dict(stream, loader=yaml.SafeLoader):
"""Provides yaml.load alternative with preserved dictionary order.
Args:
stream (string): YAML string to load.
loader (:class:`yaml.loader`): PyYAML loader class. Defaults to safe
load.
Returns:
OrderedDict: Parsed YAML.
"""
class OrderedUniqueLoader(loader):
"""
Subclasses the given pyYAML `loader` class.
Validates all sibling keys to insure no duplicates.
Returns an OrderedDict instead of a Dict.
"""
# keys which require no duplicate siblings.
NO_DUPE_SIBLINGS = ["stacks", "class_path"]
# keys which require no duplicate children keys.
NO_DUPE_CHILDREN = ["stacks"]
def _error_mapping_on_dupe(self, node, node_name):
"""check mapping node for dupe children keys."""
if isinstance(node, MappingNode):
mapping = {}
for n in node.value:
a = n[0]
b = mapping.get(a.value, None)
if b:
msg = "{} mapping cannot have duplicate keys {} {}"
raise ConstructorError(
msg.format(node_name, b.start_mark, a.start_mark)
)
mapping[a.value] = a
def _validate_mapping(self, node, deep=False):
if not isinstance(node, MappingNode):
raise ConstructorError(
None, None,
"expected a mapping node, but found %s" % node.id,
node.start_mark)
mapping = OrderedDict()
for key_node, value_node in node.value:
key = self.construct_object(key_node, deep=deep)
try:
hash(key)
except TypeError as exc:
raise ConstructorError(
"while constructing a mapping", node.start_mark,
"found unhashable key (%s)" % exc, key_node.start_mark
)
# prevent duplicate sibling keys for certain "keywords".
if key in mapping and key in self.NO_DUPE_SIBLINGS:
msg = "{} key cannot have duplicate siblings {} {}"
raise ConstructorError(
msg.format(key, node.start_mark, key_node.start_mark)
)
if key in self.NO_DUPE_CHILDREN:
# prevent duplicate children keys for this mapping.
self._error_mapping_on_dupe(value_node, key_node.value)
value = self.construct_object(value_node, deep=deep)
mapping[key] = value
return mapping
def construct_mapping(self, node, deep=False):
"""Override parent method to use OrderedDict."""
if isinstance(node, MappingNode):
self.flatten_mapping(node)
return self._validate_mapping(node, deep=deep)
def construct_yaml_map(self, node):
data = OrderedDict()
yield data
value = self.construct_mapping(node)
data.update(value)
OrderedUniqueLoader.add_constructor(
u'tag:yaml.org,2002:map', OrderedUniqueLoader.construct_yaml_map,
)
return yaml.load(stream, OrderedUniqueLoader) | python | def yaml_to_ordered_dict(stream, loader=yaml.SafeLoader):
"""Provides yaml.load alternative with preserved dictionary order.
Args:
stream (string): YAML string to load.
loader (:class:`yaml.loader`): PyYAML loader class. Defaults to safe
load.
Returns:
OrderedDict: Parsed YAML.
"""
class OrderedUniqueLoader(loader):
"""
Subclasses the given pyYAML `loader` class.
Validates all sibling keys to insure no duplicates.
Returns an OrderedDict instead of a Dict.
"""
# keys which require no duplicate siblings.
NO_DUPE_SIBLINGS = ["stacks", "class_path"]
# keys which require no duplicate children keys.
NO_DUPE_CHILDREN = ["stacks"]
def _error_mapping_on_dupe(self, node, node_name):
"""check mapping node for dupe children keys."""
if isinstance(node, MappingNode):
mapping = {}
for n in node.value:
a = n[0]
b = mapping.get(a.value, None)
if b:
msg = "{} mapping cannot have duplicate keys {} {}"
raise ConstructorError(
msg.format(node_name, b.start_mark, a.start_mark)
)
mapping[a.value] = a
def _validate_mapping(self, node, deep=False):
if not isinstance(node, MappingNode):
raise ConstructorError(
None, None,
"expected a mapping node, but found %s" % node.id,
node.start_mark)
mapping = OrderedDict()
for key_node, value_node in node.value:
key = self.construct_object(key_node, deep=deep)
try:
hash(key)
except TypeError as exc:
raise ConstructorError(
"while constructing a mapping", node.start_mark,
"found unhashable key (%s)" % exc, key_node.start_mark
)
# prevent duplicate sibling keys for certain "keywords".
if key in mapping and key in self.NO_DUPE_SIBLINGS:
msg = "{} key cannot have duplicate siblings {} {}"
raise ConstructorError(
msg.format(key, node.start_mark, key_node.start_mark)
)
if key in self.NO_DUPE_CHILDREN:
# prevent duplicate children keys for this mapping.
self._error_mapping_on_dupe(value_node, key_node.value)
value = self.construct_object(value_node, deep=deep)
mapping[key] = value
return mapping
def construct_mapping(self, node, deep=False):
"""Override parent method to use OrderedDict."""
if isinstance(node, MappingNode):
self.flatten_mapping(node)
return self._validate_mapping(node, deep=deep)
def construct_yaml_map(self, node):
data = OrderedDict()
yield data
value = self.construct_mapping(node)
data.update(value)
OrderedUniqueLoader.add_constructor(
u'tag:yaml.org,2002:map', OrderedUniqueLoader.construct_yaml_map,
)
return yaml.load(stream, OrderedUniqueLoader) | [
"def",
"yaml_to_ordered_dict",
"(",
"stream",
",",
"loader",
"=",
"yaml",
".",
"SafeLoader",
")",
":",
"class",
"OrderedUniqueLoader",
"(",
"loader",
")",
":",
"\"\"\"\n Subclasses the given pyYAML `loader` class.\n\n Validates all sibling keys to insure no duplicat... | Provides yaml.load alternative with preserved dictionary order.
Args:
stream (string): YAML string to load.
loader (:class:`yaml.loader`): PyYAML loader class. Defaults to safe
load.
Returns:
OrderedDict: Parsed YAML. | [
"Provides",
"yaml",
".",
"load",
"alternative",
"with",
"preserved",
"dictionary",
"order",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L237-L320 | train | 214,669 |
cloudtools/stacker | stacker/util.py | cf_safe_name | def cf_safe_name(name):
"""Converts a name to a safe string for a Cloudformation resource.
Given a string, returns a name that is safe for use as a CloudFormation
Resource. (ie: Only alphanumeric characters)
"""
alphanumeric = r"[a-zA-Z0-9]+"
parts = re.findall(alphanumeric, name)
return "".join([uppercase_first_letter(part) for part in parts]) | python | def cf_safe_name(name):
"""Converts a name to a safe string for a Cloudformation resource.
Given a string, returns a name that is safe for use as a CloudFormation
Resource. (ie: Only alphanumeric characters)
"""
alphanumeric = r"[a-zA-Z0-9]+"
parts = re.findall(alphanumeric, name)
return "".join([uppercase_first_letter(part) for part in parts]) | [
"def",
"cf_safe_name",
"(",
"name",
")",
":",
"alphanumeric",
"=",
"r\"[a-zA-Z0-9]+\"",
"parts",
"=",
"re",
".",
"findall",
"(",
"alphanumeric",
",",
"name",
")",
"return",
"\"\"",
".",
"join",
"(",
"[",
"uppercase_first_letter",
"(",
"part",
")",
"for",
"... | Converts a name to a safe string for a Cloudformation resource.
Given a string, returns a name that is safe for use as a CloudFormation
Resource. (ie: Only alphanumeric characters) | [
"Converts",
"a",
"name",
"to",
"a",
"safe",
"string",
"for",
"a",
"Cloudformation",
"resource",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L328-L336 | train | 214,670 |
cloudtools/stacker | stacker/util.py | get_config_directory | def get_config_directory():
"""Return the directory the config file is located in.
This enables us to use relative paths in config values.
"""
# avoid circular import
from .commands.stacker import Stacker
command = Stacker()
namespace = command.parse_args()
return os.path.dirname(namespace.config.name) | python | def get_config_directory():
"""Return the directory the config file is located in.
This enables us to use relative paths in config values.
"""
# avoid circular import
from .commands.stacker import Stacker
command = Stacker()
namespace = command.parse_args()
return os.path.dirname(namespace.config.name) | [
"def",
"get_config_directory",
"(",
")",
":",
"# avoid circular import",
"from",
".",
"commands",
".",
"stacker",
"import",
"Stacker",
"command",
"=",
"Stacker",
"(",
")",
"namespace",
"=",
"command",
".",
"parse_args",
"(",
")",
"return",
"os",
".",
"path",
... | Return the directory the config file is located in.
This enables us to use relative paths in config values. | [
"Return",
"the",
"directory",
"the",
"config",
"file",
"is",
"located",
"in",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L339-L349 | train | 214,671 |
cloudtools/stacker | stacker/util.py | read_value_from_path | def read_value_from_path(value):
"""Enables translators to read values from files.
The value can be referred to with the `file://` prefix. ie:
conf_key: ${kms file://kms_value.txt}
"""
if value.startswith('file://'):
path = value.split('file://', 1)[1]
config_directory = get_config_directory()
relative_path = os.path.join(config_directory, path)
with open(relative_path) as read_file:
value = read_file.read()
return value | python | def read_value_from_path(value):
"""Enables translators to read values from files.
The value can be referred to with the `file://` prefix. ie:
conf_key: ${kms file://kms_value.txt}
"""
if value.startswith('file://'):
path = value.split('file://', 1)[1]
config_directory = get_config_directory()
relative_path = os.path.join(config_directory, path)
with open(relative_path) as read_file:
value = read_file.read()
return value | [
"def",
"read_value_from_path",
"(",
"value",
")",
":",
"if",
"value",
".",
"startswith",
"(",
"'file://'",
")",
":",
"path",
"=",
"value",
".",
"split",
"(",
"'file://'",
",",
"1",
")",
"[",
"1",
"]",
"config_directory",
"=",
"get_config_directory",
"(",
... | Enables translators to read values from files.
The value can be referred to with the `file://` prefix. ie:
conf_key: ${kms file://kms_value.txt} | [
"Enables",
"translators",
"to",
"read",
"values",
"from",
"files",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L352-L366 | train | 214,672 |
cloudtools/stacker | stacker/util.py | ensure_s3_bucket | def ensure_s3_bucket(s3_client, bucket_name, bucket_region):
"""Ensure an s3 bucket exists, if it does not then create it.
Args:
s3_client (:class:`botocore.client.Client`): An s3 client used to
verify and create the bucket.
bucket_name (str): The bucket being checked/created.
bucket_region (str, optional): The region to create the bucket in. If
not provided, will be determined by s3_client's region.
"""
try:
s3_client.head_bucket(Bucket=bucket_name)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Message'] == "Not Found":
logger.debug("Creating bucket %s.", bucket_name)
create_args = {"Bucket": bucket_name}
location_constraint = s3_bucket_location_constraint(
bucket_region
)
if location_constraint:
create_args["CreateBucketConfiguration"] = {
"LocationConstraint": location_constraint
}
s3_client.create_bucket(**create_args)
elif e.response['Error']['Message'] == "Forbidden":
logger.exception("Access denied for bucket %s. Did " +
"you remember to use a globally unique name?",
bucket_name)
raise
else:
logger.exception("Error creating bucket %s. Error %s",
bucket_name, e.response)
raise | python | def ensure_s3_bucket(s3_client, bucket_name, bucket_region):
"""Ensure an s3 bucket exists, if it does not then create it.
Args:
s3_client (:class:`botocore.client.Client`): An s3 client used to
verify and create the bucket.
bucket_name (str): The bucket being checked/created.
bucket_region (str, optional): The region to create the bucket in. If
not provided, will be determined by s3_client's region.
"""
try:
s3_client.head_bucket(Bucket=bucket_name)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Message'] == "Not Found":
logger.debug("Creating bucket %s.", bucket_name)
create_args = {"Bucket": bucket_name}
location_constraint = s3_bucket_location_constraint(
bucket_region
)
if location_constraint:
create_args["CreateBucketConfiguration"] = {
"LocationConstraint": location_constraint
}
s3_client.create_bucket(**create_args)
elif e.response['Error']['Message'] == "Forbidden":
logger.exception("Access denied for bucket %s. Did " +
"you remember to use a globally unique name?",
bucket_name)
raise
else:
logger.exception("Error creating bucket %s. Error %s",
bucket_name, e.response)
raise | [
"def",
"ensure_s3_bucket",
"(",
"s3_client",
",",
"bucket_name",
",",
"bucket_region",
")",
":",
"try",
":",
"s3_client",
".",
"head_bucket",
"(",
"Bucket",
"=",
"bucket_name",
")",
"except",
"botocore",
".",
"exceptions",
".",
"ClientError",
"as",
"e",
":",
... | Ensure an s3 bucket exists, if it does not then create it.
Args:
s3_client (:class:`botocore.client.Client`): An s3 client used to
verify and create the bucket.
bucket_name (str): The bucket being checked/created.
bucket_region (str, optional): The region to create the bucket in. If
not provided, will be determined by s3_client's region. | [
"Ensure",
"an",
"s3",
"bucket",
"exists",
"if",
"it",
"does",
"not",
"then",
"create",
"it",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L415-L447 | train | 214,673 |
cloudtools/stacker | stacker/util.py | SourceProcessor.create_cache_directories | def create_cache_directories(self):
"""Ensure that SourceProcessor cache directories exist."""
if not os.path.isdir(self.package_cache_dir):
if not os.path.isdir(self.stacker_cache_dir):
os.mkdir(self.stacker_cache_dir)
os.mkdir(self.package_cache_dir) | python | def create_cache_directories(self):
"""Ensure that SourceProcessor cache directories exist."""
if not os.path.isdir(self.package_cache_dir):
if not os.path.isdir(self.stacker_cache_dir):
os.mkdir(self.stacker_cache_dir)
os.mkdir(self.package_cache_dir) | [
"def",
"create_cache_directories",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"self",
".",
"package_cache_dir",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"self",
".",
"stacker_cache_dir",
")",
":",
"os"... | Ensure that SourceProcessor cache directories exist. | [
"Ensure",
"that",
"SourceProcessor",
"cache",
"directories",
"exist",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L553-L558 | train | 214,674 |
cloudtools/stacker | stacker/util.py | SourceProcessor.get_package_sources | def get_package_sources(self):
"""Make remote python packages available for local use."""
# Checkout local modules
for config in self.sources.get('local', []):
self.fetch_local_package(config=config)
# Checkout S3 repositories specified in config
for config in self.sources.get('s3', []):
self.fetch_s3_package(config=config)
# Checkout git repositories specified in config
for config in self.sources.get('git', []):
self.fetch_git_package(config=config) | python | def get_package_sources(self):
"""Make remote python packages available for local use."""
# Checkout local modules
for config in self.sources.get('local', []):
self.fetch_local_package(config=config)
# Checkout S3 repositories specified in config
for config in self.sources.get('s3', []):
self.fetch_s3_package(config=config)
# Checkout git repositories specified in config
for config in self.sources.get('git', []):
self.fetch_git_package(config=config) | [
"def",
"get_package_sources",
"(",
"self",
")",
":",
"# Checkout local modules",
"for",
"config",
"in",
"self",
".",
"sources",
".",
"get",
"(",
"'local'",
",",
"[",
"]",
")",
":",
"self",
".",
"fetch_local_package",
"(",
"config",
"=",
"config",
")",
"# C... | Make remote python packages available for local use. | [
"Make",
"remote",
"python",
"packages",
"available",
"for",
"local",
"use",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L560-L570 | train | 214,675 |
cloudtools/stacker | stacker/util.py | SourceProcessor.fetch_local_package | def fetch_local_package(self, config):
"""Make a local path available to current stacker config.
Args:
config (dict): 'local' path config dictionary
"""
# Update sys.path & merge in remote configs (if necessary)
self.update_paths_and_config(config=config,
pkg_dir_name=config['source'],
pkg_cache_dir=os.getcwd()) | python | def fetch_local_package(self, config):
"""Make a local path available to current stacker config.
Args:
config (dict): 'local' path config dictionary
"""
# Update sys.path & merge in remote configs (if necessary)
self.update_paths_and_config(config=config,
pkg_dir_name=config['source'],
pkg_cache_dir=os.getcwd()) | [
"def",
"fetch_local_package",
"(",
"self",
",",
"config",
")",
":",
"# Update sys.path & merge in remote configs (if necessary)",
"self",
".",
"update_paths_and_config",
"(",
"config",
"=",
"config",
",",
"pkg_dir_name",
"=",
"config",
"[",
"'source'",
"]",
",",
"pkg_... | Make a local path available to current stacker config.
Args:
config (dict): 'local' path config dictionary | [
"Make",
"a",
"local",
"path",
"available",
"to",
"current",
"stacker",
"config",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L572-L582 | train | 214,676 |
cloudtools/stacker | stacker/util.py | SourceProcessor.fetch_git_package | def fetch_git_package(self, config):
"""Make a remote git repository available for local use.
Args:
config (dict): git config dictionary
"""
# only loading git here when needed to avoid load errors on systems
# without git installed
from git import Repo
ref = self.determine_git_ref(config)
dir_name = self.sanitize_git_path(uri=config['uri'], ref=ref)
cached_dir_path = os.path.join(self.package_cache_dir, dir_name)
# We can skip cloning the repo if it's already been cached
if not os.path.isdir(cached_dir_path):
logger.debug("Remote repo %s does not appear to have been "
"previously downloaded - starting clone to %s",
config['uri'],
cached_dir_path)
tmp_dir = tempfile.mkdtemp(prefix='stacker')
try:
tmp_repo_path = os.path.join(tmp_dir, dir_name)
with Repo.clone_from(config['uri'], tmp_repo_path) as repo:
repo.head.reference = ref
repo.head.reset(index=True, working_tree=True)
shutil.move(tmp_repo_path, self.package_cache_dir)
finally:
shutil.rmtree(tmp_dir)
else:
logger.debug("Remote repo %s appears to have been previously "
"cloned to %s -- bypassing download",
config['uri'],
cached_dir_path)
# Update sys.path & merge in remote configs (if necessary)
self.update_paths_and_config(config=config,
pkg_dir_name=dir_name) | python | def fetch_git_package(self, config):
"""Make a remote git repository available for local use.
Args:
config (dict): git config dictionary
"""
# only loading git here when needed to avoid load errors on systems
# without git installed
from git import Repo
ref = self.determine_git_ref(config)
dir_name = self.sanitize_git_path(uri=config['uri'], ref=ref)
cached_dir_path = os.path.join(self.package_cache_dir, dir_name)
# We can skip cloning the repo if it's already been cached
if not os.path.isdir(cached_dir_path):
logger.debug("Remote repo %s does not appear to have been "
"previously downloaded - starting clone to %s",
config['uri'],
cached_dir_path)
tmp_dir = tempfile.mkdtemp(prefix='stacker')
try:
tmp_repo_path = os.path.join(tmp_dir, dir_name)
with Repo.clone_from(config['uri'], tmp_repo_path) as repo:
repo.head.reference = ref
repo.head.reset(index=True, working_tree=True)
shutil.move(tmp_repo_path, self.package_cache_dir)
finally:
shutil.rmtree(tmp_dir)
else:
logger.debug("Remote repo %s appears to have been previously "
"cloned to %s -- bypassing download",
config['uri'],
cached_dir_path)
# Update sys.path & merge in remote configs (if necessary)
self.update_paths_and_config(config=config,
pkg_dir_name=dir_name) | [
"def",
"fetch_git_package",
"(",
"self",
",",
"config",
")",
":",
"# only loading git here when needed to avoid load errors on systems",
"# without git installed",
"from",
"git",
"import",
"Repo",
"ref",
"=",
"self",
".",
"determine_git_ref",
"(",
"config",
")",
"dir_name... | Make a remote git repository available for local use.
Args:
config (dict): git config dictionary | [
"Make",
"a",
"remote",
"git",
"repository",
"available",
"for",
"local",
"use",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L682-L720 | train | 214,677 |
cloudtools/stacker | stacker/util.py | SourceProcessor.update_paths_and_config | def update_paths_and_config(self, config, pkg_dir_name,
pkg_cache_dir=None):
"""Handle remote source defined sys.paths & configs.
Args:
config (dict): git config dictionary
pkg_dir_name (string): directory name of the stacker archive
pkg_cache_dir (string): fully qualified path to stacker cache
cache directory
"""
if pkg_cache_dir is None:
pkg_cache_dir = self.package_cache_dir
cached_dir_path = os.path.join(pkg_cache_dir, pkg_dir_name)
# Add the appropriate directory (or directories) to sys.path
if config.get('paths'):
for path in config['paths']:
path_to_append = os.path.join(cached_dir_path,
path)
logger.debug("Appending \"%s\" to python sys.path",
path_to_append)
sys.path.append(path_to_append)
else:
sys.path.append(cached_dir_path)
# If the configuration defines a set of remote config yamls to
# include, add them to the list for merging
if config.get('configs'):
for config_filename in config['configs']:
self.configs_to_merge.append(os.path.join(cached_dir_path,
config_filename)) | python | def update_paths_and_config(self, config, pkg_dir_name,
pkg_cache_dir=None):
"""Handle remote source defined sys.paths & configs.
Args:
config (dict): git config dictionary
pkg_dir_name (string): directory name of the stacker archive
pkg_cache_dir (string): fully qualified path to stacker cache
cache directory
"""
if pkg_cache_dir is None:
pkg_cache_dir = self.package_cache_dir
cached_dir_path = os.path.join(pkg_cache_dir, pkg_dir_name)
# Add the appropriate directory (or directories) to sys.path
if config.get('paths'):
for path in config['paths']:
path_to_append = os.path.join(cached_dir_path,
path)
logger.debug("Appending \"%s\" to python sys.path",
path_to_append)
sys.path.append(path_to_append)
else:
sys.path.append(cached_dir_path)
# If the configuration defines a set of remote config yamls to
# include, add them to the list for merging
if config.get('configs'):
for config_filename in config['configs']:
self.configs_to_merge.append(os.path.join(cached_dir_path,
config_filename)) | [
"def",
"update_paths_and_config",
"(",
"self",
",",
"config",
",",
"pkg_dir_name",
",",
"pkg_cache_dir",
"=",
"None",
")",
":",
"if",
"pkg_cache_dir",
"is",
"None",
":",
"pkg_cache_dir",
"=",
"self",
".",
"package_cache_dir",
"cached_dir_path",
"=",
"os",
".",
... | Handle remote source defined sys.paths & configs.
Args:
config (dict): git config dictionary
pkg_dir_name (string): directory name of the stacker archive
pkg_cache_dir (string): fully qualified path to stacker cache
cache directory | [
"Handle",
"remote",
"source",
"defined",
"sys",
".",
"paths",
"&",
"configs",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L722-L753 | train | 214,678 |
cloudtools/stacker | stacker/util.py | SourceProcessor.git_ls_remote | def git_ls_remote(self, uri, ref):
"""Determine the latest commit id for a given ref.
Args:
uri (string): git URI
ref (string): git ref
Returns:
str: A commit id
"""
logger.debug("Invoking git to retrieve commit id for repo %s...", uri)
lsremote_output = subprocess.check_output(['git',
'ls-remote',
uri,
ref])
if b"\t" in lsremote_output:
commit_id = lsremote_output.split(b"\t")[0]
logger.debug("Matching commit id found: %s", commit_id)
return commit_id
else:
raise ValueError("Ref \"%s\" not found for repo %s." % (ref, uri)) | python | def git_ls_remote(self, uri, ref):
"""Determine the latest commit id for a given ref.
Args:
uri (string): git URI
ref (string): git ref
Returns:
str: A commit id
"""
logger.debug("Invoking git to retrieve commit id for repo %s...", uri)
lsremote_output = subprocess.check_output(['git',
'ls-remote',
uri,
ref])
if b"\t" in lsremote_output:
commit_id = lsremote_output.split(b"\t")[0]
logger.debug("Matching commit id found: %s", commit_id)
return commit_id
else:
raise ValueError("Ref \"%s\" not found for repo %s." % (ref, uri)) | [
"def",
"git_ls_remote",
"(",
"self",
",",
"uri",
",",
"ref",
")",
":",
"logger",
".",
"debug",
"(",
"\"Invoking git to retrieve commit id for repo %s...\"",
",",
"uri",
")",
"lsremote_output",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'git'",
",",
"'ls-... | Determine the latest commit id for a given ref.
Args:
uri (string): git URI
ref (string): git ref
Returns:
str: A commit id | [
"Determine",
"the",
"latest",
"commit",
"id",
"for",
"a",
"given",
"ref",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L755-L776 | train | 214,679 |
cloudtools/stacker | stacker/util.py | SourceProcessor.determine_git_ref | def determine_git_ref(self, config):
"""Determine the ref to be used for 'git checkout'.
Args:
config (dict): git config dictionary
Returns:
str: A commit id or tag name
"""
# First ensure redundant config keys aren't specified (which could
# cause confusion as to which take precedence)
ref_config_keys = 0
for i in ['commit', 'tag', 'branch']:
if config.get(i):
ref_config_keys += 1
if ref_config_keys > 1:
raise ImportError("Fetching remote git sources failed: "
"conflicting revisions (e.g. 'commit', 'tag', "
"'branch') specified for a package source")
# Now check for a specific point in time referenced and return it if
# present
if config.get('commit'):
ref = config['commit']
elif config.get('tag'):
ref = config['tag']
else:
# Since a specific commit/tag point in time has not been specified,
# check the remote repo for the commit id to use
ref = self.git_ls_remote(
config['uri'],
self.determine_git_ls_remote_ref(config)
)
if sys.version_info[0] > 2 and isinstance(ref, bytes):
return ref.decode()
return ref | python | def determine_git_ref(self, config):
"""Determine the ref to be used for 'git checkout'.
Args:
config (dict): git config dictionary
Returns:
str: A commit id or tag name
"""
# First ensure redundant config keys aren't specified (which could
# cause confusion as to which take precedence)
ref_config_keys = 0
for i in ['commit', 'tag', 'branch']:
if config.get(i):
ref_config_keys += 1
if ref_config_keys > 1:
raise ImportError("Fetching remote git sources failed: "
"conflicting revisions (e.g. 'commit', 'tag', "
"'branch') specified for a package source")
# Now check for a specific point in time referenced and return it if
# present
if config.get('commit'):
ref = config['commit']
elif config.get('tag'):
ref = config['tag']
else:
# Since a specific commit/tag point in time has not been specified,
# check the remote repo for the commit id to use
ref = self.git_ls_remote(
config['uri'],
self.determine_git_ls_remote_ref(config)
)
if sys.version_info[0] > 2 and isinstance(ref, bytes):
return ref.decode()
return ref | [
"def",
"determine_git_ref",
"(",
"self",
",",
"config",
")",
":",
"# First ensure redundant config keys aren't specified (which could",
"# cause confusion as to which take precedence)",
"ref_config_keys",
"=",
"0",
"for",
"i",
"in",
"[",
"'commit'",
",",
"'tag'",
",",
"'bra... | Determine the ref to be used for 'git checkout'.
Args:
config (dict): git config dictionary
Returns:
str: A commit id or tag name | [
"Determine",
"the",
"ref",
"to",
"be",
"used",
"for",
"git",
"checkout",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L796-L832 | train | 214,680 |
cloudtools/stacker | stacker/util.py | SourceProcessor.sanitize_git_path | def sanitize_git_path(self, uri, ref=None):
"""Take a git URI and ref and converts it to a directory safe path.
Args:
uri (string): git URI
(e.g. git@github.com:foo/bar.git)
ref (string): optional git ref to be appended to the path
Returns:
str: Directory name for the supplied uri
"""
if uri.endswith('.git'):
dir_name = uri[:-4] # drop .git
else:
dir_name = uri
dir_name = self.sanitize_uri_path(dir_name)
if ref is not None:
dir_name += "-%s" % ref
return dir_name | python | def sanitize_git_path(self, uri, ref=None):
"""Take a git URI and ref and converts it to a directory safe path.
Args:
uri (string): git URI
(e.g. git@github.com:foo/bar.git)
ref (string): optional git ref to be appended to the path
Returns:
str: Directory name for the supplied uri
"""
if uri.endswith('.git'):
dir_name = uri[:-4] # drop .git
else:
dir_name = uri
dir_name = self.sanitize_uri_path(dir_name)
if ref is not None:
dir_name += "-%s" % ref
return dir_name | [
"def",
"sanitize_git_path",
"(",
"self",
",",
"uri",
",",
"ref",
"=",
"None",
")",
":",
"if",
"uri",
".",
"endswith",
"(",
"'.git'",
")",
":",
"dir_name",
"=",
"uri",
"[",
":",
"-",
"4",
"]",
"# drop .git",
"else",
":",
"dir_name",
"=",
"uri",
"dir... | Take a git URI and ref and converts it to a directory safe path.
Args:
uri (string): git URI
(e.g. git@github.com:foo/bar.git)
ref (string): optional git ref to be appended to the path
Returns:
str: Directory name for the supplied uri | [
"Take",
"a",
"git",
"URI",
"and",
"ref",
"and",
"converts",
"it",
"to",
"a",
"directory",
"safe",
"path",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L848-L867 | train | 214,681 |
cloudtools/stacker | stacker/hooks/command.py | run_command | def run_command(provider, context, command, capture=False, interactive=False,
ignore_status=False, quiet=False, stdin=None, env=None,
**kwargs):
"""Run a custom command as a hook
Keyword Arguments:
command (list or str):
Command to run
capture (bool, optional):
If enabled, capture the command's stdout and stderr, and return
them in the hook result. Default: false
interactive (bool, optional):
If enabled, allow the command to interact with stdin. Otherwise,
stdin will be set to the null device. Default: false
ignore_status (bool, optional):
Don't fail the hook if the command returns a non-zero status.
Default: false
quiet (bool, optional):
Redirect the command's stdout and stderr to the null device,
silencing all output. Should not be enaled if `capture` is also
enabled. Default: false
stdin (str, optional):
String to send to the stdin of the command. Implicitly disables
`interactive`.
env (dict, optional):
Dictionary of environment variable overrides for the command
context. Will be merged with the current environment.
**kwargs:
Any other arguments will be forwarded to the `subprocess.Popen`
function. Interesting ones include: `cwd` and `shell`.
Examples:
.. code-block:: yaml
pre_build:
- path: stacker.hooks.command.run_command
required: true
enabled: true
data_key: copy_env
args:
command: ['cp', 'environment.template', 'environment']
- path: stacker.hooks.command.run_command
required: true
enabled: true
data_key: get_git_commit
args:
command: ['git', 'rev-parse', 'HEAD']
cwd: ./my-git-repo
capture: true
- path: stacker.hooks.command.run_command
args:
command: `cd $PROJECT_DIR/project; npm install'
env:
PROJECT_DIR: ./my-project
shell: true
"""
if quiet and capture:
raise ImproperlyConfigured(
__name__ + '.run_command',
'Cannot enable `quiet` and `capture` options simultaneously')
if quiet:
out_err_type = _devnull()
elif capture:
out_err_type = PIPE
else:
out_err_type = None
if interactive:
in_type = None
elif stdin:
in_type = PIPE
else:
in_type = _devnull()
if env:
full_env = os.environ.copy()
full_env.update(env)
env = full_env
logger.info('Running command: %s', command)
proc = Popen(command, stdin=in_type, stdout=out_err_type,
stderr=out_err_type, env=env, **kwargs)
try:
out, err = proc.communicate(stdin)
status = proc.wait()
if status == 0 or ignore_status:
return {
'returncode': proc.returncode,
'stdout': out,
'stderr': err
}
# Don't print the command line again if we already did earlier
if logger.isEnabledFor(logging.INFO):
logger.warn('Command failed with returncode %d', status)
else:
logger.warn('Command failed with returncode %d: %s', status,
command)
return None
finally:
if proc.returncode is None:
proc.kill() | python | def run_command(provider, context, command, capture=False, interactive=False,
ignore_status=False, quiet=False, stdin=None, env=None,
**kwargs):
"""Run a custom command as a hook
Keyword Arguments:
command (list or str):
Command to run
capture (bool, optional):
If enabled, capture the command's stdout and stderr, and return
them in the hook result. Default: false
interactive (bool, optional):
If enabled, allow the command to interact with stdin. Otherwise,
stdin will be set to the null device. Default: false
ignore_status (bool, optional):
Don't fail the hook if the command returns a non-zero status.
Default: false
quiet (bool, optional):
Redirect the command's stdout and stderr to the null device,
silencing all output. Should not be enaled if `capture` is also
enabled. Default: false
stdin (str, optional):
String to send to the stdin of the command. Implicitly disables
`interactive`.
env (dict, optional):
Dictionary of environment variable overrides for the command
context. Will be merged with the current environment.
**kwargs:
Any other arguments will be forwarded to the `subprocess.Popen`
function. Interesting ones include: `cwd` and `shell`.
Examples:
.. code-block:: yaml
pre_build:
- path: stacker.hooks.command.run_command
required: true
enabled: true
data_key: copy_env
args:
command: ['cp', 'environment.template', 'environment']
- path: stacker.hooks.command.run_command
required: true
enabled: true
data_key: get_git_commit
args:
command: ['git', 'rev-parse', 'HEAD']
cwd: ./my-git-repo
capture: true
- path: stacker.hooks.command.run_command
args:
command: `cd $PROJECT_DIR/project; npm install'
env:
PROJECT_DIR: ./my-project
shell: true
"""
if quiet and capture:
raise ImproperlyConfigured(
__name__ + '.run_command',
'Cannot enable `quiet` and `capture` options simultaneously')
if quiet:
out_err_type = _devnull()
elif capture:
out_err_type = PIPE
else:
out_err_type = None
if interactive:
in_type = None
elif stdin:
in_type = PIPE
else:
in_type = _devnull()
if env:
full_env = os.environ.copy()
full_env.update(env)
env = full_env
logger.info('Running command: %s', command)
proc = Popen(command, stdin=in_type, stdout=out_err_type,
stderr=out_err_type, env=env, **kwargs)
try:
out, err = proc.communicate(stdin)
status = proc.wait()
if status == 0 or ignore_status:
return {
'returncode': proc.returncode,
'stdout': out,
'stderr': err
}
# Don't print the command line again if we already did earlier
if logger.isEnabledFor(logging.INFO):
logger.warn('Command failed with returncode %d', status)
else:
logger.warn('Command failed with returncode %d: %s', status,
command)
return None
finally:
if proc.returncode is None:
proc.kill() | [
"def",
"run_command",
"(",
"provider",
",",
"context",
",",
"command",
",",
"capture",
"=",
"False",
",",
"interactive",
"=",
"False",
",",
"ignore_status",
"=",
"False",
",",
"quiet",
"=",
"False",
",",
"stdin",
"=",
"None",
",",
"env",
"=",
"None",
"... | Run a custom command as a hook
Keyword Arguments:
command (list or str):
Command to run
capture (bool, optional):
If enabled, capture the command's stdout and stderr, and return
them in the hook result. Default: false
interactive (bool, optional):
If enabled, allow the command to interact with stdin. Otherwise,
stdin will be set to the null device. Default: false
ignore_status (bool, optional):
Don't fail the hook if the command returns a non-zero status.
Default: false
quiet (bool, optional):
Redirect the command's stdout and stderr to the null device,
silencing all output. Should not be enaled if `capture` is also
enabled. Default: false
stdin (str, optional):
String to send to the stdin of the command. Implicitly disables
`interactive`.
env (dict, optional):
Dictionary of environment variable overrides for the command
context. Will be merged with the current environment.
**kwargs:
Any other arguments will be forwarded to the `subprocess.Popen`
function. Interesting ones include: `cwd` and `shell`.
Examples:
.. code-block:: yaml
pre_build:
- path: stacker.hooks.command.run_command
required: true
enabled: true
data_key: copy_env
args:
command: ['cp', 'environment.template', 'environment']
- path: stacker.hooks.command.run_command
required: true
enabled: true
data_key: get_git_commit
args:
command: ['git', 'rev-parse', 'HEAD']
cwd: ./my-git-repo
capture: true
- path: stacker.hooks.command.run_command
args:
command: `cd $PROJECT_DIR/project; npm install'
env:
PROJECT_DIR: ./my-project
shell: true | [
"Run",
"a",
"custom",
"command",
"as",
"a",
"hook"
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/hooks/command.py#L18-L124 | train | 214,682 |
cloudtools/stacker | stacker/hooks/keypair.py | ensure_keypair_exists | def ensure_keypair_exists(provider, context, **kwargs):
"""Ensure a specific keypair exists within AWS.
If the key doesn't exist, upload it.
Args:
provider (:class:`stacker.providers.base.BaseProvider`): provider
instance
context (:class:`stacker.context.Context`): context instance
keypair (str): name of the key pair to create
ssm_parameter_name (str, optional): path to an SSM store parameter to
receive the generated private key, instead of importing it or
storing it locally.
ssm_key_id (str, optional): ID of a KMS key to encrypt the SSM
parameter with. If omitted, the default key will be used.
public_key_path (str, optional): path to a public key file to be
imported instead of generating a new key. Incompatible with the SSM
options, as the private key will not be available for storing.
Returns:
In case of failure ``False``, otherwise a dict containing:
status (str): one of "exists", "imported" or "created"
key_name (str): name of the key pair
fingerprint (str): fingerprint of the key pair
file_path (str, optional): if a new key was created, the path to
the file where the private key was stored
"""
keypair_name = kwargs["keypair"]
ssm_parameter_name = kwargs.get("ssm_parameter_name")
ssm_key_id = kwargs.get("ssm_key_id")
public_key_path = kwargs.get("public_key_path")
if public_key_path and ssm_parameter_name:
logger.error("public_key_path and ssm_parameter_name cannot be "
"specified at the same time")
return False
session = get_session(region=provider.region,
profile=kwargs.get("profile"))
ec2 = session.client("ec2")
keypair = get_existing_key_pair(ec2, keypair_name)
if keypair:
return keypair
if public_key_path:
keypair = create_key_pair_from_public_key_file(
ec2, keypair_name, public_key_path)
elif ssm_parameter_name:
ssm = session.client('ssm')
keypair = create_key_pair_in_ssm(
ec2, ssm, keypair_name, ssm_parameter_name, ssm_key_id)
else:
action, path = interactive_prompt(keypair_name)
if action == "import":
keypair = create_key_pair_from_public_key_file(
ec2, keypair_name, path)
elif action == "create":
keypair = create_key_pair_local(ec2, keypair_name, path)
else:
logger.warning("no action to find keypair, failing")
if not keypair:
return False
return keypair | python | def ensure_keypair_exists(provider, context, **kwargs):
"""Ensure a specific keypair exists within AWS.
If the key doesn't exist, upload it.
Args:
provider (:class:`stacker.providers.base.BaseProvider`): provider
instance
context (:class:`stacker.context.Context`): context instance
keypair (str): name of the key pair to create
ssm_parameter_name (str, optional): path to an SSM store parameter to
receive the generated private key, instead of importing it or
storing it locally.
ssm_key_id (str, optional): ID of a KMS key to encrypt the SSM
parameter with. If omitted, the default key will be used.
public_key_path (str, optional): path to a public key file to be
imported instead of generating a new key. Incompatible with the SSM
options, as the private key will not be available for storing.
Returns:
In case of failure ``False``, otherwise a dict containing:
status (str): one of "exists", "imported" or "created"
key_name (str): name of the key pair
fingerprint (str): fingerprint of the key pair
file_path (str, optional): if a new key was created, the path to
the file where the private key was stored
"""
keypair_name = kwargs["keypair"]
ssm_parameter_name = kwargs.get("ssm_parameter_name")
ssm_key_id = kwargs.get("ssm_key_id")
public_key_path = kwargs.get("public_key_path")
if public_key_path and ssm_parameter_name:
logger.error("public_key_path and ssm_parameter_name cannot be "
"specified at the same time")
return False
session = get_session(region=provider.region,
profile=kwargs.get("profile"))
ec2 = session.client("ec2")
keypair = get_existing_key_pair(ec2, keypair_name)
if keypair:
return keypair
if public_key_path:
keypair = create_key_pair_from_public_key_file(
ec2, keypair_name, public_key_path)
elif ssm_parameter_name:
ssm = session.client('ssm')
keypair = create_key_pair_in_ssm(
ec2, ssm, keypair_name, ssm_parameter_name, ssm_key_id)
else:
action, path = interactive_prompt(keypair_name)
if action == "import":
keypair = create_key_pair_from_public_key_file(
ec2, keypair_name, path)
elif action == "create":
keypair = create_key_pair_local(ec2, keypair_name, path)
else:
logger.warning("no action to find keypair, failing")
if not keypair:
return False
return keypair | [
"def",
"ensure_keypair_exists",
"(",
"provider",
",",
"context",
",",
"*",
"*",
"kwargs",
")",
":",
"keypair_name",
"=",
"kwargs",
"[",
"\"keypair\"",
"]",
"ssm_parameter_name",
"=",
"kwargs",
".",
"get",
"(",
"\"ssm_parameter_name\"",
")",
"ssm_key_id",
"=",
... | Ensure a specific keypair exists within AWS.
If the key doesn't exist, upload it.
Args:
provider (:class:`stacker.providers.base.BaseProvider`): provider
instance
context (:class:`stacker.context.Context`): context instance
keypair (str): name of the key pair to create
ssm_parameter_name (str, optional): path to an SSM store parameter to
receive the generated private key, instead of importing it or
storing it locally.
ssm_key_id (str, optional): ID of a KMS key to encrypt the SSM
parameter with. If omitted, the default key will be used.
public_key_path (str, optional): path to a public key file to be
imported instead of generating a new key. Incompatible with the SSM
options, as the private key will not be available for storing.
Returns:
In case of failure ``False``, otherwise a dict containing:
status (str): one of "exists", "imported" or "created"
key_name (str): name of the key pair
fingerprint (str): fingerprint of the key pair
file_path (str, optional): if a new key was created, the path to
the file where the private key was stored | [
"Ensure",
"a",
"specific",
"keypair",
"exists",
"within",
"AWS",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/hooks/keypair.py#L184-L252 | train | 214,683 |
cloudtools/stacker | stacker/context.py | get_fqn | def get_fqn(base_fqn, delimiter, name=None):
"""Return the fully qualified name of an object within this context.
If the name passed already appears to be a fully qualified name, it
will be returned with no further processing.
"""
if name and name.startswith("%s%s" % (base_fqn, delimiter)):
return name
return delimiter.join([_f for _f in [base_fqn, name] if _f]) | python | def get_fqn(base_fqn, delimiter, name=None):
"""Return the fully qualified name of an object within this context.
If the name passed already appears to be a fully qualified name, it
will be returned with no further processing.
"""
if name and name.startswith("%s%s" % (base_fqn, delimiter)):
return name
return delimiter.join([_f for _f in [base_fqn, name] if _f]) | [
"def",
"get_fqn",
"(",
"base_fqn",
",",
"delimiter",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"and",
"name",
".",
"startswith",
"(",
"\"%s%s\"",
"%",
"(",
"base_fqn",
",",
"delimiter",
")",
")",
":",
"return",
"name",
"return",
"delimiter",
".... | Return the fully qualified name of an object within this context.
If the name passed already appears to be a fully qualified name, it
will be returned with no further processing. | [
"Return",
"the",
"fully",
"qualified",
"name",
"of",
"an",
"object",
"within",
"this",
"context",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/context.py#L19-L29 | train | 214,684 |
cloudtools/stacker | stacker/context.py | Context.get_targets | def get_targets(self):
"""Returns the named targets that are specified in the config.
Returns:
list: a list of :class:`stacker.target.Target` objects
"""
if not hasattr(self, "_targets"):
targets = []
for target_def in self.config.targets or []:
target = Target(target_def)
targets.append(target)
self._targets = targets
return self._targets | python | def get_targets(self):
"""Returns the named targets that are specified in the config.
Returns:
list: a list of :class:`stacker.target.Target` objects
"""
if not hasattr(self, "_targets"):
targets = []
for target_def in self.config.targets or []:
target = Target(target_def)
targets.append(target)
self._targets = targets
return self._targets | [
"def",
"get_targets",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"_targets\"",
")",
":",
"targets",
"=",
"[",
"]",
"for",
"target_def",
"in",
"self",
".",
"config",
".",
"targets",
"or",
"[",
"]",
":",
"target",
"=",
"Target",... | Returns the named targets that are specified in the config.
Returns:
list: a list of :class:`stacker.target.Target` objects | [
"Returns",
"the",
"named",
"targets",
"that",
"are",
"specified",
"in",
"the",
"config",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/context.py#L127-L140 | train | 214,685 |
cloudtools/stacker | stacker/context.py | Context.get_stacks | def get_stacks(self):
"""Get the stacks for the current action.
Handles configuring the :class:`stacker.stack.Stack` objects that will
be used in the current action.
Returns:
list: a list of :class:`stacker.stack.Stack` objects
"""
if not hasattr(self, "_stacks"):
stacks = []
definitions = self._get_stack_definitions()
for stack_def in definitions:
stack = Stack(
definition=stack_def,
context=self,
mappings=self.mappings,
force=stack_def.name in self.force_stacks,
locked=stack_def.locked,
enabled=stack_def.enabled,
protected=stack_def.protected,
)
stacks.append(stack)
self._stacks = stacks
return self._stacks | python | def get_stacks(self):
"""Get the stacks for the current action.
Handles configuring the :class:`stacker.stack.Stack` objects that will
be used in the current action.
Returns:
list: a list of :class:`stacker.stack.Stack` objects
"""
if not hasattr(self, "_stacks"):
stacks = []
definitions = self._get_stack_definitions()
for stack_def in definitions:
stack = Stack(
definition=stack_def,
context=self,
mappings=self.mappings,
force=stack_def.name in self.force_stacks,
locked=stack_def.locked,
enabled=stack_def.enabled,
protected=stack_def.protected,
)
stacks.append(stack)
self._stacks = stacks
return self._stacks | [
"def",
"get_stacks",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"_stacks\"",
")",
":",
"stacks",
"=",
"[",
"]",
"definitions",
"=",
"self",
".",
"_get_stack_definitions",
"(",
")",
"for",
"stack_def",
"in",
"definitions",
":",
"st... | Get the stacks for the current action.
Handles configuring the :class:`stacker.stack.Stack` objects that will
be used in the current action.
Returns:
list: a list of :class:`stacker.stack.Stack` objects | [
"Get",
"the",
"stacks",
"for",
"the",
"current",
"action",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/context.py#L142-L167 | train | 214,686 |
cloudtools/stacker | stacker/context.py | Context.set_hook_data | def set_hook_data(self, key, data):
"""Set hook data for the given key.
Args:
key(str): The key to store the hook data in.
data(:class:`collections.Mapping`): A dictionary of data to store,
as returned from a hook.
"""
if not isinstance(data, collections.Mapping):
raise ValueError("Hook (key: %s) data must be an instance of "
"collections.Mapping (a dictionary for "
"example)." % key)
if key in self.hook_data:
raise KeyError("Hook data for key %s already exists, each hook "
"must have a unique data_key.", key)
self.hook_data[key] = data | python | def set_hook_data(self, key, data):
"""Set hook data for the given key.
Args:
key(str): The key to store the hook data in.
data(:class:`collections.Mapping`): A dictionary of data to store,
as returned from a hook.
"""
if not isinstance(data, collections.Mapping):
raise ValueError("Hook (key: %s) data must be an instance of "
"collections.Mapping (a dictionary for "
"example)." % key)
if key in self.hook_data:
raise KeyError("Hook data for key %s already exists, each hook "
"must have a unique data_key.", key)
self.hook_data[key] = data | [
"def",
"set_hook_data",
"(",
"self",
",",
"key",
",",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"collections",
".",
"Mapping",
")",
":",
"raise",
"ValueError",
"(",
"\"Hook (key: %s) data must be an instance of \"",
"\"collections.Mapping (a dic... | Set hook data for the given key.
Args:
key(str): The key to store the hook data in.
data(:class:`collections.Mapping`): A dictionary of data to store,
as returned from a hook. | [
"Set",
"hook",
"data",
"for",
"the",
"given",
"key",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/context.py#L186-L204 | train | 214,687 |
cloudtools/stacker | stacker/config/__init__.py | render_parse_load | def render_parse_load(raw_config, environment=None, validate=True):
"""Encapsulates the render -> parse -> validate -> load process.
Args:
raw_config (str): the raw stacker configuration string.
environment (dict, optional): any environment values that should be
passed to the config
validate (bool): if provided, the config is validated before being
loaded.
Returns:
:class:`Config`: the parsed stacker config.
"""
pre_rendered = render(raw_config, environment)
rendered = process_remote_sources(pre_rendered, environment)
config = parse(rendered)
# For backwards compatibility, if the config doesn't specify a namespace,
# we fall back to fetching it from the environment, if provided.
if config.namespace is None:
namespace = environment.get("namespace")
if namespace:
logger.warn("DEPRECATION WARNING: specifying namespace in the "
"environment is deprecated. See "
"https://stacker.readthedocs.io/en/latest/config.html"
"#namespace "
"for more info.")
config.namespace = namespace
if validate:
config.validate()
return load(config) | python | def render_parse_load(raw_config, environment=None, validate=True):
"""Encapsulates the render -> parse -> validate -> load process.
Args:
raw_config (str): the raw stacker configuration string.
environment (dict, optional): any environment values that should be
passed to the config
validate (bool): if provided, the config is validated before being
loaded.
Returns:
:class:`Config`: the parsed stacker config.
"""
pre_rendered = render(raw_config, environment)
rendered = process_remote_sources(pre_rendered, environment)
config = parse(rendered)
# For backwards compatibility, if the config doesn't specify a namespace,
# we fall back to fetching it from the environment, if provided.
if config.namespace is None:
namespace = environment.get("namespace")
if namespace:
logger.warn("DEPRECATION WARNING: specifying namespace in the "
"environment is deprecated. See "
"https://stacker.readthedocs.io/en/latest/config.html"
"#namespace "
"for more info.")
config.namespace = namespace
if validate:
config.validate()
return load(config) | [
"def",
"render_parse_load",
"(",
"raw_config",
",",
"environment",
"=",
"None",
",",
"validate",
"=",
"True",
")",
":",
"pre_rendered",
"=",
"render",
"(",
"raw_config",
",",
"environment",
")",
"rendered",
"=",
"process_remote_sources",
"(",
"pre_rendered",
","... | Encapsulates the render -> parse -> validate -> load process.
Args:
raw_config (str): the raw stacker configuration string.
environment (dict, optional): any environment values that should be
passed to the config
validate (bool): if provided, the config is validated before being
loaded.
Returns:
:class:`Config`: the parsed stacker config. | [
"Encapsulates",
"the",
"render",
"-",
">",
"parse",
"-",
">",
"validate",
"-",
">",
"load",
"process",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/config/__init__.py#L42-L78 | train | 214,688 |
cloudtools/stacker | stacker/config/__init__.py | render | def render(raw_config, environment=None):
"""Renders a config, using it as a template with the environment.
Args:
raw_config (str): the raw stacker configuration string.
environment (dict, optional): any environment values that should be
passed to the config
Returns:
str: the stacker configuration populated with any values passed from
the environment
"""
t = Template(raw_config)
buff = StringIO()
if not environment:
environment = {}
try:
substituted = t.substitute(environment)
except KeyError as e:
raise exceptions.MissingEnvironment(e.args[0])
except ValueError:
# Support "invalid" placeholders for lookup placeholders.
substituted = t.safe_substitute(environment)
if not isinstance(substituted, str):
substituted = substituted.decode('utf-8')
buff.write(substituted)
buff.seek(0)
return buff.read() | python | def render(raw_config, environment=None):
"""Renders a config, using it as a template with the environment.
Args:
raw_config (str): the raw stacker configuration string.
environment (dict, optional): any environment values that should be
passed to the config
Returns:
str: the stacker configuration populated with any values passed from
the environment
"""
t = Template(raw_config)
buff = StringIO()
if not environment:
environment = {}
try:
substituted = t.substitute(environment)
except KeyError as e:
raise exceptions.MissingEnvironment(e.args[0])
except ValueError:
# Support "invalid" placeholders for lookup placeholders.
substituted = t.safe_substitute(environment)
if not isinstance(substituted, str):
substituted = substituted.decode('utf-8')
buff.write(substituted)
buff.seek(0)
return buff.read() | [
"def",
"render",
"(",
"raw_config",
",",
"environment",
"=",
"None",
")",
":",
"t",
"=",
"Template",
"(",
"raw_config",
")",
"buff",
"=",
"StringIO",
"(",
")",
"if",
"not",
"environment",
":",
"environment",
"=",
"{",
"}",
"try",
":",
"substituted",
"=... | Renders a config, using it as a template with the environment.
Args:
raw_config (str): the raw stacker configuration string.
environment (dict, optional): any environment values that should be
passed to the config
Returns:
str: the stacker configuration populated with any values passed from
the environment | [
"Renders",
"a",
"config",
"using",
"it",
"as",
"a",
"template",
"with",
"the",
"environment",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/config/__init__.py#L81-L112 | train | 214,689 |
cloudtools/stacker | stacker/config/__init__.py | parse | def parse(raw_config):
"""Parse a raw yaml formatted stacker config.
Args:
raw_config (str): the raw stacker configuration string in yaml format.
Returns:
:class:`Config`: the parsed stacker config.
"""
# Convert any applicable dictionaries back into lists
# This is necessary due to the move from lists for these top level config
# values to either lists or OrderedDicts.
# Eventually we should probably just make them OrderedDicts only.
config_dict = yaml_to_ordered_dict(raw_config)
if config_dict:
for top_level_key in ['stacks', 'pre_build', 'post_build',
'pre_destroy', 'post_destroy']:
top_level_value = config_dict.get(top_level_key)
if isinstance(top_level_value, dict):
tmp_list = []
for key, value in top_level_value.items():
tmp_dict = copy.deepcopy(value)
if top_level_key == 'stacks':
tmp_dict['name'] = key
tmp_list.append(tmp_dict)
config_dict[top_level_key] = tmp_list
# Top-level excess keys are removed by Config._convert, so enabling strict
# mode is fine here.
try:
return Config(config_dict, strict=True)
except SchematicsError as e:
raise exceptions.InvalidConfig(e.errors) | python | def parse(raw_config):
"""Parse a raw yaml formatted stacker config.
Args:
raw_config (str): the raw stacker configuration string in yaml format.
Returns:
:class:`Config`: the parsed stacker config.
"""
# Convert any applicable dictionaries back into lists
# This is necessary due to the move from lists for these top level config
# values to either lists or OrderedDicts.
# Eventually we should probably just make them OrderedDicts only.
config_dict = yaml_to_ordered_dict(raw_config)
if config_dict:
for top_level_key in ['stacks', 'pre_build', 'post_build',
'pre_destroy', 'post_destroy']:
top_level_value = config_dict.get(top_level_key)
if isinstance(top_level_value, dict):
tmp_list = []
for key, value in top_level_value.items():
tmp_dict = copy.deepcopy(value)
if top_level_key == 'stacks':
tmp_dict['name'] = key
tmp_list.append(tmp_dict)
config_dict[top_level_key] = tmp_list
# Top-level excess keys are removed by Config._convert, so enabling strict
# mode is fine here.
try:
return Config(config_dict, strict=True)
except SchematicsError as e:
raise exceptions.InvalidConfig(e.errors) | [
"def",
"parse",
"(",
"raw_config",
")",
":",
"# Convert any applicable dictionaries back into lists",
"# This is necessary due to the move from lists for these top level config",
"# values to either lists or OrderedDicts.",
"# Eventually we should probably just make them OrderedDicts only.",
"co... | Parse a raw yaml formatted stacker config.
Args:
raw_config (str): the raw stacker configuration string in yaml format.
Returns:
:class:`Config`: the parsed stacker config. | [
"Parse",
"a",
"raw",
"yaml",
"formatted",
"stacker",
"config",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/config/__init__.py#L115-L149 | train | 214,690 |
cloudtools/stacker | stacker/config/__init__.py | load | def load(config):
"""Loads a stacker configuration by modifying sys paths, loading lookups,
etc.
Args:
config (:class:`Config`): the stacker config to load.
Returns:
:class:`Config`: the stacker config provided above.
"""
if config.sys_path:
logger.debug("Appending %s to sys.path.", config.sys_path)
sys.path.append(config.sys_path)
logger.debug("sys.path is now %s", sys.path)
if config.lookups:
for key, handler in config.lookups.items():
register_lookup_handler(key, handler)
return config | python | def load(config):
"""Loads a stacker configuration by modifying sys paths, loading lookups,
etc.
Args:
config (:class:`Config`): the stacker config to load.
Returns:
:class:`Config`: the stacker config provided above.
"""
if config.sys_path:
logger.debug("Appending %s to sys.path.", config.sys_path)
sys.path.append(config.sys_path)
logger.debug("sys.path is now %s", sys.path)
if config.lookups:
for key, handler in config.lookups.items():
register_lookup_handler(key, handler)
return config | [
"def",
"load",
"(",
"config",
")",
":",
"if",
"config",
".",
"sys_path",
":",
"logger",
".",
"debug",
"(",
"\"Appending %s to sys.path.\"",
",",
"config",
".",
"sys_path",
")",
"sys",
".",
"path",
".",
"append",
"(",
"config",
".",
"sys_path",
")",
"logg... | Loads a stacker configuration by modifying sys paths, loading lookups,
etc.
Args:
config (:class:`Config`): the stacker config to load.
Returns:
:class:`Config`: the stacker config provided above. | [
"Loads",
"a",
"stacker",
"configuration",
"by",
"modifying",
"sys",
"paths",
"loading",
"lookups",
"etc",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/config/__init__.py#L152-L172 | train | 214,691 |
cloudtools/stacker | stacker/config/__init__.py | dump | def dump(config):
"""Dumps a stacker Config object as yaml.
Args:
config (:class:`Config`): the stacker Config object.
stream (stream): an optional stream object to write to.
Returns:
str: the yaml formatted stacker Config.
"""
return yaml.safe_dump(
config.to_primitive(),
default_flow_style=False,
encoding='utf-8',
allow_unicode=True) | python | def dump(config):
"""Dumps a stacker Config object as yaml.
Args:
config (:class:`Config`): the stacker Config object.
stream (stream): an optional stream object to write to.
Returns:
str: the yaml formatted stacker Config.
"""
return yaml.safe_dump(
config.to_primitive(),
default_flow_style=False,
encoding='utf-8',
allow_unicode=True) | [
"def",
"dump",
"(",
"config",
")",
":",
"return",
"yaml",
".",
"safe_dump",
"(",
"config",
".",
"to_primitive",
"(",
")",
",",
"default_flow_style",
"=",
"False",
",",
"encoding",
"=",
"'utf-8'",
",",
"allow_unicode",
"=",
"True",
")"
] | Dumps a stacker Config object as yaml.
Args:
config (:class:`Config`): the stacker Config object.
stream (stream): an optional stream object to write to.
Returns:
str: the yaml formatted stacker Config. | [
"Dumps",
"a",
"stacker",
"Config",
"object",
"as",
"yaml",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/config/__init__.py#L175-L191 | train | 214,692 |
cloudtools/stacker | stacker/config/__init__.py | process_remote_sources | def process_remote_sources(raw_config, environment=None):
"""Stage remote package sources and merge in remote configs.
Args:
raw_config (str): the raw stacker configuration string.
environment (dict, optional): any environment values that should be
passed to the config
Returns:
str: the raw stacker configuration string
"""
config = yaml.safe_load(raw_config)
if config and config.get('package_sources'):
processor = SourceProcessor(
sources=config['package_sources'],
stacker_cache_dir=config.get('stacker_cache_dir')
)
processor.get_package_sources()
if processor.configs_to_merge:
for i in processor.configs_to_merge:
logger.debug("Merging in remote config \"%s\"", i)
remote_config = yaml.safe_load(open(i))
config = merge_map(remote_config, config)
# Call the render again as the package_sources may have merged in
# additional environment lookups
if not environment:
environment = {}
return render(str(config), environment)
return raw_config | python | def process_remote_sources(raw_config, environment=None):
"""Stage remote package sources and merge in remote configs.
Args:
raw_config (str): the raw stacker configuration string.
environment (dict, optional): any environment values that should be
passed to the config
Returns:
str: the raw stacker configuration string
"""
config = yaml.safe_load(raw_config)
if config and config.get('package_sources'):
processor = SourceProcessor(
sources=config['package_sources'],
stacker_cache_dir=config.get('stacker_cache_dir')
)
processor.get_package_sources()
if processor.configs_to_merge:
for i in processor.configs_to_merge:
logger.debug("Merging in remote config \"%s\"", i)
remote_config = yaml.safe_load(open(i))
config = merge_map(remote_config, config)
# Call the render again as the package_sources may have merged in
# additional environment lookups
if not environment:
environment = {}
return render(str(config), environment)
return raw_config | [
"def",
"process_remote_sources",
"(",
"raw_config",
",",
"environment",
"=",
"None",
")",
":",
"config",
"=",
"yaml",
".",
"safe_load",
"(",
"raw_config",
")",
"if",
"config",
"and",
"config",
".",
"get",
"(",
"'package_sources'",
")",
":",
"processor",
"=",... | Stage remote package sources and merge in remote configs.
Args:
raw_config (str): the raw stacker configuration string.
environment (dict, optional): any environment values that should be
passed to the config
Returns:
str: the raw stacker configuration string | [
"Stage",
"remote",
"package",
"sources",
"and",
"merge",
"in",
"remote",
"configs",
"."
] | ad6013a03a560c46ba3c63c4d153336273e6da5d | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/config/__init__.py#L194-L225 | train | 214,693 |
SoCo/SoCo | soco/plugins/wimp.py | _post | def _post(url, headers, body, retries=3, timeout=3.0):
"""Try 3 times to request the content.
:param headers: The HTTP headers
:type headers: dict
:param body: The body of the HTTP post
:type body: str
:param retries: The number of times to retry before giving up
:type retries: int
:param timeout: The time to wait for the post to complete, before timing
out
:type timeout: float
"""
retry = 0
out = None
while out is None:
try:
out = requests.post(url, headers=headers, data=body,
timeout=timeout)
# Due to a bug in requests, the post command will sometimes fail to
# properly wrap a socket.timeout exception in requests own exception.
# See https://github.com/kennethreitz/requests/issues/2045
# Until this is fixed, we need to catch both types of exceptions
except (requests.exceptions.Timeout, socket.timeout) as exception:
retry += 1
if retry == retries:
# pylint: disable=maybe-no-member
raise requests.exceptions.Timeout(exception.message)
return out | python | def _post(url, headers, body, retries=3, timeout=3.0):
"""Try 3 times to request the content.
:param headers: The HTTP headers
:type headers: dict
:param body: The body of the HTTP post
:type body: str
:param retries: The number of times to retry before giving up
:type retries: int
:param timeout: The time to wait for the post to complete, before timing
out
:type timeout: float
"""
retry = 0
out = None
while out is None:
try:
out = requests.post(url, headers=headers, data=body,
timeout=timeout)
# Due to a bug in requests, the post command will sometimes fail to
# properly wrap a socket.timeout exception in requests own exception.
# See https://github.com/kennethreitz/requests/issues/2045
# Until this is fixed, we need to catch both types of exceptions
except (requests.exceptions.Timeout, socket.timeout) as exception:
retry += 1
if retry == retries:
# pylint: disable=maybe-no-member
raise requests.exceptions.Timeout(exception.message)
return out | [
"def",
"_post",
"(",
"url",
",",
"headers",
",",
"body",
",",
"retries",
"=",
"3",
",",
"timeout",
"=",
"3.0",
")",
":",
"retry",
"=",
"0",
"out",
"=",
"None",
"while",
"out",
"is",
"None",
":",
"try",
":",
"out",
"=",
"requests",
".",
"post",
... | Try 3 times to request the content.
:param headers: The HTTP headers
:type headers: dict
:param body: The body of the HTTP post
:type body: str
:param retries: The number of times to retry before giving up
:type retries: int
:param timeout: The time to wait for the post to complete, before timing
out
:type timeout: float | [
"Try",
"3",
"times",
"to",
"request",
"the",
"content",
"."
] | 671937e07d7973b78c0cbee153d4f3ad68ec48c6 | https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/plugins/wimp.py#L28-L56 | train | 214,694 |
SoCo/SoCo | soco/plugins/wimp.py | _get_header | def _get_header(soap_action):
"""Return the HTTP for SOAP Action.
:param soap_action: The soap action to include in the header. Can be either
'search' or 'get_metadata'
:type soap_action: str
"""
# This way of setting accepted language is obviously flawed, in that it
# depends on the locale settings of the system. However, I'm unsure if
# they are actually used. The character coding is set elsewhere and I think
# the available music in each country is bound to the account.
language, _ = locale.getdefaultlocale()
if language is None:
language = ''
else:
language = language.replace('_', '-') + ', '
header = {
'CONNECTION': 'close',
'ACCEPT-ENCODING': 'gzip',
'ACCEPT-LANGUAGE': '{}en-US;q=0.9'.format(language),
'Content-Type': 'text/xml; charset="utf-8"',
'SOAPACTION': SOAP_ACTION[soap_action]
}
return header | python | def _get_header(soap_action):
"""Return the HTTP for SOAP Action.
:param soap_action: The soap action to include in the header. Can be either
'search' or 'get_metadata'
:type soap_action: str
"""
# This way of setting accepted language is obviously flawed, in that it
# depends on the locale settings of the system. However, I'm unsure if
# they are actually used. The character coding is set elsewhere and I think
# the available music in each country is bound to the account.
language, _ = locale.getdefaultlocale()
if language is None:
language = ''
else:
language = language.replace('_', '-') + ', '
header = {
'CONNECTION': 'close',
'ACCEPT-ENCODING': 'gzip',
'ACCEPT-LANGUAGE': '{}en-US;q=0.9'.format(language),
'Content-Type': 'text/xml; charset="utf-8"',
'SOAPACTION': SOAP_ACTION[soap_action]
}
return header | [
"def",
"_get_header",
"(",
"soap_action",
")",
":",
"# This way of setting accepted language is obviously flawed, in that it",
"# depends on the locale settings of the system. However, I'm unsure if",
"# they are actually used. The character coding is set elsewhere and I think",
"# the available m... | Return the HTTP for SOAP Action.
:param soap_action: The soap action to include in the header. Can be either
'search' or 'get_metadata'
:type soap_action: str | [
"Return",
"the",
"HTTP",
"for",
"SOAP",
"Action",
"."
] | 671937e07d7973b78c0cbee153d4f3ad68ec48c6 | https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/plugins/wimp.py#L72-L96 | train | 214,695 |
SoCo/SoCo | soco/plugins/wimp.py | Wimp.get_tracks | def get_tracks(self, search, start=0, max_items=100):
"""Search for tracks.
See get_music_service_information for details on the arguments
"""
return self.get_music_service_information('tracks', search, start,
max_items) | python | def get_tracks(self, search, start=0, max_items=100):
"""Search for tracks.
See get_music_service_information for details on the arguments
"""
return self.get_music_service_information('tracks', search, start,
max_items) | [
"def",
"get_tracks",
"(",
"self",
",",
"search",
",",
"start",
"=",
"0",
",",
"max_items",
"=",
"100",
")",
":",
"return",
"self",
".",
"get_music_service_information",
"(",
"'tracks'",
",",
"search",
",",
"start",
",",
"max_items",
")"
] | Search for tracks.
See get_music_service_information for details on the arguments | [
"Search",
"for",
"tracks",
"."
] | 671937e07d7973b78c0cbee153d4f3ad68ec48c6 | https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/plugins/wimp.py#L192-L198 | train | 214,696 |
SoCo/SoCo | soco/plugins/wimp.py | Wimp.get_albums | def get_albums(self, search, start=0, max_items=100):
"""Search for albums.
See get_music_service_information for details on the arguments
"""
return self.get_music_service_information('albums', search, start,
max_items) | python | def get_albums(self, search, start=0, max_items=100):
"""Search for albums.
See get_music_service_information for details on the arguments
"""
return self.get_music_service_information('albums', search, start,
max_items) | [
"def",
"get_albums",
"(",
"self",
",",
"search",
",",
"start",
"=",
"0",
",",
"max_items",
"=",
"100",
")",
":",
"return",
"self",
".",
"get_music_service_information",
"(",
"'albums'",
",",
"search",
",",
"start",
",",
"max_items",
")"
] | Search for albums.
See get_music_service_information for details on the arguments | [
"Search",
"for",
"albums",
"."
] | 671937e07d7973b78c0cbee153d4f3ad68ec48c6 | https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/plugins/wimp.py#L200-L206 | train | 214,697 |
SoCo/SoCo | soco/plugins/wimp.py | Wimp.get_artists | def get_artists(self, search, start=0, max_items=100):
"""Search for artists.
See get_music_service_information for details on the arguments
"""
return self.get_music_service_information('artists', search, start,
max_items) | python | def get_artists(self, search, start=0, max_items=100):
"""Search for artists.
See get_music_service_information for details on the arguments
"""
return self.get_music_service_information('artists', search, start,
max_items) | [
"def",
"get_artists",
"(",
"self",
",",
"search",
",",
"start",
"=",
"0",
",",
"max_items",
"=",
"100",
")",
":",
"return",
"self",
".",
"get_music_service_information",
"(",
"'artists'",
",",
"search",
",",
"start",
",",
"max_items",
")"
] | Search for artists.
See get_music_service_information for details on the arguments | [
"Search",
"for",
"artists",
"."
] | 671937e07d7973b78c0cbee153d4f3ad68ec48c6 | https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/plugins/wimp.py#L208-L214 | train | 214,698 |
SoCo/SoCo | soco/plugins/wimp.py | Wimp.get_playlists | def get_playlists(self, search, start=0, max_items=100):
"""Search for playlists.
See get_music_service_information for details on the arguments.
Note:
Un-intuitively this method returns MSAlbumList items. See
note in class doc string for details.
"""
return self.get_music_service_information('playlists', search, start,
max_items) | python | def get_playlists(self, search, start=0, max_items=100):
"""Search for playlists.
See get_music_service_information for details on the arguments.
Note:
Un-intuitively this method returns MSAlbumList items. See
note in class doc string for details.
"""
return self.get_music_service_information('playlists', search, start,
max_items) | [
"def",
"get_playlists",
"(",
"self",
",",
"search",
",",
"start",
"=",
"0",
",",
"max_items",
"=",
"100",
")",
":",
"return",
"self",
".",
"get_music_service_information",
"(",
"'playlists'",
",",
"search",
",",
"start",
",",
"max_items",
")"
] | Search for playlists.
See get_music_service_information for details on the arguments.
Note:
Un-intuitively this method returns MSAlbumList items. See
note in class doc string for details. | [
"Search",
"for",
"playlists",
"."
] | 671937e07d7973b78c0cbee153d4f3ad68ec48c6 | https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/plugins/wimp.py#L216-L227 | train | 214,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.