id
int32
0
252k
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
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
233,500
has2k1/plotnine
plotnine/utils.py
_id_var
def _id_var(x, drop=False): """ Assign ids to items in x. If two items are the same, they get the same id. Parameters ---------- x : array-like items to associate ids with drop : bool Whether to drop unused factor levels """ if len(x) == 0: return [] categorical = pdtypes.is_categorical_dtype(x) if categorical: if drop: x = x.cat.remove_unused_categories() lst = list(x.cat.codes + 1) else: has_nan = any(np.isnan(i) for i in x if isinstance(i, float)) if has_nan: # NaNs are -1, we give them the highest code nan_code = -1 new_nan_code = np.max(x.cat.codes) + 1 lst = [val if val != nan_code else new_nan_code for val in x] else: lst = list(x.cat.codes + 1) else: try: levels = np.sort(np.unique(x)) except TypeError: # x probably has NANs levels = multitype_sort(set(x)) lst = match(x, levels) lst = [item + 1 for item in lst] return lst
python
def _id_var(x, drop=False): if len(x) == 0: return [] categorical = pdtypes.is_categorical_dtype(x) if categorical: if drop: x = x.cat.remove_unused_categories() lst = list(x.cat.codes + 1) else: has_nan = any(np.isnan(i) for i in x if isinstance(i, float)) if has_nan: # NaNs are -1, we give them the highest code nan_code = -1 new_nan_code = np.max(x.cat.codes) + 1 lst = [val if val != nan_code else new_nan_code for val in x] else: lst = list(x.cat.codes + 1) else: try: levels = np.sort(np.unique(x)) except TypeError: # x probably has NANs levels = multitype_sort(set(x)) lst = match(x, levels) lst = [item + 1 for item in lst] return lst
[ "def", "_id_var", "(", "x", ",", "drop", "=", "False", ")", ":", "if", "len", "(", "x", ")", "==", "0", ":", "return", "[", "]", "categorical", "=", "pdtypes", ".", "is_categorical_dtype", "(", "x", ")", "if", "categorical", ":", "if", "drop", ":",...
Assign ids to items in x. If two items are the same, they get the same id. Parameters ---------- x : array-like items to associate ids with drop : bool Whether to drop unused factor levels
[ "Assign", "ids", "to", "items", "in", "x", ".", "If", "two", "items", "are", "the", "same", "they", "get", "the", "same", "id", "." ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L299-L339
233,501
has2k1/plotnine
plotnine/utils.py
join_keys
def join_keys(x, y, by=None): """ Join keys. Given two data frames, create a unique key for each row. Parameters ----------- x : dataframe y : dataframe by : list-like Column names to join by Returns ------- out : dict Dictionary with keys x and y. The values of both keys are arrays with integer elements. Identical rows in x and y dataframes would have the same key in the output. The key elements start at 1. """ if by is None: by = slice(None, None, None) if isinstance(by, tuple): by = list(by) joint = x[by].append(y[by], ignore_index=True) keys = ninteraction(joint, drop=True) keys = np.asarray(keys) nx, ny = len(x), len(y) return {'x': keys[np.arange(nx)], 'y': keys[nx + np.arange(ny)]}
python
def join_keys(x, y, by=None): if by is None: by = slice(None, None, None) if isinstance(by, tuple): by = list(by) joint = x[by].append(y[by], ignore_index=True) keys = ninteraction(joint, drop=True) keys = np.asarray(keys) nx, ny = len(x), len(y) return {'x': keys[np.arange(nx)], 'y': keys[nx + np.arange(ny)]}
[ "def", "join_keys", "(", "x", ",", "y", ",", "by", "=", "None", ")", ":", "if", "by", "is", "None", ":", "by", "=", "slice", "(", "None", ",", "None", ",", "None", ")", "if", "isinstance", "(", "by", ",", "tuple", ")", ":", "by", "=", "list",...
Join keys. Given two data frames, create a unique key for each row. Parameters ----------- x : dataframe y : dataframe by : list-like Column names to join by Returns ------- out : dict Dictionary with keys x and y. The values of both keys are arrays with integer elements. Identical rows in x and y dataframes would have the same key in the output. The key elements start at 1.
[ "Join", "keys", "." ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L342-L374
233,502
has2k1/plotnine
plotnine/utils.py
uniquecols
def uniquecols(df): """ Return unique columns This is used for figuring out which columns are constant within a group """ bool_idx = df.apply(lambda col: len(np.unique(col)) == 1, axis=0) df = df.loc[:, bool_idx].iloc[0:1, :].reset_index(drop=True) return df
python
def uniquecols(df): bool_idx = df.apply(lambda col: len(np.unique(col)) == 1, axis=0) df = df.loc[:, bool_idx].iloc[0:1, :].reset_index(drop=True) return df
[ "def", "uniquecols", "(", "df", ")", ":", "bool_idx", "=", "df", ".", "apply", "(", "lambda", "col", ":", "len", "(", "np", ".", "unique", "(", "col", ")", ")", "==", "1", ",", "axis", "=", "0", ")", "df", "=", "df", ".", "loc", "[", ":", "...
Return unique columns This is used for figuring out which columns are constant within a group
[ "Return", "unique", "columns" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L386-L395
233,503
has2k1/plotnine
plotnine/utils.py
defaults
def defaults(d1, d2): """ Update a copy of d1 with the contents of d2 that are not in d1. d1 and d2 are dictionary like objects. Parameters ---------- d1 : dict | dataframe dict with the preferred values d2 : dict | dataframe dict with the default values Returns ------- out : dict | dataframe Result of adding default values type of d1 """ d1 = d1.copy() tolist = isinstance(d2, pd.DataFrame) keys = (k for k in d2 if k not in d1) for k in keys: if tolist: d1[k] = d2[k].tolist() else: d1[k] = d2[k] return d1
python
def defaults(d1, d2): d1 = d1.copy() tolist = isinstance(d2, pd.DataFrame) keys = (k for k in d2 if k not in d1) for k in keys: if tolist: d1[k] = d2[k].tolist() else: d1[k] = d2[k] return d1
[ "def", "defaults", "(", "d1", ",", "d2", ")", ":", "d1", "=", "d1", ".", "copy", "(", ")", "tolist", "=", "isinstance", "(", "d2", ",", "pd", ".", "DataFrame", ")", "keys", "=", "(", "k", "for", "k", "in", "d2", "if", "k", "not", "in", "d1", ...
Update a copy of d1 with the contents of d2 that are not in d1. d1 and d2 are dictionary like objects. Parameters ---------- d1 : dict | dataframe dict with the preferred values d2 : dict | dataframe dict with the default values Returns ------- out : dict | dataframe Result of adding default values type of d1
[ "Update", "a", "copy", "of", "d1", "with", "the", "contents", "of", "d2", "that", "are", "not", "in", "d1", ".", "d1", "and", "d2", "are", "dictionary", "like", "objects", "." ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L398-L424
233,504
has2k1/plotnine
plotnine/utils.py
jitter
def jitter(x, factor=1, amount=None, random_state=None): """ Add a small amount of noise to values in an array_like Parameters ---------- x : array_like Values to apply a jitter factor : float Multiplicative value to used in automatically determining the `amount`. If the `amount` is given then the `factor` has no effect. amount : float This defines the range ([-amount, amount]) of the jitter to apply to the values. If `0` then ``amount = factor * z/50``. If `None` then ``amount = factor * d/5``, where d is about the smallest difference between `x` values and `z` is the range of the `x` values. random_state : int or ~numpy.random.RandomState, optional Seed or Random number generator to use. If ``None``, then numpy global generator :class:`numpy.random` is used. References: - Chambers, J. M., Cleveland, W. S., Kleiner, B. and Tukey, P.A. (1983) *Graphical Methods for Data Analysis*. Wadsworth; figures 2.8, 4.22, 5.4. """ if len(x) == 0: return x if random_state is None: random_state = np.random elif isinstance(random_state, int): random_state = np.random.RandomState(random_state) x = np.asarray(x) try: z = np.ptp(x[np.isfinite(x)]) except IndexError: z = 0 if z == 0: z = np.abs(np.min(x)) if z == 0: z = 1 if amount is None: _x = np.round(x, 3-np.int(np.floor(np.log10(z)))).astype(np.int) xx = np.unique(np.sort(_x)) d = np.diff(xx) if len(d): d = d.min() elif xx != 0: d = xx/10. else: d = z/10 amount = factor/5. * abs(d) elif amount == 0: amount = factor * (z / 50.) return x + random_state.uniform(-amount, amount, len(x))
python
def jitter(x, factor=1, amount=None, random_state=None): if len(x) == 0: return x if random_state is None: random_state = np.random elif isinstance(random_state, int): random_state = np.random.RandomState(random_state) x = np.asarray(x) try: z = np.ptp(x[np.isfinite(x)]) except IndexError: z = 0 if z == 0: z = np.abs(np.min(x)) if z == 0: z = 1 if amount is None: _x = np.round(x, 3-np.int(np.floor(np.log10(z)))).astype(np.int) xx = np.unique(np.sort(_x)) d = np.diff(xx) if len(d): d = d.min() elif xx != 0: d = xx/10. else: d = z/10 amount = factor/5. * abs(d) elif amount == 0: amount = factor * (z / 50.) return x + random_state.uniform(-amount, amount, len(x))
[ "def", "jitter", "(", "x", ",", "factor", "=", "1", ",", "amount", "=", "None", ",", "random_state", "=", "None", ")", ":", "if", "len", "(", "x", ")", "==", "0", ":", "return", "x", "if", "random_state", "is", "None", ":", "random_state", "=", "...
Add a small amount of noise to values in an array_like Parameters ---------- x : array_like Values to apply a jitter factor : float Multiplicative value to used in automatically determining the `amount`. If the `amount` is given then the `factor` has no effect. amount : float This defines the range ([-amount, amount]) of the jitter to apply to the values. If `0` then ``amount = factor * z/50``. If `None` then ``amount = factor * d/5``, where d is about the smallest difference between `x` values and `z` is the range of the `x` values. random_state : int or ~numpy.random.RandomState, optional Seed or Random number generator to use. If ``None``, then numpy global generator :class:`numpy.random` is used. References: - Chambers, J. M., Cleveland, W. S., Kleiner, B. and Tukey, P.A. (1983) *Graphical Methods for Data Analysis*. Wadsworth; figures 2.8, 4.22, 5.4.
[ "Add", "a", "small", "amount", "of", "noise", "to", "values", "in", "an", "array_like" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L427-L489
233,505
has2k1/plotnine
plotnine/utils.py
remove_missing
def remove_missing(df, na_rm=False, vars=None, name='', finite=False): """ Convenience function to remove missing values from a dataframe Parameters ---------- df : dataframe na_rm : bool If False remove all non-complete rows with and show warning. vars : list-like columns to act on name : str Name of calling method for a more informative message finite : bool If True replace the infinite values in addition to the NaNs """ n = len(df) if vars is None: vars = df.columns else: vars = df.columns.intersection(vars) if finite: lst = [np.inf, -np.inf] to_replace = {v: lst for v in vars} df.replace(to_replace, np.nan, inplace=True) txt = 'non-finite' else: txt = 'missing' df = df.dropna(subset=vars) df.reset_index(drop=True, inplace=True) if len(df) < n and not na_rm: msg = '{} : Removed {} rows containing {} values.' warn(msg.format(name, n-len(df), txt), PlotnineWarning, stacklevel=3) return df
python
def remove_missing(df, na_rm=False, vars=None, name='', finite=False): n = len(df) if vars is None: vars = df.columns else: vars = df.columns.intersection(vars) if finite: lst = [np.inf, -np.inf] to_replace = {v: lst for v in vars} df.replace(to_replace, np.nan, inplace=True) txt = 'non-finite' else: txt = 'missing' df = df.dropna(subset=vars) df.reset_index(drop=True, inplace=True) if len(df) < n and not na_rm: msg = '{} : Removed {} rows containing {} values.' warn(msg.format(name, n-len(df), txt), PlotnineWarning, stacklevel=3) return df
[ "def", "remove_missing", "(", "df", ",", "na_rm", "=", "False", ",", "vars", "=", "None", ",", "name", "=", "''", ",", "finite", "=", "False", ")", ":", "n", "=", "len", "(", "df", ")", "if", "vars", "is", "None", ":", "vars", "=", "df", ".", ...
Convenience function to remove missing values from a dataframe Parameters ---------- df : dataframe na_rm : bool If False remove all non-complete rows with and show warning. vars : list-like columns to act on name : str Name of calling method for a more informative message finite : bool If True replace the infinite values in addition to the NaNs
[ "Convenience", "function", "to", "remove", "missing", "values", "from", "a", "dataframe" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L492-L528
233,506
has2k1/plotnine
plotnine/utils.py
to_rgba
def to_rgba(colors, alpha): """ Covert hex colors to rgba values. Parameters ---------- colors : iterable | str colors to convert alphas : iterable | float alpha values Returns ------- out : ndarray | tuple rgba color(s) Notes ----- Matplotlib plotting functions only accept scalar alpha values. Hence no two objects with different alpha values may be plotted in one call. This would make plots with continuous alpha values innefficient. However :), the colors can be rgba hex values or list-likes and the alpha dimension will be respected. """ def is_iterable(var): return cbook.iterable(var) and not is_string(var) def has_alpha(c): if isinstance(c, tuple): if len(c) == 4: return True elif isinstance(c, str): if c[0] == '#' and len(c) == 9: return True return False def no_color(c): return c is None or c == '' or c.lower() == 'none' def to_rgba_hex(c, a): """ Conver rgb color to rgba hex value If color c has an alpha channel, then alpha value a is ignored """ _has_alpha = has_alpha(c) c = mcolors.to_hex(c, keep_alpha=_has_alpha) if not _has_alpha: arr = colorConverter.to_rgba(c, a) return mcolors.to_hex(arr, keep_alpha=True) return c if is_iterable(colors): if all(no_color(c) for c in colors): return 'none' if is_iterable(alpha): return [to_rgba_hex(c, a) for c, a in zip(colors, alpha)] else: return [to_rgba_hex(c, alpha) for c in colors] else: if no_color(colors): return colors if is_iterable(alpha): return [to_rgba_hex(colors, a) for a in alpha] else: return to_rgba_hex(colors, alpha)
python
def to_rgba(colors, alpha): def is_iterable(var): return cbook.iterable(var) and not is_string(var) def has_alpha(c): if isinstance(c, tuple): if len(c) == 4: return True elif isinstance(c, str): if c[0] == '#' and len(c) == 9: return True return False def no_color(c): return c is None or c == '' or c.lower() == 'none' def to_rgba_hex(c, a): """ Conver rgb color to rgba hex value If color c has an alpha channel, then alpha value a is ignored """ _has_alpha = has_alpha(c) c = mcolors.to_hex(c, keep_alpha=_has_alpha) if not _has_alpha: arr = colorConverter.to_rgba(c, a) return mcolors.to_hex(arr, keep_alpha=True) return c if is_iterable(colors): if all(no_color(c) for c in colors): return 'none' if is_iterable(alpha): return [to_rgba_hex(c, a) for c, a in zip(colors, alpha)] else: return [to_rgba_hex(c, alpha) for c in colors] else: if no_color(colors): return colors if is_iterable(alpha): return [to_rgba_hex(colors, a) for a in alpha] else: return to_rgba_hex(colors, alpha)
[ "def", "to_rgba", "(", "colors", ",", "alpha", ")", ":", "def", "is_iterable", "(", "var", ")", ":", "return", "cbook", ".", "iterable", "(", "var", ")", "and", "not", "is_string", "(", "var", ")", "def", "has_alpha", "(", "c", ")", ":", "if", "isi...
Covert hex colors to rgba values. Parameters ---------- colors : iterable | str colors to convert alphas : iterable | float alpha values Returns ------- out : ndarray | tuple rgba color(s) Notes ----- Matplotlib plotting functions only accept scalar alpha values. Hence no two objects with different alpha values may be plotted in one call. This would make plots with continuous alpha values innefficient. However :), the colors can be rgba hex values or list-likes and the alpha dimension will be respected.
[ "Covert", "hex", "colors", "to", "rgba", "values", "." ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L531-L601
233,507
has2k1/plotnine
plotnine/utils.py
groupby_apply
def groupby_apply(df, cols, func, *args, **kwargs): """ Groupby cols and call the function fn on each grouped dataframe. Parameters ---------- cols : str | list of str columns to groupby func : function function to call on the grouped data *args : tuple positional parameters to pass to func **kwargs : dict keyword parameter to pass to func This is meant to avoid pandas df.groupby('col').apply(fn, *args), as it calls fn twice on the first dataframe. If the nested code also does the same thing, it can be very expensive """ try: axis = kwargs.pop('axis') except KeyError: axis = 0 lst = [] for _, d in df.groupby(cols): # function fn should be free to modify dataframe d, therefore # do not mark d as a slice of df i.e no SettingWithCopyWarning lst.append(func(d, *args, **kwargs)) return pd.concat(lst, axis=axis, ignore_index=True)
python
def groupby_apply(df, cols, func, *args, **kwargs): try: axis = kwargs.pop('axis') except KeyError: axis = 0 lst = [] for _, d in df.groupby(cols): # function fn should be free to modify dataframe d, therefore # do not mark d as a slice of df i.e no SettingWithCopyWarning lst.append(func(d, *args, **kwargs)) return pd.concat(lst, axis=axis, ignore_index=True)
[ "def", "groupby_apply", "(", "df", ",", "cols", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "axis", "=", "kwargs", ".", "pop", "(", "'axis'", ")", "except", "KeyError", ":", "axis", "=", "0", "lst", "=", "[", "...
Groupby cols and call the function fn on each grouped dataframe. Parameters ---------- cols : str | list of str columns to groupby func : function function to call on the grouped data *args : tuple positional parameters to pass to func **kwargs : dict keyword parameter to pass to func This is meant to avoid pandas df.groupby('col').apply(fn, *args), as it calls fn twice on the first dataframe. If the nested code also does the same thing, it can be very expensive
[ "Groupby", "cols", "and", "call", "the", "function", "fn", "on", "each", "grouped", "dataframe", "." ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L604-L633
233,508
has2k1/plotnine
plotnine/utils.py
pivot_apply
def pivot_apply(df, column, index, func, *args, **kwargs): """ Apply a function to each group of a column The function is kind of equivalent to R's *tapply*. Parameters ---------- df : dataframe Dataframe to be pivoted column : str Column to apply function to. index : str Column that will be grouped on (and whose unique values will make up the index of the returned dataframe) func : function Function to apply to each column group. It *should* return a single value. *args : tuple Arguments to ``func`` **kwargs : dict Keyword arguments to ``func`` Returns ------- out : dataframe Dataframe with index ``index`` and column ``column`` of computed/aggregate values . """ def _func(x): return func(x, *args, **kwargs) return df.pivot_table(column, index, aggfunc=_func)[column]
python
def pivot_apply(df, column, index, func, *args, **kwargs): def _func(x): return func(x, *args, **kwargs) return df.pivot_table(column, index, aggfunc=_func)[column]
[ "def", "pivot_apply", "(", "df", ",", "column", ",", "index", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "_func", "(", "x", ")", ":", "return", "func", "(", "x", ",", "*", "args", ",", "*", "*", "kwargs", ")", "r...
Apply a function to each group of a column The function is kind of equivalent to R's *tapply*. Parameters ---------- df : dataframe Dataframe to be pivoted column : str Column to apply function to. index : str Column that will be grouped on (and whose unique values will make up the index of the returned dataframe) func : function Function to apply to each column group. It *should* return a single value. *args : tuple Arguments to ``func`` **kwargs : dict Keyword arguments to ``func`` Returns ------- out : dataframe Dataframe with index ``index`` and column ``column`` of computed/aggregate values .
[ "Apply", "a", "function", "to", "each", "group", "of", "a", "column" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L636-L668
233,509
has2k1/plotnine
plotnine/utils.py
copy_keys
def copy_keys(source, destination, keys=None): """ Add keys in source to destination Parameters ---------- source : dict destination: dict keys : None | iterable The keys in source to be copied into destination. If None, then `keys = destination.keys()` """ if keys is None: keys = destination.keys() for k in set(source) & set(keys): destination[k] = source[k] return destination
python
def copy_keys(source, destination, keys=None): if keys is None: keys = destination.keys() for k in set(source) & set(keys): destination[k] = source[k] return destination
[ "def", "copy_keys", "(", "source", ",", "destination", ",", "keys", "=", "None", ")", ":", "if", "keys", "is", "None", ":", "keys", "=", "destination", ".", "keys", "(", ")", "for", "k", "in", "set", "(", "source", ")", "&", "set", "(", "keys", "...
Add keys in source to destination Parameters ---------- source : dict destination: dict keys : None | iterable The keys in source to be copied into destination. If None, then `keys = destination.keys()`
[ "Add", "keys", "in", "source", "to", "destination" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L766-L784
233,510
has2k1/plotnine
plotnine/utils.py
alias
def alias(name, class_object): """ Create an alias of a class object The objective of this method is to have an alias that is Registered. i.e If we have class_b = class_a Makes `class_b` an alias of `class_a`, but if `class_a` is registered by its metaclass, `class_b` is not. The solution alias('class_b', class_a) is equivalent to: class_b = class_a Register['class_b'] = class_a """ module = inspect.getmodule(class_object) module.__dict__[name] = class_object if isinstance(class_object, Registry): Registry[name] = class_object
python
def alias(name, class_object): module = inspect.getmodule(class_object) module.__dict__[name] = class_object if isinstance(class_object, Registry): Registry[name] = class_object
[ "def", "alias", "(", "name", ",", "class_object", ")", ":", "module", "=", "inspect", ".", "getmodule", "(", "class_object", ")", "module", ".", "__dict__", "[", "name", "]", "=", "class_object", "if", "isinstance", "(", "class_object", ",", "Registry", ")...
Create an alias of a class object The objective of this method is to have an alias that is Registered. i.e If we have class_b = class_a Makes `class_b` an alias of `class_a`, but if `class_a` is registered by its metaclass, `class_b` is not. The solution alias('class_b', class_a) is equivalent to: class_b = class_a Register['class_b'] = class_a
[ "Create", "an", "alias", "of", "a", "class", "object" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L881-L904
233,511
has2k1/plotnine
plotnine/utils.py
get_kwarg_names
def get_kwarg_names(func): """ Return a list of valid kwargs to function func """ sig = inspect.signature(func) kwonlyargs = [p.name for p in sig.parameters.values() if p.default is not p.empty] return kwonlyargs
python
def get_kwarg_names(func): sig = inspect.signature(func) kwonlyargs = [p.name for p in sig.parameters.values() if p.default is not p.empty] return kwonlyargs
[ "def", "get_kwarg_names", "(", "func", ")", ":", "sig", "=", "inspect", ".", "signature", "(", "func", ")", "kwonlyargs", "=", "[", "p", ".", "name", "for", "p", "in", "sig", ".", "parameters", ".", "values", "(", ")", "if", "p", ".", "default", "i...
Return a list of valid kwargs to function func
[ "Return", "a", "list", "of", "valid", "kwargs", "to", "function", "func" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L907-L914
233,512
has2k1/plotnine
plotnine/utils.py
get_valid_kwargs
def get_valid_kwargs(func, potential_kwargs): """ Return valid kwargs to function func """ kwargs = {} for name in get_kwarg_names(func): with suppress(KeyError): kwargs[name] = potential_kwargs[name] return kwargs
python
def get_valid_kwargs(func, potential_kwargs): kwargs = {} for name in get_kwarg_names(func): with suppress(KeyError): kwargs[name] = potential_kwargs[name] return kwargs
[ "def", "get_valid_kwargs", "(", "func", ",", "potential_kwargs", ")", ":", "kwargs", "=", "{", "}", "for", "name", "in", "get_kwarg_names", "(", "func", ")", ":", "with", "suppress", "(", "KeyError", ")", ":", "kwargs", "[", "name", "]", "=", "potential_...
Return valid kwargs to function func
[ "Return", "valid", "kwargs", "to", "function", "func" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L917-L925
233,513
has2k1/plotnine
plotnine/utils.py
copy_missing_columns
def copy_missing_columns(df, ref_df): """ Copy missing columns from ref_df to df If df and ref_df are the same length, the columns are copied in the entirety. If the length ofref_df is a divisor of the length of df, then the values of the columns from ref_df are repeated. Otherwise if not the same length, df gets a column where all elements are the same as the first element in ref_df Parameters ---------- df : dataframe Dataframe to which columns will be added ref_df : dataframe Dataframe from which columns will be copied """ cols = ref_df.columns.difference(df.columns) _loc = ref_df.columns.get_loc l1, l2 = len(df), len(ref_df) if l1 >= l2 and l1 % l2 == 0: idx = np.tile(range(l2), l1 // l2) else: idx = np.repeat(0, l1) for col in cols: df[col] = ref_df.iloc[idx, _loc(col)].values
python
def copy_missing_columns(df, ref_df): cols = ref_df.columns.difference(df.columns) _loc = ref_df.columns.get_loc l1, l2 = len(df), len(ref_df) if l1 >= l2 and l1 % l2 == 0: idx = np.tile(range(l2), l1 // l2) else: idx = np.repeat(0, l1) for col in cols: df[col] = ref_df.iloc[idx, _loc(col)].values
[ "def", "copy_missing_columns", "(", "df", ",", "ref_df", ")", ":", "cols", "=", "ref_df", ".", "columns", ".", "difference", "(", "df", ".", "columns", ")", "_loc", "=", "ref_df", ".", "columns", ".", "get_loc", "l1", ",", "l2", "=", "len", "(", "df"...
Copy missing columns from ref_df to df If df and ref_df are the same length, the columns are copied in the entirety. If the length ofref_df is a divisor of the length of df, then the values of the columns from ref_df are repeated. Otherwise if not the same length, df gets a column where all elements are the same as the first element in ref_df Parameters ---------- df : dataframe Dataframe to which columns will be added ref_df : dataframe Dataframe from which columns will be copied
[ "Copy", "missing", "columns", "from", "ref_df", "to", "df" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L928-L958
233,514
has2k1/plotnine
plotnine/utils.py
data_mapping_as_kwargs
def data_mapping_as_kwargs(args, kwargs): """ Return kwargs with the mapping and data values Parameters ---------- args : tuple Arguments to :class:`geom` or :class:`stat`. kwargs : dict Keyword arguments to :class:`geom` or :class:`stat`. Returns ------- out : dict kwargs that includes 'data' and 'mapping' keys. """ # No need to be strict about the aesthetic superclass aes = dict mapping, data = aes(), None aes_err = ("Found more than one aes argument. " "Expecting zero or one") data_err = "More than one dataframe argument." # check args # for arg in args: if isinstance(arg, aes) and mapping: raise PlotnineError(aes_err) if isinstance(arg, pd.DataFrame) and data: raise PlotnineError(data_err) if isinstance(arg, aes): mapping = arg elif isinstance(arg, pd.DataFrame): data = arg else: msg = "Unknown argument of type '{0}'." raise PlotnineError(msg.format(type(arg))) # check kwargs # # kwargs mapping has precedence over that in args if 'mapping' not in kwargs: kwargs['mapping'] = mapping if data is not None and 'data' in kwargs: raise PlotnineError(data_err) elif 'data' not in kwargs: kwargs['data'] = data duplicates = set(kwargs['mapping']) & set(kwargs) if duplicates: msg = "Aesthetics {} specified two times." raise PlotnineError(msg.format(duplicates)) return kwargs
python
def data_mapping_as_kwargs(args, kwargs): # No need to be strict about the aesthetic superclass aes = dict mapping, data = aes(), None aes_err = ("Found more than one aes argument. " "Expecting zero or one") data_err = "More than one dataframe argument." # check args # for arg in args: if isinstance(arg, aes) and mapping: raise PlotnineError(aes_err) if isinstance(arg, pd.DataFrame) and data: raise PlotnineError(data_err) if isinstance(arg, aes): mapping = arg elif isinstance(arg, pd.DataFrame): data = arg else: msg = "Unknown argument of type '{0}'." raise PlotnineError(msg.format(type(arg))) # check kwargs # # kwargs mapping has precedence over that in args if 'mapping' not in kwargs: kwargs['mapping'] = mapping if data is not None and 'data' in kwargs: raise PlotnineError(data_err) elif 'data' not in kwargs: kwargs['data'] = data duplicates = set(kwargs['mapping']) & set(kwargs) if duplicates: msg = "Aesthetics {} specified two times." raise PlotnineError(msg.format(duplicates)) return kwargs
[ "def", "data_mapping_as_kwargs", "(", "args", ",", "kwargs", ")", ":", "# No need to be strict about the aesthetic superclass", "aes", "=", "dict", "mapping", ",", "data", "=", "aes", "(", ")", ",", "None", "aes_err", "=", "(", "\"Found more than one aes argument. \""...
Return kwargs with the mapping and data values Parameters ---------- args : tuple Arguments to :class:`geom` or :class:`stat`. kwargs : dict Keyword arguments to :class:`geom` or :class:`stat`. Returns ------- out : dict kwargs that includes 'data' and 'mapping' keys.
[ "Return", "kwargs", "with", "the", "mapping", "and", "data", "values" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L961-L1013
233,515
has2k1/plotnine
plotnine/utils.py
resolution
def resolution(x, zero=True): """ Compute the resolution of a data vector Resolution is smallest non-zero distance between adjacent values Parameters ---------- x : 1D array-like zero : Boolean Whether to include zero values in the computation Result ------ res : resolution of x If x is an integer array, then the resolution is 1 """ x = np.asarray(x) # (unsigned) integers or an effective range of zero _x = x[~np.isnan(x)] _x = (x.min(), x.max()) if x.dtype.kind in ('i', 'u') or zero_range(_x): return 1 x = np.unique(x) if zero: x = np.unique(np.hstack([0, x])) return np.min(np.diff(np.sort(x)))
python
def resolution(x, zero=True): x = np.asarray(x) # (unsigned) integers or an effective range of zero _x = x[~np.isnan(x)] _x = (x.min(), x.max()) if x.dtype.kind in ('i', 'u') or zero_range(_x): return 1 x = np.unique(x) if zero: x = np.unique(np.hstack([0, x])) return np.min(np.diff(np.sort(x)))
[ "def", "resolution", "(", "x", ",", "zero", "=", "True", ")", ":", "x", "=", "np", ".", "asarray", "(", "x", ")", "# (unsigned) integers or an effective range of zero", "_x", "=", "x", "[", "~", "np", ".", "isnan", "(", "x", ")", "]", "_x", "=", "(",...
Compute the resolution of a data vector Resolution is smallest non-zero distance between adjacent values Parameters ---------- x : 1D array-like zero : Boolean Whether to include zero values in the computation Result ------ res : resolution of x If x is an integer array, then the resolution is 1
[ "Compute", "the", "resolution", "of", "a", "data", "vector" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L1035-L1064
233,516
has2k1/plotnine
plotnine/utils.py
cross_join
def cross_join(df1, df2): """ Return a dataframe that is a cross between dataframes df1 and df2 ref: https://github.com/pydata/pandas/issues/5401 """ if len(df1) == 0: return df2 if len(df2) == 0: return df1 # Add as lists so that the new index keeps the items in # the order that they are added together all_columns = pd.Index(list(df1.columns) + list(df2.columns)) df1['key'] = 1 df2['key'] = 1 return pd.merge(df1, df2, on='key').loc[:, all_columns]
python
def cross_join(df1, df2): if len(df1) == 0: return df2 if len(df2) == 0: return df1 # Add as lists so that the new index keeps the items in # the order that they are added together all_columns = pd.Index(list(df1.columns) + list(df2.columns)) df1['key'] = 1 df2['key'] = 1 return pd.merge(df1, df2, on='key').loc[:, all_columns]
[ "def", "cross_join", "(", "df1", ",", "df2", ")", ":", "if", "len", "(", "df1", ")", "==", "0", ":", "return", "df2", "if", "len", "(", "df2", ")", "==", "0", ":", "return", "df1", "# Add as lists so that the new index keeps the items in", "# the order that ...
Return a dataframe that is a cross between dataframes df1 and df2 ref: https://github.com/pydata/pandas/issues/5401
[ "Return", "a", "dataframe", "that", "is", "a", "cross", "between", "dataframes", "df1", "and", "df2" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L1067-L1085
233,517
has2k1/plotnine
plotnine/utils.py
to_inches
def to_inches(value, units): """ Convert value to inches Parameters ---------- value : float Value to be converted units : str Units of value. Must be one of `['in', 'cm', 'mm']`. """ lookup = {'in': lambda x: x, 'cm': lambda x: x/2.54, 'mm': lambda x: x/(2.54*10)} try: return lookup[units](value) except KeyError: raise PlotnineError("Unknown units '{}'".format(units))
python
def to_inches(value, units): lookup = {'in': lambda x: x, 'cm': lambda x: x/2.54, 'mm': lambda x: x/(2.54*10)} try: return lookup[units](value) except KeyError: raise PlotnineError("Unknown units '{}'".format(units))
[ "def", "to_inches", "(", "value", ",", "units", ")", ":", "lookup", "=", "{", "'in'", ":", "lambda", "x", ":", "x", ",", "'cm'", ":", "lambda", "x", ":", "x", "/", "2.54", ",", "'mm'", ":", "lambda", "x", ":", "x", "/", "(", "2.54", "*", "10"...
Convert value to inches Parameters ---------- value : float Value to be converted units : str Units of value. Must be one of `['in', 'cm', 'mm']`.
[ "Convert", "value", "to", "inches" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L1088-L1106
233,518
has2k1/plotnine
plotnine/utils.py
from_inches
def from_inches(value, units): """ Convert value in inches to given units Parameters ---------- value : float Value to be converted units : str Units to convert value to. Must be one of `['in', 'cm', 'mm']`. """ lookup = {'in': lambda x: x, 'cm': lambda x: x*2.54, 'mm': lambda x: x*2.54*10} try: return lookup[units](value) except KeyError: raise PlotnineError("Unknown units '{}'".format(units))
python
def from_inches(value, units): lookup = {'in': lambda x: x, 'cm': lambda x: x*2.54, 'mm': lambda x: x*2.54*10} try: return lookup[units](value) except KeyError: raise PlotnineError("Unknown units '{}'".format(units))
[ "def", "from_inches", "(", "value", ",", "units", ")", ":", "lookup", "=", "{", "'in'", ":", "lambda", "x", ":", "x", ",", "'cm'", ":", "lambda", "x", ":", "x", "*", "2.54", ",", "'mm'", ":", "lambda", "x", ":", "x", "*", "2.54", "*", "10", "...
Convert value in inches to given units Parameters ---------- value : float Value to be converted units : str Units to convert value to. Must be one of `['in', 'cm', 'mm']`.
[ "Convert", "value", "in", "inches", "to", "given", "units" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L1109-L1127
233,519
has2k1/plotnine
plotnine/utils.py
log
def log(x, base=None): """ Calculate the log Parameters ---------- x : float or array_like Input values base : int or float (Default: None) Base of the log. If `None`, the natural logarithm is computed (`base=np.e`). Returns ------- out : float or ndarray Calculated result """ if base == 10: return np.log10(x) elif base == 2: return np.log2(x) elif base is None or base == np.e: return np.log(x) else: return np.log(x)/np.log(base)
python
def log(x, base=None): if base == 10: return np.log10(x) elif base == 2: return np.log2(x) elif base is None or base == np.e: return np.log(x) else: return np.log(x)/np.log(base)
[ "def", "log", "(", "x", ",", "base", "=", "None", ")", ":", "if", "base", "==", "10", ":", "return", "np", ".", "log10", "(", "x", ")", "elif", "base", "==", "2", ":", "return", "np", ".", "log2", "(", "x", ")", "elif", "base", "is", "None", ...
Calculate the log Parameters ---------- x : float or array_like Input values base : int or float (Default: None) Base of the log. If `None`, the natural logarithm is computed (`base=np.e`). Returns ------- out : float or ndarray Calculated result
[ "Calculate", "the", "log" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L1174-L1198
233,520
cloudtools/stacker
stacker/lookups/handlers/hook_data.py
HookDataLookup.handle
def handle(cls, value, context, **kwargs): """Returns the value of a key for a given hook in hook_data. Format of value: <hook_name>::<key> """ try: hook_name, key = value.split("::") except ValueError: raise ValueError("Invalid value for hook_data: %s. Must be in " "<hook_name>::<key> format." % value) return context.hook_data[hook_name][key]
python
def handle(cls, value, context, **kwargs): try: hook_name, key = value.split("::") except ValueError: raise ValueError("Invalid value for hook_data: %s. Must be in " "<hook_name>::<key> format." % value) return context.hook_data[hook_name][key]
[ "def", "handle", "(", "cls", ",", "value", ",", "context", ",", "*", "*", "kwargs", ")", ":", "try", ":", "hook_name", ",", "key", "=", "value", ".", "split", "(", "\"::\"", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "\"Invalid value...
Returns the value of a key for a given hook in hook_data. Format of value: <hook_name>::<key>
[ "Returns", "the", "value", "of", "a", "key", "for", "a", "given", "hook", "in", "hook_data", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/lookups/handlers/hook_data.py#L13-L26
233,521
cloudtools/stacker
stacker/variables.py
resolve_variables
def resolve_variables(variables, context, provider): """Given a list of variables, resolve all of them. Args: variables (list of :class:`stacker.variables.Variable`): list of variables context (:class:`stacker.context.Context`): stacker context provider (:class:`stacker.provider.base.BaseProvider`): subclass of the base provider """ for variable in variables: variable.resolve(context, provider)
python
def resolve_variables(variables, context, provider): for variable in variables: variable.resolve(context, provider)
[ "def", "resolve_variables", "(", "variables", ",", "context", ",", "provider", ")", ":", "for", "variable", "in", "variables", ":", "variable", ".", "resolve", "(", "context", ",", "provider", ")" ]
Given a list of variables, resolve all of them. Args: variables (list of :class:`stacker.variables.Variable`): list of variables context (:class:`stacker.context.Context`): stacker context provider (:class:`stacker.provider.base.BaseProvider`): subclass of the base provider
[ "Given", "a", "list", "of", "variables", "resolve", "all", "of", "them", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/variables.py#L23-L35
233,522
cloudtools/stacker
stacker/variables.py
Variable.value
def value(self): """Return the current value of the Variable. """ try: return self._value.value() except UnresolvedVariableValue: raise UnresolvedVariable("<unknown>", self) except InvalidLookupConcatenation as e: raise InvalidLookupCombination(e.lookup, e.lookups, self)
python
def value(self): try: return self._value.value() except UnresolvedVariableValue: raise UnresolvedVariable("<unknown>", self) except InvalidLookupConcatenation as e: raise InvalidLookupCombination(e.lookup, e.lookups, self)
[ "def", "value", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_value", ".", "value", "(", ")", "except", "UnresolvedVariableValue", ":", "raise", "UnresolvedVariable", "(", "\"<unknown>\"", ",", "self", ")", "except", "InvalidLookupConcatenation", ...
Return the current value of the Variable.
[ "Return", "the", "current", "value", "of", "the", "Variable", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/variables.py#L53-L61
233,523
cloudtools/stacker
stacker/variables.py
Variable.resolve
def resolve(self, context, provider): """Recursively resolve any lookups with the Variable. Args: context (:class:`stacker.context.Context`): Current context for building the stack provider (:class:`stacker.provider.base.BaseProvider`): subclass of the base provider """ try: self._value.resolve(context, provider) except FailedLookup as e: raise FailedVariableLookup(self.name, e.lookup, e.error)
python
def resolve(self, context, provider): try: self._value.resolve(context, provider) except FailedLookup as e: raise FailedVariableLookup(self.name, e.lookup, e.error)
[ "def", "resolve", "(", "self", ",", "context", ",", "provider", ")", ":", "try", ":", "self", ".", "_value", ".", "resolve", "(", "context", ",", "provider", ")", "except", "FailedLookup", "as", "e", ":", "raise", "FailedVariableLookup", "(", "self", "."...
Recursively resolve any lookups with the Variable. Args: context (:class:`stacker.context.Context`): Current context for building the stack provider (:class:`stacker.provider.base.BaseProvider`): subclass of the base provider
[ "Recursively", "resolve", "any", "lookups", "with", "the", "Variable", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/variables.py#L71-L84
233,524
cloudtools/stacker
stacker/plan.py
Step.run
def run(self): """Runs this step until it has completed successfully, or been skipped. """ stop_watcher = threading.Event() watcher = None if self.watch_func: watcher = threading.Thread( target=self.watch_func, args=(self.stack, stop_watcher) ) watcher.start() try: while not self.done: self._run_once() finally: if watcher: stop_watcher.set() watcher.join() return self.ok
python
def run(self): stop_watcher = threading.Event() watcher = None if self.watch_func: watcher = threading.Thread( target=self.watch_func, args=(self.stack, stop_watcher) ) watcher.start() try: while not self.done: self._run_once() finally: if watcher: stop_watcher.set() watcher.join() return self.ok
[ "def", "run", "(", "self", ")", ":", "stop_watcher", "=", "threading", ".", "Event", "(", ")", "watcher", "=", "None", "if", "self", ".", "watch_func", ":", "watcher", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "watch_func", ",",...
Runs this step until it has completed successfully, or been skipped.
[ "Runs", "this", "step", "until", "it", "has", "completed", "successfully", "or", "been", "skipped", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/plan.py#L68-L89
233,525
cloudtools/stacker
stacker/plan.py
Graph.downstream
def downstream(self, step_name): """Returns the direct dependencies of the given step""" return list(self.steps[dep] for dep in self.dag.downstream(step_name))
python
def downstream(self, step_name): return list(self.steps[dep] for dep in self.dag.downstream(step_name))
[ "def", "downstream", "(", "self", ",", "step_name", ")", ":", "return", "list", "(", "self", ".", "steps", "[", "dep", "]", "for", "dep", "in", "self", ".", "dag", ".", "downstream", "(", "step_name", ")", ")" ]
Returns the direct dependencies of the given step
[ "Returns", "the", "direct", "dependencies", "of", "the", "given", "step" ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/plan.py#L272-L274
233,526
cloudtools/stacker
stacker/plan.py
Graph.transposed
def transposed(self): """Returns a "transposed" version of this graph. Useful for walking in reverse. """ return Graph(steps=self.steps, dag=self.dag.transpose())
python
def transposed(self): return Graph(steps=self.steps, dag=self.dag.transpose())
[ "def", "transposed", "(", "self", ")", ":", "return", "Graph", "(", "steps", "=", "self", ".", "steps", ",", "dag", "=", "self", ".", "dag", ".", "transpose", "(", ")", ")" ]
Returns a "transposed" version of this graph. Useful for walking in reverse.
[ "Returns", "a", "transposed", "version", "of", "this", "graph", ".", "Useful", "for", "walking", "in", "reverse", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/plan.py#L276-L280
233,527
cloudtools/stacker
stacker/plan.py
Graph.filtered
def filtered(self, step_names): """Returns a "filtered" version of this graph.""" return Graph(steps=self.steps, dag=self.dag.filter(step_names))
python
def filtered(self, step_names): return Graph(steps=self.steps, dag=self.dag.filter(step_names))
[ "def", "filtered", "(", "self", ",", "step_names", ")", ":", "return", "Graph", "(", "steps", "=", "self", ".", "steps", ",", "dag", "=", "self", ".", "dag", ".", "filter", "(", "step_names", ")", ")" ]
Returns a "filtered" version of this graph.
[ "Returns", "a", "filtered", "version", "of", "this", "graph", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/plan.py#L282-L284
233,528
cloudtools/stacker
stacker/plan.py
Plan.execute
def execute(self, *args, **kwargs): """Walks each step in the underlying graph, and raises an exception if any of the steps fail. Raises: PlanFailed: Raised if any of the steps fail. """ self.walk(*args, **kwargs) failed_steps = [step for step in self.steps if step.status == FAILED] if failed_steps: raise PlanFailed(failed_steps)
python
def execute(self, *args, **kwargs): self.walk(*args, **kwargs) failed_steps = [step for step in self.steps if step.status == FAILED] if failed_steps: raise PlanFailed(failed_steps)
[ "def", "execute", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "walk", "(", "*", "args", ",", "*", "*", "kwargs", ")", "failed_steps", "=", "[", "step", "for", "step", "in", "self", ".", "steps", "if", "step", ...
Walks each step in the underlying graph, and raises an exception if any of the steps fail. Raises: PlanFailed: Raised if any of the steps fail.
[ "Walks", "each", "step", "in", "the", "underlying", "graph", "and", "raises", "an", "exception", "if", "any", "of", "the", "steps", "fail", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/plan.py#L358-L369
233,529
cloudtools/stacker
stacker/plan.py
Plan.walk
def walk(self, walker): """Walks each step in the underlying graph, in topological order. Args: walker (func): a walker function to be passed to :class:`stacker.dag.DAG` to walk the graph. """ def walk_func(step): # Before we execute the step, we need to ensure that it's # transitive dependencies are all in an "ok" state. If not, we # won't execute this step. for dep in self.graph.downstream(step.name): if not dep.ok: step.set_status(FailedStatus("dependency has failed")) return step.ok return step.run() return self.graph.walk(walker, walk_func)
python
def walk(self, walker): def walk_func(step): # Before we execute the step, we need to ensure that it's # transitive dependencies are all in an "ok" state. If not, we # won't execute this step. for dep in self.graph.downstream(step.name): if not dep.ok: step.set_status(FailedStatus("dependency has failed")) return step.ok return step.run() return self.graph.walk(walker, walk_func)
[ "def", "walk", "(", "self", ",", "walker", ")", ":", "def", "walk_func", "(", "step", ")", ":", "# Before we execute the step, we need to ensure that it's", "# transitive dependencies are all in an \"ok\" state. If not, we", "# won't execute this step.", "for", "dep", "in", "...
Walks each step in the underlying graph, in topological order. Args: walker (func): a walker function to be passed to :class:`stacker.dag.DAG` to walk the graph.
[ "Walks", "each", "step", "in", "the", "underlying", "graph", "in", "topological", "order", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/plan.py#L371-L390
233,530
cloudtools/stacker
stacker/blueprints/variables/types.py
TroposphereType.create
def create(self, value): """Create the troposphere type from the value. Args: value (Union[dict, list]): A dictionary or list of dictionaries (see class documentation for details) to use as parameters to create the Troposphere type instance. Each dictionary will be passed to the `from_dict` method of the type. Returns: Union[list, type]: Returns the value converted to the troposphere type """ # Explicitly check with len such that non-sequence types throw. if self._optional and (value is None or len(value) == 0): return None if hasattr(self._type, 'resource_type'): # Our type is a resource, so ensure we have a dict of title to # parameters if not isinstance(value, dict): raise ValueError("Resources must be specified as a dict of " "title to parameters") if not self._many and len(value) > 1: raise ValueError("Only one resource can be provided for this " "TroposphereType variable") result = [ self._type.from_dict(title, v) for title, v in value.items() ] else: # Our type is for properties, not a resource, so don't use # titles if self._many: result = [self._type.from_dict(None, v) for v in value] elif not isinstance(value, dict): raise ValueError("TroposphereType for a single non-resource" "type must be specified as a dict of " "parameters") else: result = [self._type.from_dict(None, value)] if self._validate: for v in result: v._validate_props() return result[0] if not self._many else result
python
def create(self, value): # Explicitly check with len such that non-sequence types throw. if self._optional and (value is None or len(value) == 0): return None if hasattr(self._type, 'resource_type'): # Our type is a resource, so ensure we have a dict of title to # parameters if not isinstance(value, dict): raise ValueError("Resources must be specified as a dict of " "title to parameters") if not self._many and len(value) > 1: raise ValueError("Only one resource can be provided for this " "TroposphereType variable") result = [ self._type.from_dict(title, v) for title, v in value.items() ] else: # Our type is for properties, not a resource, so don't use # titles if self._many: result = [self._type.from_dict(None, v) for v in value] elif not isinstance(value, dict): raise ValueError("TroposphereType for a single non-resource" "type must be specified as a dict of " "parameters") else: result = [self._type.from_dict(None, value)] if self._validate: for v in result: v._validate_props() return result[0] if not self._many else result
[ "def", "create", "(", "self", ",", "value", ")", ":", "# Explicitly check with len such that non-sequence types throw.", "if", "self", ".", "_optional", "and", "(", "value", "is", "None", "or", "len", "(", "value", ")", "==", "0", ")", ":", "return", "None", ...
Create the troposphere type from the value. Args: value (Union[dict, list]): A dictionary or list of dictionaries (see class documentation for details) to use as parameters to create the Troposphere type instance. Each dictionary will be passed to the `from_dict` method of the type. Returns: Union[list, type]: Returns the value converted to the troposphere type
[ "Create", "the", "troposphere", "type", "from", "the", "value", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/blueprints/variables/types.py#L61-L110
233,531
cloudtools/stacker
stacker/lookups/handlers/dynamodb.py
_lookup_key_parse
def _lookup_key_parse(table_keys): """Return the order in which the stacks should be executed. Args: dependencies (dict): a dictionary where each key should be the fully qualified name of a stack whose value is an array of fully qualified stack names that the stack depends on. This is used to generate the order in which the stacks should be executed. Returns: dict: includes a dict of lookup types with data types ('new_keys') and a list of the lookups with without ('clean_table_keys') """ # we need to parse the key lookup passed in regex_matcher = '\[([^\]]+)]' valid_dynamodb_datatypes = ['M', 'S', 'N', 'L'] clean_table_keys = [] new_keys = [] for key in table_keys: match = re.search(regex_matcher, key) if match: # the datatypes are pulled from the dynamodb docs if match.group(1) in valid_dynamodb_datatypes: match_val = str(match.group(1)) key = key.replace(match.group(0), '') new_keys.append({match_val: key}) clean_table_keys.append(key) else: raise ValueError( ('Stacker does not support looking up the datatype: {}') .format(str(match.group(1)))) else: new_keys.append({'S': key}) clean_table_keys.append(key) key_dict = {} key_dict['new_keys'] = new_keys key_dict['clean_table_keys'] = clean_table_keys return key_dict
python
def _lookup_key_parse(table_keys): # we need to parse the key lookup passed in regex_matcher = '\[([^\]]+)]' valid_dynamodb_datatypes = ['M', 'S', 'N', 'L'] clean_table_keys = [] new_keys = [] for key in table_keys: match = re.search(regex_matcher, key) if match: # the datatypes are pulled from the dynamodb docs if match.group(1) in valid_dynamodb_datatypes: match_val = str(match.group(1)) key = key.replace(match.group(0), '') new_keys.append({match_val: key}) clean_table_keys.append(key) else: raise ValueError( ('Stacker does not support looking up the datatype: {}') .format(str(match.group(1)))) else: new_keys.append({'S': key}) clean_table_keys.append(key) key_dict = {} key_dict['new_keys'] = new_keys key_dict['clean_table_keys'] = clean_table_keys return key_dict
[ "def", "_lookup_key_parse", "(", "table_keys", ")", ":", "# we need to parse the key lookup passed in", "regex_matcher", "=", "'\\[([^\\]]+)]'", "valid_dynamodb_datatypes", "=", "[", "'M'", ",", "'S'", ",", "'N'", ",", "'L'", "]", "clean_table_keys", "=", "[", "]", ...
Return the order in which the stacks should be executed. Args: dependencies (dict): a dictionary where each key should be the fully qualified name of a stack whose value is an array of fully qualified stack names that the stack depends on. This is used to generate the order in which the stacks should be executed. Returns: dict: includes a dict of lookup types with data types ('new_keys') and a list of the lookups with without ('clean_table_keys')
[ "Return", "the", "order", "in", "which", "the", "stacks", "should", "be", "executed", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/lookups/handlers/dynamodb.py#L85-L126
233,532
cloudtools/stacker
stacker/lookups/handlers/dynamodb.py
_build_projection_expression
def _build_projection_expression(clean_table_keys): """Given cleaned up keys, this will return a projection expression for the dynamodb lookup. Args: clean_table_keys (dict): keys without the data types attached Returns: str: A projection expression for the dynamodb lookup. """ projection_expression = '' for key in clean_table_keys[:-1]: projection_expression += ('{},').format(key) projection_expression += clean_table_keys[-1] return projection_expression
python
def _build_projection_expression(clean_table_keys): projection_expression = '' for key in clean_table_keys[:-1]: projection_expression += ('{},').format(key) projection_expression += clean_table_keys[-1] return projection_expression
[ "def", "_build_projection_expression", "(", "clean_table_keys", ")", ":", "projection_expression", "=", "''", "for", "key", "in", "clean_table_keys", "[", ":", "-", "1", "]", ":", "projection_expression", "+=", "(", "'{},'", ")", ".", "format", "(", "key", ")"...
Given cleaned up keys, this will return a projection expression for the dynamodb lookup. Args: clean_table_keys (dict): keys without the data types attached Returns: str: A projection expression for the dynamodb lookup.
[ "Given", "cleaned", "up", "keys", "this", "will", "return", "a", "projection", "expression", "for", "the", "dynamodb", "lookup", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/lookups/handlers/dynamodb.py#L129-L143
233,533
cloudtools/stacker
stacker/lookups/handlers/dynamodb.py
_convert_ddb_list_to_list
def _convert_ddb_list_to_list(conversion_list): """Given a dynamodb list, it will return a python list without the dynamodb datatypes Args: conversion_list (dict): a dynamodb list which includes the datatypes Returns: list: Returns a sanitized list without the dynamodb datatypes """ ret_list = [] for v in conversion_list: for v1 in v: ret_list.append(v[v1]) return ret_list
python
def _convert_ddb_list_to_list(conversion_list): ret_list = [] for v in conversion_list: for v1 in v: ret_list.append(v[v1]) return ret_list
[ "def", "_convert_ddb_list_to_list", "(", "conversion_list", ")", ":", "ret_list", "=", "[", "]", "for", "v", "in", "conversion_list", ":", "for", "v1", "in", "v", ":", "ret_list", ".", "append", "(", "v", "[", "v1", "]", ")", "return", "ret_list" ]
Given a dynamodb list, it will return a python list without the dynamodb datatypes Args: conversion_list (dict): a dynamodb list which includes the datatypes Returns: list: Returns a sanitized list without the dynamodb datatypes
[ "Given", "a", "dynamodb", "list", "it", "will", "return", "a", "python", "list", "without", "the", "dynamodb", "datatypes" ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/lookups/handlers/dynamodb.py#L180-L195
233,534
cloudtools/stacker
stacker/lookups/handlers/dynamodb.py
DynamodbLookup.handle
def handle(cls, value, **kwargs): """Get a value from a dynamodb table dynamodb field types should be in the following format: [<region>:]<tablename>@<primarypartionkey>:<keyvalue>.<keyvalue>... Note: The region is optional, and defaults to the environment's `AWS_DEFAULT_REGION` if not specified. """ value = read_value_from_path(value) table_info = None table_keys = None region = None table_name = None if '@' in value: table_info, table_keys = value.split('@', 1) if ':' in table_info: region, table_name = table_info.split(':', 1) else: table_name = table_info else: raise ValueError('Please make sure to include a tablename') if not table_name: raise ValueError('Please make sure to include a dynamodb table ' 'name') table_lookup, table_keys = table_keys.split(':', 1) table_keys = table_keys.split('.') key_dict = _lookup_key_parse(table_keys) new_keys = key_dict['new_keys'] clean_table_keys = key_dict['clean_table_keys'] projection_expression = _build_projection_expression(clean_table_keys) # lookup the data from dynamodb dynamodb = get_session(region).client('dynamodb') try: response = dynamodb.get_item( TableName=table_name, Key={ table_lookup: new_keys[0] }, ProjectionExpression=projection_expression ) except ClientError as e: if e.response['Error']['Code'] == 'ResourceNotFoundException': raise ValueError( 'Cannot find the dynamodb table: {}'.format(table_name)) elif e.response['Error']['Code'] == 'ValidationException': raise ValueError( 'No dynamodb record matched the partition key: ' '{}'.format(table_lookup)) else: raise ValueError('The dynamodb lookup {} had an error: ' '{}'.format(value, e)) # find and return the key from the dynamo data returned if 'Item' in response: return (_get_val_from_ddb_data(response['Item'], new_keys[1:])) else: raise ValueError( 'The dynamodb record could not be found using the following ' 'key: {}'.format(new_keys[0]))
python
def handle(cls, value, **kwargs): value = read_value_from_path(value) table_info = None table_keys = None region = None table_name = None if '@' in value: table_info, table_keys = value.split('@', 1) if ':' in table_info: region, table_name = table_info.split(':', 1) else: table_name = table_info else: raise ValueError('Please make sure to include a tablename') if not table_name: raise ValueError('Please make sure to include a dynamodb table ' 'name') table_lookup, table_keys = table_keys.split(':', 1) table_keys = table_keys.split('.') key_dict = _lookup_key_parse(table_keys) new_keys = key_dict['new_keys'] clean_table_keys = key_dict['clean_table_keys'] projection_expression = _build_projection_expression(clean_table_keys) # lookup the data from dynamodb dynamodb = get_session(region).client('dynamodb') try: response = dynamodb.get_item( TableName=table_name, Key={ table_lookup: new_keys[0] }, ProjectionExpression=projection_expression ) except ClientError as e: if e.response['Error']['Code'] == 'ResourceNotFoundException': raise ValueError( 'Cannot find the dynamodb table: {}'.format(table_name)) elif e.response['Error']['Code'] == 'ValidationException': raise ValueError( 'No dynamodb record matched the partition key: ' '{}'.format(table_lookup)) else: raise ValueError('The dynamodb lookup {} had an error: ' '{}'.format(value, e)) # find and return the key from the dynamo data returned if 'Item' in response: return (_get_val_from_ddb_data(response['Item'], new_keys[1:])) else: raise ValueError( 'The dynamodb record could not be found using the following ' 'key: {}'.format(new_keys[0]))
[ "def", "handle", "(", "cls", ",", "value", ",", "*", "*", "kwargs", ")", ":", "value", "=", "read_value_from_path", "(", "value", ")", "table_info", "=", "None", "table_keys", "=", "None", "region", "=", "None", "table_name", "=", "None", "if", "'@'", ...
Get a value from a dynamodb table dynamodb field types should be in the following format: [<region>:]<tablename>@<primarypartionkey>:<keyvalue>.<keyvalue>... Note: The region is optional, and defaults to the environment's `AWS_DEFAULT_REGION` if not specified.
[ "Get", "a", "value", "from", "a", "dynamodb", "table" ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/lookups/handlers/dynamodb.py#L17-L82
233,535
cloudtools/stacker
stacker/actions/base.py
plan
def plan(description, stack_action, context, tail=None, reverse=False): """A simple helper that builds a graph based plan from a set of stacks. Args: description (str): a description of the plan. action (func): a function to call for each stack. context (:class:`stacker.context.Context`): a :class:`stacker.context.Context` to build the plan from. tail (func): an optional function to call to tail the stack progress. reverse (bool): if True, execute the graph in reverse (useful for destroy actions). Returns: :class:`plan.Plan`: The resulting plan object """ def target_fn(*args, **kwargs): return COMPLETE steps = [ Step(stack, fn=stack_action, watch_func=tail) for stack in context.get_stacks()] steps += [ Step(target, fn=target_fn) for target in context.get_targets()] graph = build_graph(steps) return build_plan( description=description, graph=graph, targets=context.stack_names, reverse=reverse)
python
def plan(description, stack_action, context, tail=None, reverse=False): def target_fn(*args, **kwargs): return COMPLETE steps = [ Step(stack, fn=stack_action, watch_func=tail) for stack in context.get_stacks()] steps += [ Step(target, fn=target_fn) for target in context.get_targets()] graph = build_graph(steps) return build_plan( description=description, graph=graph, targets=context.stack_names, reverse=reverse)
[ "def", "plan", "(", "description", ",", "stack_action", ",", "context", ",", "tail", "=", "None", ",", "reverse", "=", "False", ")", ":", "def", "target_fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "COMPLETE", "steps", "=", "["...
A simple helper that builds a graph based plan from a set of stacks. Args: description (str): a description of the plan. action (func): a function to call for each stack. context (:class:`stacker.context.Context`): a :class:`stacker.context.Context` to build the plan from. tail (func): an optional function to call to tail the stack progress. reverse (bool): if True, execute the graph in reverse (useful for destroy actions). Returns: :class:`plan.Plan`: The resulting plan object
[ "A", "simple", "helper", "that", "builds", "a", "graph", "based", "plan", "from", "a", "set", "of", "stacks", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/base.py#L64-L97
233,536
cloudtools/stacker
stacker/actions/base.py
stack_template_key_name
def stack_template_key_name(blueprint): """Given a blueprint, produce an appropriate key name. Args: blueprint (:class:`stacker.blueprints.base.Blueprint`): The blueprint object to create the key from. Returns: string: Key name resulting from blueprint. """ name = blueprint.name return "stack_templates/%s/%s-%s.json" % (blueprint.context.get_fqn(name), name, blueprint.version)
python
def stack_template_key_name(blueprint): name = blueprint.name return "stack_templates/%s/%s-%s.json" % (blueprint.context.get_fqn(name), name, blueprint.version)
[ "def", "stack_template_key_name", "(", "blueprint", ")", ":", "name", "=", "blueprint", ".", "name", "return", "\"stack_templates/%s/%s-%s.json\"", "%", "(", "blueprint", ".", "context", ".", "get_fqn", "(", "name", ")", ",", "name", ",", "blueprint", ".", "ve...
Given a blueprint, produce an appropriate key name. Args: blueprint (:class:`stacker.blueprints.base.Blueprint`): The blueprint object to create the key from. Returns: string: Key name resulting from blueprint.
[ "Given", "a", "blueprint", "produce", "an", "appropriate", "key", "name", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/base.py#L100-L113
233,537
cloudtools/stacker
stacker/actions/base.py
stack_template_url
def stack_template_url(bucket_name, blueprint, endpoint): """Produces an s3 url for a given blueprint. Args: bucket_name (string): The name of the S3 bucket where the resulting templates are stored. blueprint (:class:`stacker.blueprints.base.Blueprint`): The blueprint object to create the URL to. endpoint (string): The s3 endpoint used for the bucket. Returns: string: S3 URL. """ key_name = stack_template_key_name(blueprint) return "%s/%s/%s" % (endpoint, bucket_name, key_name)
python
def stack_template_url(bucket_name, blueprint, endpoint): key_name = stack_template_key_name(blueprint) return "%s/%s/%s" % (endpoint, bucket_name, key_name)
[ "def", "stack_template_url", "(", "bucket_name", ",", "blueprint", ",", "endpoint", ")", ":", "key_name", "=", "stack_template_key_name", "(", "blueprint", ")", "return", "\"%s/%s/%s\"", "%", "(", "endpoint", ",", "bucket_name", ",", "key_name", ")" ]
Produces an s3 url for a given blueprint. Args: bucket_name (string): The name of the S3 bucket where the resulting templates are stored. blueprint (:class:`stacker.blueprints.base.Blueprint`): The blueprint object to create the URL to. endpoint (string): The s3 endpoint used for the bucket. Returns: string: S3 URL.
[ "Produces", "an", "s3", "url", "for", "a", "given", "blueprint", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/base.py#L116-L130
233,538
cloudtools/stacker
stacker/actions/base.py
BaseAction.ensure_cfn_bucket
def ensure_cfn_bucket(self): """The CloudFormation bucket where templates will be stored.""" if self.bucket_name: ensure_s3_bucket(self.s3_conn, self.bucket_name, self.bucket_region)
python
def ensure_cfn_bucket(self): if self.bucket_name: ensure_s3_bucket(self.s3_conn, self.bucket_name, self.bucket_region)
[ "def", "ensure_cfn_bucket", "(", "self", ")", ":", "if", "self", ".", "bucket_name", ":", "ensure_s3_bucket", "(", "self", ".", "s3_conn", ",", "self", ".", "bucket_name", ",", "self", ".", "bucket_region", ")" ]
The CloudFormation bucket where templates will be stored.
[ "The", "CloudFormation", "bucket", "where", "templates", "will", "be", "stored", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/base.py#L159-L164
233,539
cloudtools/stacker
stacker/actions/base.py
BaseAction.s3_stack_push
def s3_stack_push(self, blueprint, force=False): """Pushes the rendered blueprint's template to S3. Verifies that the template doesn't already exist in S3 before pushing. Returns the URL to the template in S3. """ key_name = stack_template_key_name(blueprint) template_url = self.stack_template_url(blueprint) try: template_exists = self.s3_conn.head_object( Bucket=self.bucket_name, Key=key_name) is not None except botocore.exceptions.ClientError as e: if e.response['Error']['Code'] == '404': template_exists = False else: raise if template_exists and not force: logger.debug("Cloudformation template %s already exists.", template_url) return template_url self.s3_conn.put_object(Bucket=self.bucket_name, Key=key_name, Body=blueprint.rendered, ServerSideEncryption='AES256', ACL='bucket-owner-full-control') logger.debug("Blueprint %s pushed to %s.", blueprint.name, template_url) return template_url
python
def s3_stack_push(self, blueprint, force=False): key_name = stack_template_key_name(blueprint) template_url = self.stack_template_url(blueprint) try: template_exists = self.s3_conn.head_object( Bucket=self.bucket_name, Key=key_name) is not None except botocore.exceptions.ClientError as e: if e.response['Error']['Code'] == '404': template_exists = False else: raise if template_exists and not force: logger.debug("Cloudformation template %s already exists.", template_url) return template_url self.s3_conn.put_object(Bucket=self.bucket_name, Key=key_name, Body=blueprint.rendered, ServerSideEncryption='AES256', ACL='bucket-owner-full-control') logger.debug("Blueprint %s pushed to %s.", blueprint.name, template_url) return template_url
[ "def", "s3_stack_push", "(", "self", ",", "blueprint", ",", "force", "=", "False", ")", ":", "key_name", "=", "stack_template_key_name", "(", "blueprint", ")", "template_url", "=", "self", ".", "stack_template_url", "(", "blueprint", ")", "try", ":", "template...
Pushes the rendered blueprint's template to S3. Verifies that the template doesn't already exist in S3 before pushing. Returns the URL to the template in S3.
[ "Pushes", "the", "rendered", "blueprint", "s", "template", "to", "S3", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/base.py#L171-L201
233,540
cloudtools/stacker
stacker/hooks/aws_lambda.py
_zip_files
def _zip_files(files, root): """Generates a ZIP file in-memory from a list of files. Files will be stored in the archive with relative names, and have their UNIX permissions forced to 755 or 644 (depending on whether they are user-executable in the source filesystem). Args: files (list[str]): file names to add to the archive, relative to ``root``. root (str): base directory to retrieve files from. Returns: str: content of the ZIP file as a byte string. str: A calculated hash of all the files. """ zip_data = StringIO() with ZipFile(zip_data, 'w', ZIP_DEFLATED) as zip_file: for fname in files: zip_file.write(os.path.join(root, fname), fname) # Fix file permissions to avoid any issues - only care whether a file # is executable or not, choosing between modes 755 and 644 accordingly. for zip_entry in zip_file.filelist: perms = (zip_entry.external_attr & ZIP_PERMS_MASK) >> 16 if perms & stat.S_IXUSR != 0: new_perms = 0o755 else: new_perms = 0o644 if new_perms != perms: logger.debug("lambda: fixing perms: %s: %o => %o", zip_entry.filename, perms, new_perms) new_attr = ((zip_entry.external_attr & ~ZIP_PERMS_MASK) | (new_perms << 16)) zip_entry.external_attr = new_attr contents = zip_data.getvalue() zip_data.close() content_hash = _calculate_hash(files, root) return contents, content_hash
python
def _zip_files(files, root): zip_data = StringIO() with ZipFile(zip_data, 'w', ZIP_DEFLATED) as zip_file: for fname in files: zip_file.write(os.path.join(root, fname), fname) # Fix file permissions to avoid any issues - only care whether a file # is executable or not, choosing between modes 755 and 644 accordingly. for zip_entry in zip_file.filelist: perms = (zip_entry.external_attr & ZIP_PERMS_MASK) >> 16 if perms & stat.S_IXUSR != 0: new_perms = 0o755 else: new_perms = 0o644 if new_perms != perms: logger.debug("lambda: fixing perms: %s: %o => %o", zip_entry.filename, perms, new_perms) new_attr = ((zip_entry.external_attr & ~ZIP_PERMS_MASK) | (new_perms << 16)) zip_entry.external_attr = new_attr contents = zip_data.getvalue() zip_data.close() content_hash = _calculate_hash(files, root) return contents, content_hash
[ "def", "_zip_files", "(", "files", ",", "root", ")", ":", "zip_data", "=", "StringIO", "(", ")", "with", "ZipFile", "(", "zip_data", ",", "'w'", ",", "ZIP_DEFLATED", ")", "as", "zip_file", ":", "for", "fname", "in", "files", ":", "zip_file", ".", "writ...
Generates a ZIP file in-memory from a list of files. Files will be stored in the archive with relative names, and have their UNIX permissions forced to 755 or 644 (depending on whether they are user-executable in the source filesystem). Args: files (list[str]): file names to add to the archive, relative to ``root``. root (str): base directory to retrieve files from. Returns: str: content of the ZIP file as a byte string. str: A calculated hash of all the files.
[ "Generates", "a", "ZIP", "file", "in", "-", "memory", "from", "a", "list", "of", "files", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/hooks/aws_lambda.py#L33-L75
233,541
cloudtools/stacker
stacker/hooks/aws_lambda.py
_calculate_hash
def _calculate_hash(files, root): """ Returns a hash of all of the given files at the given root. Args: files (list[str]): file names to include in the hash calculation, relative to ``root``. root (str): base directory to analyze files in. Returns: str: A hash of the hashes of the given files. """ file_hash = hashlib.md5() for fname in sorted(files): f = os.path.join(root, fname) file_hash.update((fname + "\0").encode()) with open(f, "rb") as fd: for chunk in iter(lambda: fd.read(4096), ""): if not chunk: break file_hash.update(chunk) file_hash.update("\0".encode()) return file_hash.hexdigest()
python
def _calculate_hash(files, root): file_hash = hashlib.md5() for fname in sorted(files): f = os.path.join(root, fname) file_hash.update((fname + "\0").encode()) with open(f, "rb") as fd: for chunk in iter(lambda: fd.read(4096), ""): if not chunk: break file_hash.update(chunk) file_hash.update("\0".encode()) return file_hash.hexdigest()
[ "def", "_calculate_hash", "(", "files", ",", "root", ")", ":", "file_hash", "=", "hashlib", ".", "md5", "(", ")", "for", "fname", "in", "sorted", "(", "files", ")", ":", "f", "=", "os", ".", "path", ".", "join", "(", "root", ",", "fname", ")", "f...
Returns a hash of all of the given files at the given root. Args: files (list[str]): file names to include in the hash calculation, relative to ``root``. root (str): base directory to analyze files in. Returns: str: A hash of the hashes of the given files.
[ "Returns", "a", "hash", "of", "all", "of", "the", "given", "files", "at", "the", "given", "root", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/hooks/aws_lambda.py#L78-L100
233,542
cloudtools/stacker
stacker/hooks/aws_lambda.py
_find_files
def _find_files(root, includes, excludes, follow_symlinks): """List files inside a directory based on include and exclude rules. This is a more advanced version of `glob.glob`, that accepts multiple complex patterns. Args: root (str): base directory to list files from. includes (list[str]): inclusion patterns. Only files matching those patterns will be included in the result. excludes (list[str]): exclusion patterns. Files matching those patterns will be excluded from the result. Exclusions take precedence over inclusions. follow_symlinks (bool): If true, symlinks will be included in the resulting zip file Yields: str: a file name relative to the root. Note: Documentation for the patterns can be found at http://www.aviser.asia/formic/doc/index.html """ root = os.path.abspath(root) file_set = formic.FileSet( directory=root, include=includes, exclude=excludes, symlinks=follow_symlinks, ) for filename in file_set.qualified_files(absolute=False): yield filename
python
def _find_files(root, includes, excludes, follow_symlinks): root = os.path.abspath(root) file_set = formic.FileSet( directory=root, include=includes, exclude=excludes, symlinks=follow_symlinks, ) for filename in file_set.qualified_files(absolute=False): yield filename
[ "def", "_find_files", "(", "root", ",", "includes", ",", "excludes", ",", "follow_symlinks", ")", ":", "root", "=", "os", ".", "path", ".", "abspath", "(", "root", ")", "file_set", "=", "formic", ".", "FileSet", "(", "directory", "=", "root", ",", "inc...
List files inside a directory based on include and exclude rules. This is a more advanced version of `glob.glob`, that accepts multiple complex patterns. Args: root (str): base directory to list files from. includes (list[str]): inclusion patterns. Only files matching those patterns will be included in the result. excludes (list[str]): exclusion patterns. Files matching those patterns will be excluded from the result. Exclusions take precedence over inclusions. follow_symlinks (bool): If true, symlinks will be included in the resulting zip file Yields: str: a file name relative to the root. Note: Documentation for the patterns can be found at http://www.aviser.asia/formic/doc/index.html
[ "List", "files", "inside", "a", "directory", "based", "on", "include", "and", "exclude", "rules", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/hooks/aws_lambda.py#L103-L134
233,543
cloudtools/stacker
stacker/hooks/aws_lambda.py
_zip_from_file_patterns
def _zip_from_file_patterns(root, includes, excludes, follow_symlinks): """Generates a ZIP file in-memory from file search patterns. Args: root (str): base directory to list files from. includes (list[str]): inclusion patterns. Only files matching those patterns will be included in the result. excludes (list[str]): exclusion patterns. Files matching those patterns will be excluded from the result. Exclusions take precedence over inclusions. follow_symlinks (bool): If true, symlinks will be included in the resulting zip file See Also: :func:`_zip_files`, :func:`_find_files`. Raises: RuntimeError: when the generated archive would be empty. """ logger.info('lambda: base directory: %s', root) files = list(_find_files(root, includes, excludes, follow_symlinks)) if not files: raise RuntimeError('Empty list of files for Lambda payload. Check ' 'your include/exclude options for errors.') logger.info('lambda: adding %d files:', len(files)) for fname in files: logger.debug('lambda: + %s', fname) return _zip_files(files, root)
python
def _zip_from_file_patterns(root, includes, excludes, follow_symlinks): logger.info('lambda: base directory: %s', root) files = list(_find_files(root, includes, excludes, follow_symlinks)) if not files: raise RuntimeError('Empty list of files for Lambda payload. Check ' 'your include/exclude options for errors.') logger.info('lambda: adding %d files:', len(files)) for fname in files: logger.debug('lambda: + %s', fname) return _zip_files(files, root)
[ "def", "_zip_from_file_patterns", "(", "root", ",", "includes", ",", "excludes", ",", "follow_symlinks", ")", ":", "logger", ".", "info", "(", "'lambda: base directory: %s'", ",", "root", ")", "files", "=", "list", "(", "_find_files", "(", "root", ",", "includ...
Generates a ZIP file in-memory from file search patterns. Args: root (str): base directory to list files from. includes (list[str]): inclusion patterns. Only files matching those patterns will be included in the result. excludes (list[str]): exclusion patterns. Files matching those patterns will be excluded from the result. Exclusions take precedence over inclusions. follow_symlinks (bool): If true, symlinks will be included in the resulting zip file See Also: :func:`_zip_files`, :func:`_find_files`. Raises: RuntimeError: when the generated archive would be empty.
[ "Generates", "a", "ZIP", "file", "in", "-", "memory", "from", "file", "search", "patterns", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/hooks/aws_lambda.py#L137-L169
233,544
cloudtools/stacker
stacker/hooks/aws_lambda.py
_head_object
def _head_object(s3_conn, bucket, key): """Retrieve information about an object in S3 if it exists. Args: s3_conn (botocore.client.S3): S3 connection to use for operations. bucket (str): name of the bucket containing the key. key (str): name of the key to lookup. Returns: dict: S3 object information, or None if the object does not exist. See the AWS documentation for explanation of the contents. Raises: botocore.exceptions.ClientError: any error from boto3 other than key not found is passed through. """ try: return s3_conn.head_object(Bucket=bucket, Key=key) except botocore.exceptions.ClientError as e: if e.response['Error']['Code'] == '404': return None else: raise
python
def _head_object(s3_conn, bucket, key): try: return s3_conn.head_object(Bucket=bucket, Key=key) except botocore.exceptions.ClientError as e: if e.response['Error']['Code'] == '404': return None else: raise
[ "def", "_head_object", "(", "s3_conn", ",", "bucket", ",", "key", ")", ":", "try", ":", "return", "s3_conn", ".", "head_object", "(", "Bucket", "=", "bucket", ",", "Key", "=", "key", ")", "except", "botocore", ".", "exceptions", ".", "ClientError", "as",...
Retrieve information about an object in S3 if it exists. Args: s3_conn (botocore.client.S3): S3 connection to use for operations. bucket (str): name of the bucket containing the key. key (str): name of the key to lookup. Returns: dict: S3 object information, or None if the object does not exist. See the AWS documentation for explanation of the contents. Raises: botocore.exceptions.ClientError: any error from boto3 other than key not found is passed through.
[ "Retrieve", "information", "about", "an", "object", "in", "S3", "if", "it", "exists", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/hooks/aws_lambda.py#L172-L194
233,545
cloudtools/stacker
stacker/hooks/aws_lambda.py
_upload_code
def _upload_code(s3_conn, bucket, prefix, name, contents, content_hash, payload_acl): """Upload a ZIP file to S3 for use by Lambda. The key used for the upload will be unique based on the checksum of the contents. No changes will be made if the contents in S3 already match the expected contents. Args: s3_conn (botocore.client.S3): S3 connection to use for operations. bucket (str): name of the bucket to create. prefix (str): S3 prefix to prepend to the constructed key name for the uploaded file name (str): desired name of the Lambda function. Will be used to construct a key name for the uploaded file. contents (str): byte string with the content of the file upload. content_hash (str): md5 hash of the contents to be uploaded. payload_acl (str): The canned S3 object ACL to be applied to the uploaded payload Returns: troposphere.awslambda.Code: CloudFormation Lambda Code object, pointing to the uploaded payload in S3. Raises: botocore.exceptions.ClientError: any error from boto3 is passed through. """ logger.debug('lambda: ZIP hash: %s', content_hash) key = '{}lambda-{}-{}.zip'.format(prefix, name, content_hash) if _head_object(s3_conn, bucket, key): logger.info('lambda: object %s already exists, not uploading', key) else: logger.info('lambda: uploading object %s', key) s3_conn.put_object(Bucket=bucket, Key=key, Body=contents, ContentType='application/zip', ACL=payload_acl) return Code(S3Bucket=bucket, S3Key=key)
python
def _upload_code(s3_conn, bucket, prefix, name, contents, content_hash, payload_acl): logger.debug('lambda: ZIP hash: %s', content_hash) key = '{}lambda-{}-{}.zip'.format(prefix, name, content_hash) if _head_object(s3_conn, bucket, key): logger.info('lambda: object %s already exists, not uploading', key) else: logger.info('lambda: uploading object %s', key) s3_conn.put_object(Bucket=bucket, Key=key, Body=contents, ContentType='application/zip', ACL=payload_acl) return Code(S3Bucket=bucket, S3Key=key)
[ "def", "_upload_code", "(", "s3_conn", ",", "bucket", ",", "prefix", ",", "name", ",", "contents", ",", "content_hash", ",", "payload_acl", ")", ":", "logger", ".", "debug", "(", "'lambda: ZIP hash: %s'", ",", "content_hash", ")", "key", "=", "'{}lambda-{}-{}....
Upload a ZIP file to S3 for use by Lambda. The key used for the upload will be unique based on the checksum of the contents. No changes will be made if the contents in S3 already match the expected contents. Args: s3_conn (botocore.client.S3): S3 connection to use for operations. bucket (str): name of the bucket to create. prefix (str): S3 prefix to prepend to the constructed key name for the uploaded file name (str): desired name of the Lambda function. Will be used to construct a key name for the uploaded file. contents (str): byte string with the content of the file upload. content_hash (str): md5 hash of the contents to be uploaded. payload_acl (str): The canned S3 object ACL to be applied to the uploaded payload Returns: troposphere.awslambda.Code: CloudFormation Lambda Code object, pointing to the uploaded payload in S3. Raises: botocore.exceptions.ClientError: any error from boto3 is passed through.
[ "Upload", "a", "ZIP", "file", "to", "S3", "for", "use", "by", "Lambda", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/hooks/aws_lambda.py#L197-L237
233,546
cloudtools/stacker
stacker/hooks/aws_lambda.py
_check_pattern_list
def _check_pattern_list(patterns, key, default=None): """Validates file search patterns from user configuration. Acceptable input is a string (which will be converted to a singleton list), a list of strings, or anything falsy (such as None or an empty dictionary). Empty or unset input will be converted to a default. Args: patterns: input from user configuration (YAML). key (str): name of the configuration key the input came from, used for error display purposes. Keyword Args: default: value to return in case the input is empty or unset. Returns: list[str]: validated list of patterns Raises: ValueError: if the input is unacceptable. """ if not patterns: return default if isinstance(patterns, basestring): return [patterns] if isinstance(patterns, list): if all(isinstance(p, basestring) for p in patterns): return patterns raise ValueError("Invalid file patterns in key '{}': must be a string or " 'list of strings'.format(key))
python
def _check_pattern_list(patterns, key, default=None): if not patterns: return default if isinstance(patterns, basestring): return [patterns] if isinstance(patterns, list): if all(isinstance(p, basestring) for p in patterns): return patterns raise ValueError("Invalid file patterns in key '{}': must be a string or " 'list of strings'.format(key))
[ "def", "_check_pattern_list", "(", "patterns", ",", "key", ",", "default", "=", "None", ")", ":", "if", "not", "patterns", ":", "return", "default", "if", "isinstance", "(", "patterns", ",", "basestring", ")", ":", "return", "[", "patterns", "]", "if", "...
Validates file search patterns from user configuration. Acceptable input is a string (which will be converted to a singleton list), a list of strings, or anything falsy (such as None or an empty dictionary). Empty or unset input will be converted to a default. Args: patterns: input from user configuration (YAML). key (str): name of the configuration key the input came from, used for error display purposes. Keyword Args: default: value to return in case the input is empty or unset. Returns: list[str]: validated list of patterns Raises: ValueError: if the input is unacceptable.
[ "Validates", "file", "search", "patterns", "from", "user", "configuration", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/hooks/aws_lambda.py#L240-L272
233,547
cloudtools/stacker
stacker/hooks/aws_lambda.py
_upload_function
def _upload_function(s3_conn, bucket, prefix, name, options, follow_symlinks, payload_acl): """Builds a Lambda payload from user configuration and uploads it to S3. Args: s3_conn (botocore.client.S3): S3 connection to use for operations. bucket (str): name of the bucket to upload to. prefix (str): S3 prefix to prepend to the constructed key name for the uploaded file name (str): desired name of the Lambda function. Will be used to construct a key name for the uploaded file. options (dict): configuration for how to build the payload. Consists of the following keys: * path: base path to retrieve files from (mandatory). If not absolute, it will be interpreted as relative to the stacker configuration file directory, then converted to an absolute path. See :func:`stacker.util.get_config_directory`. * include: file patterns to include in the payload (optional). * exclude: file patterns to exclude from the payload (optional). follow_symlinks (bool): If true, symlinks will be included in the resulting zip file payload_acl (str): The canned S3 object ACL to be applied to the uploaded payload Returns: troposphere.awslambda.Code: CloudFormation AWS Lambda Code object, pointing to the uploaded object in S3. Raises: ValueError: if any configuration is invalid. botocore.exceptions.ClientError: any error from boto3 is passed through. """ try: root = os.path.expanduser(options['path']) except KeyError as e: raise ValueError( "missing required property '{}' in function '{}'".format( e.args[0], name)) includes = _check_pattern_list(options.get('include'), 'include', default=['**']) excludes = _check_pattern_list(options.get('exclude'), 'exclude', default=[]) logger.debug('lambda: processing function %s', name) # os.path.join will ignore other parameters if the right-most one is an # absolute path, which is exactly what we want. if not os.path.isabs(root): root = os.path.abspath(os.path.join(get_config_directory(), root)) zip_contents, content_hash = _zip_from_file_patterns(root, includes, excludes, follow_symlinks) return _upload_code(s3_conn, bucket, prefix, name, zip_contents, content_hash, payload_acl)
python
def _upload_function(s3_conn, bucket, prefix, name, options, follow_symlinks, payload_acl): try: root = os.path.expanduser(options['path']) except KeyError as e: raise ValueError( "missing required property '{}' in function '{}'".format( e.args[0], name)) includes = _check_pattern_list(options.get('include'), 'include', default=['**']) excludes = _check_pattern_list(options.get('exclude'), 'exclude', default=[]) logger.debug('lambda: processing function %s', name) # os.path.join will ignore other parameters if the right-most one is an # absolute path, which is exactly what we want. if not os.path.isabs(root): root = os.path.abspath(os.path.join(get_config_directory(), root)) zip_contents, content_hash = _zip_from_file_patterns(root, includes, excludes, follow_symlinks) return _upload_code(s3_conn, bucket, prefix, name, zip_contents, content_hash, payload_acl)
[ "def", "_upload_function", "(", "s3_conn", ",", "bucket", ",", "prefix", ",", "name", ",", "options", ",", "follow_symlinks", ",", "payload_acl", ")", ":", "try", ":", "root", "=", "os", ".", "path", ".", "expanduser", "(", "options", "[", "'path'", "]",...
Builds a Lambda payload from user configuration and uploads it to S3. Args: s3_conn (botocore.client.S3): S3 connection to use for operations. bucket (str): name of the bucket to upload to. prefix (str): S3 prefix to prepend to the constructed key name for the uploaded file name (str): desired name of the Lambda function. Will be used to construct a key name for the uploaded file. options (dict): configuration for how to build the payload. Consists of the following keys: * path: base path to retrieve files from (mandatory). If not absolute, it will be interpreted as relative to the stacker configuration file directory, then converted to an absolute path. See :func:`stacker.util.get_config_directory`. * include: file patterns to include in the payload (optional). * exclude: file patterns to exclude from the payload (optional). follow_symlinks (bool): If true, symlinks will be included in the resulting zip file payload_acl (str): The canned S3 object ACL to be applied to the uploaded payload Returns: troposphere.awslambda.Code: CloudFormation AWS Lambda Code object, pointing to the uploaded object in S3. Raises: ValueError: if any configuration is invalid. botocore.exceptions.ClientError: any error from boto3 is passed through.
[ "Builds", "a", "Lambda", "payload", "from", "user", "configuration", "and", "uploads", "it", "to", "S3", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/hooks/aws_lambda.py#L275-L335
233,548
cloudtools/stacker
stacker/hooks/aws_lambda.py
select_bucket_region
def select_bucket_region(custom_bucket, hook_region, stacker_bucket_region, provider_region): """Returns the appropriate region to use when uploading functions. Select the appropriate region for the bucket where lambdas are uploaded in. Args: custom_bucket (str, None): The custom bucket name provided by the `bucket` kwarg of the aws_lambda hook, if provided. hook_region (str): The contents of the `bucket_region` argument to the hook. stacker_bucket_region (str): The contents of the `stacker_bucket_region` global setting. provider_region (str): The region being used by the provider. Returns: str: The appropriate region string. """ region = None if custom_bucket: region = hook_region else: region = stacker_bucket_region return region or provider_region
python
def select_bucket_region(custom_bucket, hook_region, stacker_bucket_region, provider_region): region = None if custom_bucket: region = hook_region else: region = stacker_bucket_region return region or provider_region
[ "def", "select_bucket_region", "(", "custom_bucket", ",", "hook_region", ",", "stacker_bucket_region", ",", "provider_region", ")", ":", "region", "=", "None", "if", "custom_bucket", ":", "region", "=", "hook_region", "else", ":", "region", "=", "stacker_bucket_regi...
Returns the appropriate region to use when uploading functions. Select the appropriate region for the bucket where lambdas are uploaded in. Args: custom_bucket (str, None): The custom bucket name provided by the `bucket` kwarg of the aws_lambda hook, if provided. hook_region (str): The contents of the `bucket_region` argument to the hook. stacker_bucket_region (str): The contents of the `stacker_bucket_region` global setting. provider_region (str): The region being used by the provider. Returns: str: The appropriate region string.
[ "Returns", "the", "appropriate", "region", "to", "use", "when", "uploading", "functions", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/hooks/aws_lambda.py#L338-L361
233,549
cloudtools/stacker
stacker/hooks/aws_lambda.py
upload_lambda_functions
def upload_lambda_functions(context, provider, **kwargs): """Builds Lambda payloads from user configuration and uploads them to S3. Constructs ZIP archives containing files matching specified patterns for each function, uploads the result to Amazon S3, then stores objects (of type :class:`troposphere.awslambda.Code`) in the context's hook data, ready to be referenced in blueprints. Configuration consists of some global options, and a dictionary of function specifications. In the specifications, each key indicating the name of the function (used for generating names for artifacts), and the value determines what files to include in the ZIP (see more details below). Payloads are uploaded to either a custom bucket or stackers default bucket, with the key containing it's checksum, to allow repeated uploads to be skipped in subsequent runs. The configuration settings are documented as keyword arguments below. Keyword Arguments: bucket (str, optional): Custom bucket to upload functions to. Omitting it will cause the default stacker bucket to be used. bucket_region (str, optional): The region in which the bucket should exist. If not given, the region will be either be that of the global `stacker_bucket_region` setting, or else the region in use by the provider. prefix (str, optional): S3 key prefix to prepend to the uploaded zip name. follow_symlinks (bool, optional): Will determine if symlinks should be followed and included with the zip artifact. Default: False payload_acl (str, optional): The canned S3 object ACL to be applied to the uploaded payload. Default: private functions (dict): Configurations of desired payloads to build. Keys correspond to function names, used to derive key names for the payload. Each value should itself be a dictionary, with the following data: * path (str): Base directory of the Lambda function payload content. If it not an absolute path, it will be considered relative to the directory containing the stacker configuration file in use. Files in this directory will be added to the payload ZIP, according to the include and exclude patterns. If not patterns are provided, all files in this directory (respecting default exclusions) will be used. Files are stored in the archive with path names relative to this directory. So, for example, all the files contained directly under this directory will be added to the root of the ZIP file. * include(str or list[str], optional): Pattern or list of patterns of files to include in the payload. If provided, only files that match these patterns will be included in the payload. Omitting it is equivalent to accepting all files that are not otherwise excluded. * exclude(str or list[str], optional): Pattern or list of patterns of files to exclude from the payload. If provided, any files that match will be ignored, regardless of whether they match an inclusion pattern. Commonly ignored files are already excluded by default, such as ``.git``, ``.svn``, ``__pycache__``, ``*.pyc``, ``.gitignore``, etc. Examples: .. Hook configuration. .. code-block:: yaml pre_build: - path: stacker.hooks.aws_lambda.upload_lambda_functions required: true enabled: true data_key: lambda args: bucket: custom-bucket follow_symlinks: true prefix: cloudformation-custom-resources/ payload_acl: authenticated-read functions: MyFunction: path: ./lambda_functions include: - '*.py' - '*.txt' exclude: - '*.pyc' - test/ .. Blueprint usage .. code-block:: python from troposphere.awslambda import Function from stacker.blueprints.base import Blueprint class LambdaBlueprint(Blueprint): def create_template(self): code = self.context.hook_data['lambda']['MyFunction'] self.template.add_resource( Function( 'MyFunction', Code=code, Handler='my_function.handler', Role='...', Runtime='python2.7' ) ) """ custom_bucket = kwargs.get('bucket') if not custom_bucket: bucket_name = context.bucket_name logger.info("lambda: using default bucket from stacker: %s", bucket_name) else: bucket_name = custom_bucket logger.info("lambda: using custom bucket: %s", bucket_name) custom_bucket_region = kwargs.get("bucket_region") if not custom_bucket and custom_bucket_region: raise ValueError("Cannot specify `bucket_region` without specifying " "`bucket`.") bucket_region = select_bucket_region( custom_bucket, custom_bucket_region, context.config.stacker_bucket_region, provider.region ) # Check if we should walk / follow symlinks follow_symlinks = kwargs.get('follow_symlinks', False) if not isinstance(follow_symlinks, bool): raise ValueError('follow_symlinks option must be a boolean') # Check for S3 object acl. Valid values from: # https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#canned-acl payload_acl = kwargs.get('payload_acl', 'private') # Always use the global client for s3 session = get_session(bucket_region) s3_client = session.client('s3') ensure_s3_bucket(s3_client, bucket_name, bucket_region) prefix = kwargs.get('prefix', '') results = {} for name, options in kwargs['functions'].items(): results[name] = _upload_function(s3_client, bucket_name, prefix, name, options, follow_symlinks, payload_acl) return results
python
def upload_lambda_functions(context, provider, **kwargs): custom_bucket = kwargs.get('bucket') if not custom_bucket: bucket_name = context.bucket_name logger.info("lambda: using default bucket from stacker: %s", bucket_name) else: bucket_name = custom_bucket logger.info("lambda: using custom bucket: %s", bucket_name) custom_bucket_region = kwargs.get("bucket_region") if not custom_bucket and custom_bucket_region: raise ValueError("Cannot specify `bucket_region` without specifying " "`bucket`.") bucket_region = select_bucket_region( custom_bucket, custom_bucket_region, context.config.stacker_bucket_region, provider.region ) # Check if we should walk / follow symlinks follow_symlinks = kwargs.get('follow_symlinks', False) if not isinstance(follow_symlinks, bool): raise ValueError('follow_symlinks option must be a boolean') # Check for S3 object acl. Valid values from: # https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#canned-acl payload_acl = kwargs.get('payload_acl', 'private') # Always use the global client for s3 session = get_session(bucket_region) s3_client = session.client('s3') ensure_s3_bucket(s3_client, bucket_name, bucket_region) prefix = kwargs.get('prefix', '') results = {} for name, options in kwargs['functions'].items(): results[name] = _upload_function(s3_client, bucket_name, prefix, name, options, follow_symlinks, payload_acl) return results
[ "def", "upload_lambda_functions", "(", "context", ",", "provider", ",", "*", "*", "kwargs", ")", ":", "custom_bucket", "=", "kwargs", ".", "get", "(", "'bucket'", ")", "if", "not", "custom_bucket", ":", "bucket_name", "=", "context", ".", "bucket_name", "log...
Builds Lambda payloads from user configuration and uploads them to S3. Constructs ZIP archives containing files matching specified patterns for each function, uploads the result to Amazon S3, then stores objects (of type :class:`troposphere.awslambda.Code`) in the context's hook data, ready to be referenced in blueprints. Configuration consists of some global options, and a dictionary of function specifications. In the specifications, each key indicating the name of the function (used for generating names for artifacts), and the value determines what files to include in the ZIP (see more details below). Payloads are uploaded to either a custom bucket or stackers default bucket, with the key containing it's checksum, to allow repeated uploads to be skipped in subsequent runs. The configuration settings are documented as keyword arguments below. Keyword Arguments: bucket (str, optional): Custom bucket to upload functions to. Omitting it will cause the default stacker bucket to be used. bucket_region (str, optional): The region in which the bucket should exist. If not given, the region will be either be that of the global `stacker_bucket_region` setting, or else the region in use by the provider. prefix (str, optional): S3 key prefix to prepend to the uploaded zip name. follow_symlinks (bool, optional): Will determine if symlinks should be followed and included with the zip artifact. Default: False payload_acl (str, optional): The canned S3 object ACL to be applied to the uploaded payload. Default: private functions (dict): Configurations of desired payloads to build. Keys correspond to function names, used to derive key names for the payload. Each value should itself be a dictionary, with the following data: * path (str): Base directory of the Lambda function payload content. If it not an absolute path, it will be considered relative to the directory containing the stacker configuration file in use. Files in this directory will be added to the payload ZIP, according to the include and exclude patterns. If not patterns are provided, all files in this directory (respecting default exclusions) will be used. Files are stored in the archive with path names relative to this directory. So, for example, all the files contained directly under this directory will be added to the root of the ZIP file. * include(str or list[str], optional): Pattern or list of patterns of files to include in the payload. If provided, only files that match these patterns will be included in the payload. Omitting it is equivalent to accepting all files that are not otherwise excluded. * exclude(str or list[str], optional): Pattern or list of patterns of files to exclude from the payload. If provided, any files that match will be ignored, regardless of whether they match an inclusion pattern. Commonly ignored files are already excluded by default, such as ``.git``, ``.svn``, ``__pycache__``, ``*.pyc``, ``.gitignore``, etc. Examples: .. Hook configuration. .. code-block:: yaml pre_build: - path: stacker.hooks.aws_lambda.upload_lambda_functions required: true enabled: true data_key: lambda args: bucket: custom-bucket follow_symlinks: true prefix: cloudformation-custom-resources/ payload_acl: authenticated-read functions: MyFunction: path: ./lambda_functions include: - '*.py' - '*.txt' exclude: - '*.pyc' - test/ .. Blueprint usage .. code-block:: python from troposphere.awslambda import Function from stacker.blueprints.base import Blueprint class LambdaBlueprint(Blueprint): def create_template(self): code = self.context.hook_data['lambda']['MyFunction'] self.template.add_resource( Function( 'MyFunction', Code=code, Handler='my_function.handler', Role='...', Runtime='python2.7' ) )
[ "Builds", "Lambda", "payloads", "from", "user", "configuration", "and", "uploads", "them", "to", "S3", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/hooks/aws_lambda.py#L364-L523
233,550
cloudtools/stacker
stacker/lookups/handlers/kms.py
KmsLookup.handle
def handle(cls, value, **kwargs): """Decrypt the specified value with a master key in KMS. kmssimple field types should be in the following format: [<region>@]<base64 encrypted value> Note: The region is optional, and defaults to the environment's `AWS_DEFAULT_REGION` if not specified. For example: # We use the aws cli to get the encrypted value for the string # "PASSWORD" using the master key called "myStackerKey" in # us-east-1 $ aws --region us-east-1 kms encrypt --key-id alias/myStackerKey \ --plaintext "PASSWORD" --output text --query CiphertextBlob CiD6bC8t2Y<...encrypted blob...> # In stacker we would reference the encrypted value like: conf_key: ${kms us-east-1@CiD6bC8t2Y<...encrypted blob...>} You can optionally store the encrypted value in a file, ie: kms_value.txt us-east-1@CiD6bC8t2Y<...encrypted blob...> and reference it within stacker (NOTE: the path should be relative to the stacker config file): conf_key: ${kms file://kms_value.txt} # Both of the above would resolve to conf_key: PASSWORD """ value = read_value_from_path(value) region = None if "@" in value: region, value = value.split("@", 1) kms = get_session(region).client('kms') # encode str value as an utf-8 bytestring for use with codecs.decode. value = value.encode('utf-8') # get raw but still encrypted value from base64 version. decoded = codecs.decode(value, 'base64') # decrypt and return the plain text raw value. return kms.decrypt(CiphertextBlob=decoded)["Plaintext"]
python
def handle(cls, value, **kwargs): value = read_value_from_path(value) region = None if "@" in value: region, value = value.split("@", 1) kms = get_session(region).client('kms') # encode str value as an utf-8 bytestring for use with codecs.decode. value = value.encode('utf-8') # get raw but still encrypted value from base64 version. decoded = codecs.decode(value, 'base64') # decrypt and return the plain text raw value. return kms.decrypt(CiphertextBlob=decoded)["Plaintext"]
[ "def", "handle", "(", "cls", ",", "value", ",", "*", "*", "kwargs", ")", ":", "value", "=", "read_value_from_path", "(", "value", ")", "region", "=", "None", "if", "\"@\"", "in", "value", ":", "region", ",", "value", "=", "value", ".", "split", "(", ...
Decrypt the specified value with a master key in KMS. kmssimple field types should be in the following format: [<region>@]<base64 encrypted value> Note: The region is optional, and defaults to the environment's `AWS_DEFAULT_REGION` if not specified. For example: # We use the aws cli to get the encrypted value for the string # "PASSWORD" using the master key called "myStackerKey" in # us-east-1 $ aws --region us-east-1 kms encrypt --key-id alias/myStackerKey \ --plaintext "PASSWORD" --output text --query CiphertextBlob CiD6bC8t2Y<...encrypted blob...> # In stacker we would reference the encrypted value like: conf_key: ${kms us-east-1@CiD6bC8t2Y<...encrypted blob...>} You can optionally store the encrypted value in a file, ie: kms_value.txt us-east-1@CiD6bC8t2Y<...encrypted blob...> and reference it within stacker (NOTE: the path should be relative to the stacker config file): conf_key: ${kms file://kms_value.txt} # Both of the above would resolve to conf_key: PASSWORD
[ "Decrypt", "the", "specified", "value", "with", "a", "master", "key", "in", "KMS", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/lookups/handlers/kms.py#L15-L67
233,551
cloudtools/stacker
stacker/actions/diff.py
diff_dictionaries
def diff_dictionaries(old_dict, new_dict): """Diffs two single dimension dictionaries Returns the number of changes and an unordered list expressing the common entries and changes. Args: old_dict(dict): old dictionary new_dict(dict): new dictionary Returns: list() int: number of changed records list: [DictValue] """ old_set = set(old_dict) new_set = set(new_dict) added_set = new_set - old_set removed_set = old_set - new_set common_set = old_set & new_set changes = 0 output = [] for key in added_set: changes += 1 output.append(DictValue(key, None, new_dict[key])) for key in removed_set: changes += 1 output.append(DictValue(key, old_dict[key], None)) for key in common_set: output.append(DictValue(key, old_dict[key], new_dict[key])) if str(old_dict[key]) != str(new_dict[key]): changes += 1 output.sort(key=attrgetter("key")) return [changes, output]
python
def diff_dictionaries(old_dict, new_dict): old_set = set(old_dict) new_set = set(new_dict) added_set = new_set - old_set removed_set = old_set - new_set common_set = old_set & new_set changes = 0 output = [] for key in added_set: changes += 1 output.append(DictValue(key, None, new_dict[key])) for key in removed_set: changes += 1 output.append(DictValue(key, old_dict[key], None)) for key in common_set: output.append(DictValue(key, old_dict[key], new_dict[key])) if str(old_dict[key]) != str(new_dict[key]): changes += 1 output.sort(key=attrgetter("key")) return [changes, output]
[ "def", "diff_dictionaries", "(", "old_dict", ",", "new_dict", ")", ":", "old_set", "=", "set", "(", "old_dict", ")", "new_set", "=", "set", "(", "new_dict", ")", "added_set", "=", "new_set", "-", "old_set", "removed_set", "=", "old_set", "-", "new_set", "c...
Diffs two single dimension dictionaries Returns the number of changes and an unordered list expressing the common entries and changes. Args: old_dict(dict): old dictionary new_dict(dict): new dictionary Returns: list() int: number of changed records list: [DictValue]
[ "Diffs", "two", "single", "dimension", "dictionaries" ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/diff.py#L73-L111
233,552
cloudtools/stacker
stacker/actions/diff.py
diff_parameters
def diff_parameters(old_params, new_params): """Compares the old vs. new parameters and returns a "diff" If there are no changes, we return an empty list. Args: old_params(dict): old paramters new_params(dict): new parameters Returns: list: A list of differences """ [changes, diff] = diff_dictionaries(old_params, new_params) if changes == 0: return [] return diff
python
def diff_parameters(old_params, new_params): [changes, diff] = diff_dictionaries(old_params, new_params) if changes == 0: return [] return diff
[ "def", "diff_parameters", "(", "old_params", ",", "new_params", ")", ":", "[", "changes", ",", "diff", "]", "=", "diff_dictionaries", "(", "old_params", ",", "new_params", ")", "if", "changes", "==", "0", ":", "return", "[", "]", "return", "diff" ]
Compares the old vs. new parameters and returns a "diff" If there are no changes, we return an empty list. Args: old_params(dict): old paramters new_params(dict): new parameters Returns: list: A list of differences
[ "Compares", "the", "old", "vs", ".", "new", "parameters", "and", "returns", "a", "diff" ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/diff.py#L133-L148
233,553
cloudtools/stacker
stacker/actions/diff.py
normalize_json
def normalize_json(template): """Normalize our template for diffing. Args: template(str): string representing the template Returns: list: json representation of the parameters """ obj = parse_cloudformation_template(template) json_str = json.dumps( obj, sort_keys=True, indent=4, default=str, separators=(',', ': '), ) result = [] lines = json_str.split("\n") for line in lines: result.append(line + "\n") return result
python
def normalize_json(template): obj = parse_cloudformation_template(template) json_str = json.dumps( obj, sort_keys=True, indent=4, default=str, separators=(',', ': '), ) result = [] lines = json_str.split("\n") for line in lines: result.append(line + "\n") return result
[ "def", "normalize_json", "(", "template", ")", ":", "obj", "=", "parse_cloudformation_template", "(", "template", ")", "json_str", "=", "json", ".", "dumps", "(", "obj", ",", "sort_keys", "=", "True", ",", "indent", "=", "4", ",", "default", "=", "str", ...
Normalize our template for diffing. Args: template(str): string representing the template Returns: list: json representation of the parameters
[ "Normalize", "our", "template", "for", "diffing", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/diff.py#L151-L168
233,554
cloudtools/stacker
stacker/actions/diff.py
DictValue.changes
def changes(self): """Returns a list of changes to represent the diff between old and new value. Returns: list: [string] representation of the change (if any) between old and new value """ output = [] if self.status() is self.UNMODIFIED: output = [self.formatter % (' ', self.key, self.old_value)] elif self.status() is self.ADDED: output.append(self.formatter % ('+', self.key, self.new_value)) elif self.status() is self.REMOVED: output.append(self.formatter % ('-', self.key, self.old_value)) elif self.status() is self.MODIFIED: output.append(self.formatter % ('-', self.key, self.old_value)) output.append(self.formatter % ('+', self.key, self.new_value)) return output
python
def changes(self): output = [] if self.status() is self.UNMODIFIED: output = [self.formatter % (' ', self.key, self.old_value)] elif self.status() is self.ADDED: output.append(self.formatter % ('+', self.key, self.new_value)) elif self.status() is self.REMOVED: output.append(self.formatter % ('-', self.key, self.old_value)) elif self.status() is self.MODIFIED: output.append(self.formatter % ('-', self.key, self.old_value)) output.append(self.formatter % ('+', self.key, self.new_value)) return output
[ "def", "changes", "(", "self", ")", ":", "output", "=", "[", "]", "if", "self", ".", "status", "(", ")", "is", "self", ".", "UNMODIFIED", ":", "output", "=", "[", "self", ".", "formatter", "%", "(", "' '", ",", "self", ".", "key", ",", "self", ...
Returns a list of changes to represent the diff between old and new value. Returns: list: [string] representation of the change (if any) between old and new value
[ "Returns", "a", "list", "of", "changes", "to", "represent", "the", "diff", "between", "old", "and", "new", "value", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/diff.py#L42-L60
233,555
cloudtools/stacker
stacker/actions/diff.py
Action._diff_stack
def _diff_stack(self, stack, **kwargs): """Handles the diffing a stack in CloudFormation vs our config""" if self.cancel.wait(0): return INTERRUPTED if not build.should_submit(stack): return NotSubmittedStatus() if not build.should_update(stack): return NotUpdatedStatus() provider = self.build_provider(stack) provider_stack = provider.get_stack(stack.fqn) # get the current stack template & params from AWS try: [old_template, old_params] = provider.get_stack_info( provider_stack) except exceptions.StackDoesNotExist: old_template = None old_params = {} stack.resolve(self.context, provider) # generate our own template & params parameters = self.build_parameters(stack) new_params = dict() for p in parameters: new_params[p['ParameterKey']] = p['ParameterValue'] new_template = stack.blueprint.rendered new_stack = normalize_json(new_template) output = ["============== Stack: %s ==============" % (stack.name,)] # If this is a completely new template dump our params & stack if not old_template: output.extend(self._build_new_template(new_stack, parameters)) else: # Diff our old & new stack/parameters old_template = parse_cloudformation_template(old_template) if isinstance(old_template, str): # YAML templates returned from CFN need parsing again # "AWSTemplateFormatVersion: \"2010-09-09\"\nParam..." # -> # AWSTemplateFormatVersion: "2010-09-09" old_template = parse_cloudformation_template(old_template) old_stack = normalize_json( json.dumps(old_template, sort_keys=True, indent=4, default=str) ) output.extend(build_stack_changes(stack.name, new_stack, old_stack, new_params, old_params)) ui.info('\n' + '\n'.join(output)) stack.set_outputs( provider.get_output_dict(provider_stack)) return COMPLETE
python
def _diff_stack(self, stack, **kwargs): if self.cancel.wait(0): return INTERRUPTED if not build.should_submit(stack): return NotSubmittedStatus() if not build.should_update(stack): return NotUpdatedStatus() provider = self.build_provider(stack) provider_stack = provider.get_stack(stack.fqn) # get the current stack template & params from AWS try: [old_template, old_params] = provider.get_stack_info( provider_stack) except exceptions.StackDoesNotExist: old_template = None old_params = {} stack.resolve(self.context, provider) # generate our own template & params parameters = self.build_parameters(stack) new_params = dict() for p in parameters: new_params[p['ParameterKey']] = p['ParameterValue'] new_template = stack.blueprint.rendered new_stack = normalize_json(new_template) output = ["============== Stack: %s ==============" % (stack.name,)] # If this is a completely new template dump our params & stack if not old_template: output.extend(self._build_new_template(new_stack, parameters)) else: # Diff our old & new stack/parameters old_template = parse_cloudformation_template(old_template) if isinstance(old_template, str): # YAML templates returned from CFN need parsing again # "AWSTemplateFormatVersion: \"2010-09-09\"\nParam..." # -> # AWSTemplateFormatVersion: "2010-09-09" old_template = parse_cloudformation_template(old_template) old_stack = normalize_json( json.dumps(old_template, sort_keys=True, indent=4, default=str) ) output.extend(build_stack_changes(stack.name, new_stack, old_stack, new_params, old_params)) ui.info('\n' + '\n'.join(output)) stack.set_outputs( provider.get_output_dict(provider_stack)) return COMPLETE
[ "def", "_diff_stack", "(", "self", ",", "stack", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "cancel", ".", "wait", "(", "0", ")", ":", "return", "INTERRUPTED", "if", "not", "build", ".", "should_submit", "(", "stack", ")", ":", "return", ...
Handles the diffing a stack in CloudFormation vs our config
[ "Handles", "the", "diffing", "a", "stack", "in", "CloudFormation", "vs", "our", "config" ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/diff.py#L220-L278
233,556
cloudtools/stacker
stacker/actions/graph.py
each_step
def each_step(graph): """Returns an iterator that yields each step and it's direct dependencies. """ steps = graph.topological_sort() steps.reverse() for step in steps: deps = graph.downstream(step.name) yield (step, deps)
python
def each_step(graph): steps = graph.topological_sort() steps.reverse() for step in steps: deps = graph.downstream(step.name) yield (step, deps)
[ "def", "each_step", "(", "graph", ")", ":", "steps", "=", "graph", ".", "topological_sort", "(", ")", "steps", ".", "reverse", "(", ")", "for", "step", "in", "steps", ":", "deps", "=", "graph", ".", "downstream", "(", "step", ".", "name", ")", "yield...
Returns an iterator that yields each step and it's direct dependencies.
[ "Returns", "an", "iterator", "that", "yields", "each", "step", "and", "it", "s", "direct", "dependencies", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/graph.py#L14-L24
233,557
cloudtools/stacker
stacker/actions/graph.py
dot_format
def dot_format(out, graph, name="digraph"): """Outputs the graph using the graphviz "dot" format.""" out.write("digraph %s {\n" % name) for step, deps in each_step(graph): for dep in deps: out.write(" \"%s\" -> \"%s\";\n" % (step, dep)) out.write("}\n")
python
def dot_format(out, graph, name="digraph"): out.write("digraph %s {\n" % name) for step, deps in each_step(graph): for dep in deps: out.write(" \"%s\" -> \"%s\";\n" % (step, dep)) out.write("}\n")
[ "def", "dot_format", "(", "out", ",", "graph", ",", "name", "=", "\"digraph\"", ")", ":", "out", ".", "write", "(", "\"digraph %s {\\n\"", "%", "name", ")", "for", "step", ",", "deps", "in", "each_step", "(", "graph", ")", ":", "for", "dep", "in", "d...
Outputs the graph using the graphviz "dot" format.
[ "Outputs", "the", "graph", "using", "the", "graphviz", "dot", "format", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/graph.py#L27-L35
233,558
cloudtools/stacker
stacker/actions/graph.py
json_format
def json_format(out, graph): """Outputs the graph in a machine readable JSON format.""" steps = {} for step, deps in each_step(graph): steps[step.name] = {} steps[step.name]["deps"] = [dep.name for dep in deps] json.dump({"steps": steps}, out, indent=4) out.write("\n")
python
def json_format(out, graph): steps = {} for step, deps in each_step(graph): steps[step.name] = {} steps[step.name]["deps"] = [dep.name for dep in deps] json.dump({"steps": steps}, out, indent=4) out.write("\n")
[ "def", "json_format", "(", "out", ",", "graph", ")", ":", "steps", "=", "{", "}", "for", "step", ",", "deps", "in", "each_step", "(", "graph", ")", ":", "steps", "[", "step", ".", "name", "]", "=", "{", "}", "steps", "[", "step", ".", "name", "...
Outputs the graph in a machine readable JSON format.
[ "Outputs", "the", "graph", "in", "a", "machine", "readable", "JSON", "format", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/graph.py#L38-L46
233,559
cloudtools/stacker
stacker/actions/graph.py
Action.run
def run(self, format=None, reduce=False, *args, **kwargs): """Generates the underlying graph and prints it. """ plan = self._generate_plan() if reduce: # This will performa a transitive reduction on the underlying # graph, producing less edges. Mostly useful for the "dot" format, # when converting to PNG, so it creates a prettier/cleaner # dependency graph. plan.graph.transitive_reduction() fn = FORMATTERS[format] fn(sys.stdout, plan.graph) sys.stdout.flush()
python
def run(self, format=None, reduce=False, *args, **kwargs): plan = self._generate_plan() if reduce: # This will performa a transitive reduction on the underlying # graph, producing less edges. Mostly useful for the "dot" format, # when converting to PNG, so it creates a prettier/cleaner # dependency graph. plan.graph.transitive_reduction() fn = FORMATTERS[format] fn(sys.stdout, plan.graph) sys.stdout.flush()
[ "def", "run", "(", "self", ",", "format", "=", "None", ",", "reduce", "=", "False", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "plan", "=", "self", ".", "_generate_plan", "(", ")", "if", "reduce", ":", "# This will performa a transitive reducti...
Generates the underlying graph and prints it.
[ "Generates", "the", "underlying", "graph", "and", "prints", "it", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/graph.py#L63-L77
233,560
cloudtools/stacker
stacker/hooks/iam.py
get_cert_contents
def get_cert_contents(kwargs): """Builds parameters with server cert file contents. Args: kwargs(dict): The keyword args passed to ensure_server_cert_exists, optionally containing the paths to the cert, key and chain files. Returns: dict: A dictionary containing the appropriate parameters to supply to upload_server_certificate. An empty dictionary if there is a problem. """ paths = { "certificate": kwargs.get("path_to_certificate"), "private_key": kwargs.get("path_to_private_key"), "chain": kwargs.get("path_to_chain"), } for key, value in paths.items(): if value is not None: continue path = input("Path to %s (skip): " % (key,)) if path == "skip" or not path.strip(): continue paths[key] = path parameters = { "ServerCertificateName": kwargs.get("cert_name"), } for key, path in paths.items(): if not path: continue # Allow passing of file like object for tests try: contents = path.read() except AttributeError: with open(utils.full_path(path)) as read_file: contents = read_file.read() if key == "certificate": parameters["CertificateBody"] = contents elif key == "private_key": parameters["PrivateKey"] = contents elif key == "chain": parameters["CertificateChain"] = contents return parameters
python
def get_cert_contents(kwargs): paths = { "certificate": kwargs.get("path_to_certificate"), "private_key": kwargs.get("path_to_private_key"), "chain": kwargs.get("path_to_chain"), } for key, value in paths.items(): if value is not None: continue path = input("Path to %s (skip): " % (key,)) if path == "skip" or not path.strip(): continue paths[key] = path parameters = { "ServerCertificateName": kwargs.get("cert_name"), } for key, path in paths.items(): if not path: continue # Allow passing of file like object for tests try: contents = path.read() except AttributeError: with open(utils.full_path(path)) as read_file: contents = read_file.read() if key == "certificate": parameters["CertificateBody"] = contents elif key == "private_key": parameters["PrivateKey"] = contents elif key == "chain": parameters["CertificateChain"] = contents return parameters
[ "def", "get_cert_contents", "(", "kwargs", ")", ":", "paths", "=", "{", "\"certificate\"", ":", "kwargs", ".", "get", "(", "\"path_to_certificate\"", ")", ",", "\"private_key\"", ":", "kwargs", ".", "get", "(", "\"path_to_private_key\"", ")", ",", "\"chain\"", ...
Builds parameters with server cert file contents. Args: kwargs(dict): The keyword args passed to ensure_server_cert_exists, optionally containing the paths to the cert, key and chain files. Returns: dict: A dictionary containing the appropriate parameters to supply to upload_server_certificate. An empty dictionary if there is a problem.
[ "Builds", "parameters", "with", "server", "cert", "file", "contents", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/hooks/iam.py#L74-L124
233,561
cloudtools/stacker
stacker/blueprints/raw.py
get_template_path
def get_template_path(filename): """Find raw template in working directory or in sys.path. template_path from config may refer to templates colocated with the Stacker config, or files in remote package_sources. Here, we emulate python module loading to find the path to the template. Args: filename (str): Template filename. Returns: Optional[str]: Path to file, or None if no file found """ if os.path.isfile(filename): return os.path.abspath(filename) for i in sys.path: if os.path.isfile(os.path.join(i, filename)): return os.path.abspath(os.path.join(i, filename)) return None
python
def get_template_path(filename): if os.path.isfile(filename): return os.path.abspath(filename) for i in sys.path: if os.path.isfile(os.path.join(i, filename)): return os.path.abspath(os.path.join(i, filename)) return None
[ "def", "get_template_path", "(", "filename", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "return", "os", ".", "path", ".", "abspath", "(", "filename", ")", "for", "i", "in", "sys", ".", "path", ":", "if", "os", ".",...
Find raw template in working directory or in sys.path. template_path from config may refer to templates colocated with the Stacker config, or files in remote package_sources. Here, we emulate python module loading to find the path to the template. Args: filename (str): Template filename. Returns: Optional[str]: Path to file, or None if no file found
[ "Find", "raw", "template", "in", "working", "directory", "or", "in", "sys", ".", "path", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/blueprints/raw.py#L18-L38
233,562
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): 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
233,563
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): 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
233,564
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): 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
233,565
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): # 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
233,566
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): 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
233,567
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): 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
233,568
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): 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
233,569
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): 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
233,570
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): 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
233,571
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): 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
233,572
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): 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
233,573
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): 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
233,574
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): 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
233,575
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): 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
233,576
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): 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
233,577
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_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
233,578
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): 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
233,579
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): 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
233,580
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): 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
233,581
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): 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
233,582
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): 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
233,583
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): 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
233,584
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): 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
233,585
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): 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
233,586
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): 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
233,587
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): 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
233,588
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): 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
233,589
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): 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
233,590
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): 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
233,591
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): 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
233,592
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): 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
233,593
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): 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
233,594
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): 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
233,595
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): 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
233,596
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): 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
233,597
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): 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
233,598
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): 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
233,599
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): 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