repo
stringclasses
856 values
pull_number
int64
3
127k
instance_id
stringlengths
12
58
issue_numbers
sequencelengths
1
5
base_commit
stringlengths
40
40
patch
stringlengths
67
1.54M
test_patch
stringlengths
0
107M
problem_statement
stringlengths
3
307k
hints_text
stringlengths
0
908k
created_at
timestamp[s]
DistrictDataLabs/yellowbrick
1,171
DistrictDataLabs__yellowbrick-1171
[ "1163" ]
77e1e16b02772436a3f1ec89b9e719bbee0e6d00
diff --git a/yellowbrick/target/feature_correlation.py b/yellowbrick/target/feature_correlation.py --- a/yellowbrick/target/feature_correlation.py +++ b/yellowbrick/target/feature_correlation.py @@ -123,7 +123,7 @@ def __init__( color=None, **kwargs ): - super(FeatureCorrelation, self).__init__(ax=None, **kwargs) + super(FeatureCorrelation, self).__init__(ax, **kwargs) self.correlation_labels = CORRELATION_LABELS self.correlation_methods = CORRELATION_METHODS
ax param ignored in feature_correlation quick method **Describe the bug** When using matplotlib subplots create 2 plots of feature correlations side by side, the ax parameter seems to be ignored and two images are created. ![image1](https://user-images.githubusercontent.com/3305726/109315893-cc35c400-7829-11eb-8453-de098ae7f375.png) ![image2](https://user-images.githubusercontent.com/3305726/109315930-d3f56880-7829-11eb-9f3f-75b4977dcac4.png) **To Reproduce** ```python import numpy as np from sklearn import datasets import matplotlib.pyplot as plt from yellowbrick.target.feature_correlation import feature_correlation #Load the diabetes dataset data = datasets.load_iris() X, y = data['data'], data['target'] features = np.array(data['feature_names']) _, axes = plt.subplots(ncols=2, figsize=(18, 6)) feature_correlation(X, y, labels=features, method='pearson', ax=axes[0]) feature_correlation(X, y, labels=features, method='mutual_info-classification', ax=axes[1]) plt.tight_layout() ``` **Expected behavior** The expected behaviour would be the plots side by side in a single image. **Desktop (please complete the following information):** - OS: macOS - Python Version: Python 3.7.10 (Google Colab) - Yellowbrick Version: 1.3.post1 **Additional context** I can confirm it happens also locally with `Yellowbrick 1.3.post1` running using command line and using jupyter notebooks
2021-04-01T19:43:31
DistrictDataLabs/yellowbrick
1,172
DistrictDataLabs__yellowbrick-1172
[ "1159", "1159" ]
4973ce4357e9004a5176066979a8351d5b781620
diff --git a/yellowbrick/cluster/elbow.py b/yellowbrick/cluster/elbow.py --- a/yellowbrick/cluster/elbow.py +++ b/yellowbrick/cluster/elbow.py @@ -43,6 +43,16 @@ __all__ = ["KElbowVisualizer", "KElbow", "distortion_score", "kelbow_visualizer"] +# Custom colors; note that LINE_COLOR is imported above +TIMING_COLOR = 'C1' # Color of timing axis, tick, label, and line +METRIC_COLOR = 'C0' # Color of metric axis, tick, label, and line + +# Keys for the color dictionary +CTIMING = "timing" +CMETRIC = "metric" +CVLINE = "vline" + + ########################################################################## ## Metrics ########################################################################## @@ -259,6 +269,13 @@ def __init__( self.timings = timings self.locate_elbow = locate_elbow + # Set the values of the colors + self.colors = { + CTIMING: TIMING_COLOR, + CMETRIC: METRIC_COLOR, + CVLINE: LINE_COLOR, + } + # Convert K into a tuple argument if an integer if isinstance(k, int): self.k_values_ = list(range(2, k + 1)) @@ -282,6 +299,7 @@ def __init__( # Holds the values of the silhoutte scores self.k_scores_ = None + # Set Default Elbow Value self.elbow_value_ = None @@ -356,13 +374,13 @@ def draw(self): Draw the elbow curve for the specified scores and values of K. """ # Plot the silhouette score against k - self.ax.plot(self.k_values_, self.k_scores_, marker="D") + self.ax.plot(self.k_values_, self.k_scores_, marker="D", c=self.metric_color) if self.locate_elbow is True and self.elbow_value_ is not None: elbow_label = "elbow at $k={}$, $score={:0.3f}$".format( self.elbow_value_, self.elbow_score_ ) self.ax.axvline( - self.elbow_value_, c=LINE_COLOR, linestyle="--", label=elbow_label + self.elbow_value_, c=self.vline_color, linestyle="--", label=elbow_label ) # If we're going to plot the timings, create a twinx axis @@ -372,7 +390,7 @@ def draw(self): self.k_values_, self.k_timers_, label="fit time", - c="g", + c=self.timing_color, marker="o", linestyle="--", alpha=0.75, @@ -403,9 +421,33 @@ def finalize(self): # Set the second y axis labels if self.timings: self.axes[1].grid(False) - self.axes[1].set_ylabel("fit time (seconds)", color="g") - self.axes[1].tick_params("y", colors="g") - + self.axes[1].set_ylabel("fit time (seconds)", color=self.timing_color) + self.axes[1].tick_params("y", colors=self.timing_color) + + + @property + def metric_color(self): + return self.colors[CMETRIC] + + @metric_color.setter + def metric_color(self, val): + self.colors[CMETRIC] = val + + @property + def timing_color(self): + return self.colors[CTIMING] + + @timing_color.setter + def timing_color(self, val): + self.colors[CTIMING] = val + + @property + def vline_color(self): + return self.colors[CVLINE] + + @vline_color.setter + def vline_color(self, val): + self.colors[CVLINE] = val # alias KElbow = KElbowVisualizer
diff --git a/tests/baseline_images/test_cluster/test_elbow/test_integrated_kmeans_elbow.png b/tests/baseline_images/test_cluster/test_elbow/test_integrated_kmeans_elbow.png Binary files a/tests/baseline_images/test_cluster/test_elbow/test_integrated_kmeans_elbow.png and b/tests/baseline_images/test_cluster/test_elbow/test_integrated_kmeans_elbow.png differ diff --git a/tests/baseline_images/test_cluster/test_elbow/test_integrated_mini_batch_kmeans_elbow.png b/tests/baseline_images/test_cluster/test_elbow/test_integrated_mini_batch_kmeans_elbow.png Binary files a/tests/baseline_images/test_cluster/test_elbow/test_integrated_mini_batch_kmeans_elbow.png and b/tests/baseline_images/test_cluster/test_elbow/test_integrated_mini_batch_kmeans_elbow.png differ diff --git a/tests/baseline_images/test_cluster/test_elbow/test_quick_method.png b/tests/baseline_images/test_cluster/test_elbow/test_quick_method.png Binary files a/tests/baseline_images/test_cluster/test_elbow/test_quick_method.png and b/tests/baseline_images/test_cluster/test_elbow/test_quick_method.png differ diff --git a/tests/baseline_images/test_cluster/test_elbow/test_set_colors_manually.png b/tests/baseline_images/test_cluster/test_elbow/test_set_colors_manually.png new file mode 100644 Binary files /dev/null and b/tests/baseline_images/test_cluster/test_elbow/test_set_colors_manually.png differ diff --git a/tests/baseline_images/test_cluster/test_elbow/test_timings.png b/tests/baseline_images/test_cluster/test_elbow/test_timings.png Binary files a/tests/baseline_images/test_cluster/test_elbow/test_timings.png and b/tests/baseline_images/test_cluster/test_elbow/test_timings.png differ diff --git a/tests/test_cluster/test_elbow.py b/tests/test_cluster/test_elbow.py --- a/tests/test_cluster/test_elbow.py +++ b/tests/test_cluster/test_elbow.py @@ -426,3 +426,28 @@ def test_quick_method_params(self): model, X, sample_weight=np.ones(X.shape[0]), title=custom_title ) assert oz.title == custom_title + + @pytest.mark.xfail(sys.platform == "win32", reason="images not close on windows") + def test_set_colors_manually(self): + """ + Test the silhouette metric of the k-elbow visualizer + """ + oz = KElbowVisualizer( + KMeans(random_state=0), k=5, + ) + + oz.metric_color = "r" + oz.timing_color = "y" + oz.vline_color = "c" + + # Create artificial "fit" data for testing purposes + oz.k_values_ = [1, 2, 3, 4, 5, 6, 7, 8] + oz.k_timers_ = [6.2, 8.3, 10.1, 15.8, 21.2, 27.9, 38.2, 44.9] + oz.k_scores_ = [.8, .7, .55, .48, .40, .38, .35, .30] + oz.elbow_value_ = 5 + oz.elbow_score_ = 0.40 + + # Execute drawing + oz.draw() + oz.finalize() + self.assert_images_similar(oz, tol=3.2) \ No newline at end of file
Change elbow plot fit time to use color palette instead of hardcoded "g" https://github.com/DistrictDataLabs/yellowbrick/blob/2d4e23648b33ad42e2e95b559e35ca6de2db5bb6/yellowbrick/cluster/elbow.py#L406 Would be nice if the fit time line, as well as the elblow line - (black/dark-grey? not sure where/if this is hardcoded) could be changed to use the global color palette instead of hardcoded values. I'd like to be able to use the matplotlib palette 'dark_background', which makes it impossible to see the black elbow line: <img width="656" alt="yellowbrick_elbow_black" src="https://user-images.githubusercontent.com/29611875/108923485-c2278180-75ed-11eb-9c6f-90b052c69f43.png"> Thanks! Change elbow plot fit time to use color palette instead of hardcoded "g" https://github.com/DistrictDataLabs/yellowbrick/blob/2d4e23648b33ad42e2e95b559e35ca6de2db5bb6/yellowbrick/cluster/elbow.py#L406 Would be nice if the fit time line, as well as the elblow line - (black/dark-grey? not sure where/if this is hardcoded) could be changed to use the global color palette instead of hardcoded values. I'd like to be able to use the matplotlib palette 'dark_background', which makes it impossible to see the black elbow line: <img width="656" alt="yellowbrick_elbow_black" src="https://user-images.githubusercontent.com/29611875/108923485-c2278180-75ed-11eb-9c6f-90b052c69f43.png"> Thanks!
2021-04-01T23:58:34
DistrictDataLabs/yellowbrick
1,173
DistrictDataLabs__yellowbrick-1173
[ "1160", "1167" ]
1057d645c5086ec4ce68e4794786b8d81d147693
diff --git a/yellowbrick/classifier/rocauc.py b/yellowbrick/classifier/rocauc.py --- a/yellowbrick/classifier/rocauc.py +++ b/yellowbrick/classifier/rocauc.py @@ -208,7 +208,10 @@ def __init__( # Set the visual parameters for ROCAUC # NOTE: the binary flag breaks our API since it's really just a meta parameter # for micro, macro, and per_class. We knew this going in, but did it anyway. - if binary: + + self.binary = binary + + if self.binary: self.micro = False self.macro = False self.per_class = False diff --git a/yellowbrick/features/pca.py b/yellowbrick/features/pca.py --- a/yellowbrick/features/pca.py +++ b/yellowbrick/features/pca.py @@ -200,6 +200,16 @@ def __init__( raise YellowbrickValueError( "heatmap and colorbar are not compatible with 3d projections" ) + self._random_state = random_state + + @property + def random_state(self): + return self._random_state + + @random_state.setter + def random_state(self, val): + self._random_state = val + self.pca_transformer.set_params(pca__random_state=val) @property def uax(self):
pca_decomposition returns sometimes an exception **Describe the bug** Some time pca_decomposition finishes with an exception (AttributeError: 'PCA' object has no attribute 'random_state'). More precisely, the picture is well generated, but there is an exception just after (cf. traceback below). **To Reproduce** ```python from yellowbrick.datasets import load_credit from yellowbrick.features import pca_decomposition # Specify the features of interest and the target X, y = load_credit() classes = ['account in default', 'current with bills'] # Create, fit, and show the visualizer pca_decomposition( X, y, scale=True, classes=classes ) ``` **Expected behavior** The picture is generated without exception **Traceback** ``` ---------------------------------------------------------------------- AttributeError Traceback (most recent call last) ~/.local/lib/python3.8/site-packages/IPython/core/formatters.py in __call__(self, obj, include, exclude) 968 969 if method is not None: --> 970 return method(include=include, exclude=exclude) 971 return None 972 else: ~/.local/lib/python3.8/site-packages/sklearn/base.py in _repr_mimebundle_(self, **kwargs) 462 def _repr_mimebundle_(self, **kwargs): 463 """Mime bundle used by jupyter kernels to display estimator""" --> 464 output = {"text/plain": repr(self)} 465 if get_config()["display"] == 'diagram': 466 output["text/html"] = estimator_html_repr(self) ~/.local/lib/python3.8/site-packages/sklearn/base.py in __repr__(self, N_CHAR_MAX) 258 n_max_elements_to_show=N_MAX_ELEMENTS_TO_SHOW) 259 --> 260 repr_ = pp.pformat(self) 261 262 # Use bruteforce ellipsis when there are a lot of non-blank characters ~/anaconda3/lib/python3.8/pprint.py in pformat(self, object) 151 def pformat(self, object): 152 sio = _StringIO() --> 153 self._format(object, sio, 0, 0, {}, 0) 154 return sio.getvalue() 155 ~/anaconda3/lib/python3.8/pprint.py in _format(self, object, stream, indent, allowance, context, level) 168 self._readable = False 169 return --> 170 rep = self._repr(object, context, level) 171 max_width = self._width - indent - allowance 172 if len(rep) > max_width: ~/anaconda3/lib/python3.8/pprint.py in _repr(self, object, context, level) 402 403 def _repr(self, object, context, level): --> 404 repr, readable, recursive = self.format(object, context.copy(), 405 self._depth, level) 406 if not readable: ~/.local/lib/python3.8/site-packages/sklearn/utils/_pprint.py in format(self, object, context, maxlevels, level) 178 179 def format(self, object, context, maxlevels, level): --> 180 return _safe_repr(object, context, maxlevels, level, 181 changed_only=self._changed_only) 182 ~/.local/lib/python3.8/site-packages/sklearn/utils/_pprint.py in _safe_repr(object, context, maxlevels, level, changed_only) 423 recursive = False 424 if changed_only: --> 425 params = _changed_params(object) 426 else: 427 params = object.get_params(deep=False) ~/.local/lib/python3.8/site-packages/sklearn/utils/_pprint.py in _changed_params(estimator) 89 estimator with non-default values.""" 90 ---> 91 params = estimator.get_params(deep=False) 92 init_func = getattr(estimator.__init__, 'deprecated_original', 93 estimator.__init__) ~/.local/lib/python3.8/site-packages/sklearn/base.py in get_params(self, deep) 193 out = dict() 194 for key in self._get_param_names(): --> 195 value = getattr(self, key) 196 if deep and hasattr(value, 'get_params'): 197 deep_items = value.get_params().items() AttributeError: 'PCA' object has no attribute 'random_state' ---------------------------------------------------------------------- AttributeError Traceback (most recent call last) ~/.local/lib/python3.8/site-packages/IPython/core/formatters.py in __call__(self, obj) 700 type_pprinters=self.type_printers, 701 deferred_pprinters=self.deferred_printers) --> 702 printer.pretty(obj) 703 printer.flush() 704 return stream.getvalue() ~/.local/lib/python3.8/site-packages/IPython/lib/pretty.py in pretty(self, obj) 392 if cls is not object \ 393 and callable(cls.__dict__.get('__repr__')): --> 394 return _repr_pprint(obj, self, cycle) 395 396 return _default_pprint(obj, self, cycle) ~/.local/lib/python3.8/site-packages/IPython/lib/pretty.py in _repr_pprint(obj, p, cycle) 698 """A pprint that just redirects to the normal repr function.""" 699 # Find newlines and replace them with p.break_() --> 700 output = repr(obj) 701 lines = output.splitlines() 702 with p.group(): ~/.local/lib/python3.8/site-packages/sklearn/base.py in __repr__(self, N_CHAR_MAX) 258 n_max_elements_to_show=N_MAX_ELEMENTS_TO_SHOW) 259 --> 260 repr_ = pp.pformat(self) 261 262 # Use bruteforce ellipsis when there are a lot of non-blank characters ~/anaconda3/lib/python3.8/pprint.py in pformat(self, object) 151 def pformat(self, object): 152 sio = _StringIO() --> 153 self._format(object, sio, 0, 0, {}, 0) 154 return sio.getvalue() 155 ~/anaconda3/lib/python3.8/pprint.py in _format(self, object, stream, indent, allowance, context, level) 168 self._readable = False 169 return --> 170 rep = self._repr(object, context, level) 171 max_width = self._width - indent - allowance 172 if len(rep) > max_width: ~/anaconda3/lib/python3.8/pprint.py in _repr(self, object, context, level) 402 403 def _repr(self, object, context, level): --> 404 repr, readable, recursive = self.format(object, context.copy(), 405 self._depth, level) 406 if not readable: ~/.local/lib/python3.8/site-packages/sklearn/utils/_pprint.py in format(self, object, context, maxlevels, level) 178 179 def format(self, object, context, maxlevels, level): --> 180 return _safe_repr(object, context, maxlevels, level, 181 changed_only=self._changed_only) 182 ~/.local/lib/python3.8/site-packages/sklearn/utils/_pprint.py in _safe_repr(object, context, maxlevels, level, changed_only) 423 recursive = False 424 if changed_only: --> 425 params = _changed_params(object) 426 else: 427 params = object.get_params(deep=False) ~/.local/lib/python3.8/site-packages/sklearn/utils/_pprint.py in _changed_params(estimator) 89 estimator with non-default values.""" 90 ---> 91 params = estimator.get_params(deep=False) 92 init_func = getattr(estimator.__init__, 'deprecated_original', 93 estimator.__init__) ~/.local/lib/python3.8/site-packages/sklearn/base.py in get_params(self, deep) 193 out = dict() 194 for key in self._get_param_names(): --> 195 value = getattr(self, key) 196 if deep and hasattr(value, 'get_params'): 197 deep_items = value.get_params().items() AttributeError: 'PCA' object has no attribute 'random_state' ``` **Desktop (please complete the following information):** - OS: linux - Python Version: 3.8 - Yellowbrick Version: 1.3 **Additional information** This bug is easy to correct, in yellowbrick/features/pca.py: actually : ``` colorbar=colorbar, **kwargs ) # Data Parameters self.scale = scale self.proj_features = proj_features ``` correction : ``` colorbar=colorbar, **kwargs ) self.random_state=random_state # Data Parameters self.scale = scale self.proj_features = proj_features ``` ROC/AUC AttributeError: 'LogisticRegression' object has no attribute 'binary' **Describe the bug** Using logistic regression with the ROC/AUC functions throws `AttributeError: 'LogisticRegression' object has no attribute 'binary'`, however, the plot still shows up and it seems like most things work. **To Reproduce** This is the demo from the docs (https://www.scikit-yb.org/en/latest/api/classifier/rocauc.html): ```python from yellowbrick.classifier.rocauc import roc_auc from yellowbrick.datasets import load_credit from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split #Load the classification dataset X, y = load_credit() #Create the train and test data X_train, X_test, y_train, y_test = train_test_split(X,y) # Instantiate the visualizer with the classification model model = LogisticRegression() roc_auc(model, X_train, y_train, X_test=X_test, y_test=y_test, classes=['not_defaulted', 'defaulted']) ``` **Dataset** From the demo. **Expected behavior** Should not throw an AttributeError. **Traceback** ```python AttributeError Traceback (most recent call last) ~\Anaconda3\envs\datasci\lib\site-packages\IPython\core\formatters.py in __call__(self, obj, include, exclude) 968 969 if method is not None: --> 970 return method(include=include, exclude=exclude) 971 return None 972 else: ~\Anaconda3\envs\datasci\lib\site-packages\sklearn\base.py in _repr_mimebundle_(self, **kwargs) 462 def _repr_mimebundle_(self, **kwargs): 463 """Mime bundle used by jupyter kernels to display estimator""" --> 464 output = {"text/plain": repr(self)} 465 if get_config()["display"] == 'diagram': 466 output["text/html"] = estimator_html_repr(self) ~\Anaconda3\envs\datasci\lib\site-packages\sklearn\base.py in __repr__(self, N_CHAR_MAX) 258 n_max_elements_to_show=N_MAX_ELEMENTS_TO_SHOW) 259 --> 260 repr_ = pp.pformat(self) 261 262 # Use bruteforce ellipsis when there are a lot of non-blank characters ~\Anaconda3\envs\datasci\lib\pprint.py in pformat(self, object) 151 def pformat(self, object): 152 sio = _StringIO() --> 153 self._format(object, sio, 0, 0, {}, 0) 154 return sio.getvalue() 155 ~\Anaconda3\envs\datasci\lib\pprint.py in _format(self, object, stream, indent, allowance, context, level) 168 self._readable = False 169 return --> 170 rep = self._repr(object, context, level) 171 max_width = self._width - indent - allowance 172 if len(rep) > max_width: ~\Anaconda3\envs\datasci\lib\pprint.py in _repr(self, object, context, level) 402 403 def _repr(self, object, context, level): --> 404 repr, readable, recursive = self.format(object, context.copy(), 405 self._depth, level) 406 if not readable: ~\Anaconda3\envs\datasci\lib\site-packages\sklearn\utils\_pprint.py in format(self, object, context, maxlevels, level) 178 179 def format(self, object, context, maxlevels, level): --> 180 return _safe_repr(object, context, maxlevels, level, 181 changed_only=self._changed_only) 182 ~\Anaconda3\envs\datasci\lib\site-packages\sklearn\utils\_pprint.py in _safe_repr(object, context, maxlevels, level, changed_only) 423 recursive = False 424 if changed_only: --> 425 params = _changed_params(object) 426 else: 427 params = object.get_params(deep=False) ~\Anaconda3\envs\datasci\lib\site-packages\sklearn\utils\_pprint.py in _changed_params(estimator) 89 estimator with non-default values.""" 90 ---> 91 params = estimator.get_params(deep=False) 92 init_func = getattr(estimator.__init__, 'deprecated_original', 93 estimator.__init__) ~\Anaconda3\envs\datasci\lib\site-packages\yellowbrick\base.py in get_params(self, deep) 340 the estimator params. 341 """ --> 342 params = super(ModelVisualizer, self).get_params(deep=deep) 343 for param in list(params.keys()): 344 if param.startswith("estimator__"): ~\Anaconda3\envs\datasci\lib\site-packages\sklearn\base.py in get_params(self, deep) 193 out = dict() 194 for key in self._get_param_names(): --> 195 value = getattr(self, key) 196 if deep and hasattr(value, 'get_params'): 197 deep_items = value.get_params().items() ~\Anaconda3\envs\datasci\lib\site-packages\yellowbrick\utils\wrapper.py in __getattr__(self, attr) 40 def __getattr__(self, attr): 41 # proxy to the wrapped object ---> 42 return getattr(self._wrapped, attr) AttributeError: 'LogisticRegression' object has no attribute 'binary' --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) ~\Anaconda3\envs\datasci\lib\site-packages\IPython\core\formatters.py in __call__(self, obj) 700 type_pprinters=self.type_printers, 701 deferred_pprinters=self.deferred_printers) --> 702 printer.pretty(obj) 703 printer.flush() 704 return stream.getvalue() ~\Anaconda3\envs\datasci\lib\site-packages\IPython\lib\pretty.py in pretty(self, obj) 392 if cls is not object \ 393 and callable(cls.__dict__.get('__repr__')): --> 394 return _repr_pprint(obj, self, cycle) 395 396 return _default_pprint(obj, self, cycle) ~\Anaconda3\envs\datasci\lib\site-packages\IPython\lib\pretty.py in _repr_pprint(obj, p, cycle) 698 """A pprint that just redirects to the normal repr function.""" 699 # Find newlines and replace them with p.break_() --> 700 output = repr(obj) 701 lines = output.splitlines() 702 with p.group(): ~\Anaconda3\envs\datasci\lib\site-packages\sklearn\base.py in __repr__(self, N_CHAR_MAX) 258 n_max_elements_to_show=N_MAX_ELEMENTS_TO_SHOW) 259 --> 260 repr_ = pp.pformat(self) 261 262 # Use bruteforce ellipsis when there are a lot of non-blank characters ~\Anaconda3\envs\datasci\lib\pprint.py in pformat(self, object) 151 def pformat(self, object): 152 sio = _StringIO() --> 153 self._format(object, sio, 0, 0, {}, 0) 154 return sio.getvalue() 155 ~\Anaconda3\envs\datasci\lib\pprint.py in _format(self, object, stream, indent, allowance, context, level) 168 self._readable = False 169 return --> 170 rep = self._repr(object, context, level) 171 max_width = self._width - indent - allowance 172 if len(rep) > max_width: ~\Anaconda3\envs\datasci\lib\pprint.py in _repr(self, object, context, level) 402 403 def _repr(self, object, context, level): --> 404 repr, readable, recursive = self.format(object, context.copy(), 405 self._depth, level) 406 if not readable: ~\Anaconda3\envs\datasci\lib\site-packages\sklearn\utils\_pprint.py in format(self, object, context, maxlevels, level) 178 179 def format(self, object, context, maxlevels, level): --> 180 return _safe_repr(object, context, maxlevels, level, 181 changed_only=self._changed_only) 182 ~\Anaconda3\envs\datasci\lib\site-packages\sklearn\utils\_pprint.py in _safe_repr(object, context, maxlevels, level, changed_only) 423 recursive = False 424 if changed_only: --> 425 params = _changed_params(object) 426 else: 427 params = object.get_params(deep=False) ~\Anaconda3\envs\datasci\lib\site-packages\sklearn\utils\_pprint.py in _changed_params(estimator) 89 estimator with non-default values.""" 90 ---> 91 params = estimator.get_params(deep=False) 92 init_func = getattr(estimator.__init__, 'deprecated_original', 93 estimator.__init__) ~\Anaconda3\envs\datasci\lib\site-packages\yellowbrick\base.py in get_params(self, deep) 340 the estimator params. 341 """ --> 342 params = super(ModelVisualizer, self).get_params(deep=deep) 343 for param in list(params.keys()): 344 if param.startswith("estimator__"): ~\Anaconda3\envs\datasci\lib\site-packages\sklearn\base.py in get_params(self, deep) 193 out = dict() 194 for key in self._get_param_names(): --> 195 value = getattr(self, key) 196 if deep and hasattr(value, 'get_params'): 197 deep_items = value.get_params().items() ~\Anaconda3\envs\datasci\lib\site-packages\yellowbrick\utils\wrapper.py in __getattr__(self, attr) 40 def __getattr__(self, attr): 41 # proxy to the wrapped object ---> 42 return getattr(self._wrapped, attr) AttributeError: 'LogisticRegression' object has no attribute 'binary' ``` **Desktop (please complete the following information):** - OS: Windows 10 - Python Version 3.8 Anaconda - Yellowbrick Version current latest (1.3.post1) - sklearn version: 0.24.1 **Additional context** I ran this in IPython, noticed a similar/the same bug in Jupyter.
Hi @phbillet thank you for the bug report, this is probably a result of the changes we made to `get_params` and `set_params` in #1147. Your solution is also a good one; the `random_state` gets used in the `PCATransformer` but I can't think of a reason why it's not a good idea to also set it on the visualizer. To keep the random state in sync, however, I suggest a property: ```python def __init__(self, ...): ... self._random_state = random_state @property def random_state(self): return self._random_state @random_state.setter(self, val): self._random_state = val self.pca_transformer.set_params(pca__random_state=val) ``` I get the same error with a GaussianNB model: `AttributeError: 'GaussianNB' object has no attribute 'binary'`. Seems like it is happening for all models most likely. @nateGeorge cheers, this is a regression and related to #1160 - thank you for finding it and bringing it to our attention! To fix this - we need to set `self.binary = binary` in the `__init__` rather than simply relying on the `if/else` to set the `macro/micro` flags. This is because scikit-learn uses `inspect` to determine the class signature for `get_params` and `set_params`.
2021-04-02T13:18:25
DistrictDataLabs/yellowbrick
1,181
DistrictDataLabs__yellowbrick-1181
[ "1179" ]
783069e082569463faa3a192d1884de627a13370
diff --git a/yellowbrick/model_selection/importances.py b/yellowbrick/model_selection/importances.py --- a/yellowbrick/model_selection/importances.py +++ b/yellowbrick/model_selection/importances.py @@ -231,6 +231,14 @@ def fit(self, X, y=None, **kwargs): # Sort the features and their importances if self.stack: + if len(self.classes_) != self.feature_importances_.shape[0]: + raise YellowbrickValueError( + ( + "The model used does not return coef_ array in the shape of (n_classes, n_features)." + " Unable to generate stacked feature importances. " + "Consider setting the stack parameter to False or using a different model" + ) + ) if self.topn: abs_sort_idx = np.argsort( np.sum(np.absolute(self.feature_importances_), 0)
diff --git a/tests/test_model_selection/test_importances.py b/tests/test_model_selection/test_importances.py --- a/tests/test_model_selection/test_importances.py +++ b/tests/test_model_selection/test_importances.py @@ -240,6 +240,22 @@ def test_multi_coefs_stacked(self): # Appveyor and Linux conda non-text-based differences self.assert_images_similar(viz, tol=17.5) + def test_stack_param_incorrectly_used_throws_error(self): + """ + Test incorrectly using stack param on a dataset with two classes which + does not return a coef_ array in the shape of (n_classes, n_features) + """ + X, y = load_occupancy() + + viz = FeatureImportances( + LogisticRegression(solver="liblinear", random_state=222), stack=True + ) + + expected_error = "The model used does not return coef_ array" + + with pytest.raises(YellowbrickValueError, match=expected_error): + viz.fit(X, y) + @pytest.mark.skipif(pd is None, reason="pandas is required for this test") def test_fit_dataframe(self): """
please specify the same number of colors as labels! **Describe the bug** Dear Yellowbrick team, When I am trying to repeat a code from examples for Stacked Feature Importances (https://www.scikit-yb.org/en/latest/api/model_selection/importances.html?highlight=feature_importance#yellowbrick.model_selection.importances.feature_importances) I receive an error when I fit the model that I should specify the same number of colors as labels. But I am not providing these arguments and I suppose that don't have any variables which can have any confusing names. **To Reproduce** ``` # Steps to reproduce the behavior (code snippet): #split dataset from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,stratify = y) #Import svm model from sklearn import svm #Create a svm Classifier clf = svm.SVC(kernel='linear',probability=True) # Linear Kernel #Train the model using the training sets clf.fit(X_train, y_train) #Predict the response for test dataset y_pred = clf.predict(X_test) from yellowbrick.model_selection import FeatureImportances viz = FeatureImportances(clf, stack=True, relative=False)#,labels = features_formatted) viz.fit(X_test, y_test) viz.show() ``` After running cells: ``` /Users/polina_turova/opt/anaconda3/lib/python3.8/site-packages/sklearn/base.py:209: FutureWarning: From version 0.24, get_params will raise an AttributeError if a parameter cannot be retrieved as an instance attribute. Previously it would return None. warnings.warn('From version 0.24, get_params will raise an ' --------------------------------------------------------------------------- YellowbrickValueError Traceback (most recent call last) <ipython-input-5-d5e7630146dc> in <module> 1 from yellowbrick.model_selection import FeatureImportances 2 viz = FeatureImportances(clf, stack=True, relative=False)#,labels = features_formatted) ----> 3 viz.fit(X_test, y_test) 4 viz.show() ~/opt/anaconda3/lib/python3.8/site-packages/yellowbrick/model_selection/importances.py in fit(self, X, y, **kwargs) 230 231 # Draw the feature importances --> 232 self.draw() 233 return self 234 ~/opt/anaconda3/lib/python3.8/site-packages/yellowbrick/model_selection/importances.py in draw(self, **kwargs) 249 colors = resolve_colors(len(self.classes_), colormap=self.colormap) 250 legend_kws = {"bbox_to_anchor": (1.04, 0.5), "loc": "center left"} --> 251 bar_stack( 252 self.feature_importances_, 253 ax=self.ax, ~/opt/anaconda3/lib/python3.8/site-packages/yellowbrick/draw.py in bar_stack(data, ax, labels, ticks, colors, colormap, orientation, legend, legend_kws, **kwargs) 191 if legend: 192 legend_kws = legend_kws or {} --> 193 manual_legend(ax, labels=labels, colors=colors, **legend_kws) 194 return ax ~/opt/anaconda3/lib/python3.8/site-packages/yellowbrick/draw.py in manual_legend(g, labels, colors, **legend_kwargs) 82 # Ensure that labels and colors are the same length to prevent odd behavior. 83 if len(colors) != len(labels): ---> 84 raise YellowbrickValueError( 85 "please specify the same number of colors as labels!" 86 ) YellowbrickValueError: please specify the same number of colors as labels! ``` ![download](https://user-images.githubusercontent.com/61549119/118780655-f204bf00-b894-11eb-9faf-82e3f84d0a0c.png) **Dataset** X and y can be uploaded from this repository: https://github.com/turovapolina/unsupervised-LC-MS-data-treatment X is a numpy array (69 samples and 83 features) y is a list of strings with 7 classes **Expected behavior** Same picture as in the example (https://www.scikit-yb.org/en/latest/api/model_selection/importances.html?highlight=feature_importance#yellowbrick.model_selection.importances.feature_importances) with values for all features and all classes **Desktop (please complete the following information):** - OS: [macOS] - Python Version [3.8.3] - Yellowbrick Version [3.1.0]
2021-05-27T03:15:17
DistrictDataLabs/yellowbrick
1,186
DistrictDataLabs__yellowbrick-1186
[ "1185" ]
07ef358dde7f9e24a71d3e4660d306dc44533611
diff --git a/yellowbrick/cluster/elbow.py b/yellowbrick/cluster/elbow.py --- a/yellowbrick/cluster/elbow.py +++ b/yellowbrick/cluster/elbow.py @@ -87,7 +87,7 @@ def distortion_score(X, labels, metric="euclidean"): """ # Encode labels to get unique centers and groups le = LabelEncoder() - labels = le.fit_transform(labels) + le.fit(labels) unique_labels = le.classes_ # Sum of the distortions @@ -432,15 +432,15 @@ def metric_color(self): @metric_color.setter def metric_color(self, val): self.colors[CMETRIC] = val - + @property def timing_color(self): return self.colors[CTIMING] - + @timing_color.setter def timing_color(self, val): self.colors[CTIMING] = val - + @property def vline_color(self): return self.colors[CVLINE]
diff --git a/tests/test_cluster/test_elbow.py b/tests/test_cluster/test_elbow.py --- a/tests/test_cluster/test_elbow.py +++ b/tests/test_cluster/test_elbow.py @@ -116,6 +116,15 @@ def test_distortion_score_pandas_input(self): score = distortion_score(df, s) assert score == pytest.approx(69.10006514142941) + def test_distortion_score_empty_clusters(self): + """ + Ensure no ValueError is thrown when there are empty clusters #1185 + """ + X = np.array([[1,2],[3,4],[5,6]]) + valuea = distortion_score(X, np.array([1,3,3])) + valueb = distortion_score(X, np.array([0,1,1])) + assert valuea == valueb + ########################################################################## ## KElbowVisualizer Test Cases @@ -439,14 +448,14 @@ def test_set_colors_manually(self): oz.metric_color = "r" oz.timing_color = "y" oz.vline_color = "c" - + # Create artificial "fit" data for testing purposes oz.k_values_ = [1, 2, 3, 4, 5, 6, 7, 8] oz.k_timers_ = [6.2, 8.3, 10.1, 15.8, 21.2, 27.9, 38.2, 44.9] oz.k_scores_ = [.8, .7, .55, .48, .40, .38, .35, .30] oz.elbow_value_ = 5 oz.elbow_score_ = 0.40 - + # Execute drawing oz.draw() oz.finalize()
KElbowVisualizer Crashes on Null Cluster **Description** I am using the Spherical K-Means outlined in [Learning Feature Representation with K-Means](https://www-cs.stanford.edu/~acoates/papers/coatesng_nntot2012.pdf), and my implementation is in [busFred/sklearn_plugins](https://github.com/busFred/sklearn_plugins). In my implementation, it is possible that some cluster centroids has no points get assigned to it. Hereafter, such centroids will be referred to as "null cluster". However, due to the incorrect usage of `sklearn.preprocessing.LabelEncoder` in [function `distortion_score` of yellowbrick/cluster/elbow.py](https://github.com/DistrictDataLabs/yellowbrick/blob/783069e082569463faa3a192d1884de627a13370/yellowbrick/cluster/elbow.py#L90), the program could fail with `ValueError: Found array with 0 sample(s) (shape=(0, 640)) while a minimum of 1 is required by check_pairwise_arrays.` I don't think the problem is not specific to my SphericalKMeans implementation. Any KMeans that produces centroids that no data point get assigned to could cause the program to fail. **To Reproduce** ```python import numpy as np from yellowbrick.cluster import distortion_score X = np.array([[1,2], [3,4], [5,6]]) labels = np.array([1,3,5]) distortion_score(X, labels) ``` **Dataset** For my research project, I am using UrbanSoundDataset. But I have backtracked the problem and pinned down the cause of the problem and can be reproduced with the code provided above. **Expected behavior** The program should not crash when null clusters exist. **Traceback** The traceback for the code in the reproduce section: ``` >>> distortion_score(X, labels) /home/fred/Documents/research/yellowbrick/yellowbrick/cluster/elbow.py:103: RuntimeWarning: Mean of empty slice. center = instances.mean(axis=0) /home/fred/anaconda3/envs/yellowbrick/lib/python3.8/site-packages/numpy/core/_methods.py:162: RuntimeWarning: invalid value encountered in true_divide ret = um.true_divide( Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/fred/Documents/research/yellowbrick/yellowbrick/cluster/elbow.py", line 114, in distortion_score distances = pairwise_distances(instances, center, metric=metric) File "/home/fred/.local/lib/python3.8/site-packages/sklearn/utils/validation.py", line 63, in inner_f return f(*args, **kwargs) File "/home/fred/.local/lib/python3.8/site-packages/sklearn/metrics/pairwise.py", line 1790, in pairwise_distances return _parallel_pairwise(X, Y, func, n_jobs, **kwds) File "/home/fred/.local/lib/python3.8/site-packages/sklearn/metrics/pairwise.py", line 1359, in _parallel_pairwise return func(X, Y, **kwds) File "/home/fred/.local/lib/python3.8/site-packages/sklearn/utils/validation.py", line 63, in inner_f return f(*args, **kwargs) File "/home/fred/.local/lib/python3.8/site-packages/sklearn/metrics/pairwise.py", line 272, in euclidean_distances X, Y = check_pairwise_arrays(X, Y) File "/home/fred/.local/lib/python3.8/site-packages/sklearn/utils/validation.py", line 63, in inner_f return f(*args, **kwargs) File "/home/fred/.local/lib/python3.8/site-packages/sklearn/metrics/pairwise.py", line 146, in check_pairwise_arrays X = check_array(X, accept_sparse=accept_sparse, dtype=dtype, File "/home/fred/.local/lib/python3.8/site-packages/sklearn/utils/validation.py", line 63, in inner_f return f(*args, **kwargs) File "/home/fred/.local/lib/python3.8/site-packages/sklearn/utils/validation.py", line 726, in check_array raise ValueError("Found array with %d sample(s) (shape=%s) while a" ValueError: Found array with 0 sample(s) (shape=(0, 2)) while a minimum of 1 is required by check_pairwise_arrays. ``` The traceback I actually encounter in my real research project: ``` /home/fred/anaconda3/envs/sound_detection/lib/python3.8/site-packages/yellowbrick/cluster/elbow.py:93: RuntimeWarning: Mean of empty slice. center = instances.mean(axis=0) /home/fred/anaconda3/envs/sound_detection/lib/python3.8/site-packages/numpy/core/_methods.py:162: RuntimeWarning: invalid value encountered in true_divide ret = um.true_divide( Traceback (most recent call last): File "/home/fred/Documents/research/sound_detection/segmented_audio_classifier/script/local/feature/../../../src/executable/training/kmeans/try_k_urban_sound_dataset.py", line 423, in <module> main(len(args), args) File "/home/fred/Documents/research/sound_detection/segmented_audio_classifier/script/local/feature/../../../src/executable/training/kmeans/try_k_urban_sound_dataset.py", line 389, in main min_optimal_k, max_optimal_k = try_k_elbow( File "/home/fred/Documents/research/sound_detection/segmented_audio_classifier/script/local/feature/../../../src/executable/training/kmeans/try_k_urban_sound_dataset.py", line 264, in try_k_elbow visualizer.fit(curr_class_feature_vectors) File "/home/fred/anaconda3/envs/sound_detection/lib/python3.8/site-packages/yellowbrick/cluster/elbow.py", line 316, in fit self.k_scores_.append(self.scoring_metric(X, self.estimator.labels_)) File "/home/fred/anaconda3/envs/sound_detection/lib/python3.8/site-packages/yellowbrick/cluster/elbow.py", line 104, in distortion_score distances = pairwise_distances(instances, center, metric=metric) File "/home/fred/anaconda3/envs/sound_detection/lib/python3.8/site-packages/sklearn/utils/validation.py", line 63, in inner_f return f(*args, **kwargs) File "/home/fred/anaconda3/envs/sound_detection/lib/python3.8/site-packages/sklearn/metrics/pairwise.py", line 1790, in pairwise_distances return _parallel_pairwise(X, Y, func, n_jobs, **kwds) File "/home/fred/anaconda3/envs/sound_detection/lib/python3.8/site-packages/sklearn/metrics/pairwise.py", line 1359, in _parallel_pairwise return func(X, Y, **kwds) File "/home/fred/anaconda3/envs/sound_detection/lib/python3.8/site-packages/sklearn/utils/validation.py", line 63, in inner_f return f(*args, **kwargs) File "/home/fred/anaconda3/envs/sound_detection/lib/python3.8/site-packages/sklearn/metrics/pairwise.py", line 272, in euclidean_distances X, Y = check_pairwise_arrays(X, Y) File "/home/fred/anaconda3/envs/sound_detection/lib/python3.8/site-packages/sklearn/utils/validation.py", line 63, in inner_f return f(*args, **kwargs) File "/home/fred/anaconda3/envs/sound_detection/lib/python3.8/site-packages/sklearn/metrics/pairwise.py", line 146, in check_pairwise_arrays X = check_array(X, accept_sparse=accept_sparse, dtype=dtype, File "/home/fred/anaconda3/envs/sound_detection/lib/python3.8/site-packages/sklearn/utils/validation.py", line 63, in inner_f return f(*args, **kwargs) File "/home/fred/anaconda3/envs/sound_detection/lib/python3.8/site-packages/sklearn/utils/validation.py", line 726, in check_array raise ValueError("Found array with %d sample(s) (shape=%s) while a" ValueError: Found array with 0 sample(s) (shape=(0, 640)) while a minimum of 1 is required by check_pairwise_arrays. ``` **Desktop (please complete the following information):** - OS: Ubuntu MATE 20.04 - Python Version: 3.8.5 - Yellowbrick Version: 1.3.post1 **Cause:** In [`distortion_score`](https://github.com/DistrictDataLabs/yellowbrick/blob/783069e082569463faa3a192d1884de627a13370/yellowbrick/cluster/elbow.py#L90), variable `labels` are reassigned to `LabelEncoder().fit_transform(labels)`. After this line, labels are represented in range 0 and n_unique_classes-1. However, the for loop on line 97, it is looping through `unique_labels`, which is assigned to `LabelEncoder().classes_`. However, `LabelEncoder().classes_` are the unique labels prior to transform, which are no necessarily in the range 0 and n_unique_classes-1. In the example above, the passed in labels is [1,3,5]. After line 90, labels is reassigned to [0,1,2] and `le.classes_` is [1,3,5]. While looping through it on line 97, when `current_label` is 0, `mask` is a boolean array that is `[false, false, false]` and `instances = X[mask]` is a length 0 array. The official sklearn.preprocessing.LabelEncoder documentation is attached below: `LabelEncoder` can be used to normalize labels. >>> from sklearn import preprocessing >>> le = preprocessing.LabelEncoder() >>> le.fit([1, 2, 2, 6]) LabelEncoder() >>> le.classes_ array([1, 2, 6]) >>> le.transform([1, 1, 2, 6]) array([0, 0, 1, 2]...) >>> le.inverse_transform([0, 0, 1, 2]) array([1, 1, 2, 6])
2021-07-09T16:41:35
DistrictDataLabs/yellowbrick
1,221
DistrictDataLabs__yellowbrick-1221
[ "1209", "1209" ]
efd942063455f1c148c3c691d8100d726b09ac90
diff --git a/yellowbrick/regressor/prediction_error.py b/yellowbrick/regressor/prediction_error.py --- a/yellowbrick/regressor/prediction_error.py +++ b/yellowbrick/regressor/prediction_error.py @@ -121,11 +121,13 @@ def __init__( is_fitted="auto", **kwargs ): - # Whether or not to check if the model is already fitted - self.is_fitted = is_fitted # Initialize the visualizer - super(PredictionError, self).__init__(estimator, ax=ax, **kwargs) + super(PredictionError, self).__init__( + estimator, + is_fitted=is_fitted, + ax=ax, + **kwargs) # Visual arguments self.colors = { diff --git a/yellowbrick/regressor/residuals.py b/yellowbrick/regressor/residuals.py --- a/yellowbrick/regressor/residuals.py +++ b/yellowbrick/regressor/residuals.py @@ -154,11 +154,13 @@ def __init__( is_fitted="auto", **kwargs ): - # Whether or not to check if the model is already fitted - self.is_fitted = is_fitted # Initialize the visualizer base - super(ResidualsPlot, self).__init__(estimator, ax=ax, **kwargs) + super(ResidualsPlot, self).__init__( + estimator, + ax=ax, + is_fitted=is_fitted, + **kwargs) # TODO: allow more scatter plot arguments for train and test points # See #475 (RE: ScatterPlotMixin)
Argument to PredictionError is overwritten **Describe the bug** Argument `is_fitted` is overwritten when Instantiating a `PredictionError` or `ResidualsPlot`. **To Reproduce** ```python from yellowbrick.regressor import PredictionError from sklearn.linear_models import Lasso visualizer = PredictionError(Lasso(), "test title", is_fitted=True) print(visualizer.is_fitted) ``` **Expected behavior** When `is_fitted` is passed in, I expect it to not be overwritten in the __init__ calls **Desktop (please complete the following information):** - OS: Ubuntu 20.04 - Python Version 3.8.10 - Yellowbrick Version : 1.3.post1 Argument to PredictionError is overwritten **Describe the bug** Argument `is_fitted` is overwritten when Instantiating a `PredictionError` or `ResidualsPlot`. **To Reproduce** ```python from yellowbrick.regressor import PredictionError from sklearn.linear_models import Lasso visualizer = PredictionError(Lasso(), "test title", is_fitted=True) print(visualizer.is_fitted) ``` **Expected behavior** When `is_fitted` is passed in, I expect it to not be overwritten in the __init__ calls **Desktop (please complete the following information):** - OS: Ubuntu 20.04 - Python Version 3.8.10 - Yellowbrick Version : 1.3.post1
@aramesh7 it does appear that `is_fitted` is defaulting to `auto` but I'm not sure why. We'll have to dig into this a bit more. @aramesh7 it does appear that `is_fitted` is defaulting to `auto` but I'm not sure why. We'll have to dig into this a bit more.
2022-02-25T06:24:27
DistrictDataLabs/yellowbrick
1,242
DistrictDataLabs__yellowbrick-1242
[ "1131" ]
ff8e3d247265b59721fbeeb074455c24979c5ef5
diff --git a/yellowbrick/cluster/elbow.py b/yellowbrick/cluster/elbow.py --- a/yellowbrick/cluster/elbow.py +++ b/yellowbrick/cluster/elbow.py @@ -130,6 +130,9 @@ def distortion_score(X, labels, metric="euclidean"): "calinski_harabasz": chs, } +DISTANCE_METRICS = ['cityblock', 'cosine', 'euclidean', 'haversine', + 'l1', 'l2', 'manhattan', 'nan_euclidean', 'precomputed'] + class KElbowVisualizer(ClusteringScoreVisualizer): """ @@ -182,6 +185,12 @@ class KElbowVisualizer(ClusteringScoreVisualizer): - **silhouette**: mean ratio of intra-cluster and nearest-cluster distance - **calinski_harabasz**: ratio of within to between cluster dispersion + distance_metric : str or callable, default='euclidean' + The metric to use when calculating distance between instances in a + feature array. If metric is a string, it must be one of the options allowed + by sklearn's metrics.pairwise.pairwise_distances. If X is the distance array itself, + use metric="precomputed". + timings : bool, default: True Display the fitting time per k to evaluate the amount of time required to train the clustering model. @@ -250,6 +259,7 @@ def __init__( ax=None, k=10, metric="distortion", + distance_metric='euclidean', timings=True, locate_elbow=True, **kwargs @@ -263,11 +273,18 @@ def __init__( "use one of distortion, silhouette, or calinski_harabasz" ) + if distance_metric not in DISTANCE_METRICS: + raise YellowbrickValueError( + "'{} is not a defined distance metric " + "use one of the sklearn metric.pairwise.pairwise_distances" + ) + # Store the arguments self.scoring_metric = KELBOW_SCOREMAP[metric] self.metric = metric self.timings = timings self.locate_elbow = locate_elbow + self.distance_metric = distance_metric # Set the values of the colors self.colors = { @@ -331,7 +348,11 @@ def fit(self, X, y=None, **kwargs): # Append the time and score to our plottable metrics self.k_timers_.append(time.time() - start) - self.k_scores_.append(self.scoring_metric(X, self.estimator.labels_)) + if self.metric != 'calinski_harabasz': + self.k_scores_.append(self.scoring_metric(X, self.estimator.labels_, + metric=self.distance_metric)) + else: + self.k_scores_.append(self.scoring_metric(X, self.estimator.labels_)) if self.locate_elbow: locator_kwargs = { @@ -465,6 +486,7 @@ def kelbow_visualizer( ax=None, k=10, metric="distortion", + distance_metric='euclidean', timings=True, locate_elbow=True, show=True, @@ -504,6 +526,12 @@ def kelbow_visualizer( distance - **calinski_harabasz**: ratio of within to between cluster dispersion + distance_metric : str or callable, default='euclidean' + The metric to use when calculating distance between instances in a + feature array. If metric is a string, it must be one of the options allowed + by sklearn's metrics.pairwise.pairwise_distances. If X is the distance array itself, + use metric="precomputed". + timings : bool, default: True Display the fitting time per k to evaluate the amount of time required to train the clustering model. @@ -542,6 +570,7 @@ def kelbow_visualizer( ax=ax, k=k, metric=metric, + distance_metric='euclidean', timings=timings, locate_elbow=locate_elbow, **kwargs diff --git a/yellowbrick/contrib/missing/bar.py b/yellowbrick/contrib/missing/bar.py --- a/yellowbrick/contrib/missing/bar.py +++ b/yellowbrick/contrib/missing/bar.py @@ -100,17 +100,16 @@ def __init__(self, width=0.5, color=None, colors=None, classes=None, **kwargs): self.colors = color_palette(kwargs.pop("colors", None), n_colors) def get_nan_col_counts(self, **kwargs): - # where matrix contains strings, handle them - if np.issubdtype(self.X.dtype, np.string_) or np.issubdtype( - self.X.dtype, np.unicode_ + if np.issubdtype(self.X.dtype, np.floating) or np.issubdtype( + self.X.dtype, np.integer ): - mask = np.where(self.X == "") + nan_matrix = self.X.astype(np.float64) + else: + # where matrix contains strings, handle them + mask = np.where((self.X == "") | (self.X == 'nan')) nan_matrix = np.zeros(self.X.shape) nan_matrix[mask] = np.nan - else: - nan_matrix = self.X.astype(np.float64) - if self.y is None: nan_col_counts = [np.count_nonzero(np.isnan(col)) for col in nan_matrix.T] return nan_col_counts @@ -126,7 +125,6 @@ def get_nan_col_counts(self, **kwargs): [np.count_nonzero(np.isnan(col)) for col in target_matrix.T] ) nan_counts.append((target_value, nan_col_counts)) - return nan_counts def draw(self, X, y, **kwargs): diff --git a/yellowbrick/contrib/missing/base.py b/yellowbrick/contrib/missing/base.py --- a/yellowbrick/contrib/missing/base.py +++ b/yellowbrick/contrib/missing/base.py @@ -66,6 +66,9 @@ def fit(self, X, y=None, **kwargs): self.features_ = X.columns else: self.X = X + if self.features_ is None: + n_columns = X.shape[1] + self.features_ = np.arange(0, n_columns) self.y = y
diff --git a/tests/baseline_images/test_cluster/test_elbow/test_distance_metric.png b/tests/baseline_images/test_cluster/test_elbow/test_distance_metric.png new file mode 100644 Binary files /dev/null and b/tests/baseline_images/test_cluster/test_elbow/test_distance_metric.png differ diff --git a/tests/baseline_images/test_contrib/test_missing/test_bar/test_missingvaluesbar_numpy_no_features_passed.png b/tests/baseline_images/test_contrib/test_missing/test_bar/test_missingvaluesbar_numpy_no_features_passed.png new file mode 100644 Binary files /dev/null and b/tests/baseline_images/test_contrib/test_missing/test_bar/test_missingvaluesbar_numpy_no_features_passed.png differ diff --git a/tests/baseline_images/test_contrib/test_missing/test_bar/test_missingvaluesbar_numpy_with_mixed_dtypes.png b/tests/baseline_images/test_contrib/test_missing/test_bar/test_missingvaluesbar_numpy_with_mixed_dtypes.png new file mode 100644 Binary files /dev/null and b/tests/baseline_images/test_contrib/test_missing/test_bar/test_missingvaluesbar_numpy_with_mixed_dtypes.png differ diff --git a/tests/baseline_images/test_contrib/test_missing/test_bar/test_missingvaluesbar_numpy_with_string_and_bool_cols.png b/tests/baseline_images/test_contrib/test_missing/test_bar/test_missingvaluesbar_numpy_with_string_and_bool_cols.png new file mode 100644 Binary files /dev/null and b/tests/baseline_images/test_contrib/test_missing/test_bar/test_missingvaluesbar_numpy_with_string_and_bool_cols.png differ diff --git a/tests/baseline_images/test_contrib/test_missing/test_bar/test_missingvaluesbar_pandas_no_features_passed.png b/tests/baseline_images/test_contrib/test_missing/test_bar/test_missingvaluesbar_pandas_no_features_passed.png new file mode 100644 Binary files /dev/null and b/tests/baseline_images/test_contrib/test_missing/test_bar/test_missingvaluesbar_pandas_no_features_passed.png differ diff --git a/tests/baseline_images/test_contrib/test_missing/test_bar/test_missingvaluesbar_pandas_with_mixed_dtypes.png b/tests/baseline_images/test_contrib/test_missing/test_bar/test_missingvaluesbar_pandas_with_mixed_dtypes.png new file mode 100644 Binary files /dev/null and b/tests/baseline_images/test_contrib/test_missing/test_bar/test_missingvaluesbar_pandas_with_mixed_dtypes.png differ diff --git a/tests/baseline_images/test_contrib/test_missing/test_bar/test_missingvaluesbar_pandas_with_string_and_bool_cols.png b/tests/baseline_images/test_contrib/test_missing/test_bar/test_missingvaluesbar_pandas_with_string_and_bool_cols.png new file mode 100644 Binary files /dev/null and b/tests/baseline_images/test_contrib/test_missing/test_bar/test_missingvaluesbar_pandas_with_string_and_bool_cols.png differ diff --git a/tests/test_cluster/test_elbow.py b/tests/test_cluster/test_elbow.py --- a/tests/test_cluster/test_elbow.py +++ b/tests/test_cluster/test_elbow.py @@ -296,6 +296,29 @@ def test_calinski_harabasz_metric(self): self.assert_images_similar(visualizer) assert_array_almost_equal(visualizer.k_scores_, expected) + @pytest.mark.xfail(sys.platform == "win32", reason="images not close on windows") + def test_distance_metric(self): + """ + Test the manhattan distance metric of the distortion metric of the k-elbow visualizer + """ + visualizer = KElbowVisualizer( + KMeans(random_state=0), + k=5, + metric="distortion", + distance_metric='manhattan', + timings=False, + locate_elbow=False, + ) + visualizer.fit(self.clusters.X) + assert len(visualizer.k_scores_) == 4 + assert visualizer.elbow_value_ is None + + expected = np.array([189.060129, 154.096223, 124.271208, 107.087566]) + + visualizer.finalize() + self.assert_images_similar(visualizer) + assert_array_almost_equal(visualizer.k_scores_, expected) + @pytest.mark.xfail( IS_WINDOWS_OR_CONDA, reason="computation of k_scores_ varies by 2.867 max absolute difference", @@ -347,6 +370,13 @@ def test_bad_metric(self): with pytest.raises(YellowbrickValueError): KElbowVisualizer(KMeans(), k=5, metric="foo") + def test_bad_distance_metric(self): + """ + Assert KElbow raises an exception when a bad distance metric is supplied + """ + with pytest.raises(YellowbrickValueError): + KElbowVisualizer(KMeans(), k=5, distance_metric="foo") + @pytest.mark.xfail( IS_WINDOWS_OR_CONDA, reason="font rendering different in OS and/or Python; see #892", diff --git a/tests/test_contrib/test_missing/test_bar.py b/tests/test_contrib/test_missing/test_bar.py --- a/tests/test_contrib/test_missing/test_bar.py +++ b/tests/test_contrib/test_missing/test_bar.py @@ -70,6 +70,31 @@ def test_missingvaluesbar_pandas(self): viz = MissingValuesBar(features=features) viz.fit(X_) viz.finalize() + + self.assert_images_similar(viz, tol=self.tol) + + @pytest.mark.skipif(pd is None, reason="pandas is required") + def test_missingvaluesbar_pandas_no_features_passed(self): + """ + Integration test of visualizer with pandas + """ + X, y = make_classification( + n_samples=400, + n_features=20, + n_informative=8, + n_redundant=8, + n_classes=2, + n_clusters_per_class=4, + random_state=854, + ) + + # add nan values to a range of values in the matrix + X[X > 1.5] = np.nan + X_ = pd.DataFrame(X) + + viz = MissingValuesBar() + viz.fit(X_) + viz.finalize() self.assert_images_similar(viz, tol=self.tol) @@ -97,6 +122,29 @@ def test_missingvaluesbar_numpy(self): self.assert_images_similar(viz, tol=self.tol) + def test_missingvaluesbar_numpy_no_features_passed(self): + """ + Integration test of visualizer with numpy without target y passed in + """ + X, y = make_classification( + n_samples=400, + n_features=20, + n_informative=8, + n_redundant=8, + n_classes=2, + n_clusters_per_class=4, + random_state=856, + ) + + # add nan values to a range of values in the matrix + X[X > 1.5] = np.nan + + viz = MissingValuesBar() + viz.fit(X) + viz.finalize() + + self.assert_images_similar(viz, tol=self.tol) + def test_missingvaluesbar_numpy_with_y_target(self): """ Integration test of visualizer with numpy without target y passed in @@ -146,3 +194,136 @@ def test_missingvaluesbar_numpy_with_y_target_with_labels(self): viz.finalize() self.assert_images_similar(viz, tol=self.tol) + + def test_missingvaluesbar_numpy_with_string_and_bool_cols(self): + """ + Integration test of visualizer with numpy array with string and boolean columns + """ + X, y = make_classification( + n_samples=400, + n_features=10, + n_informative=2, + n_redundant=3, + n_classes=2, + n_clusters_per_class=2, + random_state=854 + ) + + # add nan values to a range of values in the matrix + X[X > 1.5] = np.nan + + rng = np.random.default_rng(2021) + fruit_choices = np.array(['apples', 'pears', 'peaches', "", np.nan, 'bananas']) + fruits = rng.choice(fruit_choices, (400, 1)) + + bool_choices = np.array([np.nan, False, True]) + booleans = rng.choice(bool_choices, (400, 1)) + + X = np.append(X, fruits, axis=1) + X = np.append(X, booleans, axis=1) + + features = [str(n) for n in range(12)] + viz = MissingValuesBar(features=features) + viz.fit(X, y) + viz.finalize() + + self.assert_images_similar(viz, tol=5) + + @pytest.mark.skipif(pd is None, reason="pandas is required") + def test_missingvaluesbar_pandas_with_string_and_bool_cols(self): + """ + Integration test of visualizer with pandas dataframe with string and boolean columns + """ + X, y = make_classification( + n_samples=400, + n_features=10, + n_informative=2, + n_redundant=3, + n_classes=2, + n_clusters_per_class=2, + random_state=854 + ) + + # add nan values to a range of values in the matrix + X[X > 1.5] = np.nan + + rng = np.random.default_rng(2021) + fruit_choices = np.array(['apples', 'pears', 'peaches', "", np.nan, 'bananas']) + fruits = rng.choice(fruit_choices, (400, 1)) + + bool_choices = np.array([np.nan, False, True]) + booleans = rng.choice(bool_choices, (400, 1)) + + X = np.append(X, fruits, axis=1) + X = np.append(X, booleans, axis=1) + + X_ = pd.DataFrame(X) + + features = [str(n) for n in range(12)] + viz = MissingValuesBar(features=features) + viz.fit(X_, y) + viz.finalize() + + self.assert_images_similar(viz, tol=5) + + def test_missingvaluesbar_numpy_with_mixed_dtypes(self): + """ + Integration test of visualizer with numpy array with mixed dtypes in a single column + """ + X, y = make_classification( + n_samples=400, + n_features=10, + n_informative=2, + n_redundant=3, + n_classes=2, + n_clusters_per_class=2, + random_state=854 + ) + + # add nan values to a range of values in the matrix + X[X > 1.5] = np.nan + + rng = np.random.default_rng(2021) + mixed_dtype_choices = np.array(['apples', 'pears', 'peaches', "", np.nan, 'bananas', 1, 2.4, 5.6, False, True]) + mixed_dtypes = rng.choice(mixed_dtype_choices, (400, 1)) + + X_with_mixed_dtypes = np.append(X, mixed_dtypes, axis=1) + + features = [str(n) for n in range(11)] + viz = MissingValuesBar(features=features) + viz.fit(X_with_mixed_dtypes, y) + viz.finalize() + + self.assert_images_similar(viz, tol=5) + + @pytest.mark.skipif(pd is None, reason="pandas is required") + def test_missingvaluesbar_pandas_with_mixed_dtypes(self): + """ + Integration test of visualizer with pandas dataframe with mixed dtypes in a single column + """ + X, y = make_classification( + n_samples=400, + n_features=10, + n_informative=2, + n_redundant=3, + n_classes=2, + n_clusters_per_class=2, + random_state=854 + ) + + # add nan values to a range of values in the matrix + X[X > 1.5] = np.nan + + rng = np.random.default_rng(2021) + mixed_dtype_choices = np.array(['apples', 'pears', 'peaches', "", np.nan, 'bananas', 1, 2.4, 5.6, False, True]) + mixed_dtypes = rng.choice(mixed_dtype_choices, (400, 1)) + + X_with_mixed_dtypes = np.append(X, mixed_dtypes, axis=1) + X_ = pd.DataFrame(X_with_mixed_dtypes) + + features = [str(n) for n in range(11)] + viz = MissingValuesBar(features=features) + viz.fit(X_, y) + viz.finalize() + + self.assert_images_similar(viz, tol=5)
MissingValuesBar does not work on categorical columns ## Describe the solution you'd like Currently, I am unable to get MissingValuesBar to work on data that has categorical columns. It is internally trying to convert these columns to a floating point value and producing an error at this step. I am hoping this can be handles internally in the class itself since it is just checking for missing values so it should not care about the type of column. ## Is your feature request related to a problem? Please describe. Described above, but this is the error that I get on categorical data. One of the columns has continent values and it looks like it is producing an error at that point. ```python # Instantiate the visualizer plt.figure(figsize=(15,10)) visualizer = MissingValuesBar(features=features) visualizer.fit(X=data[features], y=data[target].values) # Supply the targets via y _ = visualizer.show() # Finalize and render the figure ``` **Traceback** ``` --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-7-2b58032dfe22> in <module> 3 visualizer = MissingValuesBar(features=features) 4 ----> 5 visualizer.fit(X=data[features], y=data[target].values) # Supply the targets via y 6 _ = visualizer.show() # Finalize and render the figure ~\.conda\envs\ds7337_cs3\lib\site-packages\yellowbrick\contrib\missing\base.py in fit(self, X, y, **kwargs) 70 self.y = y 71 ---> 72 self.draw(X, y, **kwargs) 73 return self 74 ~\.conda\envs\ds7337_cs3\lib\site-packages\yellowbrick\contrib\missing\bar.py in draw(self, X, y, **kwargs) 137 target values. 138 """ --> 139 nan_col_counts = self.get_nan_col_counts() 140 141 # the x locations for the groups ~\.conda\envs\ds7337_cs3\lib\site-packages\yellowbrick\contrib\missing\bar.py in get_nan_col_counts(self, **kwargs) 110 111 else: --> 112 nan_matrix = self.X.astype(np.float) 113 114 if self.y is None: ValueError: could not convert string to float: 'euorpe' ``` **If I just take the numeric features, it works well** ```python # Instantiate the visualizer plt.figure(figsize=(15,10)) visualizer = MissingValuesBar(features=features_numerical) visualizer.fit(X=data[features_numerical], y=data[target].values) # Supply the targets via y _ = visualizer.show() # Finalize and render the figure ``` **See output below** ![image](https://user-images.githubusercontent.com/33585645/100137410-0cb02b00-2e52-11eb-8a0f-04a94c07dfdd.png)
Hi @ngupta23 thank you so much for using Yellowbrick! Sorry it's taken us so long to reply to your issue, it just got buried in the stream of GitHub messages. I apologize for that. Thank you for mentioning the MissingValuesBar visualizer - right now this visualizer is in our `contrib` package since I don't think we fully fleshed it out for prime time use in the package. I believe @ndanielsen was working on it - @ndanielsen do you have any comments? If this visualizer is useful to you, we'd love to have you contribute to our project and help make the visualizer ready for categorical variables and moved out of contrib! Let us know if you're interested and how we can advise you to get started! @ngupta23 thanks for the detailed bug report. I'll take a look at this. My suggestion for the time being is that you encode categorical columns into numeric. For example utilizing the [LabelEncoder in scikit-learn](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html) would resolve this: ``` from sklearn import preprocessing le = preprocessing.LabelEncoder() df['label'] = le.fit_transform(df['label']) ```
2022-04-30T21:59:06
DistrictDataLabs/yellowbrick
1,243
DistrictDataLabs__yellowbrick-1243
[ "148" ]
7e238e109a6a9a3500b646d89cdf37799aab5b7f
diff --git a/docs/gallery.py b/docs/gallery.py --- a/docs/gallery.py +++ b/docs/gallery.py @@ -33,6 +33,7 @@ FreqDistVisualizer, TSNEVisualizer, DispersionPlot, + WordCorrelationPlot, PosTagVisualizer, ) @@ -404,6 +405,15 @@ def dispersion(): savefig(oz, "dispersion") +def word_correlation(): + corpus = load_hobbies() + words = ["Tatsumi Kimishima", "Nintendo", "game", "play", "man", "woman"] + + oz = WordCorrelationPlot(words, ax=newfig()) + oz.fit(corpus.data) + savefig(oz, "word_correlation") + + def postag(): tagged_stanzas = [ [ @@ -622,6 +632,7 @@ def featcorr(): "freqdist": freqdist, "tsne": tsne, "dispersion": dispersion, + "word_correlation": word_correlation, "postag": postag, "decision": decision, "binning": binning, diff --git a/yellowbrick/text/__init__.py b/yellowbrick/text/__init__.py --- a/yellowbrick/text/__init__.py +++ b/yellowbrick/text/__init__.py @@ -22,3 +22,4 @@ from .freqdist import FreqDistVisualizer, freqdist from .postag import PosTagVisualizer from .dispersion import DispersionPlot, dispersion +from .correlation import WordCorrelationPlot, word_correlation diff --git a/yellowbrick/text/correlation.py b/yellowbrick/text/correlation.py new file mode 100644 --- /dev/null +++ b/yellowbrick/text/correlation.py @@ -0,0 +1,349 @@ +# yellowbrick.text.correlation +# Implementation of word correlation for text visualization. +# +# Author: Patrick Deziel +# Created: Sun May 1 19:43:41 2022 -0600 +# +# Copyright (C) 2022 The scikit-yb developers +# For license information, see LICENSE.txt +# +# ID: correlation.py [b652fc9] [email protected] $ + +""" +Implementation of word correlation for text visualization. +""" + + +########################################################################## +## Imports +########################################################################## + +import numpy as np + +from sklearn.feature_extraction.text import CountVectorizer + +from yellowbrick.style import find_text_color +from yellowbrick.text.base import TextVisualizer +from yellowbrick.style.palettes import color_sequence +from yellowbrick.exceptions import YellowbrickValueError + +########################################################################## +## Word Correlation Plot Visualizer +########################################################################## + +class WordCorrelationPlot(TextVisualizer): + """ + Word correlation illustrates the extent to which words in a corpus appear in the + same documents. + + WordCorrelationPlot visualizes the binary correlation between words across + documents as a heatmap. The correlation is defined using the mean square + contingency coefficient (phi-coefficient) between any two words m and n. The + coefficient is a value between -1 and 1, inclusive. A value close to 1 or -1 + indicates strong positive or negative correlation between m and n, while a value + close to 0 indicates little or no correlation. The constructor takes one required + argument, which is the list of words or n-grams to be plotted. + + Parameters + ---------- + words : list of str + The list of words or n-grams to be plotted. The words must be present in the + provided corpus on fit(). + + ignore_case : bool, default: False + If True, all words will be converted to lowercase before processing. + + ax : matplotlib Axes, default: None + The axes to plot the figure on. + + cmap : str or cmap, default: "RdYlBu" + Colormap to use for the heatmap. + + colorbar : bool, default: True + If True, a colorbar will be added to the heatmap. + + fontsize : int, default: None + Font size to use for the labels on the axes. + + kwargs : dict + Pass any additional keyword arguments to the super class. + + Attributes + ---------- + self.doc_term_matrix_ : array of shape (n_docs, n_features) + The computed sparse document-term matrix containing binary values indicating if + a word is present in a document. + + self.num_docs_ : int + The number of observed documents in the corpus. + + self.vocab_ : dict + A dictionary mapping words to their indices in the document-term matrix. + + self.num_features_ : int + The number of features (word labels) in the resulting plot. + + self.correlation_matrix_ : ndarray of shape (n_features, n_features) + The computed matrix containing the phi-coefficients between all features. + """ + def __init__( + self, + words, + ignore_case=False, + ax=None, + cmap="RdYlBu", + colorbar=True, + fontsize=None, + **kwargs + ): + super(WordCorrelationPlot, self).__init__(ax=ax, **kwargs) + + # Visual parameters + self.fontsize = fontsize + self.colorbar = colorbar + self.cmap = color_sequence(cmap) + + # Fitting parameters + self.ignore_case = ignore_case + self.words = self._construct_terms(words, ignore_case) + self.ngram_range = self._compute_ngram_range() + + def _construct_terms(self, words, ignore_case): + """ + Constructs the list of terms to be plotted based on the provided words. This + performs input checking and removes duplicates to produce a list of valid words + for fitting. + """ + # Remove surrounding whitespace + terms = [word.strip() for word in words if len(word.strip()) > 0] + + if len(terms) == 0: + raise YellowbrickValueError("Must provide at least one word to plot.") + + # Convert to lowercase if ignore_case is set + if ignore_case: + terms = [word.lower() for word in terms] + + # Sort and remove duplicates + return sorted(set(terms)) + + def _compute_ngram_range(self): + """ + Computes the n-gram range to use for vectorization based on the provided words. + This allows the user to specify multi-word terms for plotting. + """ + ngrams = [len(word.split()) for word in self.words] + return (min(ngrams), max(ngrams)) + + def _compute_coefficient(self, m, n): + """ + Computes the phi-coefficient for two words m and n, which is a correlation + value between -1 and 1 inclusive. + """ + m_col = self.doc_term_matrix_.getcol(self.vocab_[m]) + n_col = self.doc_term_matrix_.getcol(self.vocab_[n]) + both = m_col.multiply(n_col).sum() + m_total = m_col.sum() + n_total = n_col.sum() + only_m = m_total - both + only_n = n_total - both + neither = self.num_docs_ - both - only_m - only_n + return ((both * neither) - (only_m * only_n)) / np.sqrt(m_total * n_total * (self.num_docs_ - m_total) * (self.num_docs_ - n_total)) + + def fit(self, X, y=None): + """ + The fit method is the primary drawing input for the word correlation + visualization. + + Parameters + ---------- + X : list of str or generator + Should be provided as a list of strings or a generator yielding strings + that represent the documents in the corpus. + + y : None + Labels are not used for the word correlation visualization. + + Returns + ------- + self: instance + Returns the instance of the transformer/visualizer. + + Attributes + ---------- + self.doc_term_matrix_ : array of shape (n_docs, n_features) + The computed sparse document-term matrix containing binary values + indicating if a word is present in a document. + + self.num_docs_ : int + The number of observed documents in the corpus. + + self.vocab_ : dict + A dictionary mapping words to their indices in the document-term matrix. + + self.num_features_ : int + The number of features (word labels) in the resulting plot. + + self.correlation_matrix_ : ndarray of shape (n_features, n_features) + The computed matrix containing the phi-coefficients between all features. + """ + + # Instantiate the CountVectorizer + vecs = CountVectorizer( + vocabulary=self.words, + lowercase=self.ignore_case, + ngram_range=self.ngram_range, + binary=True + ) + + # Get the binary document counts for the target words + self.doc_term_matrix_ = vecs.fit_transform(X) + self.num_docs_ = self.doc_term_matrix_.shape[0] + self.vocab_ = vecs.vocabulary_ + + # Verify that all target words exist in the corpus + for word in self.words: + if self.doc_term_matrix_.getcol(self.vocab_[word]).sum() == 0: + raise YellowbrickValueError("Word '{}' does not exist in the corpus.".format(word)) + + # Compute the phi-coefficient for each pair of words + self.num_features_ = len(self.words) + self.correlation_matrix_ = np.zeros((self.num_features_, self.num_features_)) + for i, m in enumerate(self.words): + for j, n in enumerate(self.words): + self.correlation_matrix_[i, j] = self._compute_coefficient(m, n) + + self.draw(X) + return self + + def draw(self, X): + """ + Called from the fit() method, this metod draws the heatmap on the figure using + the computed correlation matrix. + """ + + # Use correlation matrix data for the heatmap + wc_display = self.correlation_matrix_ + + # Set up the dimensions of the pcolormesh + X, Y = np.arange(self.num_features_ + 1), np.arange(self.num_features_ + 1) + self.ax.set_ylim(bottom=0, top=wc_display.shape[0]) + self.ax.set_xlim(left=0, right=wc_display.shape[1]) + + # Set the words as the tick labels on the plot. The Y-axis is sorted from top + # to bottom, the X-axis is sorted from left to right. + xticklabels = self.words + yticklabels = self.words[::-1] + ticks = np.arange(self.num_features_) + 0.5 + self.ax.set(xticks=ticks, yticks=ticks) + self.ax.set_xticklabels(xticklabels, rotation="vertical", fontsize=self.fontsize) + self.ax.set_yticklabels(yticklabels, fontsize=self.fontsize) + + # Flip the Y-axis values so that they match the sorted labels + wc_display = np.flipud(wc_display) + + # Draw the labels in each heatmap cell + for x in X[:-1]: + for y in Y[:-1]: + # Get the correlation value for the cell + value = wc_display[x, y] + svalue = "{:.2f}".format(value) + + # Get a compatible text color for the cell + base_color = self.cmap(value / 2 + 0.5) + text_color = find_text_color(base_color) + + # Draw the text at the center of the cell + # Note: x and y coordinates are swapped to match the pcolormesh + cx, cy = y + 0.5, x + 0.5 + self.ax.text(cx, cy, svalue, va="center", ha="center", color=text_color, fontsize=self.fontsize) + + # Draw the heatmap + g = self.ax.pcolormesh(X, Y, wc_display, cmap=self.cmap, vmin=-1, vmax=1) + + # Add the color bar + if self.colorbar: + self.ax.figure.colorbar(g, ax=self.ax) + + return self.ax + + def finalize(self): + """ + Prepares the figure for rendering by adding the title. This method is usually + called from show() and not directly by the user. + """ + self.set_title("Word Correlation Plot") + self.fig.tight_layout() + +########################################################################## +## Quick Method +########################################################################## + +def word_correlation( + words, + corpus, + ignore_case=True, + ax=None, + cmap="RdYlBu", + show=True, + colorbar=True, + fontsize=None, + **kwargs +): + """Word Correlation + + Displays the binary correlation between the given words across the documents in a + corpus. + For a list of words with length n, this produces an n x n heatmap of correlation + values in the range [-1, 1]. + + Parameters + ---------- + + words : list of str + The corpus words to display in the heatmap. + corpus : list of str or generator + The corpus as a list of documents or a generator yielding documents. + + ignore_case : bool, default: True + If True, all words will be converted to lowercase before proessing. + + ax : matplotlib axes, default: None + The axes to plot the figure on. + + cmap : str, default: "RdYlBu" + Colormap to use for the heatmap. + + show : bool, default: True + If True, calls ``show()``, which in turn calls ``plt.show()`` however + you cannot call ``plt.savefig`` from this signature, nor + ``clear_figure``. If False, simply calls ``finalize()`` + + colorbar : bool, default: True + If True, adds a colorbar to the figure. + + fontsize : int, default: None + If not None, sets the font size of the labels. + """ + # Instantiate the visualizer + visualizer = WordCorrelationPlot( + words=words, + lowercase=ignore_case, + ax=ax, + cmap=cmap, + colorbar=colorbar, + fontsize=fontsize, + **kwargs + ) + + # Fit and transform the visualizer (calls draw) + visualizer.fit(corpus) + + # Draw the final visualization + if show: + visualizer.show() + else: + visualizer.finalize() + + # Return the visualizer + return visualizer \ No newline at end of file
diff --git a/tests/baseline_images/test_text/test_correlation/test_quick_method.png b/tests/baseline_images/test_text/test_correlation/test_quick_method.png new file mode 100644 Binary files /dev/null and b/tests/baseline_images/test_text/test_correlation/test_quick_method.png differ diff --git a/tests/baseline_images/test_text/test_correlation/test_word_correlation_generator.png b/tests/baseline_images/test_text/test_correlation/test_word_correlation_generator.png new file mode 100644 Binary files /dev/null and b/tests/baseline_images/test_text/test_correlation/test_word_correlation_generator.png differ diff --git a/tests/baseline_images/test_text/test_correlation/test_word_correlation_ignore_case.png b/tests/baseline_images/test_text/test_correlation/test_word_correlation_ignore_case.png new file mode 100644 Binary files /dev/null and b/tests/baseline_images/test_text/test_correlation/test_word_correlation_ignore_case.png differ diff --git a/tests/baseline_images/test_text/test_correlation/test_word_correlation_ngrams.png b/tests/baseline_images/test_text/test_correlation/test_word_correlation_ngrams.png new file mode 100644 Binary files /dev/null and b/tests/baseline_images/test_text/test_correlation/test_word_correlation_ngrams.png differ diff --git a/tests/baseline_images/test_text/test_correlation/test_word_correlation_plot.png b/tests/baseline_images/test_text/test_correlation/test_word_correlation_plot.png new file mode 100644 Binary files /dev/null and b/tests/baseline_images/test_text/test_correlation/test_word_correlation_plot.png differ diff --git a/tests/test_text/test_correlation.py b/tests/test_text/test_correlation.py new file mode 100644 --- /dev/null +++ b/tests/test_text/test_correlation.py @@ -0,0 +1,120 @@ +# tests.test_text.test_correlation +# Tests for the dispersion plot visualization +# +# Author: Patrick Deziel +# Created: Tue May 3 16:18:21 2022 -0500 +# +# Copyright (C) 2022 The scikit-yb developers +# For license information, see LICENSE.txt +# +# ID: test_correlation.py [0a7d2fe] [email protected] $ + +""" +Tests for the word correlation plot text visualization +""" + +########################################################################## +## Imports +########################################################################## + +import pytest +import matplotlib.pyplot as plt + +from tests.base import VisualTestCase +from yellowbrick.datasets import load_hobbies +from yellowbrick.exceptions import YellowbrickValueError +from yellowbrick.text.correlation import WordCorrelationPlot, word_correlation + +########################################################################## +## Data +########################################################################## + +corpus = load_hobbies() + +########################################################################## +## WordCorrelationPlot Tests +########################################################################## + +class TestWordCorrelationPlot(VisualTestCase): + def test_quick_method(self): + """ + Assert no errors occur when using the quick method. + """ + _, ax = plt.subplots() + words = ["Game", "player", "score", "oil"] + + viz = word_correlation(words, corpus.data, ax=ax, show=False) + + self.assert_images_similar(viz, tol=25) + + def test_word_correlation_plot(self): + """ + Assert no errors are raised during normal execution. + """ + words = ["Game", "player", "score", "oil", "Man"] + + viz = WordCorrelationPlot(words) + assert viz.fit(corpus.data) is viz, "fit method should return self" + + self.assert_images_similar(viz, tol=25) + + def test_word_correlation_generator(self): + """ + Assert no errors are raised when the corpus is a generator. + """ + words = ["Game", "player", "score", "oil", "Man", "woman"] + + viz = WordCorrelationPlot(words) + + def stream_corpus(data): + for doc in data: + yield doc + viz.fit(stream_corpus(corpus.data)) + + self.assert_images_similar(viz, tol=25) + + def test_word_correlation_ignore_case(self): + """ + Assert no errors are raised when ignore_case is True. + """ + words = ["Game", "player", "score", "oil", "game"] + + viz = WordCorrelationPlot(words, ignore_case=True) + viz.fit(corpus.data) + + self.assert_images_similar(viz, tol=25) + + def test_word_correlation_ngrams(self): + """ + Assert no errors are raised when multiple-word terms are provided. + """ + words = ["Tatsumi Kimishima", "Nintendo", "game", "man", "play"] + + viz = WordCorrelationPlot(words) + viz.fit(corpus.data) + + self.assert_images_similar(viz, tol=25) + + def test_word_correlation_no_words(self): + """ + Assert that an error is raised when no words are provided. + """ + with pytest.raises(YellowbrickValueError): + WordCorrelationPlot([]) + + with pytest.raises(YellowbrickValueError): + WordCorrelationPlot([""]) + + with pytest.raises(YellowbrickValueError): + WordCorrelationPlot([" ", "\t", "\n"]) + + def test_word_correlation_missing_words(self): + """ + Assert that an error is raised on fit() when a word does not exist in the + corpus. + """ + words = ["Game", "player", "score", "oil", "NotACorpusWord"] + + viz = WordCorrelationPlot(words) + with pytest.raises(YellowbrickValueError): + viz.fit(corpus.data) \ No newline at end of file
WordCorrelationPlot Implement a `WordCorrelationPlot` that enables users to visualize the correlations between a word and other words in the corpus, similar to what is available in [ggplot2](http://stackoverflow.com/questions/19549280/plot-highly-correlated-words-against-a-specific-word-of-interest).
[See also](https://trinkerrstuff.wordpress.com/2014/03/14/qdap-1-3-1-release-demoing-dispersion-plots-sentiment-analysis-easy-hash-lookups-boolean-searches-and-more/) @rebeccabilbro sounds like something ICX might be interested in?
2022-05-02T02:09:10
DistrictDataLabs/yellowbrick
1,247
DistrictDataLabs__yellowbrick-1247
[ "1246", "1246" ]
d2bafd7a356fa6b8ec7450051f01bb881fd6adbf
diff --git a/yellowbrick/classifier/classification_report.py b/yellowbrick/classifier/classification_report.py --- a/yellowbrick/classifier/classification_report.py +++ b/yellowbrick/classifier/classification_report.py @@ -190,8 +190,11 @@ def score(self, X, y): # Call super to check if fitted and to compute self.score_ super(ClassificationReport, self).score(X, y) + # Labels must be a data type that works with np.isnan + labels = range(len(self.classes_)) + y_pred = self.predict(X) - scores = precision_recall_fscore_support(y, y_pred) + scores = precision_recall_fscore_support(y, y_pred, labels=labels) # Calculate the percentage for the support metric # and store the percent in place of raw support counts
diff --git a/tests/test_classifier/test_classification_report.py b/tests/test_classifier/test_classification_report.py --- a/tests/test_classifier/test_classification_report.py +++ b/tests/test_classifier/test_classification_report.py @@ -327,6 +327,28 @@ def test_remove_color_bar(self): self.assert_images_similar(viz, tol=40) + def test_with_missing_labels(self): + """ + Test that visualizer properly handles missing labels when scoring + """ + _, ax = plt.subplots() + + X_train = np.array([[1], [2], [3]]) + y_train = np.array([0, 1, 2]) + + X_test = np.array([[1], [2]]) + y_test = np.array([0, 1]) + + viz = ClassificationReport(LogisticRegression(), ax=ax) + viz.fit(X_train, y_train) + viz.score(X_test, y_test) + + assert viz.scores_ == { + "precision": {0: approx(1.0), 1: approx(1.0), 2: approx(0.0)}, + "recall": {0: approx(1.0), 1: approx(1.0), 2: approx(0.0)}, + "f1": {0: approx(1.0), 1: approx(1.0), 2: approx(0.0)}, + } + def test_within_pipeline(self): """ Test that visualizer can be accessed within a sklearn pipeline @@ -409,4 +431,4 @@ def test_pipeline_as_model_input_quickmethod(self): X_train, y_train, X_test, y_test, classes=["vacant", "occupied"], show=False) - self.assert_images_similar(oz, tol=15) \ No newline at end of file + self.assert_images_similar(oz, tol=15)
Issue with classification_report function when there are missing labels during scoring **Describe the bug** Yellowbrick's classification_report function crashes when there are missing labels during scoring. **To Reproduce** ```python import numpy as np from sklearn.linear_model import LogisticRegression from yellowbrick.classifier.classification_report import ClassificationReport X_train = np.array([[1, 2], [1, 2], [1, 2]]) y_train = np.array([0, 1, 2]) X_test = np.array([[1, 2], [1, 2]]) y_test = np.array([0, 1]) viz = ClassificationReport(LogisticRegression()) viz.fit(X_train, y_train) viz.score(X_test, y_test) viz.show() ``` **Expected behavior** The classification report should not crash and instead generate a valid plot with a value of 0 for labels not present in the test data. **Traceback** ``` Traceback (most recent call last): File ".\test.py", line 13, in <module> viz.score(X_test, y_test) File "C:\Users\*\AppData\Local\Programs\Anaconda3\envs\*\lib\site-packages\yellowbrick\classifier\classification_report.py", line 210, in score self.draw() File "C:\Users\*\AppData\Local\Programs\Anaconda3\envs\*\lib\site-packages\yellowbrick\classifier\classification_report.py", line 223, in draw cr_display[idx, jdx] = self.scores_[metric][cls] KeyError: 2 ``` **Desktop** - OS: Windows 10 - Python Version 3.8.13 - Yellowbrick Version 1.4 Issue with classification_report function when there are missing labels during scoring **Describe the bug** Yellowbrick's classification_report function crashes when there are missing labels during scoring. **To Reproduce** ```python import numpy as np from sklearn.linear_model import LogisticRegression from yellowbrick.classifier.classification_report import ClassificationReport X_train = np.array([[1, 2], [1, 2], [1, 2]]) y_train = np.array([0, 1, 2]) X_test = np.array([[1, 2], [1, 2]]) y_test = np.array([0, 1]) viz = ClassificationReport(LogisticRegression()) viz.fit(X_train, y_train) viz.score(X_test, y_test) viz.show() ``` **Expected behavior** The classification report should not crash and instead generate a valid plot with a value of 0 for labels not present in the test data. **Traceback** ``` Traceback (most recent call last): File ".\test.py", line 13, in <module> viz.score(X_test, y_test) File "C:\Users\*\AppData\Local\Programs\Anaconda3\envs\*\lib\site-packages\yellowbrick\classifier\classification_report.py", line 210, in score self.draw() File "C:\Users\*\AppData\Local\Programs\Anaconda3\envs\*\lib\site-packages\yellowbrick\classifier\classification_report.py", line 223, in draw cr_display[idx, jdx] = self.scores_[metric][cls] KeyError: 2 ``` **Desktop** - OS: Windows 10 - Python Version 3.8.13 - Yellowbrick Version 1.4
2022-05-13T18:11:19
DistrictDataLabs/yellowbrick
1,251
DistrictDataLabs__yellowbrick-1251
[ "1232" ]
233d9d1686dd34cfdc013b5396af585dad83d565
diff --git a/yellowbrick/cluster/elbow.py b/yellowbrick/cluster/elbow.py --- a/yellowbrick/cluster/elbow.py +++ b/yellowbrick/cluster/elbow.py @@ -186,7 +186,7 @@ class KElbowVisualizer(ClusteringScoreVisualizer): - **calinski_harabasz**: ratio of within to between cluster dispersion distance_metric : str or callable, default='euclidean' - The metric to use when calculating distance between instances in a + The metric to use when calculating distance between instances in a feature array. If metric is a string, it must be one of the options allowed by sklearn's metrics.pairwise.pairwise_distances. If X is the distance array itself, use metric="precomputed". @@ -280,6 +280,7 @@ def __init__( ) # Store the arguments + self.k = k self.scoring_metric = KELBOW_SCOREMAP[metric] self.metric = metric self.timings = timings @@ -293,50 +294,41 @@ def __init__( CVLINE: LINE_COLOR, } - # Convert K into a tuple argument if an integer - if isinstance(k, int): - self.k_values_ = list(range(2, k + 1)) + def fit(self, X, y=None, **kwargs): + """ + Fits n KMeans models where n is the length of ``self.k_values_``, + storing the silhouette scores in the ``self.k_scores_`` attribute. + The "elbow" and silhouette score corresponding to it are stored in + ``self.elbow_value`` and ``self.elbow_score`` respectively. + This method finishes up by calling draw to create the plot. + """ + # Convert K into a tuple argument if an integer + if isinstance(self.k, int): + self.k_values_ = list(range(2, self.k + 1)) elif ( - isinstance(k, tuple) - and len(k) == 2 - and all(isinstance(x, (int, np.integer)) for x in k) + isinstance(self.k, tuple) + and len(self.k) == 2 + and all(isinstance(x, (int, np.integer)) for x in self.k) ): - self.k_values_ = list(range(*k)) - elif isinstance(k, Iterable) and all( - isinstance(x, (int, np.integer)) for x in k + self.k_values_ = list(range(*self.k)) + elif isinstance(self.k, Iterable) and all( + isinstance(x, (int, np.integer)) for x in self.k ): - self.k_values_ = list(k) + self.k_values_ = list(self.k) else: raise YellowbrickValueError( ( "Specify an iterable of integers, a range, or maximal K value," - " the value '{}' is not a valid argument for K.".format(k) + " the value '{}' is not a valid argument for K.".format(self.k) ) ) - # Holds the values of the silhoutte scores - self.k_scores_ = None - - # Set Default Elbow Value - self.elbow_value_ = None - - def fit(self, X, y=None, **kwargs): - """ - Fits n KMeans models where n is the length of ``self.k_values_``, - storing the silhouette scores in the ``self.k_scores_`` attribute. - The "elbow" and silhouette score corresponding to it are stored in - ``self.elbow_value`` and ``self.elbow_score`` respectively. - This method finishes up by calling draw to create the plot. - """ - self.k_scores_ = [] self.k_timers_ = [] self.kneedle = None self.knee_value = None - - if self.locate_elbow: - self.elbow_value_ = None - self.elbow_score_ = None + self.elbow_value_ = None + self.elbow_score_ = None for k in self.k_values_: # Compute the start time for each model @@ -527,7 +519,7 @@ def kelbow_visualizer( - **calinski_harabasz**: ratio of within to between cluster dispersion distance_metric : str or callable, default='euclidean' - The metric to use when calculating distance between instances in a + The metric to use when calculating distance between instances in a feature array. If metric is a string, it must be one of the options allowed by sklearn's metrics.pairwise.pairwise_distances. If X is the distance array itself, use metric="precomputed". diff --git a/yellowbrick/model_selection/dropping_curve.py b/yellowbrick/model_selection/dropping_curve.py --- a/yellowbrick/model_selection/dropping_curve.py +++ b/yellowbrick/model_selection/dropping_curve.py @@ -243,7 +243,7 @@ def fit(self, X, y=None): # compute the mean and standard deviation of the training data self.train_scores_mean_ = np.mean(self.train_scores_, axis=1) self.train_scores_std_ = np.std(self.train_scores_, axis=1) - + # compute the mean and standard deviation of the validation data self.valid_scores_mean_ = np.mean(self.valid_scores_, axis=1) self.valid_scores_std_ = np.std(self.valid_scores_, axis=1) diff --git a/yellowbrick/utils/wrapper.py b/yellowbrick/utils/wrapper.py --- a/yellowbrick/utils/wrapper.py +++ b/yellowbrick/utils/wrapper.py @@ -17,6 +17,8 @@ ## Wrapper Class ########################################################################## +from yellowbrick.exceptions import YellowbrickAttributeError, YellowbrickTypeError + class Wrapper(object): """ @@ -38,5 +40,11 @@ def __init__(self, obj): self._wrapped = obj def __getattr__(self, attr): + if self is self._wrapped: + raise YellowbrickTypeError("wrapper cannot wrap itself or recursion will occur") + # proxy to the wrapped object - return getattr(self._wrapped, attr) + try: + return getattr(self._wrapped, attr) + except AttributeError as e: + raise YellowbrickAttributeError(f"neither visualizer '{self.__class__.__name__}' nor wrapped estimator '{type(self._wrapped).__name__}' have attribute '{attr}'") from e
diff --git a/examples/bbengfort/testing.ipynb b/examples/bbengfort/testing.ipynb --- a/examples/bbengfort/testing.ipynb +++ b/examples/bbengfort/testing.ipynb @@ -1,550 +1,397 @@ { "cells": [ - { - "cell_type": "markdown", - "metadata": { - "deletable": true, - "editable": true - }, - "source": [ - "# Visual Diagnosis of Text Analysis with Baleen \n", - "\n", - "This notebook has been created as part of the [Yellowbrick user study](http://www.scikit-yb.org/en/latest/evaluation.html). I hope to explore how visual methods might improve the workflow of text classification on a small to medium sized corpus. \n", - "\n", - "## Dataset \n", - "\n", - "The dataset used in this study is a sample of the [Baleen Corpus](http://baleen.districtdatalabs.com/). The Baleen corpus has been ingesting RSS feeds on the hour from a variety of topical feeds since March 2016, including news, hobbies, and political documents and currently has over 1.2M posts from 373 feeds. [Baleen](https://github.com/bbengfort/baleen) (an open source system) has a sister library called [Minke](https://github.com/bbengfort/minke) that provides multiprocessing support for dealing with Gigabytes worth of text. \n", - "\n", - "The dataset I'll use in this study is a sample of the larger data set that contains 68,052 or roughly 6% of the total corpus. For this test, I've chosen to use the preprocessed corpus, which means I won't have to do any tokenization, but can still apply normalization techniques. The corpus is described as follows:\n", - "\n", - "Baleen corpus contains 68,052 files in 12 categories.\n", - "Structured as:\n", - "\n", - "- 1,200,378 paragraphs (17.639 mean paragraphs per file)\n", - "- 2,058,635 sentences (1.715 mean sentences per paragraph).\n", - "\n", - "Word count of 44,821,870 with a vocabulary of 303,034 (147.910 lexical diversity).\n", - "\n", - "Category Counts: \n", - "\n", - "- books: 1,700 docs\n", - "- business: 9,248 docs\n", - "- cinema: 2,072 docs\n", - "- cooking: 733 docs\n", - "- data science: 692 docs\n", - "- design: 1,259 docs\n", - "- do it yourself: 2,620 docs\n", - "- gaming: 2,884 docs\n", - "- news: 33,253 docs\n", - "- politics: 3,793 docs\n", - "- sports: 4,710 docs\n", - "- tech: 5,088 docs\n", - "\n", - "This is quite a lot of data, so for now we'll simply create a classifier for the \"hobbies\" categories: e.g. books, cinema, cooking, diy, gaming, and sports. \n", - "\n", - "Note: this data set is not currently publically available, but I am happy to provide it on request. " - ] - }, { "cell_type": "code", "execution_count": 1, - "metadata": { - "collapsed": true, - "deletable": true, - "editable": true - }, - "outputs": [], - "source": [ - "%matplotlib inline " - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": { - "collapsed": true, - "deletable": true, - "editable": true - }, + "id": "3e15c26c", + "metadata": {}, "outputs": [], "source": [ - "import os \n", "import sys \n", - "import nltk\n", - "import pickle\n", + "sys.path.append(\"../..\")\n", + "\n", + "import numpy as np\n", + "import yellowbrick as yb \n", + "import matplotlib.pyplot as plt \n", "\n", - "# To import yellowbrick \n", - "sys.path.append(\"../..\")" + "from sklearn.cluster import KMeans\n", + "from yellowbrick.cluster import KElbowVisualizer" ] }, { - "cell_type": "markdown", - "metadata": { - "deletable": true, - "editable": true - }, + "cell_type": "code", + "execution_count": 2, + "id": "6f04357a", + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "<style>#sk-container-id-1 {color: black;background-color: white;}#sk-container-id-1 pre{padding: 0;}#sk-container-id-1 div.sk-toggleable {background-color: white;}#sk-container-id-1 label.sk-toggleable__label {cursor: pointer;display: block;width: 100%;margin-bottom: 0;padding: 0.3em;box-sizing: border-box;text-align: center;}#sk-container-id-1 label.sk-toggleable__label-arrow:before {content: \"▸\";float: left;margin-right: 0.25em;color: #696969;}#sk-container-id-1 label.sk-toggleable__label-arrow:hover:before {color: black;}#sk-container-id-1 div.sk-estimator:hover label.sk-toggleable__label-arrow:before {color: black;}#sk-container-id-1 div.sk-toggleable__content {max-height: 0;max-width: 0;overflow: hidden;text-align: left;background-color: #f0f8ff;}#sk-container-id-1 div.sk-toggleable__content pre {margin: 0.2em;color: black;border-radius: 0.25em;background-color: #f0f8ff;}#sk-container-id-1 input.sk-toggleable__control:checked~div.sk-toggleable__content {max-height: 200px;max-width: 100%;overflow: auto;}#sk-container-id-1 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {content: \"▾\";}#sk-container-id-1 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 input.sk-hidden--visually {border: 0;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);height: 1px;margin: -1px;overflow: hidden;padding: 0;position: absolute;width: 1px;}#sk-container-id-1 div.sk-estimator {font-family: monospace;background-color: #f0f8ff;border: 1px dotted black;border-radius: 0.25em;box-sizing: border-box;margin-bottom: 0.5em;}#sk-container-id-1 div.sk-estimator:hover {background-color: #d4ebff;}#sk-container-id-1 div.sk-parallel-item::after {content: \"\";width: 100%;border-bottom: 1px solid gray;flex-grow: 1;}#sk-container-id-1 div.sk-label:hover label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 div.sk-serial::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: 0;}#sk-container-id-1 div.sk-serial {display: flex;flex-direction: column;align-items: center;background-color: white;padding-right: 0.2em;padding-left: 0.2em;position: relative;}#sk-container-id-1 div.sk-item {position: relative;z-index: 1;}#sk-container-id-1 div.sk-parallel {display: flex;align-items: stretch;justify-content: center;background-color: white;position: relative;}#sk-container-id-1 div.sk-item::before, #sk-container-id-1 div.sk-parallel-item::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: -1;}#sk-container-id-1 div.sk-parallel-item {display: flex;flex-direction: column;z-index: 1;position: relative;background-color: white;}#sk-container-id-1 div.sk-parallel-item:first-child::after {align-self: flex-end;width: 50%;}#sk-container-id-1 div.sk-parallel-item:last-child::after {align-self: flex-start;width: 50%;}#sk-container-id-1 div.sk-parallel-item:only-child::after {width: 0;}#sk-container-id-1 div.sk-dashed-wrapped {border: 1px dashed gray;margin: 0 0.4em 0.5em 0.4em;box-sizing: border-box;padding-bottom: 0.4em;background-color: white;}#sk-container-id-1 div.sk-label label {font-family: monospace;font-weight: bold;display: inline-block;line-height: 1.2em;}#sk-container-id-1 div.sk-label-container {text-align: center;}#sk-container-id-1 div.sk-container {/* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */display: inline-block !important;position: relative;}#sk-container-id-1 div.sk-text-repr-fallback {display: none;}</style><div id=\"sk-container-id-1\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>KElbowVisualizer(ax=&lt;AxesSubplot:&gt;, estimator=KMeans(), k=(2, 12))</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item sk-dashed-wrapped\"><div class=\"sk-label-container\"><div class=\"sk-label sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-1\" type=\"checkbox\" ><label for=\"sk-estimator-id-1\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">KElbowVisualizer</label><div class=\"sk-toggleable__content\"><pre>KElbowVisualizer(ax=&lt;AxesSubplot:&gt;, estimator=KMeans(), k=(2, 12))</pre></div></div></div><div class=\"sk-parallel\"><div class=\"sk-parallel-item\"><div class=\"sk-item\"><div class=\"sk-label-container\"><div class=\"sk-label sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-2\" type=\"checkbox\" ><label for=\"sk-estimator-id-2\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">estimator: KMeans</label><div class=\"sk-toggleable__content\"><pre>KMeans()</pre></div></div></div><div class=\"sk-serial\"><div class=\"sk-item\"><div class=\"sk-estimator sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-3\" type=\"checkbox\" ><label for=\"sk-estimator-id-3\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">KMeans</label><div class=\"sk-toggleable__content\"><pre>KMeans()</pre></div></div></div></div></div></div></div></div></div></div>" + ], + "text/plain": [ + "KElbowVisualizer(ax=<AxesSubplot:>, estimator=KMeans(), k=(2, 12))" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + }, + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXkAAAD7CAYAAACPDORaAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8qNh9FAAAACXBIWXMAAAsTAAALEwEAmpwYAAANt0lEQVR4nO3cf4ichZnA8W82a3ahTbRF6EnhaAv1QVi0sLYmXqxXqJ6RCqH4R7FQLpCqtHC9puBFDrQFr+WwuZb+IaVX5OC4o3iUoL2WSKEc1WhoGEtxsT5hBYsULW3RREudmN3cHzPLjGF3fmVnZn36/YCQd97Z2YfH5JvX2Xnddv78eSRJNc1MewBJ0vgYeUkqzMhLUmFGXpIKM/KSVJiRl6TCBop8RFwXEf+3zuO3RcTJiHg6Ij6/6dNJki5K38hHxD3A94H5Cx6/BPgWcDNwI3BnRLxvHENKkkYzO8BzXgA+DfznBY9fBSxn5qsAEfEk8HHgfzZ6oUajMQd8FHgZWBllYEn6C7QduAI4ubi42BzmC/tGPjN/GBEfWOfULuB01/HrwKV9Xu6jwBMDTydJ6nYD8OQwXzDIlfxGzgA7u453Aq/1+ZqXAa688kp27NhxEd+6hqWlJRYWFqY9xpbgLj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": "light" + }, + "output_type": "display_data" + } + ], "source": [ - "### Loading Data \n", - "\n", - "In order to load data, I'd typically use a `CorpusReader`. However, for the sake of simplicity, I'll load data using some simple Python generator functions. I need to create two primary methods, the first loads the documents using pickle, and the second returns the vector of targets for supervised learning. " + "visualizer = KElbowVisualizer(KMeans(), k=(2,12))\n", + "visualizer" ] }, { "cell_type": "code", "execution_count": 3, - "metadata": { - "collapsed": false, - "deletable": true, - "editable": true - }, + "id": "a8eb2417", + "metadata": {}, "outputs": [], "source": [ - "CORPUS_ROOT = os.path.join(os.getcwd(), \"data\") \n", - "CATEGORIES = [\"books\", \"cinema\", \"cooking\", \"diy\", \"gaming\", \"sports\"]\n", - "\n", - "def fileids(root=CORPUS_ROOT, categories=CATEGORIES): \n", - " \"\"\"\n", - " Fetch the paths, filtering on categories (pass None for all). \n", - " \"\"\"\n", - " for name in os.listdir(root):\n", - " dpath = os.path.join(root, name)\n", - " if not os.path.isdir(dpath):\n", - " continue \n", - " \n", - " if categories and name in categories: \n", - " for fname in os.listdir(dpath):\n", - " yield os.path.join(dpath, fname)\n", - "\n", - "\n", - "def documents(root=CORPUS_ROOT, categories=CATEGORIES):\n", - " \"\"\"\n", - " Load the pickled documents and yield one at a time. \n", - " \"\"\"\n", - " for path in fileids(root, categories):\n", - " with open(path, 'rb') as f:\n", - " yield pickle.load(f)\n", - "\n", - "\n", - "def labels(root=CORPUS_ROOT, categories=CATEGORIES):\n", - " \"\"\"\n", - " Return a list of the labels associated with each document. \n", - " \"\"\" \n", - " for path in fileids(root, categories):\n", - " dpath = os.path.dirname(path) \n", - " yield dpath.split(os.path.sep)[-1]" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "deletable": true, - "editable": true - }, - "source": [ - "### Feature Extraction and Normalization \n", - "\n", - "In order to conduct analyses with Scikit-Learn, I'll need some helper transformers to modify the loaded data into a form that can be used by the `sklearn.feature_extraction` text transformers. I'll be mostly using the `CountVectorizer` and `TfidfVectorizer`, so these normalizer transformers and identity functions help a lot. " + "from yellowbrick.utils.wrapper import Wrapper\n", + "from yellowbrick.base import Visualizer" ] }, { "cell_type": "code", "execution_count": 4, - "metadata": { - "collapsed": false, - "deletable": true, - "editable": true - }, + "id": "b1664801", + "metadata": {}, "outputs": [], "source": [ - "from nltk.corpus import wordnet as wn\n", - "from nltk.stem import WordNetLemmatizer \n", - "from unicodedata import category as ucat\n", - "from nltk.corpus import stopwords as swcorpus\n", - "from sklearn.base import BaseEstimator, TransformerMixin \n", - "\n", - "\n", - "def identity(args):\n", - " \"\"\"\n", - " The identity function is used as the \"tokenizer\" for \n", - " pre-tokenized text. It just passes back it's arguments. \n", - " \"\"\"\n", - " return args \n", - "\n", - "\n", - "def is_punctuation(token):\n", - " \"\"\"\n", - " Returns true if all characters in the token are\n", - " unicode punctuation (works for most punct). \n", - " \"\"\"\n", - " return all(\n", - " ucat(c).startswith('P')\n", - " for c in token \n", - " )\n", - "\n", - "\n", - "def wnpos(tag):\n", - " \"\"\"\n", - " Returns the wn part of speech tag from the penn treebank tag. \n", - " \"\"\"\n", - " return {\n", - " \"N\": wn.NOUN,\n", - " \"V\": wn.VERB,\n", - " \"J\": wn.ADJ, \n", - " \"R\": wn.ADV, \n", - " }.get(tag[0], wn.NOUN)\n", - "\n", - "\n", - "class TextNormalizer(BaseEstimator, TransformerMixin):\n", - " \n", - " def __init__(self, stopwords='english', lowercase=True, lemmatize=True, depunct=True):\n", - " self.stopwords = frozenset(swcorpus.words(stopwords)) if stopwords else frozenset()\n", - " self.lowercase = lowercase \n", - " self.depunct = depunct \n", - " self.lemmatizer = WordNetLemmatizer() if lemmatize else None \n", + "class Outer(Visualizer, Wrapper):\n", " \n", - " def fit(self, docs, labels=None):\n", - " return self\n", - "\n", - " def transform(self, docs): \n", - " for doc in docs: \n", - " yield list(self.normalize(doc)) \n", + " def __init__(self, estimator):\n", + " self.estimator = estimator\n", + " Wrapper.__init__(self, self.estimator)\n", + " Visualizer.__init__(self, ax=None, fig=None)\n", " \n", - " def normalize(self, doc):\n", - " for paragraph in doc:\n", - " for sentence in paragraph:\n", - " for token, tag in sentence: \n", - " if token.lower() in self.stopwords:\n", - " continue \n", - " \n", - " if self.depunct and is_punctuation(token):\n", - " continue \n", - " \n", - " if self.lowercase:\n", - " token = token.lower() \n", - " \n", - " if self.lemmatizer:\n", - " token = self.lemmatizer.lemmatize(token, wnpos(tag))\n", - " \n", - " yield token " + " def get_params(self, deep=True):\n", + " \"\"\"\n", + " After v0.24 - scikit-learn is able to determine that ``self.estimator`` is\n", + " nested and fetches its params using ``estimator__param``. This functionality is\n", + " pretty cool but it's a pretty big overhaul to change our \"wrapped\" estimator API\n", + " to a \"nested\" estimator API, therefore we override ``get_params`` to flatten out\n", + " the estimator params.\n", + " \"\"\"\n", + " params = super(Outer, self).get_params(deep=deep)\n", + " for param in list(params.keys()):\n", + " if param.startswith(\"estimator__\"):\n", + " params[param[len(\"estimator__\"):]] = params.pop(param)\n", + " return params" ] }, { - "cell_type": "markdown", - "metadata": { - "deletable": true, - "editable": true - }, + "cell_type": "code", + "execution_count": 5, + "id": "73ff50c2", + "metadata": {}, + "outputs": [], "source": [ - "### Corpus Analysis \n", - "\n", - "At this stage, I'd like to get a feel for what was in my corpus, so that I can start thinking about how to best vectorize the text and do different types of counting. With the Yellowbrick 0.3.3 release, support has been added for two text visualizers, which I think I will test out at scale using this corpus. " + "class Subouter(Outer):\n", + " \n", + " def __init__(self, estimator, k=4):\n", + " super(Subouter, self).__init__(estimator)\n", + " self.k = k\n", + " " ] }, { "cell_type": "code", - "execution_count": 5, - "metadata": { - "collapsed": false, - "deletable": true, - "editable": true - }, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "/usr/local/lib/python3.5/site-packages/sklearn/cross_validation.py:44: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This module will be removed in 0.20.\n", - " \"This module will be removed in 0.20.\", DeprecationWarning)\n" - ] - }, - { - "ename": "AttributeError", - "evalue": "'NoneType' object has no attribute 'transform'", - "output_type": "error", - "traceback": [ - "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", - "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)", - "\u001b[0;32m<ipython-input-5-3514380b0c82>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 9\u001b[0m ])\n\u001b[1;32m 10\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 11\u001b[0;31m \u001b[0mvisualizer\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mfit_transform\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdocuments\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mlabels\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 12\u001b[0m \u001b[0mvisualizer\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mnamed_steps\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m'viz'\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mshow\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;32m/usr/local/lib/python3.5/site-packages/sklearn/pipeline.py\u001b[0m in \u001b[0;36mfit_transform\u001b[0;34m(self, X, y, **fit_params)\u001b[0m\n\u001b[1;32m 301\u001b[0m \u001b[0mXt\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfit_params\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_fit\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mX\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0my\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mfit_params\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 302\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mhasattr\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mlast_step\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'fit_transform'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 303\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mlast_step\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mfit_transform\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mXt\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0my\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mfit_params\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 304\u001b[0m \u001b[0;32melif\u001b[0m \u001b[0mlast_step\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 305\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mXt\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;32m/usr/local/lib/python3.5/site-packages/sklearn/base.py\u001b[0m in \u001b[0;36mfit_transform\u001b[0;34m(self, X, y, **fit_params)\u001b[0m\n\u001b[1;32m 495\u001b[0m \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 496\u001b[0m \u001b[0;31m# fit method of arity 2 (supervised transformation)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 497\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mfit\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mX\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0my\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mfit_params\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mtransform\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mX\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 498\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 499\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;31mAttributeError\u001b[0m: 'NoneType' object has no attribute 'transform'" - ] - }, - { - "data": { - "image/png": "iVBORw0KGgoAAAANSUhEUgAAA3gAAAJlCAYAAACIUVC/AAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAAPYQAAD2EBqD+naQAAIABJREFUeJzs3X2UlvV9J/734DA8OKAiQYpsF5JVEEFiE6E0+aVpIiQr\nS2R3ZZuuEYQaajZ015zoUt16tj19sNmckxobrRiQpgbyMO4SdMPpcc+Gc5az9DS2GledKAapAVEG\ng+MAOuDA/fvDw9R5BIZ7Hvj6ep3DH/d1fT739zs337lv3lzXfV01lUqlEgAAAM56wwZ7AgAAAFSH\ngAcAAFAIAQ8AAKAQAh4AAEAhBDwAAIBCCHgAAACFEPAAAAAKIeABAAAUQsADAAAoxBkHvDvvvDNL\nly7ttea5557LzJkz841vfKPLvj179mTVqlWZO3du5s6dm9WrV+fAgQP9XgcAAFCa2jNpbmhoSEND\nQ+bMmdNjzbFjx3L77bfn2LFjXfY1Nzdn6dKlaWtry8qVK9PW1pa1a9dmx44daWhoSG1tbb/UAQAA\nlKhPief48eO57777cu+996ampqbX2vvvvz8/+9nPut23fv36NDU15dFHH83UqVOTJFdccUWWL1+e\nTZs2ZcmSJf1SBwAAUKLTPkXz6NGjWbx4ce69994sXrw4EyZM6LH2+eefz/33358vfvGLqVQqXfZv\n2bIlc+bMaQ9jSTJv3rxMnTo1W7Zs6bc6AACAEp12wDty5EjefPPN3H333bnrrrtyzjnndFt34tTM\nj370o1m0aFGX/S0tLdm9e3cuv/zyLvtmzJiRZ599tl/qAAAASnXap2iOGTMmjz32WIYN6z0bPvDA\nA9m9e3fuv//+vP32213279u3L0ly0UUXddk3YcKEHDx4MIcOHap6XX19/cl/SAAAgLNQn66iebJw\n98ILL+S+++7L6tWrezyF8/Dhw0mSkSNHdtk3YsSIJMlbb71V9ToAAIBSVf2yksePH8/v/d7v5aqr\nrsp1113XY92J7+T1dpGWmpqaqtedrieffDKVSiXDhw8/7V4AAIBqePvtt1NTU5Mrr7yy17qqB7y1\na9fmhRdeyMaNG/P6668nSd54440kSWtra15//fWcf/75GT16dPu2zo4cOZIkqa+vr3rd6apUKqlU\nKjl69Ohp9wIAAAykqge8bdu25e233+5y9K6mpiZr167NunXr8r//9//OpEmTkiT79+/v8hxNTU0Z\nO3ZsRo4cWfW603XiyN2sWbNOu5dyPfXUU0mS2bNn92uPsQanx1iD02Oss2usoT6/Usca6vMrdayh\nPr9Sxxrq8xvosZ5++ulTqqt6wLv99tvbj9id8Itf/CK33nprFi9enMWLF2f8+PGpq6vL5MmT09jY\n2OU5GhsbM3PmzCTvXNSlmnUAAACl6tNFVnozY8aMzJs3r8OfE+eJTp48Ob/6q7+aurq6JMmCBQuy\nffv27Nq1q73/xOOFCxe2b6t2HQAAQImqfgTvdNx0003ZvHlzli1blhUrVqS1tTXr1q3LrFmzOtw7\nr9p1AAAAJarKEbxTuTplTU1Nl7px48Zlw4YNueyyy3LPPffkoYceyvz58/PAAw90uGpltesAAABK\ndMZH8H70ox+dtObiiy/OT3/60273TZkyJWvWrDnpc1S7DgAAoDRV/w4eAAAAg0PAAwAAKISABwAA\nUAgBD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AQ8AAKAQAh4AAEAhBDwAAIBCCHgAAACFEPAAAAAKIeABAAAU\nQsADAAAohIAHAABQCAEPAACgEAIeAABAIQQ8AACAQgh4AAAAhRDwAAAACiHgAQAAFELAAwAAKES/\nBrznnnsuv/3bv50rr7wyH/rQh3LzzTdn165dHWr27NmTVatWZe7cuZk7d25Wr16dAwcOdHmuatcB\nAACUpra/nnj37t25/vrrM2rUqKxatSqVSiUPPvhgrr/++mzevDnve9/70tzcnKVLl6atrS0rV65M\nW1tb1q5dmx07dqShoSG1te9Mr9p1AAAAJeq3xPOtb30rb775ZjZs2JDp06cnSebOnZslS5bkr/7q\nr3Lbbbdl/fr1aWpqyqOPPpqpU6cmSa644oosX748mzZtypIlS5Kk6nUAAAAl6rdTNHft2pULLrig\nPdwlyaxZs3L++ednx44dSZItW7Zkzpw57WEsSebNm5epU6dmy5Yt7duqXQcAAFCifgt4F110Ud54\n4428/vrr7duam5tz8ODBTJgwIS0tLdm9e3cuv/zyLr0zZszIs88+myRVrwMAAChVvwW8G264IXV1\ndfnyl7+c559/Ps8//3y+/OUvp66uLjfccEP27duX5J0g2NmECRNy8ODBHDp0qOp1AAAApeq37+Bd\ndtll+epXv5pbbrkl11577TuD1dbm61//eqZPn56f/OQnSZKRI0d26R0xYkSS5K233srhw4erWldf\nX3+mPxoAAMCQ1G8B7wc/+EHuuOOOXHXVVfl3/+7f5dixY/nOd76T//Sf/lO+8Y1v5LzzzkuS1NTU\n9PgcNTU1qVQqVa0DAAAoVU3lRDKqotbW1nzsYx/LlClT8r3vfa89WLW1teW6667La6+9lrVr12bx\n4sW58847c/3113fo/8pXvpK/+qu/ypNPPpmXXnop1157bdXqujvC15unn346R48edYuF97iNj21L\ny4RL2h8fP348STJsWMeznMc2vZB/v+D/O62ed/d17unPsbrT1taWJKe13vvSM5BjDfX5lTrWUJ+f\nsQanx1iD02Oswekx1uD0lD5WXV1dZs2a1Wtdv3wH78UXX0xLS0uuueaaDkfNamtrs2jRovziF7/I\nwYMHk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hDfX6ljuV3q6e+zt5+++32bNKbogLepEmTkiT79+/vsq+pqSljx47t9vTN3lx55ZVVmRsA\nAEB/K+o7eGPGjMnkyZPT2NjYZV9jY2Nmzpw5CLMCAAAYGEUFvCRZsGBBtm/fnl27drVvO/F44cKF\ngzgzAACA/lXURVaS5MCBA1m0aFHOOeecrFixIq2trVm3bl2mTJmSjRs3+i4dAABQrOICXpL84z/+\nY+666648/vjjGTVqVH791389t912Wy644ILBnhoAAEC/KTLgAQAAvBcV9x08AACA9yoBDwAAoBAC\nHgAAQCEEPAAAgEIIeAAAAIUQ8AAAAAoh4AEAABSidrAnAGebPXv25M/+7M/y+OOPJ0k+/vGPZ/Xq\n1Rk3btwp9d9555156aWX8td//de91m3bti1/+Zd/mcbGxtTU1OSDH/xgbrnllsyePbvXvr/927/N\nPffck+effz719fX59Kc/nVtuuSWjR48+pfk999xzue6663LzzTdn1apVvdZed911eeaZZ7ps/9Sn\nPpWvf/3r3fYcOHAgX/va17J169a0trbmsssuy5e//OVceeWV3da//PLL+eQnP9nrPB566KFcddVV\n3f4sX/3qV/PEE09k2LBhueqqq7J69epMnTq11+f7+7//+/z5n/95nn322YwdOzZXX311fvd3fzcX\nXHBBl9qe/j5Ptk5OZR3cfvvt2bdvXx588MFee062Vnrq622tnMr8Oq+VnnpOtk566uttrXTuOdV1\n8sgjj3Q7Vm9rpaf5dV4nM2bMyIEDB7Jjx44ef2e7Wxe//uu/nm9/+9un/Lt+55135qmnnkp9fX2v\nPZ3XxT//5/88lUolL730Uo893a2JOXPm5MEHHzzl+T333HP5N//m32TChAlpbm7usae7dVGpVHLB\nBRektbW1x77O62LSpEmpqanJz3/+8y49va2LE7cBHjFiRM4555xux+q8Lt7//vfn2LFjefHFF3uc\nX3fvH/PmzcuDDz7Y6/ty57Vx+eWX5+DBg9m5c+cpvZefWKdf+MIXTvoZ0HltTJ06NW1tbdmzZ0+P\nPZ3XxuzZs9PU1JQXXnjhlOZ34v1i4cKF+fnPf97r/DqvjRN/V+ecc07Gjx/fbU937xef+tSnsmXL\nlm7H6mltvPv20BdccEE+85nPdBmru/eLT33qU/n+97/f68/V22dLT5+9vX2WnMrndef3r556TvY5\n0lNfb58jpzK/7mp66uvts+QLX/hCtz0n+zdH57FO5bPkT/7kT/Jf/+t/7TJWb58jPf1Mp/PvjdMh\n4MFpaG5uztKlS9PW1paVK1emra0ta9euzY4dO9LQ0JDa2t5/pRoaGtLQ0JA5c+b0WvfjH/84K1eu\nzCWXXJIvfelLOXbsWDZu3JjPfe5z2bhxY2bNmtVt39/+7d/mt3/7tzNr1qzceuutefXVV/Otb30r\nzz77bDZs2HDSn+/YsWO5/fbbc+zYsZPWJsnOnTszf/78LFiwoMP2SZMmdVt/+PDhXH/99Xnttddy\n4403ZuzYsfn2t7+dG2+8MQ8//HAuueSSLj3jxo3LV7/61S7bW1tb80d/9EcZP358pk+f3mX/7t27\nc/3112fUqFFZtWpVKpVKHnzwwVx//fXZvHlz3ve+93U7x7/7u7/LTTfdlPPOOy//4T/8hxw/fjzr\n16/P3/3d3+W73/1uxowZ017b09/nydbJpk2bTroOvve972XTpk35tV/7tV7HOtlaee6557rt622t\nLF68+KTz67xWelvbva2Tnvp6WysrV67s0nMq66Sn16K3tfL5z3++257O6+TnP/95GhoaUldXl9/9\n3d9NbW1tl9/Z7tbF/fffnx/84Ae59NJLT+l3vaGhId///veTJNOmTeuxp/O62LVrV77zne+kpqYm\nN954YyZMmNClp7s1sX79+nzrW9/qdazO6+I//sf/mGPHjuXo0aO99nReFzt37sz999+fMWPG5Atf\n+EK3fZ3Xxeuvv56HHnooNTU1uemmmzJu3LgOPf/iX/yLbtfFT3/606xbty61tbVZtWpVt39fndfF\nz3/+83z3u9/NOeecky9+8YsZNWpUl57u3j8eeOCBbNiwodf35c5r48UXX8zDDz+cUaNG5dZbb01T\nU1Ov7+Unfo+mTZt20s+AzmvjxRdfzHe/+93213DYsGFdejqvjX/4h3/I//yf/zPnnnvuKX3WnHi/\naGtry+bNmzN79uxe+969Nl544YV885vfzD/7Z/8sn/jEJ1JXV9elp7v3i29+85v54z/+40ybNq3b\nsbp7zzgxVqVSydixY7N48eJ85zvf6TBWd+8Xa9asydatW3P55Zf3+HP19tmyYcOGbj97e/ss+e53\nv3vSz+vO7689fcaf7HNkxowZ3fb19jny13/91yedX3fz6e3fIT19lkycOLHbnpP9m+P9739/l76T\nfZZceOGF+da3vtVlrN4+R/7H//gf3c7vdP69cdoqwCn72te+Vrn88ssrL774Yvu27du3V6ZNm1b5\n/ve/32PfsWPHKn/xF39RmT59emX69OmVG264oddxrr322spv/MZvVI4cOdK+7bXXXqvMmTOnsmLF\nih77/vW//teVT37ykx36NmzYUJk+fXrl//yf/3PSn+8b3/hGZebMmZXp06dX/uIv/qLX2t27d1em\nTZtW2bRp00mf94Svfe1rlcsuu6zy93//9+3b9u/fX5k9e3blP//n/3zKz1OpVCp//Md/XJkxY0bl\nH/7hH7rd/0d/9EeV6dOnV37605+2b/t//+//VaZNm1b5b//tv/X4vP/qX/2rygc/+MHK7t2727c1\nNjZWLrvssspXvvKVSqVy8r/PntbJpZdeWrn55pt7XQdtbW2Vr3/96+01N954Y69j9bRWrrrqqsrV\nV1/dY193a+Xb3/52Zdq0aZVp06addJ2eWCvTpk2r3HDDDT2O09M6OZXXsPNa2bdvX2XGjBmVSy+9\n9JR+jyqVd9bJZZddVrnjjjt6HKu7tfKTn/ykcumll/b4WnReJ9dee23lox/9aGX69Ont66Tz72x3\n6+Lqq6+uXHrppZWN/397Zx5UxZX+/e+9IIuyqKhEpZQ4BmRxAUEWoyKKC8qmuCDuilucCIrBddxl\nxCBoXDKIGTMuYDmjiKMVSdRIqowV4xJroiCCCwFUghcu22Xt9w+q++3bfXrBZPL7vb7nU2VZ3NtP\nP2f5nuc53X363NOnuc9IY53fXk5OTszAgQNl44NQF2FhYcyoUaMYb29v7hihDUkTI0eOZJycnJir\nV6/Klo/l4MGDjLOzM+Pk5MSkpqZK2pB0oSbuCXXB1mvQoEFcDFETK318fBgn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gMGDPnj2S5ePrQu24\n4eviiy++ANC2BEuj0SAjIwMZGRkiG1L8WL58ORwdHXH8+HHJsUaKGT4+PtDr9di7d6/qWN69e3d8\n/PHHonEdFxeHPn36IDMzU7Luz58/x/Pnz9G5c2eRL1K88PDw4JbVqi2fVqvF+PHjUVxcLNkWpJgx\nePBg1NfXIz09nWgjFS98fX2RnZ0tmw/52lATF6XixdSpU5Gbmytppya3COOpmlyiJl+T8gj7WXvz\nCP9cSu3F/pTO2+Y6/mdKuYTkS+2cg+RfKZcIbZTyCKl8bzPfUIuGkXtTnUKhUCgUCoVCoVAo/89A\n38GjUCgUCoVCoVAolHcEeoFHoVAoFAqFQqFQKO8I9AKPQqFQKBQKhUKhUN4R6AUehUKhUCgUCoVC\nobwj0As8CoVCoVAoFAqFQnlHoBd4FAqFQqFQKBQKhfKOQC/wKBQKhUKhUCgUCuUdgV7gUSgUCoVC\noVAoFMo7Ar3Ao1AoFAqFQqFQKJR3BHqBR6FQKBQKhUKhUCjvCPQCj0KhUCgUCoVCoVDeEegFHoVC\noVAoFAqFQqG8I/wf27lDuEaJvt4AAAAASUVORK5CYII=\n", - "text/plain": [ - "<matplotlib.figure.Figure at 0x116ca22e8>" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], + "execution_count": 6, + "id": "44c63ce3", + "metadata": {}, + "outputs": [], "source": [ - "from sklearn.pipeline import Pipeline \n", - "from sklearn.feature_extraction.text import CountVectorizer \n", - "from yellowbrick.text import FreqDistVisualizer\n", - "\n", - "visualizer = Pipeline([\n", - " ('norm', TextNormalizer()),\n", - " ('count', CountVectorizer(tokenizer=lambda x: x, preprocessor=None, lowercase=False)),\n", - " ('viz', FreqDistVisualizer())\n", - "])\n", - "\n", - "visualizer.fit_transform(documents(), labels())\n", - "visualizer.named_steps['viz'].show()" + "o = Outer(KMeans())" ] }, { "cell_type": "code", - "execution_count": 6, - "metadata": { - "collapsed": false, - "deletable": true, - "editable": true - }, + "execution_count": 7, + "id": "79ea1d05", + "metadata": {}, "outputs": [ { - "data": { - "image/png": "iVBORw0KGgoAAAANSUhEUgAAA3gAAAKcCAYAAAC6zBhuAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAAPYQAAD2EBqD+naQAAIABJREFUeJzs3XtcVHX+x/H3CCoYmqlhmmviJUYRFS+oaGZe0ETNSrNM\nJU2xdtvValu01cpL62VbNW+tmrW5yWr0i7JizbI0k7yklikG3jJvgYYEKJjI+f3hY2YdB3RAcPTr\n6/l4+HjIOZ9zzpczwGPe870cm2VZlgAAAAAA171y3m4AAAAAAKB0EPAAAAAAwBAEPAAAAAAwBAEP\nAAAAAAxBwAMAAAAAQxDwAAAAAMAQBDwAAAAAMAQBDwAAAAAMQcADAAAAAEMQ8AB4xebNm2W32z36\n98MPP3i7ubiE9evXy263a9y4cc5tCQkJstvtmjJlSonOWVBQoH/961+aNWuWx8fMnTtXdrtdb775\npnPbkCFDZLfbdeDAgRK143KKaqfjurt27SqT6xbX0qVLFRkZqdDQUEVERGjdunVX7doffPCBxo8f\nf9WudzmOn82i/r3//vtux6xbt06PPvqowsPDFR4erlGjRun7778v1nVL4z6MHTtWdrtdq1evvqLz\nADCbr7cbAODGVqNGDUVERBS532azqWrVqlexRSgtNputxMeuXLlS06ZN0+DBg4t1vcKueSXtuJxL\ntbNcuWvjM9SNGzfqb3/7m3x9fdWhQwdVrFhR9erVuyrX/uabbxQbG6vOnTtflet5Ijk5WTabTZ06\nddLNN9/stv93v/udy9crVqzQiy++KH9/f7Vv3145OTn66quvtGHDBi1evFjt27e/7DVL6z4U9TMO\nABci4AHwqvr162vGjBnebgZKWffu3dWiRYtC30B7wrKsYh8zePBgRUVFqXr16iW6ZkkU1c6///3v\nys3N1e23337V2lKUHTt2SJIeffRRl17Wq6GgoOCqXs8TjhEBr7zyiipXrnzJ2rS0NE2ZMkU1atTQ\nf/7zH2f4+/LLL/X73/9ef/3rX/XJJ5+ofPnylzzPtXgfAJjr2vh4EQBglICAAAUFBalatWolOr4k\nAa9q1aoKCgpSlSpVSnTNkiiqnbfddpuCgoJUoUKFq9aWopw5c0Y2m0233XbbVb92SV7HsvbDDz+o\ndu3alw13kvT2228rPz9fI0aMcOnZ69Spk/r166djx47p008/vex5rsX7AMBcBDwA1w3HHKs1a9bo\n2WefVfPmzRUREaF3333XWZOSkqLRo0crIiJCoaGh6tGjh+bMmaPc3NxCz7lu3ToNHjxYrVq1UkRE\nhF588UXl5OSoS5cu6tq1q7POMWfwiSeecDvHyZMnZbfbXeqL2x7H+V999VXt3r1bI0eOVJs2bRQW\nFqbo6Ght3ry50Pbv2bNHf/nLX3T33XerRYsW6t27t+bNm6fTp09Lkr777jvZ7Xb169ev0ON37Ngh\nu92up556qtD9FyooKNDSpUvVp08ftWjRQt26ddPixYsL7Z0oag7emjVrFB0drY4dO6p58+bq0aOH\npk2bpoyMDGfNkCFD9Pzzz8tms+ntt9+W3W7XvHnznPvsdrv279+vhx56SKGhoerSpYt2796tefPm\nuc3Bc8jNzdX06dN11113qUWLFurfv3+hc60uNXdu0qRJLnO0PGnnxef55ZdfNGXKFHXt2lWhoaHq\n0KGDxowZU+g8U7vdrkcffVQZGRkaP368OnbsqGbNmum+++7TihUr3OovduTIEdntds2fP1+SNH36\ndLe5kjk5OZo1a5buvfdehYaGqm3btho1apS2bNnidr4uXbqoc+fO2rFjh6KiotSsWTP17NlTx48f\nL/T648aNU3R0tGw2m9auXet2bUmKj4/XgAEDFBYWprCwMA0cONDl99nBMffs8OHDeu2119SlSxe1\naNFCffr00dtvv+1xgDp8+LCys7PVpEkTj+o3bNggSbrnnnvc9nXt2lWWZenLL7+85DlK8z4UJTY2\nVna7XUOGDNGZM2ec20+fPq1XX31VPXv2VLNmzdS+fXuNHj1aqampbudwvL6nT5/W9OnTdc899yg0\nNFQ9e/bUokWLdO7cOZf6goICvfHGG3rwwQfVunVrtWzZUg8++KD+9a9/KT8/3+O2Ayh9DNEEcN1w\nzD+ZMWOGMjIy1KlTJ6Wmpsput0uSvvjiC40ePVpnz55V06ZNVbt2bX3//fdasGCB1q5dq6VLlyog\nIMB5vqVLlzrnJrVr107lypVTQkKCdu/erbNnz15x70tx2yOdD1xvvPGGqlevrnbt2ungwYPatGmT\ntm7dqrffflstWrRw1q5bt05jxoxRXl6emjZtqubNm2vnzp2aN2+ekpKS9NZbb6l58+aqX7++UlJS\ntHfvXjVs2NDleh988IFsNluRAfBCzz77rP773//q5ptvVqdOnXTy5EnNmjVL9evX92heUEJCgsaN\nGyc/Pz+1atVKN910k3bu3Kl//etf+uKLL7Ry5UpVrFhRHTt2VH5+vrZv366goCCFhoY6X2Pp/M/B\nk08+qXPnzqlz587as2ePGjZsqDVr1hTZjmeffVaHDh1S27ZtVb58eW3cuFFjx45VSkqKYmNjXWqL\nOsfF8588aeeF9u/fryFDhigjI0N169ZV165ddfToUX3yySdas2aNZs2apW7durkck5WVpYcffliZ\nmZkKCwtTbm6uvvnmG+cHEY8//niR97tSpUrq27evUlJSlJqaqpCQEDVo0EAtW7aUJGVkZOiRRx7R\nwYMHVbNmTXXp0kUZGRn66quv9OWXX2r8+PF69NFHXc55+vRpPfnkk6pWrZo6duyoX375Rbfeemuh\n12/ZsqXS09O1YcMG3XbbbQoPD3deu6CgQKNHj9ann36qm266SW3btpV0/oOO8ePHKykpSTNnznS7\n91OmTNHatWsVFhamkJAQbdy4UVOmTNH27dv1j3/8o8h74eAI0rfccotefPFFbdiwQcePH1fdunX1\n0EMPafDgwS6v2969e1WhQgXdcccdbueqX7++s+ZSSvM+FGbq1Kn64IMP1KJFCy1atEgVK1aUJGVm\nZmrIkCHas2ePatWqpU6dOikjI0Offvqp1q5dq9dee81t/nN+fr6GDx+ulJQUtWzZUg0bNtTGjRs1\nc+ZM/fzzz3rhhRectX/961+VkJCgGjVqKDw8XJZl6ZtvvtG0adO0c+dOvfLKK5dsN4AyZAGAF2za\ntMkKDg62hgwZ4vExc+fOtYKDg63Q0FDrxx9/dNl34sQJq1WrVlbz5s2tpKQk5/b8/HxrwoQJVnBw\nsDVhwgTn9p9++slq2rSp1bJlS+v77793bk9JSbHatWtnBQcHW126dHFr76hRo9zalZGR4VZf3PY4\nzm+3261JkyZZZ8+ede4bP368Zbfbraefftq5LTs724qIiLCaNGlirVq1yrn9t99+sx5//HHLbrdb\nb731lmVZlrVw4UIrODjY+sc//uHS7vz8fKtdu3ZW27ZtXa5XmMTERCs4ONi6//77rV9//dW5fe3a\ntVZISIhlt9utsWPHOre/9957VnBwsDV58mTntq5du1ohISEur11+fr41fPhwy263W//3f/93yeMt\ny7IGDx5sBQcHW1FRUdaZM2dc9s2dO9ey2+3WG2+84VYfFhZmffvtt87tBw4csDp06GDZ7XZr69at\nLvV2u93auXOn2z2YNGmSZbfbrYSEBI/aefF5+vbta9ntdmv27NkutatXr7ZCQkKssLAwKy0tzbnd\n8fPwyCOPWBkZGc7tH374oRUcHGx16NDBrY2FKey+WJZljRo1yrLb7da4ceNcXv+tW7daLVu2tEJC\nQqxdu3Y5t99zzz2W3W63hg0b5tF1Lavo35s33njD+fP0yy+/OLenpaVZvXv3tux2u7V06VLn9rFj\nx1rBwcFW48aNrY8++si5/fjx41bPnj0tu91uffLJJ5dtz5w5c6zg4GArODjYioiIsP7whz9Yjzzy\niNWsWTMrODjY5XcsMzPTCg4Otu65555Cz5WTk2MFBwdbnTt3vqr34cLvdcGCBc7js7OzXc799NNP\nF/r35KuvvrJCQ0Ot9u3buxxzzz33WMHBwVaPHj2sw4cPO7dv2bLFaty4sRUSEmLl5ORYlmVZR48e\ntYKDg61evXpZeXl5ztrjx49bd911l2W3262ffvrpsvcFQNlgiCYAr7rU4xIaN26snJwct2MiIiLc\nPlGPj4/XqVOnNGLECJdV7Xx8fDR+/HjVqFFD77//vrKzsyVJ7733nvPT6qZNmzrr77zzTj377LNX\n/H0Vtz0ON910k2JjY+Xr+78BFo8++qgsy3LpKfjss8/0yy+/qG/fvurRo4dze/ny5fWXv/xFdevW\n1YkTJyRJ/fr1k4+Pjz766COXa3355Zc6efKkevfu7XK9wqxYs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q0aJGWL1+umTNnehzwiis9Pd2ttzYtLU35+fkuvUKO17mwMHfx\nfMniCAwMlGVZOnLkSKH7Dx06JElX7SHtjp/totrz888/69y5cyV+jqEn1z58+HCRNY59F18/LS3N\nrRevoKBAaWlp8vf3v2TvYm5uriZPnqxTp07p1VdfLXR/RkaGKleu7Oy9a9iwoXbu3KkjR4649bTt\n27dPUsmHrJb0PthsNsXGxqpx48aKjY3VM888o4kTJ+qjjz5yBkHH37RWrVpp/PjxJWqfJ/z8/BQV\nFeUcAr1z505NmzZNW7du1euvv66JEyeW2bUBFI05eACM0KpVq0s+k2rUqFEaPHiw801Z27ZtZVlW\noQ8pTkpK0tmzZ122Od7wFfZp/rfffnvF7SmusLAwWZalr776ym3foUOHNGHCBOfzzxzuv/9+WZal\njz76SBs3blR4eLjHD78ODw9XXl5eoddbu3btZY8/ePCgevfu7fYcwdq1a2v8+PEqV66cc1iZVPo9\nV47nmV1o9erVklznSTpe5wufy+ewY8cOt22etrNVq1aSVORDsVetWiXp/DzFq8HRnrVr17r9rF/Y\nnvDw8Cu6TmH3p1atWqpVq5Z++umnQp/HlpycrEOHDqlu3bouH7JI5x8NcrH169frzJkz6tix4yXb\n4u/vr3Xr1mn16tXOObgXciw4cmFPWMeOHWVZlj7//HO3+s8++0w2m0133XXXJa8rlf59cMyb7NWr\nl9q3b69Dhw65/L47Xt+vv/660A8r4uPj9cADD+itt966bNsLk5iYqG7dumnRokUu25s2bao//OEP\nsizL5fcZwNVFwANghIceekgVK1bUokWLtH79epd9//znP7Vu3TqlpaU5n13Vv39/Va5cWW+//baS\nkpKctWlpaXr55Zfdzh8UFKTy5ctr9+7dzgUqJDnfWF38Bq647SmuXr16qUqVKkpISHB503vmzBlN\nmTJFNptNvXv3djmmWbNmatiwod5//33l5eXp/vvv9/h6Q4YMkWVZmjx5snMxBen8Yg5vv/32ZYNO\n3bp1lZmZqfXr1+uLL75w2ffxxx+roKBAoaGhzm2Onogr6TVzsCxLM2fO1P79+53bdu/erblz58rX\n19flWW933nmnc6GNC3tr582b5+xlu5Cn7WzXrp3uvPNO7dq1S7Nnz3YZnvfZZ59p+fLlqlSpkkdD\nZkvD7373O3Xu3Fnp6el64YUXXELe9u3bNW/ePPn6+uqhhx66ous4Vli8eDVcx8/T2LFjXT40SU9P\n19ixY2Wz2fTII4+4HON4XS5cTOXo0aOaPHmybDbbJee7OvTv31+WZWnixIku1929e7dmzZolHx8f\njRw50rndsVrrggULXFaxXbdunVauXKlatWq5rGJ7Ne7DxSZMmCAfHx+98cYbzjbWrVtXnTp10r59\n+zRlyhT99ttvzvoffvhBr7zyinbv3u3y3MbiaNSokQ4fPqylS5e6/F445gfabDaX32cAV1eJhmh+\n/fXXmjNnjlJSUhQQEKCePXtqzJgxzk8+pfPDCqZNm+aceNu5c2fFxsa6DbfwVh2A61NR81Zq166t\nKVOmaNy4cRo5cqSaNGmiOnXqKDU1VT/++KMCAgI0e/ZsZxCpVq2apk+frtGjR+vxxx9XmzZtVLly\nZW3cuFE333yz2/n9/f01cOBALVu2TNHR0c4hhps2bVJYWJhbL0hx21NclStX1rRp0zRmzBiNGjVK\nYWFhqlGjhr777jsdP35cERERGjp0qNtx/fr10yuvvKJKlSopMjLS4+vdfffdio6O1tKlS529Brm5\nudq8ebNCQ0ML7cW8kM1m00svvaQ//elPevLJJ9WsWTPVqlVLx44d044dO1SpUiWNHTvWWV+vXj1J\n58Nfdna2unTpov79+1+2nUX9fPzud79Tv3791L59e507d04bN27UuXPnNGHCBJcVDB966CEtW7ZM\nX331le69914FBwcrJSVFR44cUVRUlD7++GOX8xannTNnztRjjz2mhQsX6r///a8aN26sY8eO6bvv\nvpOfn5+mTZvm8aI5xVXYfZk8ebKGDBmi999/X0lJSWrRooUyMjK0detW2Ww2jRs37orfpNepU0c+\nPj7aunWrRo4cqdatW2vUqFF67LHHtG3bNq1Zs0bdu3d39hRu3rxZubm5uvfee/XYY4+5na9q1aqK\njo5WeHi4/P399fXXXysvL08xMTFq06bNZdvz5JNPavPm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3r07du7cKbZiTBAEQagOErYS\nheT+CIIgCEIKERERSExMhK6uLgDg4MGDuHXrFjw8PLBy5UoUFBQgLCzsHbeSIAji08bT0xM7duzA\n9evXxY59isJWtINHEARBEFI4evQoJkyYgMDAQADAr7/+iqZNm2LBggWcaMq+ffvecSsJgiA+bYqK\nitCsWTO4uLhIFba6ffs25s2bJ3LexypsRQEeQRAEQUghLy+PE1F58+YNUlNTYWlpydXdtWvXDkVF\nRe+yiQRBEJ88hw4dAlA9JmdlZSErK4s7JvRizcjIEDlHIBCorH2qhgI8giAIgpBCq1at8O+//wIA\nzp49i7KyMlhaWnLH79y5gzZt2ryj1hEEQRAAcOrUqXfdhPcKCvAIgiAIQgqmpqbYuXMnPvvsM8TH\nx0NDQwNWVlYoKirC/v37kZiYiMmTJ7/rZhIEQRAEB9kkEARBEIQUioqKMHv2bFy4cAFNmjRBQEAA\nbG1tkZ6eDldXV5iZmSE8PBxNmzZ9100lCIIgCAAU4BEEQRDEWyksLISWlhYaNWoEACgpKcH9+/fR\nt2/fd9wygiAIghCFAjyCIAiCIAiCIIiPBPLBIwiCIAiCIAiC+EigAI8gCIIgCIIgCOIjgQI8giAI\ngiAIgiCIjwQK8AiCIAiCIAiCID4SKMAjCIIgCIIgCIL4SKAAjyAIgiAIgiAI4iOBAjyCIAiCIAiC\nIIiPBArwCIIgCIIgCIIgPhL+D4YIpwprbr3zAAAAAElFTkSuQmCC\n", - "text/plain": [ - "<matplotlib.figure.Figure at 0x11752cd68>" - ] - }, - "metadata": {}, - "output_type": "display_data" + "name": "stdout", + "output_type": "stream", + "text": [ + "KMeans()\n", + "8\n" + ] } ], "source": [ - "vect = Pipeline([\n", - " ('norm', TextNormalizer()),\n", - " ('count', CountVectorizer(tokenizer=lambda x: x, preprocessor=None, lowercase=False)),\n", - "])\n", - "\n", - "docs = vect.fit_transform(documents(), labels())\n", - "viz = FreqDistVisualizer() \n", - "viz.fit(docs, vect.named_steps['count'].get_feature_names())\n", - "viz.show()" + "print(o.estimator)\n", + "print(o.n_clusters)\n", + "# print(o.foo)" ] }, { "cell_type": "code", "execution_count": 8, - "metadata": { - "collapsed": false - }, + "id": "2ef6c843", + "metadata": {}, "outputs": [ { "data": { - "image/png": "iVBORw0KGgoAAAANSUhEUgAAApgAAAJVCAYAAAB6R4WjAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAAPYQAAD2EBqD+naQAAIABJREFUeJzt3XeYVPW9+PHPKOiCBDsoiWLfUZHVABYwasAuIhpbFMSG\nGEty+VmwmwQ1ETVRESSJvcWuedQb7BUNAhFRxAIRQbFii0rn/P7w2bksLLDIh+j1vl7Pwx+cOXPO\nd2Zn2DdnvudMqSiKIgAAIMly3/YAAAD4fhGYAACkEpgAAKQSmAAApBKYAACkEpgAAKQSmAAApBKY\nAACkEpgAAKRq9G0PgO+nK664Iq644ooGr7/11lvHDTfcUPn7xx9/HNddd108+eST8fbbb8ecOXNi\njTXWiPbt28dBBx0UW2211QLb6Ny5c0yZMiWOOuqoOOWUUxa6r9NOOy3uvffeuPzyy2PXXXeNiIh3\n3nknunTp0qCxlkqlGDFiRDRr1myR6/Xs2TNGjBixwPLlllsuVlxxxWjVqlV07Ngxjj766GjZsmWD\n9r2knn/++TjssMNip512iiFDhiyTfczvySefjNtvvz0GDRpUWTZw4MAYNGhQ9OvXL4444oj/yDgy\nPffcc3HxxRfHhAkTonHjxtGzZ8/45S9/2eD7174f/vGPf8Qqq6yy2PXfe++92GuvvWKVVVaJRx99\ntM5t5XJ5sfcvlUoxbty4bzyemTNnxrXXXhv33XdfTJo0KVZdddXYeuut49hjj40NN9xwsfuPiLjn\nnnvi9NNPX2B5o0aNYqWVVor11lsvunTpEoceemistNJKDdomizZhwoTo379/XHrppQ16ncGyJDBZ\nJqqrq6Nbt251lk2ePDlGjx4d66yzTmy55ZZ1bpv3l9aYMWPiqKOOii+++CLWXXfdaN++faywwgox\nadKk+Nvf/hb33ntvHH/88XHiiScusN9SqRTXX3997LnnnrH55pvXO7ZSqRSlUqne25o2bRo777zz\nIh9bqVSKxo0bL3Kdedft2LFjrL766pVlc+fOja+++irGjBkTN954YzzwwAPx17/+NVq3bt2gbS6p\nRT3ebO+++2706dMnNt54429tDNm++OKLOO6442L69OlRU1MTa6+9dmy66aYNvv/jjz8eQ4YMWaLH\nf/rpp8eXX35ZbyTM/76a1+jRo2Py5MmLHN/ixjNz5sw44ogjYtSoUdGkSZNo165dzJkzJx588MF4\n+OGH47LLLosdd9yxwY9l3XXXrfN+nz17dkydOjVefvnlePHFF+PWW2+N66+/PtZZZ50Gb5P6HXPM\nMTFlypRvexgQEQKTZWSXXXaJXXbZpc6ye+65J1544YVo165d/O53v6v3fnPmzIn/+q//imnTpsXF\nF18ce+21V53bR44cGccee2wMHjw4ttpqq9h+++3r3caZZ54Zd911Vyy//PJLNO5VV101BgwYsET3\nWZxjjz02OnTosMDymTNnxnHHHRfDhg2L3/3ud8vkCGNNTU3893//dzRt2jR92/WZO3duvct79OgR\ne+21V53Q/t9i/PjxMW3atCiXy3Hrrbcu0X3vuOOO6N+/f8yePbvBgXnzzTfHc889t9D1F/b6fOut\nt6J79+7RvHnzuPLKK7/xeAYNGhSjRo2KDTbYIP70pz9Vwu/VV1+NI444Ik455ZQYOnRorLbaag16\nPAt7v3/++edx1llnxUMPPRS9e/eOe+65J5o0adKgbVK/oii+7SFAhTmYfKeMHDkypkyZEjvuuOMC\ncRkR0b59++jbt28URRG33357vdto2bJlvPbaa/HnP/95WQ93qaywwgrRr1+/KIoinnnmmZg5c2b6\nPlZcccVYf/31l9lH8PNb2C+4VVZZJdZff/1o3rz5f2QcmWbMmBEREWuttVaD7zN58uQ44YQT4uyz\nz45mzZo1+CPgSZMmxcUXXxwdOnRYolgoiiJOOumkmD59epx77rkL/LyXZDx33XVXlEqlOP/88+sc\nVSyXy/HLX/4yPv/887j++usbPLaFad68eVxyySXRpk2beOutt+KWW25Z6m3yNaHJd4HA5Dvl448/\nXuw6Xbp0ib333jvatm1b7+1nn312RERceeWVMWHChNTxZav9BT5nzpz4/PPPI+Lr+YrlcjkeffTR\nOOmkk6KmpiY6duwYd955Z+V+48aNi1/96lfRsWPH2GKLLWLnnXeOCy64YIHn7/nnn49yuRzHHnvs\nAvseMWJEHHPMMbHNNttETU1NdOvWLa677rqYPXt2vWP95z//GSeccEJsv/328eMf/zi6d+8eN9xw\nQ8yaNSsivp7Xt/POO0epVIo33ngjyuVyHHbYYXUe07XXXltnm7NmzYqrrroq9tlnn6ipqYn27dvH\nYYcdFo888sgC++/Zs2dsuummMWPGjBg8eHDstttu0bZt2+jcuXNccskl8dVXXzX0aW/wfjt37hy9\nevWKUqkUTzzxRJTL5QbN1f39738fjz76aGy33XZx5513xsorr7zY+xRFEaeddlpUVVXFueee2+DH\nEhFx5513xssvvxw77LBD7Lnnnt94PB9//HF89NFH0bx583rnOW+99dYREfH0008v0fgWpnHjxpX/\nMN52220L3D558uQ4/fTTY4cddog2bdrEjjvuGGeccUZMnjy53u1NmTIlfvOb30SXLl2ipqYmdttt\nt7jgggvik08+qayzqPfEJ598ssDPuHb9K664IsaMGRNHHHFE/PjHP45tttkmTj755Mq2b7zxxthj\njz1iyy23jK5du8Ydd9xR7xhfe+21Ou/d3XbbLS6//PKYNm1anfVq93vZZZfFuHHjonfv3tGhQ4fY\naqutolevXvH8888vsO67774bERHbbbddnWkS7777bpx++umV90ynTp3iuOOOi5EjR9Y7RsggMPlO\nqa6ujoiv54lde+21C/yjG/H1kaSLLroojj766Hq30a5duzjkkENi5syZceaZZy7T8S6t119/PSIi\nqqqqYtVVV42I/5mvOGDAgHjqqadihx12iB/84AeVkzv+/ve/xwEHHBAPPfRQrLvuutGlS5dYbrnl\n4oYbboh999033nrrrcXu99Zbb43DDjssnn322dhwww1jxx13jKlTp8bvf//7+MUvfrHAR9133nln\n9OzZMx577LFYb731olOnTvHhhx/GBRdcUDmhqrq6OnbZZZcoiiKaN28e3bp1q0xhqG8O5vTp06Nn\nz55x8cUXx/vvvx877LBD1NTUxOjRo+OEE06Iiy66qN6x9+3bNwYPHhwtWrSI7bffPj755JP4y1/+\nEn379m3Qc764/c77EfSuu+4anTp1iqIoYq211opu3bpVTgxblE033TQGDhwY1157bbRq1apB47rm\nmmvihRdeiLPPPnuJphJ89dVXcdlll0WjRo3itNNOW6rx1B75WtiUitopJ2+++WaDx7c422yzTTRp\n0iQmT54c7733XmX5yJEjo1u3bnHvvffGqquuGjvvvHOsvPLKcffdd8d+++0Xo0ePrrOdl19+Ofbd\nd9+49dZbo2nTprHTTjtV3hc///nP49///vdSjXPUqFFxyCGHxHvvvRedOnWKxo0bx/333x/HH398\n9O/fPwYMGBAtWrSIdu3axZtvvhnnnHNOnf8URnz971rte/eHP/xhdO7cOWbNmhWDBw+OQw89NL74\n4osF9jtmzJg4+OCDY8KECbHtttvGOuusE8OHD48jjzyy8hysvvrq0a1bt6iqqoqIiN13370yV3fq\n1KlxwAEHxL333hsrrbRSdO7cOVq3bh2PP/549OrVK5555pmlel5goQr4D7n77ruL6urq4rTTTlvk\neqeddlpRLpeL6urqYssttyyOOeaY4qqrrirGjBlTzJ07d6H3++lPf1qUy+Xik08+Kb788svK36+/\n/vp6t//ggw9Wlr399ttFdXV10blz56V7kPPo0aNHUS6Xi+eff77e2z/99NPiwAMPLMrlcp3nZODA\ngUV1dXWxxRZbFBMnTqxzn/fee69o27Zt0aZNm+KJJ56oLJ87d25x4YUXFtXV1cW+++5bWT58+PCi\nurq66NOnT2XZ66+/Xmy++eZFp06dinHjxlWWT5s2rejTp09RLpeLIUOGVJa//fbbRU1NTbHlllsW\nI0aMqCz/97//Xeyzzz5FuVwuHnnkkcq61dXVRdeuXeuMe+DAgUW5XC6uueaayrL+/fsX1dXVxdFH\nH118+eWXleXjx48vfvKTnxTlcrl49NFH6zyf1dXVxXbbbVe8+uqrleVvvvlmseWWWxblcrmYMGFC\nvc/1vJZ0v/U9h0tq3tdmfd54442ibdu2xYknnlgURVF8/PHHDX49Xn311UV1dXVx6qmnLvV45s6d\nW2y99dZFuVwu3nnnnQXud9dddxXV1dVFuVwupk+fvsh9NPT9XhRF0bVr16JcLhfPPvtsURRfvxY7\nduxYlMvl4rbbbquz7o033lhUV1cXO+ywQ2UMc+bMqWzj2muvrfN4zjjjjKK6urq44IILiqJY9M+z\nvue9dv1yuVycf/75leUfffRRsdVWWxXV1dVFTU1NMXbs2Mptt99+e1FdXV0cdNBBddZv165dUVNT\nU3mcRVEUs2fPLs4+++yiurq6OPvss+vd729/+9ti1qxZldvOOuusolwuF3379q0z/vp+rldccUVR\nLpeLgQMH1ln3nnvuKcrlctGjR48FngfI4Agm3znnnXdeHHfccdGkSZOYPn16PPXUU3HRRRfFAQcc\nEB07dozzzjtvsR+lN23aNH7zm99EURRx6aWXxjvvvNOgfU+ZMiXK5fIi/yzJ5Zcivv6o/pRTTqn8\nOemkk+Lwww+PnXbaKcaMGRPrrrtuvZdV6tix4wJnlt92220xc+bM6NmzZ50zeUulUpx66qmx6aab\nxrhx42L48OELHc8NN9wQc+bMiZNPPrnOJW+qqqrivPPOi8aNG8eNN95YWX7PPffEjBkz4qijjor2\n7dtXljdr1iz69u0bG2ywwRKfuTpjxoy44447oqqqKgYMGFDniNmGG24Y55xzThRFscBH6qVSKQ4/\n/PDKke6IiPXWWy86duwYEbHYKRHfdL/L0pw5c6Jfv37RtGnT+PWvf71E9y2KIm666aZYbrnlonfv\n3ks9llKpFF27do2iKKJfv351PloeP358XHrppZW/Z84Z/sEPfhAREZ9++mlERDzwwAMxderU2HXX\nXePAAw+ss26PHj2ic+fO8cEHH8QDDzwQEV9P33jjjTeiffv2cfjhh9d5PKecckq0bt26MgXlm6qq\nqoqTTjqp8vfVV189OnToEKVSKfbff//YbLPNKrfttttuERF1Pk2444474ssvv4yjjz46tttuu8ry\n5ZdfPs4666xYY4014t57713gSOtKK60U/fr1i0aN/uec3EMPPTSKoojx48cvdtwffvhhRES0aNGi\nzvLu3bvHmWeemfK6gfo4i5zvnOWXXz5OPPHEOOKII+LRRx+NYcOGxfPPPx/vv/9+fPrpp3HTTTfF\nfffdF9dff/0irwn4k5/8JPbZZ5/429/+Fuecc05cffXVi913kyZNFnuZooZch7BWURTx3HPP1Vm2\n/PLLx0orrRTV1dWx0047RY8ePeq9pua8EVVr1KhREREL/Zh29913j3HjxsWIESNim222qXed2rlb\ntfPp5rXGGmtEuVyOl156KSZMmBAbbrhhZZ877LDDAuvvuOOOS3TJmlovvfRSzJgxIzp16lSZGjCv\nn/70p1FVVRWjR4+OOXPm1LkawBZbbFHvuCNisfMwl2a/y8qQIUPilVdeiUsuuaTBZ2bXevzxx2PK\nlCmx0047xUYbbZQynr59+8aIESNi5MiRsdtuu0VNTU3MmDEjRo8eHZ06dYqIr6Nl3uBZWrXzfmun\nUYwaNSpKpdJCX+d77rlnPPbYYzFixIjYb7/9YsSIEVEqlep9La6yyirx4IMPLvUYN9lkk1hxxRXr\nLKt9Dc3/Xq09ma32BLGIqFwTt7735QorrBAdOnSIoUOHxgsvvFDnvVZdXR0rrLBCnfVrX+/1TSGa\nX/v27ePWW2+N888/P15++eXo0qVLbLPNNlFVVRU9evRY7P3hmxKYfGc1a9Ys9tlnn9hnn30iImLi\nxInxyCOPxHXXXRdTp06NX/3qVzF06NBFXv7ljDPOiGeeeSaeffbZytytRcm+TFGpVIobb7yxzpG/\nht6vvjOua49GLGwe3Q9/+MOIiPjoo48Wuu33338/Ir4+gWVR+//ggw9iww03rOxz7bXXbtjgG+CD\nDz6IiP8Z7/yWX375aNmyZUyaNCk+/fTTOnMSa492zas2dorFnD27NPtdFsaNGxdXXnll7LLLLvWe\nnLM4ta//7t27p42pWbNmccstt8SgQYNi6NChMXz48FhnnXWib9++0atXr9h6662jUaNGqZcU+uyz\nzyIiKicfLenrfFm8RudX3/ux9t+ehpzEVTu/tGfPngtdp1QqVd6ftep7vdf+x2dhlwWbV9euXWP0\n6NFxyy23xB133BG33357rLDCCrHddttF9+7dY4899ljsNuCbEJh8p4wfPz4+/PDDOh8h1VpvvfXi\n6KOPjr333ju6desWkyZNipdeemmhZ5NHfP0P/1lnnRV9+/aNCy+8MH7yk58sy+HXa3HRszDLLbfg\nDJbFbav2F878RzzmNWfOnCiVSrH33nsvclu1vzTnzJmzuKEuE7WPdf7Hsqwv2L6w/S4Ll156acye\nPTu+/PLLOtMkaj9+/uSTTyrL5z/pae7cufHkk09GVVVV7LTTTqnjatasWfTr1y/69etXZ/nUqVPj\niy++SL0o+ldffVU5K7z2Av1L+jrPeo0uKtiW9mh27Rh33XXXysk49WnoSWFL4qyzzopevXrF0KFD\n4+mnn47Ro0fHU089FU8++WT8/e9/j8svvzx9nyAw+U45/vjjY9KkSfHII48s9ChTy5YtY9ttt42H\nHnqocuRjUfbYY4+4//7747HHHovf/va3i/2Kx++yFi1axMSJE+Odd95ZYE5VRMTbb78dEbHII29r\nrrlmvPvuu3HGGWc06Ovk1lhjjZg4cWK8//77seaaa9a5bdasWXH77bfHxhtvXO9H7ot6HBGx0Lmx\ns2fPjvfeey8aNWpU7xGcb+rb2u/CfPXVV1EqleLZZ5+t9/Zp06bF/fffH6VSaYHAHDNmTHz22Wex\n2267LTJYltSECRPi7bffrvfj5tq5vW3atEnb31NPPRVz586NDTfcsPLR77w/p/oulzT/67z2fvMf\n/av1wAMPxIorrlg5szyi/phc2nmai7LmmmvGW2+9FX369Fnot4wtS+uss0707t07evfuHdOnT49H\nHnkkzj333Hj44YfjxRdfjJqamv/4mPh+c5IP3ym1v0xuvvnmRa43ceLEKJVKDZ53du6550azZs3i\nkUceiWHDhi31OL8t7dq1i6Io4qGHHqr39oceeihKpdIiP5Jv165dRHz9i31+M2fOjIMOOih69epV\nOcFjq622qlwMfn6jRo2K/v37x1//+teIaPjRxc033zyqqqpi1KhRdU4kqfX444/HzJkz6/0GpKXx\nbe13YW688cYYN27cAn9qg7NVq1Yxbty4eOWVVxa470svvRQRkR4Gl112WfTp0yfGjBmzwG133nln\nlEqltI9V58yZE3/5y1+iVCrVOZlnca/z2qkBtT+nRb1Gp0+fHmeccUb8+te/jkaNGlVO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cWec9NWPGjPjoo49i7NixMXPmzNhggw1iyJAh0bhx48o6TZo0iT/84Q9x\n7LHHxrnnnhu33HJLrL/++vGvf/0rXn/99Vh55ZXjkksuqRyNXG655eKiiy6Ko446Ks4555y49dZb\n40c/+lGMGzcuJk+eHJtsskn8v//3/yrbPuigg+Lmm2+OXr16VeZ7Dx8+PLbaaqvKN1Nla9WqVZx3\n3nlx+umnR+/evWOzzTaLH/3oR/H666/HxIkTo1mzZnHppZcuVeC2bt063nzzzejTp09stNFGMWDA\ngOjTp088/PDDcf/998eIESNi8803j5kzZ8aoUaNi2rRpcfTRR6fOqYVaApP/qPq+0WV+Xbp0iaFD\nh8Ytt9wSw4YNi/Hjx8fnn38ezZs3j7Zt20bXrl3jZz/7Wb3bWdy2+/fvH926datz+ZB571s7521x\ntthiiwYF5jf9ZbGo++25557RunXr+NOf/hQjR46MV199NdZee+045phj4sgjj2zQvMpjjjkm2rRp\nE9ddd128+OKL8dprr0WrVq3i8MMPj969ey8wh/PnP/95bLDBBnHVVVfFiy++GNOnT4/WrVvHCSec\nUOdSJ7XfQHThhRfGiy++GB988EElMOd/TE2aNIkbbrghrr/++rjvvvvi6aefjqqqqth2222jR48e\n9c4BXNTz0tDn+pvud2mPbC3p/Re3z48//jhKpdI3niu6qG1feeWVMXDgwBg6dGg88cQTsfbaa0eP\nHj2iT58+C8zDXdw+3n777cqcyYivT5apfS/vuuuucdBBB9V7QtXWW28d99xzTwwZMiSGDRsWb775\nZqy55ppx6KGHxlFHHbXAyTBt27aNu+++OwYPHhzPPPNMvP7669GiRYs4/PDD4/jjj69ziaEzzzwz\nWrVqFXfeeWcMHz481lhjjTjyyCPjuOOOi913332B5+ab/vznv8/ee+8d6623Xlx11VUxcuTIGD9+\nfKy11lqx//77R58+fRYIvUXtt77bTjvttPj8889j7Nix8cknn8TkyZNj4403jptvvjkGDRoUzzzz\nTDz11FNRVVUVbdq0iYMPPvgbXb0AGqJUfNNTXIHvvGeffTaOPPLI2GWXXZb4yBMAfFPmYML3WO13\nRi/pBbwBYGn4iBy+hx544IG45pprYvz48VEqlWLbbbf9tocEwP8hAhO+hyZNmhQTJ06Mpk2bxuGH\nH+7bOgD4jzIHEwCAVOZgAgCQqkEfkb/wwgtRFEWd65QBAPB/y6xZs6JUKtX7Na7zalBgFkXR4IsY\nAwDw/dTQHmxQYNYeudxiiy2++YgAAPhfbd6vDF4UczABAEglMAEASCUwAQBIJTABAEglMAEASCUw\nAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEA\nSCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEgl\nMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTAB\nAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBI\nJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUw\nAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEA\nSCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEgl\nMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTAB\nAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBI\nJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUw\nAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEA\nSCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEgl\nMAEASCVBMsRgAAAIYElEQVQwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEgl\nMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTAB\nAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBI\nJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUw\nAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEA\nSCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEgl\nMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTAB\nAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBI\nJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUw\nAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEA\nSCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEgl\nMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTAB\nAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBI\nJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUw\nAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEA\nSCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEgl\nMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTAB\nAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBI\nJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUw\nAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEA\nSCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEgl\nMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTAB\nAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBI\nJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUw\nAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEA\nSCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEgl\nMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTAB\nAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBI\nJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUw\nAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEA\nSCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEgl\nMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTAB\nAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBI\nJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUw\nAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEA\nSCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEglMAEASCUwAQBIJTABAEgl\nMAEASNWoISvNmjUriqKIl156aVmPBwCA76iZM2dGqVRa7HoNCsyGbAgAgO+3UqnUoC4sFUVR/AfG\nAwDA/xHmYAIAkEpgAgCQSmACAJBKYAIAkEpgAgCQSmACAJBKYAIAkEpgAgCQ6v8DLmrMuo/whhIA\nAAAASUVORK5CYII=\n", + "text/html": [ + "<style>#sk-container-id-2 {color: black;background-color: white;}#sk-container-id-2 pre{padding: 0;}#sk-container-id-2 div.sk-toggleable {background-color: white;}#sk-container-id-2 label.sk-toggleable__label {cursor: pointer;display: block;width: 100%;margin-bottom: 0;padding: 0.3em;box-sizing: border-box;text-align: center;}#sk-container-id-2 label.sk-toggleable__label-arrow:before {content: \"▸\";float: left;margin-right: 0.25em;color: #696969;}#sk-container-id-2 label.sk-toggleable__label-arrow:hover:before {color: black;}#sk-container-id-2 div.sk-estimator:hover label.sk-toggleable__label-arrow:before {color: black;}#sk-container-id-2 div.sk-toggleable__content {max-height: 0;max-width: 0;overflow: hidden;text-align: left;background-color: #f0f8ff;}#sk-container-id-2 div.sk-toggleable__content pre {margin: 0.2em;color: black;border-radius: 0.25em;background-color: #f0f8ff;}#sk-container-id-2 input.sk-toggleable__control:checked~div.sk-toggleable__content {max-height: 200px;max-width: 100%;overflow: auto;}#sk-container-id-2 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {content: \"▾\";}#sk-container-id-2 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-2 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-2 input.sk-hidden--visually {border: 0;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);height: 1px;margin: -1px;overflow: hidden;padding: 0;position: absolute;width: 1px;}#sk-container-id-2 div.sk-estimator {font-family: monospace;background-color: #f0f8ff;border: 1px dotted black;border-radius: 0.25em;box-sizing: border-box;margin-bottom: 0.5em;}#sk-container-id-2 div.sk-estimator:hover {background-color: #d4ebff;}#sk-container-id-2 div.sk-parallel-item::after {content: \"\";width: 100%;border-bottom: 1px solid gray;flex-grow: 1;}#sk-container-id-2 div.sk-label:hover label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-2 div.sk-serial::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: 0;}#sk-container-id-2 div.sk-serial {display: flex;flex-direction: column;align-items: center;background-color: white;padding-right: 0.2em;padding-left: 0.2em;position: relative;}#sk-container-id-2 div.sk-item {position: relative;z-index: 1;}#sk-container-id-2 div.sk-parallel {display: flex;align-items: stretch;justify-content: center;background-color: white;position: relative;}#sk-container-id-2 div.sk-item::before, #sk-container-id-2 div.sk-parallel-item::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: -1;}#sk-container-id-2 div.sk-parallel-item {display: flex;flex-direction: column;z-index: 1;position: relative;background-color: white;}#sk-container-id-2 div.sk-parallel-item:first-child::after {align-self: flex-end;width: 50%;}#sk-container-id-2 div.sk-parallel-item:last-child::after {align-self: flex-start;width: 50%;}#sk-container-id-2 div.sk-parallel-item:only-child::after {width: 0;}#sk-container-id-2 div.sk-dashed-wrapped {border: 1px dashed gray;margin: 0 0.4em 0.5em 0.4em;box-sizing: border-box;padding-bottom: 0.4em;background-color: white;}#sk-container-id-2 div.sk-label label {font-family: monospace;font-weight: bold;display: inline-block;line-height: 1.2em;}#sk-container-id-2 div.sk-label-container {text-align: center;}#sk-container-id-2 div.sk-container {/* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */display: inline-block !important;position: relative;}#sk-container-id-2 div.sk-text-repr-fallback {display: none;}</style><div id=\"sk-container-id-2\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>Subouter(estimator=KMeans())</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item sk-dashed-wrapped\"><div class=\"sk-label-container\"><div class=\"sk-label sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-4\" type=\"checkbox\" ><label for=\"sk-estimator-id-4\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">Subouter</label><div class=\"sk-toggleable__content\"><pre>Subouter(estimator=KMeans())</pre></div></div></div><div class=\"sk-parallel\"><div class=\"sk-parallel-item\"><div class=\"sk-item\"><div class=\"sk-label-container\"><div class=\"sk-label sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-5\" type=\"checkbox\" ><label for=\"sk-estimator-id-5\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">estimator: KMeans</label><div class=\"sk-toggleable__content\"><pre>KMeans()</pre></div></div></div><div class=\"sk-serial\"><div class=\"sk-item\"><div class=\"sk-estimator sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-6\" type=\"checkbox\" ><label for=\"sk-estimator-id-6\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">KMeans</label><div class=\"sk-toggleable__content\"><pre>KMeans()</pre></div></div></div></div></div></div></div></div></div></div>" + ], "text/plain": [ - "<matplotlib.figure.Figure at 0x11b5e0c88>" + "Subouter(estimator=KMeans())" ] }, + "execution_count": 8, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" } ], "source": [ - "from sklearn.pipeline import Pipeline \n", - "from sklearn.feature_extraction.text import TfidfVectorizer \n", - "from yellowbrick.text import TSNEVisualizer\n", - "\n", - "vect = Pipeline([\n", - " ('norm', TextNormalizer()),\n", - " ('tfidf', TfidfVectorizer(tokenizer=lambda x: x, preprocessor=None, lowercase=False)),\n", - "])\n", - "\n", - "docs = vect.fit_transform(documents(), labels())\n", - "\n", - "viz = TSNEVisualizer() \n", - "viz.fit(docs, labels())\n", - "viz.show()" + "Subouter(KMeans())" ] }, { - "cell_type": "markdown", + "cell_type": "code", + "execution_count": 9, + "id": "15b7b68a", "metadata": {}, + "outputs": [], "source": [ - "## Classification \n", - "\n", - "The primary task for this kind of corpus is classification - sentiment analysis, etc. " + "s = Subouter(KMeans(), k=9)" ] }, { "cell_type": "code", - "execution_count": 19, - "metadata": { - "collapsed": false - }, - "outputs": [], + "execution_count": 10, + "id": "a92f539f", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "KMeans()\n", + "8\n", + "9\n" + ] + } + ], "source": [ - "from sklearn.model_selection import train_test_split as tts \n", - "\n", - "docs_train, docs_test, labels_train, labels_test = tts(docs, list(labels()), test_size=0.2)" + "print(s.estimator)\n", + "print(s.n_clusters)\n", + "print(s.k)\n", + "# print(s.foo)" ] }, { "cell_type": "code", - "execution_count": 21, - "metadata": { - "collapsed": false - }, + "execution_count": 11, + "id": "0b23c03e", + "metadata": {}, "outputs": [ { "data": { "text/plain": [ - "LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,\n", - " intercept_scaling=1, max_iter=100, multi_class='ovr', n_jobs=1,\n", - " penalty='l2', random_state=None, solver='liblinear', tol=0.0001,\n", - " verbose=0, warm_start=False)" + "{'estimator': KMeans(),\n", + " 'k': 9,\n", + " 'algorithm': 'lloyd',\n", + " 'copy_x': True,\n", + " 'init': 'k-means++',\n", + " 'max_iter': 300,\n", + " 'n_clusters': 8,\n", + " 'n_init': 10,\n", + " 'random_state': None,\n", + " 'tol': 0.0001,\n", + " 'verbose': 0}" ] }, - "execution_count": 21, + "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ - "from sklearn.linear_model import LogisticRegression \n", - "from yellowbrick.classifier import ClassBalance, ClassificationReport, ROCAUC\n", - "\n", - "logit = LogisticRegression()\n", - "logit.fit(docs_train, labels_train)" + "s.get_params()" ] }, { "cell_type": "code", - "execution_count": 23, - "metadata": { - "collapsed": false - }, + "execution_count": 12, + "id": "7d73dd40", + "metadata": {}, "outputs": [ { "data": { - "image/png": "iVBORw0KGgoAAAANSUhEUgAAA24AAAJzCAYAAAB3bkCWAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAAPYQAAD2EBqD+naQAAIABJREFUeJzs3XlcFXX////nUQQEtNLSUjJNk4OyiBtumaHSVWrqlXqV\nW26VXXpd1qXmmtnXdq8Wl0oNXLO8wlKzTC0XNCnXNBITd8F9FxDQg/P7wx/n4+mA4oK8Oz3ut1t/\nOPOamffMezid53nPYrMsyxIAAAAAwFjFiroBAAAAAIArI7gBAAAAgOEIbgAAAABgOIIbAAAAABiO\n4AYAAAAAhiO4AQAAAIDhCG4AAAAAYDiCGwAAAAAYjuAGAAAAAIYjuAEocllZWfryyy/Vs2dPNWvW\nTCEhIWrcuLH69u2rH374Ic9l7Ha7ateufYtbev0OHDggu93u9l9wcLAiIyP15JNPavbs2bIs64a3\nFRUVpeDgYJ0+ffomtNxclmVp3LhxznOmSZMm2r59+y3Z9sSJE2W32zVx4sRbsr2rmTBhgux2u6ZN\nm3Zdy2dnZ2vcuHGaPXu2y/SoqCjZ7fbrPpdyl8/rv7CwMDVp0kS9e/fWwoULr2v9nu5G+xWAZ/Eq\n6gYA+GtLSkrSgAEDlJKSolKlSikoKEhhYWE6cOCA4uPjtXLlSrVt21Zvv/12UTf1pvDz81OLFi2c\n/75w4YLOnDmjxMREjRkzRhs3btR7771XhC388/jqq6/08ccfq2TJkmrWrJkkqWLFirds+zab7ZZt\n62psNtsNtScmJkYff/yxhgwZ4javWLEb+43XZrOpRYsWKlmypMv09PR07dq1SwkJCVqzZo127dql\nF1544Ya25WlutF8BeBaCG4Ais2vXLnXu3FnZ2dl6/vnn1adPH/n7+zvnb9u2Tf3799eCBQsUEBCg\nl19+uQhbe3Pccccdeuedd9ymnz17Vp07d9Z3332ntm3b6qGHHiqC1v25bNmyRTabTS+++KK6d+9+\ny7d/M0ZHb5auXbuqVatWKlu27HUtb1lWngFhxowZcjgcuu22226ofcOGDVOFChXynDd79myNGTNG\nMTEx6tSpU751f0U32q8APAuXSgIoMoMGDVJ2drYGDBigAQMGuIQ2SQoODtaUKVPk5eWl//3vf0pJ\nSSmilha+0qVLq0ePHrIsS8uWLSvq5vwpXLhwQZJ09913F3FLit7tt9+uKlWqqHTp0te1fH4h9N57\n71WVKlUKddSnS5cuCgsLU05OjtasWVNo2/kzutF+BeBZCG4AisT69eu1bds23X333erTp0++dVWr\nVlWnTp3UtGlTHT169KrrXblypfr27asmTZooJCRE9erVU5cuXbRgwQK32tOnT+u1115Tq1atFB4e\nrsjISPXq1SvP4HTo0CENGzZMjzzyiMLCwtS4cWP985//1IYNG65tx6+gfPnykqSMjAy3eTt27NCw\nYcPUokULhYWFKSIiQm3atNHEiROVnZ1doPVv2rRJL7zwgh566CGFhoaqTp06euKJJzRz5ky3L+52\nu11dunTRyZMnNXLkSDVp0kRhYWFq27at/ve//+W5/lOnTum///2vHnnkEdWqVUstWrTQsGHDdPDg\nQbfa1NRUDRs2TE2bNlVoaKiioqL0+uuv69SpU1fdj3Xr1slut2vevHmSpH//+99u95udOHFCr732\nmp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Xv27NGm\nTZtUrFgxl3uW6tSpI+nSY9APHDigFi1aqEmTJgoICHD74lS3bl3NmTNHr7/+un777Tc1b95ckZGR\n8vX1VdeuXa+pnSVLlnS5TM+yLGVkZGjnzp1KSUlRx44d9f7776tBgwaSpICAAL355psu67AsS6mp\nqUpMTNTx48ed+5qfwMBAjR071mVaTk6O9u3bp19//dV5j9wf12Gz2RQSEuK2vrJlyzqDwW233ab1\n69dLkpo0aeJ2WVfx4sWd90tJl+5ttNlszksF/6hx48b6/ffftW7dOlWtWjXffcrPhg0bZLPZ1LJl\nyzznP/bYY5o1a5azzZf7Y6i9WQ4dOqRDhw6pcuXKqlatmtv84OBg3Xfffdq/f78OHjwoHx8f7dy5\nU9WqVcszXD3yyCP64osvrrjNsmXLqnLlytq7d686duyoxx9/XM2aNVPlypWd99ddj9z+y+upp7ff\nfruWLFmS53ItW7Z0vg7g1KlT+umnn5STk6NmzZpp8ODBuv/++13qjx49qn379qlixYp5vuKhQYMG\nKlasmLMfT5w4cd3H7PIwc/l+SsrzPPX29la9evW0ePFi/fLLL2ratOk1fUbUrVtXq1ev1osvvqi/\n//3vatasmerUqSN/f/+rfp4kJiYqOztbjRs3dgmzuR5++GH5+vpq8+bNysnJUfHixZ3zcn/kuVzu\nD2fc5wb8ORDcABSJO++8U8nJyTp58uRNW6fD4dDChQu1ePFi7dixQ4cPH9bFixdls9ncHndeu3Zt\nDRo0SOPGjdO3336rb775Rl5eXqpdu7batGmj9u3bO8Nl69attXnzZn322WeKi4vTF198IW9vbzVs\n2FDt2rXTo48+WuA25vc6AEn6+uuvNXToUD3//PNasmSJyy/yP//8s+Li4rRt2zalpKTowoULLvtz\ntREYSfrhhx80f/58JScn6+DBg3I4HFdch4+PT573H+ZOu3jxoqT/G0HIfcDElRw+fFiWZWno0KEa\nOnRonjU2m01Hjhy56rryktuW/B4pnxsCcgNvrpt9T1tebbrSO+YCAwO1f/9+HT9+3PllO7/7/Ar6\nuPz3339f//rXv7Rt2zYlJSXprbfe0r333qvo6Gh17dq1QP31R9fS15f74+sAdu/erZ49e2rFihUK\nCgpye39b7ghy7gh1fk6ePKmcnBxn/bUeM5vNlucTG3PX161bt3y3ffl5ei2fEb169VJSUpKWLl2q\nGTNmaPr06fLz81PTpk3VoUOHK94vm3ulQH7nUvHixVW+fHnt379fp0+fdnmNQF73Heb+LRfk8wNA\n0SO4ASgSNWvW1Jo1a/Trr7+qffv2V6xNTEzUunXr1Lhx43y/xJ07d05du3ZVUlKSAgICFBYWphYt\nWig4OFiRkZFq1aqVsrKyXJbp06eP2rZtqyVLlmjVqlXasGGD8wb/L7/8UrNmzXJ+mR85cqSefvpp\nLV68WKtXr9bmzZu1atUqxcfH67vvvtP48eNv+Jg8/vjjWrRokeLj4zV//nw9++yzki49nOWLL76Q\nl5eXQkJC1L59e1WvXl21a9fWuHHjtGrVqiuu9+LFi3ruuee0evVq+fr6KjQ0VE2aNHFervbvf/87\nz0ulCvoI+JycnALvY05Ojmw2mxo3buxyyeAfXc9om3T1L6C58729vV2mF+bj7gvypTg3BHt7eztH\nQPNbrqBfsoODg7V48WKtWrVKy5cvV0JCglJTUxUbG6vPPvtM06dPV3h4eAH34pJr6esruf/++zV+\n/Hh17txZkydPVuXKldWuXTvn/Nzjceedd7pdInw5m80mh8PhHLm/nmOW1wvGc/czOjpavr6++S57\neSAs6GdEiRIlNG7cOCUnJ2vp0qX68ccf9dtvv2nJkiVavHixevToke+PGgVRFOc4gFuD4AagSDz8\n8MOaMmWK4uPj5XA4rvhkydmzZ2v+/PnavXu3Xn/99Txrpk6dqqSkJEVHR2vs2LHy8fFxzrtw4YIy\nMzPz/OJy1113qWvXruratascDod+/PFHjRo1Slu2bNH333+vxx57zFl777336plnntEzzzyjrKws\n/fDDD3rllVf0/fffa8uWLdf8JTgvDzzwgFauXOm8H2/dunX64osvdP/99ys2NtZtpCOv+4n+aMGC\nBVq9erVq166tSZMmuY0wFGQdV5J7uVV+o2QrVqxQVlaWHnzwQecoYqdOnRQdHX1D281LuXLlZFmW\nDhw4kOf83HcB3soXGufuc2pqar41ufPKlCnj/OKd12sUpPyPc168vLwUFRWlqKgoSZfuZRo3bpy+\n//57TZgwQTExMQVel3T1vv7222/l4+OjZs2aXfVpseHh4erVq5c++eQTvf7662rUqJHzWN11112S\nLl1+md8I9eVyR9puxjHL3f6+ffv03HPPqWbNmgVe7lo+I6pXr67q1aurf//+SktL09dff60333xT\nM2fOVK9evdzugZP+71zK7/x2OBw6fPiwvLy8runJngD+HHg4CYAiERERoVq1aunQoUOaOnVqvnVJ\nSUlavHixbDabOnfunG/dr7/+KpvNpu7du7uENkl5vtR37NixatKkiTZt2uSc5uXlpWbNmumJJ56Q\nJGd4GjhwoBo0aODy5c/X11etW7dW8+bNXWpv1L59+2Sz2ZwBLXe/WrVq5RbaTp48qW3btkn6vxGK\nvOSuo1OnTm6hbceOHc7Lr660jivJvV8qv5cnjxkzRi+99JKkS5eoWpaV7yjhyy+/rCeffFJr1669\nrrbk3rv4/fff5zl/8eLFki7dZ3Sr3HPPPbrnnnu0f/9+JScnu81PSkpSSkqKKlWqpHLlyql8+fKq\nVKmS9u7dq/3797vVL1++/Krb3LBhg/72t79p9OjRLtOrVq2qwYMHy7KsKz7QJj8RERGyLEs//vij\n27ysrCwNHz5co0ePvmpoy9W/f38FBgYqPT1db731lnN6xYoVdffdd2vv3r15Bt7k5GS1atXK+V62\nm3HMLlenTp0rnqfPPfecunbt6hypvpbPiG7duunBBx90uae0VKlS6tKli8LDw2VZVr5Bs2bNmvL1\n9dXGjRvzfJjQihUrdP78edWrV++a9hfAnwPBDUCRGTVqlLy8vPT+++9rwoQJbjfIJyQk6J///Key\ns7PVsWPHK/7yfffdd8uyLK1YscJl+m+//eby5TX3MrQKFSro+PHjGjdunMvLdNPT053rCAsLk3Tp\nS+Hp06f13//+1+VhKseOHdPatWtVrFixa/pVPj/Lli3TsmXLVLx4cec9Mbn7tWbNGpcvesePH9eA\nAQOcl39e6SXcuetYtWqVyyVj+/fv13/+8x/nvwv6Iu8/qlKliurXr699+/a5PSDmww8/1MGDB/XQ\nQw8pICBArVq1UtmyZfXVV1+5PLREkubPn6+5c+dq586d1308GzRooOrVq2vr1q364IMPXPb3hx9+\n0Jw5c+Tn5+dyWd71upZLz7p16+a8t+/EiRPO6UePHtXQoUNls9n01FNPOad37dpVlmVpxIgRSk9P\nd05PSEjQnDlz8ny/1+WqV6+u1NRULViwQImJiS7zFi5cKMn1YRU+Pj6yLMv5lMT85D6B8aeffnJ5\n2MfFixf1+uuv6/z582rVqtVVjsb/8fHx0fDhw2VZlr777jv9/PPPznldu3bVhQsX9NJLLznvrZOk\nM2fOaPjw4dq9e7fLvV43eswu16lTJ/n4+GjKlClavXq1y7xJkyYpPj5eR44ccT5U5Vo+I8qUKaPj\nx4+7XV69a9cubdu2TX5+fvleKlyyZEk98cQTysrK0uDBg5WRkeGct3v3br322mtX/ZELwJ8Xl0oC\nKDI1atRQTEyM+vXrp48++kgzZsxQSEiI/P39tWfPHu3evVs2m02tW7e+6ku4O3furK+++kqxsbFa\ns2aN7rvvPh06dEi//vqr6tWrpzJlymjbtm06duyYAgMD1bFjR3399ddat26doqKinJcwbd68WWfO\nnNGjjz7q/NX6ueee0/fff69vvvlG69evV82aNXX+/Hlt3LhRmZmZ6tOnj8sLi6/k1KlTbi/HdTgc\n2rdvn5KSkpyPVc9dX1RUlAIDA/XLL78oOjpaoaGhSktL08aNG1W2bFlFR0dr6dKlbg/buFy7du00\ndepUfffdd0pKSlJQUJBOnDihX375RVWrVlWjRo30008/6fjx49d9b9nrr7+ubt26acqUKVq6dKmq\nV6+u3bt3a8eOHSpfvrxeffVVSZKfn5/effddPf/88xo6dKg++eQT3X///UpNTdW2bdvk5eWld999\n1+Vx7tfqvffeU48ePTR58mR99913Cg4O1qFDh7Rlyxb5+vrqrbfeuq4Hc/yRZVmKjY3VnDlz8q2Z\nMWOGqlatqh49emjTpk1atmyZWrZsqfr160u6dClsZmamHn30UZfH63fp0kXLly/X2rVr1bJlS9Wr\nV0+nTp3Shg0bVKlSJe3fv99tVOvykFq6dGm99NJLevPNN/WPf/xDtWvXVpkyZbR3714lJyfrzjvv\n1L/+9S9nfeXKlSVJ06dP144dO9S+fXvn5ZWXK1asmMaOHavevXtr1KhRmjNnjgIDA50PzalevbrL\njwEFERUVpYceekjx8fEaM2aMvv76axUvXly9evXShg0bFB8fr7/97W8KCwuTj4+PNmzYoIyMDNWv\nX995H+jNOGaXq1Chgl577TUNGzZMzzzzjGrUqKHAwEAlJydr7969CggI0AcffOAMgtfyGTFo0CD9\n/PPPiomJ0dKlSxUUFKT09HStX79eDodDr7zyistj/v/YxkGDBmnr1q1as2aNmjdvrnr16uncuXNa\nt26dHA6Hevbs6faC+SvhwSTAnwcjbgCKVGRkpL799lv16dNHlSpVUmJiouLj43X27Fm1aNFCkydP\n1tixY/O89OryX8/tdrs+/fRTNWrUSEeOHHGOLr366quaMWOG87HeuaNp3t7eio2NVa9evXTbbbcp\nISFB69atU6VKlTRq1Ci9++67znXfdtttmj17tjp16qTixYtr1apV2rx5s0JCQvTuu+9q4MCBBdpX\nm82mzMxMffPNNy7/LV++XGfOnFGrVq00ffp09erVy7mMn5+fPv30Uz3++OOSpPj4eB06dEg9e/bU\n119/rfbt28tms7mNNF5+bMqXL6/PPvtMzZs3V0ZGhvP4vvjii5o7d67zC/qV1nGlYy9durfnyy+/\nVJcuXZSdna3ly5fr1KlT6tChg7744guXe8oaNGigefPmqX379kpPT1d8fLwzLM+dOzfPR81fi2rV\nqmnevHnq3LmzLly4oOXLl+vw4cNq37694uLi8ry37noe3GCz2ZSVlaUTJ07k+d/Jkyedo6TFihXT\nhAkTNHr0aFWtWlVr167Vpk2bVLNmTb3zzjt67733XNZdvHhxTZkyRf369VPp0qW1cuVKHTx4UC+8\n8IIGDhwoy7Lcwu0f96F79+4aO3asateure3bt2vFihXKyMhQ586dNW/ePJcHa7Ro0ULdunWTt7e3\n82EZ+a03LCxMX331ldq3b69jx45p+fLlysnJUY8ePTR79my3S5ULc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a/v7+RkpJycxurBAgLCzO6detm\n5ObmWsu2bNliNGzY0NqHunfvbjN2GsblvtihQwejT58+1rKijpUF8xZlHI+KijJatWplpKenW8sO\nHjxoNGrUyOY9URqlpqYaDRs2NP7xj3/YlE+dOtV46KGHDMP433ZOTEy0Tj937pwRFhZmdOjQwVoW\nHh5uBAcHGydOnLCW5ebmGv369TOaN29u3f4Fy9u3b5/NOj/66CPD39/f2LVrl7WsR48exiOPPGJT\nLyEhwejbt69x9OjRm/vjUSy4VBIOddddd6l9+/bW15UqVVKfPn104MABfffddzpx4oSGDRsmb29v\na50KFSpo6NChOnHihH744Qft37+/UPWu9Nxzz2nz5s2aMWOGzfolqXr16tq0aZPWrVunrKwsSdL4\n8eO1evVqeXl5FcdmKFHS0tKUlJSk3r17q2LFitbyevXqae3atRo1atRV5/P09FSHDh2sr93d3VW/\nfn2dPn1akpSRkaHdu3crNDRUOTk5Sk9PV3p6us6cOaOwsDClpqYqKSnJOr+Hh4fNvqtfv74kKSws\nzGa9tWrVst6AXbZsWX311VfWbzULpKeny8fHhyeoFcH+/fuVmpqq/v37q0yZMtbyPn36qFKlStec\nr3fv3srMzNSXX35pLUtMTFTLli3l6+tbrG12JTfqj927d9cff/zh8HH0Wq48ay5J/v7+1jFAunzW\nLzQ0VPXq1bOW+fn5qU+fPoVafkl3+PBhHTt2TIMHD5a7u7u1vFOnTrrjjjusrzdu3KglS5bYzHvq\n1ClVrFjRbhwrylh5LTcaxzMzM7V792498MADuu2226z1/P391a5du+suuzTw8fGRt7e34uLitHnz\nZp07d06S9OKLL9pc0VO3bl2bvuLp6amIiAhrP0xNTdW+ffvUt29f+fn5Weu5u7tr5MiROn/+vL76\n6iub+QvOql3P7bffrm+++UYrVqxQamqqpMuXr69bt0516tS56b8ftx7BDQ5VcAC5Ut26dSVJ//73\nv2WxWGwO4AXuvPNOSVJKSoqOHz9+3XqGYSglJcValpKSojVr1shisVjvx7jS888/L8MwNHXqVLVp\n00bDhg3Te++9p7Nnzxbx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FEkZY7bdo0DR8+XP37\n91dERISqVKmiTZs2ae/evZowYcJ1H3ZRGEFBQfLx8dFLL72klJQUVapUSd988422b9+uWrVq2Xzw\nReFNnz5dMTExGjhwoAYMGKA//vhD8fHxN9xfZcqUUffu3RUXFydvb2+b36hC4d2oPwYFBTl8HC2q\nxx9/XF988YUGDhyoyMhIlStXTgkJCdYQ4OqPI7dYLJo8ebKeeOIJDR48WH379lVqaqo++OADeXh4\nyGKxqEGDBqpZs6YWL16s3NxcVa9eXUlJSdqwYYPuuOMOp591mzRpkiIjIzVgwAANHjxYubm5io2N\n5QefdflL4NatW+uNN95QSkqKGjZsqN9//11xcXG688471bZtW7377rtyd3fXmDFjFBUVpUqVKmnN\nmjU6deqUZs+ebV1WwfFywIABGjJkiMqXL6/169fr4MGDmjZtmvWnI66lSpUqMgxD8fHxOnXqlHr1\n6qWoqCi99dZbiomJUfv27XXu3DmtWrVKXl5e6t+/f3FvHhQBpxPgMBaLRaGhoRo7dqxWrlypN998\nU7Vr11ZsbKz126f7779fy5YtU/Xq1fXWW2/p3XffVd26dbVixQqbD3mFrVew3gJubm567rnnlJub\nqxdeeEHS5YeTPProo/r+++/14osvavny5WrRooXi4+MLfYOvqwsJCdGKFStUo0YNvfXWW1q6dKkC\nAwO1cuVK6w3vf/6Ada0PXFeWN2/eXCtXrlRgYKDef/99vfLKK8rJydGcOXM0cuTIGy7vRuuoWrWq\nlixZorp16+qdd97R3LlzZRiG1q5dq549e+qnn34q8hnD0uy+++7T4sWL5eXlpTfeeENbtmzRSy+9\npPr169v9ltefFTyMJCwsjHtgiuha/TE+Pl5Vq1Z1yjj65zpXe3218jp16ig2Nlb+/v5avHixli5d\nqs6dO2vo0KGSrn7vlKu5//77NW/ePF26dEmvvfaaEhMTNWXKFDVp0kTu7u4qV66clixZoubNm2vF\nihV6+eWX9ccff+iDDz5QdHS0zp49az07JxVtrCzs66uVN2/eXMuWLVOVKlU0f/58ffjhh4qKilKX\nLl1Kxf67kTfffFMRERH64osvNGvWLK1evVr333+/3n//fetZrUaNGmnatGn6+OOPNX/+fFWrVk0r\nVqxQSEiIdTkFx8uAgAAtX75c8+fPl5eXlxYtWmTtLwWutt/atGmjHj16aMeOHZo5c6YuXLigcePG\nacqUKTp69KhefvllLVq0SHXr1lVcXBz3t5mUxeArEQCAg+zdu1eDBg3S0qVLde+99zq7OXCytLQ0\nuydPSpcfxpGQkKC9e/de98FVJd2lS5eUkZFx1W1Q8KPJBT9mbVapqal2T6yUpDFjxig5OVlbt251\nQqtKjsjISOXl5enDDz90dlNQAnDGDQDgMCtXrlT16tX5jSdIunypZM+ePW3Kzp07p23btqlRo0Yu\nHdqky/f0hoaG6vnnn7cpP3z4sH766Sc1bdrUOQ37C8LDw+2ukDh9+rS++eabEtF+oCThHjcAQLGb\nPn26jh49ql27dmny5Mkuf+8SCqdfv3565plnNGrUKHXu3Fm5ublav369Tp48qVmzZjm7ecWuXLly\n6t27t9asWSNJatKkiU6ePGm9DH3EiBFObuGN9evXT4sWLdKECRPUunVrnTlzRqtXr5YkjRs3zsmt\nA1wLwQ0AUOxSU1OVlJSkwYMH8xt6sOrfv7+8vLz03nvv6bXXXpObm5sCAgL03nvvqUWLFs5unkPM\nmDFD9erV0/r16/Xxxx/Lx8dH7dq10+OPP65q1ao5u3k39Nhjj6latWpKSEjQ1q1b5enpqXvuuUcL\nFiyw+S1OADePe9wAAAAAwOS4xw0AAAAATI7gBgAAAAAmR3ADAAAAAJMjuAEAAACAyRHcAAAAAMDk\nCG4AAAAAYHIENwAAAAAwOYIbAAAAAJjc/wHwiwk5uC6mkgAAAABJRU5ErkJggg==\n", + "text/html": [ + "<style>#sk-container-id-3 {color: black;background-color: white;}#sk-container-id-3 pre{padding: 0;}#sk-container-id-3 div.sk-toggleable {background-color: white;}#sk-container-id-3 label.sk-toggleable__label {cursor: pointer;display: block;width: 100%;margin-bottom: 0;padding: 0.3em;box-sizing: border-box;text-align: center;}#sk-container-id-3 label.sk-toggleable__label-arrow:before {content: \"▸\";float: left;margin-right: 0.25em;color: #696969;}#sk-container-id-3 label.sk-toggleable__label-arrow:hover:before {color: black;}#sk-container-id-3 div.sk-estimator:hover label.sk-toggleable__label-arrow:before {color: black;}#sk-container-id-3 div.sk-toggleable__content {max-height: 0;max-width: 0;overflow: hidden;text-align: left;background-color: #f0f8ff;}#sk-container-id-3 div.sk-toggleable__content pre {margin: 0.2em;color: black;border-radius: 0.25em;background-color: #f0f8ff;}#sk-container-id-3 input.sk-toggleable__control:checked~div.sk-toggleable__content {max-height: 200px;max-width: 100%;overflow: auto;}#sk-container-id-3 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {content: \"▾\";}#sk-container-id-3 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-3 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-3 input.sk-hidden--visually {border: 0;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);height: 1px;margin: -1px;overflow: hidden;padding: 0;position: absolute;width: 1px;}#sk-container-id-3 div.sk-estimator {font-family: monospace;background-color: #f0f8ff;border: 1px dotted black;border-radius: 0.25em;box-sizing: border-box;margin-bottom: 0.5em;}#sk-container-id-3 div.sk-estimator:hover {background-color: #d4ebff;}#sk-container-id-3 div.sk-parallel-item::after {content: \"\";width: 100%;border-bottom: 1px solid gray;flex-grow: 1;}#sk-container-id-3 div.sk-label:hover label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-3 div.sk-serial::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: 0;}#sk-container-id-3 div.sk-serial {display: flex;flex-direction: column;align-items: center;background-color: white;padding-right: 0.2em;padding-left: 0.2em;position: relative;}#sk-container-id-3 div.sk-item {position: relative;z-index: 1;}#sk-container-id-3 div.sk-parallel {display: flex;align-items: stretch;justify-content: center;background-color: white;position: relative;}#sk-container-id-3 div.sk-item::before, #sk-container-id-3 div.sk-parallel-item::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: -1;}#sk-container-id-3 div.sk-parallel-item {display: flex;flex-direction: column;z-index: 1;position: relative;background-color: white;}#sk-container-id-3 div.sk-parallel-item:first-child::after {align-self: flex-end;width: 50%;}#sk-container-id-3 div.sk-parallel-item:last-child::after {align-self: flex-start;width: 50%;}#sk-container-id-3 div.sk-parallel-item:only-child::after {width: 0;}#sk-container-id-3 div.sk-dashed-wrapped {border: 1px dashed gray;margin: 0 0.4em 0.5em 0.4em;box-sizing: border-box;padding-bottom: 0.4em;background-color: white;}#sk-container-id-3 div.sk-label label {font-family: monospace;font-weight: bold;display: inline-block;line-height: 1.2em;}#sk-container-id-3 div.sk-label-container {text-align: center;}#sk-container-id-3 div.sk-container {/* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */display: inline-block !important;position: relative;}#sk-container-id-3 div.sk-text-repr-fallback {display: none;}</style><div id=\"sk-container-id-3\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>Subouter(estimator=KMeans(), k=9)</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item sk-dashed-wrapped\"><div class=\"sk-label-container\"><div class=\"sk-label sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-7\" type=\"checkbox\" ><label for=\"sk-estimator-id-7\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">Subouter</label><div class=\"sk-toggleable__content\"><pre>Subouter(estimator=KMeans(), k=9)</pre></div></div></div><div class=\"sk-parallel\"><div class=\"sk-parallel-item\"><div class=\"sk-item\"><div class=\"sk-label-container\"><div class=\"sk-label sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-8\" type=\"checkbox\" ><label for=\"sk-estimator-id-8\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">estimator: KMeans</label><div class=\"sk-toggleable__content\"><pre>KMeans()</pre></div></div></div><div class=\"sk-serial\"><div class=\"sk-item\"><div class=\"sk-estimator sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-9\" type=\"checkbox\" ><label for=\"sk-estimator-id-9\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">KMeans</label><div class=\"sk-toggleable__content\"><pre>KMeans()</pre></div></div></div></div></div></div></div></div></div></div>" + ], "text/plain": [ - "<matplotlib.figure.Figure at 0x146a61940>" + "Subouter(estimator=KMeans(), k=9)" ] }, + "execution_count": 12, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" } ], "source": [ - "logit_balance = ClassBalance(logit, classes=set(labels_test))\n", - "logit_balance.score(docs_test, labels_test)\n", - "logit_balance.show()" + "s" ] }, { "cell_type": "code", - "execution_count": 27, - "metadata": { - "collapsed": false - }, + "execution_count": 13, + "id": "65d018fd", + "metadata": {}, "outputs": [ { - "ename": "IndexError", - "evalue": "list index out of range", - "output_type": "error", - "traceback": [ - "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", - "\u001b[0;31mIndexError\u001b[0m Traceback (most recent call last)", - "\u001b[0;32m<ipython-input-27-7b911cc79c37>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mlogit_balance\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mClassificationReport\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mlogit\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mclasses\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mset\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mlabels_test\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mlogit_balance\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mscore\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdocs_test\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mlabels_test\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 3\u001b[0m \u001b[0mlogit_balance\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mshow\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;32m/Users/benjamin/Repos/tmp/yellowbrick/yellowbrick/classifier.py\u001b[0m in \u001b[0;36mscore\u001b[0;34m(self, X, y, **kwargs)\u001b[0m\n\u001b[1;32m 133\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mscores\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mmap\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;32mlambda\u001b[0m \u001b[0ms\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0mdict\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mzip\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mclasses_\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0ms\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mscores\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;36m3\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 134\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mscores\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mdict\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mzip\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mkeys\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mscores\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 135\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mdraw\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0my\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0my_pred\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 136\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 137\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mdraw\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0my\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0my_pred\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;32m/Users/benjamin/Repos/tmp/yellowbrick/yellowbrick/classifier.py\u001b[0m in \u001b[0;36mdraw\u001b[0;34m(self, y, y_pred)\u001b[0m\n\u001b[1;32m 158\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mcolumn\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mrange\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mlen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmatrix\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m+\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 159\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mrow\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mrange\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mlen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mclasses_\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 160\u001b[0;31m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0max\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mtext\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mcolumn\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mrow\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmatrix\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mrow\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mcolumn\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mva\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m'center'\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mha\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m'center'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 161\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 162\u001b[0m \u001b[0mfig\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mplt\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mimshow\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmatrix\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0minterpolation\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m'nearest'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mcmap\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mcmap\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mvmin\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mvmax\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;31mIndexError\u001b[0m: list index out of range" - ] + "data": { + "text/html": [ + "<style>#sk-container-id-4 {color: black;background-color: white;}#sk-container-id-4 pre{padding: 0;}#sk-container-id-4 div.sk-toggleable {background-color: white;}#sk-container-id-4 label.sk-toggleable__label {cursor: pointer;display: block;width: 100%;margin-bottom: 0;padding: 0.3em;box-sizing: border-box;text-align: center;}#sk-container-id-4 label.sk-toggleable__label-arrow:before {content: \"▸\";float: left;margin-right: 0.25em;color: #696969;}#sk-container-id-4 label.sk-toggleable__label-arrow:hover:before {color: black;}#sk-container-id-4 div.sk-estimator:hover label.sk-toggleable__label-arrow:before {color: black;}#sk-container-id-4 div.sk-toggleable__content {max-height: 0;max-width: 0;overflow: hidden;text-align: left;background-color: #f0f8ff;}#sk-container-id-4 div.sk-toggleable__content pre {margin: 0.2em;color: black;border-radius: 0.25em;background-color: #f0f8ff;}#sk-container-id-4 input.sk-toggleable__control:checked~div.sk-toggleable__content {max-height: 200px;max-width: 100%;overflow: auto;}#sk-container-id-4 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {content: \"▾\";}#sk-container-id-4 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-4 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-4 input.sk-hidden--visually {border: 0;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);height: 1px;margin: -1px;overflow: hidden;padding: 0;position: absolute;width: 1px;}#sk-container-id-4 div.sk-estimator {font-family: monospace;background-color: #f0f8ff;border: 1px dotted black;border-radius: 0.25em;box-sizing: border-box;margin-bottom: 0.5em;}#sk-container-id-4 div.sk-estimator:hover {background-color: #d4ebff;}#sk-container-id-4 div.sk-parallel-item::after {content: \"\";width: 100%;border-bottom: 1px solid gray;flex-grow: 1;}#sk-container-id-4 div.sk-label:hover label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-4 div.sk-serial::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: 0;}#sk-container-id-4 div.sk-serial {display: flex;flex-direction: column;align-items: center;background-color: white;padding-right: 0.2em;padding-left: 0.2em;position: relative;}#sk-container-id-4 div.sk-item {position: relative;z-index: 1;}#sk-container-id-4 div.sk-parallel {display: flex;align-items: stretch;justify-content: center;background-color: white;position: relative;}#sk-container-id-4 div.sk-item::before, #sk-container-id-4 div.sk-parallel-item::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: -1;}#sk-container-id-4 div.sk-parallel-item {display: flex;flex-direction: column;z-index: 1;position: relative;background-color: white;}#sk-container-id-4 div.sk-parallel-item:first-child::after {align-self: flex-end;width: 50%;}#sk-container-id-4 div.sk-parallel-item:last-child::after {align-self: flex-start;width: 50%;}#sk-container-id-4 div.sk-parallel-item:only-child::after {width: 0;}#sk-container-id-4 div.sk-dashed-wrapped {border: 1px dashed gray;margin: 0 0.4em 0.5em 0.4em;box-sizing: border-box;padding-bottom: 0.4em;background-color: white;}#sk-container-id-4 div.sk-label label {font-family: monospace;font-weight: bold;display: inline-block;line-height: 1.2em;}#sk-container-id-4 div.sk-label-container {text-align: center;}#sk-container-id-4 div.sk-container {/* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */display: inline-block !important;position: relative;}#sk-container-id-4 div.sk-text-repr-fallback {display: none;}</style><div id=\"sk-container-id-4\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>ModelVisualizer(ax=&lt;AxesSubplot:&gt;, estimator=KMeans(),\n", + " fig=&lt;Figure size 432x288 with 1 Axes&gt;)</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item sk-dashed-wrapped\"><div class=\"sk-label-container\"><div class=\"sk-label sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-10\" type=\"checkbox\" ><label for=\"sk-estimator-id-10\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">ModelVisualizer</label><div class=\"sk-toggleable__content\"><pre>ModelVisualizer(ax=&lt;AxesSubplot:&gt;, estimator=KMeans(),\n", + " fig=&lt;Figure size 432x288 with 1 Axes&gt;)</pre></div></div></div><div class=\"sk-parallel\"><div class=\"sk-parallel-item\"><div class=\"sk-item\"><div class=\"sk-label-container\"><div class=\"sk-label sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-11\" type=\"checkbox\" ><label for=\"sk-estimator-id-11\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">estimator: KMeans</label><div class=\"sk-toggleable__content\"><pre>KMeans()</pre></div></div></div><div class=\"sk-serial\"><div class=\"sk-item\"><div class=\"sk-estimator sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-12\" type=\"checkbox\" ><label for=\"sk-estimator-id-12\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">KMeans</label><div class=\"sk-toggleable__content\"><pre>KMeans()</pre></div></div></div></div></div></div></div></div></div></div>" + ], + "text/plain": [ + "ModelVisualizer(ax=<AxesSubplot:>, estimator=KMeans(),\n", + " fig=<Figure size 432x288 with 1 Axes>)" + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" }, { "data": { - "image/png": "iVBORw0KGgoAAAANSUhEUgAABwIAAAsPCAYAAADlFF+DAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAAPYQAAD2EBqD+naQAAIABJREFUeJzs3X+s1fV9x/HXRURBFLEVFVZ0ReW26lplkFlnnbiN/rCb\nm3Wb1i2Q1VkWW+M2I83mXOcMbrVWlKqpzNbWH5l1NVVTzdRaW39MEWW2K1WprNhaGkBW5Zd3XM7+\nIJxw5QL3eygIbx+PpH94zud+/JzvRfJ959lzTler1WoFAAAAAAAAKGXQm30AAAAAAAAA4JdPCAQA\nAAAAAICChEAAAAAAAAAoSAgEAAAAAACAgoRAAAAAAAAAKEgIBAAAAAAAgIKEQAAAAAAAAChICAQA\nAAAAAICChEAAAAAAAAAoaHCnP/jwww/ni1/8Yl544YUkybHHHpvzzjsvxxxzzIB+vqenJ1/60pdy\n9913Z/HixRk5cmQmTZqUT3ziExk3btxm6++88858+tOf3uJ+l19+eU477bT2P7dardx666352te+\nlkWLFmXQoEE58sgjc+aZZ/ZZt1Fvb2+++tWv5q677sqiRYvSarXyq7/6qznttNPyp3/6pxk0qG8z\nbXr+ptesk/03tWTJknz4wx/O/vvvnwcffLDfNQsWLMh1112Xp556Kq+99lpGjx6dU089Neeee26G\nDBmyXefv5Pp/+ctfzp133pkf//jH2WeffXLcccflnHPOybHHHrvN1wsAwFvTzp5Lkh17H910Lnmj\ngcwBTdc3fb1N9t/Zc8Ps2bMze/bs/Od//mf233//7T4PAAAku34vabp/J3NJ07mhyfpO7tN39zls\ne9a/UVer1Wo1/aF/+7d/yyWXXJKhQ4fm+OOPz8qVKzNv3rx0dXXlhhtuyPHHH7/Vn+/p6cm0adMy\nb968DB06NO9973vT29ub+fPnZ9CgQZk1a1ZOOumkPj9z2WWX5eabb8773//+jBgxYrM9//iP/zgT\nJkxo//OFF16Yu+++O0OHDs3EiROzfv36PPnkk+np6cnUqVMzY8aM9tre3t6ce+65eeSRR7Lvvvvm\n137t15Ik8+fPz6pVq3LyySfn2muvTVdXV8fnb3LNOtn/jaZNm5bHH388Y8aM6fcPxv33358LLrgg\nvb29Oe6447Lffvvl6aefzi9+8YtMnjw51157bcfnb3r9k+SCCy7IvffemxEjRuS4447LqlWrMm/e\nvLRarfzzP/9zPvKRj2z19QIA8NbzZswlO/I+uulc0p9tzQFN1zd9vU3335lzw0MPPZRPfvKT6e3t\nzeOPP95vCGx6HgAA2NV7SdP9O5lLms4NTdc3vU/f3eew7V2/mVZDS5YsaR199NGtE044obV48eL2\n4w8//HDrqKOOap188smtnp6ere5x5ZVXtsaPH9/64Ac/2GePBQsWtH7jN36jNXHixNby5cv7/MzZ\nZ5/d6u7ubr366qvbPOPcuXNb48ePb5100kmtl19+uf34woULWxMnTmx1d3e3nnvuufbjt9xyS2v8\n+PGtj370o33+vT//+c9bp556aqu7u7t12223dXz+ptesk+uzqZtvvrk1fvz4Vnd3d2vy5MmbPb9s\n2bLWhAkTWu9973tbjzzySPvx5cuXtz7ykY+0uru7W/fdd1/H5296/e++++7W+PHjW3/4h3/Y5/f7\nxBNPtI466qjWxIkTW6tWrdri6wUA4K3nzZhLdvR9dNO55I22NQc0Xd/09Tbdf2fODbfffnvrmGOO\naZ9nxYoV230eAADYHXpJ0/2bziVN54am65vep+/uc9j2ru9P4+8IvPnmm7Nu3bp8/OMfzzve8Y72\n4+9///tz2mmn5Wc/+1nuv//+re7x7//+7+nq6spll13WZ4/u7u586lOfyquvvpqbbrqpz8/88Ic/\nzOjRo7Pvvv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ur7p3LC7z2E7Qler1Wo1/aGvfOUrmTlzZvbcc8+8733vy5o1azJ37twMHjw4\nN954Y5+6u/EzVL/1rW9l9OjR7cenTp2aJ554IoccckiOPvroLFq0KC+88EIOPPDA3HzzzTn00EPb\na9euXZtp06Zl/vz5GT58eCZMmJCenp48+eSTWb9+fS6++OI+XyzZ29ubv/zLv8x3vvOd7L333pk0\naVJ6enoyf/78rF27NlOmTMlVV12VZMNbPn/rt34rr7/+eo4++ugcdthh/b7mAw44IJ/+9Kc7On/T\na9bJ/m+0YsWKHH/88RkzZkwefPDBzZ7/13/911xxxRVJNtT1IUOG5Omnn87atWvziU98Iueff37H\n529y/ZNk3bp1mT59eh555JHss88+mTBhQlavXp1nn302PT09OfPMM/P3f//3W329AAC89ezsuSTZ\ncffRnc4lb7StOaDp+qavt8n+b8bcMHny5PzsZz/L448/nv3333+7zgMAAMmu30ua7N/pXNJ0bmiy\nvpP79N19Dtve9W/UUQhMNryFcs6cOXnuuecybNiwHHPMMTn//PPzrne9q8+67u7uDBo0KA888ECf\nP9hr1qzJNddck/vuuy/Lli3LIYcckhNPPDHnnntun+/V2Kinpyc33nhj7rnnnixevDhDhw7Ne97z\nnpxzzjmZOHHiZuvXr1+f2267LV//+tfz4osvJkmOOOKInHHGGTnjjDPa6+6///586lOf2ubrHTNm\nTB544IGOz9/kmnW6/6ZWrFiR973vfZude1OPP/545syZk+9973vp7e3NkUcemalTp/ap4Z2ef6DX\nf9P1X/nKV3LnnXfmf/7nf7Lnnnvm3e9+dz72sY9t8TwAALCz55Jkx9xHdzqXvNFA5oCm65u+3ib7\n7+y5YfLkyVmyZEkee+yxzUJgJ+cBAIBk1+8lA91/e+aSpnNDk/Wd3Kfv7nPY9qx/o45DIAAAAAAA\nALDravwdgQAAAAAAAMCuTwgEAAAAAACAgoRAAAAAAAAAKEgIBAAAAAAAgIKEQAAAAAAAAChICAQA\nAAAAAICChEAAAAAAAAAoSAgEAAAAAACAgoRAAAAAAAAAKEgIBAAAAAAA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0efPn1i8uTJccABB7R5zdlnnx333HNPbLrpprHPPvtEU1NTzJo1K4qiiMsuuyyO\nOOKINutnzJgRZ599drS0tMQ+++wTm2yySTz99NPx7rvvxpgxY+Kaa67p0fqy+7H/3t0/AAD0dC6J\niDj33HPjzjvvjIEDB0ZDQ0O0trbGE088Ec3NzTFu3LiYMGHCOl9/8sknx2OPPRbDhg3rVgjsan1P\n3xev6/otLS0xfvz4ePjhh2PjjTeOz3zmMxERMXv27GhqaoqDDjoorrnmmqhUKjXfn4svvjimTZsW\n+++/f2y66abt9vfNb34zRo4cGRER3//+9zv9OWbPnh1vvPFG7LLLLnHbbbd1uObBBx+M7373u9HS\n0hKPPfZYt0JgV/e/7NwDAAAfxVyyPtfXMjeUmWPKXr+WnrSm7swNZZ5h2Tmmlv33dE5tpyhpwYIF\nxe67716MHj26mD9/fvX4zJkzi91226046KCDiubm5nVe48orryzq6uqKQw89tM015syZU3zuc58r\nGhoaisWLF1eP33nnnUVdXV3x9a9/vXjvvfeqxx9//PFit912KxoaGoqmpqbq8UWLFhUjR44s9tpr\nr+Lhhx+uHl+8eHFxxBFHFPX19cW9995b8/qy+7H/3t0/AAD0xlzy5JNPFnV1dcUBBxxQvP3229Xj\nc+fOLRoaGor6+vripZde6vT106ZNK+rq6or6+vpizJgxXe65q/U9fV/c1fVvvvnmoq6urjjmmGPa\nzFvvvPNOcfjhhxf19fXFrbfeWj1ey/058cQTi/r6+jZzQ1mvv/56sddeexWjRo0qFixY0OGaP/zh\nD8Uee+xR/XkbGxu7vG5X96fs3AMAAB/FXLK+15edG8rOMWWvX7Ynrak7c0NvPMOi6HyOKbv/ns6p\nHSn9HYHTpk2LVatWxSmnnBKf/vSnq8f333//OOqoo+I///lPzJgxY53X+NOf/hSVSiUuvvjiNteo\nr6+PM888M95777246aabqsfvuuuuqFQq8b3vfS823njj6vFRo0bF6NGjY+nSpfHss89Wj998883R\n1NQUp59+eowePbp6fMiQIXHWWWfF1ltvXf3zzlrWl92P/ffu/gE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TV1RXHHHNMsXDhwurx119/vTjkkEOK+vr64q67\n7qoenzJlSlFfX1/85S9/qR5bsmRJUVdXV4wZM6bd9cusr+V9cdn9dOTCCy8s6urqilGjRhVz585t\nc67s/Xn//feLuXPnFqtWrWr37zzwwANFXV1dceSRR3a4j/vvv7+oq6srxo8f3619r3bQQQcV9fX1\nRWNjY7tzPbk/ZeckAAA+fj6quWR9r+9IZ3NDb/1+f11zSU960mqdzQ09fYbdmWPK7r83ntfaSv1F\n4OrPMV25cmWH51cfHzhw4DqvM2jQoLjlllti3LhxsdFGG8Xjjz8eixcvjrPPPjt+8YtfxPLly6Nf\nv34dXmfDDTeMQYMGxWabbRZHH310XHTRRdHa2hpTpkxps8eIiOOOO67d67/1rW9FRMQTTzxR0/qy\n+7H/9bt/AAA+fnprLrnpppuiUqnEpZdeWv3Il4gPvqD+oosuiqIo4vrrr4+IDz728tprr61+xGRX\nyq4v+7647PXX9r///S/OOeecuPnmm2PTTTeNG264IYYPH95mTZn7ExHRv3//GD58eIcfn7nffvtF\nv3794uWXX47W1tZ25++9997qXxP2hp7en7JzEgAAHz8fxVzyYaxfU1dzQ09/v9+duaQnPakrPX2G\n3Zljyu6/J8+rM6W+I3DQoEExcODATj8PddGiRRERbTa3rmudd955cd5557U5vnjx4li2bFl8+tOf\n7taexo4dG5/4xCdi7ty50dLSEkOGDKmeW/tLKCMittpqq+jbt2/1TzDLri+7n66+Q8L+e3f/AADk\n1xtzyXvvvReLFi2KLbbYot2gGRHR0NAQAwcOrL7PnTRpUqxatSqampri3HPPra5b/fEtjY2N1eOX\nX3556fVl3xeXvf6ali1bFqeffno8+eSTsfnmm8fUqVOjvr6+R/enq7mhX79+sckmm0RjY2OsXLmy\nzS8MWltbY+bMmTFgwIA48MAD13md7urJ/elI2TkJAID8Poq5pKmpab2uX/N9bnfmhp78fr8711+t\nt3pSR9et9RmWmWO6u//ensNWKxUCIyJGjBgRzz//fLz11lvtHuyrr74aERE777zzOq/x6quvxptv\nvhkHHHBAu3OPP/54RETsvvvu1WOXXnppLFy4MK644oqoVCpt1vfp0yf69esXzc3N0draGltvvXVs\nvPHGsWzZsli4cGFstdVWbdY3NjZGS0tLbLHFFhERpdeX3U/fvn3tv5f3DwAAPZ1LWlpaIuKDQNWR\nSqVS/W64lpaWWL58eVQqlXj00Uc7XL9ixYq46667olKpxOWXX156fXffF2+55ZYREaWvv9p///vf\n+Pa3vx0vv/xybL/99jF16tT41Kc+1eP709zcHBdddFE0NTXF5MmTO9zPkiVLYuONN24TASM++D6R\nd999N8aOHdvpd3OUVcv9KTsnAQDAhz2XrO/1q9/ndnduqPX3+929fkT5nlRWrc+wu3NMmf3X+ry6\nUuqjQSMivvCFL0RRFPHAAw+0O3ffffdFpVKJ/fbbb53XmDx5cowfPz6effbZduemT58elUolDj30\n0Oqxv/3tb3H33Xd3+OejTz31VDQ1NcWIESNigw02qO4xIuKee+5pt/6hhx6KiIjPfvazbX6mMuvL\n7sf+e3f/AADQ07lk8ODBsdVWW8WCBQuqw92a/vnPf8by5ctj++23j/79+8dvf/vbmDNnTrv/rQ5N\nQ4cOjTlz5sS//vWviIjS61f/TBHrfl88cuTImq/f3Nwcp5xySrzyyiux2267xa233trpsN3d+7Pd\ndttF//79Y+DAgTFz5sz461//Gk8//XS79au/0H706NHtzj333HMREbHnnnt2uJda1HJ/ys49AADw\nYc0lq993r6/1q+eeiHJzw+p7ENH93++XvX7ZnlRWrc+wu3NMmf3X8ry6o3QIPProo6N///5xzTXX\nxNy5c6vHZ86cGXfccUdss802MXbs2Orx1157LV577bVqyYyIGDNmTEREXHXVVdWPZomImDp1ajz6\n6KOx0047xSGHHFI9fuyxx0ZRFPHTn/60+qeYERHz5s2LH/7wh1GpVOLkk0+uHh83blxERPziF7+I\nZ555ps36K6+8Mvr06RPHH398zevL7sf+e77/E044IQAAYLXemEuOP/74KIoiJkyYEEuWLKkef/vt\nt+NHP/pRVCqVD/V96Pp+Xzx58uR4/vnnY9ttt42bbropBg8evM713bk/J554YvX4McccE0VRxAUX\nXNDmo3XmzJkTP//5z6Nv375x6qmntvt3XnjhhahUKrHrrrvW/LP1hrJzDwAAfFhzyZrvu9fH+jXn\njLJzQ9keUPb6ZXtSWWWf4WrdnWPK7n99zKmVoiiKUq+IiN/85jdxySWXxAYbbBCf//znY8WKFfHk\nk09Gv3794sYbb2xTd1d/pusDDzwQQ4cOrR4fN25cPP7447HNNtvE7rvvHvPmzYtXXnkltthii5g2\nbVpst9121bWrVq2K008/PR5++OHYaKONYuTIkbF8+fJ49tlno7m5OY477rj48Y9/3GaPv/zlL+OK\nK66IiA9qc//+/ePpp5+OlStXxmmnnRZnnXVWzevL7sf+e3f/AAAQ0fO5pKWlJb7zne/E3//+9xgw\nYECMGjUqmpubY/bs2bFy5coYO3ZsTJo0aZ17aGxsjH333TeGDRsW999/f5d77mp9T98Xd3b9//73\nv3HggQfG+++/H7vvvntsv/32Hb5+yJAh8YMf/CAiyt+flStXxsknnxyzZ8+OQYMGxciRI6O5uTme\neOKJaG1tjfPPPz+OO+64dv/mSSedFE899VTceeedMWLEiC7v4ZrGjBkT//nPf+Kxxx6LzTbbrMv1\n67r/tcw9AADwYc8l63N9LXNDRPfnmFqvX6YndaSruaHMM1ytzBxTZv+9MaeuraYQGPHBn0ROnTo1\nXnrppdhwww1jjz32iLPOOit22WWXNuvq6+ujT58+cd9997UJgStWrIirr7467r333li0aFFss802\nsd9++8X48eM7/D641tbW+M1vfhO33357vP7667HBBhvErrvuGieccEKHNTYi4rHHHoupU6fGc889\nFy0tLbHzzjvHuHHjemV92f3Yf+/uHwAAIno+l7S2tsatt94at912W7z22msREbHTTjvFscceG8ce\ne2yX/35jY2N8/vOfj2HDhsV9993XK+t78r64s+vPmDEjzjzzzC5fv/bryt6f5ubmuPHGG+Ouu+6K\n+fPnx8CBA2PPPfeMU089NRoaGjr8N7/yla/EvHnz4sEHH2z3nSJdGTNmTCxYsCAeffTRbofAdd3/\nWuYeAAD4sOeS9bW+1rkhontzTK3XL9uT1taduaG7z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ABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQ\nAAAAAAAAEhICAQAAAAAAICEhEAAAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQ\nAAAAAAAAEhICAQAAAAAAICEhEAAAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQ\nAAAAAAAAEhICAQAAAAAAICEhEAAAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQ\nAAAAAAAAEhICAQAAAAAAICEhEAAAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQ\nAAAAAAAAEhICAQAAAAAAICEhEAAAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQ\nAAAAAAAAEhICAQAAAAAAICEhEAAAAAAAABISAgEAAAAAACChztX+4Lhx4+Kqq66Kt956KyIitt9+\n+zjllFNim222adXPl8vluPXWW+POO++MqVOnRqdOnaJv375x5JFHxqGHHtrm17znnnvinHPOafb1\nhw8f3uh16uvr47rrrov7778/pk2bFmuttVYMHDgwTj755Ojdu/dyP9/Q0BA33XRT3HfffTF16tQo\nl8ux2WabxaGHHhrHHntsdOrUcmMdOXJkjBw5Mp555plYc801v/TrrWb+urq6uPLKK+P555+Pzz//\nPHr27BkHHnhgnHTSSdGlS5fl1uf666+Pe+65J957771YbbXVYocddogTTzwxtt9+++XO3db1BADg\nm6mt+5Ki+4Ci991F9z1F52nrGsyYMSMOOOCAWHPNNWPMmDErfH5772MyrD8AAHyZvaS2tnaF5yuV\nSlFXV1f55yL30dWcv5res7QV7TPaep++on1PR88fUayvtHWeZVUVAv/2t7/F0KFDo1u3brHTTjvF\nnDlzYvz48fHUU0/F1VdfHTvttNMKz/GrX/0q7r///ujWrVt85zvficWLF8dzzz0XQ4YMiddffz2G\nDBnSptd87bXXolQqxe677x7du3df7vU33njjyn+vr6+P448/Pl544YXo1q1b7LjjjtHQ0BD//Oc/\nY/To0TFixIjYY489Ks9vaGiIk046KcaPHx+rr7567LDDDhERMWnSpBg2bFg888wzccUVV0SpVGry\n2seOHRujRo1q9vGOvt5q5h89enScfvrp0dDQEDvssEOsscYa8eKLL8bll18edXV1ccUVVzR6vTPP\nPDMeeuih6N69e+y6664xd+7cGDduXDz++OPxpz/9KQ466KB2W08AAL6Z2rovKboPiCh23x1RbN9T\nzTxtXYNzzjkn5s6d2+xmdWntvY/JsP4AAPBl95KDDz642fNMmjQppk+fHltuuWWj40Xuo6s5f9He\ns7QV7TPa4z59Rfuejpw/onhfacs8TSoXNGPGjHL//v3Lu+yyS3natGmV4+PGjStvvfXW5b322qtc\nX1/f4jkmTpxY7tevX3mPPfYof/DBB5XjU6ZMKQ8YMKBcW1tbfuONN9r0msccc0y5tra2/Nlnn63w\nmi666KJyv379yvvtt1+j89fV1ZW/+93vlgcMGFCeNWtW5fgtt9xS7tevX/nwww9vdPyjjz4qH3jg\ngeXa2trybbfd1uRr3XHHHeVtttmm3K9fv3JtbW159uzZyz2no6+36PwzZ84s77jjjuXtttuuPH78\n+MrxWbNmlQ866KBybW1t+eGHH64cv//++8v9+vUr/+hHP2o0z7PPPlveeuutywMGDCjPnTu36nkA\nAKA99iVF9wHlcrH77qL7nqLztHUNbr755sq+ZO+9927xWjpiH/N1X38AAPgqeklz3n333fJ2221X\nHjhwYHnGjBmNHityH130/G2ZvzX7jLbep69o39PR8xftK+31+7C0wp+3ePPNN8eiRYvihBNOaFSJ\nd9999zj00EPjww8/jNGjR7d4jpdeeilKpVIceuihseGGG1aO9+7dOw488MCIiHjhhRfa9Jqvv/56\n9OzZM1ZfffUVXtPf//73KJVK8cc//rHR+Wtra+PUU0+Nzz77LG644YbK8XvvvTdKpVKce+650aNH\nj8rx9dZbL4YMGRLlcjkefPDBRq8xffr0OOWUU+Lcc8+NmpqaWG211Zqdp6Ovt+j8t9xyS8ydOzcG\nDx4cu+yyS+V4jx494rTTTosNNtig8pbniIgHHnggSqVSnHnmmY3mGThwYOyy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449//GO89NJLcdFFF0XEF2+/7N69e8yYMSM++OCD5V7nxRdfjIiIBQsWxMKF\nCytzNaWhoSGuuOKKKJVKMWjQoEaPLV10W9LR19uSpuZ///33o6GhIdZbb70YNWpUXHrppZV/+crl\ncowaNSqGDRu23N8CWOKTTz6JoUOHxhtvvBHTpk2LLbbYIkaMGFH5F7ToPAAA0B77kmr2AUXvu4vs\ne4rOs2DBgqrWYMqUKXHppZfG97///dh///0rf6O0OR21j/m6r39L+0IAAL4Zvope0pTbb789Zs6c\nGYccckhsttlmyz3e1n6wovNXM39r9xnV3qcX2fd05PzV9JW2/j40pdBHg86fPz8iIrp27drk40uO\nL/n4x5Zcf/31MX78+KipqYlddtklBg4cGF27do0JEybEfffd16bXfP311yufoTp27NgYOXJk3Hrr\nrXH33XdHz54946GHHoo777wzIiJKpVIceOCBUS6X4+yzz270CzFlypS45JJLKv9cX1/f4jWdd955\n8dZbb0Xv3r3jsMMOW+EaNKWjr7fo/HPmzImIiMmTJ8dll10WgwcPjscffzyeeuqpOOuss6KhoSGG\nDBkSb7zxRpPnnD59ejz66KMxffr0KJVKsXjx4njzzTdbtRbtsZ4AAOTTHvuSavYB1dx3t3bfU3Se\natagoaEhzj777Fh11VXj97//fbNrU42i83zd1x8AAL6KXrKscrkcN998c3Tq1ClOPPHEJp/Tln7Q\nmvO3Zf4VqeY+vZp9T0fNX21fae95Cr0jsFOnL7phS28Tjfi/t2s25+qrr47rrrsuttlmm7jyyisr\nZfy9996Ln/3sZ/HnP/851ltvvTjggAOqes2LL744pk+fHptuummjd5717t07zj333Bg8eHDccsst\nccQRR0RExOmnnx4TJ06M559/PgYNGhTbbrttLFy4MCZNmlT58saPP/640ffaLev888+PO+64I7p3\n7x4jRoyIlVdeucV5m/NlXG+R+RcuXBgRX/zCHn/88fGLX/yi8jM//elPY86cOXHllVfG1VdfHRdc\ncMFy591iiy1i4sSJsWjRohgzZkwMGzYsfvnLX0bnzp1bfNtse60nAAD5tNe+pOg+oOh9d5F9T9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zb7DBBrH66qtHxBdvr13W7Nmzo6GhIdZee+3KseHDh8cZZ5zR\n5FueO3XqFJ07d46GhoZGf8OgI9cTAIB82rovWfK81u4Dit53V7PvKbovKbIG8+bNi1KpFBMmTIgH\nHnig8p9HHnmkMv8DDzwQ//jHP5p8/dYo+mfydV9/AAD4KnrJEpMnT45PP/00dt9992a/p7DaftDa\n87dl/tYqcp9edN/T0fMX7SsdNU/hELjrrrtGuVyOxx57bLnHHn300SiVSrHbbrs1+/NrrbVWrL/+\n+jFjxozKvwhL+9e//hXz5s2LTTbZJLp06VL4Nbt16xbjxo2LRx55JF588cXlnr/kixSXfHZsRMSI\nESPipJNOismTJy/3/LvuuitKpVLst99+lWP19fVxwgknxFtvvRVbb7113HbbbfGtb32r2WsuqqOv\nt+j8u+66a0REPPTQQ8s99uSTT0ZExLe//e3KsccffzwefPDBJj8u9Pnnn4+5c+dGnz59Kt/719Hr\nCQBAPm3dl0QU2wcUve+uZt9TdF9SZA1uuummqKurW+4/EyZMiIiInj17Rl1dXbz22mstrllLiv6Z\nfN3XHwAAvqxesummm1buW5d4+eWXIyJi2223bfb81fSDIudvy/yt1Zr79H333Tciiu97voz5i/SV\njpqncAg87LDDokuXLnHFFVfElClTKsfHjRsX9913X2y44YYxaNCgyvF33nkn3nnnnUZ18qijjopy\nuRxDhgyJTz75pHL8gw8+iN/+9rdRKpXimGOOqfo1Dz/88CiXy3Heeec1eltuXV1dXHzxxbHSSivF\niSeeWDm+9957R0TEpZdeWnmLaETENddcExMmTIgtttgifvCDH1SOjxgxIl555ZXo1atX3HDDDbHW\nWmsVXcYWdfT1Fp3/uOOOi4iIyy+/PF566aXK8alTp8ZFF10UnTp1iqOOOqpy/IgjjohyuRz/8z//\nU3n785Ln/+Y3v4lSqRTHH3981fMAAEB77EuK7gOK3ncX3fcUnafoGnS0ovN83dcfAAC+rF5y9NFH\nL/far776apRKpdhqq61anLHofXTR81c7f2t19H16R89ftK90xDylclOf37gCN954YwwbNixWXnnl\n2HnnnWP+/PkxceLE6Ny5c1x77bWN3h225OMdH3vssejZs2dEfPH2xp///OfxxBNPRNeuXWPgwIFR\nX18fkyZNigULFsSgQYPikksuqfo1FyxYEMcff3xMmjQpampqYscdd4z6+vp47rnnYvHixXHuuecu\n98WMxx13XDz77LOx4YYbRv/+/WPq1Knx1ltvxbrrrhs333xzbLLJJhHxxUdY7rnnnrFw4cLo379/\nbLrppk2uUY8ePeKcc85pdg333nvv+PDDD+Ppp5+ONddcs01rXOR6q53/r3/9a1xwwQUR8UWd7tKl\nS7z44ouxYMGCOPnkkxu9tXjRokUxePDgGD9+fKy22mqx4447xrx582Ly5MlRX18fRx55ZPzud79r\n1/UEAOCbp637kojW7wMiiu8zqtn3FJmn6Bo0Zfbs2bHTTjvFRhttFGPGjFnhmrfnPibD+gMAwFfR\nSyIijj322Hj++efj/vvvjz59+jQ7XzW9pMj5q51/aSvaZ7T1Pr2lfc+XMX+RvtIe8yyrqhAY8cXb\nWq+55pp44403YtVVV41tttkmTjvttNhyyy0bPa+2tjY6deoUjz76aKMN9+LFi+O2226Lu+++O955\n552IiNhiiy3iiCOOiCOOOKJNrxnxxcdNXnvttfHAAw/EtGnTolu3brHtttvGiSeeGAMGDFju+fPn\nz4/LLrssHn744Zg5c2ZsuOGGsdtuu8VJJ50U6667buV5o0ePjlNPPXWF67PRRhvFo48+2uzje++9\nd8yYMSMmTJjQ5C9GR11vW+Z/+umn45prromXX345Ghoaom/fvnHcccc1+beMFy9eHDfeeGPcc889\n8e6778bKK68cW221VRx99NGNnt9e6wkAwDdTW/clrd0HLFF0n1F031N0niJr0JTZs2fHzjvv3Or7\n7fbex2RYfwAA+Cp6yQEHHBBTp06NsWPHxvrrr9/ifEXvo4uev5r5l7aifUZb79NXtO/p6PkjiveV\ntsyzrKpDIAAAAAAAAPD/V+HvCAQAAAAAAAD+/xMCAQAAAAAAICEhEAAAAAAAABISAgEAAAAAACAh\nIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQA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\nAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICEhEAA\nAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICEhEAA\nAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICEhEAA\nAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEiobXPfOH369Ljxxhtj\n/vz5ERFx6KGHxrnnnhv9+/dv0vtramri1ltvjUceeSQWLVoU3bp1i4EDB8YPf/jD6NWrV73za2tr\n484774yHH344Fi5cGOVyOfbbb78YNmxYnHHGGdGmTd2mWS6X4+677477778/Fi5cGG3atIn9998/\nTj311Bg2bFi99R988MG45JJLGr3ecePGVd5XXV29xfsrlUoxb968Rl+fMGFCTJgwIf7xj39E165d\nt7je0qVL44QTToiuXbvG1KlT673e2p8PAACt09bMJc3Zt27LfXRE8X19bW1t3HbbbfHggw/Gu+++\nG506dYrDDjssRo4cGYceeugW729Lc0bR+y065zVnLixyv0WfZ9HrAQCAiK3vJdt6zih6jc3ZF1t/\n+66/OaVyuVwu+qY///nPMWbMmKiqqoojjjgiPvnkk5g9e3aUSqW46aab4ogjjtjs+2tqamLEiBEx\ne/bsqKqqikMOOSRqa2tjzpw50aZNmxg/fnx89atfrZxfW1sbZ599djzzzDOx0047xRe/+MWIiJgz\nZ06sWrUqjjnmmLjuuuuiVCpV3nPRRRfFI488ElVVVTFgwIDYsGFDPP/881FTUxNnnnlmXHzxxXWu\n6fLLL4+JEyfG4MGDo0uXLvWu+Xvf+14cfvjhERHxs5/9rNF7mzNnTixevDgOOOCAeOCBBxo8Z9q0\nafHjH/84amtr47nnnmtS6BoxYkQ899xzsddee9Ub0D0fAABao62dS5qzb92W++jm7OsvuOCCeOyx\nx6JLly5x2GGHxapVq2L27NlRLpfjd7/7XXzrW9/a7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yZNavDjuv+r\nXC7HxRdfHB06dIgxY8Y0el5rfT4AALReWzuXNGZz+9ZtvY8uuq+/9tpr46GHHqrMUJtavXp1RES0\nbVv/Z+GLzBlNvd+ic15z5sKi91vkeTbnegAAoCXmkm09ZxS5xubsi62/fddvivpT4RYsWLAg2rdv\nXxmcNvWFL3yhck5jNv5t044dOzb4+g477BAREQsXLqwcu+GGGxpd7+WXX46IiM997nOVY9/85jdj\nwoQJ8fDDD0d1dXWcdNJJEfFpSX388cejZ8+eceyxx1bOf/311yPi0//DjRkzJp599tn44IMPomfP\nnvHd7343Tj/99Dq/w/G/Vq9eHePHj4+2bdvW+67ejQ444ID49re/HV/72tcaXed/3XLLLfHSSy/F\nFVdcEbvuumuj57XW5wMAQOu1tXNJQ7a0b93W++ii+/p27drF/vvvX+/cSZMmxezZs6Nnz54NDo9N\nnTOK3G/ROa85c2HR+y3yPJtzPQAA0BJzybaeM4pcY3P2xdbfvus3RaEQ+OGHH0ZNTU306NGjwdd3\n2223iIhYvnx5o2vssssu0aVLl1i6dGksWbKk3lovvvhiRESsXbs21q1bFzvuuGOja9XW1lZ+3H3o\n0KGV4507d678+OLYsWNj7NixldeOPfbY+M1vflNn3Xnz5kVExH333Re77rprHHroobHHHnvEq6++\nGpdffnm89NJLceWVVzZ6Hffee28sW7YsTjrppNhvv/0aPOfcc89t9P0NWbBgQVxzzTXx9a9/PY4/\n/vhK+S8i8/MBAKD1aom5pCFb2rd+1vvojRrb129qxYoVMWbMmHjjjTdi0aJF0adPnxg/fnxlUNyo\nyJxR5H6LznlbOxc29X4b0tDzbMk5FQCA1qGl5pJtOWcUvcai++K1a9dafzuu39S5pNBXg65ZsyYi\nIjp06NDg6xuPb/xaloaUSqU48cQTo1wux6hRo+oMngsWLIirr7668u81NTWbvZ5LL7005s+fH716\n9YqTTz65zmu33XZbPPPMM9G5c+cYNGhQDBw4MDp06BAzZsyIhx9+uM65r7/+euU7eKdNmxYTJkyI\nu+++Ox544IHo0aNHPPbYY3H//fc3eA3lcjkmTpwYbdq0iZEjR272epuqtrY2Ro0aFR07doxf//rX\nzV4n6/MBAKB1a4m55H81dd/6We2jN7W5ff1GixcvjilTpsTixYujVCrFhg0b4s0336xzTnPmjKbe\nb9E5b2vnwqbcb2Maep4tOacCANA6tORcsq3mjKLXWHRfbP3tu35TFfpEYJs2bSoXszmN/dj8Rhdc\ncEHMmjUrXnjhhRg6dGgcfPDBsW7dupgzZ04MGjQoIj79rYaGfs9io8suuyzuu+++6NKlS4wfPz7a\ntWtXee2mm26KW2+9Nfr37x/XX399paq+++678YMf/CB+//vfxx577BEnnHBCRERcddVVsXjx4th3\n333r/A3SXr16xejRo+Occ86Ju+66K4YPH17vOqZNmxZLliyJo48+Onr37r3Z+26qG264IV577bW4\n4oor6vyofRGZnw8AAK1bS80lm2rKvvWz3EdvtLl9/ab69OkTs2bNivXr18fUqVNj7Nix8ZOf/CTa\ntm1b+fr9onNG0fstOudtzVzYlPst+jxbYk4FAKD1aKm5ZFvOGc25xiL7Yutv3/WbqtAnAjd+L+na\ntWsbfH3j8aqqqs2u07lz57j77rvjzDPPjE6dOsXMmTNj+fLlccEFF8Sf/vSnWL16dbRt27bBdf77\n3//GhRdeGHfddVd06dIlbrrppujVq1edc26//fYolUoxbty4yv9pIj79QfjLLrssyuVy3HjjjZXj\n7du3j169ejX4NTJHHXVUtG3bNt58883YsGFDvdcff/zxSn1vCfPmzYvrr7++8lU9RWV/PgAA0FJz\nyaaasm/9LPfRTdnXb6pjx47RuXPn6Nq1a5x88slx2WWXxYYNG2LChAkR0bw5o+j9Fp3ztmYu3NL9\nNud5bs31AADQ+rTUXLIt54zmXGORfbH1t+/6TVXorzJ27tw5qqqqGv1O22XLlkVE1Pkf6+bWGjVq\nVIwaNarO8eXLl8cnn3wSe++9d733fPLJJ3HOOefErFmzYrfddoubb745qqur65zz0UcfxbJly2L3\n3XdvcFAeMGBAVFVVxYIFC6K2tnaLvyHRtm3b2HnnnWPlypWxdu3aOj/SuGHDhpg+fXp06NAhjj76\n6C3ec1NcffXVsX79+li1alVcdNFFleMbP+a5cuXKyvE//OEPdd7bGp4PAAC05FwS0bR962e5j27K\nvn5Lhg4dGjvuuGPleorOGc2936JzXnPmwqbc76bPv8jzbKnrAQAgv5aYS7b1nNHca2zqvtj623f9\npir0icCIiN69e8e6devi3//+d73X3nrrrYiI2H///Te7xltvvRXTp09v8LWZM2dGRES/fv3qHP/P\nf/4Tp512WsyaNSv23XffuPfeexsc3mprayMiGv1YZKlUqvyGRG1tbaxZsyZ+/vOfx/nnn9/g+WvW\nrIkVK1ZE586d6wznERFz586NDz/8MAYPHtzod7wWtXr16iiVSjFjxoyYPHly5Z8nnniicj2TJ0+O\nv/71r3Xe11qeDwAARLTMXLJRU/atn9U+uqn7+oiIcePGxYUXXtjgVw21adMm2rZtG7W1tbFhw4bC\nc0bR+40oPucVPb/I/W5U5Hk2Z04FAKB129q55LOYM4peY9F9sfW37/pNUTgEfuUrX4lyuRxPPfVU\nvdemTJkSpVIpjjrqqM2uMX78+Dj77LNj7ty59V6bNGlSlEqlOO644yrHampq4qyzzor58+fHQQcd\nFPfcc098/vOfb3Dtbt26xZ577hlLly6tPMRN/fOf/4zVq1fHPvvsE+3bt4+qqqqYPn16PPHEE/Hi\niy/WO3/jD3Fu/O7VTb388ssREXHwwQdv9n6LuPPOO2PevHn1/pkxY0ZERPTo0SPmzZsXr732WuU9\nren5AABARMvMJRs1Zd/6Weyji+zrIyL+9re/xaOPPhrPP/98vddeeOGFWLVqVfTu3TvatWtXeM4o\ner8Rxee8oucXud/mPM+i1wMAAFs7l3wWc0bRayy6L7b+9l2/KQqHwJNPPjnat28f1113XSxYsKBy\nfPr06fHwww9H9+7dY+jQoZXjb7/9drz99tuVsh0RMWTIkIiIuOaaaypfRRMRcfPNN8eMGTOiT58+\n8Y1vfKNyfPz48fHKK69Ez5494/bbb49u3bpt9hpPO+20KJfLcfHFF8eKFSsqx5csWRK//OUvo1Qq\nxemnn145fsopp0S5XI5LL720zkc0582bF1dddVXssMMOMXLkyHp/zquvvhqlUikOPPDAzV7Ptub5\nAADQ2rTEXLJRU/et23ofXXRfP3z48CiXy/Hb3/628pUyERELFy6MX/ziF1EqlWLEiBGbXaMl77fo\nnFf0/KL3W/R5Fr0eAABoiblkW88ZRa+x6L7Y+tt3/aYolRv6XpUtuOOOO2Ls2LHRrl27OPLII2PN\nmjUxa9asaNu2bdxyyy3xpS99qXLuxq9deeqpp6JHjx6V42eeeWbMnDkzunfvHv369YuFCxfG/Pnz\nY/fdd4+JEyfGPvvsExGffpXL0UcfHevWrYt+/frFvvvu2+A17bLLLnHJJZdExKcfp/3Rj34UTz/9\ndHTo0CEGDhwYNTU1MWfOnFi7dm0MHTo0rr766sp7165dGyNGjIg5c+ZE586d4/DDD4+ampp4/vnn\nY8OGDTF69Og49dRT6/2ZZ5xxRrzwwgvxyCOPRO/evQs9wyFDhsR7770Xzz33XHTt2nWL569cuTKO\nOOKI2GuvvWLq1KmV454PAACtVUvMJRFN37duy310c/b169evj3POOSeeeeaZ6NSpUxx++OGxevXq\nmDt3btTU1MSpp54av/rVrzb7DBubM5pzvxFNn/Oac36R+23O82zO9QMAwNbOJZ/Ff68vco0RxffF\n1t++629Js0JgxKcfWbz55pvjjTfeiI4dO0b//v3j/PPPjwMOOKDOedXV1dGmTZuYMmVKnYF7zZo1\nce2118bjjz8ey5Yti+7du8dRRx0VZ599duy+++6V85588sk477zztng9e+21V0yZMqXy7xs2bIh7\n7rknHnjggXj77bcjIqJPnz4xfPjwGD58eL3319TUxC233BKTJ0+ORYsWRVVVVRx88MExcuTIGDBg\nQIN/5gknnBALFy6MadOmxZ577rnFa9zUkCFDYunSpTFjxowmh8Ajjzyy3n16PgAAtGZbO5dEFNu3\nbqt99Nbs6++444548MEH45133ol27drFgQceGN///vfr/K3SxjQ2ZzT3fps65zX3/Kbeb3OfZ9Hr\nAQCAiK2fSz6L/17f1GuMaN6+2Prbd/3NaXYIBAAAAAAAAP7/KvwbgQAAAAAAAMD/f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EhICAQAAAAAAICEhEAAAAAAAABISAgE\nAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICEhEAAAAAAAABISAgE\nAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICEhEAAAAAAAABISAgE\nAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICEhEAAAAAAAABISAgE\nAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICEhEAAAAAAAABISAgE\nAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICEhEAAAAAAAABISAgE\nAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICEhEAAAAAAAABISAgE\nAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICEhLDNACMAACAASURB\nVEAAAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICE\nhEAAAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICE\nhEAAAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICE\nhEAAAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICE\nhEAAAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICE\nhEAAAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICE\nhEAAAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICE\nhEAAAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICE\nhEAAAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICE\nhEAAAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICE\nhEAAAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICE\nhEAAAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICE\nhEAAAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICE\nhEAAAAAAAABISAgEAAAAAACAhNpv6xOfeeaZmDBhQvzpT3+KiIi+ffvGxRdfHIcddthWPb8oirj3\n3nvj/vvvj8WLF0e7du3i4IMPjnPPPTdOO+20ZuM3bNgQd9xxRzz66KOxdOnS6NGjRwwYMCC+8Y1v\nRO/evZuMra6ubvP1S6VSzJ8/v9XHX3vttTjppJOie/fu8eSTTzZ7vL6+Pu688854+OGHY8mSJdGp\nU6fo169fDB06NPr27dts/MMPPxxXXnllq693/fXXN/m532/zExExf/78GDduXDz//POxZs2a6NWr\nV5x88slx4YUXRocOHdp8zwAAvP9s776kknV0xMZ17k9+8pN45JFHYvHixVEURey///5x2mmnxRe/\n+MVo167p31pWug/YXFvr7kr3DRFbP2fbum+oZF3/bs//tuxLNlVTUxM1NTXx7LPPRvfu3dscDwAA\nm3qv9yubq3Q9e+utt8b48ePj+eefj86dOzd7vL6+Pu6+++545JFH4q9//WsURREHHHBAnH766fH5\nz3++2Xp8c8uXL4/BgwfHHnvsEY8//vgOOf9LL70U48ePjxdeeCHWrl0bvXr1isGDB8fQoUNb7ApP\nP/10+TNp165d9O3bNy655JLo06dPs7F1dXVxxx13xNSpU2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nK52fVatWFf379y+OOOKIYubMmeXjr7/+enHKKacU1dXVxfTp09t8/wAAvH/siH1JpevoyZMnF1VV\nVcVZZ53V5Pjf//734uSTTy6qq6uL++67r8lrVLIP2Fxb6+5K9w07Ys6KovV9Q6Xr+nd7/rdl39Zo\nypQpxWGHHVae/3/+859tzgsAADT6b+xXNlXpevanP/1p8dGPfrQ8fs2aNc3G3H333UVVVVVx9tln\nF2+88UaTn/XEE08sqquriylTprT6GnfeeWf5/J/5zGe2+/z/+Mc/in79+hVHHHFEMXv27PLxVatW\nlfcHM2bMKB9fsWJF0adPn+ITn/hEsXz58vLx2traok+fPsWnPvWp4p133ikff/jhh4uqqqpiyJAh\nTeZj9uzZRZ8+fYoBAwYUb731VpOf4ZxzzikOOeSQVvcZm6t0/Laq+B6B99xzT9TV1cXXvva1JjXy\nqKOOitNOOy1effXVmDFjxhbPMXfu3CiVSnHaaafFhz70ofLx3r17x8knnxwRES+88EL5+IMPPhil\nUimuu+66Jq9ZXV0dl156aaxevTruuuuuLb7mlClTYtq0adHQ0BAjRoyIPffcs8VxS5cujZtuuil2\n3nnniIjo0qVLfPWrX42nnnoqLrjggqirq4tf/OIXUSqV4vLLL48uXbqUnztgwIAYNGhQrFmzJl58\n8cUm512wYEH06tWryfj/pfkpiiK++93vxttvv71V83PkkUdGURQtjql0fiZPnhxvvvlmXHTRRTFo\n0KDy8d122y2+9a1vxV577VX+6jQAAETsmH1JpevoqVOnRqlUiquuuip222238vGePXvG8OHDoyiK\n+OUvf9nkNSrZB2xqa9bdle4bdsScbWnfUOm6/t2e/23Zty1btiwuvvjiuOqqq6Jz587RqVOnLc4H\nAAC05L+xX4mofD27bNmy+OY3vxkjRoyIrl27RseOHVsd+/Of/7y8Hu/Ro0f5+J577hnDhg2Loihi\n2rRpLT538eLFccstt2xxf1Pp+e+5555Yt25dXHLJJU2+Xbn77rvHpZdeGnvttVcsWrSofPzuu+8u\nX2Vk7733Lh8/5phj4pRTTokVK1Y0uR3DY489FqVSKb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+7G2PpOGhoYWj1dXV8ecOXPinXfeiSeeeCKu\nv/76+Pa3vx01NTXl+0COHj06li1bFvvvv3+TbwoedNBB8f3vfz8uvvjimDx5cpxxxhnbNH57VPQv\npPF6tG+//XaLjzceb+3ym43uuuuuKJVKcf3115c3qxEbb/B+7bXXxpe+9KWYMGFCOXR17tw57r33\n3rjtttti+vTp8dxzz8U+++wTl112WXz5y1+OAQMGRPv27Vt83enTp5f/CvdHP/pRs8fnz58f48aN\nK196Z+7cuRGx5X8Qmz626TV6zzzzzNh1113jsssui5qamvKGskOHDrF69er4/e9/32xj2qNHj9hp\np51i4cKF8fvf/z7atWsXkyZNilKpFF/96lfj1VdfjVdffbU8/vzzz49rrrkmRo8e3eR+hz/4wQ/i\n/vvvj9mzZ8ezzz4bPXv2jHPOOSdOOumk+MpXvhI77bRTi9ccvu+++6JUKkW/fv3K19nd1OLFi2Ps\n2LExYMCA2Geffcpj1qxZExEb/9qgpee15OCDD46hQ4fGLbfcEjfeeGPsueee8be//a38eEvvofEa\nu7Nmzdrq1wEAILfGv+ZcvXp1i2vExr/ibN++fZtryG1dR9fV1UVNTU3MmjUrOnXqFMOHD49169a1\n+Hovv/xys2Ob7wOWLFlS8bq7kn3DpnM2d+7cZvfGa2svt+m+qiWb7ovOPffcZo+fc845MW7cuPjt\nb39bPrY9+7x33nknhg8fHo899lh069YtJk6cGL17927xvW3+/lrbtwEAwI6wozrK9qyX320bNmyI\nYcOGxfTp06Nbt24xadKk2G+//cqPv/TSSzFhwoQ44YQT4jOf+cwOP/+mP3NL+4+zzz47JkyYUN5/\nNI5vDIiba+sz6dSpU/l/DxkyJDp27BiXX355kxDYoUOHVvckRx11VLRr167JlQ8rHb89KgqBnTv/\nP/buPUir+rD/+OeBZRHCRVEhykWZqlUECaJS1IyWRm10nMoE2iQqglWj0WrbhCFW00mb/JpoWm9p\nMkoWvOClHW2RqKQxRmJNcRQQQYWIF2IxaQQE5LLLdff3h7Nb112UBZa137xeM/7Bc855+D5njzPn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kSNHtni/F154IZs2bcpZZ52V0aNHt/p3denSJZVKJS+9\n9FKr27ds2ZK5c+emUqlk2rRpSZLvfOc7Oz0/yXsXcW1tbT71qU+lS5cu6dmzZzZu3JhBgwalX79+\nzfZdu3Zt6uvr07dv352eD3bNokWLkvzvKkvY11yDfBy4DulorsG956ijjspLL72UT37yky3mJU8+\n+WSS5FOf+tSH3kPuzn30unXrMmHChCxbtiyHH354ampqMmDAgBbH19XV5Zvf/GY2bdqUW2+9tdXt\nGzZsSK9evXLKKafk9ttvb9N99+7MG4466qi8+OKLWbduXavnIml9Lrcr86pPfvKTTff1q1atavW+\nfseOHc0m1rszz9vV8598+Lzkg/M2IRAAgL1pTztK436700Xa05o1azJhwoS89tprGTx4cKZNm5ZD\nDz20xX51dXWpVCr5xS9+0WJbpVJJbW1tHn300RYhcFfff8CAAenevXvq6uqyevXqFlF1zZo1aWho\naAqGlUolv/d7v5elS5fm7bffbjFfeeONN5K891jO5L1fhrzhhhvyzjvvtPqVZZ07d05VVVW2bNmS\nhoaG1NbW5lvf+lbq6uqa/WJno40bN+bdd99N7969U11dnU2bNrVp/z3V6aN3ae7UU09NQ0ND0+T6\n/Z544olUKpV8+tOf3unxBxxwQPr165ff/va3TRf8+y1atCi1tbU57LDDmj7grbfemi996UtZvHhx\ni/0feuihpkj3QY2Pzvmwf2iZMWNGli5d2uy/gQMHNoWxQw89NEuXLs2SJUuyZMmSDB06ND//+c8z\ne/bsZo+1aTR//vxs2rQpRxxxRLp06ZJu3brlqaeeyrPPPtvqdxT+6Ec/SpKmZ/r+Xzg/S5cubQqn\n7z8/jdpyfpL3rqkk+fGPf9xi/6effjpJcsIJJ+x0jAAA/O7Z03lJ0vb76K1bt+aSSy7Jq6++mmOP\nPTYPPPDATiNU4zzg8ccfz/PPP99ie+M84OSTT07S9vvu3Zk3NN53z5s3r8X+H3bOdmXe8P7339X7\n+vY8/0nb5yUAALC3dMR8pb013o+//vrrOe644/Iv//IvrUa65L0nDbY2v3n66afT0NC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/87Of/Wzj/16yZEmef/75vPXWW0mSmpqaLF26NLvuumuT8//Hf/xH7r777tTW1mafffbJ\nkiVL8tRTT2XKlCn5z//8z3z605/O6NGjs9lmm7U6pvPOOy+LFy9u9V9yXV1dvv71r2f69OltHm/z\nelauXJnHH388Y8aMyfTp0zNmzJjGfevr63PaaaflkUceSffu3bPXXnslSaZMmZKxY8fmD3/4Q666\n6qqUSqWqr/8555yTX//61+nZs2c++tGPZvHixXnwwQfzu9/9LpdcckkOP/zwJvtPnTo1pVIpH//4\nx9OzZ88W12Tbbbetun4AAEja35ckla27m5s0aVKuueaaNa5TK11HN7emPiOpbN2dJH/+858r2v++\n++7L2Wefnfr6+uy1117p0aNHnn766Vx55ZWZNm1arrrqqqrrWbVva27KlCmZPXt2i76tubX1YZX0\nPfoSAACq8X70JZX2AZWev9IxVdo3NLeu+55VtaVva0/9azv/+shv1qpcoTlz5pR333338n777Vd+\n9dVXGz9/8MEHy7vttlv5wAMPLNfV1a3xHJdddll5l112KX/6059uco5p06aV/+mf/qk8ZMiQ8ttv\nv93u75w/f375wAMPLH/sYx8rjx8/vjx27NjyzjvvXN51113Lr732WuN+TzzxRHmXXXYp77///uW/\n/OUvjccNGzas/JGPfKS8yy67lAcNGlQeMWJE+d13323xPbfeemt5l112Kffv37980EEHrXa8Bx54\nYJvG27yeBi+++GJ5yJAh5f79+5dnzJjR+Pltt91W3mWXXcojR45scp433nij/JnPfKbcv3//8k9+\n8pOqr//dd99d3mWXXcqf//znywsWLGj8/LHHHivvtttu5SFDhpQXL17cZMzHHntsuX///k32X51K\n66c6U6ZMKU+ZMuX9LoN/YOYgfw/MQ95v5uC6sy76kkrX3av62c9+Vh44cGBjHzB//vwW+1Szjl7V\n2vqMcrmydXe5XC4fccQRbd7/rbfeKg8ePLi85557lh955JHGz99+++3y4YcfXu7fv3/53nvvbVc9\nrfnzn/9c3nPPPctDhw4tz5kzZ7X7tbUPa2vfoy8BAKBS71dfUsm6u9LzVzqmavqGVXVE39OgLX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Gx9y0plQq5TOf+UzK5XJGjx7d5F/wiy++mMsvv7zxz3V1dVV/5+LFi5MkG2ywQW699dZ0\n6tQpp5xySuNnq44nSW688cY88sgjqa2tTfJesr3hhhtm8uTJueuuu5oct2jRoowePTobbbRRLrro\notWOtfl4r7766rWOt3k93bp1y3777ZehQ4e2qGdtLr744rzwwgvZcccdc+SRR7aopy3Xv7nZs2fn\n/vvvz+zZs1MqlbJy5crMnDmzyT7Tp09vfObwpEmTMm7cuEyYMCG/+MUv0rt37/z617/O7bffXlX9\nAACwLvqSButi3d0WbVlH19fXt7nPSCpfdzf8Ju3++++/1v0XLVqUJHnuuefywx/+MGeccUZ+97vf\n5dFHH825556b+vr6jBkzJjNmzKi6nlWVy+UWfVtzlVyf9vY9q9KXAADQmverL6lm3d3W81c6pmr6\nho7ueypRTf3rSkfkN6tT0R2BnTp1aixmTdb0UsckOfvss/PEE0/kySefzCGHHJI99tgjy5cvz5Qp\nUxpfxjh37tx06dKl6u9s+POMGTPyl7/8JQcccEB22mmnJvs0nPO6667LDTfckIEDB+Zf//Vfc8YZ\nZ+Tkk0/O3nvvnVNPPTXf+c530qtXr8bjbrnllkydOjXf+973mrzccU3jfeihhzJ9+vQMHz48O+20\nU95999288MIL+chHPpJ333038+fPzx//+MdssMEGufvuu/PTn/40H/7wh3POOec0Pl92zpw5+c53\nvpNLLrkkixYtyr777rva77zxxhtz3333ZeONN86pp56a5557rnHbAQcckIceeihPPPFEm+pZ1bJl\ny3Lttddm5cqVefLJJ3Prrbfm7LPPziuvvJK99947SXL88cfnkEMOydZbb914a2uDo48+Ot/73vdy\n3XXXNd5GXGn9tE/zF8vC+mYO8vfAPOT9Zg62T0MztGzZslav5cqVK5Mk77777hqv9bpYd9fV1aVc\nLufZZ59Nt27dVrtfW9bRv/jFL/KnP/0pX/nKVzJr1qzMmjUrCxcuTJIsX768xVgqXXc37N+7d+/U\n1NQ07rvjjjvmggsuyBlnnJHbbrstRx11VJYvX57kvcZ41KhR+cpXvtK4/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N37+3e9+t3H7vvvu2+pvEr/99ttZunRptt122wwcODALFizIO++8ky233DKf/vSnW+y/\n++6755JLLslrr72WAQMGNEnAFy1alDPOOCNPPPFEtthii4wfPz79+/dv9bolydChQ9daz9rstttu\nueqqq/L666+3qGd1evbsmfnz56dfv35N/kOrtH4AAP5x1dbWZuHCha2uWV955ZUkydZbb73aNW17\n1t2ravjNzQEDBmSTTTZpc/3N19Hjxo1LfX19unTpkptvvrlxv4Y+Y/HixY2fr9pnrMnq1t2t6dKl\nS3r06JH58+dn2bJlTX4zd5tttmmx/1ZbbZXOnTuv8V0eazr/qvWsXLkyDz74YIu+bVWXX355VX1Y\nW/vOVelLAABoi3WRlzTPJ5pbNZ+or69f69+/N193r1ixoqLzVzqmSvuGatf1bR3v2vqe5tZ137Mm\nlfQZ1fQxa1JREJgkO+20U55//vm8/vrrLS7MSy+9lCTZeeed13iOl156Ka+99lr233//Ftsee+yx\nJO813u35zu7du6dXr155880386lPfarJM22nTp3aeP6GOw4bbqPs3r17+vTpk6lTpyb5v9/wXbly\nZaZOnZqNN944CxcuzOTJk1sd29KlS/OrX/0qpVKpcaJWMt7m9TS3aj2r/of/t7/9Lccff3xmzpyZ\nHXbYIePHj0+fPn1aPUel1//b3/525s6dm0svvbTFbw936tQpXbp0SV1dXVauXJm6urp84xvfyOLF\ni3PFFVe0en3mzZuX7t27N/mPspL6AQCgvX1JtevuSlSyjl6yZElKpVKb+4ylS5dWtO6udP+NNtoo\n3bt3z6JFizJ37txstdVWTfafP39+6uvrG++krPT8q3ruuefyzjvv5JBDDlntu0gqvT5J5X1Poi8B\nAKAy67svqfTv3xsCrEr6nkrG9KEPfahNfUPDq9c6uu+pVFvrX/UJMtXoyPymLSq7TzLJRz/60ZTL\n5fz2t79tse3+++9PqVTKxz72sTWe44orrshpp53W6nvf7rjjjpRKpSa/lVvtdza8C2PVdHTy5MmZ\nNWtW4220m266abbaaqvMmTOncRIffPDBjfs9++yzWbJkSbbaaqv8+c9/zpgxYzJt2rQW/zRM3N69\ne2fatGmNQWKl422tnlU11LPDDjs0Phqorq4uJ598cl544YXstttu+clPfrLGZrXS6/+73/0u99xz\nT6u3vz755JNZvHhxdtppp3Tt2jW1tbV58MEH85vf/CZPP/10i/0bXjza8CzbauoHAID29iXVrLsr\nVck6+pZbbqmoz6h03V3NOv2jH/1okvceodrcww8/nCSN7zes5vwNGt5vuMcee7TY1qDS65NU3vfo\nSwAAqNT66ku233771NTUVLzurvT81YypLX3D4MGDk1S+rm9Pn9FWlfQ91ejo/KYtKg4CjzzyyNTU\n1OSqq67Kiy++2Pj5gw8+mLvuuitbb711DjnkkMbPX3755bz88suNyXaSHHTQQUmSH/zgB423fCbJ\n+PHjM3ny5PTr1y8HH3xw1d/ZoOG2zjvuuCM33nhjrrnmmpx11lkZOHBgDj/88CTJ7NmzM2jQoJTL\n5YwZMybz5s3LySefnJ49e+bYY4/Nl7/85STvJb+rHleJSsd7zDHHNKmnwV/+8pecf/75KZVK+ed/\n/ufGz6+44oo8//zz2W677XLTTTdl0003Xaf1HHXUUSmXy/mv//qvxlt/k2TWrFn5f//v/6VUKmXU\nqFGNn48cOTLlcjkXX3xxk1uIp02blu9///vp3LlzTjnllKrrBwCAddGXVLrurlSl6+hKVbrurnT/\nE088MUly5ZVX5plnnmlS/2WXXZZOnTrlmGOOqfr8Df70pz+lVCplwIABVV+L1lTa9+hLAACo1Prq\nS4499tjGzytdd1d6/krH1Ja+oT19VbV9Rlt1dP0dnd+0RdTFyRYAAA31SURBVKlcLpcrLfzmm2/O\n2LFj07Vr1+y7775ZunRpnnjiiXTp0iU//vGPm6SjDc84/e1vf5vevXs3fn7iiSfmsccey9Zbb53d\nd989s2bNygsvvJAtt9wyt956a7bffvuqv7PBcccdlyeffDKDBw/O1KlTU1tbm/333z/nnntu48We\nOHFizjvvvOyyyy6N7xMcOnRo3nnnnTz33HOpr69PTU1NDj/88CbHNTd//vwMGzYs22yzTR544IEW\n2ysZb319ff71X/81Dz30UGM9dXV1mTJlSpYtW5ZDDjkkl19+eZL3bik94IADsnz58uy+++7ZYYcd\nWq1vs802y3nnnVdVPStWrMgZZ5yRRx55JBtvvHEGDx6cJUuW5LnnnktdXV2OPvro/Od//mfj/suW\nLcuoUaMyZcqUdOvWLYMHD05dXV0ef/zxrFy5MhdccEHjizerrR8AANrbl1Sy7l6dgw46KH/961/z\n+9//vsU7AitdR7dmTX1GJevuavZPkuuvvz6XXnppkvd+C7ampiZPP/10li1bltNPPz1nnXVWu86f\n/F/fdvfdd2ennXZa4/Wo5Pokbe979CUAAFRrffclla67q+l7Ks1jKukbWrMu+57WrKlvWxf1r+78\n6yO/aYuqgsDkvVtAx48fnxkzZmSjjTbKwIEDc9ZZZ2XXXXdtsl///v3TqVOn3H///U2CwKVLl+aH\nP/xh7r333rz11lvZeuut87GPfSynnXbaap+32tbvbHDYYYdl1qxZmTRpUotnuza3cuXK/OQnP8kv\nfvGLvPzyy0mSfv365aijjspRRx211usxf/787Lvvvtlmm21y//33t9he6XjbWs99992Xf/u3f1tr\nfc3rqqaem2++ORMnTsyf//zndO3aNQMGDMg///M/t3o3Zl1dXX784x/nV7/6VV599dXU1tZmjz32\nyCmnnJIhQ4a0u34AAEja35e0tw846KCDMmfOnEyePLnVhrLSdXRza+sz2rrurnb/JPn973+f8ePH\n549//GPq6+uz884758QTT2xXH7CqSvq2Sq9PW/sefQkAAO2xvvuSStfd1fQ9leYxlfQNza3rvqe5\ntfVt7a1/dedfX/nN2lQdBAIAAAAAAAB/vyp+RyAAAAAAAADw908QCAAAAAAAAAUkCAQAAAAAAIAC\nEgQCAAAAAABAAQkCAQAAAAAAoIAEgevAa6+9ljPPPDP77LNP9tlnn4wePTrz5s3rsOOguWrn0sMP\nP5xjjjkme+65ZwYNGpRRo0bl2WefXQ8VU0Tr4mfa9OnTs/vuu2fcuHEdVCVFVu0cnDdvXs4///zs\nt99+GTx4cI499tg888wz66FiiqbaOTh9+vT8y7/8SwYNGpTBgwfn9NNPz6xZs9ZDxRTZBRdckOOP\nP75N++pLAAAAiqtULpfL73cRH2R/+9vf8vnPfz4rVqzICSeckBUrVmT8+PHp06dPbr/99nTp0mWd\nHgfNVTuXHn/88Zxwwgnp169fjjzyyNTX12fChAl54403MmHChAwcOHA9j4QPsnXxM62+vj4jR47M\n9OnT8+Uvfzlnnnnmeqicoqh2Di5evDgjR47MW2+9lRNPPDE9evTIrbfemjlz5uSOO+5Iv3791vNI\n+KCqdg7Onj07I0aMSG1tbUaNGpVyuZwf//jHSZI777wzW2655focBgVx++2354ILLsjQoUNz8803\nr3FffQkAAECx6era6YYbbsibb76Zu+++O3379k2SfOQjH8moUaMyceLEHHXUUev0OGiu2rn0rW99\nK1tvvXXuuOOO1NTUJEmOOOKIHHroobn88stz/fXXr7cx8MG3Ln6mXXPNNXnxxRc7ulQKqto5eO21\n1+aVV17JLbfcksGDBydJPv3pT+cTn/hExo8fn0suuWS9jYEPtmrn4E033ZQlS5bktttuS//+/ZMk\n++yzT4466qjceOONOffcc9fbGPjgW7lyZa666qpceeWVKZVKbTpGXwIAAFBsHg3aTvfcc0+GDh3a\n2DQnybBhw9K3b9/cc8896/w4aK6aubRgwYLMnDkzhx56aGMImCSbb755hgwZkqeffrrD66ZY2vsz\nbcaMGbnmmmvy5S9/OW5UpxrVzsFf/vKXOeCAAxpDwCTZYostMnr06Oy9994dWjPFUu0cnDVrVjbd\ndNPGEDBJBg4cmE022SQzZ87s0Joplrq6uowYMSJXXnllRowYkV69erXpOH0JAABAsQkC22HBggWZ\nPXt2dttttxbbBgwYkD/96U/r9Dhortq51K1bt9x777054YQTWmybP3++R0BRkfb+TKuvr895552X\nj370ozn88MM7qkwKrNo5+Nprr+WNN97Ivvvu2/jZkiVLkiRHH320u2Bos/b8HNxqq63yzjvvZP78\n+Y2f/e1vf8vChQvbHORAkixfvjxLlizJ5ZdfnrFjx6Zz585rPUZfAgAAUHyCwHZ44403krz3FzjN\n9erVKwsXLsyiRYvW2XHQXLVzqVOnTtluu+1avHdo+vTpefrpp7PX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iIjbaV2tHZv8aBPXaxfX0/qo8pGIeAL4XWb+fvIjTkyvXfwJ+A3wrvY/qxOfbvJeAD69zuNX0fpU46uZeZbWx9E/3u/Fxhn5de+U3eBcvztl38k23ENmvpWZf4iIbRHxTeCXmVn5duANdxERC7T+k/y+aQw2Bb3+fFwOfAL4J2Af8I8RceWE55ukXruA1sXQc8AzwHcmOdg0tD+G/tY6p0bq5jgjv5l3yr6T9doD7RvJ/qv9nC9MeLZJ67WLzwHvB34G/D1wKCJumex4E9VrF38ETmbmK5n5BvBz4CMTnm+Seu1iH607PT8I/DWwPyI+NuH5toqRujnOyB+nddMUG9wpe0NEzEfEpfS5U/YdbsM9RMQ24FHgV5l5V2ZW/189bLiLzLwnM69r/6DpP4B/y8zKb9v0+vPxDLAQEZe3r2h307qSrarXLl4F/gw0M/NNWlG7bMLzbRW/Bj4cEe+NiB203qp5ut8Xje3TNcBR4KaIeIr2nbIRcYjOnbLfAZ6g9RfNP7f/BVa04R5o/f8obgTm2p+mALg3M/v+i3uH6vl7YrqjTVy/Px/3Ao+3n/tIZla9CIL+u/gkcCIiVmm9D/3TKc46cRFxB/DuzPxeey+P0+rmw5n5235f7x2vklSYN0NJUmFGXpIKM/KSVJiRl6TCjLwkFWbkJakwIy9JhRl5SSrs/wGJkN5Gxl0dUgAAAABJRU5ErkJggg==\n", "text/plain": [ - "<matplotlib.figure.Figure at 0x12ee61da0>" + "<Figure size 432x288 with 1 Axes>" ] }, - "metadata": {}, + "metadata": { + "needs_background": "light" + }, "output_type": "display_data" } ], "source": [ - "logit_balance = ClassificationReport(logit, classes=set(labels_test))\n", - "logit_balance.score(docs_test, labels_test)\n", - "logit_balance.show()" + "from yellowbrick.base import ModelVisualizer \n", + "\n", + "v = ModelVisualizer(KMeans())\n", + "v" ] }, { "cell_type": "code", - "execution_count": 29, - "metadata": { - "collapsed": false - }, + "execution_count": 14, + "id": "6a55c544", + "metadata": {}, + "outputs": [], + "source": [ + "from yellowbrick.model_selection import CVScores \n", + "from sklearn.naive_bayes import GaussianNB" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "id": "78392b14", + "metadata": {}, "outputs": [ { - "ename": "IndexError", - "evalue": "list index out of range", - "output_type": "error", - "traceback": [ - "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", - "\u001b[0;31mIndexError\u001b[0m Traceback (most recent call last)", - "\u001b[0;32m<ipython-input-29-3e54aae07a7d>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mlogit_balance\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mClassificationReport\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mLogisticRegression\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0mlogit_balance\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mfit\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdocs_train\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mlabels_train\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0mlogit_balance\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mscore\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdocs_test\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mlabels_test\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 4\u001b[0m \u001b[0mlogit_balance\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mshow\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;32m/Users/benjamin/Repos/tmp/yellowbrick/yellowbrick/classifier.py\u001b[0m in \u001b[0;36mscore\u001b[0;34m(self, X, y, **kwargs)\u001b[0m\n\u001b[1;32m 133\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mscores\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mmap\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;32mlambda\u001b[0m \u001b[0ms\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0mdict\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mzip\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mclasses_\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0ms\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mscores\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;36m3\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 134\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mscores\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mdict\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mzip\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mkeys\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mscores\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 135\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mdraw\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0my\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0my_pred\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 136\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 137\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mdraw\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0my\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0my_pred\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;32m/Users/benjamin/Repos/tmp/yellowbrick/yellowbrick/classifier.py\u001b[0m in \u001b[0;36mdraw\u001b[0;34m(self, y, y_pred)\u001b[0m\n\u001b[1;32m 158\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mcolumn\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mrange\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mlen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmatrix\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m+\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 159\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mrow\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mrange\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mlen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mclasses_\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 160\u001b[0;31m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0max\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mtext\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mcolumn\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mrow\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmatrix\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mrow\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mcolumn\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mva\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m'center'\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mha\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m'center'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 161\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 162\u001b[0m \u001b[0mfig\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mplt\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mimshow\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmatrix\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0minterpolation\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m'nearest'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mcmap\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mcmap\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mvmin\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mvmax\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;31mIndexError\u001b[0m: list index out of range" + "name": "stdout", + "output_type": "stream", + "text": [ + "None\n" ] - }, + } + ], + "source": [ + "c = CVScores(GaussianNB())\n", + "print(c.color)" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "id": "6b561595", + "metadata": {}, + "outputs": [ { "data": { - "image/png": "iVBORw0KGgoAAAANSUhEUgAABwIAAAsPCAYAAADlFF+DAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAAPYQAAD2EBqD+naQAAIABJREFUeJzs3X+s1fV9x/HXRURBFLEVFVZ0ReW26lplkFlnnbiN/rCb\nm3Wb1i2Q1VkWW+M2I83mXOcMbrVWlKqpzNbWH5l1NVVTzdRaW39MEWW2K1WprNhaGkBW5Zd3XM7+\nIJxw5QL3eygIbx+PpH94zud+/JzvRfJ959lzTler1WoFAAAAAAAAKGXQm30AAAAAAAAA4JdPCAQA\nAAAAAICChEAAAAAAAAAoSAgEAAAAAACAgoRAAAAAAAAAKEgIBAAAAAAAgIKEQAAAAAAAAChICAQA\nAAAAAICChEAAAAAAAAAoaHCnP/jwww/ni1/8Yl544YUkybHHHpvzzjsvxxxzzIB+vqenJ1/60pdy\n9913Z/HixRk5cmQmTZqUT3ziExk3btxm6++88858+tOf3uJ+l19+eU477bT2P7dardx666352te+\nlkWLFmXQoEE58sgjc+aZZ/ZZt1Fvb2+++tWv5q677sqiRYvSarXyq7/6qznttNPyp3/6pxk0qG8z\nbXr+ptesk/03tWTJknz4wx/O/vvvnwcffLDfNQsWLMh1112Xp556Kq+99lpGjx6dU089Neeee26G\nDBmyXefv5Pp/+ctfzp133pkf//jH2WeffXLcccflnHPOybHHHrvN1wsAwFvTzp5Lkh17H910Lnmj\ngcwBTdc3fb1N9t/Zc8Ps2bMze/bs/Od//mf233//7T4PAAAku34vabp/J3NJ07mhyfpO7tN39zls\ne9a/UVer1Wo1/aF/+7d/yyWXXJKhQ4fm+OOPz8qVKzNv3rx0dXXlhhtuyPHHH7/Vn+/p6cm0adMy\nb968DB06NO9973vT29ub+fPnZ9CgQZk1a1ZOOumkPj9z2WWX5eabb8773//+jBgxYrM9//iP/zgT\nJkxo//OFF16Yu+++O0OHDs3EiROzfv36PPnkk+np6cnUqVMzY8aM9tre3t6ce+65eeSRR7Lvvvvm\n137t15Ik8+fPz6pVq3LyySfn2muvTVdXV8fnb3LNOtn/jaZNm5bHH388Y8aM6fcPxv33358LLrgg\nvb29Oe6447Lffvvl6aefzi9+8YtMnjw51157bcfnb3r9k+SCCy7IvffemxEjRuS4447LqlWrMm/e\nvLRarfzzP/9zPvKRj2z19QIA8NbzZswlO/I+uulc0p9tzQFN1zd9vU3335lzw0MPPZRPfvKT6e3t\nzeOPP95vCGx6HgAA2NV7SdP9O5lLms4NTdc3vU/f3eew7V2/mVZDS5YsaR199NGtE044obV48eL2\n4w8//HDrqKOOap188smtnp6ere5x5ZVXtsaPH9/64Ac/2GePBQsWtH7jN36jNXHixNby5cv7/MzZ\nZ5/d6u7ubr366qvbPOPcuXNb48ePb5100kmtl19+uf34woULWxMnTmx1d3e3nnvuufbjt9xyS2v8\n+PGtj370o33+vT//+c9bp556aqu7u7t12223dXz+ptesk+uzqZtvvrk1fvz4Vnd3d2vy5MmbPb9s\n2bLWhAkTWu9973tbjzzySPvx5cuXtz7ykY+0uru7W/fdd1/H5296/e++++7W+PHjW3/4h3/Y5/f7\nxBNPtI466qjWxIkTW6tWrdri6wUA4K3nzZhLdvR9dNO55I22NQc0Xd/09Tbdf2fODbfffnvrmGOO\naZ9nxYoV230eAADYHXpJ0/2bziVN54am65vep+/uc9j2ru9P4+8IvPnmm7Nu3bp8/OMfzzve8Y72\n4+9///tz2mmn5Wc/+1nuv//+re7x7//+7+nq6spll13WZ4/u7u586lOfyquvvpqbbrqpz8/88Ic/\nzOjRo7Pvvvtu84zPPPNMurq6ctppp+WQQw5pPz5u3LiceuqpSZJ58+a1H//GN76Rrq6uXHzxxTng\ngAPaj48aNSozZsxIq9XKN7/5zY7P3/SadXJ9Nlq8eHGuuOKKTJw4Ma0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zzTn00EPb\na9euXZtp06Zl/vz5GT58eCZMmJCenp48+eSTWb9+fS6++OI+XyzZ29ubv/zLv8x3vvOd7L333pk0\naVJ6enoyf/78rF27NlOmTMlVV12VZMNbPn/rt34rr7/+eo4++ugcdthh/b7mAw44IJ/+9Kc7On/T\na9bJ/m+0YsWKHH/88RkzZkwefPDBzZ7/13/911xxxRVJNtT1IUOG5Omnn87atWvziU98Iueff37H\n529y/ZNk3bp1mT59eh555JHss88+mTBhQlavXp1nn302PT09OfPMM/P3f//3W329AAC89ezsuSTZ\ncffRnc4lb7StOaDp+qavt8n+b8bcMHny5PzsZz/L448/nv3333+7zgMAAMmu30ua7N/pXNJ0bmiy\nvpP79N19Dtve9W/UUQhMNryFcs6cOXnuuecybNiwHHPMMTn//PPzrne9q8+67u7uDBo0KA888ECf\nP9hr1qzJNddck/vuuy/Lli3LIYcckhNPPDHnnntun+/V2Kinpyc33nhj7rnnnixevDhDhw7Ne97z\nnpxzzjmZOHHiZuvXr1+f2267LV//+tfz4osvJkmOOOKInHHGGTnjjDPa6+6///586lOf2ubrHTNm\nTB544IGOz9/kmnW6/6ZWrFiR973vfZude1OPP/545syZk+9973vp7e3NkUcemalTp/ap4Z2ef6DX\nf9P1X/nKV3LnnXfmf/7nf7Lnnnvm3e9+dz72sY9t8TwAALCz55Jkx9xHdzqXvNFA5oCm65u+3ib7\n7+y5YfLkyVmyZEkee+yxzUJgJ+cBAIBk1+8lA91/e+aSpnNDk/Wd3Kfv7nPY9qx/o45DIAAAAAAA\nALDravwdgQAAAAAAAMCuTwgEAAAAAACAgoRAAAAAAAAAKEgIBAAAAAAAgIKEQAAAAAAAAChICAQA\nAAAAAICChEAAAAAAAAAoSAgEAAAAAACAgoRAAAAAAAAAKEgIBAAAAAAAgIKEQAAAAAAAAChICAQA\nAAAAAICChEAAAAAAAAAoSAgEAAAAAACAgoRAAAAAAAAAKEgIBAAAAAAAgIKEQAAAAAAAAChICAQA\nAAAAAICChEAAAAAAAAAoSAgEAA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3t0/AAD0dC6J\niDj33HPjzjvvjIEDB0ZDQ0O0trbGE088Ec3NzTFu3LiYMGHCOl9/8sknx2OPPRbDhg3rVgjsan1P\n3xev6/otLS0xfvz4ePjhh2PjjTeOz3zmMxERMXv27GhqaoqDDjoorrnmmqhUKjXfn4svvjimTZsW\n+++/f2y66abt9vfNb34zRo4cGRER3//+9zv9OWbPnh1vvPFG7LLLLnHbbbd1uObBBx+M7373u9HS\n0hKPPfZYt0JgV/e/7NwDAAAfxVyyPtfXMjeUmWPKXr+WnrSm7swNZZ5h2Tmmlv33dE5tpyhpwYIF\nxe67716MHj26mD9/fvX4zJkzi91226046KCDiubm5nVe48orryzq6uqKQw89tM015syZU3zuc58r\nGhoaisWLF1eP33nnnUVdXV3x9a9/vXjvvfeqxx9//PFit912KxoaGoqmpqbq8UWLFhUjR44s9tpr\nr+Lhhx+uHl+8eHFxxBFHFPX19cW9995b8/qy+7H/3t0/AAD0xlzy5JNPFnV1dcUBBxxQvP3229Xj\nc+fOLRoaGor6+vripZde6vT106ZNK+rq6or6+vpizJgxXe65q/U9fV/c1fVvvvnmoq6urjjmmGPa\nzFvvvPNOcfjhhxf19fXFrbfeWj1ey/058cQTi/r6+jZzQ1mvv/56sddeexWjRo0qFixY0OGaP/zh\nD8Uee+xR/XkbGxu7vG5X96fs3AMAAB/FXLK+15edG8rOMWWvX7Ynrak7c0NvPMOi6HyOKbv/ns6p\nHSn9HYHTpk2LVatWxSmnnBKf/vSnq8f333//OOqoo+I///lPzJgxY53X+NOf/hSVSiUuvvjiNteo\nr6+PM888M95777246aabqsfvuuuuqFQq8b3vfS823njj6vFRo0bF6NGjY+nSpfHss89Wj998883R\n1NQUp59+eowePbp6fMiQIXHWWWfF1ltvXf3zzlrWl92P/ffu/gEAoDfmkmeeeSYqlUocddRRsc02\n21SPDx8+PA4//PCIiJg1a1aHr50/f35cccUV0dDQEEU3PmSlO+t78r64O9f/85//HJVKJc4///wY\nMmRI9fiWW24ZEyZMiKIo4u67764er+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XPnFqtWrWr37zzwwANFXV1dceSRR3a4j/vvv7+oq6srxo8f3619r3bQQQcV9fX1\nRWNjY7tzPbk/ZeckAAA+fj6quWR9r+9IZ3NDb/1+f11zSU960mqdzQ09fYbdmWPK7r83ntfaSv1F\n4OrPMV25cmWH51cfHzhw4DqvM2jQoLjlllti3LhxsdFGG8Xjjz8eixcvjrPPPjt+8YtfxPLly6Nf\nv34dXmfDDTeMQYMGxWabbRZHH310XHTRRdHa2hpTpkxps8eIiOOOO67d67/1rW9FRMQTTzxR0/qy\n+7H/9bt/AAA+fnprLrnpppuiUqnEpZdeWv3Il4gPvqD+oosuiqIo4vrrr4+IDz728tprr61+xGRX\nyq4v+7647PXX9r///S/OOeecuPnmm2PTTTeNG264IYYPH95mTZn7ExHRv3//GD58eIcfn7nffvtF\nv3794uWXX47W1tZ25++9997qXxP2hp7en7JzEgAAHz8fxVzyYaxfU1dzQ09/v9+duaQnPakrPX2G\n3Zljyu6/J8+rM6W+I3DQoEExcODATj8PddGiRRERbTa3rmudd955cd5557U5vnjx4li2bFl8+tOf\n7taexo4dG5/4xCdi7ty50dLSEkOGDKmeW/tLKCMittpqq+jbt2/1TzDLri+7n66+Q8L+e3f/AADk\n1xtzyXvvvReLFi2KLbbYot2gGRHR0NAQAwcOrL7PnTRpUqxatSqampri3HPPra5b/fEtjY2N1eOX\nX3556fVl3xeXvf6ali1bFqeffno8+eSTsfnmm8fUqVOjvr6+R/enq7mhX79+sckmm0RjY2OsXLmy\nzS8MWltbY+bMmTFgwIA48MAD13md7urJ/elI2TkJAID8Poq5pKmpab2uX/N9bnfmhp78fr8711+t\nt3pSR9et9RmWmWO6u//ensNWKxUCIyJGjBgRzz//fLz11lvtHuyrr74aERE777zzOq/x6quvxptv\nvhkHHHBAu3OPP/54RETsvvvu1WOXXnppLFy4MK644oqoVCpt1vfp0yf69esXzc3N0draGltvvXVs\nvPHGsWzZsli4cGFstdVWbdY3NjZGS0tLbLHFFhERpdeX3U/fvn3tv5f3DwAAPZ1LWlpaIuKDQNWR\nSqVS/W64lpaWWL58eVQqlXj00Uc7XL9ixYq46667olKpxOWXX156fXffF2+55ZYREaWvv9p///vf\n+Pa3vx0vv/xybL/99jF16tT41Kc+1eP709zcHBdddFE0NTXF5MmTO9zPkiVLYuONN24TASM++D6R\nd999N8aOHdvpd3OUVcv9KTsnAQDAhz2XrO/1q9/ndnduqPX3+929fkT5nlRWrc+wu3NMmf3X+ry6\nUuqjQSMivvCFL0RRFPHAAw+0O3ffffdFpVKJ/fbbb53XmDx5cowfPz6effbZduemT58elUolDj30\n0Oqxv/3tb3H33Xd3+OejTz31VDQ1NcWIESNigw02qO4xIuKee+5pt/6hhx6KiIjPfvazbX6mMuvL\n7sf+e3f/AADQ07lk8ODBsdVWW8WCBQuqw92a/vnPf8by5ctj++23j/79+8dvf/vbmDNnTrv/rQ5N\nQ4cOjTlz5sS//vWviIjS61f/TBHrfl88cuTImq/f3Nwcp5xySrzyyiux2267xa233trpsN3d+7Pd\ndttF//79Y+DAgTFz5sz461//Gk8//XS79au/0H706NHtzj333HMREbHnnnt2uJda1HJ/ys49AADw\nYc0lq993r6/1q+eeiHJzw+p7ENH93++XvX7ZnlRWrc+wu3NMmf3X8ry6o3QIPProo6N///5xzTXX\nxNy5c6vHZ86cGXfccUdss802MXbs2Orx1157LV577bVqyYyIGDNmTEREXHXVVdWPZomImDp1ajz6\n6KOx0047xSGHHFI9fuyxx0ZRFPHTn/60+qeYERHz5s2LH/7wh1GpVOLkk0+uHh83blxERPziF7+I\nZ555ps36K6+8Mvr06RPHH398zevL7sf+e77/E044IQAAYLXemEuOP/74KIoiJkyYEEuWLKkef/vt\nt+NHP/pRVCqVD/V96Pp+Xzx58uR4/vnnY9ttt42bbropBg8evM713bk/J554YvX4McccE0VRxAUX\nXNDmo3XmzJkTP//5z6Nv375x6qmntvt3XnjhhahUKrHrrrvW/LP1hrJzDwAAfFhzyZrvu9fH+jXn\njLJzQ9keUPb6ZXtSWWWf4WrdnWPK7n99zKmVoiiKUq+IiN/85jdxySWXxAYbbBCf//znY8WKFfHk\nk09Gv3794sYbb2xTd1d/pusDDzwQQ4cOrR4fN25cPP7447HNNtvE7rvvHvPmzYtXXnkltthii5g2\nbVpst9121bWrVq2K008/PR5++OHYaKONYuTIkbF8+fJ49tlno7m5OY477rj48Y9/3GaPv/zlL+OK\nK66IiA9qc//+/ePpp5+OlStXxmmnnRZnnXVWzevL7sf+e3f/AAAQ0fO5pKWlJb7zne/E3//+9xgw\nYECMGjUqmpubY/bs2bFy5coYO3ZsTJo0aZ17aGxsjH333TeGDRsW999/f5d77mp9T98Xd3b9//73\nv3HggQfG+++/H7vvvntsv/32Hb5+yJAh8YMf/CAiyt+flStXxsknnxyzZ8+OQYMGxciRI6O5uTme\neOKJaG1tjfPPPz+OO+64dv/mSSedFE899VTceeedMWLEiC7v4ZrGjBkT//nPf+Kxxx6LzTbbrMv1\n67r/tcw9AADwYc8l63N9LXNDRPfnmFqvX6YndaSruaHMM1ytzBxTZv+9MaeuraYQGPHBn0ROnTo1\nXnrppdhwww1jjz32iLPOOit22WWXNuvq6+ujT58+cd9997UJgStWrIirr7467r333li0aFFss802\nsd9++8X48eM7/D641tbW+M1vfhO33357vP7667HBBhvErrvuGieccEKHNTYi4rHHHoupU6fGc889\nFy0tLbHzzjvHuHHjemV92f3Yf+/uHwAAIno+l7S2tsatt94at912W7z22msREbHTTjvFscceG8ce\ne2yX/35jY2N8/vOfj2HDhsV9993XK+t78r64s+vPmDEjzjzzzC5fv/bryt6f5ubmuPHGG+Ouu+6K\n+fPnx8CBA2PPPfeMU089NRoaGjr8N7/yla/EvHnz4sEHH2z3nSJdGTNmTCxYsCAeffTRbofAdd3/\nWuYeAAD4sOeS9bW+1rkhontzTK3XL9uT1taduaG7z3C1MnNMLT2sJ3Pq2moOgQAAAAAAAMD/XaW/\nIxAAAAAAAAD4v08IBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICEhEAAAAAAAABISAgEAAAAAACA\nhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICEhEAAAAAAAABISAgEAAAAAACA\nhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICEhEAAAAAAAABISAgEAAAAAACA\nhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICEhEAAAAAAAABISAgEAAAAAACA\nhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICEhEAAAAAAAABISAgEAAAAAACA\nhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICEhEAAAAAAAABISAgEAAAAAACA\nhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICEhEAAAAAAAABISAgEAAAAAACA\nhKzi0PwAACAASURBVIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICEhEAAAAAA\nAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICEhEAAAAAA\nAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICEhEAAAAAA\nAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICEhEAAAAAA\nAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICEhEAAAAAA\nAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICEhEAAAAAA\nAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICEhEAAAAAA\nAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICEhEAAAAAA\nAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgIS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AAAAAEhICAQAAAAAAICEhEAAAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQ\nAAAAAAAAEhICAQAAAAAAICEhEAAAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQ\nAAAAAAAAEhICAQAAAAAAICEhEAAAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQ\nAAAAAAAAEhICAQAAAAAAICEhEAAAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQ\nAAAAAAAAEhICAQAAAAAAICEhEAAAAAAAABISAgEAAAAAACChztX+4Lhx4+Kqq66Kt956KyIitt9+\n+zjllFNim222adXPl8vluPXWW+POO++MqVOnRqdOnaJv375x5JFHxqGHHtrm17znnnvinHPOafb1\nhw8f3uh16uvr47rrrov7778/pk2bFmuttVYMHDgwTj755Ojdu/dyP9/Q0BA33XRT3HfffTF16tQo\nl8ux2WabxaGHHhrHHntsdOrUcmMdOXJkjBw5Mp555plYc801v/TrrWb+urq6uPLKK+P555+Pzz//\nPHr27BkHHnhgnHTSSdGlS5fl1uf666+Pe+65J957771YbbXVYocddogTTzwxtt9+++XO3db1BADg\nm6mt+5Ki+4Ci991F9z1F52nrGsyYMSMOOOCAWHPNNWPMmDErfH5772MyrD8AAHyZvaS2tnaF5yuV\nSlFXV1f55yL30dWcv5res7QV7TPaep++on1PR88fUayvtHWeZVUVAv/2t7/F0KFDo1u3brHTTjvF\nnDlzYvz48fHUU0/F1VdfHTvttNMKz/GrX/0q7r///ujWrVt85zvficWLF8dzzz0XQ4YMiddffz2G\nDBnSptd87bXXolQqxe677x7du3df7vU33njjyn+vr6+P448/Pl544YXo1q1b7LjjjtHQ0BD//Oc/\nY/To0TFixIjYY489Ks9vaGiIk046KcaPHx+rr7567LDDDhERMWnSpBg2bFg888wzccUVV0SpVGry\n2seOHRujRo1q9vGOvt5q5h89enScfvrp0dDQEDvssEOsscYa8eKLL8bll18edXV1ccU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e5D666Pmrmb/IPqMt9+mt2fd09PxF+0p7/D4sq3AIfOqppyIiYq+9\n9lrusX322SfK5XI88cQTLZ5jrbXWinK5HB999NFyj82ePTsiotHbU4u+5r///e/4/PPPY6uttlrh\n9XzyyScxc+bMWGONNZr87rqBAwdGRMSTTz7ZaP4+ffo0ef5NNtkkIiI+/vjjRseHDx8eY8aMiZ12\n2inuuuuuJt9+u0RHXm81848ePTpWWmmlOOqoo5qcZ+zYsXHKKadUjl122WVx7733VtZuafPmzYuI\niM6d/+9TaatZTwAAvtnaui+pZh9QzX13a/c91cxT7RqUy+UYMmRIdO3aNYYOHdriNXTUPibD+gMA\nwFfRS5py1113xSuvvBK777577L///o0eK3ofXfT81czf2n1GW+7TW7vv6cj5I4r3lfb4fVhW4e8I\nnDJlSnTp0qUSaJa2+eabV57Tkn333TdGjhwZ9913X9TW1sYhhxwSEV+U3Ycffjh69eoV++yzT9Wv\n+frrr0fEFws2dOjQeOqpp+Ljjz+OXr16xY9//OM45phjKp/XuqQCr7rqqk3OutJKK0VExNSpUyvH\nRo0a1ey1vfzyyxERscEGGzQ6vuWWW8YPf/jD+N73vtfszy7RkddbdP76+vp45513YvPNN4+ampp4\n880346GHHoqPP/44Ntpoozj44INjo402anSOlVdeOfr27bvcue+666544YUXolevXo3+pa1mPQEA\n+GZr676kmn1A0fvuIvueauapdg2uvfbaeOmll+LCCy+Mtddeu8nXW6Kj9jEZ1h8AAL6KXrKsefPm\nxYgRI6Jz585Nfndc0fvoouevZv7W7jPacp/e2n1PR85fTV9p6+9DUwqFwE8//TTq6+ujZ8+eTT6+\nzjrrRETErFmzWjxPTU1N5Qs0hw0bFsOGDas8ts8++8Qf/vCHWGWVVap+zbq6uoiIuOOOO2LttdeO\n7bffPtZbb7149dVX449//GO89NJLcdFFF0XEF2+/7N69e8yYMSM++OCD5V7nxRdfjIiIBQsWxMKF\nCytzNaWhoSGuuOKKKJVKMWjQoEaPLV10W9LR19uSpuZ///33o6GhIdZbb70YNWpUXHrppZV/+crl\ncowaNSqGDRu23N8CWOKTTz6JoUOHxhtvvBHTpk2LLbbYIkaMGFH5F7ToPAAA0B77kmr2AUXvu4vs\ne4rOs2DBgqrWYMqUKXHppZfG97///dh///0rf6O0OR21j/m6r39L+0IAAL4Zvope0pTbb789Zs6c\nGYccckhsttlmyz3e1n6wovNXM39r9xnV3qcX2fd05PzV9JW2/j40pdBHg86fPz8iIrp27drk40uO\nL/n4x5Zcf/31MX78+KipqYlddtklBg4cGF27do0JEybEfffd16bXfP311yufoTp27NgYOXJk3Hrr\nrXH33XdHz54946GHHoo777wzIiJKpVIceOCBUS6X4+yzz270CzFlypS45JJLKv9cX1/f4jWdd955\n8dZbb0Xv3r3jsMMOW+EaNKWjr7fo/HPmzImIiMmTJ8dll10WgwcPjscffzyeeuqpOOuss6KhoSGG\nDBkSb7zxRpPnnD59ejz66KMxffr0KJVKsXjx4njzzTdbtRbtsZ4AAOTTHvuSavYB1dx3t3bfU3Se\natagoaEhzj777Fh11VXj97//fbNrU42i83zd1x8AAL6KXrKscrkcN998c3Tq1ClOPPHEJp/Tln7Q\nmvO3Zf4VqeY+vZp9T0fNX21fae95Cr0jsFOnL7phS28Tjfi/t2s25+qrr47rrrsuttlmm7jyyisr\nZfy9996Ln/3sZ/HnP/851ltvvTjggAOqes2LL744pk+fHptuummjd5717t07zj333Bg8eHDccsst\nccQRR0RExOmnnx4TJ06M559/PgYNGhTbbrttLFy4MCZNmlT58saPP/640ffaLev888+PO+64I7p3\n7x4jRoyIlVdeucV5m/NlXG+R+RcuXBgRX/zCHn/88fGLX/yi8jM//elPY86cOXHllVfG1VdfHRdc\ncMFy591iiy1i4sSJsWjRohgzZkwMGzYsfvnLX0bnzp1bfNtse60nAAD5tNe+pOg+oOh9d5F9T9F5\nqlmDUaNGxWuvvRYXXnhh9OjRo8WfK6qaeb7O6w8AAF9FL1nW2LFj44MPPog999wz+vTp0+T529IP\nWnP+tszfGkXv04vuezpy/mr6SkfMU+gdgUs+h3XBggVNP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H\nHnig8p9HHnmkMv8DDzwQ//jHP5p8/dYo+mfydV9/AAD4KnrJEpMnT45PP/00dt9992a/p7DaftDa\n87dl/tYqcp9edN/T0fMX7SsdNU/hELjrrrtGuVyOxx57bLnHHn300SiVSrHbbrs1+/NrrbVWrL/+\n+jFjxozKvwhL+9e//hXz5s2LTTbZJLp06VL4Nbt16xbjxo2LRx55JF588cXlnr/kixSXfHZsRMSI\nESPipJNOismTJy/3/LvuuitKpVLst99+lWP19fVxwgknxFtvvRVbb7113HbbbfGtb32r2WsuqqOv\nt+j8u+66a0REPPTQQ8s99uSTT0ZExLe//e3KsccffzwefPDBJj8u9Pnnn4+5c+dGnz59Kt/719Hr\nCQBAPm3dl0QU2wcUve+uZt9TdF9SZA1uuummqKurW+4/EyZMiIiInj17Rl1dXbz22mstrllLiv6Z\nfN3XHwAAvqxesummm1buW5d4+eWXIyJi2223bfb81fSDIudvy/yt1Zr79H333Tciiu97voz5i/SV\njpqncAg87LDDokuXLnHFFVfElClTKsfHjRsX9913X2y44YYxaNCgyvF33nkn3nnnnUZ18qijjopy\nuRxDhgyJTz75pHL8gw8+iN/+9rdRKpXimGOOqfo1Dz/88CiXy3Heeec1eltuXV1dXHzxxbHSSivF\niSeeWDm+9957R0TEpZdeWnmLaETENddcExMmTIgtttgifvCDH1SOjxgxIl555ZXo1atX3HDDDbHW\nWmsVXcYWdfT1Fp3/uOOOi4iIyy+/PF566aXK8alTp8ZFF10UnTp1iqOOOqpy/IgjjohyuRz/8z//\nU3n785Ln/+Y3v4lSqRTHH3981fMAAEB77EuK7gOK3ncX3fcUnafoGnS0ovN83dcfAAC+rF5y9NFH\nL/far776apRKpdhqq61anLHofXTR81c7f2t19H16R89ftK90xDylclOf37gCN954YwwbNixWXnnl\n2HnnnWP+/PkxceLE6Ny5c1x77bWN3h225OMdH3vssejZs2dEfPH2xp///OfxxBNPRNeuXWPgwIFR\nX18fkyZNigULFsSgQYPikksuqfo1FyxYEMcff3xMmjQpampqYscdd4z6+vp47rnnYvHixXHuuecu\n98WMxx13XDz77LOx4YYbRv/+/WPq1Knx1ltvxbrrrhs333xzbLLJJhHxxUdY7rnnnrFw4cLo379/\nbLrppk2uUY8ePeKcc85pdg333nvv+PDDD+Ppp5+ONddcs01rXOR6q53/r3/9a1xwwQUR8UWd7tKl\nS7z44ouxYMGCOPnkkxu9tXjRokUxePDgGD9+fKy22mqx4447xrx582Ly5MlRX18fRx55ZPzud79r\n1/UEAOCbp637kojW7wMiiu8zqtn3FJmn6Bo0Zfbs2bHTTjvFRhttFGPGjFnhmrfnPibD+gMAwFfR\nSyIijj322Hj++efj/vvvjz59+jQ7XzW9pMj5q51/aSvaZ7T1Pr2lfc+XMX+RvtIe8yyrqhAY8cXb\nWq+55pp44403YtVVV41tttkmTjvttNhyyy0bPa+2tjY6deoUjz76aKMN9+LFi+O2226Lu+++O955\n552IiNhiiy3iiCOOiCOOOKJNrxnxxcdNXnvttfHAAw/EtGnTolu3brHtttvGiSeeGAMGDFju+fPn\nz4/LLrssHn744Zg5c2ZsuOGGsdtuu8VJJ50U6667buV5o0ePjlNPPXWF67PRRhvFo48+2uzje++9\nd8yYMSMmTJjQ5C9GR11vW+Z/+umn45prromXX345Ghoaom/fvnHcccc1+beMFy9eHDfeeGPcc889\n8e6778bKK68cW221VRx99NGNnt9e6wkAwDdTW/clrd0HLFF0n1F031N0niJr0JTZs2fHzjvv3Or7\n7fbex2RYfwAA+Cp6yQEHHBBTp06NsWPHxvrrr9/ifEXvo4uev5r5l7aifUZb79NXtO/p6PkjiveV\ntsyzrKpDIAAAAAAAAPD/V+HvCAQAAAAAAAD+/xMCAQAAAAAAICEhEAAAAAAAABISAgEAAAAAACAh\nIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICEhEAAAAAAAABISAgEAAAAAACAh\nIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICEhEAAAAAAAABISAgEAAAAAACAh\nIRAAAAAAAAASEgIB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AAAAAAAAEhICAQAAAAAAICEhEAA\nAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICEhEAA\nAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEiobXPfOH369Ljxxhtj\n/vz5ERFx6KGHxrnnnhv9+/dv0vtramri1ltvjUceeSQWLVoU3bp1i4EDB8YPf/jD6NWrV73za2tr\n484774yHH344Fi5cGOVyOfbbb78YNmxYnHHGGdGmTd2mWS6X4+677477778/Fi5cGG3atIn9998/\nTj311Bg2bFi99R988MG45JJLGr3ecePGVd5XXV29xfsrlUoxb968Rl+fMGFCTJgwIf7xj39E165d\nt7je0qVL44QTToiuXbvG1KlT673e2p8PAACt09bMJc3Zt27LfXRE8X19bW1t3HbbbfHggw/Gu+++\nG506dYrDDjssRo4cGYceeugW729Lc0bR+y065zVnLixyv0WfZ9HrAQCAiK3vJdt6zih6jc3ZF1t/\n+66/OaVyuVwu+qY///nPMWbMmKiqqoojjjgiPvnkk5g9e3aUSqW46aab4ogjjtjs+2tqamLEiBEx\ne/bsqKqqikMOOSRqa2tjzpw50aZNmxg/fnx89atfrZxfW1sbZ599djzzzDOx0047xRe/+MWIiJgz\nZ06sWrUqjjnmmLjuuuuiVCpV3nPRRRfFI488ElVVVTFgwIDYsGFDPP/881FTUxNnnnlmXHzxxXWu\n6fLLL4+JEyfG4MGDo0uXLvWu+Xvf+14cfvjhERHxs5/9rNF7mzNnTixevDgOOOCAeOCBBxo8Z9q0\nafHjH/84amtr47nnnmtS6BoxYkQ899xzsddee9Ub0D0fAABao62dS5qzb92W++jm7OsvuOCCeOyx\nx6JLly5x2GGHxapVq2L27NlRLpfjd7/7XXzrW9/a7DPY3JxR9H6LznlFzy96v0WfZ3OuBwAAtnYu\nidi2c0bRa2zOvtj623f9LSoXtHTp0nK/fv3KgwYNKi9atKhyfPr06eWDDjqofMwxx5Rramo2u8aV\nV15Z7tu3b/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AAoCXmkm09ZxS5xubsi62/fddvivpT4RYsWLAg2rdv\nXxmcNvWFL3yhck5jNv5t044dOzb4+g477BAREQsXLqwcu+GGGxpd7+WXX46IiM997nOVY9/85jdj\nwoQJ8fDDD0d1dXWcdNJJEfFpSX388cejZ8+eceyxx1bOf/311yPi0//DjRkzJp599tn44IMPomfP\nnvHd7343Tj/99Dq/w/G/Vq9eHePHj4+2bdvW+67ejQ444ID49re/HV/72tcaXed/3XLLLfHSSy/F\nFVdcEbvuumuj57XW5wMAQOu1tXNJQ7a0b93W++ii+/p27drF/vvvX+/cSZMmxezZs6Nnz54NDo9N\nnTOK3G/ROa85c2HR+y3yPJtzPQAA0BJzybaeM4pcY3P2xdbfvus3RaEQ+OGHH0ZNTU306NGjwdd3\n2223iIhYvnx5o2vssssu0aVLl1i6dGksWbKk3lovvvhiRESsXbs21q1bFzvuuGOja9XW1lZ+3H3o\n0KGV4507d678+OLYsWNj7NixldeOPfbY+M1vflNn3Xnz5kVExH333Re77rprHHroobHHHnvEq6++\nGpdffnm89NJLceWVVzZ6Hffee28sW7YsTjrppNhvv/0aPOfcc89t9P0NWbBgQVxzzTXx9a9/PY4/\n/vhK+S8i8/MBAKD1aom5pCFb2rd+1vvojRrb129qxYoVMWbMmHjjjTdi0aJF0adPnxg/fnxlUNyo\nyJxR5H6LznlbOxc29X4b0tDzbMk5FQCA1qGl5pJtOWcUvcai++K1a9dafzuu39S5pNBXg65ZsyYi\nIjp06NDg6xuPb/xaloaUSqU48cQTo1wux6hRo+oMngsWLIirr7668u81NTWbvZ5LL7005s+fH716\n9YqTTz65zmu33XZbPPPMM9G5c+cYNGhQDBw4MDp06BAzZsyIhx9+uM65r7/+euU7eKdNmxYTJkyI\nu+++Ox544IHo0aNHPPbYY3H//fc3eA3lcjkmTpwYbdq0iZEjR272epuqtrY2Ro0aFR07doxf//rX\nzV4n6/MBAKB1a4m55H81dd/6We2jN7W5ff1GixcvjilTpsTixYujVCrFhg0b4s0336xzTnPmjKbe\nb9E5b2vnwqbcb2Maep4tOacCANA6tORcsq3mjKLXWHRfbP3tu35TFfpEYJs2bSoXszmN/dj8Rhdc\ncEHMmjUrXnjhhRg6dGgcfPDBsW7dupgzZ04MGjQoIj79rYaGfs9io8suuyzuu+++6NKlS4wfPz7a\ntWtXee2mm26KW2+9Nfr37x/XX399paq+++678YMf/CB+//vfxx577BEnnHBCRERcddVVsXjx4th3\n333r/A3SXr16xejRo+Occ86Ju+66K4YPH17vOqZNmxZLliyJo48+Onr37r3Z+26qG264IV577bW4\n4oor6vyofRGZnw8AAK1bS80lm2rKvvWz3EdvtLl9/ab69OkTs2bNivXr18fUqVNj7Nix8ZOf/CTa\ntm1b+fr9onNG0fstOudtzVzYlPst+jxbYk4FAKD1aKm5ZFvOGc25xiL7Yutv3/WbqtAnAjd+L+na\ntWsbfH3j8aqqqs2u07lz57j77rvjzDPPjE6dOsXMmTNj+fLlccEFF8Sf/vSnWL16dbRt27bBdf77\n3//GhRdeGHfddVd06dIlbrrppujVq1edc26//fYolUoxbty4yv9pIj79QfjLLrssyuVy3HjjjZXj\n7du3j169ejX4NTJHHXVUtG3bNt58883YsGFDvdcff/zxSn1vCfPmzYvrr7++8lU9RWV/PgAA0FJz\nyaaasm/9LPfRTdnXb6pjx47RuXPn6Nq1a5x88slx2WWXxYYNG2LChAkR0bw5o+j9Fp3ztmYu3NL9\nNud5bs31AADQ+rTUXLIt54zmXGORfbH1t+/6TVXorzJ27tw5qqqqGv1O22XLlkVE1Pkf6+bWGjVq\nVIwaNarO8eXLl8cnn3wSe++9d733fPLJJ3HOOefErFmzYrfddoubb745qqur65zz0UcfxbJly2L3\n3XdvcFAeMGBAVFVVxYIFC6K2tnaLvyHRtm3b2HnnnWPlypWxdu3aOj/SuGHDhpg+fXp06NAhjj76\n6C3ec1NcffXVsX79+li1alVcdNFFleMbP+a5cuXKyvE//OEPdd7bGp4PAAC05FwS0bR962e5j27K\nvn5Lhg4dGjvuuGPleorOGc2936JzXnPmwqbc76bPv8jzbKnrAQAgv5aYS7b1nNHca2zqvtj623f9\npir0icCIiN69e8e6devi3//+d73X3nrrrYiI2H///Te7xltvvRXTp09v8LWZM2dGRES/fv3qHP/P\nf/4Tp512WsyaNSv23XffuPfeexsc3mprayMiGv1YZKlUqvyGRG1tbaxZsyZ+/vOfx/nnn9/g+WvW\nrIkVK1ZE586d6wznERFz586NDz/8MAYPHtzod7wWtXr16iiVSjFjxoyYPHly5Z8nnniicj2TJ0+O\nv/71r3Xe11qeDwAARLTMXLJRU/atn9U+uqn7+oiIcePGxYUXXtjgVw21adMm2rZtG7W1tbFhw4bC\nc0bR+40oPucVPb/I/W5U5Hk2Z04FAKB129q55LOYM4peY9F9sfW37/pNUTgEfuUrX4lyuRxPPfVU\nvdemTJkSpVIpjjrqqM2uMX78+Dj77LNj7ty59V6bNGlSlEqlOO644yrHampq4qyzzor58+fHQQcd\nFPfcc098/vOfb3Dtbt26xZ577hlLly6tPMRN/fOf/4zVq1fHPvvsE+3bt4+qqqqYPn16PPHEE/Hi\niy/WO3/jD3Fu/O7VTb388ssREXHwwQdv9n6LuPPOO2PevHn1/pkxY0ZERPTo0SPmzZsXr732WuU9\nren5AABARMvMJRs1Zd/6Weyji+zrIyL+9re/xaOPPhrPP/98vddeeOGFWLVqVfTu3TvatWtXeM4o\ner8Rxee8oucXud/mPM+i1wMAAFs7l3wWc0bRayy6L7b+9l2/KQqHwJNPPjnat28f1113XSxYsKBy\nfPr06fHwww9H9+7dY+jQoZXjb7/9drz99tuVsh0RMWTIkIiIuOaaaypfRRMRcfPNN8eMGTOiT58+\n8Y1vfKNyfPz48fHKK69Ez5494/bbb49u3bpt9hpPO+20KJfLcfHFF8eKFSsqx5csWRK//OUvo1Qq\nxemnn145fsopp0S5XI5LL720zkc0582bF1dddVXssMMOMXLkyHp/zquvvhqlUikOPPDAzV7Ptub5\nAADQ2rTEXLJRU/et23ofXXRfP3z48CiXy/Hb3/628pUyERELFy6MX/ziF1EqlWLEiBGbXaMl77fo\nnF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AASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICEhEAAAAAAAABISAgE\nAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICEhEAAAAAAAABISAgE\nAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICEhEAAAAAAAABISAgE\nAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICEhEAAAAAAAABISAgE\nAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICEhEAAAAAAAABISAgE\nAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICEhLDNACMAACAASURB\nVEAAAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICE\nhEAAAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICE\nhEAAAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICE\nhEAAAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICE\nhEAAAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICE\nhEAAAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICE\nhEAAAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICE\nhEAAAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICE\nhEAAAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICE\nhEAAAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICE\nhEAAAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICE\nhEAAAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICE\nhEAAAAAAAABISAgEAAAAAACAhIRAAAAAAAAASEgIBAAAAAAAgISEQAAAAAAAAEhICAQAAAAAAICE\nhEAAAAAAAABISAgEAAAAAACAhNpv6xOfeeaZmDBhQvzpT3+KiIi+ffvGxRdfHIcddthWPb8oirj3\n3nvj/vvvj8WLF0e7du3i4IMPjnPPPTdOO+20ZuM3bNgQd9xxRzz66KOxdOnS6NGjRwwYMCC+8Y1v\nRO/evZuMra6ubvP1S6VSzJ8/v9XHX3vttTjppJOie/fu8eSTTzZ7vL6+Pu688854+OGHY8mSJdGp\nU6fo169fDB06NPr27dts/MMPPxxXXnllq693/fXXN/m532/zExExf/78GDduXDz//POxZs2a6NWr\nV5x88slx4YUXRocOHdp8zwAAvP9s776kknV0xMZ17k9+8pN45JFHYvHixVEURey///5x2mmnxRe/\n+MVo167p31pWug/YXFvr7kr3DRFbP2fbum+oZF3/bs//tuxLNlVTUxM1NTXx7LPPRvfu3dscDwAA\nm3qv9yubq3Q9e+utt8b48ePj+eefj86dOzd7vL6+Pu6+++545JFH4q9//WsURREHHHBAnH766fH5\nz3++2Xp8c8uXL4/BgwfHHnvsEY8//vgOOf9LL70U48ePjxdeeCHWrl0bvXr1isGDB8fQoUNb7ApP\nP/10+TNp165d9O3bNy655JLo06dPs7F1dXVxxx13xNSpU2Pp0qXRqVOn6N+/fwwdOjQOP/zwZuPv\nv//+uOqqq1r9+W+88cY45ZRTtnn8ttqmEPizn/0sRowYER07doyBAwfG2rVrY+bMmTFr1qyYOHFi\nDBw4sM1zDBs2LB599NHo2LFjfOxjH4uGhob47W9/G8OHD48FCxbE8OHDy2M3bNgQ559/frzwwgvR\nsWPH6N+/f9TX18fjjz8eM2bMiFGjRsXRRx9dHj948OBWX3fevHmxbNmyOOSQQ7b4/q688sp48803\nW/3luPzyy2PatGnRrVu3+MQnPhFvvvlmPPPMM/H000/HDTfc0OzDefnll6NUKsVRRx0V3bp1a3a+\nffbZ5309PzNmzIjLLrss6uvro1+/ftG1a9f43e9+F7fddlvMnz8/xo4du8X3AwDA+8/27ksqXUfX\n19fHhRdeGDNnzowuXbpEv379ImLjGnrkyJHx7LPPxtixY6NUKpWfU+k+YHNtrbsr2TdUOmfbsm+o\nZF3/Xsx/pfuSTdXW1sb48eObnA8AALbWe71f2Vyl69knnngiJk2a1Or4urq6+PrXvx6zZ8+Orl27\nRv/+/aMoipg3b15cd9118dxzz0VNTc0WX+PKK6+MdevW7bDzT58+PS6//PJoaGiIfv36RefOnWPu\n3LkxZsyYWLBgQYwZM6bJ+MmTJ8e1114bu+66awwcODBWr14dv/71r2PmzJlx++23x4ABA5qM/853\nvhO/+tWvonv37jFo0KBYu3ZtPPXUU/HUU0/FTTfdFCeeeGKT8fPnz49SqRRHH310dO3atdnPuPn+\nr9Lx26yo0GuvvVZ89KMfLQYNGlQsXbq0fPyZZ54p+vTpU3zyk58sNmzYsMVzzJkzp6iqqiqOPvro\nYsWKFeXjixYtKo488siiurq6WLhwYfn4j3/846Kqqqr47Gc/2+Q158+fX3z84x8vjjzyyOL1119v\n871/61vfKqqrq4sBAwYUr732Wqvj7rnnnqKqqqo4+OCDy+OHDRtWfo1HH320qKqqKs4444xi9erV\n5ec999xzRZ8+fYojjzyyePPNN5uc8wtf+EJRXV3dZPz/2vz89a9/LY444oitnp/q6uriU5/6VLPH\nK52fVatWFf379y+OOOKIYubMmeXjr7/+enHKKacU1dXVxfTp09t8/wAAvH/siH1JpevoyZMnF1VV\nVcVZZ53V5Pjf//734uSTTy6qq6uL++67r8lrVLIP2Fxb6+5K9w07Ys6KovV9Q6Xr+nd7/rdl39Zo\nypQpxWGHHVae/3/+859tzgsAADT6b+xXNlXpevanP/1p8dGPfrQ8fs2aNc3G3H333UVVVVVx9tln\nF2+88UaTn/XEE08sqquriylTprT6GnfeeWf5/J/5zGe2+/z/+Mc/in79+hVHHHFEMXv27PLxVatW\nlfcHM2bMKB9fsWJF0adPn+ITn/hEsXz58vLx2traok+fPsWnPvWp4p133ikff/jhh4uqqqpiyJAh\nTeZj9uzZRZ8+fYoBAwYUb731VpOf4ZxzzikOOeSQVvcZm6t0/Laq+B6B99xzT9TV1cXXvva1JjXy\nqKOOitNOOy1effXVmDFjxhbPMXfu3CiVSnHaaafFhz70ofLx3r17x8knnxwRES+88EL5+IMPPhil\nUimuu+66Jq9ZXV0dl156aaxevTruuuuuLb7mlClTYtq0adHQ0BAjRoyIPffcs8VxS5cujZtuuil2\n3nnniIjo0qVLfPWrX42nnnoqLrjggqirq4tf/OIXUSqV4vLLL48uXbqUnztgwIAYNGhQrFmzJl58\n8cUm512wYEH06tWryfj/pfkpiiK++93vxttvv71V83PkkUdGURQtjql0fiZPnhxvvvlmXHTRRTFo\n0KDy8d122y2+9a1vxV577VX+6jQAAETsmH1JpevoqVOnRqlUiquuuip222238vGePXvG8OHDoyiK\n+OUvf9nkNSrZB2xqa9bdle4bdsScbWnfUOm6/t2e/23Zty1btiwuvvjiuOqqq6Jz587RqVOnLc4H\nAAC05L+xX4mofD27bNmy+OY3vxkjRoyIrl27RseOHVsd+/Of/7y8Hu/Ro0f5+J577hnDhg2Loihi\n2rRpLT538eLFccstt2xxf1Pp+e+5555Yt25dXHLJJU2+Xbn77rvHpZdeGnvttVcsWrSofPzuu+8u\nX2Vk7733Lh8/5phj4pRTTokVK1Y0uR3DY489FqVSKb73ve81uUzqwIED42Mf+1isXr06XnrppSY/\nw8KFC2OfffaJXXfdtdV53J7x26riEDhr1qyIiPjkJz/Z7LFjjz02iqKIX//611s8R48ePaIoivj7\n3//e7LF//vOfERHly+a88cY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Ljzceb+3ym43uuuuuKJVKcf3115c3qxEbb/B+7bXXxpe+9KWYMGFCOXR17tw57r33\n3rjtttti+vTp8dxzz8U+++wTl112WXz5y1+OAQMGRPv27Vt83enTp5f/CvdHP/pRs8fnz58f48aN\nK196Z+7cuRGx5X8Qmz626TV6zzzzzNh1113jsssui5qamvKGskOHDrF69er4/e9/32xj2qNHj9hp\np51i4cKF8fvf/z7atWsXkyZNilKpFF/96lfj1VdfjVdffbU8/vzzz49rrrkmRo8e3eR+hz/4wQ/i\n/vvvj9mzZ8ezzz4bPXv2jHPOOSdOOumk+MpXvhI77bRTi9ccvu+++6JUKkW/fv3K19nd1OLFi2Ps\n2LExYMCA2Geffcpj1qxZExEb/9qgpee15OCDD46hQ4fGLbfcEjfeeGPsueee8be//a38eEvvofEa\nu7Nmzdrq1wEAILfGv+ZcvXp1i2vExr/ibN++fZtryG1dR9fV1UVNTU3MmjUrOnXqFMOHD49169a1\n+Hovv/xys2Ob7wOWLFlS8bq7kn3DpnM2d+7cZvfGa2svt+m+qiWb7ovOPffcZo+fc845MW7cuPjt\nb39bPrY9+7x33nknhg8fHo899lh069YtJk6cGL17927xvW3+/lrbtwEAwI6wozrK9qyX320bNmyI\nYcOGxfTp06Nbt24xadKk2G+//cqPv/TSSzFhwoQ44YQT4jOf+cwOP/+mP3NL+4+zzz47JkyYUN5/\nNI5vDIiba+sz6dSpU/l/DxkyJDp27BiXX355kxDYoUOHVvckRx11VLRr167JlQ8rHb89KgqBnTv/\nP/buPUir+rD/+OeBZRHCRVEhykWZqlUECaJS1IyWRm10nMoE2iQqglWj0WrbhCFW00mb/JpoWm9p\nMkoWvOClHW2RqKQxRmJNcRQQQYWIF2IxaQQE5LLLdff3h7Nb112UBZa137xeM/7Bc855+D5njzPn\ny3u/5+mRbt267fTZtY3PT31/3Pug9evXZ/Xq1Tn44INb/ZAnnnhiunXrltdeey07duxoKrU9evTI\nlClTMmXKlGb7v/POO9m4cWMGDhzY4r3q6+vz1FNPZb/99svpp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W55ppr2jQ+\nWvIoMjqaa5CPA9chHc01uHft6bwk2fX76HXr1uX000/Pli1bMnTo0GZfVP9+ffr0ybXXXpvkvXnA\npEmT8sILL6RHjx4fOQ9ozYfdd+/OvOH//b//l3vvvXeXzlmjtswb2npf357nf3fmJR80ZsyY/M//\n/E+eeeaZ7L///h+6LwAAvN++nK/sTFvvZ0877bSsXLky8+bNS48ePZpeX7NmTU4//fRs27Ytxx13\nXAYNGtTq8QcddFCL7zN8v9WrV+fUU0/NYYcdlp/85Cd7/P5Tp07NzTffnEqlkhNOOCFdunTJggUL\nsmXLllx55ZW56qqrmh1/55135sYbb0x1dXVGjx6d2trazJs3L9XV1bnrrrsyYsSIpn23bduWyy+/\nPHPnzk2PHj1y/PHHp7a2NosWLcq2bdtywQUX5Lrrrmvav66uLhMnTszixYub5n9btmzJvHnzUl9f\nn2984xv50z/9093ef0/sVghM3lsqWVNTk1deeSXdu3fPsGHDcs011+SYY45ptt/RRx+dTp065Ykn\nnmh2AdfX1+eBBx7Iv//7vzd7/ur48eMzfvz4Fn9fXV1dvve97+U//uM/snr16hxyyCH59Kc/nS99\n6Us7/QLHc845J8uXL8+cOXPSr1+/jBkzJgMHDszdd9/dtM/MmTPzN3/zN/n2t7+d8847r+n1xYsX\nZ/z48alUKjnwwANz2mmnZfLkyU2/dVpfX5977rknM2fOzK9+9at06dIlQ4YMyfnnn9/qb9E+//zz\nmTlzZhYuXJj//u//Trdu3TJ8+PBceumlzZanduT5aYu1a9fm5JNPTv/+/fPEE0+0Ov62nJ8keeaZ\nZ1JTU5MXX3wxO3bsyFFHHZWJEyfudH/axj880tFcg3wcuA7paK7BvW9P5yW7eh/905/+NFdfffVH\njueD98dbt27N9OnT8+ijj+7SPOCDduW+uy3zhgULFuSFF17IT3/60488Z43aOm9oy319e5//3ZmX\nvN+YMWPy29/+NnPnzhUCAQBos301X9mZtt7PnnbaaVm1alWee+65ZiHwxz/+cf76r//6I48fNGhQ\ns8D3QatXr86nP/3pFvvtyfv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fhfQkf72t7/l+OOPz4oVK3LqqadmxYoVGT9+fGbOnJnbb789Xbq0PvzHH388p556avr165ez\nzz479fX1mTBhQo499thMmDAhAwcOXM8jAQAAAAAAgMoUOgi84YYb8uabb+buu+9O3759kyQf+chH\nMmrUqEycODFHHXVUq8d961vfytZbb5077rgjNTU1SZIjjjgihx56aC6//PJcf/31620MAAAAAAAA\nUI1CPxr0nnvuydChQxtDwCQZNmxY+vbtm3vuuafVYxYsWJCZM2fm0EMPbQwBk2TzzTfPkCFD8vTT\nT3d43QAAAAAAANBehb0jcMGCBZk9e3Y+9alPtdg2YMCAPPzww60e161bt9x7772pra1tsW3+/Pmr\nfZwoAAAAAAAA/D0p7B2Bb7zxRpJkq622arGtV69eWbhwYRYtWtRiW6dOnbLddttlyy23bPL59OnT\n8/TTT2evvfbqmIIBAAAAAABgHSpsELh48eIkyYYbbthi2wYbbJAkWbp0aZvOtWTJkowePTqlUimn\nnHLKuisSAAAAAAAAOkhhg8ByuZwkKZVKq91nTdsaLFu2LKeffnpmzpyZU089NXvvvfc6qxEAAAAA\nAAA6SmFfeLfRRhsleS/Ia2758uVJ3nsf4JosXLgwp556aqZMmZKRI0fm3//939td17PPPtvuc0A1\nVqxYkcQc5P1jDvL3wDzk/WYOAgAAAOtTYYPA3r17J0nmzp3bYtubb76ZHj16tPrY0Abz5s3LSSed\nlBkzZuSLX/xiLrrooo4qFQAAAAAAANa5wgaB3bt3T58+fTJ16tQW26ZOnZrdd999tccuXry4MQQ8\n8cQTM3r06HVW1x577LHOzgWVaLjzwBzk/WIO8vfAPOT9Zg7yfnvqqafe7xIAAABYjwr7jsAkOfjg\ngzN58uTMmjWr8bOGPx922GGrPe7iiy/OjBkzcsIJJ6zTEBAAAAAAAADWl8LeEZgkJ598cu68886c\ncMIJOemkk7Js2bJcf/31GThwYA4//PAkyezZs/PMM89k0KBB2XbbbfPSSy/lrrvuSs+ePbPLLrvk\nrrvuanHez372s+t7KAAAAAAAAFCRQgeBm222WW677baMHTs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V1dvv71r2f69OltHm/z\nelauXJnHH388Y8aMyfTp0zNmzJjGfevr63PaaaflkUceSffu3bPXXnslSaZMmZKxY8fmD3/4Q666\n6qqUSqWqr/8555yTX//61+nZs2c++tGPZvHixXnwwQfzu9/9LpdcckkOP/zwJvtPnTo1pVIpH//4\nx9OzZ88W12Tbbbetun4AAEja35ckla27m5s0aVKuueaaNa5TK11HN7emPiOpbN2dJH/+858r2v++\n++7L2Wefnfr6+uy1117p0aNHnn766Vx55ZWZNm1arrrqqqrrWbVva27KlCmZPXt2i76tubX1YZX0\nPfoSAACq8X70JZX2AZWev9IxVdo3NLeu+55VtaVva0/9azv/+shv1qpcoTlz5pR333338n777Vd+\n9dVXGz9/8MEHy7vttlv5wAMPLNfV1a3xHJdddll5l112KX/6059uco5p06aV/+mf/qk8ZMiQ8ttv\nv93u75w/f375wAMPLH/sYx8rjx8/vjx27NjyzjvvXN51113Lr732WuN+TzzxRHmXXXYp77///uW/\n/OUvjccNGzas/JGPfKS8yy67lAcNGlQeMWJE+d13323xPbfeemt5l112Kffv37980EEHrXa8Bx54\nYJvG27yeBi+++GJ5yJAh5f79+5dnzJjR+Pltt91W3mWXXcojR45scp433nij/JnPfKbcv3//8k9+\n8pOqr//dd99d3mWXXcqf//znywsWLGj8/LHHHivvtttu5SFDhpQXL17cZMzHHntsuX///k32X51K\n66c6U6ZMKU+ZMuX9LoN/YOYgfw/MQ95v5uC6sy76kkrX3av62c9+Vh44cGBjHzB//vwW+1Szjl7V\n2vqMcrmydXe5XC4fccQRbd7/rbfeKg8ePLi85557lh955JHGz99+++3y4YcfXu7fv3/53nvvbVc9\nrfnzn/9c3nPPPctDhw4tz5kzZ7X7tbUPa2vfoy8BAKBS71dfUsm6u9LzVzqmavqGVXVE39OgLX1b\ne+pvy/k7Or9pi4qfa3LrrbdmxYoVOfnkk5ukrB//+MczYsSI/PWvf8199923xnP8/Oc/T6lUyje/\n+c0m5+jfv3/+7d/+LQsWLMhNN93U7u+84YYb8uabb+amm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2jRoowePTobbbRRLrro\notWOtfl4r7766rWOt3k93bp1y3777ZehQ4e2qGdtLr744rzwwgvZcccdc+SRR7aopy3Xv7nZs2fn\n/vvvz+zZs1MqlbJy5crMnDmzyT7Tp09vfObwpEmTMm7cuEyYMCG/+MUv0rt37/z617/O7bffXlX9\nAACwLvqSButi3d0WbVlH19fXt7nPSCpfdzf8Ju3++++/1v0XLVqUJHnuuefywx/+MGeccUZ+97vf\n5dFHH825556b+vr6jBkzJjNmzKi6nlWVy+UWfVtzlVyf9vY9q9KXAADQmverL6lm3d3W81c6pmr6\nho7ueypRTf3rSkfkN6tT0R2BnTp1aixmTdb0UsckOfvss/PEE0/kySefzCGHHJI99tgjy5cvz5Qp\nUxpfxjh37tx06dKl6u9s+POMGTPyl7/8JQcccEB22mmnJvs0nPO6667LDTfckIEDB+Zf//Vfc8YZ\nZ+Tkk0/O3nvvnVNPPTXf+c530qtXr8bjbrnllkydOjXf+973mrzccU3jfeihhzJ9+vQMHz48O+20\nU95999288MIL+chHPpJ333038+fPzx//+MdssMEGufvuu/PTn/40H/7wh3POOec0Pl92zpw5+c53\nvpNLLrkkixYtyr777rva77zxxhtz3333ZeONN86pp56a5557rnHbAQcckIceeihPPPFEm+pZ1bJl\ny3Lttddm5cqVefLJJ3Prrbfm7LPPziuvvJK99947SXL88cfnkEMOydZbb914a2uDo48+Ot/73vdy\n3XXXNd5GXGn9tE/zF8vC+mYO8vfAPOT9Zg62T0MztGzZslav5cqVK5Mk77777hqv9bpYd9fV1aVc\nLufZZ59Nt27dVrtfW9bRv/jFL/KnP/0pX/nKVzJr1qzMmjUrCxcuTJIsX768xVgqXXc37N+7d+/U\n1NQ07rvjjjvmggsuyBlnnJHbbrstRx11VJYvX57kvcZ41KhR+cpXvtK4/7/8y79k0aJFufrqq3Pd\nddfl0ksvTZJ8//vfz+zZs7PDDjs0udOxtfM3N2nSpNX2bQ2uueaaivuwtvadq/ONb3wjP/vZz9Kz\nZ89cccUV6dq161q/FwCAfwzrKi9ZNZ+4+uqrG++6e+WVV5rkE4cddliSytfdlZy/0jFV0zdUuq5v\nT5+xNtXUvy6sqc9YF31McxUFgQ3PJV22bFmr2xs+b7irbnW6deuWCRMm5Morr8y9996bxx57LNtu\nu23OPvvsnHDCCRk6dGi6dOmS2tra1NfXV/WdDbU+++yzjWlxg4Z/uQ2N+k033ZRSqZRvf/vbWbFi\nReN5t99++3zjG9/I8ccfn2uvvTb77rtvyuVybrrppsZbVtuiW7duufjii/Pzn/88f/jDHzJt2rT0\n6tUrxxxzTA477LCceOKJ6dKlS7p3754k+fWvf51SqZSvfOUr2XLLLRvPs9122+WMM87IRRddlF/9\n6lc54IADWnzXihUrMm7cuDz66KPZeOONc/7557d4rE5NTU2++c1v5vbbb8/kyZPXWk/zYxscfPDB\n6datW77//e/nF7/4ReNfkNTU1Kz2UT5DhgxJ586dM3v27CZBbyX1AwDwj61hnfruu+82WZ82WPW3\nWFvb3qA96+4GpVIppVIpXbt2XeN3rW0dPWvWrPzyl7/MPvvsk49//OMtjiuVSi3OX+m6u6amJn36\n9Gm1qf/Yxz6WLl26ZObMmVm5cmWTd1IcffTRLfb/0pe+lKuvvjqPP/54k3p23HHHVutpfv7mfcC9\n997bom9b1bRp03L11VdX3Ie1te9s7t13382YMWPyP//zP+nZs2euu+661Y4NAIB/TOsqL1k1n2gI\n6ZK0yCcagsBK192VnL/SMVXaN1Szrm9Pn7E21fQ97dGWPqM9fczqVBQEduvWLbW1tat9pm3DO/BW\nnUxrOtfo0aMzevToJp+//fbbWbRoUbbddtt2fWfv3r1TLpczc+bMbLjhhk2a9zfffDM9evTIhhtu\nmAULFuStt97KlltumR133LHxN27nzp2b5L0Gura2Ni+++GJ23HHHdO7cOStWrMjixYtz7rnnNp6z\n4TbM+fPnN37+3e9+t3H7vvvu2+pvEr/99ttZunRptt122wwcODALFizIO++8ky233DKf/vSnW+y/\n++6755JLLslrr72WAQMGNEnAFy1alDPOOCNPPPFEtthii4wfPz79+/dv9bolydChQ9daz9rstttu\nueqqq/L666+3qGd1evbsmfnz56dfv35N/kOrtH4AAP5x1dbWZuHCha2uWV955ZUkydZbb73aNW17\n1t2ravjNzQEDBmSTTTZpc/3N19Hjxo1LfX19unTpkptvvrlxv4Y+Y/HixY2fr9pnrMnq1t2t6dKl\nS3r06JH58+dn2bJlTX4zd5tttmmx/1ZbbZXOnTuv8V0eazr/qvWsXLkyDz74YIu+bVWXX355VX1Y\nW/vOVelLAABoi3WRlzTPJ5pbNZ+or69f69+/N193r1ixoqLzVzqmSvuGatf1bR3v2vqe5tZ137Mm\nlfQZ1fQxa1JREJgkO+20U55//vm8/vrrLS7MSy+9lCTZeeed13iOl156Ka+99lr233//Ftsee+yx\nJO813u35zu7du6dXr155880386lPfarJM22nTp3aeP6GOw4bbqPs3r17+vTpk6lTpyb5v9/wXbly\nZaZOnZqNN944CxcuzOTJk1sd29KlS/OrX/0qpVKpcaJWMt7m9TS3aj2r/of/t7/9Lccff3xmzpyZ\nHXbYIePHj0+fPn1aPUel1//b3/525s6dm0svvbTFbw936tQpXbp0SV1dXVauXJm6urp84xvfyOLF\ni3PFFVe0en3mzZuX7t27N/mPspL6AQCgvX1JtevuSlSyjl6yZElKpVKb+4ylS5dWtO6udP+NNtoo\n3bt3z6JFizJ37txstdVWTfafP39+6uvrG++krPT8q3ruuefyzjvv5JBDDlntu0gqvT5J5X1Poi8B\nAKAy67svqfTv3xsCrEr6nkrG9KEPfahNfUPDq9c6uu+pVFvrX/UJMtXoyPymLSq7TzLJRz/60ZTL\n5fz2t79tse3+++9PqVTKxz72sTWe44orrshpp53W6nvf7rjjjpRKpSa/lVvtdza8C2PVdHTy5MmZ\nNWtW4220m266abbaaqvMmTOncRIffPDBjfs9++yzWbJkSbbaaqv8+c9/zpgxYzJt2rQW/zRM3N69\ne2fatGmNQWKl422tnlU11LPDDjs0Phqorq4uJ598cl544YXstttu+clPfrLGZrXS6/+73/0u99xz\nT6u3vz755JNZvHhxdtppp3Tt2jW1tbV58MEH85vf/CZPP/10i/0bXjza8CzbauoHAID29iXVrLsr\nVck6+pZbbqmoz6h03V3NOv2jH/1okvceodrcww8/nCSN7zes5vwNGt5vuMcee7TY1qDS65NU3vfo\nSwAAqNT66ku233771NTUVLzurvT81YypLX3D4MGDk1S+rm9Pn9FWlfQ91ejo/KYtKg4CjzzyyNTU\n1OSqq67Kiy++2Pj5gw8+mLvuuitbb711DjnkkMbPX3755bz88suNyXaSHHTQQUmSH/zgB423fCbJ\n+PHjM3ny5PTr1y8HH3xw1d/ZoOG2zjvuuCM33nhjrrnmmpx11lkZOHBgDj/88CTJ7NmzM2jQoJTL\n5YwZMybz5s3LySefnJ49e+bYY4/Nl7/85STvJb+rHleJSsd7zDHHNKmnwV/+8pecf/75KZVK+ed/\n/ufGz6+44oo8//zz2W677XLTTTdl0003Xaf1HHXUUSmXy/mv//qvxlt/k2TWrFn5f//v/6VUKmXU\nqFGNn48cOTLlcjkXX3xxk1uIp02blu9///vp3LlzTjnllKrrBwCAddGXVLrurlSl6+hKVbrurnT/\nE088MUly5ZVX5plnnmlS/2WXXZZOnTrlmGOOqfr8Df70pz+lVCplwIABVV+L1lTa9+hLAACo1Prq\nS4499tjGzytdd1d6/krH1Ja+oT19VbV9Rlt1dP0dnd+0RdTFyRYAAA31SURBVKlcLpcrLfzmm2/O\n2LFj07Vr1+y7775ZunRpnnjiiXTp0iU//vGPm6SjDc84/e1vf5vevXs3fn7iiSfmsccey9Zbb53d\nd989s2bNygsvvJAtt9wyt956a7bffvuqv7PBcccdlyeffDKDBw/O1KlTU1tbm/333z/nnntu48We\nOHFizjvvvOyyyy6N7xMcOnRo3nnnnTz33HOpr69PTU1NDj/88CbHNTd//vwMGzYs22yzTR544IEW\n2ysZb319ff71X/81Dz30UGM9dXV1mTJlSpYtW5ZDDjkkl19+eZL3bik94IADsnz58uy+++7ZYYcd\nWq1vs802y3nnnVdVPStWrMgZZ5yRRx55JBtvvHEGDx6cJUuW5LnnnktdXV2OPvro/Od//mfj/suW\nLcuoUaMyZcqUdOvWLYMHD05dXV0ef/zxrFy5MhdccEHjizerrR8AANrbl1Sy7l6dgw46KH/961/z\n+9//vsU7AitdR7dmTX1GJevuavZPkuuvvz6XXnppkvd+C7ampiZPP/10li1bltNPPz1nnXVWu86f\n/F/fdvfdd2ennXZa4/Wo5Pokbe979CUAAFRrffclla67q+l7Ks1jKukbWrMu+57WrKlvWxf1r+78\n6yO/aYuqgsDkvVtAx48fnxkzZmSjjTbKwIEDc9ZZZ2XXXXdtsl///v3TqVOn3H///U2CwKVLl+aH\nP/xh7r333rz11lvZeuut87GPfSynnXbaap+32tbvbHDYYYdl1qxZmTRpUotnuza3cuXK/OQnP8kv\nfvGLvPzyy0mSfv365aijjspRRx211usxf/787Lvvvtlmm21y//33t9he6XjbWs99992Xf/u3f1tr\nfc3rqqaem2++ORMnTsyf//zndO3aNQMGDMg///M/t3o3Zl1dXX784x/nV7/6VV599dXU1tZmjz32\nyCmnnJIhQ4a0u34AAEja35e0tw846KCDMmfOnEyePLnVhrLSdXRza+sz2rrurnb/JPn973+f8ePH\n549//GPq6+uz884758QTT2xXH7CqSvq2Sq9PW/sefQkAAO2xvvuSStfd1fQ9leYxlfQNza3rvqe5\ntfVt7a1/dedfX/nN2lQdBAIAAAAAAAB/vyp+RyAAAAAAAADw908QCAAAAAAAAAUkCAQAAAAAAIAC\nEgQCAAAAAABAAQkCAQAAAAAAoIAEgevAa6+9ljPPPDP77LNP9tlnn4wePTrz5s3rsOOguWrn0sMP\nP5xjjjkme+65ZwYNGpRRo0bl2WefXQ8VU0Tr4mfa9OnTs/vuu2fcuHEdVCVFVu0cnDdvXs4///zs\nt99+GTx4cI499tg888wz66FiiqbaOTh9+vT8y7/8SwYNGpTBgwfn9NNPz6xZs9ZDxRTZBRdckOOP\nP75N++pLAAAAiqtULpfL73cRH2R/+9vf8vnPfz4rVqzICSeckBUrVmT8+PHp06dPbr/99nTp0mWd\nHgfNVTuXHn/88Zxwwgnp169fjjzyyNTX12fChAl54403MmHChAwcOHA9j4QPsnXxM62+vj4jR47M\n9OnT8+Uvfzlnnnnmeqicoqh2Di5evDgjR47MW2+9lRNPPDE9evTIrbfemjlz5uSOO+5Iv3791vNI\n+KCqdg7Onj07I0aMSG1tbUaNGpVyuZwf//jHSZI777wzW2655focBgVx++2354ILLsjQoUNz8803\nr3FffQkAAECx6era6YYbbsibb76Zu+++O3379k2SfOQjH8moUaMyceLEHHXUUev0OGiu2rn0rW99\nK1tvvXXuuOOO1NTUJEmOOOKIHHroobn88stz/fXXr7cx8MG3Ln6mXXPNNXnxxRc7ulQKqto5eO21\n1+aVV17JLbfcksGDBydJPv3pT+cTn/hExo8fn0suuWS9jYEPtmrn4E033ZQlS5bktttuS//+/ZMk\n++yzT4466qjceOONOffcc9fbGPjgW7lyZa666qpceeWVKZVKbTpGXwIAAFBsHg3aTvfcc0+GDh3a\n2DQnybBhw9K3b9/cc8896/w4aK6aubRgwYLMnDkzhx56aGMImCSbb755hgwZkqeffrrD66ZY2vsz\nbcaMGbnmmmvy5S9/OW5UpxrVzsFf/vKXOeCAAxpDwCTZYostMnr06Oy9994dWjPFUu0cnDVrVjbd\ndNPGEDBJBg4cmE022SQzZ87s0Joplrq6uowYMSJXXnllRowYkV69erXpOH0JAABAsQkC22HBggWZ\nPXt2dttttxbbBgwYkD/96U/r9Dhortq51K1bt9x777054YQTWmybP3++R0BRkfb+TKuvr895552X\nj370ozn88MM7qkwKrNo5+Nprr+WNN97Ivvvu2/jZkiVLkiRHH320u2Bos/b8HNxqq63yzjvvZP78\n+Y2f/e1vf8vChQvbHORAkixfvjxLlizJ5ZdfnrFjx6Zz585rPUZfAgAAUHyCwHZ44403krz3FzjN\n9erVKwsXLsyiRYvW2XHQXLVzqVOnTtluu+1avHdo+vTpefrpp7PXXnt1TMEUUnt/pl177bWZPXt2\nLr744g6rkWKrdg6+8sorKZVK2WyzzXLJJZdk7733zl577ZWDDz44kyZN6vC6KY72/Bw87rjjUlNT\nk69+9auZMWNGZsyYka9+9aupqanJ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"text/plain": [ - "<matplotlib.figure.Figure at 0x13466ad30>" + "{'ax': <AxesSubplot:>,\n", + " 'color': None,\n", + " 'cv': None,\n", + " 'estimator': GaussianNB(),\n", + " 'scoring': None,\n", + " 'priors': None,\n", + " 'var_smoothing': 1e-09}" ] }, + "execution_count": 16, "metadata": {}, + "output_type": "execute_result" + }, + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXkAAAD7CAYAAACPDORaAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8qNh9FAAAACXBIWXMAAAsTAAALEwEAmpwYAAANt0lEQVR4nO3cf4ichZnA8W82a3ahTbRF6EnhaAv1QVi0sLYmXqxXqJ6RCqH4R7FQLpCqtHC9puBFDrQFr+WwuZb+IaVX5OC4o3iUoL2WSKEc1WhoGEtxsT5hBYsULW3RREudmN3cHzPLjGF3fmVnZn36/YCQd97Z2YfH5JvX2Xnddv78eSRJNc1MewBJ0vgYeUkqzMhLUmFGXpIKM/KSVJiRl6TCBop8RFwXEf+3zuO3RcTJiHg6Ij6/6dNJki5K38hHxD3A94H5Cx6/BPgWcDNwI3BnRLxvHENKkkYzO8BzXgA+DfznBY9fBSxn5qsAEfEk8HHgfzZ6oUajMQd8FHgZWBllYEn6C7QduAI4ubi42BzmC/tGPjN/GBEfWOfULuB01/HrwKV9Xu6jwBMDTydJ6nYD8OQwXzDIlfxGzgA7u453Aq/1+ZqXAa688kp27NhxEd+6hqWlJRYWFqY9xpbgLjrcRYe7aDl79iynTp2CdkOHcTGR/zXw4Yh4L/AGrbdqvtnna1YAduzYwdzc3EV86zrcQ4e76HAXHe7ibYZ+m3voyEfEHcC7M/N7EXEIeJzWD3AfzszfDvt6kqTxGSjymfkisLv96//uevxHwI/GMpkk6aJ5M5QkFWbkJakwIy9JhRl5SSrMyEtSYUZekgoz8pJUmJGXpMKMvCQVZuQlqTAjL0mFGXlJKszIS1JhR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HjlwDforWHG4E7I+J9/V5vnJF/252ywLp3ymbmaWDtTtmKeu3hJeCWzFxpX6VdArw5+REnptcuiIjbaV2tHZv8aBPXaxfX0/qo8pGIeAL4XWb+fvIjTkyvXfwJ+A3wrvY/qxOfbvJeAD69zuNX0fpU46uZeZbWx9E/3u/Fxhn5de+U3eBcvztl38k23ENmvpWZf4iIbRHxTeCXmVn5duANdxERC7T+k/y+aQw2Bb3+fFwOfAL4J2Af8I8RceWE55ukXruA1sXQc8AzwHcmOdg0tD+G/tY6p0bq5jgjv5l3yr6T9doD7RvJ/qv9nC9MeLZJ67WLzwHvB34G/D1wKCJumex4E9VrF38ETmbmK5n5BvBz4CMTnm+Seu1iH607PT8I/DWwPyI+NuH5toqRujnOyB+nddMUG9wpe0NEzEfEpfS5U/YdbsM9RMQ24FHgV5l5V2ZW/189bLiLzLwnM69r/6DpP4B/y8zKb9v0+vPxDLAQEZe3r2h307qSrarXLl4F/gw0M/NNWlG7bMLzbRW/Bj4cEe+NiB203qp5ut8Xje3TNcBR4KaIeIr2nbIRcYjOnbLfAZ6g9RfNP7f/BVa04R5o/f8obgTm2p+mALg3M/v+i3uH6vl7YrqjTVy/Px/3Ao+3n/tIZla9CIL+u/gkcCIiVmm9D/3TKc46cRFxB/DuzPxeey+P0+rmw5n5235f7x2vklSYN0NJUmFGXpIKM/KSVJiRl6TCjLwkFWbkJakwIy9JhRl5SSrs/wGJkN5Gxl0dUgAAAABJRU5ErkJggg==\n", + "text/plain": [ + "<Figure size 432x288 with 1 Axes>" + ] + }, + "metadata": { + "needs_background": "light" + }, "output_type": "display_data" } ], "source": [ - "logit_balance = ClassificationReport(LogisticRegression())\n", - "logit_balance.fit(docs_train, labels_train)\n", - "logit_balance.score(docs_test, labels_test)\n", - "logit_balance.show()" + "c.get_params()" ] }, { "cell_type": "code", - "execution_count": 28, - "metadata": { - "collapsed": false - }, + "execution_count": 17, + "id": "2be7cf21", + "metadata": {}, "outputs": [ { - "ename": "ValueError", - "evalue": "Data is not binary and pos_label is not specified", - "output_type": "error", - "traceback": [ - "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", - "\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)", - "\u001b[0;32m<ipython-input-28-5eccb2a02e03>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mlogit_balance\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mROCAUC\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mlogit\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mlogit_balance\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mscore\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdocs_test\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mlabels_test\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 3\u001b[0m \u001b[0mlogit_balance\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mshow\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;32m/Users/benjamin/Repos/tmp/yellowbrick/yellowbrick/classifier.py\u001b[0m in \u001b[0;36mscore\u001b[0;34m(self, X, y, **kwargs)\u001b[0m\n\u001b[1;32m 311\u001b[0m \"\"\"\n\u001b[1;32m 312\u001b[0m \u001b[0my_pred\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpredict\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mX\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 313\u001b[0;31m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mfpr\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mtpr\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mthresholds\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mroc_curve\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0my\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0my_pred\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 314\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mroc_auc\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mauc\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mfpr\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mtpr\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 315\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mdraw\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0my\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0my_pred\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;32m/usr/local/lib/python3.5/site-packages/sklearn/metrics/ranking.py\u001b[0m in \u001b[0;36mroc_curve\u001b[0;34m(y_true, y_score, pos_label, sample_weight, drop_intermediate)\u001b[0m\n\u001b[1;32m 503\u001b[0m \"\"\"\n\u001b[1;32m 504\u001b[0m fps, tps, thresholds = _binary_clf_curve(\n\u001b[0;32m--> 505\u001b[0;31m y_true, y_score, pos_label=pos_label, sample_weight=sample_weight)\n\u001b[0m\u001b[1;32m 506\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 507\u001b[0m \u001b[0;31m# Attempt to drop thresholds corresponding to points in between and\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;32m/usr/local/lib/python3.5/site-packages/sklearn/metrics/ranking.py\u001b[0m in \u001b[0;36m_binary_clf_curve\u001b[0;34m(y_true, y_score, pos_label, sample_weight)\u001b[0m\n\u001b[1;32m 312\u001b[0m \u001b[0marray_equal\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mclasses\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mor\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 313\u001b[0m array_equal(classes, [1]))):\n\u001b[0;32m--> 314\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mValueError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Data is not binary and pos_label is not specified\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 315\u001b[0m \u001b[0;32melif\u001b[0m \u001b[0mpos_label\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 316\u001b[0m \u001b[0mpos_label\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m1.\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;31mValueError\u001b[0m: Data is not binary and pos_label is not specified" - ] + "data": { + "text/html": [ + "<style>#sk-container-id-5 {color: black;background-color: white;}#sk-container-id-5 pre{padding: 0;}#sk-container-id-5 div.sk-toggleable {background-color: white;}#sk-container-id-5 label.sk-toggleable__label {cursor: pointer;display: block;width: 100%;margin-bottom: 0;padding: 0.3em;box-sizing: border-box;text-align: center;}#sk-container-id-5 label.sk-toggleable__label-arrow:before {content: \"▸\";float: left;margin-right: 0.25em;color: #696969;}#sk-container-id-5 label.sk-toggleable__label-arrow:hover:before {color: black;}#sk-container-id-5 div.sk-estimator:hover label.sk-toggleable__label-arrow:before {color: black;}#sk-container-id-5 div.sk-toggleable__content {max-height: 0;max-width: 0;overflow: hidden;text-align: left;background-color: #f0f8ff;}#sk-container-id-5 div.sk-toggleable__content pre {margin: 0.2em;color: black;border-radius: 0.25em;background-color: #f0f8ff;}#sk-container-id-5 input.sk-toggleable__control:checked~div.sk-toggleable__content {max-height: 200px;max-width: 100%;overflow: auto;}#sk-container-id-5 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {content: \"▾\";}#sk-container-id-5 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-5 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-5 input.sk-hidden--visually {border: 0;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);height: 1px;margin: -1px;overflow: hidden;padding: 0;position: absolute;width: 1px;}#sk-container-id-5 div.sk-estimator {font-family: monospace;background-color: #f0f8ff;border: 1px dotted black;border-radius: 0.25em;box-sizing: border-box;margin-bottom: 0.5em;}#sk-container-id-5 div.sk-estimator:hover {background-color: #d4ebff;}#sk-container-id-5 div.sk-parallel-item::after {content: \"\";width: 100%;border-bottom: 1px solid gray;flex-grow: 1;}#sk-container-id-5 div.sk-label:hover label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-5 div.sk-serial::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: 0;}#sk-container-id-5 div.sk-serial {display: flex;flex-direction: column;align-items: center;background-color: white;padding-right: 0.2em;padding-left: 0.2em;position: relative;}#sk-container-id-5 div.sk-item {position: relative;z-index: 1;}#sk-container-id-5 div.sk-parallel {display: flex;align-items: stretch;justify-content: center;background-color: white;position: relative;}#sk-container-id-5 div.sk-item::before, #sk-container-id-5 div.sk-parallel-item::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: -1;}#sk-container-id-5 div.sk-parallel-item {display: flex;flex-direction: column;z-index: 1;position: relative;background-color: white;}#sk-container-id-5 div.sk-parallel-item:first-child::after {align-self: flex-end;width: 50%;}#sk-container-id-5 div.sk-parallel-item:last-child::after {align-self: flex-start;width: 50%;}#sk-container-id-5 div.sk-parallel-item:only-child::after {width: 0;}#sk-container-id-5 div.sk-dashed-wrapped {border: 1px dashed gray;margin: 0 0.4em 0.5em 0.4em;box-sizing: border-box;padding-bottom: 0.4em;background-color: white;}#sk-container-id-5 div.sk-label label {font-family: monospace;font-weight: bold;display: inline-block;line-height: 1.2em;}#sk-container-id-5 div.sk-label-container {text-align: center;}#sk-container-id-5 div.sk-container {/* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */display: inline-block !important;position: relative;}#sk-container-id-5 div.sk-text-repr-fallback {display: none;}</style><div id=\"sk-container-id-5\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>CVScores(ax=&lt;AxesSubplot:&gt;, estimator=GaussianNB())</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item sk-dashed-wrapped\"><div class=\"sk-label-container\"><div class=\"sk-label sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-13\" type=\"checkbox\" ><label for=\"sk-estimator-id-13\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">CVScores</label><div class=\"sk-toggleable__content\"><pre>CVScores(ax=&lt;AxesSubplot:&gt;, estimator=GaussianNB())</pre></div></div></div><div class=\"sk-parallel\"><div class=\"sk-parallel-item\"><div class=\"sk-item\"><div class=\"sk-label-container\"><div class=\"sk-label sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-14\" type=\"checkbox\" ><label for=\"sk-estimator-id-14\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">estimator: GaussianNB</label><div class=\"sk-toggleable__content\"><pre>GaussianNB()</pre></div></div></div><div class=\"sk-serial\"><div class=\"sk-item\"><div class=\"sk-estimator sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-15\" type=\"checkbox\" ><label for=\"sk-estimator-id-15\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">GaussianNB</label><div class=\"sk-toggleable__content\"><pre>GaussianNB()</pre></div></div></div></div></div></div></div></div></div></div>" + ], + "text/plain": [ + "CVScores(ax=<AxesSubplot:>, estimator=GaussianNB())" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" } ], "source": [ - "logit_balance = ROCAUC(logit)\n", - "logit_balance.score(docs_test, labels_test)\n", - "logit_balance.show()" + "c" ] } ], "metadata": { "kernelspec": { - "display_name": "Python 3", + "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, @@ -558,9 +405,9 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.5.2" + "version": "3.10.2" } }, "nbformat": 4, - "nbformat_minor": 0 + "nbformat_minor": 5 } diff --git a/tests/test_cluster/test_elbow.py b/tests/test_cluster/test_elbow.py --- a/tests/test_cluster/test_elbow.py +++ b/tests/test_cluster/test_elbow.py @@ -205,12 +205,16 @@ def test_invalid_k(self): """ Assert that invalid values of K raise exceptions """ + # Generate a blobs data set + X, y = make_blobs( + n_samples=1000, n_features=12, centers=6, shuffle=True, random_state=42 + ) with pytest.raises(YellowbrickValueError): - KElbowVisualizer(KMeans(), k=(1, 2, 3, "foo", 5)) + KElbowVisualizer(KMeans(), k=(1, 2, 3, "foo", 5)).fit(X) with pytest.raises(YellowbrickValueError): - KElbowVisualizer(KMeans(), k="foo") + KElbowVisualizer(KMeans(), k="foo").fit(X) def test_valid_k(self): """ @@ -220,16 +224,21 @@ def test_valid_k(self): # if k is a tuple of 2 ints, k_values = range(k[0], k[1]) # if k is an iterable, k_values_ = list(k) - visualizer = KElbowVisualizer(KMeans(), k=8) + # Generate a blobs data set + X, y = make_blobs( + n_samples=1000, n_features=12, centers=6, shuffle=True, random_state=42 + ) + + visualizer = KElbowVisualizer(KMeans(), k=8).fit(X) assert visualizer.k_values_ == list(np.arange(2, 8 + 1)) - visualizer = KElbowVisualizer(KMeans(), k=(4, 12)) + visualizer = KElbowVisualizer(KMeans(), k=(4, 12)).fit(X) assert visualizer.k_values_ == list(np.arange(4, 12)) - visualizer = KElbowVisualizer(KMeans(), k=np.arange(10, 100, 10)) + visualizer = KElbowVisualizer(KMeans(), k=np.arange(10, 100, 10)).fit(X) assert visualizer.k_values_ == list(np.arange(10, 100, 10)) - visualizer = KElbowVisualizer(KMeans(), k=[10, 20, 30, 40, 50, 60, 70, 80, 90]) + visualizer = KElbowVisualizer(KMeans(), k=[10, 20, 30, 40, 50, 60, 70, 80, 90]).fit(X) assert visualizer.k_values_ == list(np.arange(10, 100, 10)) @pytest.mark.xfail(sys.platform == "win32", reason="images not close on windows") @@ -491,4 +500,14 @@ def test_set_colors_manually(self): # Execute drawing oz.draw() oz.finalize() - self.assert_images_similar(oz, tol=3.2) \ No newline at end of file + self.assert_images_similar(oz, tol=3.2) + + def test_get_params(self): + """ + Ensure the get params works for sklearn-compatibility + """ + oz = KElbowVisualizer( + KMeans(random_state=0), k=5, + ) + params = oz.get_params() + assert len(params) > 0 \ No newline at end of file diff --git a/tests/test_model_selection/test_dropping_curve.py b/tests/test_model_selection/test_dropping_curve.py --- a/tests/test_model_selection/test_dropping_curve.py +++ b/tests/test_model_selection/test_dropping_curve.py @@ -188,4 +188,12 @@ def test_bad_train_sizes(self): Test learning curve with bad input for feature size. """ with pytest.raises(YellowbrickValueError): - DroppingCurve(SVC(), param_name="gamma", feature_sizes=100) \ No newline at end of file + DroppingCurve(SVC(), param_name="gamma", feature_sizes=100) + + def test_get_params(self): + """ + Ensure dropping curve get params works correctly + """ + oz = DroppingCurve(MultinomialNB()) + params = oz.get_params() + assert len(params) > 0 \ No newline at end of file diff --git a/tests/test_utils/test_wrapper.py b/tests/test_utils/test_wrapper.py --- a/tests/test_utils/test_wrapper.py +++ b/tests/test_utils/test_wrapper.py @@ -17,10 +17,13 @@ ## Imports ########################################################################## +import pytest + from unittest import mock from yellowbrick.base import Visualizer from yellowbrick.utils.wrapper import * +from yellowbrick.exceptions import YellowbrickAttributeError, YellowbrickTypeError from sklearn.naive_bayes import MultinomialNB from sklearn.naive_bayes import GaussianNB @@ -133,3 +136,21 @@ def test_rewrap_object(self): obj.predict() old.predict.assert_called_once() new.predict.assert_called_once() + + def test_wrapper_recursion(self): + """ + Ensure wrapper recursion isn't possible + """ + obj = Wrapper("") + obj._wrapped = obj + with pytest.raises(YellowbrickTypeError): + obj.foo + + def test_attribute_error(self): + """ + Attribute errors should return a YellowbrickAttributeError + """ + obj = WrappedEstimator() + pat = r"neither visualizer 'WrappedEstimator' nor wrapped estimator 'MagicMock' have attribute 'notaproperty'" + with pytest.raises(YellowbrickAttributeError, match=pat): + obj.notaproperty \ No newline at end of file
KElbowVisualizer wrapping functionality does not work with notebook rendering of estimator **Describe the bug** In Jupyter Notebook, this code produces this error: ``` AttributeError: 'KMeans' object has no attribute 'k' ``` **To Reproduce** ```python from sklearn.cluster import KMeans from yellowbrick.cluster import KElbowVisualizer visualizer = KElbowVisualizer(KMeans(), k=(2,12)) visualizer ``` **Additional context** The use case above is just an example. The bug shows in other complex use cases.
@lwgray I was able to reproduce this error on: Python: 3.10.2 Yellowbrick: develop branch Dependencies: ``` matplotlib==3.5.2 scipy==1.8.1 scikit-learn==1.1.1 numpy==1.22.4 cycler==0.11.0 ``` Taking a look at it now. @vtphan @lwgray this appears to be related to the new scikit-learn print functionality that attempts to render Estimators using matplotlib with interactive dropdowns, e.g. ![Screen Shot 2022-05-21 at 11 47 56](https://user-images.githubusercontent.com/745966/169661382-26515ce2-cc05-47c6-8d7e-893518d04872.png) Because the last line of the cell is `visualizer` the notebook is trying to render it as output and because the visualizer extends `Estimator` it goes through the scikit-learn pretty drawing functionality. @vtphan this bug does not affect the behavior of the visualizer; you can still fit and show the visual image, but I can see how it can be annoying, so it's something we'll want to try to deal with. It looks like this might be a subclassing issue; `ModelVisualizer` renders just fine: ![Screen Shot 2022-05-21 at 12 28 49](https://user-images.githubusercontent.com/745966/169662741-c215f709-3146-40d3-8eed-3f7fe88defe3.png) Turns out this is specifically a problem with `KElbowVisualizer` -- PR fix coming.
2022-05-21T18:19:27
DistrictDataLabs/yellowbrick
1,265
DistrictDataLabs__yellowbrick-1265
[ "1236" ]
1bf4c2f3f18ae54ce87beb79d0dde1ef6abcad4f
diff --git a/yellowbrick/utils/kneed.py b/yellowbrick/utils/kneed.py --- a/yellowbrick/utils/kneed.py +++ b/yellowbrick/utils/kneed.py @@ -59,7 +59,8 @@ class KneeLocator(object): A list of k values representing the no. of clusters in KMeans Clustering algorithm. y : list - A list of silhouette score corresponding to each value of k. + A list of k scores corresponding to each value of k. The type of k scores are determined + by the metric parameter from the KElbowVisualizer class. S : float, default: 1.0 Sensitivity parameter that allows us to adjust how aggressive we want KneeLocator to
Add description of parameter to docstring @Haebuk had opened a PR to deal with this but closed it https://github.com/DistrictDataLabs/yellowbrick/pull/1233 We just need to add this line below to the KneeLocator docstring for `y` located in yellowbrick/utils/kneed.py "A list of k scores corresponding to each value of k. The type of k scores are determined by the metric parameter from the KElbowVisualizer class. " https://github.com/DistrictDataLabs/yellowbrick/blob/092c0ca25187b3cde9f608a1f7bc6d8c2b998f96/yellowbrick/utils/kneed.py#L61-L62 ``` class KneeLocator(object): """ Finds the "elbow" or "knee" which is a value corresponding to the point of maximum curvature in an elbow curve, using knee point detection algorithm. This point is accessible via the `knee` attribute. Parameters ---------- x : list A list of k values representing the no. of clusters in KMeans Clustering algorithm. y : list A list of k scores corresponding to each value of k. The type of k scores are determined by the metric parameter from the KElbowVisualizer class. S : float, default: 1.0 Sensitivity parameter that allows us to adjust how aggressive we want KneeLocator to be when detecting "knees" or "elbows". curve_nature : string, default: 'concave' A string that determines the nature of the elbow curve in which "knee" or "elbow" is to be found. curve_direction : string, default: 'increasing' A string that determines tha increasing or decreasing nature of the elbow curve in which "knee" or "elbow" is to be found. online : bool, default: False kneed will correct old knee points if True, will return first knee if False Notes ----- The KneeLocator is implemented using the "knee point detection algorithm" which can be read at `<https://www1.icsi.berkeley.edu/~barath/papers/kneedle-simplex11.pdf>` ```
@lwgray Can I please submit a PR on this ? Sure, make sure it is on the development branch. And thanks for using yellowbrick
2022-06-24T13:38:20
DistrictDataLabs/yellowbrick
1,294
DistrictDataLabs__yellowbrick-1294
[ "1182" ]
7a3c94c76851c0e486e8198cfe1c71e742d7ee61
diff --git a/yellowbrick/cluster/silhouette.py b/yellowbrick/cluster/silhouette.py --- a/yellowbrick/cluster/silhouette.py +++ b/yellowbrick/cluster/silhouette.py @@ -23,6 +23,35 @@ from sklearn.metrics import silhouette_score, silhouette_samples +try: + from sklearn.metrics.pairwise import _VALID_METRICS +except ImportError: + _VALID_METRICS = [ + "cityblock", + "cosine", + "euclidean", + "l1", + "l2", + "manhattan", + "braycurtis", + "canberra", + "chebyshev", + "correlation", + "dice", + "hamming", + "jaccard", + "kulsinski", + "mahalanobis", + "minkowski", + "rogerstanimoto", + "russellrao", + "seuclidean", + "sokalmichener", + "sokalsneath", + "sqeuclidean", + "yule", + ] + from yellowbrick.utils import check_fitted from yellowbrick.style import resolve_colors from yellowbrick.cluster.base import ClusteringScoreVisualizer @@ -113,7 +142,6 @@ class SilhouetteVisualizer(ClusteringScoreVisualizer): """ def __init__(self, estimator, ax=None, colors=None, is_fitted="auto", **kwargs): - # Initialize the visualizer bases super(SilhouetteVisualizer, self).__init__( estimator, ax=ax, is_fitted=is_fitted, **kwargs @@ -130,23 +158,47 @@ def __init__(self, estimator, ax=None, colors=None, is_fitted="auto", **kwargs): def fit(self, X, y=None, **kwargs): """ Fits the model and generates the silhouette visualization. + + Unlike other visualizers that use the score() method to draw the results, this + visualizer errs on visualizing on fit since this is when the clusters are + computed. This means that a predict call is required in fit (or a fit_predict) + in order to produce the visualization. """ - # TODO: decide to use this method or the score method to draw. - # NOTE: Probably this would be better in score, but the standard score - # is a little different and I'm not sure how it's used. + # If the estimator is not fitted, fit it; then call predict to get the labels + # for computing the silhoutte score on. If the estimator is already fitted, then + # attempt to predict the labels, but if the estimator is stateless, fit and + # predict on the data specified. At the end of this block, no matter the fitted + # state of the estimator and the method, we should have cluster labels for X. if not check_fitted(self.estimator, is_fitted_by=self.is_fitted): - # Fit the wrapped estimator - self.estimator.fit(X, y, **kwargs) + if hasattr(self.estimator, "fit_predict"): + labels = self.estimator.fit_predict(X, y, **kwargs) + else: + self.estimator.fit(X, y, **kwargs) + labels = self.estimator.predict(X) + else: + if hasattr(self.estimator, "predict"): + labels = self.estimator.predict(X) + else: + labels = self.estimator.fit_predict(X, y, **kwargs) # Get the properties of the dataset self.n_samples_ = X.shape[0] - self.n_clusters_ = self.estimator.n_clusters + + # Compute the number of available clusters from the estimator + if hasattr(self.estimator, "n_clusters"): + self.n_clusters_ = self.estimator.n_clusters + else: + unique_labels = set(labels) + n_noise_clusters = 1 if -1 in unique_labels else 0 + self.n_clusters_ = len(unique_labels) - n_noise_clusters + + # Identify the distance metric to use for silhouette scoring + metric = self._identify_silhouette_metric() # Compute the scores of the cluster - labels = self.estimator.predict(X) - self.silhouette_score_ = silhouette_score(X, labels) - self.silhouette_samples_ = silhouette_samples(X, labels) + self.silhouette_score_ = silhouette_score(X, labels, metric=metric) + self.silhouette_samples_ = silhouette_samples(X, labels, metric=metric) # Draw the silhouette figure self.draw(labels) @@ -185,7 +237,6 @@ def draw(self, labels): # For each cluster, plot the silhouette scores self.y_tick_pos_ = [] for idx in range(self.n_clusters_): - # Collect silhouette scores for samples in the current cluster . values = self.silhouette_samples_[labels == idx] values.sort() @@ -260,6 +311,26 @@ def finalize(self): # Show legend (Average Silhouette Score axis) self.ax.legend(loc="best") + def _identify_silhouette_metric(self): + """ + The Silhouette metric must be one of the distance options allowed by + metrics.pairwise.pairwise_distances or a callable. This method attempts to + discover a valid distance metric from the underlying estimator or returns + "euclidean" by default. + """ + if hasattr(self.estimator, "metric"): + if callable(self.estimator.metric): + return self.estimator.metric + + if self.estimator.metric in _VALID_METRICS: + return self.estimator.metric + + if hasattr(self.estimator, "affinity"): + if self.estimator.affinity in _VALID_METRICS: + return self.estimator.affinity + + return "euclidean" + ########################################################################## ## Quick Method
diff --git a/tests/baseline_images/test_cluster/test_silhouette/test_colormap_as_colors_silhouette.png b/tests/baseline_images/test_cluster/test_silhouette/test_colormap_as_colors_silhouette.png Binary files a/tests/baseline_images/test_cluster/test_silhouette/test_colormap_as_colors_silhouette.png and b/tests/baseline_images/test_cluster/test_silhouette/test_colormap_as_colors_silhouette.png differ diff --git a/tests/baseline_images/test_cluster/test_silhouette/test_colormap_silhouette.png b/tests/baseline_images/test_cluster/test_silhouette/test_colormap_silhouette.png Binary files a/tests/baseline_images/test_cluster/test_silhouette/test_colormap_silhouette.png and b/tests/baseline_images/test_cluster/test_silhouette/test_colormap_silhouette.png differ diff --git a/tests/baseline_images/test_cluster/test_silhouette/test_colors_silhouette.png b/tests/baseline_images/test_cluster/test_silhouette/test_colors_silhouette.png Binary files a/tests/baseline_images/test_cluster/test_silhouette/test_colors_silhouette.png and b/tests/baseline_images/test_cluster/test_silhouette/test_colors_silhouette.png differ diff --git a/tests/baseline_images/test_cluster/test_silhouette/test_integrated_kmeans_silhouette.png b/tests/baseline_images/test_cluster/test_silhouette/test_integrated_kmeans_silhouette.png Binary files a/tests/baseline_images/test_cluster/test_silhouette/test_integrated_kmeans_silhouette.png and b/tests/baseline_images/test_cluster/test_silhouette/test_integrated_kmeans_silhouette.png differ diff --git a/tests/baseline_images/test_cluster/test_silhouette/test_integrated_mini_batch_kmeans_silhouette.png b/tests/baseline_images/test_cluster/test_silhouette/test_integrated_mini_batch_kmeans_silhouette.png Binary files a/tests/baseline_images/test_cluster/test_silhouette/test_integrated_mini_batch_kmeans_silhouette.png and b/tests/baseline_images/test_cluster/test_silhouette/test_integrated_mini_batch_kmeans_silhouette.png differ diff --git a/tests/baseline_images/test_cluster/test_silhouette/test_quick_method.png b/tests/baseline_images/test_cluster/test_silhouette/test_quick_method.png Binary files a/tests/baseline_images/test_cluster/test_silhouette/test_quick_method.png and b/tests/baseline_images/test_cluster/test_silhouette/test_quick_method.png differ diff --git a/tests/test_cluster/test_silhouette.py b/tests/test_cluster/test_silhouette.py --- a/tests/test_cluster/test_silhouette.py +++ b/tests/test_cluster/test_silhouette.py @@ -20,14 +20,15 @@ import sys import pytest import matplotlib.pyplot as plt +import numpy as np from sklearn.datasets import make_blobs from sklearn.cluster import KMeans, MiniBatchKMeans +from sklearn.cluster import SpectralClustering, AgglomerativeClustering from unittest import mock from tests.base import VisualTestCase -from yellowbrick.datasets import load_nfl from yellowbrick.cluster.silhouette import SilhouetteVisualizer, silhouette_visualizer @@ -53,7 +54,6 @@ def test_integrated_kmeans_silhouette(self): n_samples=1000, n_features=12, centers=8, shuffle=False, random_state=0 ) - fig = plt.figure() ax = fig.add_subplot() @@ -62,7 +62,6 @@ def test_integrated_kmeans_silhouette(self): visualizer.finalize() self.assert_images_similar(visualizer, remove_legend=True) - @pytest.mark.xfail(sys.platform == "win32", reason="images not close on windows") def test_integrated_mini_batch_kmeans_silhouette(self): @@ -84,7 +83,6 @@ def test_integrated_mini_batch_kmeans_silhouette(self): visualizer.finalize() self.assert_images_similar(visualizer, remove_legend=True) - @pytest.mark.skip(reason="no negative silhouette example available yet") def test_negative_silhouette_score(self): @@ -103,7 +101,6 @@ def test_colormap_silhouette(self): n_samples=1000, n_features=12, centers=8, shuffle=False, random_state=0 ) - fig = plt.figure() ax = fig.add_subplot() @@ -138,7 +135,7 @@ def test_colors_silhouette(self): visualizer.finalize() self.assert_images_similar(visualizer, remove_legend=True) - + def test_colormap_as_colors_silhouette(self): """ Test no exceptions for modifying the colors in a silhouette visualizer @@ -162,7 +159,7 @@ def test_colormap_as_colors_silhouette(self): 3.2 if sys.platform == "win32" else 0.01 ) # Fails on AppVeyor with RMS 3.143 self.assert_images_similar(visualizer, remove_legend=True, tol=tol) - + def test_quick_method(self): """ Test the quick method producing a valid visualization @@ -177,29 +174,44 @@ def test_quick_method(self): self.assert_images_similar(oz) - @pytest.mark.xfail( - reason="""third test fails with AssertionError: Expected fit - to be called once. Called 0 times.""" - ) def test_with_fitted(self): """ Test that visualizer properly handles an already-fitted model """ - X, y = load_nfl(return_dataset=True).to_numpy() - - model = MiniBatchKMeans().fit(X, y) + X, y = make_blobs( + n_samples=100, n_features=5, centers=3, shuffle=False, random_state=112 + ) + model = MiniBatchKMeans().fit(X) + labels = model.predict(X) with mock.patch.object(model, "fit") as mockfit: oz = SilhouetteVisualizer(model) - oz.fit(X, y) + oz.fit(X) mockfit.assert_not_called() with mock.patch.object(model, "fit") as mockfit: oz = SilhouetteVisualizer(model, is_fitted=True) - oz.fit(X, y) + oz.fit(X) mockfit.assert_not_called() - with mock.patch.object(model, "fit") as mockfit: + with mock.patch.object(model, "fit_predict", return_value=labels) as mockfit: oz = SilhouetteVisualizer(model, is_fitted=False) - oz.fit(X, y) - mockfit.assert_called_once_with(X, y) + oz.fit(X) + mockfit.assert_called_once_with(X, None) + + @pytest.mark.parametrize( + "model", + [SpectralClustering, AgglomerativeClustering], + ) + def test_clusterer_without_predict(self, model): + """ + Assert that clustering estimators that don't implement + a predict() method utilize fit_predict() + """ + X = np.array([[1, 2], [1, 4], [1, 0], [4, 2], [4, 4], [4, 0]]) + try: + visualizer = SilhouetteVisualizer(model(n_clusters=2)) + visualizer.fit(X) + visualizer.finalize() + except AttributeError: + self.fail("could not use fit or fit_predict methods")
Add more estimators to Silhouette Visualizer At the moment Silhouette Visualizer can handle KMeans and MiniBatchKMeans. But as far as I know, the construction of silhouette plot isn't tied to centroid clustering in any way, but simply counts the score according to the specified metric. The only problem I can see here is that some algorithms, like OPTICS and DBSCAN, have a separate label for outliers. Maybe I could help with this, however I'm new on GitHub, so I might need some help :)
@gshigin it's a great idea and it would be great to see a PR for this! I came across the same problem, I think it might be as easy as replacing all self.estimator.n_clusters with len(np.unique(self.estimator.labels_)). Is anyone working on this? Otherwise I'd give it a try @rpauli You are more than welcome to submit a PR for this.
2023-01-19T00:53:13
DistrictDataLabs/yellowbrick
1,300
DistrictDataLabs__yellowbrick-1300
[ "1296" ]
5f12bc3f30b5189156b60f4eca82c46c38deec43
diff --git a/yellowbrick/cluster/elbow.py b/yellowbrick/cluster/elbow.py --- a/yellowbrick/cluster/elbow.py +++ b/yellowbrick/cluster/elbow.py @@ -24,9 +24,9 @@ import scipy.sparse as sp from collections.abc import Iterable -from sklearn.metrics import silhouette_score from sklearn.preprocessing import LabelEncoder from sklearn.metrics.pairwise import pairwise_distances +from sklearn.metrics import silhouette_score, DistanceMetric from yellowbrick.utils import KneeLocator, get_param_names from yellowbrick.style.palettes import LINE_COLOR @@ -44,13 +44,13 @@ # Custom colors; note that LINE_COLOR is imported above -TIMING_COLOR = 'C1' # Color of timing axis, tick, label, and line -METRIC_COLOR = 'C0' # Color of metric axis, tick, label, and line +TIMING_COLOR = "C1" # Color of timing axis, tick, label, and line +METRIC_COLOR = "C0" # Color of metric axis, tick, label, and line # Keys for the color dictionary CTIMING = "timing" CMETRIC = "metric" -CVLINE = "vline" +CVLINE = "vline" ########################################################################## @@ -112,7 +112,7 @@ def distortion_score(X, labels, metric="euclidean"): # Compute the square distances from the instances to the center distances = pairwise_distances(instances, center, metric=metric) - distances = distances ** 2 + distances = distances**2 # Add the sum of square distance to the distortion distortion += distances.sum() @@ -130,9 +130,6 @@ def distortion_score(X, labels, metric="euclidean"): "calinski_harabasz": chs, } -DISTANCE_METRICS = ['cityblock', 'cosine', 'euclidean', 'haversine', - 'l1', 'l2', 'manhattan', 'nan_euclidean', 'precomputed'] - class KElbowVisualizer(ClusteringScoreVisualizer): """ @@ -188,8 +185,8 @@ class KElbowVisualizer(ClusteringScoreVisualizer): distance_metric : str or callable, default='euclidean' The metric to use when calculating distance between instances in a feature array. If metric is a string, it must be one of the options allowed - by sklearn's metrics.pairwise.pairwise_distances. If X is the distance array itself, - use metric="precomputed". + by sklearn's metrics.pairwise.pairwise_distances. If X is the distance array + itself, use metric="precomputed". timings : bool, default: True Display the fitting time per k to evaluate the amount of time required @@ -259,7 +256,7 @@ def __init__( ax=None, k=10, metric="distortion", - distance_metric='euclidean', + distance_metric="euclidean", timings=True, locate_elbow=True, **kwargs @@ -273,11 +270,15 @@ def __init__( "use one of distortion, silhouette, or calinski_harabasz" ) - if distance_metric not in DISTANCE_METRICS: - raise YellowbrickValueError( - "'{} is not a defined distance metric " - "use one of the sklearn metric.pairwise.pairwise_distances" - ) + # Check to ensure the distance metric is valid + if not callable(distance_metric): + try: + DistanceMetric.get_metric(distance_metric) + except ValueError as e: + raise YellowbrickValueError( + "'{} is not a defined distance metric " + "use one of the sklearn metric.pairwise.pairwise_distances" + ) from e # Store the arguments self.k = k @@ -302,7 +303,7 @@ def fit(self, X, y=None, **kwargs): ``self.elbow_value`` and ``self.elbow_score`` respectively. This method finishes up by calling draw to create the plot. """ - # Convert K into a tuple argument if an integer + # Convert K into a tuple argument if an integer if isinstance(self.k, int): self.k_values_ = list(range(2, self.k + 1)) elif ( @@ -340,9 +341,12 @@ def fit(self, X, y=None, **kwargs): # Append the time and score to our plottable metrics self.k_timers_.append(time.time() - start) - if self.metric != 'calinski_harabasz': - self.k_scores_.append(self.scoring_metric(X, self.estimator.labels_, - metric=self.distance_metric)) + if self.metric != "calinski_harabasz": + self.k_scores_.append( + self.scoring_metric( + X, self.estimator.labels_, metric=self.distance_metric + ) + ) else: self.k_scores_.append(self.scoring_metric(X, self.estimator.labels_)) @@ -437,7 +441,6 @@ def finalize(self): self.axes[1].set_ylabel("fit time (seconds)", color=self.timing_color) self.axes[1].tick_params("y", colors=self.timing_color) - @property def metric_color(self): return self.colors[CMETRIC] @@ -462,6 +465,7 @@ def vline_color(self): def vline_color(self, val): self.colors[CVLINE] = val + # alias KElbow = KElbowVisualizer @@ -478,7 +482,7 @@ def kelbow_visualizer( ax=None, k=10, metric="distortion", - distance_metric='euclidean', + distance_metric="euclidean", timings=True, locate_elbow=True, show=True, @@ -521,8 +525,8 @@ def kelbow_visualizer( distance_metric : str or callable, default='euclidean' The metric to use when calculating distance between instances in a feature array. If metric is a string, it must be one of the options allowed - by sklearn's metrics.pairwise.pairwise_distances. If X is the distance array itself, - use metric="precomputed". + by sklearn's metrics.pairwise.pairwise_distances. If X is the distance array + itself, use metric="precomputed". timings : bool, default: True Display the fitting time per k to evaluate the amount of time required @@ -562,7 +566,7 @@ def kelbow_visualizer( ax=ax, k=k, metric=metric, - distance_metric='euclidean', + distance_metric="euclidean", timings=timings, locate_elbow=locate_elbow, **kwargs
diff --git a/tests/requirements.txt b/tests/requirements.txt --- a/tests/requirements.txt +++ b/tests/requirements.txt @@ -6,7 +6,7 @@ # Library Dependencies matplotlib==3.4.2 scipy==1.8.0 -scikit-learn==1.0.0 +scikit-learn==1.0.2 numpy==1.22.0 cycler==0.10.0
Let `KElbowVisualizer` use all the distance metrics supported by sklearn **Describe the solution you'd like** Is there a reason `KElbowVisualizer` can use only the distance metrics in `DISTANCE_METRICS`? The `distortion_score` relies on `sklearn.metrics.pairwise.pairwise_distances()`, that supports distance metrics not included in `DISTANCE_METRICS`. For the silhouette score `KElbowVisualizer` uses `sklearn.metrics.cluster._unsupervised.silhouette_score()`, that also supports metrics not included in `DISTANCE_METRICS`. I don't see a reason why there is this limitation.
@stergion it actually is supposed to use any callable that the user supplies; the docstring says: > distance_metric : str or callable, default='euclidean' > The metric to use when calculating distance between instances in a > feature array. If metric is a string, it must be one of the options allowed > by sklearn's metrics.pairwise.pairwise_distances. If X is the distance array itself, > use metric="precomputed". So I think we need to have the `DISTANCE_METRICS` check only happen if the input is a string. I'll open a quick PR for a fix shortly.
2023-02-25T18:51:24
DistrictDataLabs/yellowbrick
1,301
DistrictDataLabs__yellowbrick-1301
[ "1299" ]
da26d1ec33143ed9dd2fff51fde322e11702cd6f
diff --git a/yellowbrick/datasaurus.py b/yellowbrick/datasaurus.py --- a/yellowbrick/datasaurus.py +++ b/yellowbrick/datasaurus.py @@ -1218,7 +1218,7 @@ def datasaurus(): y = arr[1] # Draw the points in the scatter plot - ax.scatter(x, y, c=color) + ax.scatter(x, y, color=color) # Set the X and Y limits ax.set_xlim(0, 100)
Matplotlib warning about color usage in Datasaurus **Describe the bug** the datasaurus function used to demonstrate Anscombe's quartet is isssuiing the following warning WARNING:matplotlib.axes._axes:*c* argument looks like a single numeric RGB or RGBA sequence, which should be avoided as value-mapping will have precedence in case its length matches with *x* & *y*. Please use the *color* keyword-argument or provide a 2D array with a single row if you intend to specify the same RGB or RGBA value for all points. **To Reproduce** ```python from yellowbrick import datasaurus datasaurus() ``` **Dataset** **Expected behavior** Produce the image without warnings **Desktop (please complete the following information):** - OS: [e.g. macOS] Google Colab - Python Version [e.g. 2.7, 3.6, miniconda] 3.8.10 - Yellowbrick Version [e.g. 0.7] 1.5
2023-03-07T21:33:54
ansible-collections/community.aws
38
ansible-collections__community.aws-38
[ "37" ]
1a1be5f494bb3935084b33d9183a41b9e9389cff
diff --git a/plugins/modules/ec2_win_password.py b/plugins/modules/ec2_win_password.py --- a/plugins/modules/ec2_win_password.py +++ b/plugins/modules/ec2_win_password.py @@ -115,12 +115,12 @@ except ImportError: HAS_CRYPTOGRAPHY = False -from ansible.module_utils.basic import AnsibleModule +from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule from ansible_collections.amazon.aws.plugins.module_utils.ec2 import HAS_BOTO, ec2_argument_spec, ec2_connect from ansible.module_utils._text import to_bytes -def main(): +def setup_module_object(): argument_spec = ec2_argument_spec() argument_spec.update(dict( instance_id=dict(required=True), @@ -131,21 +131,21 @@ def main(): wait_timeout=dict(default=120, required=False, type='int'), ) ) - module = AnsibleModule(argument_spec=argument_spec) + module = AnsibleAWSModule(argument_spec=argument_spec) + return module - if not HAS_BOTO: - module.fail_json(msg='Boto required for this module.') - - if not HAS_CRYPTOGRAPHY: - module.fail_json(msg='cryptography package required for this module.') +def ec2_win_password(module): instance_id = module.params.get('instance_id') key_file = module.params.get('key_file') - key_data = module.params.get('key_data') if module.params.get('key_passphrase') is None: b_key_passphrase = None else: b_key_passphrase = to_bytes(module.params.get('key_passphrase'), errors='surrogate_or_strict') + if module.params.get('key_data') is None: + b_key_data = None + else: + b_key_data = to_bytes(module.params.get('key_data'), errors='surrogate_or_strict') wait = module.params.get('wait') wait_timeout = module.params.get('wait_timeout') @@ -169,7 +169,7 @@ def main(): if wait and datetime.datetime.now() >= end: module.fail_json(msg="wait for password timeout after %d seconds" % wait_timeout) - if key_file is not None and key_data is None: + if key_file is not None and b_key_data is None: try: with open(key_file, 'rb') as f: key = load_pem_private_key(f.read(), b_key_passphrase, default_backend()) @@ -179,9 +179,9 @@ def main(): except (ValueError, TypeError) as e: # Handle issues loading key module.fail_json(msg="unable to parse key file") - elif key_data is not None and key_file is None: + elif b_key_data is not None and key_file is None: try: - key = load_pem_private_key(key_data, b_key_passphrase, default_backend()) + key = load_pem_private_key(b_key_data, b_key_passphrase, default_backend()) except (ValueError, TypeError) as e: module.fail_json(msg="unable to parse key data") @@ -200,5 +200,17 @@ def main(): module.exit_json(win_password=decrypted, changed=True) +def main(): + module = setup_module_object() + + if not HAS_BOTO: + module.fail_json(msg='Boto required for this module.') + + if not HAS_CRYPTOGRAPHY: + module.fail_json(msg='cryptography package required for this module.') + + ec2_win_password(module) + + if __name__ == '__main__': main()
diff --git a/tests/unit/modules/fixtures/certs/ec2_win_password.pem b/tests/unit/modules/fixtures/certs/ec2_win_password.pem new file mode 100644 --- /dev/null +++ b/tests/unit/modules/fixtures/certs/ec2_win_password.pem @@ -0,0 +1,15 @@ +-----BEGIN RSA PRIVATE KEY----- +MIICXQIBAAKBgQDAt4WXUohebyTXAxEBkfCjuaKBgv5VgGwHeSWomB0IoKszlNHL +itadHg/vDi1gHSeRANw4KccpFAEIy4Oq3bMpI/rFrDdj/otp4wDcZKuIxq8OtU4b +KBXsSJD9vxAMZktaJ28gpv+mSjnmz+uC0QiuticKaO62pWPGdd6RjuylkwIDAQAB +AoGAUNSo069qQzGa4hQHLgFoTUOvRWMMChCzPu8xPGWQx+2b4SaqWBUDryLMzBfG +MGoKDmet9mCPiEs7o9S4hRI38m2dKBPHRjpFJDPrJmsKNyjk9yBrcJf6EysNEPbd +mYt7DxyUHVNQJpLOPXuMFSi/iloXTBRZ0dEzvhCp2nmX9wECQQD8+s89dwIm41QK +laqELxSVDtSkfLkBIYtw4xPEfuXufna7LHXnR6b9CELAD8L5ht5CiXHzVPpiuwz4 +AaIvK44tAkEAwwSHaT6AOeXKNnNLTM+UzFW4rKixsSMQVD/7OjU0/IabFOkE+uY/ +WTgLrp1OsqhhDRS/F/eN9uj0dXHXgBEavwJAImW77gCTg1QfpjzJbaW1J7tXgHIQ ++a1k91l445vZib8aR8L42RSuCPOpl9HM0f7bk7J6kvp3/Rqv3bzjH4TNlQJBAId1 +k+FEqqiMtsLPntRBs+ei+13i51pVMrhyoLyzzJRDo2EI4o6sdAAy79pgJhPu5UrC +yGGLcK667WLOqpOoTd0CQQC/4Bq12KCwk9VEWOzNV+kPFzTb85RuzwH5Tis+Fbp2 +CNc26WPeNwOvNxXgzAve4G4CaUNLnmATatr5BKjU8Xkr +-----END RSA PRIVATE KEY----- \ No newline at end of file diff --git a/tests/unit/modules/test_ec2_win_password.py b/tests/unit/modules/test_ec2_win_password.py new file mode 100644 --- /dev/null +++ b/tests/unit/modules/test_ec2_win_password.py @@ -0,0 +1,50 @@ +from __future__ import (absolute_import, division, print_function) + +__metaclass__ = type + +''' +Commands to encrypt a message that can be decrypted: +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives.serialization import load_pem_private_key +from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15 +import base64 + +path = '/path/to/rsa_public_key.pem' +with open(path, 'r') as f: + rsa_public_key_pem = to_text(f.read()) +load_pem_public_key(rsa_public_key_pem = , default_backend()) +base64_cipher = public_key.encrypt('Ansible_AWS_EC2_Win_Password', PKCS1v15()) +string_cipher = base64.b64encode(base64_cipher) +''' + +from ansible.module_utils._text import to_bytes, to_text +from ansible_collections.community.aws.plugins.modules.ec2_win_password import setup_module_object, ec2_win_password +from ansible_collections.community.aws.tests.unit.compat.mock import patch +from ansible_collections.community.aws.tests.unit.modules.utils import AnsibleExitJson, ModuleTestCase, set_module_args + +fixture_prefix = 'tests/unit/modules/fixtures/certs' + + +class TestEc2WinPasswordModule(ModuleTestCase): + @patch('ansible_collections.community.aws.plugins.modules.ec2_win_password.ec2_connect') + def test_decryption(self, mock_connect): + + path = fixture_prefix + '/ec2_win_password.pem' + with open(path, 'r') as f: + pem = to_text(f.read()) + + with self.assertRaises(AnsibleExitJson) as exec_info: + set_module_args({'instance_id': 'i-12345', + 'key_data': pem + }) + module = setup_module_object() + mock_connect().get_password_data.return_value = 'L2k1iFiu/TRrjGr6Rwco/T3C7xkWxUw4+YPYpGGOmP3KDdy3hT1' \ + '8RvdDJ2i0e+y7wUcH43DwbRYSlkSyALY/nzjSV9R5NChUyVs3W5' \ + '5oiVuyTKsk0lor8dFJ9z9unq14tScZHvyQ3Nx1ggOtS18S9Pk55q' \ + 'IaCXfx26ucH76VRho=' + ec2_win_password(module) + + self.assertEqual( + exec_info.exception.args[0]['win_password'], + to_bytes('Ansible_AWS_EC2_Win_Password'), + )
ec2_win_password fails for given key_data if module is executed with python3. It works with python2. ##### Avoiding duplicates At the time of writing there were 11 issues raised. None of them was referring to ec2_win_password ##### Affected Branches At the time of writing there is only 1 branch at all and it is affected by the issue. ##### SUMMARY ec2_win_password fails for given key_data if module is executed with python3. It works with python2. ##### ISSUE TYPE - Bug Report ("Code is not compatible with python3.") - Feature Report ("Please make modules python3 compatible.") ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> ec2_win_password ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ``` Ansible 2.9.5 ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> ##### STEPS TO REPRODUCE We have a pem file which is saved in a variable with linebreaks. If we have a task like this ```yaml - name: get admin pws for systems ec2_win_password: region: "{{ aws_region }}" aws_access_key: "{{ access_key }}" aws_secret_key: "{{ secret_key }}" security_token: "{{ security_token }}" instance_id: "{{ item }}" key_data: "{{ sshkeyplain }}" key_passphrase: "{{ passphrase }}" wait: yes no_log: true register: passwords loop: "{{ system_ids }}" ``` If you execute this module with python2 backend it works. If you execute this module with python3 backend it fails. ("unable to parse key data") ##### EXPECTED RESULTS I expect the key_data to be parsed correctly with python3 backend. ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> Error when executing "load_pem_private_key" in python3 plain. ```python key = load_pem_private_key(key_data, b_key_passphrase, default_backend()) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/var/lib/awx/venv/ansible/lib/python3.6/site-packages/cryptography/hazmat/primitives/serialization/base.py", line 16, in load_pem_private_key return backend.load_pem_private_key(data, password) File "/var/lib/awx/venv/ansible/lib/python3.6/site-packages/cryptography/hazmat/backends/openssl/backend.py", line 1089, in load_pem_private_key password, File "/var/lib/awx/venv/ansible/lib/python3.6/site-packages/cryptography/hazmat/backends/openssl/backend.py", line 1282, in _load_key mem_bio = self._bytes_to_bio(data) File "/var/lib/awx/venv/ansible/lib/python3.6/site-packages/cryptography/hazmat/backends/openssl/backend.py", line 473, in _bytes_to_bio data_ptr = self._ffi.from_buffer(data) TypeError: from_buffer() cannot return the address of a unicode object ``` ##### SOLUTION PROPOSAL Our tests showed that explicit encoding is compatible with python2 and python3. Please verify. ```python key = load_pem_private_key(key_data.encode("ascii"), b_key_passphrase, default_backend()) ```
2020-04-16T13:56:48
ansible-collections/community.aws
47
ansible-collections__community.aws-47
[ "40", "41" ]
63dac48d90b848be65f005e84ffd9df6fcbd2f13
diff --git a/plugins/modules/aws_s3_bucket_info.py b/plugins/modules/aws_s3_bucket_info.py --- a/plugins/modules/aws_s3_bucket_info.py +++ b/plugins/modules/aws_s3_bucket_info.py @@ -47,7 +47,7 @@ description: "List of buckets" returned: always sample: - - creation_date: 2017-07-06 15:05:12 +00:00 + - creation_date: '2017-07-06 15:05:12 +00:00' name: my_bucket type: list ''' diff --git a/plugins/modules/ec2_vpc_vpn.py b/plugins/modules/ec2_vpc_vpn.py --- a/plugins/modules/ec2_vpc_vpn.py +++ b/plugins/modules/ec2_vpc_vpn.py @@ -288,7 +288,7 @@ vgw_telemetry: [{ 'outside_ip_address': 'string', 'status': 'up', - 'last_status_change': datetime(2015, 1, 1), + 'last_status_change': 'datetime(2015, 1, 1)', 'status_message': 'string', 'accepted_route_count': 123 }]
Module docs of aws_s3_bucket_info contain something that is parsed as datetime by YAML parser ##### SUMMARY Module docs of `aws_s3_bucket_info` contain something that is parsed as datetime by YAML parser. (This triggered ansible/ansible#69031.) ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME aws_s3_bucket_info ##### ANSIBLE VERSION ```paste below 2.9 2.10 ``` Module return docs of ec2_vpc_vpn contain broken sample ##### SUMMARY The sample for the `vgw_telemetry` return value contains `datetime(2015, 1, 1)`: ```.yaml vgw_telemetry: type: list returned: I(state=present) description: The telemetry for the VPN tunnel. sample: vgw_telemetry: [{ 'outside_ip_address': 'string', 'status': 'up', 'last_status_change': datetime(2015, 1, 1), 'status_message': 'string', 'accepted_route_count': 123 }] ``` The inner dict parses as (list of items): ```.py [('outside_ip_address', 'string'), ('status', 'up'), ('last_status_change', 'datetime(2015'), (1, None), ('1)', None), ('status_message', 'string'), ('accepted_route_count', 123)] ``` When ansible-doc tries to serialize this as JSON, it crashes. Also, the docs are rendered incorrectly, see [here](https://docs.ansible.com/ansible/latest/modules/ec2_vpc_vpn_module.html#return-vgw_telemetry). (See also ansible/ansible#69031.) ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME vgw_telemetry ##### ANSIBLE VERSION ```paste below 2.9 2.10 ```
2020-04-22T20:31:06
ansible-collections/community.aws
74
ansible-collections__community.aws-74
[ "49" ]
d542bbb88bc2e5e71279c2051dab76265c88b46a
diff --git a/plugins/modules/elb_target_group.py b/plugins/modules/elb_target_group.py --- a/plugins/modules/elb_target_group.py +++ b/plugins/modules/elb_target_group.py @@ -107,8 +107,8 @@ type: int stickiness_type: description: - - The type of sticky sessions. The possible value is lb_cookie. - default: lb_cookie + - The type of sticky sessions. + - If not set AWS will default to C(lb_cookie) for Application Load Balancers or C(source_ip) for Network Load Balancers. type: str successful_response_codes: description: @@ -547,7 +547,7 @@ def create_or_update_target_group(connection, module): # Only need to check response code and path for http(s) health checks if tg['HealthCheckProtocol'] in ['HTTP', 'HTTPS']: # Health check path - if 'HealthCheckPath'in params and tg['HealthCheckPath'] != params['HealthCheckPath']: + if 'HealthCheckPath' in params and tg['HealthCheckPath'] != params['HealthCheckPath']: health_check_params['HealthCheckPath'] = params['HealthCheckPath'] # Matcher (successful response codes) @@ -744,8 +744,8 @@ def create_or_update_target_group(connection, module): if stickiness_lb_cookie_duration is not None: if str(stickiness_lb_cookie_duration) != current_tg_attributes['stickiness_lb_cookie_duration_seconds']: update_attributes.append({'Key': 'stickiness.lb_cookie.duration_seconds', 'Value': str(stickiness_lb_cookie_duration)}) - if stickiness_type is not None and "stickiness_type" in current_tg_attributes: - if stickiness_type != current_tg_attributes['stickiness_type']: + if stickiness_type is not None: + if stickiness_type != current_tg_attributes.get('stickiness_type'): update_attributes.append({'Key': 'stickiness.type', 'Value': stickiness_type}) if update_attributes: @@ -825,7 +825,7 @@ def main(): protocol=dict(choices=protocols_list), purge_tags=dict(default=True, type='bool'), stickiness_enabled=dict(type='bool'), - stickiness_type=dict(default='lb_cookie'), + stickiness_type=dict(), stickiness_lb_cookie_duration=dict(type='int'), state=dict(required=True, choices=['present', 'absent']), successful_response_codes=dict(),
elb_target_group stickiness_type default no longer works on TCP target groups <!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY This issue was first reported in https://github.com/ansible/ansible/issues/67993 (it was closed by the author because they found a workaround). The default value of `lb_cookie` for `stickiness_type` is no longer ignored by AWS for TCP target groups, which is causing this module to fail when not explicitly specifying a stickiness type (even when stickiness is off/not set). It looks like Amazon is changing their API and rolling it out slowly as the linked issue starts on Mar 4, and seems to be hitting people little by little. It showed up today at different times for us on different target groups across some of our accounts. --- The default should either be left out in the call to AWS so that it chooses its own default (if that's possible), or this module should choose a default based on the protocol of the target group. The current workaround I'm using is a conditional in jinja, something like: ```yaml - elb_target_group: protocol: "{{ proto }}" stickiness_type: "{{ 'source_ip' if proto == 'tcp' else omit }}" ``` ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> elb_target_group ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below 2.9.6 ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> <!--- Paste example playbooks or commands between quotes below --> ```yaml #pseudo - elb_target_group: name: test protocol: tcp ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> Success ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> <!--- Paste verbatim command output between quotes --> ```paste below TASK [immutable_server : target group for analytics-tst-plebos loadbalancer] *** 17:21:08 An exception occurred during task execution. To see the full traceback, use -vvv. The error was: InvalidConfigurationRequestException: An error occurred (InvalidConfigurationRequest) when calling the ModifyTargetGroupAttributes operation: Stickiness type 'lb_cookie' is not supported for target groups with the TCP protocol 17:21:08 fatal: [localhost]: FAILED! => {"changed": false, "error": {"code": "InvalidConfigurationRequest", "message": "Stickiness type 'lb_cookie' is not supported for target groups with the TCP protocol", "type": "Sender"}, "msg": "An error occurred (InvalidConfigurationRequest) when calling the ModifyTargetGroupAttributes operation: Stickiness type 'lb_cookie' is not supported for target groups with the TCP protocol", "response_metadata": {"http_headers": {"connection": "close", "content-length": "359", "content-type": "text/xml", "date": "Tue, 03 Mar 2020 11:51:08 GMT", "x-amzn-requestid": "23b0ca87-e0fb-4b84-b93b-ae5b1363df53"}, "http_status_code": 400, "request_id": "23b0ca87-e0fb-4b84-b93b-ae5b1363df53", "retry_attempts": 0}} ```
2020-05-14T19:59:21
ansible-collections/community.aws
80
ansible-collections__community.aws-80
[ "79" ]
05672a64e2362cc2d865b5af6a57da6bc3cd08e3
diff --git a/plugins/modules/cloudwatchlogs_log_group_metric_filter.py b/plugins/modules/cloudwatchlogs_log_group_metric_filter.py --- a/plugins/modules/cloudwatchlogs_log_group_metric_filter.py +++ b/plugins/modules/cloudwatchlogs_log_group_metric_filter.py @@ -89,12 +89,15 @@ description: Return the origin response value returned: success type: list - contains: - creation_time: - filter_name: - filter_pattern: - log_group_name: - metric_filter_count: + sample: [ + { + "default_value": 3.1415, + "metric_name": "box_free_space", + "metric_namespace": "made_with_ansible", + "metric_value": "$.value" + } + ] + """ from ansible_collections.amazon.aws.plugins.module_utils.aws.core import AnsibleAWSModule, is_boto3_error_code, get_boto3_client_method_parameters from ansible_collections.amazon.aws.plugins.module_utils.ec2 import camel_dict_to_snake_dict diff --git a/plugins/modules/ecs_service.py b/plugins/modules/ecs_service.py --- a/plugins/modules/ecs_service.py +++ b/plugins/modules/ecs_service.py @@ -103,10 +103,17 @@ placement_constraints: description: - The placement constraints for the tasks in the service. + - See U(https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_PlacementConstraint.html) for more details. required: false type: list elements: dict suboptions: + type: + description: The type of constraint. + type: str + expression: + description: A cluster query language expression to apply to the constraint. + type: str placement_strategy: description: - The placement strategy objects to use for tasks in your service. You can specify a maximum of 5 strategy rules per service. @@ -648,8 +655,14 @@ def main(): repeat=dict(required=False, type='int', default=10), force_new_deployment=dict(required=False, default=False, type='bool'), deployment_configuration=dict(required=False, default={}, type='dict'), - placement_constraints=dict(required=False, default=[], type='list'), - placement_strategy=dict(required=False, default=[], type='list'), + placement_constraints=dict(required=False, default=[], type='list', options=dict( + type=dict(type='str'), + expression=dict(type='str') + )), + placement_strategy=dict(required=False, default=[], type='list', options=dict( + type=dict(type='str'), + field=dict(type='str'), + )), health_check_grace_period_seconds=dict(required=False, type='int'), network_configuration=dict(required=False, type='dict', options=dict( subnets=dict(type='list'),
diff --git a/tests/sanity/ignore-2.9.txt b/tests/sanity/ignore-2.9.txt --- a/tests/sanity/ignore-2.9.txt +++ b/tests/sanity/ignore-2.9.txt @@ -84,8 +84,6 @@ plugins/modules/ec2_vpc_vpn_info.py validate-modules:doc-elements-mismatch plugins/modules/ec2_vpc_vpn_info.py validate-modules:parameter-list-no-elements plugins/modules/ecs_attribute.py validate-modules:doc-elements-mismatch plugins/modules/ecs_attribute.py validate-modules:parameter-list-no-elements -plugins/modules/ecs_service.py validate-modules:doc-elements-mismatch -plugins/modules/ecs_service.py validate-modules:parameter-list-no-elements plugins/modules/ecs_service_info.py validate-modules:doc-elements-mismatch plugins/modules/ecs_service_info.py validate-modules:parameter-list-no-elements plugins/modules/ecs_task.py validate-modules:doc-elements-mismatch @@ -149,4 +147,4 @@ tests/unit/mock/yaml_helper.py metaclass-boilerplate tests/unit/modules/conftest.py future-import-boilerplate tests/unit/modules/conftest.py metaclass-boilerplate tests/unit/modules/utils.py future-import-boilerplate -tests/unit/modules/utils.py metaclass-boilerplate \ No newline at end of file +tests/unit/modules/utils.py metaclass-boilerplate
Some documentation errors in the cloudwatchlogs_log_group_metric_filter and ecs_service modules <!--- Verify first that your improvement is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY I've written a schema for DOCUMENTATION, RETURN, etc. There are a few problems in the structure of the return docs on a pair of modules: ``` E module -> community.aws.cloudwatchlogs_log_group_metric_filter -> return -> metric_filters -> contains -> creation_time E none is not an allowed value (type=type_error.none.not_allowed) E module -> community.aws.cloudwatchlogs_log_group_metric_filter -> return -> metric_filters -> contains -> filter_name E none is not an allowed value (type=type_error.none.not_allowed) E module -> community.aws.cloudwatchlogs_log_group_metric_filter -> return -> metric_filters -> contains -> filter_pattern E none is not an allowed value (type=type_error.none.not_allowed) E module -> community.aws.cloudwatchlogs_log_group_metric_filter -> return -> metric_filters -> contains -> log_group_name E none is not an allowed value (type=type_error.none.not_allowed) E module -> community.aws.cloudwatchlogs_log_group_metric_filter -> return -> metric_filters -> contains -> metric_filter_count E none is not an allowed value (type=type_error.none.not_allowed) E module -> community.aws.ecs_service -> doc -> options -> placement_constraints -> suboptions E none is not an allowed value (type=type_error.none.not_allowed) ``` Since this schema is new, it is possible that None should be allowed in one or all of the locations listed. If so, let me know and we can discuss whether/how to update the schema to allow that. ##### ISSUE TYPE - Documentation Report ##### COMPONENT NAME * cloudwatchlogs_log_group_metric_filter.py * ecs_service.py ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ```
2020-05-20T19:30:43
ansible-collections/community.aws
81
ansible-collections__community.aws-81
[ "79" ]
05672a64e2362cc2d865b5af6a57da6bc3cd08e3
diff --git a/plugins/modules/cloudwatchlogs_log_group_metric_filter.py b/plugins/modules/cloudwatchlogs_log_group_metric_filter.py --- a/plugins/modules/cloudwatchlogs_log_group_metric_filter.py +++ b/plugins/modules/cloudwatchlogs_log_group_metric_filter.py @@ -89,12 +89,15 @@ description: Return the origin response value returned: success type: list - contains: - creation_time: - filter_name: - filter_pattern: - log_group_name: - metric_filter_count: + sample: [ + { + "default_value": 3.1415, + "metric_name": "box_free_space", + "metric_namespace": "made_with_ansible", + "metric_value": "$.value" + } + ] + """ from ansible_collections.amazon.aws.plugins.module_utils.aws.core import AnsibleAWSModule, is_boto3_error_code, get_boto3_client_method_parameters from ansible_collections.amazon.aws.plugins.module_utils.ec2 import camel_dict_to_snake_dict diff --git a/plugins/modules/ecs_service.py b/plugins/modules/ecs_service.py --- a/plugins/modules/ecs_service.py +++ b/plugins/modules/ecs_service.py @@ -103,10 +103,17 @@ placement_constraints: description: - The placement constraints for the tasks in the service. + - See U(https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_PlacementConstraint.html) for more details. required: false type: list elements: dict suboptions: + type: + description: The type of constraint. + type: str + expression: + description: A cluster query language expression to apply to the constraint. + type: str placement_strategy: description: - The placement strategy objects to use for tasks in your service. You can specify a maximum of 5 strategy rules per service.
Some documentation errors in the cloudwatchlogs_log_group_metric_filter and ecs_service modules <!--- Verify first that your improvement is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY I've written a schema for DOCUMENTATION, RETURN, etc. There are a few problems in the structure of the return docs on a pair of modules: ``` E module -> community.aws.cloudwatchlogs_log_group_metric_filter -> return -> metric_filters -> contains -> creation_time E none is not an allowed value (type=type_error.none.not_allowed) E module -> community.aws.cloudwatchlogs_log_group_metric_filter -> return -> metric_filters -> contains -> filter_name E none is not an allowed value (type=type_error.none.not_allowed) E module -> community.aws.cloudwatchlogs_log_group_metric_filter -> return -> metric_filters -> contains -> filter_pattern E none is not an allowed value (type=type_error.none.not_allowed) E module -> community.aws.cloudwatchlogs_log_group_metric_filter -> return -> metric_filters -> contains -> log_group_name E none is not an allowed value (type=type_error.none.not_allowed) E module -> community.aws.cloudwatchlogs_log_group_metric_filter -> return -> metric_filters -> contains -> metric_filter_count E none is not an allowed value (type=type_error.none.not_allowed) E module -> community.aws.ecs_service -> doc -> options -> placement_constraints -> suboptions E none is not an allowed value (type=type_error.none.not_allowed) ``` Since this schema is new, it is possible that None should be allowed in one or all of the locations listed. If so, let me know and we can discuss whether/how to update the schema to allow that. ##### ISSUE TYPE - Documentation Report ##### COMPONENT NAME * cloudwatchlogs_log_group_metric_filter.py * ecs_service.py ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ```
2020-05-20T21:21:21
ansible-collections/community.aws
93
ansible-collections__community.aws-93
[ "92" ]
315f54619a07fc0d7520aa318d9b8d1cf2b1070f
diff --git a/plugins/modules/kinesis_stream.py b/plugins/modules/kinesis_stream.py --- a/plugins/modules/kinesis_stream.py +++ b/plugins/modules/kinesis_stream.py @@ -362,6 +362,8 @@ def find_stream(client, stream_name, check_mode=False): ) shards.extend(results.pop('Shards')) has_more_shards = results['HasMoreShards'] + if has_more_shards: + params['ExclusiveStartShardId'] = shards[-1]['ShardId'] results['Shards'] = shards num_closed_shards = len([s for s in shards if 'EndingSequenceNumber' in s['SequenceNumberRange']]) results['OpenShardsCount'] = len(shards) - num_closed_shards
Ansible kinesis stream paginated shards gets stuck in infinite loop ##### SUMMARY For Kinesis streams with > 100 shards, `client.describe_stream(**params)['StreamDescription']` returns a paginated view, thus https://github.com/ansible-collections/community.aws/blob/master/plugins/modules/kinesis_stream.py#L363 will always be true and we'll be stuck in this infinite while loop since `has_more_shards` is always True. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME Kinesis Streams ##### ANSIBLE VERSION ``` 2.9.9 ``` ##### STEPS TO REPRODUCE ``` Hard to give you steps to reproduce this issue as it only happens with kinesis streams with > 100 shards. ``` ##### EXPECTED RESULTS Creating kinesis streams should not cause a timeout! ##### ACTUAL RESULTS ``` Our deployment failed when trying to create a kinesis stream due to a timeout. TASK [kinesis : create kinesis stream] ***************************************** --   | fatal: [localhost]: FAILED! => {"changed": true, "msg": "Wait time out reached, while waiting for results", "result": {}, "success": false} ```
2020-06-09T16:11:17
ansible-collections/community.aws
218
ansible-collections__community.aws-218
[ "24" ]
315f54619a07fc0d7520aa318d9b8d1cf2b1070f
diff --git a/plugins/connection/aws_ssm.py b/plugins/connection/aws_ssm.py --- a/plugins/connection/aws_ssm.py +++ b/plugins/connection/aws_ssm.py @@ -20,6 +20,21 @@ - The control machine must have the aws session manager plugin installed. - The remote EC2 linux instance must have the curl installed. options: + access_key_id: + description: The STS access key to use when connecting via session-manager. + vars: + - name: ansible_aws_ssm_access_key_id + version_added: 1.3.0 + secret_access_key: + description: The STS secret key to use when connecting via session-manager. + vars: + - name: ansible_aws_ssm_secret_access_key + version_added: 1.3.0 + session_token: + description: The STS session token to use when connecting via session-manager. + vars: + - name: ansible_aws_ssm_session_token + version_added: 1.3.0 instance_id: description: The EC2 instance ID. vars: @@ -289,8 +304,7 @@ def start_session(self): profile_name = '' region_name = self.get_option('region') ssm_parameters = dict() - - client = boto3.client('ssm', region_name=region_name) + client = self._get_boto_client('ssm', region_name=region_name) self._client = client response = client.start_session(Target=self.instance_id, Parameters=ssm_parameters) self._session_id = response['SessionId'] @@ -483,9 +497,27 @@ def _flush_stderr(self, subprocess): def _get_url(self, client_method, bucket_name, out_path, http_method): ''' Generate URL for get_object / put_object ''' - client = boto3.client('s3') + client = self._get_boto_client('s3') return client.generate_presigned_url(client_method, Params={'Bucket': bucket_name, 'Key': out_path}, ExpiresIn=3600, HttpMethod=http_method) + def _get_boto_client(self, service, region_name=None): + ''' Gets a boto3 client based on the STS token ''' + + aws_access_key_id = self.get_option('access_key_id') + aws_secret_access_key = self.get_option('secret_access_key') + aws_session_token = self.get_option('session_token') + if aws_access_key_id is None or aws_secret_access_key is None or aws_session_token is None: + aws_access_key_id = os.environ.get("AWS_ACCESS_KEY_ID", None) + aws_secret_access_key = os.environ.get("AWS_SECRET_ACCESS_KEY", None) + aws_session_token = os.environ.get("AWS_SESSION_TOKEN", None) + client = boto3.client( + service, + aws_access_key_id=aws_access_key_id, + aws_secret_access_key=aws_secret_access_key, + aws_session_token=aws_session_token, + region_name=region_name) + return client + @_ssm_retry def _file_transport_command(self, in_path, out_path, ssm_action): ''' transfer a file from using an intermediate S3 bucket ''' @@ -504,7 +536,7 @@ def _file_transport_command(self, in_path, out_path, ssm_action): get_command = "curl '%s' -o '%s'" % ( self._get_url('get_object', self.get_option('bucket_name'), s3_path, 'GET'), out_path) - client = boto3.client('s3') + client = self._get_boto_client('s3') if ssm_action == 'get': (returncode, stdout, stderr) = self.exec_command(put_command, in_data=None, sudoable=False) with open(to_bytes(out_path, errors='surrogate_or_strict'), 'wb') as data:
Support STS token in aws_ssm connection plugin. ##### SUMMARY The current implementation of the aws_ssm connection plugin relies on the exported environment variables, or on a default connection profile being configured on the controller. An ideal implementation would allow the task caller to pass an STS token, for example in cases where there is a cross-account trust policy and the node is able to retrieve such session token and execute tasks in the target account. This would also allow a more versatile usage from the API, by dynamically assume the target role STS session and pass it to each invocation. ##### ISSUE TYPE - Feature Idea ##### COMPONENT NAME aws_ssm.py connection plugin ##### ADDITIONAL INFORMATION This is how a task can be called with all the sts parameters: <!--- Paste example playbooks or commands between quotes below --> ```yaml --- - hosts: all vars: ansible_aws_ssm_region: us-east-1 bucket_name: helper-bucket-flavioelawi ansible_aws_ssm_access_key_id: <THE_ACCESS_KEY_ID> ansible_aws_ssm_secret_access_key: <THE_SECRET_KEY> ansible_aws_ssm_session_token: <THE_SESSION_TOKEN> tasks: - name: test stat stat: path: /etc/foo.conf register: file_details - debug: msg: "file or dir exists" when: file_details.stat.exists ```
2020-09-01T20:13:45
ansible-collections/community.aws
224
ansible-collections__community.aws-224
[ "223" ]
a147040a2d092e128823890ceac8f68e01eb8087
diff --git a/plugins/modules/rds_subnet_group.py b/plugins/modules/rds_subnet_group.py --- a/plugins/modules/rds_subnet_group.py +++ b/plugins/modules/rds_subnet_group.py @@ -1,8 +1,11 @@ #!/usr/bin/python +# -*- coding: utf-8 -*- + # Copyright: Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function + __metaclass__ = type @@ -66,10 +69,18 @@ type: complex contains: name: + description: The name of the DB subnet group (maintained for backward compatibility) + returned: I(state=present) + type: str + db_subnet_group_name: description: The name of the DB subnet group returned: I(state=present) type: str description: + description: The description of the DB subnet group (maintained for backward compatibility) + returned: I(state=present) + type: str + db_subnet_group_description: description: The description of the DB subnet group returned: I(state=present) type: str @@ -81,32 +92,32 @@ description: Contains a list of Subnet IDs returned: I(state=present) type: list + subnets: + description: Contains a list of Subnet elements (@see https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html#RDS.Client.describe_db_subnet_groups) # noqa + returned: I(state=present) + type: list status: + description: The status of the DB subnet group (maintained for backward compatibility) + returned: I(state=present) + type: str + subnet_group_status: description: The status of the DB subnet group returned: I(state=present) type: str + db_subnet_group_arn: + description: The ARN of the DB subnet group + returned: I(state=present) + type: str ''' -try: - import boto.rds - from boto.exception import BotoServerError -except ImportError: - pass # Handled by HAS_BOTO +from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict +from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule, is_boto3_error_code -from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule -from ansible_collections.amazon.aws.plugins.module_utils.ec2 import HAS_BOTO -from ansible_collections.amazon.aws.plugins.module_utils.ec2 import connect_to_aws -from ansible_collections.amazon.aws.plugins.module_utils.ec2 import get_aws_connection_info - -def get_subnet_group_info(subnet_group): - return dict( - name=subnet_group.name, - description=subnet_group.description, - vpc_id=subnet_group.vpc_id, - subnet_ids=subnet_group.subnet_ids, - status=subnet_group.status - ) +try: + import botocore +except ImportError: + pass # Handled by AnsibleAWSModule def create_result(changed, subnet_group=None): @@ -114,11 +125,34 @@ def create_result(changed, subnet_group=None): return dict( changed=changed ) - else: - return dict( - changed=changed, - subnet_group=get_subnet_group_info(subnet_group) - ) + result_subnet_group = dict(camel_dict_to_snake_dict(subnet_group)) + result_subnet_group['name'] = result_subnet_group.get( + 'db_subnet_group_name') + result_subnet_group['description'] = result_subnet_group.get( + 'db_subnet_group_description') + result_subnet_group['status'] = result_subnet_group.get( + 'subnet_group_status') + result_subnet_group['subnet_ids'] = create_subnet_list( + subnet_group.get('Subnets')) + return dict( + changed=changed, + subnet_group=result_subnet_group + ) + + +def create_subnet_list(subnets): + ''' + Construct a list of subnet ids from a list of subnets dicts returned by boto. + Parameters: + subnets (list): A list of subnets definitions. + @see https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html#RDS.Client.describe_db_subnet_groups + Returns: + (list): List of subnet ids (str) + ''' + subnets_ids = [] + for subnet in subnets: + subnets_ids.append(subnet.get('SubnetIdentifier')) + return subnets_ids def main(): @@ -128,70 +162,63 @@ def main(): description=dict(required=False), subnets=dict(required=False, type='list', elements='str'), ) - module = AnsibleAWSModule(argument_spec=argument_spec) - - if not HAS_BOTO: - module.fail_json(msg='boto required for this module') - + required_if = [('state', 'present', ['description', 'subnets'])] + module = AnsibleAWSModule( + argument_spec=argument_spec, required_if=required_if) state = module.params.get('state') group_name = module.params.get('name').lower() group_description = module.params.get('description') - group_subnets = module.params.get('subnets') or {} - - if state == 'present': - for required in ['description', 'subnets']: - if not module.params.get(required): - module.fail_json(msg=str("Parameter %s required for state='present'" % required)) - else: - for not_allowed in ['description', 'subnets']: - if module.params.get(not_allowed): - module.fail_json(msg=str("Parameter %s not allowed for state='absent'" % not_allowed)) - - # Retrieve any AWS settings from the environment. - region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module) - - if not region: - module.fail_json(msg=str("Either region or AWS_REGION or EC2_REGION environment variable or boto config aws_region or ec2_region must be set.")) + group_subnets = module.params.get('subnets') or [] try: - conn = connect_to_aws(boto.rds, region, **aws_connect_kwargs) - except BotoServerError as e: - module.fail_json(msg=e.error_message) + conn = module.client('rds') + except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: + module.fail_json_aws(e, 'Failed to instantiate AWS connection') + # Default. + result = create_result(False) try: - exists = False - result = create_result(False) - + matching_groups = conn.describe_db_subnet_groups( + DBSubnetGroupName=group_name, MaxRecords=100).get('DBSubnetGroups') + except is_boto3_error_code('DBSubnetGroupNotFoundFault'): + # No existing subnet, create it if needed, else we can just exit. + if state == 'present': + try: + new_group = conn.create_db_subnet_group( + DBSubnetGroupName=group_name, DBSubnetGroupDescription=group_description, SubnetIds=group_subnets) + result = create_result(True, new_group.get('DBSubnetGroup')) + except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: + module.fail_json_aws(e, 'Failed to create a new subnet group') + module.exit_json(**result) + except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: # pylint: disable=duplicate-except + module.fail_json_aws(e, 'Failed to get subnet groups description') + # We have one or more subnets at this point. + if state == 'absent': try: - matching_groups = conn.get_all_db_subnet_groups(group_name, max_records=100) - exists = len(matching_groups) > 0 - except BotoServerError as e: - if e.error_code != 'DBSubnetGroupNotFoundFault': - module.fail_json(msg=e.error_message) - - if state == 'absent': - if exists: - conn.delete_db_subnet_group(group_name) - result = create_result(True) - else: - if not exists: - new_group = conn.create_db_subnet_group(group_name, desc=group_description, subnet_ids=group_subnets) - result = create_result(True, new_group) - else: - # Sort the subnet groups before we compare them - matching_groups[0].subnet_ids.sort() - group_subnets.sort() - if (matching_groups[0].name != group_name or - matching_groups[0].description != group_description or - matching_groups[0].subnet_ids != group_subnets): - changed_group = conn.modify_db_subnet_group(group_name, description=group_description, subnet_ids=group_subnets) - result = create_result(True, changed_group) - else: - result = create_result(False, matching_groups[0]) - except BotoServerError as e: - module.fail_json(msg=e.error_message) - - module.exit_json(**result) + conn.delete_db_subnet_group(DBSubnetGroupName=group_name) + result = create_result(True) + module.exit_json(**result) + except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: + module.fail_json_aws(e, 'Failed to delete a subnet group') + + # Sort the subnet groups before we compare them + existing_subnets = create_subnet_list(matching_groups[0].get('Subnets')) + existing_subnets.sort() + group_subnets.sort() + # See if anything changed. + if (matching_groups[0].get('DBSubnetGroupName') == group_name and + matching_groups[0].get('DBSubnetGroupDescription') == group_description and + existing_subnets == group_subnets): + result = create_result(False, matching_groups[0]) + module.exit_json(**result) + # Modify existing group. + try: + changed_group = conn.modify_db_subnet_group( + DBSubnetGroupName=group_name, DBSubnetGroupDescription=group_description, SubnetIds=group_subnets) + result = create_result(True, changed_group.get('DBSubnetGroup')) + module.exit_json(**result) + except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: + module.fail_json_aws(e, 'Failed to update a subnet group') if __name__ == '__main__':
diff --git a/tests/integration/targets/rds_subnet_group/tasks/params.yml b/tests/integration/targets/rds_subnet_group/tasks/params.yml --- a/tests/integration/targets/rds_subnet_group/tasks/params.yml +++ b/tests/integration/targets/rds_subnet_group/tasks/params.yml @@ -1,62 +1,30 @@ --- # Try creating without a description -- name: 'Create a subnet group (no description)' +- name: "Create a subnet group (no description)" rds_subnet_group: state: present - name: '{{ resource_prefix }}' + name: "{{ resource_prefix }}" subnets: - - '{{ subnet_ids[0] }}' - - '{{ subnet_ids[1] }}' + - "{{ subnet_ids[0] }}" + - "{{ subnet_ids[1] }}" ignore_errors: yes register: create_missing_param - assert: that: - - create_missing_param is failed - - "'description' in create_missing_param.msg" - - "\"required for state='present'\" in create_missing_param.msg" + - create_missing_param is failed + - "'description' in create_missing_param.msg" + - "'state is present but all of the following are missing' in create_missing_param.msg" # Try creating without subnets -- name: 'Create a subnet group (no subnets)' +- name: "Create a subnet group (no subnets)" rds_subnet_group: state: present - name: '{{ resource_prefix }}' - description: '{{ group_description }}' + name: "{{ resource_prefix }}" + description: "{{ group_description }}" ignore_errors: yes register: create_missing_param - assert: that: - - create_missing_param is failed - - "'subnets' in create_missing_param.msg" - - "\"required for state='present'\" in create_missing_param.msg" - -# XXX This feels like a bad pattern -# Try deleting with subnets -- name: 'Delete a subnet group (with subnets)' - rds_subnet_group: - state: absent - name: '{{ resource_prefix }}' - subnets: - - '{{ subnet_ids[0] }}' - - '{{ subnet_ids[1] }}' - ignore_errors: yes - register: delete_extra_param -- assert: - that: - - delete_extra_param is failed - - "'subnets' in delete_extra_param.msg" - - "\"not allowed for state='absent'\" in delete_extra_param.msg" - -# XXX This feels like a bad pattern -# Try deleting with a description -- name: 'Create a subnet group (with description)' - rds_subnet_group: - state: absent - name: '{{ resource_prefix }}' - description: '{{ group_description }}' - ignore_errors: yes - register: delete_extra_param -- assert: - that: - - delete_extra_param is failed - - "'description' in delete_extra_param.msg" - - "\"not allowed for state='absent'\" in delete_extra_param.msg" + - create_missing_param is failed + - "'subnets' in create_missing_param.msg" + - "'state is present but all of the following are missing' in create_missing_param.msg"
Port rds_subnet_group to boto3 ##### SUMMARY Use boto3 instead of boto (and remove logic on mandatory arguments on state: absent) ##### ISSUE TYPE - Chore ##### COMPONENT NAME rds_subnet_group.py ##### ADDITIONAL INFORMATION I've only focused on the minimal work to get it working in the same way as it was from a functional point of view. Would probably need some tests and a few additional features (like support for tags), but seems to be working for my use case.
2020-09-07T13:39:38
ansible-collections/community.aws
232
ansible-collections__community.aws-232
[ "231" ]
0d245596966100516f1eeab5dcf26ee0ebca24b5
diff --git a/plugins/modules/ec2_asg.py b/plugins/modules/ec2_asg.py --- a/plugins/modules/ec2_asg.py +++ b/plugins/modules/ec2_asg.py @@ -93,6 +93,67 @@ - A list of instance_types. type: list elements: str + required: false + instances_distribution: + description: + - >- + Specifies the distribution of On-Demand Instances and Spot Instances, the maximum price + to pay for Spot Instances, and how the Auto Scaling group allocates instance types + to fulfill On-Demand and Spot capacity. + - 'See also U(https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_InstancesDistribution.html)' + required: false + type: dict + version_added: 1.5.0 + suboptions: + on_demand_allocation_strategy: + description: + - Indicates how to allocate instance types to fulfill On-Demand capacity. + type: str + required: false + version_added: 1.5.0 + on_demand_base_capacity: + description: + - >- + The minimum amount of the Auto Scaling group's capacity that must be fulfilled by On-Demand + Instances. This base portion is provisioned first as your group scales. + - >- + Default if not set is 0. If you leave it set to 0, On-Demand Instances are launched as a + percentage of the Auto Scaling group's desired capacity, per the OnDemandPercentageAboveBaseCapacity setting. + type: int + required: false + version_added: 1.5.0 + on_demand_percentage_above_base_capacity: + description: + - Controls the percentages of On-Demand Instances and Spot Instances for your additional capacity beyond OnDemandBaseCapacity. + - Default if not set is 100. If you leave it set to 100, the percentages are 100% for On-Demand Instances and 0% for Spot Instances. + - 'Valid range: 0 to 100' + type: int + required: false + version_added: 1.5.0 + spot_allocation_strategy: + description: + - Indicates how to allocate instances across Spot Instance pools. + type: str + required: false + version_added: 1.5.0 + spot_instance_pools: + description: + - >- + The number of Spot Instance pools across which to allocate your Spot Instances. The Spot pools are determined from + the different instance types in the Overrides array of LaunchTemplate. Default if not set is 2. + - Used only when the Spot allocation strategy is lowest-price. + - 'Valid Range: Minimum value of 1. Maximum value of 20.' + type: int + required: false + version_added: 1.5.0 + spot_max_price: + description: + - The maximum price per unit hour that you are willing to pay for a Spot Instance. + - If you leave the value of this parameter blank (which is the default), the maximum Spot price is set at the On-Demand price. + - To remove a value that you previously set, include the parameter but leave the value blank. + type: str + required: false + version_added: 1.5.0 type: dict placement_group: description: @@ -339,6 +400,9 @@ - t3a.large - t3.large - t2.large + instances_distribution: + on_demand_percentage_above_base_capacity: 0 + spot_allocation_strategy: capacity-optimized min_size: 1 max_size: 10 desired_capacity: 5 @@ -447,11 +511,38 @@ returned: success type: int sample: 1 -mixed_instance_policy: - description: Returns the list of instance types if a mixed instance policy is set. +mixed_instances_policy: + description: Returns the list of instance types if a mixed instances policy is set. returned: success type: list sample: ["t3.micro", "t3a.micro"] +mixed_instances_policy_full: + description: Returns the full dictionary representation of the mixed instances policy if a mixed instances policy is set. + returned: success + type: dict + sample: { + "instances_distribution": { + "on_demand_allocation_strategy": "prioritized", + "on_demand_base_capacity": 0, + "on_demand_percentage_above_base_capacity": 0, + "spot_allocation_strategy": "capacity-optimized" + }, + "launch_template": { + "launch_template_specification": { + "launch_template_id": "lt-53c2425cffa544c23", + "launch_template_name": "random-LaunchTemplate", + "version": "2" + }, + "overrides": [ + { + "instance_type": "m5.xlarge" + }, + { + "instance_type": "m5a.xlarge" + }, + ] + } + } pending_instances: description: Number of instances in pending state returned: success @@ -536,7 +627,10 @@ from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule from ansible_collections.amazon.aws.plugins.module_utils.core import is_boto3_error_code +from ansible_collections.amazon.aws.plugins.module_utils.core import scrub_none_parameters from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AWSRetry +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import snake_dict_to_camel_dict +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import camel_dict_to_snake_dict ASG_ATTRIBUTES = ('AvailabilityZones', 'DefaultCooldown', 'DesiredCapacity', 'HealthCheckGracePeriod', 'HealthCheckType', 'LaunchConfigurationName', @@ -742,6 +836,7 @@ def get_properties(autoscaling_group): properties['vpc_zone_identifier'] = autoscaling_group.get('VPCZoneIdentifier') raw_mixed_instance_object = autoscaling_group.get('MixedInstancesPolicy') if raw_mixed_instance_object: + properties['mixed_instances_policy_full'] = camel_dict_to_snake_dict(raw_mixed_instance_object) properties['mixed_instances_policy'] = [x['InstanceType'] for x in raw_mixed_instance_object.get('LaunchTemplate').get('Overrides')] metrics = autoscaling_group.get('EnabledMetrics') @@ -792,6 +887,7 @@ def get_launch_object(connection, ec2_connection): if mixed_instances_policy: instance_types = mixed_instances_policy.get('instance_types', []) + instances_distribution = mixed_instances_policy.get('instances_distribution', {}) policy = { 'LaunchTemplate': { 'LaunchTemplateSpecification': launch_object['LaunchTemplate'] @@ -802,6 +898,9 @@ def get_launch_object(connection, ec2_connection): for instance_type in instance_types: instance_type_dict = {'InstanceType': instance_type} policy['LaunchTemplate']['Overrides'].append(instance_type_dict) + if instances_distribution: + instances_distribution_params = scrub_none_parameters(instances_distribution) + policy['InstancesDistribution'] = snake_dict_to_camel_dict(instances_distribution_params, capitalize_first=True) launch_object['MixedInstancesPolicy'] = policy return launch_object @@ -1661,6 +1760,18 @@ def main(): type='list', elements='str' ), + instances_distribution=dict( + type='dict', + default=None, + options=dict( + on_demand_allocation_strategy=dict(type='str'), + on_demand_base_capacity=dict(type='int'), + on_demand_percentage_above_base_capacity=dict(type='int'), + spot_allocation_strategy=dict(type='str'), + spot_instance_pools=dict(type='int'), + spot_max_price=dict(type='str'), + ) + ) ) ), placement_group=dict(type='str'),
diff --git a/tests/integration/targets/ec2_asg/tasks/main.yml b/tests/integration/targets/ec2_asg/tasks/main.yml --- a/tests/integration/targets/ec2_asg/tasks/main.yml +++ b/tests/integration/targets/ec2_asg/tasks/main.yml @@ -629,9 +629,9 @@ until: status is finished retries: 200 delay: 15 - + # we need a launch template, otherwise we cannot test the mixed instance policy - - name: create launch template for autoscaling group to test its mixed instance policy + - name: create launch template for autoscaling group to test its mixed instances policy ec2_launch_template: template_name: "{{ resource_prefix }}-lt" image_id: "{{ ec2_ami_image }}" @@ -645,10 +645,10 @@ groups: - "{{ sg.group_id }}" - - name: update autoscaling group with mixed-instance policy + - name: update autoscaling group with mixed-instances policy with mixed instances types ec2_asg: name: "{{ resource_prefix }}-asg" - launch_template: + launch_template: launch_template_name: "{{ resource_prefix }}-lt" desired_capacity: 1 min_size: 1 @@ -668,6 +668,33 @@ - "output.mixed_instances_policy[0] == 't3.micro'" - "output.mixed_instances_policy[1] == 't3a.micro'" + - name: update autoscaling group with mixed-instances policy with instances_distribution + ec2_asg: + name: "{{ resource_prefix }}-asg" + launch_template: + launch_template_name: "{{ resource_prefix }}-lt" + desired_capacity: 1 + min_size: 1 + max_size: 1 + vpc_zone_identifier: "{{ testing_subnet.subnet.id }}" + state: present + mixed_instances_policy: + instance_types: + - t3.micro + - t3a.micro + instances_distribution: + on_demand_percentage_above_base_capacity: 0 + spot_allocation_strategy: capacity-optimized + wait_for_instances: yes + register: output + + - assert: + that: + - "output.mixed_instances_policy_full['launch_template']['overrides'][0]['instance_type'] == 't3.micro'" + - "output.mixed_instances_policy_full['launch_template']['overrides'][1]['instance_type'] == 't3a.micro'" + - "output.mixed_instances_policy_full['instances_distribution']['on_demand_percentage_above_base_capacity'] == 0" + - "output.mixed_instances_policy_full['instances_distribution']['spot_allocation_strategy'] == 'capacity-optimized'" + # ============================================================ always:
ec2_asg mixed_instance_policy does not support instances_distribution <!--- Verify first that your feature was not already discussed on GitHub --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY ec2_asg mixed_instance_policy does not support instances_distribution. It only supports setting multiple instance types. Instead, it should support all of the features in https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_MixedInstancesPolicy.html, not just instance type overrides. ##### ISSUE TYPE - Feature Idea ##### COMPONENT NAME ec2_asg ##### ADDITIONAL INFORMATION This would be useful for users trying to add spot instances to their ASGs.
2020-09-16T16:46:58
ansible-collections/community.aws
248
ansible-collections__community.aws-248
[ "247" ]
cd938b2c0ef3d1bc98ac68b217187f45278af2b1
diff --git a/plugins/modules/ecs_ecr.py b/plugins/modules/ecs_ecr.py --- a/plugins/modules/ecs_ecr.py +++ b/plugins/modules/ecs_ecr.py @@ -58,12 +58,12 @@ type: str lifecycle_policy: description: - - JSON or dict that represents the new lifecycle policy + - JSON or dict that represents the new lifecycle policy. required: false type: json purge_lifecycle_policy: description: - - if yes, remove the lifecycle policy from the repository + - if yes, remove the lifecycle policy from the repository. required: false default: false type: bool @@ -74,6 +74,14 @@ choices: [present, absent] default: 'present' type: str + scan_on_push: + description: + - if yes, images are scanned for known vulnerabilities after being pushed to the repository. + - I(scan_on_push) requires botocore >= 1.13.3 + required: false + default: false + type: bool + version_added: 1.3.0 author: - David M. Lee (@leedm777) extends_documentation_fragment: @@ -132,6 +140,7 @@ - name: set-lifecycle-policy community.aws.ecs_ecr: name: needs-lifecycle-policy + scan_on_push: yes lifecycle_policy: rules: - rulePriority: 1 @@ -355,6 +364,25 @@ def purge_lifecycle_policy(self, registry_id, name): return policy return None + def put_image_scanning_configuration(self, registry_id, name, scan_on_push): + if not self.check_mode: + if registry_id: + scan = self.ecr.put_image_scanning_configuration( + registryId=registry_id, + repositoryName=name, + imageScanningConfiguration={'scanOnPush': scan_on_push} + ) + else: + scan = self.ecr.put_image_scanning_configuration( + repositoryName=name, + imageScanningConfiguration={'scanOnPush': scan_on_push} + ) + self.changed = True + return scan + else: + self.skipped = True + return None + def sort_lists_of_strings(policy): for statement_index in range(0, len(policy.get('Statement', []))): @@ -378,6 +406,7 @@ def run(ecr, params): image_tag_mutability = params['image_tag_mutability'].upper() lifecycle_policy_text = params['lifecycle_policy'] purge_lifecycle_policy = params['purge_lifecycle_policy'] + scan_on_push = params['scan_on_push'] # Parse policies, if they are given try: @@ -474,6 +503,13 @@ def run(ecr, params): result['policy'] = policy_text raise + original_scan_on_push = ecr.get_repository(registry_id, name) + if original_scan_on_push is not None: + if scan_on_push != original_scan_on_push['imageScanningConfiguration']['scanOnPush']: + result['changed'] = True + result['repository']['imageScanningConfiguration']['scanOnPush'] = scan_on_push + response = ecr.put_image_scanning_configuration(registry_id, name, scan_on_push) + elif state == 'absent': result['name'] = name if repo: @@ -510,7 +546,8 @@ def main(): purge_policy=dict(required=False, type='bool', aliases=['delete_policy'], deprecated_aliases=[dict(name='delete_policy', date='2022-06-01', collection_name='community.aws')]), lifecycle_policy=dict(required=False, type='json'), - purge_lifecycle_policy=dict(required=False, type='bool') + purge_lifecycle_policy=dict(required=False, type='bool'), + scan_on_push=(dict(required=False, type='bool', default=False)) ) mutually_exclusive = [ ['policy', 'purge_policy'],
diff --git a/tests/integration/targets/ecs_ecr/tasks/main.yml b/tests/integration/targets/ecs_ecr/tasks/main.yml --- a/tests/integration/targets/ecs_ecr/tasks/main.yml +++ b/tests/integration/targets/ecs_ecr/tasks/main.yml @@ -1,22 +1,18 @@ --- -- set_fact: - ecr_name: '{{ resource_prefix }}-ecr' +- module_defaults: + group/aws: + region: "{{ aws_region }}" + aws_access_key: "{{ aws_access_key }}" + aws_secret_key: "{{ aws_secret_key }}" + security_token: "{{ security_token | default(omit) }}" -- block: - - - name: set connection information for all tasks - set_fact: - aws_connection_info: &aws_connection_info - aws_access_key: "{{ aws_access_key }}" - aws_secret_key: "{{ aws_secret_key }}" - security_token: "{{ security_token }}" - region: "{{ aws_region }}" - no_log: yes + block: + - set_fact: + ecr_name: '{{ resource_prefix }}-ecr' - name: When creating with check mode ecs_ecr: name: '{{ ecr_name }}' - <<: *aws_connection_info register: result check_mode: yes @@ -32,7 +28,6 @@ ecs_ecr: registry_id: 999999999999 name: '{{ ecr_name }}' - <<: *aws_connection_info register: result ignore_errors: true @@ -46,7 +41,6 @@ - name: When creating a repository ecs_ecr: name: '{{ ecr_name }}' - <<: *aws_connection_info register: result - name: it should change and create @@ -64,7 +58,6 @@ - name: When creating a repository that already exists in check mode ecs_ecr: name: '{{ ecr_name }}' - <<: *aws_connection_info register: result check_mode: yes @@ -78,7 +71,6 @@ - name: When creating a repository that already exists ecs_ecr: name: '{{ ecr_name }}' - <<: *aws_connection_info register: result - name: it should not change @@ -91,7 +83,6 @@ ecs_ecr: name: '{{ ecr_name }}' purge_policy: yes - <<: *aws_connection_info register: result check_mode: yes @@ -106,7 +97,6 @@ ecs_ecr: name: '{{ ecr_name }}' policy: '{{ policy }}' - <<: *aws_connection_info register: result check_mode: yes @@ -122,7 +112,6 @@ ecs_ecr: name: '{{ ecr_name }}' policy: '{{ policy }}' - <<: *aws_connection_info register: result - name: it should change and not create @@ -136,7 +125,6 @@ ecs_ecr: name: '{{ ecr_name }}' delete_policy: yes - <<: *aws_connection_info register: result check_mode: yes @@ -153,7 +141,6 @@ ecs_ecr: name: '{{ ecr_name }}' purge_policy: yes - <<: *aws_connection_info register: result check_mode: yes @@ -170,7 +157,6 @@ ecs_ecr: name: '{{ ecr_name }}' purge_policy: yes - <<: *aws_connection_info register: result - name: it should change and not create @@ -184,7 +170,6 @@ ecs_ecr: name: '{{ ecr_name }}' policy: '{{ policy | to_json }}' - <<: *aws_connection_info register: result - name: it should change and not create @@ -198,7 +183,6 @@ ecs_ecr: name: '{{ ecr_name }}' policy: '{{ policy }}' - <<: *aws_connection_info register: result - name: it should not change @@ -209,7 +193,6 @@ - name: When omitting policy on a repository that has a policy ecs_ecr: name: '{{ ecr_name }}' - <<: *aws_connection_info register: result - name: it should not change @@ -222,7 +205,6 @@ name: '{{ ecr_name }}' policy: '{{ policy }}' purge_policy: yes - <<: *aws_connection_info register: result ignore_errors: true @@ -236,7 +218,6 @@ ecs_ecr: name: '{{ ecr_name }}' policy: "Ceci n'est pas une JSON" - <<: *aws_connection_info register: result ignore_errors: true @@ -250,7 +231,6 @@ ecs_ecr: name: '{{ ecr_name }}' purge_lifecycle_policy: yes - <<: *aws_connection_info register: result check_mode: yes @@ -265,7 +245,6 @@ ecs_ecr: name: '{{ ecr_name }}' lifecycle_policy: '{{ lifecycle_policy }}' - <<: *aws_connection_info register: result check_mode: yes @@ -281,7 +260,6 @@ ecs_ecr: name: '{{ ecr_name }}' lifecycle_policy: '{{ lifecycle_policy }}' - <<: *aws_connection_info register: result - name: it should change and not create @@ -297,7 +275,6 @@ ecs_ecr: name: '{{ ecr_name }}' purge_lifecycle_policy: yes - <<: *aws_connection_info register: result check_mode: yes @@ -313,7 +290,6 @@ ecs_ecr: name: '{{ ecr_name }}' purge_lifecycle_policy: yes - <<: *aws_connection_info register: result - name: it should change and not create @@ -327,7 +303,6 @@ ecs_ecr: name: '{{ ecr_name }}' lifecycle_policy: '{{ lifecycle_policy | to_json }}' - <<: *aws_connection_info register: result - name: it should change and not create @@ -341,7 +316,6 @@ ecs_ecr: name: '{{ ecr_name }}' lifecycle_policy: '{{ lifecycle_policy }}' - <<: *aws_connection_info register: result - name: it should not change @@ -353,7 +327,6 @@ - name: When omitting lifecycle policy on a repository that has a policy ecs_ecr: name: '{{ ecr_name }}' - <<: *aws_connection_info register: result - name: it should not change @@ -367,7 +340,6 @@ name: '{{ ecr_name }}' lifecycle_policy: '{{ lifecycle_policy }}' purge_lifecycle_policy: yes - <<: *aws_connection_info register: result ignore_errors: true @@ -381,7 +353,6 @@ ecs_ecr: name: '{{ ecr_name }}' lifecycle_policy: "Ceci n'est pas une JSON" - <<: *aws_connection_info register: result ignore_errors: true @@ -397,7 +368,6 @@ lifecycle_policy: rules: - invalid: "Ceci n'est pas une rule" - <<: *aws_connection_info register: result ignore_errors: true @@ -411,7 +381,6 @@ ecs_ecr: name: '{{ ecr_name }}' state: absent - <<: *aws_connection_info register: result check_mode: yes @@ -427,7 +396,6 @@ ecs_ecr: name: '{{ ecr_name }}' state: absent - <<: *aws_connection_info register: result - name: it should change @@ -440,7 +408,6 @@ ecs_ecr: name: '{{ ecr_name }}' state: absent - <<: *aws_connection_info register: result check_mode: yes @@ -455,7 +422,6 @@ ecs_ecr: name: '{{ ecr_name }}' state: absent - <<: *aws_connection_info register: result - name: it should not change @@ -466,10 +432,6 @@ - name: When creating an immutable repository ecs_ecr: name: '{{ ecr_name }}' - region: '{{ ec2_region }}' - ec2_access_key: '{{ec2_access_key}}' - ec2_secret_key: '{{ec2_secret_key}}' - security_token: '{{security_token}}' image_tag_mutability: immutable register: result @@ -488,10 +450,6 @@ - name: When configuring an existing immutable repository to be mutable in check mode ecs_ecr: name: '{{ ecr_name }}' - region: '{{ ec2_region }}' - ec2_access_key: '{{ec2_access_key}}' - ec2_secret_key: '{{ec2_secret_key}}' - security_token: '{{security_token}}' image_tag_mutability: mutable register: result check_mode: yes @@ -506,10 +464,6 @@ - name: When configuring an existing immutable repository to be mutable ecs_ecr: name: '{{ ecr_name }}' - region: '{{ ec2_region }}' - ec2_access_key: '{{ec2_access_key}}' - ec2_secret_key: '{{ec2_secret_key}}' - security_token: '{{security_token}}' image_tag_mutability: mutable register: result @@ -522,10 +476,6 @@ - name: When configuring an already mutable repository to be mutable ecs_ecr: name: '{{ ecr_name }}' - region: '{{ ec2_region }}' - ec2_access_key: '{{ec2_access_key}}' - ec2_secret_key: '{{ec2_secret_key}}' - security_token: '{{security_token}}' image_tag_mutability: mutable register: result @@ -534,10 +484,58 @@ that: - result is not changed + - name: enable scan on push in check mode + ecs_ecr: + name: '{{ ecr_name }}' + scan_on_push: yes + check_mode: yes + register: result + + - name: it should change + assert: + that: + - result is skipped + - result is changed + + - name: enable scan on push + ecs_ecr: + name: '{{ ecr_name }}' + scan_on_push: yes + register: result + + - name: it should change + assert: + that: + - result is changed + - result.repository.imageScanningConfiguration.scanOnPush + + - name: verify enable scan on push + ecs_ecr: + name: '{{ ecr_name }}' + scan_on_push: yes + register: result + + - name: it should not change + assert: + that: + - result is not changed + - result.repository.imageScanningConfiguration.scanOnPush + + - name: disable scan on push + ecs_ecr: + name: '{{ ecr_name }}' + scan_on_push: no + register: result + + - name: it should change + assert: + that: + - result is changed + - not result.repository.imageScanningConfiguration.scanOnPush + always: - name: Delete lingering ECR repository ecs_ecr: name: '{{ ecr_name }}' state: absent - <<: *aws_connection_info
ecr option scan_on_push ##### SUMMARY ecr module does not support `--image-scanning-configuration` option. ##### ISSUE TYPE - Feature Idea ##### COMPONENT NAME ecs_ecr
2020-09-30T08:56:52
ansible-collections/community.aws
259
ansible-collections__community.aws-259
[ "250" ]
d7e36178c674dc902af4925726a38483d7293f0a
diff --git a/plugins/modules/lightsail_static_ip.py b/plugins/modules/lightsail_static_ip.py new file mode 100644 --- /dev/null +++ b/plugins/modules/lightsail_static_ip.py @@ -0,0 +1,148 @@ +#!/usr/bin/python + +# -*- coding: utf-8 -*- +# Copyright: Ansible Project +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + +DOCUMENTATION = ''' +--- +module: lightsail_static_ip +version_added: 4.1.0 +short_description: Manage static IP addresses in AWS Lightsail +description: + - Manage static IP addresses in AWS Lightsail. +author: + - "Daniel Cotton (@danielcotton)" +options: + state: + description: + - Describes the desired state. + default: present + choices: ['present', 'absent'] + type: str + name: + description: Name of the static IP. + required: true + type: str +extends_documentation_fragment: + - amazon.aws.aws + - amazon.aws.ec2 +''' + + +EXAMPLES = ''' +- name: Provision a Lightsail static IP + community.aws.lightsail_static_ip: + state: present + name: my_static_ip + register: my_ip + +- name: Remove a static IP + community.aws.lightsail_static_ip: + state: absent + name: my_static_ip +''' + +RETURN = ''' +static_ip: + description: static_ipinstance data + returned: always + type: dict + sample: + arn: "arn:aws:lightsail:ap-southeast-2:184297340509:StaticIp/d8f47672-c261-4443-a484-4a2ec983db9a" + created_at: "2021-02-28T00:04:05.202000+10:30" + ip_address: "192.0.2.5" + is_attached: false + location: + availability_zone: all + region_name: ap-southeast-2 + name: "static_ip" + resource_type: StaticIp + support_code: "677585553206/192.0.2.5" +''' + +try: + import botocore +except ImportError: + # will be caught by AnsibleAWSModule + pass + +from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict + +from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule +from ansible_collections.amazon.aws.plugins.module_utils.core import is_boto3_error_code + + +def find_static_ip_info(module, client, static_ip_name, fail_if_not_found=False): + + try: + res = client.get_static_ip(staticIpName=static_ip_name) + except is_boto3_error_code('NotFoundException') as e: + if fail_if_not_found: + module.fail_json_aws(e) + return None + except botocore.exceptions.ClientError as e: # pylint: disable=duplicate-except + module.fail_json_aws(e) + return res['staticIp'] + + +def create_static_ip(module, client, static_ip_name): + + inst = find_static_ip_info(module, client, static_ip_name) + if inst: + module.exit_json(changed=False, static_ip=camel_dict_to_snake_dict(inst)) + else: + create_params = {'staticIpName': static_ip_name} + + try: + client.allocate_static_ip(**create_params) + except botocore.exceptions.ClientError as e: + module.fail_json_aws(e) + + inst = find_static_ip_info(module, client, static_ip_name, fail_if_not_found=True) + + module.exit_json(changed=True, static_ip=camel_dict_to_snake_dict(inst)) + + +def delete_static_ip(module, client, static_ip_name): + + inst = find_static_ip_info(module, client, static_ip_name) + if inst is None: + module.exit_json(changed=False, static_ip={}) + + changed = False + try: + client.release_static_ip(staticIpName=static_ip_name) + changed = True + except botocore.exceptions.ClientError as e: + module.fail_json_aws(e) + + module.exit_json(changed=changed, static_ip=camel_dict_to_snake_dict(inst)) + + +def main(): + + argument_spec = dict( + name=dict(type='str', required=True), + state=dict(type='str', default='present', choices=['present', 'absent']), + ) + + module = AnsibleAWSModule(argument_spec=argument_spec) + + client = module.client('lightsail') + + name = module.params.get('name') + state = module.params.get('state') + + if state == 'present': + create_static_ip(module, client, name) + elif state == 'absent': + delete_static_ip(module, client, name) + + +if __name__ == '__main__': + main()
diff --git a/tests/integration/targets/lightsail_static_ip/aliases b/tests/integration/targets/lightsail_static_ip/aliases new file mode 100644 --- /dev/null +++ b/tests/integration/targets/lightsail_static_ip/aliases @@ -0,0 +1 @@ +cloud/aws diff --git a/tests/integration/targets/lightsail_static_ip/defaults/main.yml b/tests/integration/targets/lightsail_static_ip/defaults/main.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/lightsail_static_ip/defaults/main.yml @@ -0,0 +1 @@ +static_ip_name: "{{ resource_prefix }}_static_ip" diff --git a/tests/integration/targets/lightsail_static_ip/tasks/main.yml b/tests/integration/targets/lightsail_static_ip/tasks/main.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/lightsail_static_ip/tasks/main.yml @@ -0,0 +1,96 @@ +--- + +- module_defaults: + group/aws: + aws_access_key: '{{ aws_access_key | default(omit) }}' + aws_secret_key: '{{ aws_secret_key | default(omit) }}' + security_token: '{{ security_token | default(omit) }}' + region: '{{ aws_region | default(omit) }}' + + block: + + # ==== Tests =================================================== + + - name: Create a new static IP + lightsail_static_ip: + name: "{{ static_ip_name }}" + register: result + + - assert: + that: + - result.changed == True + - '"static_ip" in result' + - '"arn" in result.static_ip' + - '"created_at" in result.static_ip' + - '"ip_address" in result.static_ip' + - '"is_attached" in result.static_ip' + - '"location" in result.static_ip' + - '"name" in result.static_ip' + - '"resource_type" in result.static_ip' + - '"support_code" in result.static_ip' + - result.static_ip.arn.startswith("arn:") + - result.static_ip.name == static_ip_name + - result.static_ip.resource_type == 'StaticIp' + - result.static_ip.is_attached == false + - result.static_ip.ip_address | ansible.utils.ipaddr + - '"availability_zone" in result.static_ip.location' + - '"region_name" in result.static_ip.location' + + - set_fact: + lightsail_ip_arn: '{{ result.static_ip.arn }}' + lightsail_ip_address: '{{ result.static_ip.ip_address }}' + + - name: Make sure create is idempotent + lightsail_static_ip: + name: "{{ static_ip_name }}" + register: result + + - assert: + that: + - result.changed == False + - '"static_ip" in result' + - '"arn" in result.static_ip' + - '"created_at" in result.static_ip' + - '"ip_address" in result.static_ip' + - '"is_attached" in result.static_ip' + - '"location" in result.static_ip' + - '"name" in result.static_ip' + - '"resource_type" in result.static_ip' + - '"support_code" in result.static_ip' + - result.static_ip.arn == lightsail_ip_arn + - result.static_ip.name == static_ip_name + - result.static_ip.resource_type == 'StaticIp' + - result.static_ip.is_attached == false + - result.static_ip.ip_address == lightsail_ip_address + - '"availability_zone" in result.static_ip.location' + - '"region_name" in result.static_ip.location' + + - name: Delete the static IP + lightsail_static_ip: + name: "{{ static_ip_name }}" + state: absent + register: result + + - assert: + that: + - result.changed == True + + - name: Make sure deletion is idempotent + lightsail_static_ip: + name: "{{ static_ip_name }}" + state: absent + register: result + + - assert: + that: + - result.changed == False + + # ==== Cleanup ==================================================== + + always: + + - name: Cleanup - delete static IP + lightsail_static_ip: + name: "{{ static_ip_name }}" + state: absent + ignore_errors: yes
Add a module to manage AWS Lightsail Static IPs <!--- Verify first that your feature was not already discussed on GitHub --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY Issue #174 requests adding the ability to manage firewall and static IP settings in a Lightsail VPS. I suggest that it may be beneficial to have a module that can manage static IPs for Lightsail (which are managed seperately from VMs). ##### ISSUE TYPE - Feature Idea ##### COMPONENT NAME community.aws.lightsail ##### ADDITIONAL INFORMATION In Lightsail, static IP addresses are managed separately from VPSes. You create and manage static IPs, and can attach them to a VPS as per #174. A module that can mange these IPs would be a prerequisite for end-to-end configuration management for Lightsail. I already have a basic version of this and am planning on submitting a PR in the next couple of weeks once it's cleaned up & tested Relevant API Documentation: * https://docs.aws.amazon.com/lightsail/2016-11-28/api-reference/API_AllocateStaticIp.html * https://docs.aws.amazon.com/lightsail/2016-11-28/api-reference/API_GetStaticIps.html * https://docs.aws.amazon.com/lightsail/2016-11-28/api-reference/API_ReleaseStaticIp.html Possible Playbook notation: ```yaml - name: Create a new Lightsail static IP community.aws.lightsail_static_ip: state: present name: static_ip_1 aws_access_key: XXXXXXXX ```
2020-10-12T12:46:50
ansible-collections/community.aws
273
ansible-collections__community.aws-273
[ "272" ]
d02886f4d8c54433e872b72e16fff717153c6c0e
diff --git a/plugins/modules/s3_sync.py b/plugins/modules/s3_sync.py --- a/plugins/modules/s3_sync.py +++ b/plugins/modules/s3_sync.py @@ -237,7 +237,10 @@ try: import botocore + from boto3.s3.transfer import TransferConfig + DEFAULT_CHUNK_SIZE = TransferConfig().multipart_chunksize except ImportError: + DEFAULT_CHUNK_SIZE = 5 * 1024 * 1024 pass # Handled by AnsibleAWSModule from ansible.module_utils._text import to_text @@ -270,10 +273,6 @@ # # You should have received a copy of the GNU General Public License # along with calculate_multipart_etag. If not, see <http://www.gnu.org/licenses/>. - -DEFAULT_CHUNK_SIZE = 5 * 1024 * 1024 - - def calculate_multipart_etag(source_path, chunk_size=DEFAULT_CHUNK_SIZE): """ calculates a multipart upload etag for amazon s3
diff --git a/tests/integration/targets/s3_sync/aliases b/tests/integration/targets/s3_sync/aliases new file mode 100644 --- /dev/null +++ b/tests/integration/targets/s3_sync/aliases @@ -0,0 +1,3 @@ +cloud/aws +shippable/aws/group1 + diff --git a/tests/integration/targets/s3_sync/files/test1.txt b/tests/integration/targets/s3_sync/files/test1.txt new file mode 100644 --- /dev/null +++ b/tests/integration/targets/s3_sync/files/test1.txt @@ -0,0 +1 @@ +test1 \ No newline at end of file diff --git a/tests/integration/targets/s3_sync/files/test2.yml b/tests/integration/targets/s3_sync/files/test2.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/s3_sync/files/test2.yml @@ -0,0 +1,2 @@ +--- +test2: example diff --git a/tests/integration/targets/s3_sync/files/test3.json b/tests/integration/targets/s3_sync/files/test3.json new file mode 100644 --- /dev/null +++ b/tests/integration/targets/s3_sync/files/test3.json @@ -0,0 +1,3 @@ +{ + "test3": "value" +} \ No newline at end of file diff --git a/tests/integration/targets/s3_sync/meta/main.yml b/tests/integration/targets/s3_sync/meta/main.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/s3_sync/meta/main.yml @@ -0,0 +1,3 @@ +dependencies: + - prepare_tests + - setup_ec2 diff --git a/tests/integration/targets/s3_sync/tasks/main.yml b/tests/integration/targets/s3_sync/tasks/main.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/s3_sync/tasks/main.yml @@ -0,0 +1,108 @@ +--- +- name: S3 bucket creation + collections: + - amazon.aws + - community.general + module_defaults: + group/aws: + aws_access_key: '{{ aws_access_key }}' + aws_secret_key: '{{ aws_secret_key }}' + security_token: '{{ security_token | default(omit) }}' + region: '{{ aws_region }}' + block: + # ============================================================ + - name: Create simple s3_bucket + s3_bucket: + name: "{{ resource_prefix }}-testbucket-ansible" + state: present + register: output + + - assert: + that: + - output.changed + - output.name == '{{ resource_prefix }}-testbucket-ansible' + - not output.requester_pays + # ============================================================ + - name: Prepare fixtures folder + file: + path: "{{ output_dir }}/s3_sync" + state: directory + mode: '0755' + + - name: Prepare files to sync + copy: + src: "{{ item }}" + dest: "{{ output_dir }}/s3_sync/{{ item }}" + mode: preserve + with_items: + - test1.txt + - test2.yml + - test3.json + + - name: Prepare file with size bigger than chunk size + shell: | + dd if=/dev/zero of=test4.txt bs=1M count=10 + args: + chdir: "{{ output_dir }}/s3_sync" + + - name: Sync files with remote bucket + s3_sync: + bucket: "{{ resource_prefix }}-testbucket-ansible" + file_root: "{{ output_dir }}/s3_sync" + register: output + - assert: + that: + - output is changed + + # ============================================================ + - name: Sync files already present + s3_sync: + bucket: "{{ resource_prefix }}-testbucket-ansible" + file_root: "{{ output_dir }}/s3_sync" + register: output + - assert: + that: + - output is not changed + + # ============================================================ + - name: Sync files with etag calculation + s3_sync: + bucket: "{{ resource_prefix }}-testbucket-ansible" + file_root: "{{ output_dir }}/s3_sync" + file_change_strategy: checksum + register: output + - assert: + that: + - output is not changed + + # ============================================================ + # DOCUMENTATION EXAMPLES + # ============================================================ + - name: all the options + s3_sync: + bucket: "{{ resource_prefix }}-testbucket-ansible" + file_root: "{{ output_dir }}/s3_sync" + mime_map: + .yml: application/text + .json: application/text + key_prefix: config_files/web + file_change_strategy: force + permission: public-read + cache_control: "public, max-age=31536000" + include: "*" + exclude: "*.txt,.*" + register: output + + - assert: + that: + - output is changed + + always: + - name: Ensure all buckets are deleted + s3_bucket: + name: "{{item}}" + state: absent + force: true + ignore_errors: yes + with_items: + - "{{ resource_prefix }}-testbucket-ansible"
s3_sync etag calculation is wrong because use hardcoded chunk_size <!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY The s3_sync module reports wrong etags compared to the one calculated from AWS S3 on server side. The etag algorithm is based on the chunk_size used during multipart upload. The s3_sync module uses the boto3 defaults for the S3 Transfer, but the function that calculates the local etags does not use those defaults (it uses an hardcoded value instead) ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME plugins/modules/s3_sync.py ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.10.2 config file = None configured module search path = ['/Users/chiesa/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /Users/chiesa/.local/pipx/venvs/ansible/lib/python3.8/site-packages/ansible executable location = /Users/chiesa/.local/bin/ansible python version = 3.8.2 (default, May 1 2020, 13:24:17) [Clang 11.0.3 (clang-1103.0.32.59)] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> no changes ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> Mac OS 10.15.7 ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> Upload some folder with s3_sync module and compare the local_etag calculated by the module with the S3 remote tags (calculated with the chunk_size used by boto3 - underlying library to tranfer the file) <!--- Paste example playbooks or commands between quotes below --> ```yaml ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> The local_etags of the file just uploaded should match the etags on S3 ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> The local_etags of the files just uploaded are mismatching S3 etags due to the wrong chunk_size hardcoded in the module: <!--- Paste verbatim command output between quotes --> ```paste below DEFAULT_CHUNK_SIZE = 5 * 1024 * 1024 ```
2020-10-21T07:53:18
ansible-collections/community.aws
283
ansible-collections__community.aws-283
[ "142" ]
d02886f4d8c54433e872b72e16fff717153c6c0e
diff --git a/plugins/modules/ec2_win_password.py b/plugins/modules/ec2_win_password.py --- a/plugins/modules/ec2_win_password.py +++ b/plugins/modules/ec2_win_password.py @@ -187,13 +187,13 @@ def ec2_win_password(module): decrypted = None if decrypted is None: - module.exit_json(win_password='', changed=False) + module.fail_json(msg="unable to decrypt password", win_password='', changed=False) else: if wait: elapsed = datetime.datetime.now() - start - module.exit_json(win_password=decrypted, changed=True, elapsed=elapsed.seconds) + module.exit_json(win_password=decrypted, changed=False, elapsed=elapsed.seconds) else: - module.exit_json(win_password=decrypted, changed=True) + module.exit_json(win_password=decrypted, changed=False) def main():
ec2_win_password returns success when it fails to decode the password ### SUMMARY An unsuccessful decode call returns: ``` ok: [localhost] => { "changed": false, "invocation": { "module_args": { [trimmed] } }, "win_password": "" } ``` I would expect it to return a failure state
Files identified in the description: None If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> @fd-davidtulloh: Greetings! Thanks for taking the time to open this issue. In order for the community to handle your issue effectively, we need a bit more information. Here are the items we could not find in your description: - issue type - ansible version - component name Please set the description of this issue with this template: https://raw.githubusercontent.com/ansible/ansible/devel/.github/ISSUE_TEMPLATE/bug_report.md [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: issue_missing_data ---> @fd-davidtulloh I am working on this issue
2020-10-29T10:33:11
ansible-collections/community.aws
284
ansible-collections__community.aws-284
[ "264" ]
d02886f4d8c54433e872b72e16fff717153c6c0e
diff --git a/plugins/modules/ecs_taskdefinition.py b/plugins/modules/ecs_taskdefinition.py --- a/plugins/modules/ecs_taskdefinition.py +++ b/plugins/modules/ecs_taskdefinition.py @@ -47,7 +47,7 @@ - A list of containers definitions. required: False type: list - elements: str + elements: dict network_mode: description: - The Docker networking mode to use for the containers in the task. @@ -321,7 +321,7 @@ def main(): family=dict(required=False, type='str'), revision=dict(required=False, type='int'), force_create=dict(required=False, default=False, type='bool'), - containers=dict(required=False, type='list', elements='str'), + containers=dict(required=False, type='list', elements='dict'), network_mode=dict(required=False, default='bridge', choices=['default', 'bridge', 'host', 'none', 'awsvpc'], type='str'), task_role_arn=dict(required=False, default='', type='str'), execution_role_arn=dict(required=False, default='', type='str'),
Wrong datatype in ecs_taskdefinition.containers https://github.com/ansible-collections/community.aws/blob/6eab8b0c0e805fe8881a834f4f1329193396fd0a/plugins/modules/ecs_taskdefinition.py#L324 In current version argument_spec is following: `containers=dict(required=False, type='list', elements='str'),` This causes dicts inside container list to be converted to strings. If we select some example from documentation ... ``` - name: Create task definition community.aws.ecs_taskdefinition: family: nginx containers: - name: nginx essential: true image: "nginx" portMappings: - containerPort: 8080 hostPort: 8080 cpu: 512 memory: 1024 state: present ``` ... then running it causes following exception: ``` File "[..]/debug_dir/ansible_collections/community/aws/plugins/modules/ecs_taskdefinition.py", line 353, in main for environment in container.get('environment', []): AttributeError: 'str' object has no attribute 'get' ``` To get examples (and container section) working, argument spec needs to be changed to following: `containers=dict(required=False, type='list', elements='dict'),`
Yes, it seems to be an issue indeed. The last time I used it was not in the community edition, but the built-in ecs_taskdefinition.py, in which it worked: https://github.com/ansible/ansible/blob/stable-2.4/lib/ansible/modules/cloud/amazon/ecs_taskdefinition.py As you can see from there the elements were not forced to be converted into any data format. Now the formatting is forced and it seems that they shouldn't be forced to be strings, but rather dicts if any as the reporter suggested. Is there anything that we're missing here? #251 https://github.com/ansible-collections/amazon.aws/pull/184 Ah no... the fix is easy...and not related by what I've linked. `element=str` is just wrong.
2020-10-30T12:31:46
ansible-collections/community.aws
286
ansible-collections__community.aws-286
[ "265" ]
d02886f4d8c54433e872b72e16fff717153c6c0e
diff --git a/plugins/modules/ecs_service.py b/plugins/modules/ecs_service.py --- a/plugins/modules/ecs_service.py +++ b/plugins/modules/ecs_service.py @@ -52,7 +52,7 @@ - The list of ELBs defined for this service. required: false type: list - elements: str + elements: dict desired_count: description: - The count of how many instances of the service. @@ -648,7 +648,7 @@ def main(): name=dict(required=True, type='str'), cluster=dict(required=False, type='str'), task_definition=dict(required=False, type='str'), - load_balancers=dict(required=False, default=[], type='list', elements='str'), + load_balancers=dict(required=False, default=[], type='list', elements='dict'), desired_count=dict(required=False, type='int'), client_token=dict(required=False, default='', type='str'), role=dict(required=False, default='', type='str'),
ecs_service load_balancers not working with container port <!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> The ecs_service module doesn't work as expected when a load balancer is defined with a container port. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> ecs_service.py ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below v2.10.1 ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> Docker inside alpine image. ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> Just execute the following task and it should fail. <!--- Paste example playbooks or commands between quotes below --> ```yaml - name: "Criando/atualizando serviço {{ service.name }}" community.aws.ecs_service: aws_access_key: "{{ ec2_access_key }}" aws_secret_key: "{{ ec2_secret_key }}" state: present force_new_deployment: yes name: "{{ service.name }}" cluster: "{{ service.cluster }}" region: "{{ service.region }}" task_definition: "{{ service.task }}" desired_count: 1 #service.desired_count launch_type: "{{ service.launch_type }}" load_balancers: - targetGroupArn: "{{ service.alb_arn_tg }}" containerName: "{{ service.http_container }}" containerPort: 80 network_configuration: subnets: - "{{ service.subnet }}" security_groups: - "{{ service.security_group }}" ``` My var file is here, in case you're wondering: ```yaml name: "Service_Site_Plataforma" cluster: "openbox-plataforma" region: "us-east-1" task: "openbox-plataforma-prod:11" desired_count: 1 launch_type: "FARGATE" alb_arn_tg: "arn:aws:elasticloadbalancing:us-east-1:880610698981:targetgroup/ECS-site/5f7722edab69f6a3" http_container: "nginx-server" http_container_port: 80 vpc: "vpc-0813fd6181f0580a4" subnet: "subnet-051274368a7c79e66" security_group: "sg-08e8273b3b2959ada" ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> It should work. ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> It fails with the following error message: <!--- Paste verbatim command output between quotes --> ```paste below TASK [ecs-services : Criando/atualizando serviço Service_Site_Plataforma] ****** task path: /ansible/roles/ecs-services/tasks/ecs-service.yml:1 <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: root <127.0.0.1> EXEC /bin/sh -c 'echo ~root && sleep 0' <127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /root/.ansible/tmp `"&& mkdir "` echo /root/.ansible/tmp/ansible-tmp-1602784189.4565227-171-150065538834260 `" && echo ansible-tmp-1602784189.4565227-171-150065538834260="` echo /root/.ansible/tmp/ansible-tmp-1602784189.4565227-171-150065538834260 `" ) && sleep 0' Using module file /root/.ansible/collections/ansible_collections/community/aws/plugins/modules/ecs_service.py <127.0.0.1> PUT /root/.ansible/tmp/ansible-local-178n3qw9g/tmpg7h1z76m TO /root/.ansible/tmp/ansible-tmp-1602784189.4565227-171-150065538834260/AnsiballZ_ecs_service.py <127.0.0.1> EXEC /bin/sh -c 'chmod u+x /root/.ansible/tmp/ansible-tmp-1602784189.4565227-171-150065538834260/ /root/.ansible/tmp/ansible-tmp-1602784189.4565227-171-150065538834260/AnsiballZ_ecs_service.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c '/usr/local/bin/python /root/.ansible/tmp/ansible-tmp-1602784189.4565227-171-150065538834260/AnsiballZ_ecs_service.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'rm -f -r /root/.ansible/tmp/ansible-tmp-1602784189.4565227-171-150065538834260/ > /dev/null 2>&1 && sleep 0' The full traceback is: Traceback (most recent call last): File "/root/.ansible/tmp/ansible-tmp-1602784189.4565227-171-150065538834260/AnsiballZ_ecs_service.py", line 102, in <module> _ansiballz_main() File "/root/.ansible/tmp/ansible-tmp-1602784189.4565227-171-150065538834260/AnsiballZ_ecs_service.py", line 94, in _ansiballz_main invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS) File "/root/.ansible/tmp/ansible-tmp-1602784189.4565227-171-150065538834260/AnsiballZ_ecs_service.py", line 40, in invoke_module runpy.run_module(mod_name='ansible_collections.community.aws.plugins.modules.ecs_service', init_globals=None, run_name='__main__', alter_sys=True) File "/usr/local/lib/python3.6/runpy.py", line 205, in run_module return _run_module_code(code, init_globals, run_name, mod_spec) File "/usr/local/lib/python3.6/runpy.py", line 96, in _run_module_code mod_name, mod_spec, pkg_name, script_name) File "/usr/local/lib/python3.6/runpy.py", line 85, in _run_code exec(code, run_globals) File "/tmp/ansible_community.aws.ecs_service_payload_a3wwyvdm/ansible_community.aws.ecs_service_payload.zip/ansible_collections/community/aws/plugins/modules/ecs_service.py", line 860, in <module> File "/tmp/ansible_community.aws.ecs_service_payload_a3wwyvdm/ansible_community.aws.ecs_service_payload.zip/ansible_collections/community/aws/plugins/modules/ecs_service.py", line 754, in main TypeError: string indices must be integers fatal: [localhost]: FAILED! => { "changed": false, "module_stderr": "Traceback (most recent call last):\n File \"/root/.ansible/tmp/ansible-tmp-1602784189.4565227-171-150065538834260/AnsiballZ_ecs_service.py\", line 102, in <module>\n _ansiballz_main()\n File \"/root/.ansible/tmp/ansible-tmp-1602784189.4565227-171-150065538834260/AnsiballZ_ecs_service.py\", line 94, in _ansiballz_main\n invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n File \"/root/.ansible/tmp/ansible-tmp-1602784189.4565227-171-150065538834260/AnsiballZ_ecs_service.py\", line 40, in invoke_module\n runpy.run_module(mod_name='ansible_collections.community.aws.plugins.modules.ecs_service', init_globals=None, run_name='__main__', alter_sys=True)\n File \"/usr/local/lib/python3.6/runpy.py\", line 205, in run_module\n return _run_module_code(code, init_globals, run_name, mod_spec)\n File \"/usr/local/lib/python3.6/runpy.py\", line 96, in _run_module_code\n mod_name, mod_spec, pkg_name, script_name)\n File \"/usr/local/lib/python3.6/runpy.py\", line 85, in _run_code\n exec(code, run_globals)\n File \"/tmp/ansible_community.aws.ecs_service_payload_a3wwyvdm/ansible_community.aws.ecs_service_payload.zip/ansible_collections/community/aws/plugins/modules/ecs_service.py\", line 860, in <module>\n File \"/tmp/ansible_community.aws.ecs_service_payload_a3wwyvdm/ansible_community.aws.ecs_service_payload.zip/ansible_collections/community/aws/plugins/modules/ecs_service.py\", line 754, in main\nTypeError: string indices must be integers\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1 } ```
somewhere is a type error > TypeError: string indices must be integers So somehwere you're refering to a position of an array? But I cannot find it adhoc. Basically we do the same all day... ```yml - name: update or create ecs service for ecs_service: state: present region: "{{ region }}" name: "{{ SERVICE }}" cluster: "{{ CLUSTER }}" task_definition: "{{ TASK_NAME }}:{{ output.taskdefinition.revision }}" desired_count: "{{ DESIRED_COUNT }}" launch_type: EC2 load_balancers: - targetGroupArn: "{{ tg.target_groups[0].target_group_arn }}" containerName: website containerPort: 80 deployment_configuration: minimum_healthy_percent: 50 ``` #264 same error. `element` type is wrong for load _balancers.
2020-10-30T13:09:48
ansible-collections/community.aws
340
ansible-collections__community.aws-340
[ "338" ]
932263d415ac7b16f06d4c26f2c960e4ebf3af01
diff --git a/plugins/modules/ecs_service.py b/plugins/modules/ecs_service.py --- a/plugins/modules/ecs_service.py +++ b/plugins/modules/ecs_service.py @@ -12,16 +12,16 @@ version_added: 1.0.0 short_description: Create, terminate, start or stop a service in ECS description: - - Creates or terminates ECS. services. + - Creates or terminates ECS services. notes: - The service role specified must be assumable. (i.e. have a trust relationship for the ecs service, ecs.amazonaws.com) - For details of the parameters and returns see U(https://boto3.readthedocs.io/en/latest/reference/services/ecs.html). - An IAM role must have been previously created. author: - - "Mark Chance (@Java1Guy)" - - "Darek Kaczynski (@kaczynskid)" - - "Stephane Maarek (@simplesteph)" - - "Zac Blazic (@zacblazic)" + - "Mark Chance (@Java1Guy)" + - "Darek Kaczynski (@kaczynskid)" + - "Stephane Maarek (@simplesteph)" + - "Zac Blazic (@zacblazic)" options: state: description: @@ -46,11 +46,15 @@ description: - The task definition the service will run. - This parameter is required when I(state=present). + - This parameter is ignored when updating a service with a C(CODE_DEPLOY) deployment controller in which case + the task definition is managed by Code Pipeline and cannot be updated. required: false type: str load_balancers: description: - The list of ELBs defined for this service. + - Load balancers for an existing service cannot be updated, and it is an error to do so. + - When the deployment controller is CODE_DEPLOY changes to this value are simply ignored, and do not cause an error. required: false type: list elements: dict @@ -90,6 +94,17 @@ required: false type: bool default: false + deployment_controller: + description: + - The deployment controller to use for the service. If no deploymenet controller is specified, the ECS controller is used. + required: false + version_added: 4.1.0 + type: dict + suboptions: + type: + type: str + choices: ["ECS", "CODE_DEPLOY", "EXTERNAL"] + description: The deployment controller type to use. deployment_configuration: description: - Optional parameters that control the deployment_configuration. @@ -238,9 +253,8 @@ default: false version_added: 4.1.0 extends_documentation_fragment: -- amazon.aws.aws -- amazon.aws.ec2 - + - amazon.aws.aws + - amazon.aws.ec2 ''' EXAMPLES = r''' @@ -590,6 +604,10 @@ ''' import time +DEPLOYMENT_CONTROLLER_TYPE_MAP = { + 'type': 'str', +} + DEPLOYMENT_CONFIGURATION_TYPE_MAP = { 'maximum_percent': 'int', 'minimum_healthy_percent': 'int', @@ -664,7 +682,8 @@ def is_matching_service(self, expected, existing): # but the user is just entering # ansible-fargate-nginx:3 if expected['task_definition'] != existing['taskDefinition'].split('/')[-1]: - return False + if existing['deploymentController']['type'] != 'CODE_DEPLOY': + return False if expected.get('health_check_grace_period_seconds'): if expected.get('health_check_grace_period_seconds') != existing.get('healthCheckGracePeriodSeconds'): @@ -682,7 +701,7 @@ def is_matching_service(self, expected, existing): return True def create_service(self, service_name, cluster_name, task_definition, load_balancers, - desired_count, client_token, role, deployment_configuration, + desired_count, client_token, role, deployment_controller, deployment_configuration, placement_constraints, placement_strategy, health_check_grace_period_seconds, network_configuration, service_registries, launch_type, platform_version, scheduling_strategy, capacity_provider_strategy): @@ -699,6 +718,8 @@ def create_service(self, service_name, cluster_name, task_definition, load_balan ) if network_configuration: params['networkConfiguration'] = network_configuration + if deployment_controller: + params['deploymentController'] = deployment_controller if launch_type: params['launchType'] = launch_type if platform_version: @@ -786,6 +807,7 @@ def main(): repeat=dict(required=False, type='int', default=10), force_new_deployment=dict(required=False, default=False, type='bool'), force_deletion=dict(required=False, default=False, type='bool'), + deployment_controller=dict(required=False, default={}, type='dict'), deployment_configuration=dict(required=False, default={}, type='dict'), wait=dict(required=False, default=False, type='bool'), placement_constraints=dict( @@ -851,6 +873,11 @@ def main(): else: network_configuration = None + deployment_controller = map_complex_type(module.params['deployment_controller'], + DEPLOYMENT_CONTROLLER_TYPE_MAP) + + deploymentController = snake_dict_to_camel_dict(deployment_controller) + deployment_configuration = map_complex_type(module.params['deployment_configuration'], DEPLOYMENT_CONFIGURATION_TYPE_MAP) @@ -912,12 +939,19 @@ def main(): if 'capacityProviderStrategy' in existing.keys(): module.fail_json(msg="It is not possible to change an existing service from capacity_provider_strategy to launch_type.") if (existing['loadBalancers'] or []) != loadBalancers: - module.fail_json(msg="It is not possible to update the load balancers of an existing service") + if existing['deploymentController']['type'] != 'CODE_DEPLOY': + module.fail_json(msg="It is not possible to update the load balancers of an existing service") + + if existing.get('deploymentController', {}).get('type', None) == 'CODE_DEPLOY': + task_definition = '' + network_configuration = [] + else: + task_definition = module.params['task_definition'] # update required response = service_mgr.update_service(module.params['name'], module.params['cluster'], - module.params['task_definition'], + task_definition, module.params['desired_count'], deploymentConfiguration, network_configuration, @@ -935,6 +969,7 @@ def main(): module.params['desired_count'], clientToken, role, + deploymentController, deploymentConfiguration, module.params['placement_constraints'], module.params['placement_strategy'],
community.aws.ecs_service should support deploymentController parameter ##### SUMMARY [More on deploymentController](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service_definition_parameters.html) parameter. [What this does](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/deployment-types.html): An Amazon ECS deployment type determines the deployment strategy that your service uses. There are three deployment types: rolling update, blue/green, and external. ##### COMPONENT NAME community.aws.ecs_service
2020-12-23T00:17:13
ansible-collections/community.aws
359
ansible-collections__community.aws-359
[ "357" ]
0412f0026eb80a27de60cd8d97040d8af373a7ac
diff --git a/plugins/modules/ec2_vpc_route_table.py b/plugins/modules/ec2_vpc_route_table.py --- a/plugins/modules/ec2_vpc_route_table.py +++ b/plugins/modules/ec2_vpc_route_table.py @@ -492,20 +492,16 @@ def ensure_routes(connection=None, module=None, route_table=None, route_specs=No for route_spec in route_specs_to_recreate: try: - connection.replace_route( - aws_retry=True, - RouteTableId=route_table['RouteTableId'], - **route_spec) + connection.replace_route(aws_retry=True, RouteTableId=route_table['RouteTableId'], **route_spec) except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: module.fail_json_aws(e, msg="Couldn't recreate route") for route_spec in route_specs_to_create: try: - connection.create_route( - aws_retry=True, - RouteTableId=route_table['RouteTableId'], - **route_spec) - except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: + connection.create_route(aws_retry=True, RouteTableId=route_table['RouteTableId'], **route_spec) + except is_boto3_error_code('RouteAlreadyExists'): + changed = False + except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: # pylint: disable=duplicate-except module.fail_json_aws(e, msg="Couldn't create route") return {'changed': bool(changed)}
ec2_vpc_route_table not idempotent - failing on adding already existing route This issue was already reported in the old Ansible repo here https://github.com/ansible/ansible/issues/59863 but wasn't migrated over. ##### SUMMARY when rerunning ec2_vpc_route_table module with the same route listing if fails with ``` botocore.exceptions.ClientError: An error occurred (RouteAlreadyExists) when calling the CreateRoute operation: The route identified by 10.31.0.0/16 already exists. ``` IMO the module should catch that error and should just return `changed: false`. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME ec2_vpc_route_table ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.9.1 config file = ~/be-infrastructure/ansible.cfg configured module search path = ['~/be-infrastructure/library'] ansible python module location = ~/.local/lib/python3.8/site-packages/ansible executable location = ~/.local/bin/ansible python version = 3.8.5 (default, Jul 28 2020, 12:59:40) [GCC 9.3.0] ``` Couldn't test with newer version yet. However I would assume that this still happens in newer version, as the ticket in the old repo was open till the end and the module hasn't seen any code changes since the migration as far I can see. See https://github.com/ansible-collections/community.aws/commits/main/plugins/modules/ec2_vpc_route_table.py ##### ADDTIONAL INFORMATION For other details just look up https://github.com/ansible/ansible/issues/59863
PR that attempts to fix this https://github.com/ansible-collections/community.aws/pull/359 cc @jillr @s-hertel @tremble @willthames @wimnat [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify --->
2021-01-14T11:52:15
ansible-collections/community.aws
372
ansible-collections__community.aws-372
[ "345" ]
d3e57bf2cc3fcc62f1fafda853c3d630ee656db8
diff --git a/plugins/modules/ec2_vpc_nat_gateway.py b/plugins/modules/ec2_vpc_nat_gateway.py --- a/plugins/modules/ec2_vpc_nat_gateway.py +++ b/plugins/modules/ec2_vpc_nat_gateway.py @@ -48,6 +48,19 @@ required: false default: false type: bool + tags: + description: + - A dict of tags to apply to the internet gateway. + - To remove all tags set I(tags={}) and I(purge_tags=true). + aliases: [ 'resource_tags' ] + type: dict + version_added: 1.4.0 + purge_tags: + description: + - Remove tags not listed in I(tags). + type: bool + default: true + version_added: 1.4.0 release_eip: description: - Deallocate the EIP from the VPC. @@ -153,6 +166,17 @@ wait: yes wait_timeout: 300 region: ap-southeast-2 + +- name: Create new nat gateway using an allocation-id and tags. + community.aws.ec2_vpc_nat_gateway: + state: present + subnet_id: subnet-12345678 + allocation_id: eipalloc-12345678 + region: ap-southeast-2 + tags: + Tag1: tag1 + Tag2: tag2 + register: new_nat_gateway ''' RETURN = ''' @@ -176,6 +200,13 @@ returned: In all cases. type: str sample: "available" +tags: + description: The tags associated the VPC NAT Gateway. + type: dict + returned: When tags are present. + sample: + tags: + "Ansible": "Test" vpc_id: description: id of the VPC. returned: In all cases. @@ -204,11 +235,17 @@ except ImportError: pass # Handled by AnsibleAWSModule -from ansible.module_utils._text import to_native + +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AWSRetry from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule from ansible_collections.amazon.aws.plugins.module_utils.core import is_boto3_error_code from ansible_collections.amazon.aws.plugins.module_utils.ec2 import camel_dict_to_snake_dict - +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import ansible_dict_to_boto3_filter_list +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import ansible_dict_to_boto3_tag_list +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import boto3_tag_list_to_ansible_dict +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import compare_aws_tags +from ansible.module_utils.six import string_types +from ansible.module_utils._text import to_native DRY_RUN_GATEWAYS = [ { @@ -451,6 +488,7 @@ def gateway_in_subnet_exists(client, subnet_id, allocation_id=None, allocation_id_exists = False gateways = [] states = ['available', 'pending'] + gws_retrieved, err_msg, gws = ( get_nat_gateways( client, subnet_id, states=states, check_mode=check_mode @@ -609,7 +647,7 @@ def release_address(client, allocation_id, check_mode=False): return ip_released, err_msg -def create(client, subnet_id, allocation_id, client_token=None, +def create(client, module, subnet_id, allocation_id, tags, purge_tags, client_token=None, wait=False, wait_timeout=0, if_exist_do_not_create=False, check_mode=False): """Create an Amazon NAT Gateway. @@ -680,7 +718,6 @@ def create(client, subnet_id, allocation_id, client_token=None, result['create_time'] = datetime.datetime.utcnow() result['nat_gateway_addresses'][0]['allocation_id'] = allocation_id result['subnet_id'] = subnet_id - success = True changed = True create_time = result['create_time'].replace(tzinfo=None) @@ -689,15 +726,18 @@ def create(client, subnet_id, allocation_id, client_token=None, elif wait: success, err_msg, result = ( wait_for_status( - client, wait_timeout, result['nat_gateway_id'], 'available', - check_mode=check_mode + client, wait_timeout, result['nat_gateway_id'], + 'available', check_mode=check_mode ) ) if success: err_msg = ( 'NAT gateway {0} created'.format(result['nat_gateway_id']) ) - + result['tags'], tags_update_exists = ensure_tags( + client, module, nat_gw_id=result['nat_gateway_id'], tags=tags, + purge_tags=purge_tags, check_mode=check_mode + ) except is_boto3_error_code('IdempotentParameterMismatch'): err_msg = ( 'NAT Gateway does not support update and token has already been provided: ' + err_msg @@ -714,7 +754,7 @@ def create(client, subnet_id, allocation_id, client_token=None, return success, changed, err_msg, result -def pre_create(client, subnet_id, allocation_id=None, eip_address=None, +def pre_create(client, module, subnet_id, tags, purge_tags, allocation_id=None, eip_address=None, if_exist_do_not_create=False, wait=False, wait_timeout=0, client_token=None, check_mode=False): """Create an Amazon NAT Gateway. @@ -772,14 +812,18 @@ def pre_create(client, subnet_id, allocation_id=None, eip_address=None, results = list() if not allocation_id and not eip_address: - existing_gateways, allocation_id_exists = ( - gateway_in_subnet_exists(client, subnet_id, check_mode=check_mode) - ) - + existing_gateways, allocation_id_exists = (gateway_in_subnet_exists(client, subnet_id, check_mode=check_mode)) if len(existing_gateways) > 0 and if_exist_do_not_create: + results = existing_gateways[0] + results['tags'], tags_update_exists = ensure_tags(client, module, results['nat_gateway_id'], tags, purge_tags, check_mode) + + if tags_update_exists: + success = True + changed = True + return success, changed, err_msg, results + success = True changed = False - results = existing_gateways[0] err_msg = ( 'NAT Gateway {0} already exists in subnet_id {1}' .format( @@ -805,16 +849,22 @@ def pre_create(client, subnet_id, allocation_id=None, eip_address=None, success = False changed = False return success, changed, err_msg, dict() - existing_gateways, allocation_id_exists = ( gateway_in_subnet_exists( client, subnet_id, allocation_id, check_mode=check_mode ) ) + if len(existing_gateways) > 0 and (allocation_id_exists or if_exist_do_not_create): + results = existing_gateways[0] + results['tags'], tags_update_exists = ensure_tags(client, module, results['nat_gateway_id'], tags, purge_tags, check_mode) + if tags_update_exists: + success = True + changed = True + return success, changed, err_msg, results + success = True changed = False - results = existing_gateways[0] err_msg = ( 'NAT Gateway {0} already exists in subnet_id {1}' .format( @@ -824,7 +874,7 @@ def pre_create(client, subnet_id, allocation_id=None, eip_address=None, return success, changed, err_msg, results success, changed, err_msg, results = create( - client, subnet_id, allocation_id, client_token, + client, module, subnet_id, allocation_id, tags, purge_tags, client_token, wait, wait_timeout, if_exist_do_not_create, check_mode=check_mode ) @@ -919,8 +969,7 @@ def remove(client, nat_gateway_id, wait=False, wait_timeout=0, if release_eip: eip_released, eip_err = ( - release_address(client, allocation_id, check_mode) - ) + release_address(client, allocation_id, check_mode)) if not eip_released: err_msg = ( "{0}: Failed to release EIP {1}: {2}" @@ -931,6 +980,64 @@ def remove(client, nat_gateway_id, wait=False, wait_timeout=0, return success, changed, err_msg, results +def ensure_tags(client, module, nat_gw_id, tags, purge_tags, check_mode): + final_tags = [] + changed = False + + filters = ansible_dict_to_boto3_filter_list({'resource-id': nat_gw_id, 'resource-type': 'natgateway'}) + cur_tags = None + try: + cur_tags = client.describe_tags(aws_retry=True, Filters=filters) + except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: + module.fail_json_aws(e, 'Couldnt describe tags') + if tags is None: + return boto3_tag_list_to_ansible_dict(cur_tags['Tags']), changed + + to_update, to_delete = compare_aws_tags(boto3_tag_list_to_ansible_dict(cur_tags.get('Tags')), tags, purge_tags) + final_tags = boto3_tag_list_to_ansible_dict(cur_tags.get('Tags')) + + if to_update: + try: + if check_mode: + # update tags + final_tags.update(to_update) + else: + client.create_tags( + aws_retry=True, + Resources=[nat_gw_id], + Tags=ansible_dict_to_boto3_tag_list(to_update) + ) + + changed = True + except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: + module.fail_json_aws(e, "Couldn't create tags") + + if to_delete: + try: + if check_mode: + # update tags + for key in to_delete: + del final_tags[key] + else: + tags_list = [] + for key in to_delete: + tags_list.append({'Key': key}) + + client.delete_tags(aws_retry=True, Resources=[nat_gw_id], Tags=tags_list) + + changed = True + except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: + module.fail_json_aws(e, "Couldn't delete tags") + + if not check_mode and (to_update or to_delete): + try: + response = client.describe_tags(aws_retry=True, Filters=filters) + final_tags = boto3_tag_list_to_ansible_dict(response.get('Tags')) + except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: + module.fail_json_aws(e, "Couldn't describe tags") + return final_tags, changed + + def main(): argument_spec = dict( subnet_id=dict(type='str'), @@ -943,6 +1050,8 @@ def main(): release_eip=dict(type='bool', default=False), nat_gateway_id=dict(type='str'), client_token=dict(type='str'), + tags=dict(required=False, type='dict', aliases=['resource_tags']), + purge_tags=dict(default=True, type='bool'), ) module = AnsibleAWSModule( argument_spec=argument_spec, @@ -965,9 +1074,11 @@ def main(): release_eip = module.params.get('release_eip') client_token = module.params.get('client_token') if_exist_do_not_create = module.params.get('if_exist_do_not_create') + tags = module.params.get('tags') + purge_tags = module.params.get('purge_tags') try: - client = module.client('ec2') + client = module.client('ec2', retry_decorator=AWSRetry.jittered_backoff()) except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: module.fail_json_aws(e, msg='Failed to connect to AWS') @@ -977,7 +1088,7 @@ def main(): if state == 'present': success, changed, err_msg, results = ( pre_create( - client, subnet_id, allocation_id, eip_address, + client, module, subnet_id, tags, purge_tags, allocation_id, eip_address, if_exist_do_not_create, wait, wait_timeout, client_token, check_mode=check_mode )
diff --git a/tests/integration/targets/ec2_vpc_nat_gateway/defaults/main.yml b/tests/integration/targets/ec2_vpc_nat_gateway/defaults/main.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/ec2_vpc_nat_gateway/defaults/main.yml @@ -0,0 +1,5 @@ +--- +vpc_name: "{{ resource_prefix }}-vpc" +vpc_seed: "{{ resource_prefix }}" +vpc_cidr: "10.0.0.0/16" +subnet_cidr: "10.0.{{ 256 | random(seed=vpc_seed) }}.0/24" diff --git a/tests/integration/targets/ec2_vpc_nat_gateway/tasks/main.yml b/tests/integration/targets/ec2_vpc_nat_gateway/tasks/main.yml --- a/tests/integration/targets/ec2_vpc_nat_gateway/tasks/main.yml +++ b/tests/integration/targets/ec2_vpc_nat_gateway/tasks/main.yml @@ -3,80 +3,546 @@ # They take advantage of hard-coded results within the module to trigger both changed and unchanged responses. # They were migrated to maintain test coverage while removing unit tests that depended on use of TaskQueueManager. -- name: Create new nat gateway with eip allocation-id - ec2_vpc_nat_gateway: - subnet_id: subnet-12345678 - allocation_id: eipalloc-12345678 - wait: yes - region: us-west-2 - register: nat_gateway - check_mode: yes - -- assert: - that: - - nat_gateway.changed - -- name: Create new nat gateway with eip allocation-id - ec2_vpc_nat_gateway: - subnet_id: subnet-123456789 - allocation_id: eipalloc-1234567 - wait: yes - region: us-west-2 - register: nat_gateway - check_mode: yes - -- assert: - that: - - not nat_gateway.changed - -- name: Create new nat gateway with eip address - ec2_vpc_nat_gateway: - subnet_id: subnet-12345678 - eip_address: 55.55.55.55 - wait: yes - region: us-west-2 - register: nat_gateway - check_mode: yes - -- assert: - that: - - nat_gateway.changed - -- name: Create new nat gateway with eip address - ec2_vpc_nat_gateway: - subnet_id: subnet-123456789 - eip_address: 55.55.55.55 - wait: yes - region: us-west-2 - register: nat_gateway - check_mode: yes - -- assert: - that: - - not nat_gateway.changed - -- name: Create new nat gateway only if one does not exist already - ec2_vpc_nat_gateway: - if_exist_do_not_create: yes - subnet_id: subnet-123456789 - wait: yes - region: us-west-2 - register: nat_gateway - check_mode: yes - -- assert: - that: - - not nat_gateway.changed - -- name: Delete Nat Gateway - ec2_vpc_nat_gateway: - nat_gateway_id: nat-123456789 - state: absent - wait: yes - region: us-west-2 - register: nat_gateway - check_mode: yes - -- assert: - that: - - nat_gateway.changed +--- +# ============================================================ +# Known issues: +# +# `check_mode` is not working correctly due to the hard-coded DRY_RUN_GATEWAY (module code). The values passed here, +# when CHECK_MODE is used, don't correspond to those used for the DRY_RUN_GATEWAY and all test +# (except when the NAT gateway is created for the first time) fail. +# +# `Create new NAT gateway with eip address` - when the task is run for the first time, do we expect changed=true? +# As we use the same EIP, I think changed should be false (if this is correct, lines 194-218 are redundant and +# lines 177 and 190 should report `not create_ngw.changed`). +# ============================================================ + +- name: ec2_vpc_nat_gateway tests + module_defaults: + group/aws: + aws_access_key: "{{ aws_access_key }}" + aws_secret_key: "{{ aws_secret_key }}" + security_token: "{{ security_token | default(omit) }}" + region: "{{ aws_region }}" + collections: + - amazon.aws + + block: + + # ============================================================ + - name: Create a VPC + ec2_vpc_net: + name: "{{ vpc_name }}" + state: present + cidr_block: "{{ vpc_cidr }}" + register: vpc_result + + - name: Assert success + assert: + that: + - vpc_result is successful + + - name: "set fact: VPC ID" + set_fact: + vpc_id: "{{ vpc_result.vpc.id }}" + + # ============================================================ + - name: Allocate a new EIP + ec2_eip: + in_vpc: true + reuse_existing_ip_allowed: true + tag_name: FREE + register: eip_result + + - name: Assert success + assert: + that: + - eip_result is successful + + - name: "set fact: EIP allocation ID and EIP public IP" + set_fact: + eip_address: "{{ eip_result.public_ip }}" + allocation_id: "{{ eip_result.allocation_id }}" + + + # ============================================================ + - name: Create subnet and associate to the VPC + ec2_vpc_subnet: + state: present + vpc_id: "{{ vpc_id }}" + cidr: "{{ subnet_cidr }}" + register: subnet_result + + - name: Assert success + assert: + that: + - subnet_result is successful + + - name: "set fact: VPC subnet ID" + set_fact: + subnet_id: "{{ subnet_result.subnet.id }}" + + + # ============================================================ + - name: Search for NAT gateways by subnet - no matches + ec2_vpc_nat_gateway_info: + filters: + subnet-id: "{{ subnet_id }}" + state: ['available'] + register: existing_ngws + retries: 10 + until: existing_ngws is not failed + + - name: Assert no NAT gateway found + assert: + that: + - existing_ngws is successful + - (existing_ngws.result|length) == 0 + + + + # ============================================================ + - name: Create IGW + ec2_vpc_igw: + vpc_id: "{{ vpc_id }}" + register: create_igw + + - name: Assert success + assert: + that: + - create_igw is successful + + + # ============================================================ + - name: Create new NAT gateway with eip allocation-id + ec2_vpc_nat_gateway: + subnet_id: "{{ subnet_id }}" + allocation_id: "{{ allocation_id }}" + wait: yes + register: create_ngw + retries: 10 + until: create_ngw is not failed + + - name: Assert creation happened (expected changed=true) + assert: + that: + - create_ngw.changed + + - name: "set facts: NAT gateway ID" + set_fact: + nat_gateway_id: "{{ create_ngw.nat_gateway_id }}" + network_interface_id: "{{ create_ngw.nat_gateway_addresses[0].network_interface_id }}" + + # - name: Create new NAT gateway with eip allocation-id - CHECK_MODE + # ec2_vpc_nat_gateway: + # subnet_id: "{{ subnet_id }}" + # allocation_id: "{{ allocation_id }}" + # wait: yes + # register: create_ngw + # check_mode: yes + # + # - name: Assert creation happened (expected changed=true) - CHECK_MODE + # assert: + # that: + # - create_ngw.changed + + # ============================================================ + - name: Trying this again for idempotency - create new NAT gateway with eip allocation-id + ec2_vpc_nat_gateway: + subnet_id: "{{ subnet_id }}" + allocation_id: "{{ allocation_id }}" + wait: yes + register: create_ngw + retries: 10 + until: create_ngw is not failed + + - name: Assert recreation would do nothing (expected changed=false) + assert: + that: + - not create_ngw.changed + + # - name: Trying this again for idempotency - create new NAT gateway with eip allocation-id - CHECK_MODE + # ec2_vpc_nat_gateway: + # subnet_id: "{{ subnet_id }}" + # allocation_id: "{{ allocation_id }}" + # wait: yes + # register: create_ngw + # check_mode: yes + + # - name: Assert recreation would do nothing (expected changed=false) - CHECK_MODE + # assert: + # that: + # - not create_ngw.changed + + + # ============================================================ + #- name: Create new NAT gateway with eip address + # ec2_vpc_nat_gateway: + # subnet_id: "{{ subnet_id }}" + # eip_address: "{{ eip_address }}" + # wait: yes + # register: create_ngw + # + #- name: Assert creation happened (expected changed=true) + # assert: + # that: + # - create_ngw.changed + + # - name: Create new nat gateway with eip address - CHECK_MODE + # ec2_vpc_nat_gateway: + # subnet_id: "{{ subnet_id }}" + # eip_address: "{{ eip_address }}" + # wait: yes + # register: create_ngw + # check_mode: yes + + # - name: Assert creation happened (expected changed=true) - CHECK_MODE + # assert: + # that: + # - create_ngw.changed + + + # ============================================================ + # - name: Trying this again for idempotency - create new nat gateway with eip address + # ec2_vpc_nat_gateway: + # subnet_id: "{{ subnet_id }}" + # eip_address: "{{ eip_address }}" + # wait: yes + # register: create_ngw + + # - name: Assert recreation would do nothing (expected changed=false) + # assert: + # that: + # - not create_ngw.changed + + # - name: Trying this again for idempotency - create new nat gateway with eip address - CHECK_MODE + # ec2_vpc_nat_gateway: + # subnet_id: "{{ subnet_id }}" + # eip_address: "{{ eip_address }}" + # wait: yes + # register: create_ngw + # check_mode: yes + + # - name: Assert recreation would do nothing (expected changed=false) - CHECK_MODE + # assert: + # that: + # - not create_ngw.changed + + + # ============================================================ + - name: Create new NAT gateway only if one does not exist already + ec2_vpc_nat_gateway: + if_exist_do_not_create: yes + subnet_id: "{{ subnet_id }}" + wait: yes + register: create_ngw + retries: 10 + until: create_ngw is not failed + + - name: Assert recreation would do nothing (expected changed=false) + assert: + that: + - not create_ngw.changed + + # - name: Create new nat gateway only if one does not exist already - CHECK_MODE + # ec2_vpc_nat_gateway: + # if_exist_do_not_create: yes + # subnet_id: "{{ subnet_id }}" + # wait: yes + # register: create_ngw + # check_mode: yes + + # - name: Assert recreation would do nothing (expected changed=false) - CHECK_MODE + # assert: + # that: + # - not create_ngw.changed + + + # ============================================================ + - name: Delete NAT gateway + ec2_vpc_nat_gateway: + nat_gateway_id: "{{ nat_gateway_id }}" + state: absent + wait: yes + register: delete_nat_gateway + retries: 10 + until: delete_nat_gateway is not failed + + - name: Assert state=absent (expected changed=true) + assert: + that: + - delete_nat_gateway.changed + + # - name: Delete NAT gateway - CHECK_MODE + # ec2_vpc_nat_gateway: + # nat_gateway_id: "{{ nat_gateway_id }}" + # state: absent + # wait: yes + # register: delete_nat_gateway + # check_mode: yes + + # - name: Assert state=absent (expected changed=true) - CHECK_MODE + # assert: + # that: + # - delete_nat_gateway.changed + + # ============================================================ + - name: Create new NAT gateway with eip allocation-id and tags + ec2_vpc_nat_gateway: + subnet_id: "{{ subnet_id }}" + allocation_id: "{{ allocation_id }}" + tags: + tag_one: '{{ resource_prefix }} One' + "Tag Two": 'two {{ resource_prefix }}' + wait: yes + register: create_ngw + + - name: Assert creation happened (expected changed=true) + assert: + that: + - create_ngw.changed + + # - name: Create new NAT gateway with eip allocation-id and tags - CHECK_MODE + # ec2_vpc_nat_gateway: + # subnet_id: "{{ subnet_id }}" + # allocation_id: "{{ allocation_id }}" + # tags: + # tag_one: '{{ resource_prefix }} One' + # "Tag Two": 'two {{ resource_prefix }}' + # wait: yes + # register: create_ngw + # check_mode: yes + + # - name: Assert creation happened (expected changed=true) - CHECK_MODE + # assert: + # that: + # - create_ngw.changed + + + # ============================================================ + - name: Update the tags (no change) + ec2_vpc_nat_gateway: + subnet_id: "{{ subnet_id }}" + allocation_id: "{{ allocation_id }}" + tags: + tag_one: '{{ resource_prefix }} One' + "Tag Two": 'two {{ resource_prefix }}' + wait: yes + register: update_tags_ngw + + - name: assert tag update would do nothing (expected changed=false) + assert: + that: + - not update_tags_ngw.changed + + # - name: Update the tags (no change) - CHECK_MODE + # ec2_vpc_nat_gateway: + # subnet_id: "{{ subnet_id }}" + # allocation_id: "{{ allocation_id }}" + # tags: + # tag_one: '{{ resource_prefix }} One' + # "Tag Two": 'two {{ resource_prefix }}' + # wait: yes + # register: update_tags_ngw + # check_mode: yes + + # - name: assert tag update would do nothing (expected changed=false) - CHECK_MODE + # assert: + # that: + # - not update_tags_ngw.changed + + + # ============================================================ + - name: Update the tags - remove and add + ec2_vpc_nat_gateway: + subnet_id: "{{ subnet_id }}" + allocation_id: "{{ allocation_id }}" + tags: + tag_three: '{{ resource_prefix }} Three' + "Tag Two": 'two {{ resource_prefix }}' + wait: yes + register: update_tags_ngw + + - name: Assert tag update would happen (expected changed=true) + assert: + that: + - update_tags_ngw.changed + + # - name: Update the tags - remove and add - CHECK_MODE + # ec2_vpc_nat_gateway: + # subnet_id: "{{ subnet_id }}" + # allocation_id: "{{ allocation_id }}" + # tags: + # tag_three: '{{ resource_prefix }} Three' + # "Tag Two": 'two {{ resource_prefix }}' + # wait: yes + # register: update_tags_ngw + # check_mode: yes + + # - name: Assert tag update would happen (expected changed=true) - CHECK_MODE + # assert: + # that: + # - update_tags_ngw.changed + + + # ============================================================ + - name: Update the tags add without purge + ec2_vpc_nat_gateway: + if_exist_do_not_create: yes + subnet_id: "{{ subnet_id }}" + allocation_id: "{{ allocation_id }}" + purge_tags: no + tags: + tag_one: '{{ resource_prefix }} One' + wait: yes + register: update_tags_ngw + + - name: Assert tags would be added + assert: + that: + - update_tags_ngw.changed + + # - name: Update the tags add without purge - CHECK_MODE + # ec2_vpc_nat_gateway: + # if_exist_do_not_create: yes + # subnet_id: "{{ subnet_id }}" + # allocation_id: "{{ allocation_id }}" + # purge_tags: no + # tags: + # tag_one: '{{ resource_prefix }} One' + # wait: yes + # register: update_tags_ngw + # check_mode: yes + + # - name: Assert tags would be added - CHECK_MODE + # assert: + # that: + # - update_tags_ngw.changed + + + # ============================================================ + - name: Remove all tags + ec2_vpc_nat_gateway: + subnet_id: "{{ subnet_id }}" + allocation_id: "{{ allocation_id }}" + tags: {} + register: delete_tags_ngw + + - name: assert tags would be removed + assert: + that: + - delete_tags_ngw.changed + + # - name: Remove all tags - CHECK_MODE + # ec2_vpc_nat_gateway: + # subnet_id: "{{ subnet_id }}" + # allocation_id: "{{ allocation_id }}" + # tags: {} + # register: delete_tags_ngw + # check_mode: yes + + # - name: assert tags would be removed - CHECK_MODE + # assert: + # that: + # - delete_tags_ngw.changed + + + + # ============================================================ + - name: Update with CamelCase tags + ec2_vpc_nat_gateway: + if_exist_do_not_create: yes + subnet_id: "{{ subnet_id }}" + allocation_id: "{{ allocation_id }}" + purge_tags: no + tags: + "lowercase spaced": 'hello cruel world ❤️' + "Title Case": 'Hello Cruel World ❤️' + CamelCase: 'SimpleCamelCase ❤️' + snake_case: 'simple_snake_case ❤️' + wait: yes + register: update_tags_ngw + + - name: Assert tags would be added + assert: + that: + - update_tags_ngw.changed + - update_tags_ngw.tags["lowercase spaced"] == 'hello cruel world ❤️' + - update_tags_ngw.tags["Title Case"] == 'Hello Cruel World ❤️' + - update_tags_ngw.tags["CamelCase"] == 'SimpleCamelCase ❤️' + - update_tags_ngw.tags["snake_case"] == 'simple_snake_case ❤️' + + + # - name: Update with CamelCase tags - CHECK_MODE + # ec2_vpc_nat_gateway: + # if_exist_do_not_create: yes + # subnet_id: "{{ subnet_id }}" + # allocation_id: "{{ allocation_id }}" + # purge_tags: no + # tags: + # "lowercase spaced": 'hello cruel world ❤️' + # "Title Case": 'Hello Cruel World ❤️' + # CamelCase: 'SimpleCamelCase ❤️' + # snake_case: 'simple_snake_case ❤️' + # wait: yes + # register: update_tags_ngw + + #- name: Assert tags would be added - CHECK_MODE + # assert: + # that: + # - update_tags_ngw.changed + # - update_tags_ngw.tags["lowercase spaced"] == 'hello cruel world ❤️' + # - update_tags_ngw.tags["Title Case"] == 'Hello Cruel World ❤️' + # - update_tags_ngw.tags["CamelCase"] == 'SimpleCamelCase ❤️' + # - update_tags_ngw.tags["snake_case"] == 'simple_snake_case ❤️' + + # ============================================================ + + + always: + - name: Get NAT gateways + ec2_vpc_nat_gateway_info: + filters: + vpc-id: "{{ vpc_id }}" + register: existing_ngws + retries: 10 + until: existing_ngws is not failed + ignore_errors: true + + - name: Tidy up NAT gateway + ec2_vpc_nat_gateway: + subnet_id: "{{ item.subnet_id }}" + nat_gateway_id: "{{ item.nat_gateway_id }}" + #release_eip: yes + state: absent + wait: yes + with_items: "{{ existing_ngws.result }}" + ignore_errors: true + + - name: Delete IGW + ec2_vpc_igw: + vpc_id: "{{ vpc_id }}" + state: absent + ignore_errors: true + + - name: Remove subnet + ec2_vpc_subnet: + state: absent + cidr: "{{ subnet_cidr }}" + vpc_id: "{{ vpc_id }}" + ignore_errors: true + + - name: Ensure EIP is actually released + ec2_eip: + state: absent + device_id: "{{ item.nat_gateway_addresses[0].network_interface_id }}" + in_vpc: yes + with_items: "{{ existing_ngws.result }}" + ignore_errors: yes + + - name: Delete VPC + ec2_vpc_net: + name: "{{ vpc_name }}" + cidr_block: "{{ vpc_cidr }}" + state: absent + purge_cidrs: yes + ignore_errors: yes
ec2_vpc_nat_gateway should support tags ##### SUMMARY The ec2_vpc_nat_gateway module does not support tags and it should. NAT Gateways support tags in AWS. ##### ISSUE TYPE - Feature Idea ##### COMPONENT NAME The module name is ec2_vpc_nat_gateway ##### ADDITIONAL INFORMATION The ec2_vpc_nat_gateway should accept a dictionary of tags, like the internet gateway module (as documented [here](https://docs.ansible.com/ansible/latest/collections/community/aws/ec2_vpc_igw_module.html)). <!--- Paste example playbooks or commands between quotes below --> ```yaml - name: setup NAT gateways tags: always ec2_vpc_nat_gateway: profile: your_aws_profile state: present region: us-west-1 subnet_id: "{{ item }}" if_exist_do_not_create: yes tags: #<-- This is currently not supported - Name: MyNATGateway - Purpuse: NATing things loop: "{{nat_subnet_list}}" #This is an array of subnet IDs in format `nat_subnet_id: subnet-12345, subnet-54321` ```
Files identified in the description: * [`plugins/modules/ec2_vpc_nat_gateway.py`](https://github.com/['ansible-collections/amazon.aws', 'ansible-collections/community.aws']/blob/main/plugins/modules/ec2_vpc_nat_gateway.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @Etherdaemon @jillr @jonhadfield @linuxdynasty @s-hertel @tremble @wimnat [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify --->
2021-01-26T13:36:48
ansible-collections/community.aws
389
ansible-collections__community.aws-389
[ "172" ]
3d2bbcc76aca2fee84b3a10fd39b426423f8254a
diff --git a/plugins/modules/sqs_queue.py b/plugins/modules/sqs_queue.py --- a/plugins/modules/sqs_queue.py +++ b/plugins/modules/sqs_queue.py @@ -375,7 +375,7 @@ def update_sqs_queue(module, client, queue_url): if isinstance(new_value, bool): new_value = str(new_value).lower() - existing_value = str(existing_value).lower() + value = str(value).lower() if new_value == value: continue
diff --git a/tests/integration/targets/sqs_queue/tasks/main.yml b/tests/integration/targets/sqs_queue/tasks/main.yml --- a/tests/integration/targets/sqs_queue/tasks/main.yml +++ b/tests/integration/targets/sqs_queue/tasks/main.yml @@ -104,3 +104,25 @@ with_items: - { name: "{{ create_result.name }}" } - { name: "{{ dead_letter_queue.name }}" } + - name: Test FIFO queue + block: + - name: Creating FIFO queue + sqs_queue: + name: "{{ resource_prefix }}{{ 1000 | random }}" + queue_type: fifo + content_based_deduplication: yes + register: create_result + - name: Assert queue created with configuration + assert: + that: + - create_result.changed + always: + - name: Cleaning up queue + sqs_queue: + name: "{{ item.name }}" + state: absent + register: delete_result + retries: 3 + delay: 3 + with_items: + - { name: "{{ create_result.name }}" }
UnboundLocalError in sqs_queue <!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY Copied the "Create FIFO queue" example from documentation, and it fails to run with an UnboundLocalError. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME sqs_queue ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ``` ansible 2.9.10 config file = /home/mstudd/.ansible.cfg configured module search path = ['/home/mstudd/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /usr/lib/python3.8/site-packages/ansible executable location = /usr/bin/ansible python version = 3.8.3 (default, May 29 2020, 00:00:00) [GCC 10.1.1 20200507 (Red Hat 10.1.1-1)] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ``` DEFAULT_VAULT_IDENTITY_LIST(env: ANSIBLE_VAULT_IDENTITY_LIST) = ['ops@~/.vault/ops', 'dev@~/.vault/dev'] ``` ##### OS / ENVIRONMENT Fedora 32 x86_64 ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> <!--- Paste example playbooks or commands between quotes below --> ``` --- - hosts: localhost tasks: - community.aws.sqs_queue: name: fifo-queue region: us-east-1 queue_type: fifo content_based_deduplication: yes ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS ansible-playbook creates the SQS queue as described (or reports relevant auth error if AWS creds aren't correct). ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> <!--- Paste verbatim command output between quotes --> ``` config file = /home/mstudd/dev/git/ansible/ansible.cfg configured module search path = ['/home/mstudd/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /usr/lib/python3.8/site-packages/ansible executable location = /usr/bin/ansible-playbook python version = 3.8.3 (default, May 29 2020, 00:00:00) [GCC 10.1.1 20200507 (Red Hat 10.1.1-1)] Using /home/mstudd/dev/git/ansible/ansible.cfg as config file setting up inventory plugins host_list declined parsing /home/mstudd/dev/git/ansible/inventories/dev/hosts as it did not pass its verify_file() method script declined parsing /home/mstudd/dev/git/ansible/inventories/dev/hosts as it did not pass its verify_file() method auto declined parsing /home/mstudd/dev/git/ansible/inventories/dev/hosts as it did not pass its verify_file() method Set default localhost to localhost Parsed /home/mstudd/dev/git/ansible/inventories/dev/hosts inventory source with ini plugin [WARNING]: Found both group and host with same name: api-charts Loading callback plugin default of type stdout, v2.0 from /usr/lib/python3.8/site-packages/ansible/plugins/callback/default.py PLAYBOOK: test.yml ********************************************************************************************************************************************************************************************************************************************************************************************************** Positional arguments: test.yml verbosity: 4 connection: smart timeout: 10 become_method: sudo tags: ('all',) inventory: ('/home/mstudd/dev/git/ansible/inventories/dev/hosts',) forks: 5 1 plays in test.yml PLAY [localhost] ************************************************************************************************************************************************************************************************************************************************************************************************************ Trying secret FileVaultSecret(filename='/home/mstudd/.vault/ops') for vault_id=ops Tried to use the vault secret (ops) to decrypt (/home/mstudd/dev/git/ansible/inventories/dev/group_vars/all/secrets.yml) but it failed. Error: HMAC verification failed: Signature did not match digest. Trying secret FileVaultSecret(filename='/home/mstudd/.vault/dev') for vault_id=dev TASK [Gathering Facts] ****************************************************************************************************************************************************************************************************************************************************************************************************** task path: /home/mstudd/dev/git/ansible/test.yml:3 <localhost.dev> ESTABLISH LOCAL CONNECTION FOR USER: mstudd <localhost.dev> EXEC /bin/sh -c 'echo ~mstudd && sleep 0' <localhost.dev> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/mstudd/.ansible/tmp `"&& mkdir /home/mstudd/.ansible/tmp/ansible-tmp-1596227662.5343304-234250-22361424934479 && echo ansible-tmp-1596227662.5343304-234250-22361424934479="` echo /home/mstudd/.ansible/tmp/ansible-tmp-1596227662.5343304-234250-22361424934479 `" ) && sleep 0' <localhost> Attempting python interpreter discovery <localhost.dev> EXEC /bin/sh -c 'echo PLATFORM; uname; echo FOUND; command -v '"'"'/usr/bin/python'"'"'; command -v '"'"'python3.7'"'"'; command -v '"'"'python3.6'"'"'; command -v '"'"'python3.5'"'"'; command -v '"'"'python2.7'"'"'; command -v '"'"'python2.6'"'"'; command -v '"'"'/usr/libexec/platform-python'"'"'; command -v '"'"'/usr/bin/python3'"'"'; command -v '"'"'python'"'"'; echo ENDFOUND && sleep 0' <localhost.dev> EXEC /bin/sh -c '/usr/bin/python && sleep 0' Using module file /usr/lib/python3.8/site-packages/ansible/modules/system/setup.py <localhost.dev> PUT /home/mstudd/.ansible/tmp/ansible-local-234246mzlywzby/tmphl8okmrr TO /home/mstudd/.ansible/tmp/ansible-tmp-1596227662.5343304-234250-22361424934479/AnsiballZ_setup.py <localhost.dev> EXEC /bin/sh -c 'chmod u+x /home/mstudd/.ansible/tmp/ansible-tmp-1596227662.5343304-234250-22361424934479/ /home/mstudd/.ansible/tmp/ansible-tmp-1596227662.5343304-234250-22361424934479/AnsiballZ_setup.py && sleep 0' <localhost.dev> EXEC /bin/sh -c '/usr/bin/python3 /home/mstudd/.ansible/tmp/ansible-tmp-1596227662.5343304-234250-22361424934479/AnsiballZ_setup.py && sleep 0' <localhost.dev> EXEC /bin/sh -c 'rm -f -r /home/mstudd/.ansible/tmp/ansible-tmp-1596227662.5343304-234250-22361424934479/ > /dev/null 2>&1 && sleep 0' ok: [localhost] META: ran handlers TASK [community.aws.sqs_queue] ********************************************************************************************************************************************************************************************************************************************************************************************** task path: /home/mstudd/dev/git/ansible/test.yml:5 <localhost.dev> ESTABLISH LOCAL CONNECTION FOR USER: mstudd <localhost.dev> EXEC /bin/sh -c 'echo ~mstudd && sleep 0' <localhost.dev> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/mstudd/.ansible/tmp `"&& mkdir /home/mstudd/.ansible/tmp/ansible-tmp-1596227663.4545841-234299-215745550363761 && echo ansible-tmp-1596227663.4545841-234299-215745550363761="` echo /home/mstudd/.ansible/tmp/ansible-tmp-1596227663.4545841-234299-215745550363761 `" ) && sleep 0' Using module file /home/mstudd/dev/git/ansible/galaxy-roles/ansible_collections/community/aws/plugins/modules/sqs_queue.py <localhost.dev> PUT /home/mstudd/.ansible/tmp/ansible-local-234246mzlywzby/tmpifp2ngt5 TO /home/mstudd/.ansible/tmp/ansible-tmp-1596227663.4545841-234299-215745550363761/AnsiballZ_sqs_queue.py <localhost.dev> EXEC /bin/sh -c 'chmod u+x /home/mstudd/.ansible/tmp/ansible-tmp-1596227663.4545841-234299-215745550363761/ /home/mstudd/.ansible/tmp/ansible-tmp-1596227663.4545841-234299-215745550363761/AnsiballZ_sqs_queue.py && sleep 0' <localhost.dev> EXEC /bin/sh -c '/usr/bin/python3 /home/mstudd/.ansible/tmp/ansible-tmp-1596227663.4545841-234299-215745550363761/AnsiballZ_sqs_queue.py && sleep 0' <localhost.dev> EXEC /bin/sh -c 'rm -f -r /home/mstudd/.ansible/tmp/ansible-tmp-1596227663.4545841-234299-215745550363761/ > /dev/null 2>&1 && sleep 0' The full traceback is: Traceback (most recent call last): File "/home/mstudd/.ansible/tmp/ansible-tmp-1596227663.4545841-234299-215745550363761/AnsiballZ_sqs_queue.py", line 102, in <module> _ansiballz_main() File "/home/mstudd/.ansible/tmp/ansible-tmp-1596227663.4545841-234299-215745550363761/AnsiballZ_sqs_queue.py", line 94, in _ansiballz_main invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS) File "/home/mstudd/.ansible/tmp/ansible-tmp-1596227663.4545841-234299-215745550363761/AnsiballZ_sqs_queue.py", line 40, in invoke_module runpy.run_module(mod_name='ansible_collections.community.aws.plugins.modules.sqs_queue', init_globals=None, run_name='__main__', alter_sys=True) File "/usr/lib64/python3.8/runpy.py", line 207, in run_module return _run_module_code(code, init_globals, run_name, mod_spec) File "/usr/lib64/python3.8/runpy.py", line 97, in _run_module_code _run_code(code, mod_globals, init_globals, File "/usr/lib64/python3.8/runpy.py", line 87, in _run_code exec(code, run_globals) File "/tmp/ansible_community.aws.sqs_queue_payload_vm5yiveu/ansible_community.aws.sqs_queue_payload.zip/ansible_collections/community/aws/plugins/modules/sqs_queue.py", line 474, in <module> File "/tmp/ansible_community.aws.sqs_queue_payload_vm5yiveu/ansible_community.aws.sqs_queue_payload.zip/ansible_collections/community/aws/plugins/modules/sqs_queue.py", line 464, in main File "/tmp/ansible_community.aws.sqs_queue_payload_vm5yiveu/ansible_community.aws.sqs_queue_payload.zip/ansible_collections/community/aws/plugins/modules/sqs_queue.py", line 311, in create_or_update_sqs_queue File "/tmp/ansible_community.aws.sqs_queue_payload_vm5yiveu/ansible_community.aws.sqs_queue_payload.zip/ansible_collections/community/aws/plugins/modules/sqs_queue.py", line 377, in update_sqs_queue UnboundLocalError: local variable 'existing_value' referenced before assignment fatal: [localhost]: FAILED! => { "changed": false, "module_stderr": "Traceback (most recent call last):\n File \"/home/mstudd/.ansible/tmp/ansible-tmp-1596227663.4545841-234299-215745550363761/AnsiballZ_sqs_queue.py\", line 102, in <module>\n _ansiballz_main()\n File \"/home/mstudd/.ansible/tmp/ansible-tmp-1596227663.4545841-234299-215745550363761/AnsiballZ_sqs_queue.py\", line 94, in _ansiballz_main\n invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n File \"/home/mstudd/.ansible/tmp/ansible-tmp-1596227663.4545841-234299-215745550363761/AnsiballZ_sqs_queue.py\", line 40, in invoke_module\n runpy.run_module(mod_name='ansible_collections.community.aws.plugins.modules.sqs_queue', init_globals=None, run_name='__main__', alter_sys=True)\n File \"/usr/lib64/python3.8/runpy.py\", line 207, in run_module\n return _run_module_code(code, init_globals, run_name, mod_spec)\n File \"/usr/lib64/python3.8/runpy.py\", line 97, in _run_module_code\n _run_code(code, mod_globals, init_globals,\n File \"/usr/lib64/python3.8/runpy.py\", line 87, in _run_code\n exec(code, run_globals)\n File \"/tmp/ansible_community.aws.sqs_queue_payload_vm5yiveu/ansible_community.aws.sqs_queue_payload.zip/ansible_collections/community/aws/plugins/modules/sqs_queue.py\", line 474, in <module>\n File \"/tmp/ansible_community.aws.sqs_queue_payload_vm5yiveu/ansible_community.aws.sqs_queue_payload.zip/ansible_collections/community/aws/plugins/modules/sqs_queue.py\", line 464, in main\n File \"/tmp/ansible_community.aws.sqs_queue_payload_vm5yiveu/ansible_community.aws.sqs_queue_payload.zip/ansible_collections/community/aws/plugins/modules/sqs_queue.py\", line 311, in create_or_update_sqs_queue\n File \"/tmp/ansible_community.aws.sqs_queue_payload_vm5yiveu/ansible_community.aws.sqs_queue_payload.zip/ansible_collections/community/aws/plugins/modules/sqs_queue.py\", line 377, in update_sqs_queue\nUnboundLocalError: local variable 'existing_value' referenced before assignment\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1 } PLAY RECAP ****************************************************************************************************************************************************************************************************************************************************************************************************************** localhost : ok=1 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0 ```
Looks like changing `existing_value` to `value` in line 377 of sqs_queue.py fixes it. cc @jillr @loia @nand0p @s-hertel @sbj-ss @tremble @wimnat [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> we are encountering this issue as well. @mestuddtc do you have a Pull Request that can be merged in to fix this?
2021-02-03T21:39:25
ansible-collections/community.aws
402
ansible-collections__community.aws-402
[ "401" ]
48d1b486730da7c09840ad1c94186d4f1325a81c
diff --git a/plugins/modules/ecs_task.py b/plugins/modules/ecs_task.py --- a/plugins/modules/ecs_task.py +++ b/plugins/modules/ecs_task.py @@ -19,17 +19,20 @@ operation: description: - Which task operation to execute. + - When I(operation=run) I(task_definition) must be set. + - When I(operation=start) both I(task_definition) and I(container_instances) must be set. + - When I(operation=stop) both I(task_definition) and I(task) must be set. required: True choices: ['run', 'start', 'stop'] type: str cluster: description: - The name of the cluster to run the task on. - required: False + required: True type: str task_definition: description: - - The task definition to start or run. + - The task definition to start, run or stop. required: False type: str overrides: @@ -44,7 +47,7 @@ type: int task: description: - - The task to stop. + - The ARN of the task to stop. required: False type: str container_instances: @@ -332,7 +335,7 @@ def ecs_api_handles_network_configuration(self): def main(): argument_spec = dict( operation=dict(required=True, choices=['run', 'start', 'stop']), - cluster=dict(required=False, type='str'), # R S P + cluster=dict(required=True, type='str'), # R S P task_definition=dict(required=False, type='str'), # R* S* overrides=dict(required=False, type='dict'), # R S count=dict(required=False, type='int'), # R @@ -345,28 +348,26 @@ def main(): ) module = AnsibleAWSModule(argument_spec=argument_spec, supports_check_mode=True, - required_if=[('launch_type', 'FARGATE', ['network_configuration'])]) + required_if=[ + ('launch_type', 'FARGATE', ['network_configuration']), + ('operation', 'run', ['task_definition']), + ('operation', 'start', [ + 'task_definition', + 'container_instances' + ]), + ('operation', 'stop', ['task_definition', 'task']), + ]) # Validate Inputs if module.params['operation'] == 'run': - if 'task_definition' not in module.params and module.params['task_definition'] is None: - module.fail_json(msg="To run a task, a task_definition must be specified") task_to_list = module.params['task_definition'] status_type = "RUNNING" if module.params['operation'] == 'start': - if 'task_definition' not in module.params and module.params['task_definition'] is None: - module.fail_json(msg="To start a task, a task_definition must be specified") - if 'container_instances' not in module.params and module.params['container_instances'] is None: - module.fail_json(msg="To start a task, container instances must be specified") task_to_list = module.params['task'] status_type = "RUNNING" if module.params['operation'] == 'stop': - if 'task' not in module.params and module.params['task'] is None: - module.fail_json(msg="To stop a task, a task must be specified") - if 'task_definition' not in module.params and module.params['task_definition'] is None: - module.fail_json(msg="To stop a task, a task definition must be specified") task_to_list = module.params['task_definition'] status_type = "STOPPED"
Parameter validation logic in ecs_task does not work as intended ##### SUMMARY ecs_task attempts to validate parameters using an `and` statement. For example: ```python if 'task_definition' not in module.params and module.params['task_definition'] is None: module.fail_json(msg="To stop a task, a task definition must be specified") ``` This will not evaluate to true even if `task_definition` not provided because `module.params['task_definiton'] = None` by default. Which means the condition `'task_definition' not in module.params` is always false. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME ecs_task ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.10.3 config file = None configured module search path = ['/home/mjmayer/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /home/mjmayer/.local/lib/python3.8/site-packages/ansible executable location = /home/mjmayer/.local/bin/ansible python version = 3.8.6 (default, Sep 25 2020, 09:36:53) [GCC 10.2.0] ``` ##### CONFIGURATION ```paste below ``` ##### OS / ENVIRONMENT N/A ##### STEPS TO REPRODUCE <!--- Paste example playbooks or commands between quotes below --> ```yaml - name: stop running tasks ecs_task: operation: stop cluster: "{{ cluster_name }}" task: "{{ ecs_task }}" aws_access_key: "{{ aws_key }}" aws_secret_key: "{{ aws_secret }}" region: "{{ region }}" ``` ##### EXPECTED RESULTS Error indicatin that the `task_definition` parameter is missing. ##### ACTUAL RESULTS ```paste below The full traceback is: Traceback (most recent call last): File "/home/mjmayer/.ansible/tmp/ansible-tmp-1612908699.9970727-2470578-69922562765386/AnsiballZ_ecs_task.py", line 249, in <module> _ansiballz_main() File "/home/mjmayer/.ansible/tmp/ansible-tmp-1612908699.9970727-2470578-69922562765386/AnsiballZ_ecs_task.py", line 239, in _ansiballz_main invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS) File "/home/mjmayer/.ansible/tmp/ansible-tmp-1612908699.9970727-2470578-69922562765386/AnsiballZ_ecs_task.py", line 110, in invoke_module runpy.run_module(mod_name='ansible_collections.community.aws.plugins.modules.ecs_task', init_globals=None, run_name='__main__', alter_sys=True) File "/usr/lib/python3.8/runpy.py", line 207, in run_module return _run_module_code(code, init_globals, run_name, mod_spec) File "/usr/lib/python3.8/runpy.py", line 97, in _run_module_code _run_code(code, mod_globals, init_globals, File "/usr/lib/python3.8/runpy.py", line 87, in _run_code exec(code, run_globals) File "/tmp/ansible_ecs_task_payload_1abc2nbk/ansible_ecs_task_payload.zip/ansible_collections/community/aws/plugins/modules/ecs_task.py", line 443, in <module> File "/tmp/ansible_ecs_task_payload_1abc2nbk/ansible_ecs_task_payload.zip/ansible_collections/community/aws/plugins/modules/ecs_task.py", line 390, in main File "/tmp/ansible_ecs_task_payload_1abc2nbk/ansible_ecs_task_payload.zip/ansible_collections/community/aws/plugins/modules/ecs_task.py", line 251, in list_tasks File "/home/mjmayer/.local/lib/python3.8/site-packages/botocore/client.py", line 357, in _api_call return self._make_api_call(operation_name, kwargs) File "/home/mjmayer/.local/lib/python3.8/site-packages/botocore/client.py", line 648, in _make_api_call request_dict = self._convert_to_request_dict( File "/home/mjmayer/.local/lib/python3.8/site-packages/botocore/client.py", line 696, in _convert_to_request_dict request_dict = self._serializer.serialize_to_request( File "/home/mjmayer/.local/lib/python3.8/site-packages/botocore/validate.py", line 297, in serialize_to_request raise ParamValidationError(report=report.generate_report()) botocore.exceptions.ParamValidationError: Parameter validation failed: Invalid type for parameter family, value: None, type: <class 'NoneType'>, valid types: <class 'str'> failed: [localhost] (item=arn:aws:ecs:us-west-2:989838493125:task/ait-ecs_cluster-np/b7fa41f566ed47a895035b9536bc88a7) => { "ansible_loop_var": "item", "changed": false, "item": "arn:aws:ecs:us-west-2:989838493125:task/ait-ecs_cluster-np/b7fa41f566ed47a895035b9536bc88a7", "module_stderr": "Traceback (most recent call last):\n File \"/home/mjmayer/.ansible/tmp/ansible-tmp-1612908699.9970727-2470578-69922562765386/AnsiballZ_ecs_task.py\", line 249, in <module>\n _ansiballz_main()\n File \"/home/mjmayer/.ansible/tmp/ansible-tmp-1612908699.9970727-2470578-69922562765386/AnsiballZ_ecs_task.py\", line 239, in _ansiballz_main\n invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n File \"/home/mjmayer/.ansible/tmp/ansible-tmp-1612908699.9970727-2470578-69922562765386/AnsiballZ_ecs_task.py\", line 110, in invoke_module\n runpy.run_module(mod_name='ansible_collections.community.aws.plugins.modules.ecs_task', init_globals=None, run_name='__main__', alter_sys=True)\n File \"/usr/lib/python3.8/runpy.py\", line 207, in run_module\n return _run_module_code(code, init_globals, run_name, mod_spec)\n File \"/usr/lib/python3.8/runpy.py\", line 97, in _run_module_code\n _run_code(code, mod_globals, init_globals,\n File \"/usr/lib/python3.8/runpy.py\", line 87, in _run_code\n exec(code, run_globals)\n File \"/tmp/ansible_ecs_task_payload_1abc2nbk/ansible_ecs_task_payload.zip/ansible_collections/community/aws/plugins/modules/ecs_task.py\", line 443, in <module>\n File \"/tmp/ansible_ecs_task_payload_1abc2nbk/ansible_ecs_task_payload.zip/ansible_collections/community/aws/plugins/modules/ecs_task.py\", line 390, in main\n File \"/tmp/ansible_ecs_task_payload_1abc2nbk/ansible_ecs_task_payload.zip/ansible_collections/community/aws/plugins/modules/ecs_task.py\", line 251, in list_tasks\n File \"/home/mjmayer/.local/lib/python3.8/site-packages/botocore/client.py\", line 357, in _api_call\n return self._make_api_call(operation_name, kwargs)\n File \"/home/mjmayer/.local/lib/python3.8/site-packages/botocore/client.py\", line 648, in _make_api_call\n request_dict = self._convert_to_request_dict(\n File \"/home/mjmayer/.local/lib/python3.8/site-packages/botocore/client.py\", line 696, in _convert_to_request_dict\n request_dict = self._serializer.serialize_to_request(\n File \"/home/mjmayer/.local/lib/python3.8/site-packages/botocore/validate.py\", line 297, in serialize_to_request\n raise ParamValidationError(report=report.generate_report())\nbotocore.exceptions.ParamValidationError: Parameter validation failed:\nInvalid type for parameter family, value: None, type: <class 'NoneType'>, valid types: <class 'str'>\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1 } ```
2021-02-09T22:20:23
ansible-collections/community.aws
454
ansible-collections__community.aws-454
[ "453", "453" ]
52fb23054101acbd78e13a45048ddcf935899586
diff --git a/plugins/modules/sns_topic.py b/plugins/modules/sns_topic.py --- a/plugins/modules/sns_topic.py +++ b/plugins/modules/sns_topic.py @@ -349,8 +349,11 @@ def _set_topic_attrs(self): return changed def _canonicalize_endpoint(self, protocol, endpoint): + # AWS SNS expects phone numbers in + # and canonicalizes to E.164 format + # See <https://docs.aws.amazon.com/sns/latest/dg/sms_publish-to-phone.html> if protocol == 'sms': - return re.sub('[^0-9]*', '', endpoint) + return re.sub('[^0-9+]*', '', endpoint) return endpoint def _set_topic_subs(self):
sns_topic module always deletes and replaces SMS subscriptions <!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> The `sns_topic` module always deletes and replaces SMS subscriptions, because the [`_canonicalize_endpoint()` function](https://github.com/ansible-collections/community.aws/blob/52fb23054101acbd78e13a45048ddcf935899586/plugins/modules/sns_topic.py#L353) strips all non-numeric characters. A leading `+` character is added by AWS when a new subscription is created, so the `sns_topic` module never sees its previously-created subscriptions. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME sns_topic ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.9.15 config file = None configured module search path = ['$HOME/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = $HOME/Dev/ansible-site/.venv/lib/python3.7/site-packages/ansible executable location = $HOME/Dev/ansible-site/.venv/bin/ansible python version = 3.7.9 (default, Feb 1 2021, 15:19:48) [Clang 10.0.1 ([email protected]:llvm/llvm-project.git llvmorg-10.0.1-0-gef32c611a ``` ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> 1. Run the following playbook 2. Confirm the SNS subscription 3. Run the playbook again <!--- Paste example playbooks or commands between quotes below --> ```yaml --- - hosts: localhost gather_facts: no vars: aws_access_key_id: KEYID aws_secret_access_key: SECRET aws_region: REGION # Must include leading plus and country code (+1 for North America) mobile_number: YOUR_VALID_MOBILE tasks: - sns_topic: aws_access_key: '{{ aws_access_key_id }}' aws_secret_key: '{{ aws_secret_access_key }}' region: '{{ aws_region }}' name: Test_Topic state: present display_name: Test Topic subscriptions: - protocol: sms endpoint: '{{ mobile_number }}' ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> On the first run, the task result is `changed`. On the second run, the task result is `ok`. ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> The task result is `changed` on both runs. <!--- Paste verbatim command output between quotes --> <details><summary>Verbatim command output</summary> ```console $ ansible-playbook -vvvv sns_test.yml ansible-playbook 2.9.15 config file = HOMEDIR/Dev/ansible-site/ansible.cfg configured module search path = ['HOMEDIR/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = HOMEDIR/Dev/ansible-site/.venv/lib/python3.7/site-packages/ansible executable location = HOMEDIR/Dev/ansible-site/.venv/bin/ansible-playbook python version = 3.7.9 (default, Feb 1 2021, 15:19:48) [Clang 10.0.1 ([email protected]:llvm/llvm-project.git llvmorg-10.0.1-0-gef32c611a Using HOMEDIR/Dev/ansible-site/ansible.cfg as config file setting up inventory plugins Parsed HOMEDIR/Dev/ansible-site/inventories/zee/hosts.yml inventory source with yaml plugin Loading callback plugin default of type stdout, v2.0 from HOMEDIR/Dev/ansible-site/.venv/lib/python3.7/site-packages/ansible/plugins/callback/default.py PLAYBOOK: sns_test.yml ******************************************************************************************************************************** Positional arguments: sns_test.yml verbosity: 4 connection: smart timeout: 10 become_method: sudo tags: ('all',) inventory: ('HOMEDIR/Dev/ansible-site/inventories/DIRNAME',) forks: 5 1 plays in sns_test.yml PLAY [aws_client] ************************************************************************************************************************************* META: ran handlers Trying secret ScriptVaultSecret(filename='HOMEDIR/bin/get_ansible_vault_password.sh') for vault_id=default Trying secret ScriptVaultSecret(filename='HOMEDIR/bin/get_ansible_vault_password.sh') for vault_id=default TASK [sns_topic] ************************************************************************************************************************************** task path: HOMEDIR/Dev/ansible-site/sns_test.yml:6 <localhost> ESTABLISH LOCAL CONNECTION FOR USER: USERNAME <localhost> EXEC /bin/sh -c 'echo ~USERNAME && sleep 0' <localhost> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo HOMEDIR/.ansible/tmp `"&& mkdir "` echo HOMEDIR/.ansible/tmp/ansible-tmp-1614793718.438763-70642-181606092157004 `" && echo ansible-tmp-1614793718.438763-70642-181606092157004="` echo HOMEDIR/.ansible/tmp/ansible-tmp-1614793718.438763-70642-181606092157004 `" ) && sleep 0' Using module file HOMEDIR/Dev/ansible-site/.venv/lib/python3.7/site-packages/ansible/modules/cloud/amazon/sns_topic.py <localhost> PUT HOMEDIR/.ansible/tmp/ansible-local-70581b86ao8uh/tmp1hmf83g4 TO HOMEDIR/.ansible/tmp/ansible-tmp-1614793718.438763-70642-181606092157004/AnsiballZ_sns_topic.py <localhost> EXEC /bin/sh -c 'chmod u+x HOMEDIR/.ansible/tmp/ansible-tmp-1614793718.438763-70642-181606092157004/ HOMEDIR/.ansible/tmp/ansible-tmp-1614793718.438763-70642-181606092157004/AnsiballZ_sns_topic.py && sleep 0' <localhost> EXEC /bin/sh -c 'HOMEDIR/Dev/ansible-site/.venv/bin/python3.7m HOMEDIR/.ansible/tmp/ansible-tmp-1614793718.438763-70642-181606092157004/AnsiballZ_sns_topic.py && sleep 0' <localhost> EXEC /bin/sh -c 'rm -f -r HOMEDIR/.ansible/tmp/ansible-tmp-1614793718.438763-70642-181606092157004/ > /dev/null 2>&1 && sleep 0' changed: [aws_client] => { "changed": true, "invocation": { "module_args": { "aws_access_key": "AKIAJA6ZHTNW5FLJYE3Q", "aws_secret_key": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER", "debug_botocore_endpoint_logs": false, "delivery_policy": null, "display_name": "Test Topic", "ec2_url": null, "name": "Test_Topic", "policy": null, "profile": null, "purge_subscriptions": true, "region": "us-east-1", "security_token": null, "state": "present", "subscriptions": [ { "endpoint": "+1VALIDMOBILE", "protocol": "sms" } ], "validate_certs": true } }, "sns_arn": "arn:aws:sns:us-east-1:AWS_ACCOUNT_ID:Test_Topic", "sns_topic": { "attributes_set": [ "display_name" ], "check_mode": false, "delivery_policy": "{\"http\":{\"defaultHealthyRetryPolicy\":{\"minDelayTarget\":20,\"maxDelayTarget\":20,\"numRetries\":3,\"numMaxDelayRetries\":0,\"numNoDelayRetries\":0,\"numMinDelayRetries\":0,\"backoffFunction\":\"linear\"},\"disableSubscriptionOverrides\":false}}", "display_name": "Test Topic", "name": "Test_Topic", "owner": "AWS_ACCOUNT_ID", "policy": "{\"Version\":\"2008-10-17\",\"Id\":\"__default_policy_ID\",\"Statement\":[{\"Sid\":\"__default_statement_ID\",\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"*\"},\"Action\":[\"SNS:GetTopicAttributes\",\"SNS:SetTopicAttributes\",\"SNS:AddPermission\",\"SNS:RemovePermission\",\"SNS:DeleteTopic\",\"SNS:Subscribe\",\"SNS:ListSubscriptionsByTopic\",\"SNS:Publish\",\"SNS:Receive\"],\"Resource\":\"arn:aws:sns:us-east-1:AWS_ACCOUNT_ID:Test_Topic\",\"Condition\":{\"StringEquals\":{\"AWS:SourceOwner\":\"AWS_ACCOUNT_ID\"}}}]}", "state": "present", "subscriptions": [ { "endpoint": "+1VALIDMOBILE", "owner": "AWS_ACCOUNT_ID", "protocol": "sms", "subscription_arn": "arn:aws:sns:us-east-1:AWS_ACCOUNT_ID:Test_Topic:19322f05-0265-479b-84c8-e5669a24ac0c", "topic_arn": "arn:aws:sns:us-east-1:AWS_ACCOUNT_ID:Test_Topic" } ], "subscriptions_added": [ [ "sms", "1VALIDMOBILE" ] ], "subscriptions_confirmed": "0", "subscriptions_deleted": "0", "subscriptions_existing": [], "subscriptions_new": [ { "endpoint": "+1VALIDMOBILE", "protocol": "sms" } ], "subscriptions_pending": "0", "subscriptions_purge": true, "topic_arn": "arn:aws:sns:us-east-1:AWS_ACCOUNT_ID:Test_Topic", "topic_created": false, "topic_deleted": false } } META: ran handlers META: ran handlers PLAY RECAP ******************************************************************************************************************************************** aws_client : ok=1 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 $ # Confirmed subscription in AWS console $ ansible-playbook -vvvv sns_test.yml ansible-playbook 2.9.15 config file = HOMEDIR/Dev/ansible-site/ansible.cfg configured module search path = ['HOMEDIR/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = HOMEDIR/Dev/ansible-site/.venv/lib/python3.7/site-packages/ansible executable location = HOMEDIR/Dev/ansible-site/.venv/bin/ansible-playbook python version = 3.7.9 (default, Feb 1 2021, 15:19:48) [Clang 10.0.1 ([email protected]:llvm/llvm-project.git llvmorg-10.0.1-0-gef32c611a Using HOMEDIR/Dev/ansible-site/ansible.cfg as config file setting up inventory plugins Parsed HOMEDIR/Dev/ansible-site/inventories/zee/hosts.yml inventory source with yaml plugin Loading callback plugin default of type stdout, v2.0 from HOMEDIR/Dev/ansible-site/.venv/lib/python3.7/site-packages/ansible/plugins/callback/default.py PLAYBOOK: sns_test.yml ******************************************************************************************************************************** Positional arguments: sns_test.yml verbosity: 4 connection: smart timeout: 10 become_method: sudo tags: ('all',) inventory: ('HOMEDIR/Dev/ansible-site/inventories/zee',) forks: 5 1 plays in sns_test.yml PLAY [aws_client] ************************************************************************************************************************************* META: ran handlers Trying secret ScriptVaultSecret(filename='HOMEDIR/.homesick/repos/dotfiles/home/bin/get_ansible_vault_password.sh') for vault_id=default Trying secret ScriptVaultSecret(filename='HOMEDIR/.homesick/repos/dotfiles/home/bin/get_ansible_vault_password.sh') for vault_id=default TASK [sns_topic] ************************************************************************************************************************************** task path: HOMEDIR/Dev/ansible-site/sns_test.yml:6 <localhost> ESTABLISH LOCAL CONNECTION FOR USER: USERNAME <localhost> EXEC /bin/sh -c 'echo ~USERNAME && sleep 0' <localhost> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo HOMEDIR/.ansible/tmp `"&& mkdir "` echo HOMEDIR/.ansible/tmp/ansible-tmp-1614793769.8479924-71437-25683009179857 `" && echo ansible-tmp-1614793769.8479924-71437-25683009179857="` echo HOMEDIR/.ansible/tmp/ansible-tmp-1614793769.8479924-71437-25683009179857 `" ) && sleep 0' Using module file HOMEDIR/Dev/ansible-site/.venv/lib/python3.7/site-packages/ansible/modules/cloud/amazon/sns_topic.py <localhost> PUT HOMEDIR/.ansible/tmp/ansible-local-71384z34ghj5q/tmp19on15xu TO HOMEDIR/.ansible/tmp/ansible-tmp-1614793769.8479924-71437-25683009179857/AnsiballZ_sns_topic.py <localhost> EXEC /bin/sh -c 'chmod u+x HOMEDIR/.ansible/tmp/ansible-tmp-1614793769.8479924-71437-25683009179857/ HOMEDIR/.ansible/tmp/ansible-tmp-1614793769.8479924-71437-25683009179857/AnsiballZ_sns_topic.py && sleep 0' <localhost> EXEC /bin/sh -c 'HOMEDIR/Dev/ansible-site/.venv/bin/python3.7m HOMEDIR/.ansible/tmp/ansible-tmp-1614793769.8479924-71437-25683009179857/AnsiballZ_sns_topic.py && sleep 0' <localhost> EXEC /bin/sh -c 'rm -f -r HOMEDIR/.ansible/tmp/ansible-tmp-1614793769.8479924-71437-25683009179857/ > /dev/null 2>&1 && sleep 0' changed: [aws_client] => { "changed": true, "invocation": { "module_args": { "aws_access_key": "ACCESS_KEY_ID", "aws_secret_key": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER", "debug_botocore_endpoint_logs": false, "delivery_policy": null, "display_name": "Test Topic", "ec2_url": null, "name": "Test_Topic", "policy": null, "profile": null, "purge_subscriptions": true, "region": "us-east-1", "security_token": null, "state": "present", "subscriptions": [ { "endpoint": "+1VALIDMOBILE", "protocol": "sms" } ], "validate_certs": true } }, "sns_arn": "arn:aws:sns:us-east-1:AWS_ACCOUNT_ID:Test_Topic", "sns_topic": { "attributes_set": [], "check_mode": false, "delivery_policy": "{\"http\":{\"defaultHealthyRetryPolicy\":{\"minDelayTarget\":20,\"maxDelayTarget\":20,\"numRetries\":3,\"numMaxDelayRetries\":0,\"numNoDelayRetries\":0,\"numMinDelayRetries\":0,\"backoffFunction\":\"linear\"},\"disableSubscriptionOverrides\":false}}", "display_name": "Test Topic", "name": "Test_Topic", "owner": "AWS_ACCOUNT_ID", "policy": "{\"Version\":\"2008-10-17\",\"Id\":\"__default_policy_ID\",\"Statement\":[{\"Sid\":\"__default_statement_ID\",\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"*\"},\"Action\":[\"SNS:GetTopicAttributes\",\"SNS:SetTopicAttributes\",\"SNS:AddPermission\",\"SNS:RemovePermission\",\"SNS:DeleteTopic\",\"SNS:Subscribe\",\"SNS:ListSubscriptionsByTopic\",\"SNS:Publish\",\"SNS:Receive\"],\"Resource\":\"arn:aws:sns:us-east-1:AWS_ACCOUNT_ID:Test_Topic\",\"Condition\":{\"StringEquals\":{\"AWS:SourceOwner\":\"AWS_ACCOUNT_ID\"}}}]}", "state": "present", "subscriptions": [ { "endpoint": "+1VALIDMOBILE", "owner": "AWS_ACCOUNT_ID", "protocol": "sms", "subscription_arn": "arn:aws:sns:us-east-1:AWS_ACCOUNT_ID:Test_Topic:8842de3c-25db-4f90-bc10-b7a51669ccc3", "topic_arn": "arn:aws:sns:us-east-1:AWS_ACCOUNT_ID:Test_Topic" } ], "subscriptions_added": [ [ "sms", "1VALIDMOBILE" ] ], "subscriptions_confirmed": "0", "subscriptions_deleted": "0", "subscriptions_existing": [], "subscriptions_new": [ { "endpoint": "+1VALIDMOBILE", "protocol": "sms" } ], "subscriptions_pending": "0", "subscriptions_purge": true, "topic_arn": "arn:aws:sns:us-east-1:AWS_ACCOUNT_ID:Test_Topic", "topic_created": false, "topic_deleted": false } } META: ran handlers META: ran handlers PLAY RECAP ******************************************************************************************************************************************** aws_client : ok=1 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 ``` </details> sns_topic module always deletes and replaces SMS subscriptions <!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> The `sns_topic` module always deletes and replaces SMS subscriptions, because the [`_canonicalize_endpoint()` function](https://github.com/ansible-collections/community.aws/blob/52fb23054101acbd78e13a45048ddcf935899586/plugins/modules/sns_topic.py#L353) strips all non-numeric characters. A leading `+` character is added by AWS when a new subscription is created, so the `sns_topic` module never sees its previously-created subscriptions. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME sns_topic ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.9.15 config file = None configured module search path = ['$HOME/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = $HOME/Dev/ansible-site/.venv/lib/python3.7/site-packages/ansible executable location = $HOME/Dev/ansible-site/.venv/bin/ansible python version = 3.7.9 (default, Feb 1 2021, 15:19:48) [Clang 10.0.1 ([email protected]:llvm/llvm-project.git llvmorg-10.0.1-0-gef32c611a ``` ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> 1. Run the following playbook 2. Confirm the SNS subscription 3. Run the playbook again <!--- Paste example playbooks or commands between quotes below --> ```yaml --- - hosts: localhost gather_facts: no vars: aws_access_key_id: KEYID aws_secret_access_key: SECRET aws_region: REGION # Must include leading plus and country code (+1 for North America) mobile_number: YOUR_VALID_MOBILE tasks: - sns_topic: aws_access_key: '{{ aws_access_key_id }}' aws_secret_key: '{{ aws_secret_access_key }}' region: '{{ aws_region }}' name: Test_Topic state: present display_name: Test Topic subscriptions: - protocol: sms endpoint: '{{ mobile_number }}' ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> On the first run, the task result is `changed`. On the second run, the task result is `ok`. ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> The task result is `changed` on both runs. <!--- Paste verbatim command output between quotes --> <details><summary>Verbatim command output</summary> ```console $ ansible-playbook -vvvv sns_test.yml ansible-playbook 2.9.15 config file = HOMEDIR/Dev/ansible-site/ansible.cfg configured module search path = ['HOMEDIR/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = HOMEDIR/Dev/ansible-site/.venv/lib/python3.7/site-packages/ansible executable location = HOMEDIR/Dev/ansible-site/.venv/bin/ansible-playbook python version = 3.7.9 (default, Feb 1 2021, 15:19:48) [Clang 10.0.1 ([email protected]:llvm/llvm-project.git llvmorg-10.0.1-0-gef32c611a Using HOMEDIR/Dev/ansible-site/ansible.cfg as config file setting up inventory plugins Parsed HOMEDIR/Dev/ansible-site/inventories/zee/hosts.yml inventory source with yaml plugin Loading callback plugin default of type stdout, v2.0 from HOMEDIR/Dev/ansible-site/.venv/lib/python3.7/site-packages/ansible/plugins/callback/default.py PLAYBOOK: sns_test.yml ******************************************************************************************************************************** Positional arguments: sns_test.yml verbosity: 4 connection: smart timeout: 10 become_method: sudo tags: ('all',) inventory: ('HOMEDIR/Dev/ansible-site/inventories/DIRNAME',) forks: 5 1 plays in sns_test.yml PLAY [aws_client] ************************************************************************************************************************************* META: ran handlers Trying secret ScriptVaultSecret(filename='HOMEDIR/bin/get_ansible_vault_password.sh') for vault_id=default Trying secret ScriptVaultSecret(filename='HOMEDIR/bin/get_ansible_vault_password.sh') for vault_id=default TASK [sns_topic] ************************************************************************************************************************************** task path: HOMEDIR/Dev/ansible-site/sns_test.yml:6 <localhost> ESTABLISH LOCAL CONNECTION FOR USER: USERNAME <localhost> EXEC /bin/sh -c 'echo ~USERNAME && sleep 0' <localhost> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo HOMEDIR/.ansible/tmp `"&& mkdir "` echo HOMEDIR/.ansible/tmp/ansible-tmp-1614793718.438763-70642-181606092157004 `" && echo ansible-tmp-1614793718.438763-70642-181606092157004="` echo HOMEDIR/.ansible/tmp/ansible-tmp-1614793718.438763-70642-181606092157004 `" ) && sleep 0' Using module file HOMEDIR/Dev/ansible-site/.venv/lib/python3.7/site-packages/ansible/modules/cloud/amazon/sns_topic.py <localhost> PUT HOMEDIR/.ansible/tmp/ansible-local-70581b86ao8uh/tmp1hmf83g4 TO HOMEDIR/.ansible/tmp/ansible-tmp-1614793718.438763-70642-181606092157004/AnsiballZ_sns_topic.py <localhost> EXEC /bin/sh -c 'chmod u+x HOMEDIR/.ansible/tmp/ansible-tmp-1614793718.438763-70642-181606092157004/ HOMEDIR/.ansible/tmp/ansible-tmp-1614793718.438763-70642-181606092157004/AnsiballZ_sns_topic.py && sleep 0' <localhost> EXEC /bin/sh -c 'HOMEDIR/Dev/ansible-site/.venv/bin/python3.7m HOMEDIR/.ansible/tmp/ansible-tmp-1614793718.438763-70642-181606092157004/AnsiballZ_sns_topic.py && sleep 0' <localhost> EXEC /bin/sh -c 'rm -f -r HOMEDIR/.ansible/tmp/ansible-tmp-1614793718.438763-70642-181606092157004/ > /dev/null 2>&1 && sleep 0' changed: [aws_client] => { "changed": true, "invocation": { "module_args": { "aws_access_key": "AKIAJA6ZHTNW5FLJYE3Q", "aws_secret_key": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER", "debug_botocore_endpoint_logs": false, "delivery_policy": null, "display_name": "Test Topic", "ec2_url": null, "name": "Test_Topic", "policy": null, "profile": null, "purge_subscriptions": true, "region": "us-east-1", "security_token": null, "state": "present", "subscriptions": [ { "endpoint": "+1VALIDMOBILE", "protocol": "sms" } ], "validate_certs": true } }, "sns_arn": "arn:aws:sns:us-east-1:AWS_ACCOUNT_ID:Test_Topic", "sns_topic": { "attributes_set": [ "display_name" ], "check_mode": false, "delivery_policy": "{\"http\":{\"defaultHealthyRetryPolicy\":{\"minDelayTarget\":20,\"maxDelayTarget\":20,\"numRetries\":3,\"numMaxDelayRetries\":0,\"numNoDelayRetries\":0,\"numMinDelayRetries\":0,\"backoffFunction\":\"linear\"},\"disableSubscriptionOverrides\":false}}", "display_name": "Test Topic", "name": "Test_Topic", "owner": "AWS_ACCOUNT_ID", "policy": "{\"Version\":\"2008-10-17\",\"Id\":\"__default_policy_ID\",\"Statement\":[{\"Sid\":\"__default_statement_ID\",\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"*\"},\"Action\":[\"SNS:GetTopicAttributes\",\"SNS:SetTopicAttributes\",\"SNS:AddPermission\",\"SNS:RemovePermission\",\"SNS:DeleteTopic\",\"SNS:Subscribe\",\"SNS:ListSubscriptionsByTopic\",\"SNS:Publish\",\"SNS:Receive\"],\"Resource\":\"arn:aws:sns:us-east-1:AWS_ACCOUNT_ID:Test_Topic\",\"Condition\":{\"StringEquals\":{\"AWS:SourceOwner\":\"AWS_ACCOUNT_ID\"}}}]}", "state": "present", "subscriptions": [ { "endpoint": "+1VALIDMOBILE", "owner": "AWS_ACCOUNT_ID", "protocol": "sms", "subscription_arn": "arn:aws:sns:us-east-1:AWS_ACCOUNT_ID:Test_Topic:19322f05-0265-479b-84c8-e5669a24ac0c", "topic_arn": "arn:aws:sns:us-east-1:AWS_ACCOUNT_ID:Test_Topic" } ], "subscriptions_added": [ [ "sms", "1VALIDMOBILE" ] ], "subscriptions_confirmed": "0", "subscriptions_deleted": "0", "subscriptions_existing": [], "subscriptions_new": [ { "endpoint": "+1VALIDMOBILE", "protocol": "sms" } ], "subscriptions_pending": "0", "subscriptions_purge": true, "topic_arn": "arn:aws:sns:us-east-1:AWS_ACCOUNT_ID:Test_Topic", "topic_created": false, "topic_deleted": false } } META: ran handlers META: ran handlers PLAY RECAP ******************************************************************************************************************************************** aws_client : ok=1 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 $ # Confirmed subscription in AWS console $ ansible-playbook -vvvv sns_test.yml ansible-playbook 2.9.15 config file = HOMEDIR/Dev/ansible-site/ansible.cfg configured module search path = ['HOMEDIR/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = HOMEDIR/Dev/ansible-site/.venv/lib/python3.7/site-packages/ansible executable location = HOMEDIR/Dev/ansible-site/.venv/bin/ansible-playbook python version = 3.7.9 (default, Feb 1 2021, 15:19:48) [Clang 10.0.1 ([email protected]:llvm/llvm-project.git llvmorg-10.0.1-0-gef32c611a Using HOMEDIR/Dev/ansible-site/ansible.cfg as config file setting up inventory plugins Parsed HOMEDIR/Dev/ansible-site/inventories/zee/hosts.yml inventory source with yaml plugin Loading callback plugin default of type stdout, v2.0 from HOMEDIR/Dev/ansible-site/.venv/lib/python3.7/site-packages/ansible/plugins/callback/default.py PLAYBOOK: sns_test.yml ******************************************************************************************************************************** Positional arguments: sns_test.yml verbosity: 4 connection: smart timeout: 10 become_method: sudo tags: ('all',) inventory: ('HOMEDIR/Dev/ansible-site/inventories/zee',) forks: 5 1 plays in sns_test.yml PLAY [aws_client] ************************************************************************************************************************************* META: ran handlers Trying secret ScriptVaultSecret(filename='HOMEDIR/.homesick/repos/dotfiles/home/bin/get_ansible_vault_password.sh') for vault_id=default Trying secret ScriptVaultSecret(filename='HOMEDIR/.homesick/repos/dotfiles/home/bin/get_ansible_vault_password.sh') for vault_id=default TASK [sns_topic] ************************************************************************************************************************************** task path: HOMEDIR/Dev/ansible-site/sns_test.yml:6 <localhost> ESTABLISH LOCAL CONNECTION FOR USER: USERNAME <localhost> EXEC /bin/sh -c 'echo ~USERNAME && sleep 0' <localhost> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo HOMEDIR/.ansible/tmp `"&& mkdir "` echo HOMEDIR/.ansible/tmp/ansible-tmp-1614793769.8479924-71437-25683009179857 `" && echo ansible-tmp-1614793769.8479924-71437-25683009179857="` echo HOMEDIR/.ansible/tmp/ansible-tmp-1614793769.8479924-71437-25683009179857 `" ) && sleep 0' Using module file HOMEDIR/Dev/ansible-site/.venv/lib/python3.7/site-packages/ansible/modules/cloud/amazon/sns_topic.py <localhost> PUT HOMEDIR/.ansible/tmp/ansible-local-71384z34ghj5q/tmp19on15xu TO HOMEDIR/.ansible/tmp/ansible-tmp-1614793769.8479924-71437-25683009179857/AnsiballZ_sns_topic.py <localhost> EXEC /bin/sh -c 'chmod u+x HOMEDIR/.ansible/tmp/ansible-tmp-1614793769.8479924-71437-25683009179857/ HOMEDIR/.ansible/tmp/ansible-tmp-1614793769.8479924-71437-25683009179857/AnsiballZ_sns_topic.py && sleep 0' <localhost> EXEC /bin/sh -c 'HOMEDIR/Dev/ansible-site/.venv/bin/python3.7m HOMEDIR/.ansible/tmp/ansible-tmp-1614793769.8479924-71437-25683009179857/AnsiballZ_sns_topic.py && sleep 0' <localhost> EXEC /bin/sh -c 'rm -f -r HOMEDIR/.ansible/tmp/ansible-tmp-1614793769.8479924-71437-25683009179857/ > /dev/null 2>&1 && sleep 0' changed: [aws_client] => { "changed": true, "invocation": { "module_args": { "aws_access_key": "ACCESS_KEY_ID", "aws_secret_key": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER", "debug_botocore_endpoint_logs": false, "delivery_policy": null, "display_name": "Test Topic", "ec2_url": null, "name": "Test_Topic", "policy": null, "profile": null, "purge_subscriptions": true, "region": "us-east-1", "security_token": null, "state": "present", "subscriptions": [ { "endpoint": "+1VALIDMOBILE", "protocol": "sms" } ], "validate_certs": true } }, "sns_arn": "arn:aws:sns:us-east-1:AWS_ACCOUNT_ID:Test_Topic", "sns_topic": { "attributes_set": [], "check_mode": false, "delivery_policy": "{\"http\":{\"defaultHealthyRetryPolicy\":{\"minDelayTarget\":20,\"maxDelayTarget\":20,\"numRetries\":3,\"numMaxDelayRetries\":0,\"numNoDelayRetries\":0,\"numMinDelayRetries\":0,\"backoffFunction\":\"linear\"},\"disableSubscriptionOverrides\":false}}", "display_name": "Test Topic", "name": "Test_Topic", "owner": "AWS_ACCOUNT_ID", "policy": "{\"Version\":\"2008-10-17\",\"Id\":\"__default_policy_ID\",\"Statement\":[{\"Sid\":\"__default_statement_ID\",\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"*\"},\"Action\":[\"SNS:GetTopicAttributes\",\"SNS:SetTopicAttributes\",\"SNS:AddPermission\",\"SNS:RemovePermission\",\"SNS:DeleteTopic\",\"SNS:Subscribe\",\"SNS:ListSubscriptionsByTopic\",\"SNS:Publish\",\"SNS:Receive\"],\"Resource\":\"arn:aws:sns:us-east-1:AWS_ACCOUNT_ID:Test_Topic\",\"Condition\":{\"StringEquals\":{\"AWS:SourceOwner\":\"AWS_ACCOUNT_ID\"}}}]}", "state": "present", "subscriptions": [ { "endpoint": "+1VALIDMOBILE", "owner": "AWS_ACCOUNT_ID", "protocol": "sms", "subscription_arn": "arn:aws:sns:us-east-1:AWS_ACCOUNT_ID:Test_Topic:8842de3c-25db-4f90-bc10-b7a51669ccc3", "topic_arn": "arn:aws:sns:us-east-1:AWS_ACCOUNT_ID:Test_Topic" } ], "subscriptions_added": [ [ "sms", "1VALIDMOBILE" ] ], "subscriptions_confirmed": "0", "subscriptions_deleted": "0", "subscriptions_existing": [], "subscriptions_new": [ { "endpoint": "+1VALIDMOBILE", "protocol": "sms" } ], "subscriptions_pending": "0", "subscriptions_purge": true, "topic_arn": "arn:aws:sns:us-east-1:AWS_ACCOUNT_ID:Test_Topic", "topic_created": false, "topic_deleted": false } } META: ran handlers META: ran handlers PLAY RECAP ******************************************************************************************************************************************** aws_client : ok=1 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 ``` </details>
Files identified in the description: None If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> @overhacked: Greetings! Thanks for taking the time to open this issue. In order for the community to handle your issue effectively, we need a bit more information. Here are the items we could not find in your description: - component name Please set the description of this issue with this template: https://raw.githubusercontent.com/ansible/ansible/devel/.github/ISSUE_TEMPLATE/bug_report.md [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: issue_missing_data ---> Files identified in the description: * [`plugins/modules/sns_topic.py`](https://github.com/['ansible-collections/amazon.aws', 'ansible-collections/community.aws', 'ansible-collections/community.vmware']/blob/main/plugins/modules/sns_topic.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @jillr @joelthompson @nand0p @s-hertel @tremble @willthames @wimnat [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> Files identified in the description: None If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> @overhacked: Greetings! Thanks for taking the time to open this issue. In order for the community to handle your issue effectively, we need a bit more information. Here are the items we could not find in your description: - component name Please set the description of this issue with this template: https://raw.githubusercontent.com/ansible/ansible/devel/.github/ISSUE_TEMPLATE/bug_report.md [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: issue_missing_data ---> Files identified in the description: * [`plugins/modules/sns_topic.py`](https://github.com/['ansible-collections/amazon.aws', 'ansible-collections/community.aws', 'ansible-collections/community.vmware']/blob/main/plugins/modules/sns_topic.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @jillr @joelthompson @nand0p @s-hertel @tremble @willthames @wimnat [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify --->
2021-03-03T18:18:46
ansible-collections/community.aws
477
ansible-collections__community.aws-477
[ "451" ]
26ad34916c017c0f1566e4606c20cd2e7a311717
diff --git a/plugins/modules/aws_acm.py b/plugins/modules/aws_acm.py --- a/plugins/modules/aws_acm.py +++ b/plugins/modules/aws_acm.py @@ -207,7 +207,7 @@ arn: description: The ARN of the certificate in ACM type: str - returned: when I(state=present) + returned: when I(state=present) and not in check mode sample: "arn:aws:acm:ap-southeast-2:123456789012:certificate/01234567-abcd-abcd-abcd-012345678901" domain_name: description: The domain name encoded within the public certificate @@ -362,30 +362,39 @@ def main(): else: module.debug("Existing certificate in ACM is different, overwriting") - # update cert in ACM - arn = acm.import_certificate(client, module, + if module.check_mode: + arn = old_cert['certificate_arn'] + # note: returned domain will be the domain of the previous cert + else: + # update cert in ACM + arn = acm.import_certificate(client, module, + certificate=module.params['certificate'], + private_key=module.params['private_key'], + certificate_chain=module.params['certificate_chain'], + arn=old_cert['certificate_arn'], + tags=tags) + domain = acm.get_domain_of_cert(client=client, module=module, arn=arn) + module.exit_json(certificate=dict(domain_name=domain, arn=arn), changed=True) + else: # len(certificates) == 0 + module.debug("No certificate in ACM. Creating new one.") + if module.check_mode: + domain = 'example.com' + module.exit_json(certificate=dict(domain_name=domain), changed=True) + else: + arn = acm.import_certificate(client=client, + module=module, certificate=module.params['certificate'], private_key=module.params['private_key'], certificate_chain=module.params['certificate_chain'], - arn=old_cert['certificate_arn'], tags=tags) domain = acm.get_domain_of_cert(client=client, module=module, arn=arn) - module.exit_json(certificate=dict(domain_name=domain, arn=arn), changed=True) - else: # len(certificates) == 0 - module.debug("No certificate in ACM. Creating new one.") - arn = acm.import_certificate(client=client, - module=module, - certificate=module.params['certificate'], - private_key=module.params['private_key'], - certificate_chain=module.params['certificate_chain'], - tags=tags) - domain = acm.get_domain_of_cert(client=client, module=module, arn=arn) - module.exit_json(certificate=dict(domain_name=domain, arn=arn), changed=True) + module.exit_json(certificate=dict(domain_name=domain, arn=arn), changed=True) else: # state == absent for cert in certificates: - acm.delete_certificate(client, module, cert['certificate_arn']) + if not module.check_mode: + acm.delete_certificate(client, module, cert['certificate_arn']) module.exit_json(arns=[cert['certificate_arn'] for cert in certificates], changed=(len(certificates) > 0))
diff --git a/tests/integration/targets/aws_acm/tasks/full_acm_test.yml b/tests/integration/targets/aws_acm/tasks/full_acm_test.yml --- a/tests/integration/targets/aws_acm/tasks/full_acm_test.yml +++ b/tests/integration/targets/aws_acm/tasks/full_acm_test.yml @@ -9,7 +9,16 @@ - name: list certs aws_acm_info: null register: list_all - failed_when: list_all.certificates is not defined + - name: list certs with check mode + aws_acm_info: null + register: list_all_check + check_mode: yes # read-only task, should work the same as with no + - name: check certificate listing worked + assert: + that: + - list_all.certificates is defined + - list_all_check.certificates is defined + - list_all.certificates == list_all_check.certificates - name: ensure absent cert which doesn't exist - first time aws_acm: name_tag: '{{ item.name }}' @@ -17,18 +26,33 @@ with_items: '{{ local_certs }}' - name: ensure absent cert which doesn't exist - second time aws_acm: - name_tag: '{{ item.name }}' + name_tag: '{{ item[0].name }}' state: absent - with_items: '{{ local_certs }}' + check_mode: '{{ item[1] }}' + with_nested: + - '{{ local_certs }}' + - [true, false] register: absent_start_two - failed_when: absent_start_two.changed + - name: check no change when ensuring absent cert is absent + assert: + that: + - not item.changed + with_items: "{{ absent_start_two.results }}" - name: list cert which shouldn't exist aws_acm_info: tags: - Name: '{{ item.name }}' + Name: '{{ item[0].name }}' register: list_tag - with_items: '{{ local_certs }}' - failed_when: list_tag.certificates | length > 0 + check_mode: '{{ item[1] }}' + with_nested: + - '{{ local_certs }}' + - [ False, True ] # read-only task, should work the same with check mode or not + - name: check listing of missing cert returns no result + with_items: "{{ list_tag.results }}" + assert: + that: + - (item.certificates | length) == 0 + - not list_tag.changed - name: check directory was made assert: that: @@ -54,6 +78,27 @@ privatekey_path: '{{ item.priv_key }}' signature_algorithms: - sha256WithRSAEncryption + - name: upload certificate with check mode + aws_acm: + name_tag: '{{ item.name }}' + certificate: '{{ lookup(''file'', item.cert ) }}' + private_key: '{{ lookup(''file'', item.priv_key ) }}' + state: present + check_mode: yes + register: upload_check + with_items: '{{ local_certs }}' + - name: check whether cert was uploaded in check mode + aws_acm_info: + tags: + Name: '{{ item.name }}' + register: list_after_check_mode_upload + with_items: '{{ local_certs }}' + - name: check cert was not really uploaded in check mode + with_items: "{{ list_after_check_mode_upload.results }}" + assert: + that: + - upload_check.changed + - (item.certificates | length) == 0 - name: upload certificates first time aws_acm: name_tag: '{{ item.name }}' @@ -61,6 +106,7 @@ private_key: '{{ lookup(''file'', item.priv_key ) }}' state: present register: upload + check_mode: no with_items: '{{ local_certs }}' until: upload is succeeded retries: 5 @@ -148,7 +194,33 @@ register: upload2 with_items: '{{ local_certs }}' failed_when: upload2.changed - - name: update first cert with body of the second, first time + - name: update first cert with body of the second, first time, check mode + aws_acm: + state: present + name_tag: '{{ local_certs[0].name }}' + certificate: '{{ lookup(''file'', local_certs[1].cert ) }}' + private_key: '{{ lookup(''file'', local_certs[1].priv_key ) }}' + check_mode: yes + register: overwrite_check + - name: check update in check mode detected required update + assert: + that: + - overwrite_check.changed + - name: check previous tasks did not change real cert + aws_acm_info: + tags: + Name: '{{ local_certs[0].name }}' + register: fetch_after_overwrite_check + - name: check update with check mode did not change real cert + assert: + that: + - fetch_after_overwrite_check.certificates | length == 1 + - fetch_after_overwrite_check.certificates[0].certificate_arn == fetch_after_up.results[0].certificates[0].certificate_arn + - fetch_after_overwrite_check.certificates[0].domain_name == local_certs[0].domain + - (fetch_after_overwrite_check.certificates[0].certificate | replace( ' ', '' ) | replace( '\n', '')) == (lookup('file', local_certs[0].cert )| replace( ' ', '' ) | replace( '\n', '')) + - '''Name'' in fetch_after_overwrite_check.certificates[0].tags' + - fetch_after_overwrite_check.certificates[0].tags['Name'] == local_certs[0].name + - name: update first cert with body of the second, first real time aws_acm: state: present name_tag: '{{ local_certs[0].name }}' @@ -206,7 +278,30 @@ - overwrite2.certificate.arn == upload.results[0].certificate.arn - overwrite2.certificate.domain_name == local_certs[1].domain - not overwrite2.changed - - name: delete certs 1 and 2 + - name: delete certs 1 and 2 in check mode + aws_acm: + state: absent + domain_name: '{{ local_certs[1].domain }}' + check_mode: yes + register: delete_both_check + - name: test deletion with check mode detected change + assert: + that: + - delete_both_check.changed + - name: fetch info for certs 1 and 2 + aws_acm_info: + tags: + Name: '{{ local_certs[item].name }}' + register: check_del_one_check + with_items: + - 0 + - 1 + - name: test deletion with check mode detected change + with_items: '{{ check_del_one_check.results }}' + assert: + that: + - (item.certificates | length) == 1 + - name: delete certs 1 and 2 real aws_acm: state: absent domain_name: '{{ local_certs[1].domain }}' @@ -234,13 +329,16 @@ - name: check certs 1 and 2 were already deleted with_items: '{{ check_del_one.results }}' assert: - that: item.certificates | length == 0 - - name: check cert 3 not deleted + that: (item.certificates | length) == 0 + - name: check cert 3 aws_acm_info: tags: Name: '{{ local_certs[2].name }}' register: check_del_one_remain - failed_when: check_del_one_remain.certificates | length != 1 + - name: check cert 3 not deleted + assert: + that: + - (check_del_one_remain.certificates | length) == 1 - name: delete cert 3 aws_acm: state: absent @@ -270,6 +368,16 @@ - delete_third.arns is defined - delete_third.arns | length == 0 - not delete_third.changed + - name: delete cert 3 again, check mode + aws_acm: + state: absent + domain_name: '{{ local_certs[2].domain }}' + check_mode: yes + register: delete_third_check + - name: test deletion in check mode detected required change + assert: + that: + - not delete_third_check.changed - name: check directory was made assert: that:
ACM module has no "check" mode <!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY When running a playbook in check mode, changes are affected. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME aws_acm ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below $ aws --version aws-cli/1.19.17 Python/3.6.9 Linux/4.15.0-136-generic botocore/1.20.16 ``` ##### CONFIGURATION ```paste below $ ansible-config dump --only-changed ANSIBLE_PIPELINING(./myproject/ansible.cfg) = True ANSIBLE_SSH_CONTROL_PATH(./myproject/ansible.cfg) = ~/.ssh/ansible-ssh-%%C COLLECTIONS_PATHS(./myproject/ansible.cfg) = ['./myproject/collections'] DEFAULT_CALLBACK_PLUGIN_PATH(./myproject/ansible.cfg) = ['./myproject/callbacks'] DEFAULT_FORKS(./myproject/ansible.cfg) = 20 DEFAULT_ROLES_PATH(./myproject/ansible.cfg) = ['./myproject/roles'] INTERPRETER_PYTHON(./myproject/ansible.cfg) = /usr/bin/python3 INVENTORY_IGNORE_PATTERNS(./myproject/ansible.cfg) = ['ssh-config'] RETRY_FILES_ENABLED(./myproject/ansible.cfg) = False ``` ##### OS / ENVIRONMENT ``` $ uname -a Linux mybox 4.15.0-136-generic #140-Ubuntu SMP Thu Jan 28 05:20:47 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux ``` ##### STEPS TO REPRODUCE Full playbook is at https://gist.github.com/dale-c-anderson/31c6212e8a9e86f4a829e2bdee40a6f8 The relevant portion is reproduced here: ```yaml - hosts: localhost run_once: true become: false connection: local vars_files: - "{{ playbook_dir }}/path_definitions.yml" tags: - install_certs tasks: - name: Import SSL cert to AWS Certificate Manager community.aws.aws_acm: state: present region: ca-central-1 certificate: "{{ lookup('file', ssl_public_certs_dir + '/dummy.crt') }}" private_key: "{{ lookup('file', ssl_private_keys_dir + '/dummy.key') }}" # Key has already been encrypted. name_tag: dummy.example.com ``` Ran the above with ```bash ansible-playbook --diff --check --tags install_certs ``` ##### EXPECTED RESULTS Certificate import should only be simulated. ##### ACTUAL RESULTS Certificate was actually imported. <!--- Paste verbatim command output between quotes --> ```paste below $ ansible-playbook playbooks/ssl-999-bug-report.yml --diff --check --tags install_certs [WARNING]: No inventory was parsed, only implicit localhost is available [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all' [WARNING]: Skipping plugin (/home/danderson/repos/git.acromedia.com/teams/telus/project-lion/telus-lion-drupal-infrastructure/callbacks/human-log.py) as it seems to be invalid: name 'reload' is not defined PLAY [localhost] ******************************************************************************************************************************************************************************************** PLAY [localhost] ******************************************************************************************************************************************************************************************** TASK [Gathering Facts] ************************************************************************************************************************************************************************************** ok: [localhost] TASK [Import SSL cert to AWS Certificate Manager] *********************************************************************************************************************************************************** changed: [localhost] PLAY RECAP ************************************************************************************************************************************************************************************************** localhost : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 ``` ![image](https://user-images.githubusercontent.com/634971/109711209-73c93400-7b53-11eb-967a-316ecdc570af.png) ![image](https://user-images.githubusercontent.com/634971/109711248-817eb980-7b53-11eb-801c-8d2e458fcf93.png)
Files identified in the description: None If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> Files identified in the description: * [`plugins/modules/aws_acm.py`](https://github.com/['ansible-collections/amazon.aws', 'ansible-collections/community.aws', 'ansible-collections/community.vmware']/blob/main/plugins/modules/aws_acm.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @jillr @matt-telstra @s-hertel @tremble @wimnat [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> Ah, woops. I never use check mode myself, so I forgot to put this in. What's check mode supposed to do? Just check the input parameters match the module spec? Or should it check that it can find IAM credentials? Some boto calls allow you to do a "dry_run" to check that you've got sufficient IAM permissions, but I expect that this particular call does not. @matt-telstra See https://docs.ansible.com/ansible/latest/user_guide/playbooks_checkmode.html Yes, check mode and dry run are the same thing. If the boto call doesn't support dry run directly, the module would probably need simulate it in some other way. Having a module that affects changes when it's not supposed to will result in a never-ending litany of bug reports. For testing in my own projects (outside of Ansible), I use moto. I suppose I could just turn on moto and do the checks that way? Although that would start with a clean slate for every task. So deleting a cert would throw an error because the cert doesn't exist. So I'd have to handle that case. I'm not sure whether other Ansible AWS modules use moto. That would add a dependency to the module. Is that worth it? It looks like some modules [only check the input](https://github.com/ansible-collections/amazon.aws/blob/76aeec280994454fc2e99fcf3996e5a5ab1e8184/plugins/modules/aws_s3.py#L389). Others say `supports_check_mode=False` ([example](https://github.com/matt-telstra/community.aws/blob/52fb23054101acbd78e13a45048ddcf935899586/plugins/modules/aws_api_gateway.py#L209)), although I'm not sure what that does. @jillr what do AWS modules normally do in check mode? Just validate the input? Or is there a helper function I can call to check IAM credentials? Would we expect an AWS task to fail in check mode if no IAM credentials can be found? Is this the kind of thing we need? https://github.com/matt-telstra/community.aws/commit/0df3af8b3354ebcbae21101403e0061ab4315ff1 (I haven't created a PR yet, because I haven't written the tests for this, or tested it manually, yet) The idea of "check_mode" is generally to tell you if changes would be made. The most common way to do this is just to exit with changed=True or return True from a function (depending on the structure of the module) just before you'd apply a change. Generally read-only (get, list or describe) calls should still happen. Please note, the Boto/AWS check mode only tests permissions, not if a change would occur, and is especially useless on read-only operations.
2021-03-14T02:32:01
ansible-collections/community.aws
493
ansible-collections__community.aws-493
[ "492" ]
95ecf7d9b6b6afac9a2f19f72b7d6db00a53a035
diff --git a/plugins/modules/ec2_asg.py b/plugins/modules/ec2_asg.py --- a/plugins/modules/ec2_asg.py +++ b/plugins/modules/ec2_asg.py @@ -1260,25 +1260,22 @@ def create_autoscaling_group(connection): # Get differences wanted_tgs = set(target_group_arns) has_tgs = set(as_group['TargetGroupARNs']) - # check if all requested are already existing - if has_tgs.issuperset(wanted_tgs): - # if wanted contains less than existing, then we need to delete some - tgs_to_detach = has_tgs.difference(wanted_tgs) - if tgs_to_detach: - changed = True - try: - detach_lb_target_groups(connection, group_name, list(tgs_to_detach)) - except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: - module.fail_json_aws(e, msg="Failed to detach load balancer target groups {0}".format(tgs_to_detach)) - if wanted_tgs.issuperset(has_tgs): - # if has contains less than wanted, then we need to add some - tgs_to_attach = wanted_tgs.difference(has_tgs) - if tgs_to_attach: - changed = True - try: - attach_lb_target_groups(connection, group_name, list(tgs_to_attach)) - except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: - module.fail_json(msg="Failed to attach load balancer target groups {0}".format(tgs_to_attach)) + + tgs_to_detach = has_tgs.difference(wanted_tgs) + if tgs_to_detach: + changed = True + try: + detach_lb_target_groups(connection, group_name, list(tgs_to_detach)) + except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: + module.fail_json_aws(e, msg="Failed to detach load balancer target groups {0}".format(tgs_to_detach)) + + tgs_to_attach = wanted_tgs.difference(has_tgs) + if tgs_to_attach: + changed = True + try: + attach_lb_target_groups(connection, group_name, list(tgs_to_attach)) + except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: + module.fail_json(msg="Failed to attach load balancer target groups {0}".format(tgs_to_attach)) # check for attributes that aren't required for updating an existing ASG # check if min_size/max_size/desired capacity have been specified and if not use ASG values
diff --git a/tests/integration/targets/ec2_asg/tasks/main.yml b/tests/integration/targets/ec2_asg/tasks/main.yml --- a/tests/integration/targets/ec2_asg/tasks/main.yml +++ b/tests/integration/targets/ec2_asg/tasks/main.yml @@ -695,6 +695,134 @@ - "output.mixed_instances_policy_full['instances_distribution']['on_demand_percentage_above_base_capacity'] == 0" - "output.mixed_instances_policy_full['instances_distribution']['spot_allocation_strategy'] == 'capacity-optimized'" + # ============================================================ + + # Target group names have max length of 32 characters + - set_fact: + tg1_name: "{{ (resource_prefix + '-tg1' ) | regex_search('(.{1,32})$') }}" + tg2_name: "{{ (resource_prefix + '-tg2' ) | regex_search('(.{1,32})$') }}" + + - name: create target group 1 + elb_target_group: + name: "{{ tg1_name }}" + protocol: tcp + port: 80 + health_check_protocol: tcp + health_check_port: 80 + healthy_threshold_count: 2 + unhealthy_threshold_count: 2 + vpc_id: "{{ testing_vpc.vpc.id }}" + state: present + register: out_tg1 + + - name: create target group 2 + elb_target_group: + name: "{{ tg2_name }}" + protocol: tcp + port: 80 + health_check_protocol: tcp + health_check_port: 80 + healthy_threshold_count: 2 + unhealthy_threshold_count: 2 + vpc_id: "{{ testing_vpc.vpc.id }}" + state: present + register: out_tg2 + + - name: update autoscaling group with tg1 + ec2_asg: + name: "{{ resource_prefix }}-asg" + launch_template: + launch_template_name: "{{ resource_prefix }}-lt" + target_group_arns: + - "{{ out_tg1.target_group_arn }}" + desired_capacity: 1 + min_size: 1 + max_size: 1 + state: present + wait_for_instances: yes + register: output + + - assert: + that: + - output.target_group_arns[0] == out_tg1.target_group_arn + + - name: update autoscaling group add tg2 + ec2_asg: + name: "{{ resource_prefix }}-asg" + launch_template: + launch_template_name: "{{ resource_prefix }}-lt" + target_group_arns: + - "{{ out_tg1.target_group_arn }}" + - "{{ out_tg2.target_group_arn }}" + desired_capacity: 1 + min_size: 1 + max_size: 1 + state: present + wait_for_instances: yes + register: output + + - assert: + that: + - "output.target_group_arns | length == 2" + + - name: update autoscaling group remove tg1 + ec2_asg: + name: "{{ resource_prefix }}-asg" + launch_template: + launch_template_name: "{{ resource_prefix }}-lt" + target_group_arns: + - "{{ out_tg2.target_group_arn }}" + desired_capacity: 1 + min_size: 1 + max_size: 1 + state: present + wait_for_instances: yes + register: output + + - assert: + that: + - "output.target_group_arns | length == 1" + - "output.target_group_arns[0] == out_tg2.target_group_arn" + + - name: update autoscaling group remove tg2 and add tg1 + ec2_asg: + name: "{{ resource_prefix }}-asg" + launch_template: + launch_template_name: "{{ resource_prefix }}-lt" + target_group_arns: + - "{{ out_tg1.target_group_arn }}" + desired_capacity: 1 + min_size: 1 + max_size: 1 + state: present + wait_for_instances: yes + register: output + + - assert: + that: + - "output.target_group_arns | length == 1" + - "output.target_group_arns[0] == out_tg1.target_group_arn" + + - name: target group no change + ec2_asg: + name: "{{ resource_prefix }}-asg" + launch_template: + launch_template_name: "{{ resource_prefix }}-lt" + target_group_arns: + - "{{ out_tg1.target_group_arn }}" + desired_capacity: 1 + min_size: 1 + max_size: 1 + state: present + wait_for_instances: yes + register: output + + - assert: + that: + - "output.target_group_arns | length == 1" + - "output.target_group_arns[0] == out_tg1.target_group_arn" + - "output.changed == false" + # ============================================================ always: @@ -710,6 +838,18 @@ # Remove the testing dependencies + - name: remove target group + elb_target_group: + name: "{{ item }}" + state: absent + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10 + loop: + - "{{ tg1_name }}" + - "{{ tg2_name }}" + - name: remove the load balancer ec2_elb_lb: name: "{{ load_balancer_name }}" @@ -738,7 +878,7 @@ - name: remove launch configs ec2_lc: - name: "{{ resource_prefix }}-lc" + name: "{{ item }}" state: absent register: removed until: removed is not failed
ec2_asg not updating target group ##### SUMMARY Previously reported at https://github.com/ansible/ansible/issues/65008. But in the repo migrations it looks like it got closed without ever getting fixed. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME ec2_asg ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ``` ansible 2.10.6 config file = None configured module search path = ['/home/msven/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /home/msven/python3/venv/lib/python3.6/site-packages/ansible executable location = /home/msven/python3/venv/bin/ansible python version = 3.6.9 (default, Jan 26 2021, 15:33:00) [GCC 8.4.0] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ``` COLLECTIONS_PATHS(env: ANSIBLE_COLLECTIONS_PATH) = ['/home/msven/git/ansible_collections', '/home/msven'] ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> 1. Create new ec2 auto scaling group 2. Create new target group or attach existing target group via target_group_arns property under ec2_asg module. 3. Now create new target group and update target_group_arns with new arn. <!--- Paste example playbooks or commands between quotes below --> <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> * New target group should get attached to asg and old should be removed. ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> * Target group doesn't get updated with new arn. <!--- Paste verbatim command output between quotes -->
Files identified in the description: * [`plugins/modules/ec2_asg.py`](https://github.com/['ansible-collections/amazon.aws', 'ansible-collections/community.aws', 'ansible-collections/community.vmware']/blob/main/plugins/modules/ec2_asg.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @garethr @jillr @s-hertel @tremble @wimnat [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> I have a fix for this and will submit a PR to fix soon.
2021-03-23T02:38:45
ansible-collections/community.aws
506
ansible-collections__community.aws-506
[ "246" ]
a38682a79ede336de99cbec977b050bc8c49832e
diff --git a/plugins/modules/cloudtrail.py b/plugins/modules/cloudtrail.py --- a/plugins/modules/cloudtrail.py +++ b/plugins/modules/cloudtrail.py @@ -261,6 +261,24 @@ ) +def get_kms_key_aliases(module, client, keyId): + """ + get list of key aliases + + module : AnsibleAWSModule object + client : boto3 client connection object for kms + keyId : keyId to get aliases for + """ + try: + key_resp = client.list_aliases(KeyId=keyId) + except (BotoCoreError, ClientError) as err: + # Don't fail here, just return [] to maintain backwards compat + # in case user doesn't have kms:ListAliases permissions + return [] + + return key_resp['Aliases'] + + def create_trail(module, client, ct_params): """ Creates a CloudTrail @@ -500,6 +518,7 @@ def main(): # If the trail exists set the result exists variable if trail is not None: results['exists'] = True + initial_kms_key_id = trail.get('KmsKeyId') if state == 'absent' and results['exists']: # If Trail exists go ahead and delete @@ -524,7 +543,11 @@ def main(): val = ct_params.get(key) if val != trail.get(tkey): do_update = True - results['changed'] = True + if tkey != 'KmsKeyId': + # We'll check if the KmsKeyId casues changes later since + # user could've provided a key alias, alias arn, or key id + # and trail['KmsKeyId'] is always a key arn + results['changed'] = True # If we are in check mode copy the changed values to the trail facts in result output to show what would change. if module.check_mode: trail.update({tkey: ct_params.get(key)}) @@ -533,6 +556,26 @@ def main(): update_trail(module, client, ct_params) trail = get_trail_facts(module, client, ct_params['Name']) + # Determine if KmsKeyId changed + if not module.check_mode: + if initial_kms_key_id != trail.get('KmsKeyId'): + results['changed'] = True + else: + new_key = ct_params.get('KmsKeyId') + if initial_kms_key_id != new_key: + # Assume changed for a moment + results['changed'] = True + + # However, new_key could be a key id, alias arn, or alias name + # that maps back to the key arn in initial_kms_key_id. So check + # all aliases for a match. + initial_aliases = get_kms_key_aliases(module, module.client('kms'), initial_kms_key_id) + for a in initial_aliases: + if(a['AliasName'] == new_key or + a['AliasArn'] == new_key or + a['TargetKeyId'] == new_key): + results['changed'] = False + # Check if we need to start/stop logging if enable_logging and not trail['IsLogging']: results['changed'] = True @@ -554,11 +597,12 @@ def main(): results['changed'] = True trail['tags'] = tags # Populate trail facts in output - results['trail'] = camel_dict_to_snake_dict(trail) + results['trail'] = camel_dict_to_snake_dict(trail, ignore_list=['tags']) elif state == 'present' and not results['exists']: # Trail doesn't exist just go create it results['changed'] = True + results['exists'] = True if not module.check_mode: # If we aren't in check_mode then actually create it created_trail = create_trail(module, client, ct_params) @@ -598,7 +642,7 @@ def main(): trail['IsLogging'] = enable_logging trail['tags'] = tags # Populate trail facts in output - results['trail'] = camel_dict_to_snake_dict(trail) + results['trail'] = camel_dict_to_snake_dict(trail, ignore_list=['tags']) module.exit_json(**results)
diff --git a/tests/integration/targets/cloudtrail/defaults/main.yml b/tests/integration/targets/cloudtrail/defaults/main.yml --- a/tests/integration/targets/cloudtrail/defaults/main.yml +++ b/tests/integration/targets/cloudtrail/defaults/main.yml @@ -5,3 +5,4 @@ sns_topic: '{{ resource_prefix }}-cloudtrail-notifications' cloudtrail_prefix: 'test-prefix' cloudwatch_log_group: '{{ resource_prefix }}-cloudtrail' cloudwatch_role: '{{ resource_prefix }}-cloudtrail' +cloudwatch_no_kms_role: '{{ resource_prefix }}-cloudtrail2' diff --git a/tests/integration/targets/cloudtrail/tasks/main.yml b/tests/integration/targets/cloudtrail/tasks/main.yml --- a/tests/integration/targets/cloudtrail/tasks/main.yml +++ b/tests/integration/targets/cloudtrail/tasks/main.yml @@ -24,9 +24,6 @@ # - Using blank string for CloudWatch Log Group / Role doesn't remove them # # Possible Bugs: -# - output.exists == false when creating -# - Changed reports true when using a KMS alias -# - Tags Keys are being lower-cased - module_defaults: group/aws: @@ -175,6 +172,27 @@ policy_name: 'CloudWatch' policy_json: "{{ lookup('template', 'cloudwatch-policy.j2') | to_json }}" + - name: 'Create CloudWatch IAM Role with no kms permissions' + iam_role: + state: present + name: '{{ cloudwatch_no_kms_role }}' + assume_role_policy_document: "{{ lookup('template', 'cloudtrail-no-kms-assume-policy.j2') }}" + managed_policies: + - "arn:aws:iam::aws:policy/AWSCloudTrail_FullAccess" + register: output_cloudwatch_no_kms_role + + - name: pause to ensure role exists before attaching policy + pause: + seconds: 15 + + - name: 'Add inline policy to CloudWatch Role' + iam_policy: + state: present + iam_type: role + iam_name: '{{ cloudwatch_no_kms_role }}' + policy_name: 'CloudWatchNokms' + policy_json: "{{ lookup('template', 'cloudtrail-no-kms-policy.j2') }}" + # ============================================================ # Tests # ============================================================ @@ -197,8 +215,7 @@ - assert: that: - output is changed - # XXX This appears to be a bug... - #- output.exists == True + - output.exists == True - output.trail.name == cloudtrail_name - name: 'No-op update to trail' @@ -451,7 +468,7 @@ - output.trail.name == cloudtrail_name - output.trail.tags | length == 2 - '("tag2" in output.trail.tags) and (output.trail.tags["tag2"] == "Value2")' - #- '("Tag3" in output.trail.tags) and (output.trail.tags["Tag3"] == "Value3")' + - '("Tag3" in output.trail.tags) and (output.trail.tags["Tag3"] == "Value3")' - name: 'Change tags (no change)' cloudtrail: @@ -467,7 +484,7 @@ - output.trail.name == cloudtrail_name - output.trail.tags | length == 2 - '("tag2" in output.trail.tags) and (output.trail.tags["tag2"] == "Value2")' - #- '("Tag3" in output.trail.tags) and (output.trail.tags["Tag3"] == "Value3")' + - '("Tag3" in output.trail.tags) and (output.trail.tags["Tag3"] == "Value3")' - name: 'Remove tags (CHECK MODE)' cloudtrail: @@ -1146,6 +1163,18 @@ - output is not changed - output.trail.kms_key_id == kms_key.key_arn + - name: 'Enable logging encryption (no change, check mode)' + cloudtrail: + state: present + name: '{{ cloudtrail_name }}' + kms_key_id: '{{ kms_key.key_arn }}' + check_mode: yes + register: output + - assert: + that: + - output is not changed + - output.trail.kms_key_id == kms_key.key_arn + - name: 'No-op update to trail' cloudtrail: state: present @@ -1219,9 +1248,48 @@ register: output - assert: that: - # - output is not changed + - output is not changed - output.trail.kms_key_id == kms_key.key_arn + - name: 'Update logging encryption to alias (CHECK MODE, no change)' + cloudtrail: + state: present + name: '{{ cloudtrail_name }}' + kms_key_id: '{{ kms_key.key_id }}' # Test when using key id + register: output + check_mode: yes + - assert: + that: + - output is not changed + - output.trail.kms_key_id == kms_key.key_id + + # Assume role to a role with Denied access to KMS + + - community.aws.sts_assume_role: + role_arn: '{{ output_cloudwatch_no_kms_role.arn }}' + role_session_name: "cloudtrailNoKms" + aws_access_key: '{{ aws_access_key }}' + aws_secret_key: '{{ aws_secret_key }}' + security_token: '{{ security_token | default(omit) }}' + region: '{{ aws_region }}' + register: noKms_assumed_role + + - name: 'Enable logging encryption w/ alias (no change, no kms permmissions, check mode)' + cloudtrail: + state: present + name: '{{ cloudtrail_name }}' + kms_key_id: 'alias/{{ kms_alias }}' + aws_access_key: "{{ noKms_assumed_role.sts_creds.access_key }}" + aws_secret_key: "{{ noKms_assumed_role.sts_creds.secret_key }}" + security_token: "{{ noKms_assumed_role.sts_creds.session_token }}" + check_mode: yes + register: output + - assert: + that: + - output is changed + # when using check_mode, with no kms permissions, and not giving kms_key_id as a key arn + # output will always be marked as changed. + #- name: 'Disable logging encryption (CHECK MODE)' # cloudtrail: # state: present @@ -1423,3 +1491,15 @@ state: absent name: '{{ cloudwatch_role }}' ignore_errors: yes + - name: 'Remove inline policy to CloudWatch Role' + iam_policy: + state: absent + iam_type: role + iam_name: '{{ cloudwatch_no_kms_role }}' + policy_name: 'CloudWatchNokms' + ignore_errors: yes + - name: 'Delete CloudWatch No KMS IAM Role' + iam_role: + state: absent + name: '{{ cloudwatch_no_kms_role }}' + ignore_errors: yes diff --git a/tests/integration/targets/cloudtrail/templates/cloudtrail-no-kms-assume-policy.j2 b/tests/integration/targets/cloudtrail/templates/cloudtrail-no-kms-assume-policy.j2 new file mode 100644 --- /dev/null +++ b/tests/integration/targets/cloudtrail/templates/cloudtrail-no-kms-assume-policy.j2 @@ -0,0 +1,11 @@ +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "AssumeRole", + "Effect": "Allow", + "Principal": { "AWS": "arn:aws:iam::{{ aws_caller_info.account }}:root" }, + "Action": "sts:AssumeRole" + } + ] +} diff --git a/tests/integration/targets/cloudtrail/templates/cloudtrail-no-kms-policy.j2 b/tests/integration/targets/cloudtrail/templates/cloudtrail-no-kms-policy.j2 new file mode 100644 --- /dev/null +++ b/tests/integration/targets/cloudtrail/templates/cloudtrail-no-kms-policy.j2 @@ -0,0 +1,11 @@ +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "kmsDeny", + "Effect": "Deny", + "Action": [ "kms:*" ], + "Resource": [ "*" ] + } + ] +}
cloudtrail Always Reports Changed=True When KMS Key Alias is used <!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> `cloudtrail` module always reports `changed = True` if `kms_key_id` attribute is set to a KMS key alias or alias ARN. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> cloudtrail ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below $ ansible --version ansible 2.9.13 config file = /home/user/.ansible.cfg configured module search path = ['/home/user/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /usr/local/lib/python3.8/dist-packages/ansible executable location = /usr/local/bin/ansible python version = 3.8.2 (default, Jul 16 2020, 14:00:26) [GCC 9.3.0] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below $ ansible-config dump --only-changed DEFAULT_ROLES_PATH(/home/user/.ansible.cfg) = ['/home/user/ansible'] RETRY_FILES_ENABLED(/home/user/.ansible.cfg) = False ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> N/A ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> Execute the following task: <!--- Paste example playbooks or commands between quotes below --> ```yaml community.aws.cloudtrail: - name: MyTrail s3_bucket_name: my-bucket kms_key_id: alias/mykey ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> After the first execution: ``` changed: [localhost] ``` After the second and subsequent executions: ``` ok: [localhost] ``` ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> Every execution reports `changed = True`. I suspect this is the result of the fact that module invocation includes key alias (`"kms_key_id": "arn:aws:kms:us-east-1:123412341234:alias/mykey"`), while the API returns the key ID (`"kms_key_id": "arn:aws:kms:us-east-1:123412341234:key/1234abcd-e83d-484c-a7e7-1234abcd"`) <!--- Paste verbatim command output between quotes --> ```paste below changed: [localhost] => { "changed": true, "exists": true, "invocation": { "module_args": { "aws_access_key": null, "aws_ca_bundle": null, "aws_config": null, "aws_secret_key": null, "cloudwatch_logs_log_group_arn": null, "cloudwatch_logs_role_arn": null, "debug_botocore_endpoint_logs": false, "ec2_url": null, "enable_log_file_validation": true, "enable_logging": true, "include_global_events": true, "is_multi_region_trail": true, "kms_key_id": "arn:aws:kms:us-east-1:123412341234:alias/mykey", "name": "MyTrail", "profile": null, "region": null, "s3_bucket_name": "my-bucket", "s3_key_prefix": null, "security_token": null, "sns_topic_name": null, "state": "present", "tags": null, "validate_certs": true } }, "trail": { "cloud_watch_logs_log_group_arn": null, "cloud_watch_logs_role_arn": null, "has_custom_event_selectors": false, "has_insight_selectors": false, "home_region": "us-east-1", "include_global_service_events": true, "is_logging": true, "is_multi_region_trail": true, "is_organization_trail": false, "kms_key_id": "arn:aws:kms:us-east-1:123412341234:key/1234abcd-e83d-484c-a7e7-1234abcd", "log_file_validation_enabled": true, "name": "MyTrail", "s3_bucket_name": "my-bucket", "s3_key_prefix": null, "sns_topic_arn": null, "sns_topic_name": null, "tags": null, "trail_arn": "arn:aws:cloudtrail:us-east-1:123412341234:trail/MyTrail" } } ```
FWIW, the same behavior happens when alias ARN is specified, e.g. `arn:aws:kms:us-east-1:123412341234:alias/mykey`. cc @jillr @s-hertel @shepdelacreme @tremble @wimnat [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify --->
2021-03-27T22:07:48
ansible-collections/community.aws
510
ansible-collections__community.aws-510
[ "509", "509" ]
327aabefbd304016b205d0cdbba75f608086412c
diff --git a/plugins/modules/route53.py b/plugins/modules/route53.py --- a/plugins/modules/route53.py +++ b/plugins/modules/route53.py @@ -410,15 +410,9 @@ def get_zone_id_by_name(route53, module, zone_name, want_private, want_vpc_id): if want_vpc_id: # NOTE: These details aren't available in other boto methods, hence the necessary # extra API call - hosted_zone = route53.get_hosted_zone(aws_retry=True, Id=zone.id) - zone_details = hosted_zone['HostedZone'] - # this is to deal with this boto bug: https://github.com/boto/boto/pull/2882 - if isinstance(zone_details['VPCs'], dict): - if zone_details['VPCs']['VPC']['VPCId'] == want_vpc_id: - return zone_id - else: # Forward compatibility for when boto fixes that bug - if want_vpc_id in [v['VPCId'] for v in zone_details['VPCs']]: - return zone_id + hosted_zone = route53.get_hosted_zone(aws_retry=True, Id=zone_id) + if want_vpc_id in [v['VPCId'] for v in hosted_zone['VPCs']]: + return zone_id else: return zone_id return None
diff --git a/tests/integration/targets/route53/tasks/main.yml b/tests/integration/targets/route53/tasks/main.yml --- a/tests/integration/targets/route53/tasks/main.yml +++ b/tests/integration/targets/route53/tasks/main.yml @@ -16,6 +16,14 @@ route53: region: null block: + + - name: create VPC + ec2_vpc_net: + cidr_block: 192.0.2.0/24 + name: '{{ resource_prefix }}_vpc' + state: present + register: vpc + - route53_zone: zone: '{{ zone_one }}' comment: Created in Ansible test {{ resource_prefix }} @@ -39,13 +47,39 @@ that: - hosted_zones.HostedZone.ResourceRecordSetCount == 2 + - route53_zone: + zone: '{{ zone_two }}' + vpc_id: '{{ vpc.vpc.id }}' + vpc_region: '{{ aws_region }}' + comment: Created in Ansible test {{ resource_prefix }} + register: z2 + + - assert: + that: + - z2 is success + - z2 is changed + - "z2.comment == 'Created in Ansible test {{ resource_prefix }}'" + + - name: Get zone details + route53_info: + query: hosted_zone + hosted_zone_id: '{{ z2.zone_id }}' + hosted_zone_method: details + register: hosted_zones + + - name: Assert newly created hosted zone only has NS and SOA records + assert: + that: + - hosted_zones.HostedZone.ResourceRecordSetCount == 2 + - hosted_zones.HostedZone.Config.PrivateZone + - name: Create A record using zone fqdn route53: state: present zone: '{{ zone_one }}' record: 'qdn_test.{{ zone_one }}' type: A - value: 1.2.3.4 + value: 192.0.2.1 register: qdn - assert: that: @@ -63,7 +97,7 @@ that: - get_result.nameservers|length > 0 - get_result.set.Name == "qdn_test.{{ zone_one }}" - - get_result.set.ResourceRecords[0].Value == "1.2.3.4" + - get_result.set.ResourceRecords[0].Value == "192.0.2.1" - get_result.set.Type == "A" - name: Create same A record using zone non-qualified domain @@ -72,7 +106,7 @@ zone: '{{ zone_one[:-1] }}' record: 'qdn_test.{{ zone_one[:-1] }}' type: A - value: 1.2.3.4 + value: 192.0.2.1 register: non_qdn - assert: that: @@ -85,7 +119,7 @@ hosted_zone_id: '{{ z1.zone_id }}' record: 'zid_test.{{ zone_one }}' type: A - value: 1.2.3.4 + value: 192.0.2.1 register: zid - assert: that: @@ -99,8 +133,8 @@ record: 'order_test.{{ zone_one }}' type: A value: - - 4.5.6.7 - - 1.2.3.4 + - 192.0.2.2 + - 192.0.2.1 register: mv_a_record - assert: that: @@ -114,8 +148,8 @@ record: 'order_test.{{ zone_one }}' type: A value: - - 4.5.6.7 - - 1.2.3.4 + - 192.0.2.2 + - 192.0.2.1 register: mv_a_record - assert: that: @@ -134,8 +168,8 @@ that: - records.ResourceRecordSets|length == 3 - records.ResourceRecordSets[0].ResourceRecords|length == 2 - - records.ResourceRecordSets[0].ResourceRecords[0].Value == "4.5.6.7" - - records.ResourceRecordSets[0].ResourceRecords[1].Value == "1.2.3.4" + - records.ResourceRecordSets[0].ResourceRecords[0].Value == "192.0.2.2" + - records.ResourceRecordSets[0].ResourceRecords[1].Value == "192.0.2.1" - name: Remove a member from multi-value A record with values in different order route53: @@ -144,7 +178,7 @@ record: 'order_test.{{ zone_one }}' type: A value: - - 4.5.6.7 + - 192.0.2.2 register: del_a_record ignore_errors: true - name: This should fail, because `overwrite` is false @@ -160,7 +194,7 @@ overwrite: true type: A value: - - 4.5.6.7 + - 192.0.2.2 register: del_a_record ignore_errors: true - name: This should not fail, because `overwrite` is true @@ -181,7 +215,7 @@ that: - records.ResourceRecordSets|length == 3 - records.ResourceRecordSets[0].ResourceRecords|length == 1 - - records.ResourceRecordSets[0].ResourceRecords[0].Value == "4.5.6.7" + - records.ResourceRecordSets[0].ResourceRecords[0].Value == "192.0.2.2" - name: Create a LetsEncrypt CAA record route53: @@ -232,6 +266,93 @@ - caa is not failed - caa is not changed + # Tests on zone two (private zone) + - name: Create A record using zone fqdn + route53: + state: present + zone: '{{ zone_two }}' + record: 'qdn_test.{{ zone_two }}' + type: A + value: 192.0.2.1 + private_zone: true + register: qdn + - assert: + that: + - qdn is not failed + - qdn is changed + + - name: Get A record using 'get' method of route53 module + route53: + state: get + zone: "{{ zone_two }}" + record: "qdn_test.{{ zone_two }}" + type: A + private_zone: true + register: get_result + - assert: + that: + - get_result.nameservers|length > 0 + - get_result.set.Name == "qdn_test.{{ zone_two }}" + - get_result.set.ResourceRecords[0].Value == "192.0.2.1" + - get_result.set.Type == "A" + + - name: Create same A record using zone non-qualified domain + route53: + state: present + zone: '{{ zone_two[:-1] }}' + record: 'qdn_test.{{ zone_two[:-1] }}' + type: A + value: 192.0.2.1 + private_zone: true + register: non_qdn + - assert: + that: + - non_qdn is not failed + - non_qdn is not changed + + - name: Create A record using zone ID + route53: + state: present + hosted_zone_id: '{{ z2.zone_id }}' + record: 'zid_test.{{ zone_two }}' + type: A + value: 192.0.2.2 + private_zone: true + register: zid + - assert: + that: + - zid is not failed + - zid is changed + + - name: Create A record using zone fqdn and vpc_id + route53: + state: present + zone: '{{ zone_two }}' + record: 'qdn_test_vpc.{{ zone_two }}' + type: A + value: 192.0.2.3 + private_zone: true + vpc_id: '{{ vpc.vpc.id }}' + register: qdn + - assert: + that: + - qdn is not failed + - qdn is changed + + - name: Create A record using zone ID and vpc_id + route53: + state: present + hosted_zone_id: '{{ z2.zone_id }}' + record: 'zid_test_vpc.{{ zone_two }}' + type: A + value: 192.0.2.4 + private_zone: true + vpc_id: '{{ vpc.vpc.id }}' + register: zid + - assert: + that: + - zid is not failed + - zid is changed always: - route53_info: @@ -247,6 +368,20 @@ type: '{{ item.Type }}' value: '{{ item.ResourceRecords | map(attribute="Value") | join(",") }}' loop: '{{ z1_records.ResourceRecordSets | selectattr("Type", "in", ["A", "AAAA", "CNAME", "CAA"]) | list }}' + - route53_info: + query: record_sets + hosted_zone_id: '{{ z2.zone_id }}' + register: z2_records + - debug: var=z2_records + - name: Loop over A/AAAA/CNAME records and delete them + route53: + state: absent + zone: '{{ zone_two }}' + record: '{{ item.Name }}' + type: '{{ item.Type }}' + value: '{{ item.ResourceRecords | map(attribute="Value") | join(",") }}' + private_zone: true + loop: '{{ z2_records.ResourceRecordSets | selectattr("Type", "in", ["A", "AAAA", "CNAME", "CAA"]) | list }}' - name: Delete test zone one '{{ zone_one }}' route53_zone: state: absent @@ -264,3 +399,13 @@ retries: 10 until: delete_two is not failed when: false + - name: destroy VPC + ec2_vpc_net: + cidr_block: 192.0.2.0/24 + name: '{{ resource_prefix }}_vpc' + state: absent + register: remove_vpc + retries: 10 + delay: 5 + until: remove_vpc is success + ignore_errors: true
route53: error when creating records in private zone with vpc_id <!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY `route53` has a special behaviour when working on private zones and `vpc_id` option is provided. As stated in documentation: > When used in conjunction with private_zone: true, this will only modify records in the private hosted zone attached to this VPC. > This allows you to have multiple private hosted zones, all with the same name, attached to different VPCs. The following error occurs when creating or updating a record in such zone: `AttributeError: 'dict' object has no attribute 'id'`. In case anyone wonders, this is not a duplicate of https://github.com/ansible-collections/community.aws/issues/434 because no `vpc_id` option is used there. I'll provide a PR soon. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME `route53` ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.10.5 config file = /home/admin/ansible/ansible.cfg configured module search path = ['/home/admin/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /usr/local/lib/python3.7/dist-packages/ansible executable location = /usr/local/bin/ansible python version = 3.7.3 (default, Jul 25 2020, 13:03:44) [GCC 8.3.0] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below ALLOW_WORLD_READABLE_TMPFILES(/home/admin/ansible/ansible.cfg) = True ANSIBLE_SSH_CONTROL_PATH(/home/admin/ansible/ansible.cfg) = %(directory)s/%%h-%%p-%%r DEFAULT_NO_TARGET_SYSLOG(/home/admin/ansible/ansible.cfg) = True DEFAULT_ROLES_PATH(/home/admin/ansible/ansible.cfg) = ['/home/admin/ansible/roles'] INTERPRETER_PYTHON(/home/admin/ansible/ansible.cfg) = /usr/bin/python3 RETRY_FILES_ENABLED(/home/admin/ansible/ansible.cfg) = False ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> Debian 10 ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> Ensure a private zone exists, then run the following task. <!--- Paste example playbooks or commands between quotes below --> ```yaml - hosts: all tasks: route53: aws_access_key: "{{ aws_access_key }}" aws_secret_key: "{{ aws_secret_key }}" overwrite: true private_zone: true record: "test-ansible.internal.example.com" state: present type: A value: "1.2.3.4" vpc_id: vpc-xyz1234 zone: "internal.example.com" ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> The record is created inside the zone. ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> An error occured. <!--- Paste verbatim command output between quotes --> ```paste below The full traceback is: Traceback (most recent call last): File "/home/admin/.ansible/tmp/ansible-tmp-1617023331.5792427-11521-49668929273150/AnsiballZ_route53.py", line 102, in <module> _ansiballz_main() File "/home/admin/.ansible/tmp/ansible-tmp-1617023331.5792427-11521-49668929273150/AnsiballZ_route53.py", line 94, in _ansiballz_main invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS) File "/home/admin/.ansible/tmp/ansible-tmp-1617023331.5792427-11521-49668929273150/AnsiballZ_route53.py", line 40, in invoke_module runpy.run_module(mod_name='ansible_collections.community.aws.plugins.modules.route53', init_globals=None, run_name='__main__', alter_sys=True) File "/usr/lib/python3.7/runpy.py", line 205, in run_module return _run_module_code(code, init_globals, run_name, mod_spec) File "/usr/lib/python3.7/runpy.py", line 96, in _run_module_code mod_name, mod_spec, pkg_name, script_name) File "/usr/lib/python3.7/runpy.py", line 85, in _run_code exec(code, run_globals) File "/tmp/ansible_route53_payload_n6znsp0f/ansible_route53_payload.zip/ansible_collections/community/aws/plugins/modules/route53.py", line 626, in <module> File "/tmp/ansible_route53_payload_n6znsp0f/ansible_route53_payload.zip/ansible_collections/community/aws/plugins/modules/route53.py", line 529, in main File "/tmp/ansible_route53_payload_n6znsp0f/ansible_route53_payload.zip/ansible_collections/community/aws/plugins/modules/route53.py", line 413, in get_zone_id_by_name AttributeError: 'dict' object has no attribute 'id' ``` route53: error when creating records in private zone with vpc_id <!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY `route53` has a special behaviour when working on private zones and `vpc_id` option is provided. As stated in documentation: > When used in conjunction with private_zone: true, this will only modify records in the private hosted zone attached to this VPC. > This allows you to have multiple private hosted zones, all with the same name, attached to different VPCs. The following error occurs when creating or updating a record in such zone: `AttributeError: 'dict' object has no attribute 'id'`. In case anyone wonders, this is not a duplicate of https://github.com/ansible-collections/community.aws/issues/434 because no `vpc_id` option is used there. I'll provide a PR soon. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME `route53` ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.10.5 config file = /home/admin/ansible/ansible.cfg configured module search path = ['/home/admin/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /usr/local/lib/python3.7/dist-packages/ansible executable location = /usr/local/bin/ansible python version = 3.7.3 (default, Jul 25 2020, 13:03:44) [GCC 8.3.0] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below ALLOW_WORLD_READABLE_TMPFILES(/home/admin/ansible/ansible.cfg) = True ANSIBLE_SSH_CONTROL_PATH(/home/admin/ansible/ansible.cfg) = %(directory)s/%%h-%%p-%%r DEFAULT_NO_TARGET_SYSLOG(/home/admin/ansible/ansible.cfg) = True DEFAULT_ROLES_PATH(/home/admin/ansible/ansible.cfg) = ['/home/admin/ansible/roles'] INTERPRETER_PYTHON(/home/admin/ansible/ansible.cfg) = /usr/bin/python3 RETRY_FILES_ENABLED(/home/admin/ansible/ansible.cfg) = False ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> Debian 10 ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> Ensure a private zone exists, then run the following task. <!--- Paste example playbooks or commands between quotes below --> ```yaml - hosts: all tasks: route53: aws_access_key: "{{ aws_access_key }}" aws_secret_key: "{{ aws_secret_key }}" overwrite: true private_zone: true record: "test-ansible.internal.example.com" state: present type: A value: "1.2.3.4" vpc_id: vpc-xyz1234 zone: "internal.example.com" ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> The record is created inside the zone. ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> An error occured. <!--- Paste verbatim command output between quotes --> ```paste below The full traceback is: Traceback (most recent call last): File "/home/admin/.ansible/tmp/ansible-tmp-1617023331.5792427-11521-49668929273150/AnsiballZ_route53.py", line 102, in <module> _ansiballz_main() File "/home/admin/.ansible/tmp/ansible-tmp-1617023331.5792427-11521-49668929273150/AnsiballZ_route53.py", line 94, in _ansiballz_main invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS) File "/home/admin/.ansible/tmp/ansible-tmp-1617023331.5792427-11521-49668929273150/AnsiballZ_route53.py", line 40, in invoke_module runpy.run_module(mod_name='ansible_collections.community.aws.plugins.modules.route53', init_globals=None, run_name='__main__', alter_sys=True) File "/usr/lib/python3.7/runpy.py", line 205, in run_module return _run_module_code(code, init_globals, run_name, mod_spec) File "/usr/lib/python3.7/runpy.py", line 96, in _run_module_code mod_name, mod_spec, pkg_name, script_name) File "/usr/lib/python3.7/runpy.py", line 85, in _run_code exec(code, run_globals) File "/tmp/ansible_route53_payload_n6znsp0f/ansible_route53_payload.zip/ansible_collections/community/aws/plugins/modules/route53.py", line 626, in <module> File "/tmp/ansible_route53_payload_n6znsp0f/ansible_route53_payload.zip/ansible_collections/community/aws/plugins/modules/route53.py", line 529, in main File "/tmp/ansible_route53_payload_n6znsp0f/ansible_route53_payload.zip/ansible_collections/community/aws/plugins/modules/route53.py", line 413, in get_zone_id_by_name AttributeError: 'dict' object has no attribute 'id' ```
2021-03-29T13:15:23
ansible-collections/community.aws
514
ansible-collections__community.aws-514
[ "343" ]
a11073ede7a7f2fd292b1f7d7b5829ea3e18b541
diff --git a/plugins/connection/aws_ssm.py b/plugins/connection/aws_ssm.py --- a/plugins/connection/aws_ssm.py +++ b/plugins/connection/aws_ssm.py @@ -24,16 +24,22 @@ description: The STS access key to use when connecting via session-manager. vars: - name: ansible_aws_ssm_access_key_id + env: + - name: AWS_ACCESS_KEY_ID version_added: 1.3.0 secret_access_key: description: The STS secret key to use when connecting via session-manager. vars: - name: ansible_aws_ssm_secret_access_key + env: + - name: AWS_SECRET_ACCESS_KEY version_added: 1.3.0 session_token: description: The STS session token to use when connecting via session-manager. vars: - name: ansible_aws_ssm_session_token + env: + - name: AWS_SESSION_TOKEN version_added: 1.3.0 instance_id: description: The EC2 instance ID. @@ -43,6 +49,9 @@ description: The region the EC2 instance is located. vars: - name: ansible_aws_ssm_region + env: + - name: AWS_REGION + - name: AWS_DEFAULT_REGION default: 'us-east-1' bucket_name: description: The name of the S3 bucket used for file transfers. @@ -57,6 +66,8 @@ description: Sets AWS profile to use. vars: - name: ansible_aws_ssm_profile + env: + - name: AWS_PROFILE version_added: 1.5.0 reconnection_retries: description: Number of attempts to connect. @@ -736,15 +747,6 @@ def _get_boto_client(self, service, region_name=None, profile_name=None, endpoin aws_secret_access_key = self.get_option('secret_access_key') aws_session_token = self.get_option('session_token') - if aws_access_key_id is None: - aws_access_key_id = os.environ.get("AWS_ACCESS_KEY_ID", None) - if aws_secret_access_key is None: - aws_secret_access_key = os.environ.get("AWS_SECRET_ACCESS_KEY", None) - if aws_session_token is None: - aws_session_token = os.environ.get("AWS_SESSION_TOKEN", None) - if not profile_name: - profile_name = os.environ.get("AWS_PROFILE", None) - session_args = dict( aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key,
Cannot connect to ec2 instance via aws_ssm if AWS_SESSION_TOKEN is missing <!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> Cannot connect to ec2 instance via aws_ssm if AWS_SESSION_TOKEN is not set. (I do not configure any AWS variables in OS via `aws configure`) ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> `ansible-collections/community.aws/blob/main/plugins/connection/aws_ssm.py ` ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.9.9 config file = None configured module search path = ['/Users/it-ops/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /usr/local/lib/python3.7/site-packages/ansible executable location = /usr/local/bin/ansible python version = 3.7.7 (default, Mar 10 2020, 15:43:03) [Clang 11.0.0 (clang-1100.0.33.17)] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> OSX 10.14.6 (18G3020) ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> I created a role to ping ec2 instance. <!--- Paste example playbooks or commands between quotes below --> ```yaml # roles/ssm/tasks/main.yml - name: ping ping: # roles/ssm/defaults/main.yml ansible_connection: aws_ssm ansible_aws_ssm_region: ap-southeast-1 ansible_aws_ssm_access_key_id: XXXXXXXXX ansible_aws_ssm_secret_access_key: XXXXXXXXX ansible_aws_ssm_instance_id: i-XXXXXXXX ansible_aws_ssm_bucket_name: bucket-name ``` <!--- HINT: You can paste gist.github.com links for larger files --> I guess this is related with this loc: ``` def _get_boto_client(self, service, region_name=None): ''' Gets a boto3 client based on the STS token ''' aws_access_key_id = self.get_option('access_key_id') aws_secret_access_key = self.get_option('secret_access_key') aws_session_token = self.get_option('session_token') if aws_access_key_id is None or aws_secret_access_key is None or aws_session_token is None: aws_access_key_id = os.environ.get("AWS_ACCESS_KEY_ID", None) aws_secret_access_key = os.environ.get("AWS_SECRET_ACCESS_KEY", None) aws_session_token = os.environ.get("AWS_SESSION_TOKEN", None) ``` Because I do not need `aws_session_token` (yet) to connect to ec2 instances via aws_ssm to do a ping, and I do not set any OS environment variables, all my `aws_access_key_id` and `aws_secret_access_key` are set to None again because the `aws_session_token` is empty. Suggested fixes: ``` def _get_boto_client(self, service, region_name=None): ''' Gets a boto3 client based on the STS token ''' aws_access_key_id = self.get_option('access_key_id') aws_secret_access_key = self.get_option('secret_access_key') aws_session_token = self.get_option('session_token') if aws_access_key_id is None: aws_access_key_id = os.environ.get("AWS_ACCESS_KEY_ID", None) if aws_secret_access_key is None: aws_secret_access_key = os.environ.get("AWS_SECRET_ACCESS_KEY", None) if aws_session_token is None: aws_session_token = os.environ.get("AWS_SESSION_TOKEN", None) ``` ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> ``` TASK [ssm : ping] ***************************************************************************************************************************************************************************** ok: [ec2] PLAY RECAP ************************************************************************************************************************************************************************************ ec2 : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 ``` ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> <!--- Paste verbatim command output between quotes --> ```paste below PLAY [nodes] ********************************************************************************************************************************************************************************** TASK [ssm : ping] ***************************************************************************************************************************************************************************** An exception occurred during task execution. To see the full traceback, use -vvv. The error was: botocore.exceptions.NoCredentialsError: Unable to locate credentials fatal: [ec2]: FAILED! => {"msg": "Unexpected failure during module execution.", "stdout": ""} PLAY RECAP ************************************************************************************************************************************************************************************ ec2 : ok=0 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0 ```
Files identified in the description: * [`plugins/modules/aws_ssm_parameter_store.py`](https://github.com/['ansible-collections/amazon.aws', 'ansible-collections/community.aws']/blob/main/plugins/modules/aws_ssm_parameter_store.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @jillr @mikedlr @nathanwebsterdotme @ozbillwang @s-hertel @tremble @wimnat [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> @ru-rocker thank you for filing the issue and the suggested fix. Would you like to open a PR for this? cc @116davinder [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> Perhaps this issue could be addressed differently. The ansible options parser already supports the ability to pick-up environment variables. Why not use that instead? Right now these fallbacks including region and remote_addr behavior could be addressed by updating configs. Say something like: ``` session_token: description: The STS session token to use when connecting via session-manager. vars: - name: ansible_aws_ssm_session_token env: - name: AWS_SESSION_TOKEN version_added: 1.5.0 version_added: 1.3.0 ``` I just had to address this in our environment because as designed, the code will override the configured vars with `None`'s because there are no such environment variables set. I'll look at attaching a pull request to address this since I just had to work-around it manually. Sorry for the late reply. The reason I opened this issue is I need dynamic access_key_id and access_secret_key_id due to security requirements. I need to store those keys inside some password manager and it is prohibited to store them as environment variables.
2021-03-30T20:02:22
ansible-collections/community.aws
525
ansible-collections__community.aws-525
[ "524" ]
92f9995c1032a34d79ff28e9d51386324cffe7ab
diff --git a/plugins/modules/route53.py b/plugins/modules/route53.py --- a/plugins/modules/route53.py +++ b/plugins/modules/route53.py @@ -384,8 +384,9 @@ def get_record(route53, zone_id, record_name, record_type, record_identifier): record_sets_results = _list_record_sets(route53, HostedZoneId=zone_id) for record_set in record_sets_results: + record_set['Name'] = record_set['Name'].encode().decode('unicode_escape') # If the record name and type is not equal, move to the next record - if (record_name, record_type) != (record_set['Name'], record_set['Type']): + if (record_name.lower(), record_type) != (record_set['Name'].lower(), record_set['Type']): continue if record_identifier and record_identifier != record_set.get("SetIdentifier"): @@ -561,6 +562,8 @@ def main(): # On CAA records order doesn't matter if type_in == 'CAA': resource_record_set['ResourceRecords'] = sorted(resource_record_set['ResourceRecords'], key=itemgetter('Value')) + if aws_record: + aws_record['ResourceRecords'] = sorted(aws_record['ResourceRecords'], key=itemgetter('Value')) if command_in == 'create' and aws_record == resource_record_set: module.exit_json(changed=False)
diff --git a/tests/integration/targets/route53/tasks/main.yml b/tests/integration/targets/route53/tasks/main.yml --- a/tests/integration/targets/route53/tasks/main.yml +++ b/tests/integration/targets/route53/tasks/main.yml @@ -266,6 +266,63 @@ - caa is not failed - caa is not changed + - name: Create an A record for a wildcard prefix + route53: + state: present + zone: '{{ zone_one }}' + record: '*.wildcard_test.{{ zone_one }}' + type: A + value: + - 192.0.2.1 + register: wc_a_record + - assert: + that: + - wc_a_record is not failed + - wc_a_record is changed + + - name: Create an A record for a wildcard prefix (idempotency) + route53: + state: present + zone: '{{ zone_one }}' + record: '*.wildcard_test.{{ zone_one }}' + type: A + value: + - 192.0.2.1 + register: wc_a_record + - assert: + that: + - wc_a_record is not failed + - wc_a_record is not changed + + - name: Create an A record for a wildcard prefix (change) + route53: + state: present + zone: '{{ zone_one }}' + record: '*.wildcard_test.{{ zone_one }}' + type: A + value: + - 192.0.2.2 + overwrite: true + register: wc_a_record + - assert: + that: + - wc_a_record is not failed + - wc_a_record is changed + + - name: Delete an A record for a wildcard prefix + route53: + state: absent + zone: '{{ zone_one }}' + record: '*.wildcard_test.{{ zone_one }}' + type: A + value: + - 192.0.2.2 + register: wc_a_record + - assert: + that: + - wc_a_record is not failed + - wc_a_record is changed + # Tests on zone two (private zone) - name: Create A record using zone fqdn route53:
route53 idempotency issues ##### SUMMARY Since #405, route53 has several idempotency issues when running with `-C --diff`: 1. it tries to change CAA entries where the values are in a different order; 2. it tries to re-add wildcard records that already exist. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME route53 ##### ANSIBLE VERSION ```paste below devel ```
Files identified in the description: * [`plugins/modules/route53.py`](https://github.com/['ansible-collections/amazon.aws', 'ansible-collections/community.aws', 'ansible-collections/community.vmware']/blob/main/plugins/modules/route53.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @jillr @jimbydamonk @s-hertel @tremble @wimnat [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> 1. is a regression for ansible/ansible#46049. 2. is caused by removing the escaped character handling (see for example https://github.com/ansible/ansible/pull/60508).
2021-04-05T16:03:25
ansible-collections/community.aws
535
ansible-collections__community.aws-535
[ "343" ]
1b6dcca86b3057a432d94315205324cb23f36c36
diff --git a/plugins/connection/aws_ssm.py b/plugins/connection/aws_ssm.py --- a/plugins/connection/aws_ssm.py +++ b/plugins/connection/aws_ssm.py @@ -510,10 +510,14 @@ def _get_boto_client(self, service, region_name=None): aws_access_key_id = self.get_option('access_key_id') aws_secret_access_key = self.get_option('secret_access_key') aws_session_token = self.get_option('session_token') - if aws_access_key_id is None or aws_secret_access_key is None or aws_session_token is None: + + if aws_access_key_id is None: aws_access_key_id = os.environ.get("AWS_ACCESS_KEY_ID", None) + if aws_secret_access_key is None: aws_secret_access_key = os.environ.get("AWS_SECRET_ACCESS_KEY", None) + if aws_session_token is None: aws_session_token = os.environ.get("AWS_SESSION_TOKEN", None) + client = boto3.client( service, aws_access_key_id=aws_access_key_id,
Cannot connect to ec2 instance via aws_ssm if AWS_SESSION_TOKEN is missing <!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> Cannot connect to ec2 instance via aws_ssm if AWS_SESSION_TOKEN is not set. (I do not configure any AWS variables in OS via `aws configure`) ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> `ansible-collections/community.aws/blob/main/plugins/connection/aws_ssm.py ` ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.9.9 config file = None configured module search path = ['/Users/it-ops/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /usr/local/lib/python3.7/site-packages/ansible executable location = /usr/local/bin/ansible python version = 3.7.7 (default, Mar 10 2020, 15:43:03) [Clang 11.0.0 (clang-1100.0.33.17)] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> OSX 10.14.6 (18G3020) ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> I created a role to ping ec2 instance. <!--- Paste example playbooks or commands between quotes below --> ```yaml # roles/ssm/tasks/main.yml - name: ping ping: # roles/ssm/defaults/main.yml ansible_connection: aws_ssm ansible_aws_ssm_region: ap-southeast-1 ansible_aws_ssm_access_key_id: XXXXXXXXX ansible_aws_ssm_secret_access_key: XXXXXXXXX ansible_aws_ssm_instance_id: i-XXXXXXXX ansible_aws_ssm_bucket_name: bucket-name ``` <!--- HINT: You can paste gist.github.com links for larger files --> I guess this is related with this loc: ``` def _get_boto_client(self, service, region_name=None): ''' Gets a boto3 client based on the STS token ''' aws_access_key_id = self.get_option('access_key_id') aws_secret_access_key = self.get_option('secret_access_key') aws_session_token = self.get_option('session_token') if aws_access_key_id is None or aws_secret_access_key is None or aws_session_token is None: aws_access_key_id = os.environ.get("AWS_ACCESS_KEY_ID", None) aws_secret_access_key = os.environ.get("AWS_SECRET_ACCESS_KEY", None) aws_session_token = os.environ.get("AWS_SESSION_TOKEN", None) ``` Because I do not need `aws_session_token` (yet) to connect to ec2 instances via aws_ssm to do a ping, and I do not set any OS environment variables, all my `aws_access_key_id` and `aws_secret_access_key` are set to None again because the `aws_session_token` is empty. Suggested fixes: ``` def _get_boto_client(self, service, region_name=None): ''' Gets a boto3 client based on the STS token ''' aws_access_key_id = self.get_option('access_key_id') aws_secret_access_key = self.get_option('secret_access_key') aws_session_token = self.get_option('session_token') if aws_access_key_id is None: aws_access_key_id = os.environ.get("AWS_ACCESS_KEY_ID", None) if aws_secret_access_key is None: aws_secret_access_key = os.environ.get("AWS_SECRET_ACCESS_KEY", None) if aws_session_token is None: aws_session_token = os.environ.get("AWS_SESSION_TOKEN", None) ``` ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> ``` TASK [ssm : ping] ***************************************************************************************************************************************************************************** ok: [ec2] PLAY RECAP ************************************************************************************************************************************************************************************ ec2 : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 ``` ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> <!--- Paste verbatim command output between quotes --> ```paste below PLAY [nodes] ********************************************************************************************************************************************************************************** TASK [ssm : ping] ***************************************************************************************************************************************************************************** An exception occurred during task execution. To see the full traceback, use -vvv. The error was: botocore.exceptions.NoCredentialsError: Unable to locate credentials fatal: [ec2]: FAILED! => {"msg": "Unexpected failure during module execution.", "stdout": ""} PLAY RECAP ************************************************************************************************************************************************************************************ ec2 : ok=0 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0 ```
Files identified in the description: * [`plugins/modules/aws_ssm_parameter_store.py`](https://github.com/['ansible-collections/amazon.aws', 'ansible-collections/community.aws']/blob/main/plugins/modules/aws_ssm_parameter_store.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @jillr @mikedlr @nathanwebsterdotme @ozbillwang @s-hertel @tremble @wimnat [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> @ru-rocker thank you for filing the issue and the suggested fix. Would you like to open a PR for this? cc @116davinder [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> Perhaps this issue could be addressed differently. The ansible options parser already supports the ability to pick-up environment variables. Why not use that instead? Right now these fallbacks including region and remote_addr behavior could be addressed by updating configs. Say something like: ``` session_token: description: The STS session token to use when connecting via session-manager. vars: - name: ansible_aws_ssm_session_token env: - name: AWS_SESSION_TOKEN version_added: 1.5.0 version_added: 1.3.0 ``` I just had to address this in our environment because as designed, the code will override the configured vars with `None`'s because there are no such environment variables set. I'll look at attaching a pull request to address this since I just had to work-around it manually. Sorry for the late reply. The reason I opened this issue is I need dynamic access_key_id and access_secret_key_id due to security requirements. I need to store those keys inside some password manager and it is prohibited to store them as environment variables.
2021-04-09T14:42:34
ansible-collections/community.aws
542
ansible-collections__community.aws-542
[ "494" ]
36f8a0586835731baa6c2824f51f79d7e2c55eec
diff --git a/plugins/connection/aws_ssm.py b/plugins/connection/aws_ssm.py --- a/plugins/connection/aws_ssm.py +++ b/plugins/connection/aws_ssm.py @@ -280,6 +280,9 @@ def __init__(self, *args, **kwargs): self._shell_type = 'powershell' self.is_windows = True + def __del__(self): + self.close() + def _connect(self): ''' connect to the host via ssm '''
SSM connection plugin doesnt properly close connections ##### SUMMARY When trying to run a big playbook using the SSM connection plugin, it randomly hangs in the middle of it. Very rarely am I able to run the entire playbook without issues. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME ssm connection plugin ##### ANSIBLE VERSION ``` ansible 2.10.5 config file = /Users/xxx/.ansible.cfg configured module search path = ['/Users/xxx/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /usr/local/lib/python3.8/site-packages/ansible executable location = /usr/local/bin/ansible python version = 3.8.8 (default, Feb 21 2021, 10:35:39) [Clang 12.0.0 (clang-1200.0.32.29)] ``` ##### CONFIGURATION ``` DEFAULT_HOST_LIST(env: ANSIBLE_INVENTORY) = ['/Users/xxx/ansible_hosts'] DEFAULT_VAULT_IDENTITY_LIST(/Users/xxx/.ansible.cfg) = ['xx@~/.vault_pass.txt', 'xxx@~/.vault_pass_xxx.txt', 'xxx@~/.vault_pass_xxx.txt'] ``` Ansible variables used in the playbook for configuring the SSM plugin: ``` vars: ansible_connection: community.aws.aws_ssm ansible_aws_ssm_bucket_name: xxx-ansible-ssm ansible_aws_ssm_region: eu-west-1 ``` ##### OS / ENVIRONMENT Target OS: `Amazon-Linux 2` ##### STEPS TO REPRODUCE I dont have exact steps to replicate this issue, it seems to happen to bigger playbooks. And happens randomly, sometimes it dies immediately, sometimes it dies in the middle or end, and very rarely does it complete without issues. ##### EXPECTED RESULTS To complete the playbook without hanging. ##### ACTUAL RESULTS When running in verbose mode, these are the last lines printed, i left the playbook running for 10 minutes and no change happened after which i stopped it manually: ``` .... <i-xxx> ESTABLISH SSM CONNECTION TO: i-xxx <i-xxx> SSM CONNECTION ID: xxx-0a55f9c52a37613a0 <i-xxx> EXEC echo ~ ^C [ERROR]: User interrupted execution ``` If I SSH to the server, it seems there are a lot of connections left hanging, this is the output of `ps -e --forest -o ppid,pid,user,command`: ![output of ps command](https://user-images.githubusercontent.com/1773227/112132377-d483e380-8bca-11eb-83f0-fd0f081c6dde.png) This has been an issue for me for several releases of the ssm connection plugin.
Files identified in the description: * [`lib/ansible/plugins/connection`](https://github.com/['ansible-collections/amazon.aws', 'ansible-collections/community.aws', 'ansible-collections/community.vmware']/blob/main/lib/ansible/plugins/connection) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> Looking more into the issue, it seems if you run a task with a loop, only the last SSM connection is actually terminated. The rest of them are left hanging. When running with `-vvvv` debug, only one `TERMINATE SSM SESSION` line is output, but it establishes a new SSM connection for each iteration of the loop. Once the task is done, there are a bunch of connections left hanging on the server even though the ansible playbook is done. Running `strace` on the hanging connections on the server shows that they seem stuck on the `read` syscall. Presumably just waiting on input from a dead connection. I am experiencing a similar issue where in my case I have a large set of playbook with around 200 tasks that are being executed across several private EC2 instances. At one point my tasks start timing-out with a particularly "hot" instance. I have noticed that in the middle of the execution I have over 100 connections with status "connected" in my AWS account. I have noticed this by checking Systems Manager console. A sample of the log associated with the failing command is similar to this: `failed: [i-11111222223333344444] (item={u'name': u'some-name', u'value': u'some-value'}) => {"ansible_loop_var": "item", "item": {"name": "some-name", "value": "some-value"}, "msg": "SSM exec_command timeout on host: i-11111222223333344444", "unreachable": true}`
2021-04-14T09:50:39
ansible-collections/community.aws
558
ansible-collections__community.aws-558
[ "113" ]
316f0acb76d81a3065aa78c4f37fc5ef87212bf6
diff --git a/plugins/connection/aws_ssm.py b/plugins/connection/aws_ssm.py --- a/plugins/connection/aws_ssm.py +++ b/plugins/connection/aws_ssm.py @@ -447,11 +447,94 @@ def exec_command(self, cmd, in_data=None, sudoable=True): def _prepare_terminal(self): ''' perform any one-time terminal settings ''' + # No windows setup for now + if self.is_windows: + return + + # *_complete variables are 3 valued: + # - None: not started + # - False: started + # - True: complete + + startup_complete = False + disable_echo_complete = None + disable_echo_cmd = to_bytes("stty -echo\n", errors="surrogate_or_strict") + + disable_prompt_complete = None + end_mark = "".join( + [random.choice(string.ascii_letters) for i in xrange(self.MARK_LENGTH)] + ) + disable_prompt_cmd = to_bytes( + "PS1='' ; printf '\\n%s\\n' '" + end_mark + "'\n", + errors="surrogate_or_strict", + ) + disable_prompt_reply = re.compile( + r"\r\r\n" + re.escape(end_mark) + r"\r\r\n", re.MULTILINE + ) - if not self.is_windows: - cmd = "stty -echo\n" + "PS1=''\n" - cmd = to_bytes(cmd, errors='surrogate_or_strict') - self._session.stdin.write(cmd) + stdout = "" + # Custom command execution for when we're waiting for startup + stop_time = int(round(time.time())) + self.get_option("ssm_timeout") + while (not disable_prompt_complete) and (self._session.poll() is None): + remaining = stop_time - int(round(time.time())) + if remaining < 1: + self._timeout = True + display.vvvv( + "PRE timeout stdout: {0}".format(to_bytes(stdout)), host=self.host + ) + raise AnsibleConnectionFailure( + "SSM start_session timeout on host: %s" % self.instance_id + ) + if self._poll_stdout.poll(1000): + stdout += to_text(self._stdout.read(1024)) + display.vvvv( + "PRE stdout line: {0}".format(to_bytes(stdout)), host=self.host + ) + else: + display.vvvv("PRE remaining: {0}".format(remaining), host=self.host) + + # wait til prompt is ready + if startup_complete is False: + match = str(stdout).find("Starting session with SessionId") + if match != -1: + display.vvvv("PRE startup output received", host=self.host) + startup_complete = True + + # disable echo + if startup_complete and (disable_echo_complete is None): + display.vvvv( + "PRE Disabling Echo: {0}".format(disable_echo_cmd), host=self.host + ) + self._session.stdin.write(disable_echo_cmd) + disable_echo_complete = False + + if disable_echo_complete is False: + match = str(stdout).find("stty -echo") + if match != -1: + disable_echo_complete = True + + # disable prompt + if disable_echo_complete and disable_prompt_complete is None: + display.vvvv( + "PRE Disabling Prompt: {0}".format(disable_prompt_cmd), + host=self.host, + ) + self._session.stdin.write(disable_prompt_cmd) + disable_prompt_complete = False + + if disable_prompt_complete is False: + match = disable_prompt_reply.search(stdout) + if match: + stdout = stdout[match.end():] + disable_prompt_complete = True + + if not disable_prompt_complete: + raise AnsibleConnectionFailure( + "SSM process closed during _prepare_terminal on host: %s" + % self.instance_id + ) + else: + display.vvv("PRE Terminal configured", host=self.host) def _wrap_command(self, cmd, sudoable, mark_start, mark_end): ''' wrap command so stdout and status can be extracted ''' @@ -463,7 +546,11 @@ def _wrap_command(self, cmd, sudoable, mark_start, mark_end): else: if sudoable: cmd = "sudo " + cmd - cmd = "echo " + mark_start + "\n" + cmd + "\necho $'\\n'$?\n" + "echo " + mark_end + "\n" + cmd = ( + f"printf '%s\\n' '{mark_start}';\n" + f"echo | {cmd};\n" + f"printf '\\n%s\\n%s\\n' \"$?\" '{mark_end}';\n" + ) display.vvvv(u"_wrap_command: '{0}'".format(to_text(cmd)), host=self.host) return cmd
ssm connection plugin fails at gathering facts <!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> Using the ssm plugin, playbooks fail at the gathering facts stage, with: ``` An exception occurred during task execution. To see the full traceback, use -vvv. The error was: ValueError: invalid literal for int() with base 10: "echo $'\\n'$?" fatal: [i-xxxxx]: FAILED! => {"msg": "Unexpected failure during module execution.", "stdout": ""} ``` If using `gather_facts: false`, the same error occurs at the first task As far as I can tell, SSM is configured correctly: I can run `aws ssm start-session --target i-xxxxx` from my ansible host and successfully get a shell on the target host. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> ssm connection plugin ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.9.9 config file = /etc/ansible/ansible.cfg configured module search path = ['/home/ubuntu/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /home/ubuntu/.local/lib/python3.8/site-packages/ansible executable location = /home/ubuntu/.local/bin/ansible python version = 3.8.2 (default, Apr 27 2020, 15:53:34) [GCC 9.3.0] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below INVENTORY_ENABLED(/etc/ansible/ansible.cfg) = ['aws_ec2'] ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> Both the instance running Ansible and the target (SSM-managed) instance are regular ubuntu 20.04 AMIs ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> * Launch 2 EC2 instances running Ubuntu 20.04 (in same AWS region) * Install ansible, boto3, aws cli & sms plugin on first instance * Run AWS Systems Manager quick start (using default roles & choosing all instances as targets) * confirm that SSM can start a shell from Ansible to second instance: `aws ssm start-session --target i-xxxxx` * Enable ansible aws_ec2 inventory plugin * Run the following playbook with the attached inventory config: <!--- Paste example playbooks or commands between quotes below --> ```yaml # Playbook - hosts: all vars: ansible_connection: community.aws.aws_ssm ansible_aws_ssm_region: eu-west-2 # substitute for your region tasks: - name: test command: cmd: ls -l ``` ```yaml # aws_ec2.yaml inventory plugin: aws_ec2 regions: - eu-west-2 keyed_groups: - prefix: tag key: tags - prefix: aws_region key: placement.region hostnames: - instance-id compose: ansible_host: instance-id ``` Run: ``` ansible-playbook -i aws_ec2.yaml -c community.aws.aws_ssm test-playbook.yaml ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> Playbook runs successfully with no errors ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> Playbook errors on gathering facts stage, with: <!--- Paste verbatim command output between quotes --> ```paste below An exception occurred during task execution. To see the full traceback, use -vvv. The error was: ValueError: invalid literal for int() with base 10: "echo $'\\n'$?" fatal: [i-xxxxx]: FAILED! => {"msg": "Unexpected failure during module execution.", "stdout": ""} ``` with `-vvvv` verbosity: ``` ansible-playbook 2.9.9 config file = /etc/ansible/ansible.cfg configured module search path = ['/home/ubuntu/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /home/ubuntu/.local/lib/python3.8/site-packages/ansible executable location = /home/ubuntu/.local/bin/ansible-playbook python version = 3.8.2 (default, Apr 27 2020, 15:53:34) [GCC 9.3.0] Using /etc/ansible/ansible.cfg as config file setting up inventory plugins Parsed /home/ubuntu/aws_ec2.yaml inventory source with aws_ec2 plugin Loading callback plugin default of type stdout, v2.0 from /home/ubuntu/.local/lib/python3.8/site-packages/ansible/plugins/callback/default.py PLAYBOOK: test_ssm.yaml **************************************************************************************************************************************************************************************** Positional arguments: test_ssm.yaml verbosity: 4 connection: community.aws.aws_ssm timeout: 10 become_method: sudo tags: ('all',) inventory: ('/home/ubuntu/aws_ec2.yaml',) forks: 5 1 plays in test_ssm.yaml PLAY [all] ***************************************************************************************************************************************************************************************************** TASK [Gathering Facts] ***************************************************************************************************************************************************************************************** task path: /home/ubuntu/test_ssm.yaml:1 <i-xxxxx> ESTABLISH SSM CONNECTION TO: i-xxxxx <i-xxxxx> SSM COMMAND: ['/usr/local/bin/session-manager-plugin', '{"SessionId": "i-xxxxx-yyyyy", "TokenValue": "XXXXX", "StreamUrl": "wss://ssmmessages.eu-west-2.amazonaws.com/v1/data-channel/i-yyyyy-zzzzz?role=publish_subscribe", "ResponseMetadata": {"RequestId": "xxxx-xxxx-xxxx-xxxx", "HTTPStatusCode": 200, "HTTPHeaders": {"x-amzn-requestid": "xxxx-xxxx-xxxx-xxxx-xxxx", "content-type": "application/x-amz-json-1.1", "content-length": "626", "date": "Fri, 19 Jun 2020 14:41:52 GMT"}, "RetryAttempts": 0}}', 'eu-west-2', 'StartSession', '', '{"Target": "i-xxxxx"}', 'https://ssm.eu-west-2.amazonaws.com'] <i-xxxxx> SSM CONNECTION ID: i-xxxx-xxxxx <i-xxxxx> EXEC echo ~ <i-xxxxx> _wrap_command: 'echo XXXXX echo ~ echo $'\n'$? echo YYYYY ' <i-xxxxx> EXEC stdout line: <i-xxxxx> EXEC stdout line: Starting session with SessionId: i-xxxxx-yyyyy <i-xxxxx> EXEC remaining: 60 <i-xxxxx> EXEC stdout line: $ stty -echo <i-xxxxx> EXEC stdout line: PS1='' <i-xxxxx> EXEC stdout line: echo XXXXX <i-xxxxx> EXEC stdout line: echo ~ <i-xxxxx> EXEC stdout line: echo $'\n'$? <i-xxxxx> EXEC stdout line: echo YYYYY <i-xxxxx> POST_PROCESS: echo ~ echo $'\n'$? <i-xxxxx> ssm_retry: attempt: 0, caught exception(invalid literal for int() with base 10: "echo $'\\n'$?") from cmd (echo ~...), pausing for 0 seconds <i-xxxxx> CLOSING SSM CONNECTION TO: i-xxxxx <i-xxxxx> TERMINATE SSM SESSION: i-xxxxx-yyyyy <i-xxxxx> ESTABLISH SSM CONNECTION TO: i-xxxxx <i-xxxxx> SSM COMMAND: ['/usr/local/bin/session-manager-plugin', '{"SessionId": "i-xxxxx-yyyyy", "TokenValue": "XXXXX", "StreamUrl": "wss://ssmmessages.eu-west-2.amazonaws.com/v1/data-channel/i-yyyyy-zzzzz?role=publish_subscribe", "ResponseMetadata": {"RequestId": "xxxx-xxxx-xxxx-xxxx-xxxx", "HTTPStatusCode": 200, "HTTPHeaders": {"x-amzn-requestid": "xxxx-xxxx-xxxx-xxxx-xxxx", "content-type": "application/x-amz-json-1.1", "content-length": "626", "date": "Fri, 19 Jun 2020 14:41:53 GMT"}, "RetryAttempts": 0}}', 'eu-west-2', 'StartSession', '', '{"Target": "i-xxxxx"}', 'https://ssm.eu-west-2.amazonaws.com'] <i-xxxxx> SSM CONNECTION ID: i-xxxx-xxxx <i-xxxxx> EXEC echo ~ <i-xxxxx> _wrap_command: 'echo YYYYY echo ~ echo $'\n'$? echo ZZZZZ ' <i-xxxxx> EXEC stdout line: <i-xxxxx> EXEC stdout line: Starting session with SessionId: i-xxxx-yyyy <i-xxxxx> EXEC remaining: 60 <i-xxxxx> EXEC stdout line: $ stty -echo <i-xxxxx> EXEC stdout line: PS1='' <i-xxxxx> EXEC stdout line: echo YYYYY <i-xxxxx> EXEC stdout line: echo ~ <i-xxxxx> EXEC stdout line: echo $'\n'$? <i-xxxxx> EXEC stdout line: echo ZZZZZ <i-xxxxx> POST_PROCESS: echo ~ echo $'\n'$? <i-xxxxx> CLOSING SSM CONNECTION TO: i-xxxxx <i-xxxxx> TERMINATE SSM SESSION: i-xxxxx-yyyyy The full traceback is: Traceback (most recent call last): File "/home/ubuntu/.local/lib/python3.8/site-packages/ansible/executor/task_executor.py", line 146, in run res = self._execute() File "/home/ubuntu/.local/lib/python3.8/site-packages/ansible/executor/task_executor.py", line 645, in _execute result = self._handler.run(task_vars=variables) File "/home/ubuntu/.local/lib/python3.8/site-packages/ansible/plugins/action/gather_facts.py", line 79, in run res = self._execute_module(module_name=fact_module, module_args=mod_args, task_vars=task_vars, wrap_async=False) File "/home/ubuntu/.local/lib/python3.8/site-packages/ansible/plugins/action/__init__.py", line 780, in _execute_module self._make_tmp_path() File "/home/ubuntu/.local/lib/python3.8/site-packages/ansible/plugins/action/__init__.py", line 343, in _make_tmp_path tmpdir = self._remote_expand_user(self.get_shell_option('remote_tmp', default='~/.ansible/tmp'), sudoable=False) File "/home/ubuntu/.local/lib/python3.8/site-packages/ansible/plugins/action/__init__.py", line 664, in _remote_expand_user data = self._low_level_execute_command(cmd, sudoable=False) File "/home/ubuntu/.local/lib/python3.8/site-packages/ansible/plugins/action/__init__.py", line 1075, in _low_level_execute_command rc, stdout, stderr = self._connection.exec_command(cmd, in_data=in_data, sudoable=sudoable) File "/home/ubuntu/.ansible/collections/ansible_collections/community/aws/plugins/connection/aws_ssm.py", line 197, in wrapped return_tuple = func(self, *args, **kwargs) File "/home/ubuntu/.ansible/collections/ansible_collections/community/aws/plugins/connection/aws_ssm.py", line 389, in exec_command returncode, stdout = self._post_process(stdout, mark_begin) File "/home/ubuntu/.ansible/collections/ansible_collections/community/aws/plugins/connection/aws_ssm.py", line 442, in _post_process returncode = int(stdout.splitlines()[-2]) ValueError: invalid literal for int() with base 10: "echo $'\\n'$?" fatal: [i-xxxxx]: FAILED! => { "msg": "Unexpected failure during module execution.", "stdout": "" } ```
Same issue, unusual plugin I looked into this, and there are several things wrong I think. See [this line](https://github.com/ansible-collections/community.aws/blob/main/plugins/connection/aws_ssm.py#L430) ```python cmd = "echo " + mark_start + "\n" + cmd + "\necho $'\\n'$?\n" + "echo " + mark_end + "\n" ``` The shell used by the session-manager is `sh`, which does not support bashisms like `$'\n'` to print a new line. See the difference: **`sh`** ```console $ echo $'\n'$? $ 0 ``` **`bash`** ```console $ echo $'\n'$? 0 ``` --- However, that might be a red herring. Notice the output: ``` <i-xxxxx> EXEC stdout line: $ stty -echo <i-xxxxx> EXEC stdout line: PS1='' <i-xxxxx> EXEC stdout line: echo YYYYY <i-xxxxx> EXEC stdout line: echo ~ <i-xxxxx> EXEC stdout line: echo $'\n'$? <i-xxxxx> EXEC stdout line: echo ZZZZZ ``` That is the input commands, not the stdout. Where is the output? Here is a workaround that avoids `sh` entirely by starting a bash shell. ```patch --- a/plugins/connection/aws_ssm.py 2020-09-03 18:43:43.818000000 +0200 +++ b/plugins/connection/aws_ssm.py 2020-09-03 18:43:19.805000000 +0200 @@ -288,11 +288,17 @@ profile_name = '' region_name = self.get_option('region') - ssm_parameters = dict() client = boto3.client('ssm', region_name=region_name) self._client = client - response = client.start_session(Target=self.instance_id, Parameters=ssm_parameters) + + if self.is_windows: + ssm_parameters = dict() + response = client.start_session(Target=self.instance_id, Parameters=ssm_parameters) + else: + ssm_parameters = {"command": ["bash -l"]} + response = client.start_session(Target=self.instance_id, DocumentName="AWS-StartInteractiveCommand", Parameters=ssm_parameters) + self._session_id = response['SessionId'] cmd = [ ``` ``` I looked at this for a bit today and found that you were right to be skeptical @abeluck . The issue appears to actually be in `_prepare_terminal`. The current code does not wait for `tty -echo` to return before sending additional bytes. This causes all characters that are sent *prior* to the return of `tty -echo` to be printed and any characters written afterwards to not be printed. Since the commands are sent so quickly, the terminal prints *all lines*. Then we break out of the loop because `<start_mark>` is definitely present in `echo <start_mark>`. You can quickly fix the behavior by adding a delay (and also probably the fix for the bashism) Here are some logs to demonstrate: ## After removing the loop breakout: ``` Loading callback plugin minimal of type stdout, v2.0 from /usr/lib/python3.8/site-packages/ansible/plugins/callback/minimal.py META: ran handlers <ip-___-__-_-___.ec2.internal> ESTABLISH SSM CONNECTION TO: i-0cc44a1e2f7995c53 <ip-___-__-_-___.ec2.internal> SSM COMMAND: ['/usr/local/bin/session-manager-plugin',...] <ip-___-__-_-___.ec2.internal> SSM CONNECTION ID: DanFallon-095d5d09e63ce624c <ip-___-__-_-___.ec2.internal> EXEC echo ~ubuntu <ip-___-__-_-___.ec2.internal> _wrap_command: 'echo PKjewgTIHJcLjaXeCjlasDjfZw echo ~ubuntu echo $'\n'$? echo uZmXXhFRmkCzCEZEPjWMQlNiIF ' <ip-___-__-_-___.ec2.internal> EXEC stdout line: <ip-___-__-_-___.ec2.internal> EXEC stdout line: Starting session with SessionId: DanFallon-095d5d09e63ce624c <ip-___-__-_-___.ec2.internal> EXEC remaining: 60 <ip-___-__-_-___.ec2.internal> EXEC stdout line: $ stty -echo ; <ip-___-__-_-___.ec2.internal> EXEC stdout line: PS1='' ; <ip-___-__-_-___.ec2.internal> EXEC stdout line: echo PKjewgTIHJcLjaXeCjlasDjfZw <ip-___-__-_-___.ec2.internal> EXEC stdout line: echo ~ubuntu <ip-___-__-_-___.ec2.internal> EXEC stdout line: echo $'\n'$? <ip-___-__-_-___.ec2.internal> EXEC stdout line: echo uZmXXhFRmkCzCEZEPjWMQlNiIF <ip-___-__-_-___.ec2.internal> EXEC stdout line: $ PKjewgTIHJcLjaXeCjlasDjfZw <ip-___-__-_-___.ec2.internal> EXEC stdout line: /home/ubuntu <ip-___-__-_-___.ec2.internal> EXEC stdout line: $ <ip-___-__-_-___.ec2.internal> EXEC stdout line: 0 <ip-___-__-_-___.ec2.internal> EXEC stdout line: uZmXXhFRmkCzCEZEPjWMQlNiIF <ip-___-__-_-___.ec2.internal> EXEC remaining: 59 <ip-___-__-_-___.ec2.internal> EXEC remaining: 58 <ip-___-__-_-___.ec2.internal> EXEC remaining: 57 <ip-___-__-_-___.ec2.internal> EXEC remaining: 56 <ip-___-__-_-___.ec2.internal> EXEC remaining: 55 <ip-___-__-_-___.ec2.internal> EXEC remaining: 54 <ip-___-__-_-___.ec2.internal> EXEC remaining: 53 ... ``` ## After adding a 5 second delay ``` Loading callback plugin minimal of type stdout, v2.0 from /usr/lib/python3.8/site-packages/ansible/plugins/callback/minimal.py META: ran handlers <ip-___-__-_-___.ec2.internal> ESTABLISH SSM CONNECTION TO: i-0cc44a1e2f7995c53 <ip-___-__-_-___.ec2.internal> SSM COMMAND: ['/usr/local/bin/session-manager-plugin', ...] Sleeping for 5 seconds. <ip-___-__-_-___.ec2.internal> SSM CONNECTION ID: DanFallon-05193c016e933c229 <ip-___-__-_-___.ec2.internal> EXEC echo ~ubuntu <ip-___-__-_-___.ec2.internal> _wrap_command: 'echo KylNOeAyCbfmTzlCZGrbHiYnSm echo ~ubuntu echo $'\n'$? echo PujmuNjsUIsmGZzoUwNAUvowBk ' <ip-___-__-_-___.ec2.internal> EXEC stdout line: <ip-___-__-_-___.ec2.internal> EXEC stdout line: Starting session with SessionId: DanFallon-05193c016e933c229 <ip-___-__-_-___.ec2.internal> EXEC stdout line: $ stty -echo ; <ip-___-__-_-___.ec2.internal> EXEC stdout line: PS1='' ; <ip-___-__-_-___.ec2.internal> EXEC stdout line: $ KylNOeAyCbfmTzlCZGrbHiYnSm <ip-___-__-_-___.ec2.internal> EXEC stdout line: /home/ubuntu <ip-___-__-_-___.ec2.internal> EXEC stdout line: $ <ip-___-__-_-___.ec2.internal> EXEC stdout line: 0 <ip-___-__-_-___.ec2.internal> EXEC stdout line: PujmuNjsUIsmGZzoUwNAUvowBk <ip-___-__-_-___.ec2.internal> EXEC remaining: 60 <ip-___-__-_-___.ec2.internal> EXEC remaining: 59 <ip-___-__-_-___.ec2.internal> EXEC remaining: 58 <ip-___-__-_-___.ec2.internal> EXEC remaining: 57 <ip-___-__-_-___.ec2.internal> EXEC remaining: 56 <ip-___-__-_-___.ec2.internal> EXEC remaining: 55 ``` Would love to see these fixes land, and maybe get some tests around this plugin (not sure how that would work). We bailed on the ssm plugin for now and are running ansible over ssh over ssm, which means we still have to manage ssh keys on instances (though we don't need a bastion any longer). Another strange issue that i see related to this during gathering facts is the AnsiballZ_setup.py that is run does something to mess with the shell and always hits EXEC remaining and always times out after without echoing to stdout the new line and the end mark. My remote host is running an older version of python so I'm initially thinking thats related. Trying to stand up a venv on remote to use as env Here's a patch that I'm willing to contribute (haven't gotten a chance to set up a fork yet) - Replaces `echo` with `printf` because it's more portable and robust - waits on receiving command replies before starting additional executions. Problems I still see: - Does aws_ssm.py need to support python2? I don't think my code is compatible. (and I thought boto3 was python3 only, maybe I'm wrong) - cmd (line 517) when executed could eat the end_mark command. maybe we could disconnect cmd's stdin? Any solution I thought of for this makes some assumptions about the command or the terminal that I didn't like. Anywho, I freely release the below under a GPL V3.0+ license like the files from which the were derived. I can look at figuring out the contributor agreement/etc later this week. ``` diff --git a/plugins/connection/aws_ssm.py b/plugins/connection/aws_ssm.py index 7f7d692..4dc3965 100644 --- a/plugins/connection/aws_ssm.py +++ b/plugins/connection/aws_ssm.py @@ -412,11 +412,97 @@ class Connection(ConnectionBase): def _prepare_terminal(self): ''' perform any one-time terminal settings ''' - if not self.is_windows: - cmd = "stty -echo\n" + "PS1=''\n" - cmd = to_bytes(cmd, errors='surrogate_or_strict') - self._session.stdin.write(cmd) + # No windows setup for now + if self.is_windows: + return + + # *_complete variables are 3 valued: + # - None: not started + # - False: started + # - True: complete + + startup_complete = False + startup_reply = re.compile( + r"Starting session with SessionId:\W+" + + re.escape(self._session_id) + + r"\r\n\$ ", re.MULTILINE) + + disable_echo_complete = None + disable_echo_cmd = to_bytes("stty -echo\n", errors='surrogate_or_strict') + disable_echo_reply = re.compile( + r"stty \-echo" + + r"\r\r\n\$", re.MULTILINE + ) + + disable_prompt_complete = None + end_mark = "".join([random.choice(string.ascii_letters) for i in xrange(self.MARK_LENGTH)]) + disable_prompt_cmd = to_bytes( + "PS1='' ; printf '\\n%s\\n' '" + end_mark + "'\n", + errors='surrogate_or_strict') + disable_prompt_reply = re.compile( + r"\r\r\n" + + re.escape(end_mark) + + r"\r\r\n", re.MULTILINE + ) + + stdout = "" + cursor = 0 + # Custom command execution for when we're waiting for startup + stop_time = int(round(time.time())) + self.get_option('ssm_timeout') + while (not disable_prompt_complete) and (self._session.poll() is None): + remaining = stop_time - int(round(time.time())) + if remaining < 1: + self._timeout = True + display.vvvv(u"PRE timeout stdout: {0}".format(to_bytes(stdout)), host=self.host) + raise AnsibleConnectionFailure("SSM start_session timeout on host: %s" + % self.instance_id) + if self._poll_stdout.poll(1000): + stdout += to_text(self._stdout.read(1024)) + display.vvvv(u"PRE stdout line: {0}".format(to_bytes(stdout)), host=self.host) + else: + display.vvvv(u"PRE remaining: {0}".format(remaining), host=self.host) + + # wait til prompt is ready + if startup_complete is False: + match = startup_reply.search(stdout,cursor) + if match: + display.vvvv(u"PRE startup output received", host=self.host) + cursor = match.end() + startup_complete = True + + + # disable echo + if startup_complete and (disable_echo_complete is None): + display.vvvv(u"PRE Disabling Echo: {0}".format(disable_echo_cmd), host=self.host) + self._session.stdin.write(disable_echo_cmd) + disable_echo_complete = False + + if disable_echo_complete is False: + match = disable_echo_reply.search(stdout) + if match: + stdout = stdout[match.end():] + disable_echo_complete = True + + + # disable prompt + if disable_echo_complete and disable_prompt_complete is None: + display.vvvv(u"PRE Disabling Prompt: {0}".format(disable_prompt_cmd), host=self.host) + self._session.stdin.write(disable_prompt_cmd) + disable_prompt_complete = False + + if disable_prompt_complete is False: + match = disable_prompt_reply.search(stdout) + if match: + stdout = stdout[match.end():] + disable_prompt_complete = True + + if not disable_prompt_complete: + raise AnsibleConnectionFailure("SSM process closed during _prepare_terminal on host: %s" + % self.instance_id) + else: + display.vvv(u"PRE Terminal configured", host=self.host) + def _wrap_command(self, cmd, sudoable, mark_start, mark_end): ''' wrap command so stdout and status can be extracted ''' @@ -427,7 +513,9 @@ class Connection(ConnectionBase): else: if sudoable: cmd = "sudo " + cmd - cmd = "echo " + mark_start + "\n" + cmd + "\necho $'\\n'$?\n" + "echo " + mark_end + "\n" + cmd = ("printf '%s\\n' '{0}' ;\n".format(mark_start) + + cmd + + " ;\nprintf '\\n%s\\n%s\\n' \"$?\" '{0}' ;\n".format(mark_end)) display.vvvv(u"_wrap_command: '{0}'".format(to_text(cmd)), host=self.host) return cmd ``` Im willing to try it because im stuck. My executing node is running py3. My endpoint is only running 2.7 (legacy os). So the plugin being py3 only should be fine. The py2 issues may just be with what ansible packages up and sends over to the endpoint @DanielFallon thanks for the patch. Had to change your ssm_timeout to timeout for the self.get_option call. upon executing im getting stuck in a PRE remaining loop eg prompt not ready during gathering facts The change in get_option call is because my patch was for the development version instead of the currently released version (they just changed it from timeout to ssm_timeout) can you post a redacted log with debug level at least 4? (-vvvv) I'd like to see which part of the setup loop it's getting stuck in. There are sort of 3 phases: first, waits for it to receive the string: ``` Starting session with SessionId: ``` second, waits to receive the string: ``` stty -echo $ ``` and the third wait's to receive a custom generated end string: ``` <end_mark> ``` I expected this code to be a bit fragile but fail safe. Maybe I should add some more detail to the timeout exception I can grab you a log, but may take some time, my inventory script now isn't populating as expected which sets up the s3 bucket name, and instance id. it's also worth noting that I only tested this with a sort of hello world example. I wouldn't be surprised if there are still things that don't work. I do think that some sort of scripted regression testing would be *very* valuable for this as it is fragile and could be broken by: - changes to ansible - changes to the ssm session plugin - changes to the aws api - probably differences in a hosts' `/etc/profile` all things to enumerate and test Does your patch apply to the 1.2 tagged release or on the main branch? Please see sanitized output. I took stock 1.2 and added just your patch and got the following ``` $ ansible-playbook $ANS_VAULT_FLAGS --limit TEST-GRP --user testuser --tags debug-vars common_aws_node.yml -vvvvvv ansible-playbook 2.9.9 config file = /home/user/ansibletest/ansible.cfg configured module search path = ['/home/user/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /home/user/venvs/ansible/lib64/python3.6/site-packages/ansible executable location = /home/user/venvs/ansible/bin/ansible-playbook python version = 3.6.8 (default, Apr 2 2020, 13:34:55) [GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] Using /home/user/ansibletest/ansible.cfg as config file Reading vault password file: XXXX Reading vault password file: XXXX Reading vault password file: XXXX setting up inventory plugins host_list declined parsing /home/user/ansibletest/inventories/dynamic_inv.yml as it did not pass its verify_file() method Start parsing DYN inventory Blacklisted hosts Done parsing DYN inventory Parsed /home/user/ansibletest/inventories/dynamic_inv.yml inventory source with auto plugin statically imported: /home/user/ansibletest/roles/basic-provisioning/tasks/10_install_start_aws_ssm.yml Loading callback plugin default of type stdout, v2.0 from /home/user/venvs/ansible/lib64/python3.6/site-packages/ansible/plugins/callback/default.py PLAYBOOK: common_aws_node.yml ************************************************************************************************************************************************************************************************************************ Positional arguments: common_aws_node.yml verbosity: 6 remote_user: testuser connection: smart timeout: 10 become_method: sudo tags: ('debug-vars',) inventory: ('/home/user/ansibletest/inventories/dynamic_inv.yml',) subset: TEST-GRP vault_ids: XXXX forks: 5 7 plays in common_aws_node.yml PLAY [provision] ************************************************************************************************************************************************************************************************************************************* META: ran handlers META: ran handlers META: ran handlers --- CUT --- (Skipped roles) PLAY [debug-vars] ************************************************************************************************************************************************************************************************************************************ TASK [Gathering Facts] ******************************************************************************************************************************************************************************************************************************* task path: /home/user/ansibletest/common_aws_node.yml:59 <10.x.x.x> ESTABLISH SSM CONNECTION TO: i-0AWS_INSTANCEID <10.x.x.x> SSM COMMAND: ['/usr/local/bin/session-manager-plugin', '{"SessionId": "[email protected]", "TokenValue": "XXXCUTXXX", "StreamUrl": "wss://ssmmessages.us-east-1.amazonaws.com/v1/data-channel/[email protected]?role=publish_subscribe", "ResponseMetadata": {"RequestId": "XXX REQ ID XXX", "HTTPStatusCode": 200, "HTTPHeaders": {"server": "Server", "date": "Fri, 02 Oct 2020 14:49:59 GMT", "content-type": "application/x-amz-json-1.1", "content-length": "668", "connection": "keep-alive", "x-amzn-requestid": "XXX amzn id XXX"}, "RetryAttempts": 0}}', 'us-east-1', 'StartSession', '', '{"Target": "i-0AWS_INSTANCEID"}', 'https://ssm.us-east-1.amazonaws.com'] <10.x.x.x> PRE stdout line: b'\r\nStarting session with SessionId: [email protected]\r\n' <10.x.x.x> PRE remaining: 60 <10.x.x.x> PRE stdout line: b'\r\nStarting session with SessionId: [email protected]\r\n\x1b[?1034hsh-4.2$ ' <10.x.x.x> PRE remaining: 59 <10.x.x.x> PRE remaining: 58 --- CUT --- <10.x.x.x> PRE remaining: 3 <10.x.x.x> PRE remaining: 2 <10.x.x.x> PRE remaining: 1 <10.x.x.x> PRE timeout stdout: b'\r\nStarting session with SessionId: [email protected]\r\n\x1b[?1034hsh-4.2$ ' <10.x.x.x> ssm_retry: attempt: 0, cmd (echo ~testuser...), pausing for 0 seconds <10.x.x.x> CLOSING SSM CONNECTION TO: i-0AWS_INSTANCEID <10.x.x.x> TERMINATE SSM SESSION: [email protected] <10.x.x.x> ESTABLISH SSM CONNECTION TO: i-0AWS_INSTANCEID <10.x.x.x> SSM COMMAND: ['/usr/local/bin/session-manager-plugin', '{"SessionId": "[email protected]", "TokenValue": "XXXCUTXXX", "StreamUrl": "wss://ssmmessages.us-east-1.amazonaws.com/v1/data-channel/[email protected]?role=publish_subscribe", "ResponseMetadata": {"RequestId": "XXX REQ ID XXX", "HTTPStatusCode": 200, "HTTPHeaders": {"server": "Server", "date": "Fri, 02 Oct 2020 14:51:00 GMT", "content-type": "application/x-amz-json-1.1", "content-length": "668", "connection": "keep-alive", "x-amzn-requestid": "XXX amzn id XXX"}, "RetryAttempts": 0}}', 'us-east-1', 'StartSession', '', '{"Target": "i-0AWS_INSTANCEID"}', 'https://ssm.us-east-1.amazonaws.com'] <10.x.x.x> PRE stdout line: b'\r\nStarting session with SessionId: [email protected]\r\n' <10.x.x.x> PRE remaining: 60 <10.x.x.x> PRE stdout line: b'\r\nStarting session with SessionId: [email protected]\r\n\x1b[?1034hsh-4.2$ ' <10.x.x.x> PRE remaining: 59 <10.x.x.x> PRE remaining: 58 ``` I also added the bash shell patch as well (but changed bash -l to bash --noprofile -l) with a similar result I modified some of the re's that are in the patch (mainly removing the \r\n's). Now I'm hitting the same issue. The AnsiballZ_setup.py gets transferred and executed. It prints out the json for the facts, but i never get the end mark. As in I never see the second printf output ``` sudo sudo -H -S -n -u root /bin/sh -c 'echo BECOME-SUCCESS-lzrbkhycxnugzysliwrhdukemyhhtyde ; /usr/bin/python /home/maintuser/.ansible/tmp/ansible-tmp-1601664494.6311371-10330-41749016017816/AnsiballZ_setup.py' ; printf '\n%s\n%s\n' "$?" 'icjRpqBJJHvCxBxLeqZMYeJKhQ' ; ``` Then back to the retry loop the bash patch is definitely incompatible with mine. (because the regex would *definitely* have to change.) does `python ansible-tmp-1601664494.6311371-10330-41749016017816/AnsiballZ_setup.py` open stdin? if yes, then it might be eating the printf command (meaning that the shell would never receive it.) This is one of the things I was worried about in my comment above. I kind of want to look at some other connection plugins and see how they handle this, because I think a lot of pieces of this are pretty fragile and I want to see others ideas. maybe instead of clearing the prompt, we could set it to an end_mark so that the shell will print it. I tried both sh and bash (with and w/o modding the re's) and both have similar behavior. I do think that AnsiballZ_setup.py is doing something to stdin. This is not an SSM specific solution, but I'm tempted to try out using SendSSHPublicKey from the EC2 instance connect api and then wrapping the ssh connection library instead. Feels like it might be generally more stable (and would support sftp as well) SSM might still be necessary for the tunnel, but I'm not sure piping commands to stdin is ever really going to be partiuclarly stable. Any reason why ssmStartSession is superior that I should know about? Looking at this a bit closer, it looks like the right way to address this if use of SSM is wanted is to add a parameter like `ssm_exec_document_name`. I had not gotten a chance to use SSM much prior to now and wasn't super familiar with its api. The document name in the current version of the api can define most of the behavior of how an interactive session starts, although it unfortunately seems to still start with a raw shell (see here: https://github.com/aws/amazon-ssm-agent/blob/b9654b268afcb7e70a9cc6c6d9b7d2a676f5b468/agent/session/plugins/shell/shell_unix.go#L53 ) Because customization of the shell is *so* fragile, it's probably worthwhile to provide a sane default and then allow users to override the --document-name provided to the session to configure things further. To facilitate this, the important part is to establish a protocol for communicating stdout and the exit code back to the client (preferably one that is *slightly* more robust than what is present now so that a user can *always* produce working results for their system) I'll give it another half an hour today and post results @DanielFallon would be interested to see your results. Seems to be a step in the right direction. > Here is a workaround that avoids `sh` entirely by starting a bash shell. > > ```diff > --- a/plugins/connection/aws_ssm.py 2020-09-03 18:43:43.818000000 +0200 > +++ b/plugins/connection/aws_ssm.py 2020-09-03 18:43:19.805000000 +0200 > @@ -288,11 +288,17 @@ > > profile_name = '' > region_name = self.get_option('region') > - ssm_parameters = dict() > > client = boto3.client('ssm', region_name=region_name) > self._client = client > - response = client.start_session(Target=self.instance_id, Parameters=ssm_parameters) > + > + if self.is_windows: > + ssm_parameters = dict() > + response = client.start_session(Target=self.instance_id, Parameters=ssm_parameters) > + else: > + ssm_parameters = {"command": ["bash -l"]} > + response = client.start_session(Target=self.instance_id, DocumentName="AWS-StartInteractiveCommand", Parameters=ssm_parameters) > + > self._session_id = response['SessionId'] > > cmd = [ > ``` I think this solution work partially, because is not closing the sessions in session manager. And the system open one session for every one task in Ansible. This causes if I execute a playbook with 10 tasks, 10 session is opening and no closing xd ... The above wont work if there is anything custom about the systems (or users) bash profile that changes what is presented on stdout. I've tried this even with --noprofile and it still hangs for me when gathering facts. @mikeneiderhauser hey btw I did rewrite this using paramiko ssh over the weekend. it's still a bit grody but should work. The biggest problem is that the connections aren't cached. so there are *A LOT* of aws API calls. I didn't realize that paramiko didn't support persistent connections. I'll have to switch it to borrow from the SSH connection plugin and leverage ssh pipelining instead. Hopefully I can detect whether or not a pipeline is open and not restart the connection from the logic of that plugin. If not, then I'll have to build a disk based cache of some kind for the key timeout. (Also sorry for the extra cruft trying to cache things, I forgot that ansible forks to a new process for each connection) Here's what I tried and I think this finally should work just as well as the ssh plugin, but it will exhaust your aws api rate limit rather quickly. https://gist.github.com/DanielFallon/dffad373c688da32919e709d6738d715 As another workaround, here's a proxy command that should just work to allow connections via ec2-instance-connect and then proxy via ssm: https://gist.github.com/DanielFallon/45310cc76f46c1f1b2f7272d19b76312 ^Technically this is *significantly* more efficient than the plugin in the gist because SSH Multiplexing will be used if it available. (and is by default) @DanielFallon thanks for this. ill take a look I'll turn this into a pull request later this week, but here's a plugin that uses ec2-instance-connect to push a temporary ssh key to the host and uses this to authenticate. If paired with a proxycommand for ssm this should be pretty effective: https://gist.github.com/DanielFallon/67572f4439602774d02fbbe3bce8a5b9 > does `python ansible-tmp-1601664494.6311371-10330-41749016017816/AnsiballZ_setup.py` open stdin? if yes, then it might be eating the printf command (meaning that the shell would never receive it.) Yes I'm finding that the python command eats the printf. I can get around it by adding an `echo | {cmd};` to the wrapped command, and the mark end printf seems to appear. Here's the full patch, making use of your previous patch @DanielFallon I made some minor changes so we don't use the regexes, as they were being fickle. ``` diff --git a/playbooks/connection_plugins/aws_ssm2.py b/playbooks/connection_plugins/aws_ssm2.py index 1c01dba..baa15f3 100644 --- a/playbooks/connection_plugins/aws_ssm2.py +++ b/playbooks/connection_plugins/aws_ssm2.py @@ -444,10 +444,94 @@ class Connection(ConnectionBase): def _prepare_terminal(self): """ perform any one-time terminal settings """ - if not self.is_windows: - cmd = "stty -echo\n" + "PS1=''\n" - cmd = to_bytes(cmd, errors="surrogate_or_strict") - self._session.stdin.write(cmd) + # No windows setup for now + if self.is_windows: + return + + # *_complete variables are 3 valued: + # - None: not started + # - False: started + # - True: complete + + startup_complete = False + disable_echo_complete = None + disable_echo_cmd = to_bytes("stty -echo\n", errors="surrogate_or_strict") + + disable_prompt_complete = None + end_mark = "".join( + [random.choice(string.ascii_letters) for i in xrange(self.MARK_LENGTH)] + ) + disable_prompt_cmd = to_bytes( + "PS1='' ; printf '\\n%s\\n' '" + end_mark + "'\n", + errors="surrogate_or_strict", + ) + disable_prompt_reply = re.compile( + r"\r\r\n" + re.escape(end_mark) + r"\r\r\n", re.MULTILINE + ) + + stdout = "" + # Custom command execution for when we're waiting for startup + stop_time = int(round(time.time())) + self.get_option("ssm_timeout") + while (not disable_prompt_complete) and (self._session.poll() is None): + remaining = stop_time - int(round(time.time())) + if remaining < 1: + self._timeout = True + display.vvvv( + "PRE timeout stdout: {0}".format(to_bytes(stdout)), host=self.host + ) + raise AnsibleConnectionFailure( + "SSM start_session timeout on host: %s" % self.instance_id + ) + if self._poll_stdout.poll(1000): + stdout += to_text(self._stdout.read(1024)) + display.vvvv( + "PRE stdout line: {0}".format(to_bytes(stdout)), host=self.host + ) + else: + display.vvvv("PRE remaining: {0}".format(remaining), host=self.host) + + # wait til prompt is ready + if startup_complete is False: + match = str(stdout).find("Starting session with SessionId") + if match != -1: + display.vvvv("PRE startup output received", host=self.host) + startup_complete = True + + # disable echo + if startup_complete and (disable_echo_complete is None): + display.vvvv( + "PRE Disabling Echo: {0}".format(disable_echo_cmd), host=self.host + ) + self._session.stdin.write(disable_echo_cmd) + disable_echo_complete = False + + if disable_echo_complete is False: + match = str(stdout).find("stty -echo") + if match != -1: + disable_echo_complete = True + + # disable prompt + if disable_echo_complete and disable_prompt_complete is None: + display.vvvv( + "PRE Disabling Prompt: {0}".format(disable_prompt_cmd), + host=self.host, + ) + self._session.stdin.write(disable_prompt_cmd) + disable_prompt_complete = False + + if disable_prompt_complete is False: + match = disable_prompt_reply.search(stdout) + if match: + stdout = stdout[match.end() :] + disable_prompt_complete = True + + if not disable_prompt_complete: + raise AnsibleConnectionFailure( + "SSM process closed during _prepare_terminal on host: %s" + % self.instance_id + ) + else: + display.vvv("PRE Terminal configured", host=self.host) def _wrap_command(self, cmd, sudoable, mark_start, mark_end): """ wrap command so stdout and status can be extracted """ @@ -460,14 +544,9 @@ class Connection(ConnectionBase): if sudoable: cmd = "sudo " + cmd cmd = ( - "echo " - + mark_start - + "\n" - + cmd - + "\necho $'\\n'$?\n" - + "echo " - + mark_end - + "\n" + f"printf '%s\\n' '{mark_start}';\n" + f"echo | {cmd};\n" + f"printf '\\n%s\\n%s\\n' \"$?\" '{mark_end}';\n" ) display.vvvv(u"_wrap_command: '{0}'".format(to_text(cmd)), host=self.host) ``` I put the patched version of `aws_ssm2.py` into my playbooks directory in `connection_plugins/` dir, set `ansible_connection: aws_ssm2`, and was able to successfully use ssm to run playbooks against my Ubuntu EC2 instance. Hi, is there an official solution? I am facing the same problem.
2021-04-28T07:52:05
ansible-collections/community.aws
592
ansible-collections__community.aws-592
[ "578" ]
ba89813d1a91a2b57f506f019de65452f9e1c0a9
diff --git a/plugins/modules/sqs_queue.py b/plugins/modules/sqs_queue.py --- a/plugins/modules/sqs_queue.py +++ b/plugins/modules/sqs_queue.py @@ -377,7 +377,7 @@ def update_sqs_queue(module, client, queue_url): new_value = str(new_value).lower() value = str(value).lower() - if new_value == value: + if str(new_value) == str(value): continue # Boto3 expects strings
diff --git a/tests/integration/targets/sqs_queue/tasks/main.yml b/tests/integration/targets/sqs_queue/tasks/main.yml --- a/tests/integration/targets/sqs_queue/tasks/main.yml +++ b/tests/integration/targets/sqs_queue/tasks/main.yml @@ -67,6 +67,50 @@ - create_result.policy.Version == "2012-10-17" - create_result.policy.Statement[0].Effect == "Allow" - create_result.policy.Statement[0].Action == "*" + - name: Test idempotentcy + sqs_queue: + name: "{{ create_result.name }}" + default_visibility_timeout: 900 + delivery_delay: 900 + maximum_message_size: 9009 + message_retention_period: 900 + receive_message_wait_time: 10 + policy: + Version: "2012-10-17" + Statement: + Effect: Allow + Action: "*" + register: create_result + - name: Assert nothing changed + assert: + that: + - not create_result.changed + - name: Test update + sqs_queue: + name: "{{ create_result.name }}" + default_visibility_timeout: 899 + delivery_delay: 899 + maximum_message_size: 9008 + message_retention_period: 899 + receive_message_wait_time: 9 + policy: + Version: "2012-10-17" + Statement: + Effect: Allow + Action: "*" + register: create_result + - name: Assert queue updated with configuration + assert: + that: + - create_result.changed + - create_result.default_visibility_timeout == 899 + - create_result.delivery_delay == 899 + - create_result.maximum_message_size == 9008 + - create_result.message_retention_period == 899 + - create_result.receive_message_wait_time == 9 + - create_result.policy.Version == "2012-10-17" + - create_result.policy.Statement[0].Effect == "Allow" + - create_result.policy.Statement[0].Action == "*" always: - name: Cleaning up queue sqs_queue:
sqs_queue is not idempotent when any queue attribute parameter passed in playbook <!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> sqs-queue is not idempotent if we pass any parameter (sqs attributes) ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.10.4 config file = None configured module search path = ['/Users/spathak3/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/ansible executable location = /Library/Frameworks/Python.framework/Versions/3.8/bin/ansible python version = 3.8.0 (v3.8.0:fa919fdf25, Oct 14 2019, 10:23:27) [Clang 6.0 (clang-600.0.57)] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below No change ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> Darwin Darwin Kernel Version 20.3.0: Thu Jan 21 00:07:06 PST 2021; root:xnu-7195.81.3~1/RELEASE_X86_64 i386 ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> <!--- Paste example playbooks or commands between quotes below --> ```yaml # This playbook is idempotent running multiple time --- - name: sqs idempotency check hosts: localhost tasks: - name: Idempotence check community.aws.sqs_queue: name: sqs-idempotency-issue region: eu-west-1 state: present # This playbook is NOT idempotent on multiple run, only happen when we pass any attribute params here e.g. default_visibility_timeout --- - name: sqs idempotency check hosts: localhost tasks: - name: Idempotence check community.aws.sqs_queue: name: sqs-idempotency-issue region: eu-west-1 state: present default_visibility_timeout: 120 ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> setting parameter (sqs attributes) in playbook shouldn't prevent the idempotency. ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> Adding parameter `default_visibility_timeout: 120` prevents idempotency on multiple run. <!--- Paste verbatim command output between quotes --> ```paste below spathak3@macbook ~/infra/aws-operator > $ (⎈ |minikube:aws-operator-system) ansible-playbook roles/sqs-queue/tasks/demo.yaml -v No config file found; using defaults [WARNING]: No inventory was parsed, only implicit localhost is available [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all' PLAY [sqs idempotency check] ************************************************************************************************************************************************************************* TASK [Gathering Facts] ******************************************************************************************************************************************************************************* ok: [localhost] TASK [Idempotence check] ***************************************************************************************************************************************************************************** changed: [localhost] => {"approximate_number_of_messages": 0, "approximate_number_of_messages_delayed": 0, "approximate_number_of_messages_not_visible": 0, "changed": true, "created_timestamp": 1620915962, "default_visibility_timeout": 120, "delay_seconds": 0, "delivery_delay": 0, "last_modified_timestamp": 1620916213, "maximum_message_size": 262144, "message_retention_period": 345600, "name": "sqs-idempotency-issue", "policy": null, "queue_arn": "arn:aws:sqs:eu-west-1:822436023150:sqs-idempotency-issue", "queue_url": "https://eu-west-1.queue.amazonaws.com/822436023150/sqs-idempotency-issue", "receive_message_wait_time": 0, "receive_message_wait_time_seconds": 0, "redrive_policy": null, "region": "eu-west-1", "tags": {}, "visibility_timeout": 120} PLAY RECAP ******************************************************************************************************************************************************************************************* localhost : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 spathak3@macbook ~/infra/aws-operator > $ (⎈ |minikube:aws-operator-system) ansible-playbook roles/sqs-queue/tasks/demo.yaml -v No config file found; using defaults [WARNING]: No inventory was parsed, only implicit localhost is available [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all' PLAY [sqs idempotency check] ************************************************************************************************************************************************************************* TASK [Gathering Facts] ******************************************************************************************************************************************************************************* ok: [localhost] TASK [Idempotence check] ***************************************************************************************************************************************************************************** changed: [localhost] => {"approximate_number_of_messages": 0, "approximate_number_of_messages_delayed": 0, "approximate_number_of_messages_not_visible": 0, "changed": true, "created_timestamp": 1620915962, "default_visibility_timeout": 120, "delay_seconds": 0, "delivery_delay": 0, "last_modified_timestamp": 1620916213, "maximum_message_size": 262144, "message_retention_period": 345600, "name": "sqs-idempotency-issue", "policy": null, "queue_arn": "arn:aws:sqs:eu-west-1:822436023150:sqs-idempotency-issue", "queue_url": "https://eu-west-1.queue.amazonaws.com/822436023150/sqs-idempotency-issue", "receive_message_wait_time": 0, "receive_message_wait_time_seconds": 0, "redrive_policy": null, "region": "eu-west-1", "tags": {}, "visibility_timeout": 120} PLAY RECAP ******************************************************************************************************************************************************************************************* localhost : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 spathak3@macbook~/infra/aws-operator > $ (⎈ |minikube:aws-operator-system) ansible-playbook roles/sqs-queue/tasks/demo.yaml -v No config file found; using defaults [WARNING]: No inventory was parsed, only implicit localhost is available [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all' PLAY [sqs idempotency check] ************************************************************************************************************************************************************************* TASK [Gathering Facts] ******************************************************************************************************************************************************************************* ok: [localhost] TASK [Idempotence check] ***************************************************************************************************************************************************************************** changed: [localhost] => {"approximate_number_of_messages": 0, "approximate_number_of_messages_delayed": 0, "approximate_number_of_messages_not_visible": 0, "changed": true, "created_timestamp": 1620915962, "default_visibility_timeout": 120, "delay_seconds": 0, "delivery_delay": 0, "last_modified_timestamp": 1620916213, "maximum_message_size": 262144, "message_retention_period": 345600, "name": "sqs-idempotency-issue", "policy": null, "queue_arn": "arn:aws:sqs:eu-west-1:822436023150:sqs-idempotency-issue", "queue_url": "https://eu-west-1.queue.amazonaws.com/822436023150/sqs-idempotency-issue", "receive_message_wait_time": 0, "receive_message_wait_time_seconds": 0, "redrive_policy": null, "region": "eu-west-1", "tags": {}, "visibility_timeout": 120} PLAY RECAP ******************************************************************************************************************************************************************************************* localhost : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 ```
2021-06-03T02:23:12
ansible-collections/community.aws
648
ansible-collections__community.aws-648
[ "597" ]
60aa1c7f3033eaa7315bafee002f76c18981b605
diff --git a/plugins/modules/aws_kms_info.py b/plugins/modules/aws_kms_info.py --- a/plugins/modules/aws_kms_info.py +++ b/plugins/modules/aws_kms_info.py @@ -46,6 +46,17 @@ description: Whether to get full details (tags, grants etc.) of keys pending deletion default: False type: bool + keys_attr: + description: + - Whether to return the results in the C(keys) attribute as well as the + C(kms_keys) attribute. + - Returning the C(keys) attribute conflicts with the builtin keys() + method on dictionaries and as such has been deprecated. + - After version C(3.0.0) this parameter will do nothing, and after + version C(4.0.0) this parameter will be removed. + type: bool + default: True + version_added: 2.0.0 extends_documentation_fragment: - amazon.aws.aws - amazon.aws.ec2 @@ -70,7 +81,7 @@ ''' RETURN = ''' -keys: +kms_keys: description: list of keys type: complex returned: always @@ -441,6 +452,7 @@ def main(): key_id=dict(aliases=['key_arn']), filters=dict(type='dict'), pending_deletion=dict(type='bool', default=False), + keys_attr=dict(type='bool', default=True), ) module = AnsibleAWSModule(argument_spec=argument_spec, @@ -455,7 +467,17 @@ def main(): module.fail_json_aws(e, msg='Failed to connect to AWS') all_keys = get_kms_info(connection, module) - module.exit_json(keys=[key for key in all_keys if key_matches_filters(key, module.params['filters'])]) + filtered_keys = [key for key in all_keys if key_matches_filters(key, module.params['filters'])] + ret_params = dict(kms_keys=filtered_keys) + + # We originally returned "keys" + if module.params['keys_attr']: + module.deprecate("Returning results in the 'keys' attribute conflicts with the builtin keys() method on " + "dicts and as such is deprecated. Please use the kms_keys attribute. This warning can be " + "silenced by setting keys_attr to False.", + version='3.0.0', collection_name='community.aws') + ret_params.update(dict(keys=filtered_keys)) + module.exit_json(**ret_params) if __name__ == '__main__':
aws_kms_info keys attribute returns builtin keys method <!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY Using the info result in a registered variable results that the keys attr is overwritten by the builtin keys method. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME ``` aws_kms_info ``` ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.10.5 config file = /home/gthielebein/.ansible.cfg configured module search path = ['/home/gthielebein/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /usr/lib/python3/dist-packages/ansible executable location = /usr/bin/ansible python version = 3.9.5 (default, May 11 2021, 08:20:37) [GCC 10.3.0] ``` ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> Create snippet: <!--- Paste example playbooks or commands between quotes below --> ```yaml - name: Get KMS key community.aws.aws_kms_info: register: kms_key_result - name: Print KMS keys debug: msg="{{ kms_key_result.keys }}" ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> The debug output shows the ```keys``` attr. ``` ok: [localhost] => { "msg": { "changed": false, "failed": false, "keys": [ ``` This should be the content of ```keys```: ``` TASK [Print KMS keys] { "aliases": [ "aws/ecr" ], "aws_account_id": "**************", "creation_date": "2021-05-28T13:22:06.321000+02:00", "customer_master_key_spec": "SYMMETRIC_DEFAULT", "description": "Default master key that protects my ECR data when no other key is defined", "enable_key_rotation": true, "enabled": true, "encryption_algorithms": [ "SYMMETRIC_DEFAULT" ], "grants": [ .... ``` ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> <!--- Paste verbatim command output between quotes --> ```paste below TASK [Print KMS keys] *********************************************************************************************************************************************************************** ok: [localhost] => { "msg": "<built-in method keys of dict object at 0x7fb34b567ac0>" } ```
Current workaround is to use this syntax: ``` debug: msg="{{ kms_key_result['keys'] }}" ``` cc @jillr @s-hertel @tremble @wimnat [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> I do not believe that it is an easy fix since this is a Python related issue more than a module related issue. For example, the following tasks would produce the same output : ``` - set_fact: kms_key_result: {'keys': ''} - name: Print KMS keys debug: var: kms_key_result.keys ``` ``` TASK [Print KMS keys] ********************************************************************************************************************************************************************************************* ok: [127.0.0.1] => kms_key_result.keys: <built-in method keys of dict object at 0x7f3149419780> ``` The only way to solve this issue is to use another key name on this line of the module : ``` module.exit_json(keys=[key for key in all_keys if key_matches_filters(key, module.params['filters'])]) ``` However this would require a major version since it would break the backward compatibility of the plugin and I don't believe that it an easy decision to make. cc @markuman [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify --->
2021-07-19T11:13:51
ansible-collections/community.aws
692
ansible-collections__community.aws-692
[ "689" ]
780255142ecd09a9f9bb1f76ecb3f186db398017
diff --git a/plugins/modules/s3_sync.py b/plugins/modules/s3_sync.py --- a/plugins/modules/s3_sync.py +++ b/plugins/modules/s3_sync.py @@ -148,6 +148,11 @@ file_root: roles/s3/files/ storage_class: GLACIER +- name: basic individual file upload + community.aws.s3_sync: + bucket: tedder + file_root: roles/s3/files/file_name + - name: all the options community.aws.s3_sync: bucket: tedder @@ -322,41 +327,57 @@ def calculate_multipart_etag(source_path, chunk_size=DEFAULT_CHUNK_SIZE): def gather_files(fileroot, include=None, exclude=None): ret = [] - for (dirpath, dirnames, filenames) in os.walk(fileroot): - for fn in filenames: - fullpath = os.path.join(dirpath, fn) - # include/exclude - if include: - found = False - for x in include.split(','): - if fnmatch.fnmatch(fn, x): - found = True - if not found: - # not on the include list, so we don't want it. - continue - - if exclude: - found = False - for x in exclude.split(','): - if fnmatch.fnmatch(fn, x): - found = True - if found: - # skip it, even if previously included. - continue - - chopped_path = os.path.relpath(fullpath, start=fileroot) - fstat = os.stat(fullpath) - f_size = fstat[osstat.ST_SIZE] - f_modified_epoch = fstat[osstat.ST_MTIME] - ret.append({ - 'fullpath': fullpath, - 'chopped_path': chopped_path, - 'modified_epoch': f_modified_epoch, - 'bytes': f_size, - }) - # dirpath = path *to* the directory - # dirnames = subdirs *in* our directory - # filenames + + if os.path.isfile(fileroot): + fullpath = fileroot + fstat = os.stat(fullpath) + path_array = fileroot.split('/') + chopped_path = path_array[-1] + f_size = fstat[osstat.ST_SIZE] + f_modified_epoch = fstat[osstat.ST_MTIME] + ret.append({ + 'fullpath': fullpath, + 'chopped_path': chopped_path, + 'modified_epoch': f_modified_epoch, + 'bytes': f_size, + }) + + else: + for (dirpath, dirnames, filenames) in os.walk(fileroot): + for fn in filenames: + fullpath = os.path.join(dirpath, fn) + # include/exclude + if include: + found = False + for x in include.split(','): + if fnmatch.fnmatch(fn, x): + found = True + if not found: + # not on the include list, so we don't want it. + continue + + if exclude: + found = False + for x in exclude.split(','): + if fnmatch.fnmatch(fn, x): + found = True + if found: + # skip it, even if previously included. + continue + + chopped_path = os.path.relpath(fullpath, start=fileroot) + fstat = os.stat(fullpath) + f_size = fstat[osstat.ST_SIZE] + f_modified_epoch = fstat[osstat.ST_MTIME] + ret.append({ + 'fullpath': fullpath, + 'chopped_path': chopped_path, + 'modified_epoch': f_modified_epoch, + 'bytes': f_size, + }) + # dirpath = path *to* the directory + # dirnames = subdirs *in* our directory + # filenames return ret
diff --git a/tests/integration/targets/s3_sync/defaults/main.yml b/tests/integration/targets/s3_sync/defaults/main.yml --- a/tests/integration/targets/s3_sync/defaults/main.yml +++ b/tests/integration/targets/s3_sync/defaults/main.yml @@ -1,2 +1,3 @@ test_bucket: "{{ tiny_prefix }}-testbucket-ansible" test_bucket_2: "{{ tiny_prefix }}-testbucket-ansible-2" +test_bucket_3: "{{ tiny_prefix }}-testbucket-ansible-3" diff --git a/tests/integration/targets/s3_sync/tasks/main.yml b/tests/integration/targets/s3_sync/tasks/main.yml --- a/tests/integration/targets/s3_sync/tasks/main.yml +++ b/tests/integration/targets/s3_sync/tasks/main.yml @@ -77,6 +77,7 @@ - assert: that: - output is changed + # ============================================================ - name: Sync files already present @@ -99,6 +100,27 @@ that: - output is not changed + # ============================================================ + - name: Create a third s3_bucket + s3_bucket: + name: "{{ test_bucket_3 }}" + state: present + register: output + + - assert: + that: + - output.changed + - output.name == "{{ test_bucket_3 }}" + - not output.requester_pays + + - name: Sync individual file with remote bucket + s3_sync: + bucket: "{{ test_bucket_3 }}" + file_root: "{{ output_dir }}/s3_sync/test1.txt" + register: output + - assert: + that: + - output is changed # ============================================================ # DOCUMENTATION EXAMPLES @@ -132,3 +154,4 @@ with_items: - "{{ test_bucket }}" - "{{ test_bucket_2 }}" + - "{{ test_bucket_3 }}"
s3_sync file_root parameter does not accept file path ### Summary Hello, the s3_sync module documentation for file_root parameter comment states: > File/directory path for synchronization. To me, this suggests that an individual file can be specified, ex: `/home/me/my_archive.tar.gz` When an individual file path is provided, no file is detected by the file globbing. Thus, nothing is uploaded: ``` TASK [ia-home-archive : upload to S3 Glacier] ***************************************************** ok: [127.0.0.1] => { "changed": false, "filelist_actionable": [], "filelist_initial": [], "filelist_local_etag": [], "filelist_s3": [], "filelist_typed": [], "invocation": { "module_args": { "aws_access_key": null, "aws_ca_bundle": null, "aws_config": null, "aws_secret_key": null, "bucket": "ia-home-archive", "cache_control": "", "debug_botocore_endpoint_logs": false, "delete": false, "ec2_url": null, "exclude": ".*", "file_change_strategy": "date_size", "file_root": "/home/me/my_archive.tar.gz", "include": "*", "key_prefix": "", "mime_map": null, "mode": "push", "permission": "private", "profile": "2fa", "region": "us-west-2", "retries": null, "security_token": null, "storage_class": "DEEP_ARCHIVE", "validate_certs": true } }, "uploads": [] } ``` Once I changed the `file_root` parameter to `/home/me` and `include` parameter to `my_archive.tar.gz`, I got the desired result. It seems the documentation could be revised to clarify that `file_root` can only be a directory, or the module could be further improved to support a file path in the `file_root` parameter. ### Issue Type Bug Report ### Component Name s3_sync ### Ansible Version ```console (paste below) $ ansible --version ansible [core 2.11.3] config file = None configured module search path = ['/home/peter.hall/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /usr/local/share/virtualenvs/aws/lib/python3.6/site-packages/ansible ansible collection location = /home/peter.hall/.ansible/collections:/usr/share/ansible/collections executable location = /usr/local/share/virtualenvs/aws/bin/ansible python version = 3.6.8 (default, Nov 16 2020, 16:55:22) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] jinja version = 3.0.1 libyaml = True ``` ### Collection Versions ```console (paste below) $ ansible-galaxy collection list Collection Version ----------------------------- ------- amazon.aws 1.5.0 ansible.netcommon 2.3.0 ansible.posix 1.2.0 ansible.utils 2.3.1 ansible.windows 1.7.2 arista.eos 2.2.0 awx.awx 19.2.2 azure.azcollection 1.8.0 check_point.mgmt 2.0.0 chocolatey.chocolatey 1.1.0 cisco.aci 2.0.0 cisco.asa 2.0.2 cisco.intersight 1.0.16 cisco.ios 2.3.1 cisco.iosxr 2.4.0 cisco.meraki 2.4.2 cisco.mso 1.2.0 cisco.nso 1.0.3 cisco.nxos 2.5.0 cisco.ucs 1.6.0 cloudscale_ch.cloud 2.2.0 community.aws 1.5.0 community.azure 1.0.0 community.crypto 1.8.0 community.digitalocean 1.8.0 community.docker 1.9.0 community.fortios 1.0.0 community.general 3.5.0 community.google 1.0.0 community.grafana 1.2.1 community.hashi_vault 1.3.2 community.hrobot 1.1.1 community.kubernetes 1.2.1 community.kubevirt 1.0.0 community.libvirt 1.0.2 community.mongodb 1.3.0 community.mysql 2.1.0 community.network 3.0.0 community.okd 1.1.2 community.postgresql 1.4.0 community.proxysql 1.1.0 community.rabbitmq 1.1.0 community.routeros 1.2.0 community.skydive 1.0.0 community.sops 1.1.0 community.vmware 1.12.0 community.windows 1.6.0 community.zabbix 1.4.0 containers.podman 1.6.2 cyberark.conjur 1.1.0 cyberark.pas 1.0.7 dellemc.enterprise_sonic 1.1.0 dellemc.openmanage 3.6.0 dellemc.os10 1.1.1 dellemc.os6 1.0.7 dellemc.os9 1.0.4 f5networks.f5_modules 1.11.0 fortinet.fortimanager 2.1.3 fortinet.fortios 2.1.2 frr.frr 1.0.3 gluster.gluster 1.0.1 google.cloud 1.0.2 hetzner.hcloud 1.4.4 hpe.nimble 1.1.3 ibm.qradar 1.0.3 infinidat.infinibox 1.2.4 inspur.sm 1.2.0 junipernetworks.junos 2.4.0 kubernetes.core 1.2.1 mellanox.onyx 1.0.0 netapp.aws 21.6.0 netapp.azure 21.8.1 netapp.cloudmanager 21.9.0 netapp.elementsw 21.6.1 netapp.ontap 21.9.0 netapp.um_info 21.7.0 netapp_eseries.santricity 1.2.13 netbox.netbox 3.1.1 ngine_io.cloudstack 2.1.0 ngine_io.exoscale 1.0.0 ngine_io.vultr 1.1.0 openstack.cloud 1.5.0 openvswitch.openvswitch 2.0.0 ovirt.ovirt 1.5.4 purestorage.flasharray 1.10.0 purestorage.flashblade 1.6.0 sensu.sensu_go 1.11.1 servicenow.servicenow 1.0.6 splunk.es 1.0.2 t_systems_mms.icinga_director 1.20.0 theforeman.foreman 2.1.2 vyos.vyos 2.5.0 wti.remote 1.0.1 ``` ### AWS SDK versions ```console (paste below) $ pip show boto boto3 botocore Name: boto Version: 2.49.0 Summary: Amazon Web Services Library Home-page: https://github.com/boto/boto/ Author: Mitch Garnaat Author-email: [email protected] License: MIT Location: /usr/local/share/virtualenvs/aws/lib/python3.6/site-packages Requires: Required-by: --- Name: boto3 Version: 1.18.18 Summary: The AWS SDK for Python Home-page: https://github.com/boto/boto3 Author: Amazon Web Services Author-email: License: Apache License 2.0 Location: /usr/local/share/virtualenvs/aws/lib/python3.6/site-packages Requires: botocore, jmespath, s3transfer Required-by: --- Name: botocore Version: 1.21.18 Summary: Low-level, data-driven core of boto 3. Home-page: https://github.com/boto/botocore Author: Amazon Web Services Author-email: License: Apache License 2.0 Location: /usr/local/share/virtualenvs/aws/lib/python3.6/site-packages Requires: urllib3, jmespath, python-dateutil Required-by: s3transfer, boto3 ``` ### Configuration ```console (paste below) $ ansible-config dump --only-changed CALLBACKS_ENABLED(/home/peter.hall/ansible/ansible.cfg) = ['profile_tasks'] DEFAULT_HOST_LIST(/home/peter.hall/ansible/ansible.cfg) = ['/home/peter.hall/repos DEFAULT_STDOUT_CALLBACK(/home/peter.hall/ansible/ansible.cfg) = debug DEFAULT_TIMEOUT(/home/peter.hall/ansible/ansible.cfg) = 30 ``` ### OS / Environment CentOS 7 ### Steps to Reproduce <!--- Paste example playbooks or commands between quotes below --> ```yaml (paste below) - name: upload to S3 Glacier community.aws.s3_sync: bucket: home-archive file_root: /home/me/my_archive.tar.gz storage_class: DEEP_ARCHIVE permission: private profile: 2fa region: us-west-2 ``` ### Expected Results file specified by `file_root: /home/me/my_archive.tar.gz` is uploaded ### Actual Results File globbing does not detect any file. ```console (paste below) TASK [ia-home-archive : upload to S3 Glacier] ***************************************************** task path: /home/peter.hall/repositories/do-ansible/roles/ia-home-archive/tasks/main_loop.yml:13 Friday 13 August 2021 15:45:07 -0700 (0:00:01.783) 0:00:10.643 ********* <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: peter.hall <127.0.0.1> EXEC /bin/sh -c 'echo ~peter.hall && sleep 0' <127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/peter.hall/.ansible/tmp `"&& mkdir "` echo /home/peter.hall/.ansible/tmp/ansible-tmp-1628894707.9170668-3601-171520442577912 `" && echo ansible-tmp-1628894707.9170668-3601-171520442577912="` echo /home/peter.hall/.ansible/tmp/ansible-tmp-1628894707.9170668-3601-171520442577912 `" ) && sleep 0' Loading collection amazon.aws from /usr/local/share/virtualenvs/aws/lib/python3.6/site-packages/ansible_collections/amazon/aws Including module_utils file ansible/__init__.py Including module_utils file ansible/module_utils/__init__.py Including module_utils file ansible/module_utils/_text.py Including module_utils file ansible/module_utils/basic.py Including module_utils file ansible/module_utils/common/_collections_compat.py Including module_utils file ansible/module_utils/common/__init__.py Including module_utils file ansible/module_utils/common/_json_compat.py Including module_utils file ansible/module_utils/common/_utils.py Including module_utils file ansible/module_utils/common/arg_spec.py Including module_utils file ansible/module_utils/common/file.py Including module_utils file ansible/module_utils/common/parameters.py Including module_utils file ansible/module_utils/common/collections.py Including module_utils file ansible/module_utils/common/process.py Including module_utils file ansible/module_utils/common/sys_info.py Including module_utils file ansible/module_utils/common/text/converters.py Including module_utils file ansible/module_utils/common/text/__init__.py Including module_utils file ansible/module_utils/common/text/formatters.py Including module_utils file ansible/module_utils/common/validation.py Including module_utils file ansible/module_utils/common/warnings.py Including module_utils file ansible/module_utils/compat/selectors.py Including module_utils file ansible/module_utils/compat/__init__.py Including module_utils file ansible/module_utils/compat/_selectors2.py Including module_utils file ansible/module_utils/compat/selinux.py Including module_utils file ansible/module_utils/distro/__init__.py Including module_utils file ansible/module_utils/distro/_distro.py Including module_utils file ansible/module_utils/errors.py Including module_utils file ansible/module_utils/parsing/convert_bool.py Including module_utils file ansible/module_utils/parsing/__init__.py Including module_utils file ansible/module_utils/pycompat24.py Including module_utils file ansible/module_utils/six/__init__.py Including module_utils file ansible_collections/amazon/aws/plugins/module_utils/core.py Including module_utils file ansible/module_utils/common/dict_transformations.py Including module_utils file ansible_collections/__init__.py Including module_utils file ansible_collections/amazon/__init__.py Including module_utils file ansible_collections/amazon/aws/__init__.py Including module_utils file ansible_collections/amazon/aws/plugins/__init__.py Including module_utils file ansible_collections/amazon/aws/plugins/module_utils/__init__.py Including module_utils file ansible_collections/amazon/aws/plugins/module_utils/ec2.py Including module_utils file ansible/module_utils/ansible_release.py Including module_utils file ansible_collections/amazon/aws/plugins/module_utils/cloud.py Using module file /usr/local/share/virtualenvs/aws/lib/python3.6/site-packages/ansible_collections/community/aws/plugins/modules/s3_sync.py <127.0.0.1> PUT /home/peter.hall/.ansible/tmp/ansible-local-3507r12mon4r/tmpvuqi_l11 TO /home/peter.hall/.ansible/tmp/ansible-tmp-1628894707.9170668-3601-171520442577912/AnsiballZ_s3_sync.py <127.0.0.1> EXEC /bin/sh -c 'chmod u+x /home/peter.hall/.ansible/tmp/ansible-tmp-1628894707.9170668-3601-171520442577912/ /home/peter.hall/.ansible/tmp/ansible-tmp-1628894707.9170668-3601-171520442577912/AnsiballZ_s3_sync.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c '/usr/local/share/virtualenvs/aws/bin/python /home/peter.hall/.ansible/tmp/ansible-tmp-1628894707.9170668-3601-171520442577912/AnsiballZ_s3_sync.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'rm -f -r /home/peter.hall/.ansible/tmp/ansible-tmp-1628894707.9170668-3601-171520442577912/ > /dev/null 2>&1 && sleep 0' ok: [127.0.0.1] => { "changed": false, "filelist_actionable": [], "filelist_initial": [], "filelist_local_etag": [], "filelist_s3": [], "filelist_typed": [], "invocation": { "module_args": { "aws_access_key": null, "aws_ca_bundle": null, "aws_config": null, "aws_secret_key": null, "bucket": "ia-home-archive", "cache_control": "", "debug_botocore_endpoint_logs": false, "delete": false, "ec2_url": null, "exclude": ".*", "file_change_strategy": "date_size", "file_root": "/home/me/my_archive.tar.gz", "include": "*", "key_prefix": "", "mime_map": null, "mode": "push", "permission": "private", "profile": "2fa", "region": "us-west-2", "retries": null, "security_token": null, "storage_class": "DEEP_ARCHIVE", "validate_certs": true } }, "uploads": [] } ``` ### Code of Conduct - [X] I agree to follow the Ansible Code of Conduct
Files identified in the description: * [`plugins/modules/s3_sync.py`](https://github.com/['ansible-collections/amazon.aws', 'ansible-collections/community.aws', 'ansible-collections/community.vmware']/blob/main/plugins/modules/s3_sync.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @jillr @markuman @s-hertel @tremble @wimnat [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> @pthall Thanks for your report. I can confirm this bug/behaviour. According to the documentation, `file_root` must also accept a single file. The issue is, that [it is using `os.walk(file_root)` only, which will return nothing for a single file](https://github.com/ansible-collections/community.aws/blob/main/plugins/modules/s3_sync.py#L325). A fix for that is possibly easy. Just check `os.path.isfile(fileroot)` before and [return the expected object for the single file](https://github.com/ansible-collections/community.aws/blob/main/plugins/modules/s3_sync.py#L351). @pthall do you have some time and energy to provide a PR for this issue?
2021-08-19T05:49:46
ansible-collections/community.aws
780
ansible-collections__community.aws-780
[ "769" ]
bebdd7576e1018e4a198afd7babacdfd96b52fe5
diff --git a/plugins/modules/cloudfront_info.py b/plugins/modules/cloudfront_info.py --- a/plugins/modules/cloudfront_info.py +++ b/plugins/modules/cloudfront_info.py @@ -269,6 +269,7 @@ from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule from ansible_collections.amazon.aws.plugins.module_utils.ec2 import boto3_tag_list_to_ansible_dict +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AWSRetry class CloudFrontServiceManager: @@ -278,64 +279,72 @@ def __init__(self, module): self.module = module try: - self.client = module.client('cloudfront') + self.client = module.client('cloudfront', retry_decorator=AWSRetry.jittered_backoff()) except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: module.fail_json_aws(e, msg='Failed to connect to AWS') def get_distribution(self, distribution_id): try: - func = partial(self.client.get_distribution, Id=distribution_id) - return self.paginated_response(func) + distribution = self.client.get_distribution(aws_retry=True, Id=distribution_id) + return distribution except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: self.module.fail_json_aws(e, msg="Error describing distribution") def get_distribution_config(self, distribution_id): try: - func = partial(self.client.get_distribution_config, Id=distribution_id) - return self.paginated_response(func) + distribution = self.client.get_distribution_config(aws_retry=True, Id=distribution_id) + return distribution except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: self.module.fail_json_aws(e, msg="Error describing distribution configuration") def get_origin_access_identity(self, origin_access_identity_id): try: - func = partial(self.client.get_cloud_front_origin_access_identity, Id=origin_access_identity_id) - return self.paginated_response(func) + origin_access_identity = self.client.get_cloud_front_origin_access_identity(aws_retry=True, Id=origin_access_identity_id) + return origin_access_identity except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: self.module.fail_json_aws(e, msg="Error describing origin access identity") def get_origin_access_identity_config(self, origin_access_identity_id): try: - func = partial(self.client.get_cloud_front_origin_access_identity_config, Id=origin_access_identity_id) - return self.paginated_response(func) + origin_access_identity = self.client.get_cloud_front_origin_access_identity_config(aws_retry=True, Id=origin_access_identity_id) + return origin_access_identity except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: self.module.fail_json_aws(e, msg="Error describing origin access identity configuration") def get_invalidation(self, distribution_id, invalidation_id): try: - func = partial(self.client.get_invalidation, DistributionId=distribution_id, Id=invalidation_id) - return self.paginated_response(func) + invalidation = self.client.get_invalidation(aws_retry=True, DistributionId=distribution_id, Id=invalidation_id) + return invalidation except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: self.module.fail_json_aws(e, msg="Error describing invalidation") def get_streaming_distribution(self, distribution_id): try: - func = partial(self.client.get_streaming_distribution, Id=distribution_id) - return self.paginated_response(func) + streaming_distribution = self.client.get_streaming_distribution(aws_retry=True, Id=distribution_id) + return streaming_distribution except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: self.module.fail_json_aws(e, msg="Error describing streaming distribution") def get_streaming_distribution_config(self, distribution_id): try: - func = partial(self.client.get_streaming_distribution_config, Id=distribution_id) - return self.paginated_response(func) + streaming_distribution = self.client.get_streaming_distribution_config(aws_retry=True, Id=distribution_id) + return streaming_distribution except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: self.module.fail_json_aws(e, msg="Error describing streaming distribution") + # Split out paginator to allow for the backoff decorator to function + @AWSRetry.jittered_backoff() + def _paginated_result(self, paginator_name, **params): + paginator = self.client.get_paginator(paginator_name) + results = paginator.paginate(**params).build_full_result() + return results + def list_origin_access_identities(self): try: - func = partial(self.client.list_cloud_front_origin_access_identities) - origin_access_identity_list = self.paginated_response(func, 'CloudFrontOriginAccessIdentityList') - if origin_access_identity_list['Quantity'] > 0: + results = self._paginated_result('list_cloud_front_origin_access_identities') + origin_access_identity_list = results.get('CloudFrontOriginAccessIdentityList', {'Items': []}) + + if len(origin_access_identity_list['Items']) > 0: return origin_access_identity_list['Items'] return {} except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: @@ -343,12 +352,14 @@ def list_origin_access_identities(self): def list_distributions(self, keyed=True): try: - func = partial(self.client.list_distributions) - distribution_list = self.paginated_response(func, 'DistributionList') - if distribution_list['Quantity'] == 0: - return {} - else: + results = self._paginated_result('list_distributions') + distribution_list = results.get('DistributionList', {'Items': []}) + + if len(distribution_list['Items']) > 0: distribution_list = distribution_list['Items'] + else: + return {} + if not keyed: return distribution_list return self.keyed_list_helper(distribution_list) @@ -357,21 +368,23 @@ def list_distributions(self, keyed=True): def list_distributions_by_web_acl_id(self, web_acl_id): try: - func = partial(self.client.list_distributions_by_web_acl_id, WebAclId=web_acl_id) - distribution_list = self.paginated_response(func, 'DistributionList') - if distribution_list['Quantity'] == 0: - return {} - else: + results = self._paginated_result('list_cloud_front_origin_access_identities', WebAclId=web_acl_id) + distribution_list = results.get('DistributionList', {'Items': []}) + + if len(distribution_list['Items']) > 0: distribution_list = distribution_list['Items'] + else: + return {} return self.keyed_list_helper(distribution_list) except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: self.module.fail_json_aws(e, msg="Error listing distributions by web acl id") def list_invalidations(self, distribution_id): try: - func = partial(self.client.list_invalidations, DistributionId=distribution_id) - invalidation_list = self.paginated_response(func, 'InvalidationList') - if invalidation_list['Quantity'] > 0: + results = self._paginated_result('list_invalidations', DistributionId=distribution_id) + invalidation_list = results.get('InvalidationList', {'Items': []}) + + if len(invalidation_list['Items']) > 0: return invalidation_list['Items'] return {} except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: @@ -379,12 +392,14 @@ def list_invalidations(self, distribution_id): def list_streaming_distributions(self, keyed=True): try: - func = partial(self.client.list_streaming_distributions) - streaming_distribution_list = self.paginated_response(func, 'StreamingDistributionList') - if streaming_distribution_list['Quantity'] == 0: - return {} - else: + results = self._paginated_result('list_streaming_distributions') + streaming_distribution_list = results.get('StreamingDistributionList', {'Items': []}) + + if len(streaming_distribution_list['Items']) > 0: streaming_distribution_list = streaming_distribution_list['Items'] + else: + return {} + if not keyed: return streaming_distribution_list return self.keyed_list_helper(streaming_distribution_list) @@ -484,30 +499,6 @@ def get_aliases_from_distribution_id(self, distribution_id): except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: self.module.fail_json_aws(e, msg="Error getting list of aliases from distribution_id") - def paginated_response(self, func, result_key=""): - ''' - Returns expanded response for paginated operations. - The 'result_key' is used to define the concatenated results that are combined from each paginated response. - ''' - args = dict() - results = dict() - loop = True - while loop: - response = func(**args) - if result_key == "": - result = response - result.pop('ResponseMetadata', None) - else: - result = response.get(result_key) - results.update(result) - args['Marker'] = response.get('NextMarker') - for key in response.keys(): - if key.endswith('List'): - args['Marker'] = response[key].get('NextMarker') - break - loop = args['Marker'] is not None - return results - def keyed_list_helper(self, list_to_key): keyed_list = dict() for item in list_to_key:
[BUG] `self.paginated_response` does not return the aggregated list of distributions (cloudfront_info) ### Summary AWS paginates distributions by default at 100 items per page. Trying the following can cause an error if the distribution appears in the first page of the results: ```yaml - name: "Check if distribution already exists for {{ domainName }}" cloudfront_info: <<: *AWS_CREDENTIALS distribution: true domain_name_alias: "{{ domainName }}" register: distribution_data ``` --- The error lies at the line 502, in the function `paginated_response`: https://github.com/ansible-collections/community.aws/blob/3ae2b3efa4588ac1284c565d6f73543a555a5edd/plugins/modules/cloudfront_info.py#L502 For distributions, AWS returns an object as follows: ```js { "IsTruncated": true, "Items": [{ "ARN": "REDACTED", // ... distribution data }, { "ARN": "REDACTED", // ... distribution data }], "Marker": "", "MaxItems": 100, "NextMarker": "REDACTED_MARKER", "Quantity": 100 } ``` Which means `results.update(result)` on the Nth page overwrites the previous results, causing the returned data to only include the distributions included in the last page -- as the `items` arrays are not concatenated together In my case the 2nd page shows the following object: ```js { "IsTruncated": true, "Items": [{ "ARN": "REDACTED", // ... distribution data }, { "ARN": "REDACTED", // ... distribution data }], "Marker": "REDACTED_MARKER", "MaxItems": 100, "NextMarker": "", "Quantity": 59 } ``` And printing the length of results returned by `service_mgr.get_distribution_id_from_domain_name(domain_name_alias)` yields `59`, which is incorrect, and should be 159 as can be seen from the following screenshot ![image](https://user-images.githubusercontent.com/2607260/137746793-f32242e2-5485-4c54-bf8f-306b49e5647a.png) ### Issue Type Bug Report ### Component Name cloudfront_info ### Ansible Version ![image](https://user-images.githubusercontent.com/2607260/137741051-806d003b-59ca-4cfd-9209-bc8e543e6414.png) ### Collection Versions The bug exists in both - the embedded core of Ansible - the latest revision of `cloudfront_unfo` taken directly from https://github.com/ansible-collections/community.aws/blob/3ae2b3efa4588ac1284c565d6f73543a555a5edd/plugins/modules/cloudfront_info.py (3ae2b3efa4588ac1284c565d6f73543a555a5edd being the latest as of the this writing) ### AWS SDK versions ![image](https://user-images.githubusercontent.com/2607260/137741051-806d003b-59ca-4cfd-9209-bc8e543e6414.png) ### Configuration ```console (paste below) $ ansible-config dump --only-changed ANY_ERRORS_FATAL(~/workspace/ansible/ansible.cfg) = True DEFAULT_STDOUT_CALLBACK(~/workspace/ansible/ansible.cfg) = debug DUPLICATE_YAML_DICT_KEY(~/workspace/ansible/ansible.cfg) = warn HOST_KEY_CHECKING(~/workspace/ansible/ansible.cfg) = False INJECT_FACTS_AS_VARS(~/workspace/ansible/ansible.cfg) = False INTERPRETER_PYTHON(~/workspace/ansible/ansible.cfg) = auto RETRY_FILES_ENABLED(~/workspace/ansible/ansible.cfg) = False TRANSFORM_INVALID_GROUP_CHARS(~/workspace/ansible/ansible.cfg) = never ``` ### OS / Environment Debian 4.19.194-3 (2021-07-18) x86_64 ### Steps to Reproduce <!--- Paste example playbooks or commands between quotes below --> ```yaml (paste below) 1. Have over 100 distributions (or adjust the pagination of distribtions down enough to have multiple pages) 2. Try to fetch the info of a distribution that would appear on the first of multiple pages 3. Lo and behold: "Error unable to source a distribution id from domain_name_alias" ``` Sample fetch: ```yaml - name: "Check if distribution already exists for {{ domainName }}" cloudfront_info: <<: *AWS_CREDENTIALS distribution: true domain_name_alias: "{{ domainName }}" register: distribution_data ``` ### Expected Results **EXPECTATIONS**: - Have the corresponding distribution data fetched disregarding on which page it may be ### Actual Results ```console (paste below) fatal: [REDACTED]: FAILED! => { "changed": false, "invocation": { "module_args": { "all_lists": false, "aws_access_key": "REDACTED", "aws_ca_bundle": null, "aws_config": null, "aws_secret_key": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER", "debug_botocore_endpoint_logs": false, "distribution": true, "distribution_config": false, "distribution_id": null, "domain_name_alias": "REDACTED", "ec2_url": null, "invalidation": false, "invalidation_id": null, "list_distributions": false, "list_distributions_by_web_acl_id": false, "list_invalidations": false, "list_origin_access_identities": false, "list_streaming_distributions": false, "origin_access_identity": false, "origin_access_identity_config": false, "origin_access_identity_id": null, "profile": null, "region": "eu-west-3", "security_token": null, "streaming_distribution": false, "streaming_distribution_config": false, "summary": false, "validate_certs": true } } } MSG: Error unable to source a distribution id from domain_name_alias ``` Thrown by: https://github.com/ansible-collections/community.aws/blob/3ae2b3efa4588ac1284c565d6f73543a555a5edd/plugins/modules/cloudfront_info.py#L607-L611 ### Code of Conduct - [X] I agree to follow the Ansible Code of Conduct
Files identified in the description: * [`plugins/modules/cloudfront_info.py`](https://github.com/['ansible-collections/amazon.aws', 'ansible-collections/community.aws', 'ansible-collections/community.vmware']/blob/main/plugins/modules/cloudfront_info.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @jillr @markuman @s-hertel @tremble @wilvk @wimnat [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> An ugly-yet-simple fix would be: ```python # Only necessary until https://github.com/ansible-collections/community.aws/issues/769 gets fixed def paginated_response(self, func, result_key=""): ''' Returns expanded response for paginated operations. The 'result_key' is used to define the concatenated results that are combined from each paginated response. ''' args = dict() results = dict() items = [] loop = True while loop: response = func(**args) if result_key == "": result = response result.pop('ResponseMetadata', None) else: result = response.get(result_key) results.update(result) if 'Items' in result.keys(): items = items + result.get('Items') results['Items'] = items args['Marker'] = response.get('NextMarker') for key in response.keys(): if key.endswith('List'): args['Marker'] = response[key].get('NextMarker') break loop = args['Marker'] is not None return results ``` Hi @TheOptimisticFactory, There's actually a simpler option: boto3 has paginator helpers (only for some calls) https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cloudfront.html#CloudFront.Paginator.ListDistributions You can see an example of how to use them in #472 : https://github.com/ansible-collections/community.aws/pull/472/files#diff-5b6740d7309875806709fffb540ad4344cf7621a6bcb580e28cdee673a453a95R162 Would you be interested in submitting a Pull Request? Mark While my problem is purely on the distribution listing, it _may_ also occur on any of the calls to `self.paginated_response()` which [covers an array of different AWS functions](https://github.com/ansible-collections/community.aws/blob/3ae2b3efa4588ac1284c565d6f73543a555a5edd/plugins/modules/cloudfront_info.py) 1. `self.client.get_distribution` 2. `self.client.get_distribution_config` 3. `self.client.get_cloud_front_origin_access_identity` 4. `self.client.get_cloud_front_origin_access_identity_config` 5. `self.client.get_invalidation` 6. `self.client.get_streaming_distribution` 7. `self.client.get_streaming_distribution_config` 8. `self.client.list_cloud_front_origin_access_identities` 9. `self.client.list_distributions` 10. `self.client.list_distributions_by_web_acl_id` 11. `self.client.list_invalidations` 12. `self.client.list_streaming_distributions` 13. `self.client.list_distributions_by_web_acl_id` --- The method `get_distribution_id_from_domain_name` itself uses both distributions and streaming distributions (L462-L463) https://github.com/ansible-collections/community.aws/blob/3ae2b3efa4588ac1284c565d6f73543a555a5edd/plugins/modules/cloudfront_info.py#L459-L472 --- Switching to boto3 iterators implies adjusting all the above calls, and I would rather wait for an experienced maintainer to carry out that task safely :)
2021-10-25T12:33:26
ansible-collections/community.aws
790
ansible-collections__community.aws-790
[ "784" ]
91101624f5c21658d1e36d09f4beb474363bf661
diff --git a/plugins/modules/ec2_lc.py b/plugins/modules/ec2_lc.py --- a/plugins/modules/ec2_lc.py +++ b/plugins/modules/ec2_lc.py @@ -107,6 +107,12 @@ description: - The number of IOPS per second to provision for the volume. - Required when I(volume_type=io1). + throughput: + type: int + description: + - The throughput to provision for a gp3 volume. + - Valid Range is a minimum value of 125 and a maximum value of 1000. + version_added: 3.1.0 encrypted: type: bool default: false @@ -478,7 +484,7 @@ def create_block_device_meta(module, volume): if 'no_device' in volume: return_object['NoDevice'] = volume.get('no_device') - if any(key in volume for key in ['snapshot', 'volume_size', 'volume_type', 'delete_on_termination', 'iops', 'encrypted']): + if any(key in volume for key in ['snapshot', 'volume_size', 'volume_type', 'delete_on_termination', 'iops', 'throughput', 'encrypted']): return_object['Ebs'] = {} if 'snapshot' in volume: @@ -496,6 +502,11 @@ def create_block_device_meta(module, volume): if 'iops' in volume: return_object['Ebs']['Iops'] = volume.get('iops') + if 'throughput' in volume: + if volume.get('volume_type') != 'gp3': + module.fail_json(msg='The throughput parameter is supported only for GP3 volumes.') + return_object['Ebs']['Throughput'] = volume.get('throughput') + if 'encrypted' in volume: return_object['Ebs']['Encrypted'] = volume.get('encrypted')
diff --git a/tests/integration/targets/ec2_lc/tasks/main.yml b/tests/integration/targets/ec2_lc/tasks/main.yml --- a/tests/integration/targets/ec2_lc/tasks/main.yml +++ b/tests/integration/targets/ec2_lc/tasks/main.yml @@ -112,6 +112,58 @@ - lc_2_create_idem is not changed - '"autoscaling:CreateLaunchConfiguration" not in lc_2_create_idem.resource_actions' + - name: Create launch configuration 3 - test throughput parameter + vars: + ansible_python_interpreter: "{{ botocore_virtualenv_interpreter }}" + community.aws.ec2_lc: + name: '{{ resource_prefix }}-lc3' + image_id: '{{ ec2_ami_id }}' + instance_type: '{{ ec2_instance_type }}' + volumes: + - device_name: /dev/sda1 + volume_size: 10 + volume_type: gp3 + throughput: 250 + delete_on_termination: true + register: lc_3_create + + - name: Gather information about launch configuration 3 + vars: + ansible_python_interpreter: "{{ botocore_virtualenv_interpreter }}" + community.aws.ec2_lc_info: + name: '{{ resource_prefix }}-lc3' + register: lc_3_info_result + + - assert: + that: + - lc_3_create is changed + - '"throughput" in lc_3_info_result.launch_configurations[0].block_device_mappings[0].ebs' + - lc_3_info_result.launch_configurations[0].block_device_mappings[0].ebs.throughput == 250 + - lc_3_info_result.launch_configurations[0].block_device_mappings[0].ebs.volume_size == 10 + - lc_3_info_result.launch_configurations[0].block_device_mappings[0].ebs.volume_type == 'gp3' + - lc_3_info_result.launch_configurations[0].instance_type == 't2.micro' + - '"autoscaling:CreateLaunchConfiguration" in lc_3_create.resource_actions' + + - name: Create launch configuration 3 - Idempotency + vars: + ansible_python_interpreter: "{{ botocore_virtualenv_interpreter }}" + community.aws.ec2_lc: + name: '{{ resource_prefix }}-lc3' + image_id: '{{ ec2_ami_id }}' + instance_type: '{{ ec2_instance_type }}' + volumes: + - device_name: /dev/sda1 + volume_size: 10 + volume_type: gp3 + throughput: 250 + delete_on_termination: true + register: lc_3_create_idem + + - assert: + that: + - lc_3_create_idem is not changed + - '"autoscaling:CreateLaunchConfiguration" not in lc_3_create_idem.resource_actions' + - name: Search for the Launch Configurations that start with test resource_prefix community.aws.ec2_lc_find: name_regex: '{{ resource_prefix }}*' @@ -120,7 +172,7 @@ - assert: that: - - lc_find_result.results | length == 2 + - lc_find_result.results | length == 3 - '"autoscaling:DescribeLaunchConfigurations" in lc_find_result.resource_actions' - name: Delete launch configuration 1 @@ -187,6 +239,38 @@ - lc_2_info_result is not changed - lc_2_info_result.launch_configurations | length == 0 + - name: Delete launch configuration 3 + community.aws.ec2_lc: + name: '{{ resource_prefix }}-lc3' + state: absent + register: lc_3_delete + + - assert: + that: + - lc_3_delete is changed + - '"autoscaling:DeleteLaunchConfiguration" in lc_3_delete.resource_actions' + + - name: Delete launch configuration 3 - Idempotency + community.aws.ec2_lc: + name: '{{ resource_prefix }}-lc3' + state: absent + register: lc_3_delete_idem + + - assert: + that: + - lc_3_delete_idem is not changed + - '"autoscaling:DeleteLaunchConfiguration" not in lc_3_delete_idem.resource_actions' + + - name: Gather information about launch configuration 3 + community.aws.ec2_lc_info: + name: '{{ resource_prefix }}-lc2' + register: lc_3_info_result + + - assert: + that: + - lc_3_info_result is not changed + - lc_3_info_result.launch_configurations | length == 0 + always: - include_tasks: env_cleanup.yml
add support for gp3 volume throughput setting in ec2_lc ### Summary The ec2_lc module doesn't seem to support the `throughput` parameter for `gp3` volume types. This parameter is supported by `amazon.aws.ec2_vol`. ### Issue Type Feature Idea ### Component Name ec2_lc ### Additional Information <!--- Paste example playbooks or commands between quotes below --> ```yaml (paste below) - name: Create launch configuration community.aws.ec2_lc: name: lc1 image_id: ami-xxxx instance_type: t4g.nano security_groups: "['sg-xxxx']" volumes: - device_name: /dev/sda1 volume_size: 100 volume_type: gp3 throughput: 250 ``` ### Code of Conduct - [X] I agree to follow the Ansible Code of Conduct
Files identified in the description: * [`plugins/modules/ec2_lc.py`](https://github.com/['ansible-collections/amazon.aws', 'ansible-collections/community.aws', 'ansible-collections/community.vmware']/blob/main/plugins/modules/ec2_lc.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @garethr @jillr @markuman @s-hertel @tremble @wilvk [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> good one! I think ec2_launch_template is also missing this option.
2021-11-01T20:18:32
ansible-collections/community.aws
801
ansible-collections__community.aws-801
[ "800" ]
482ab82c0ba2cc6973bfc167bed90f767d550410
diff --git a/plugins/modules/route53.py b/plugins/modules/route53.py --- a/plugins/modules/route53.py +++ b/plugins/modules/route53.py @@ -69,7 +69,6 @@ value: description: - The new value when creating a DNS record. YAML lists or multiple comma-spaced values are allowed for non-alias records. - - When deleting a record all values for the record must be specified or Route 53 will not delete it. type: list elements: str overwrite: @@ -513,8 +512,6 @@ def main(): required_if=( ('state', 'present', ['value']), ('state', 'create', ['value']), - ('state', 'absent', ['value']), - ('state', 'delete', ['value']), ), # failover, region and weight are mutually exclusive mutually_exclusive=[ @@ -607,6 +604,10 @@ def main(): 'HealthCheckId': health_check_in, 'SetIdentifier': identifier_in, }) + if command_in == 'delete' and aws_record is not None: + resource_record_set['TTL'] = aws_record.get('TTL') + if not resource_record_set['ResourceRecords']: + resource_record_set['ResourceRecords'] = aws_record.get('ResourceRecords') if alias_in: resource_record_set['AliasTarget'] = dict(
diff --git a/tests/integration/targets/route53/tasks/main.yml b/tests/integration/targets/route53/tasks/main.yml --- a/tests/integration/targets/route53/tasks/main.yml +++ b/tests/integration/targets/route53/tasks/main.yml @@ -387,6 +387,45 @@ - wc_a_record is not failed - wc_a_record is changed + - name: create a record with different TTL + community.aws.route53: + state: present + zone: '{{ zone_one }}' + record: 'localhost.{{ zone_one }}' + type: A + value: 127.0.0.1 + ttl: 30 + register: ttl30 + - name: check return values + assert: + that: + - ttl30.diff.resource_record_sets[0].ttl == 30 + - ttl30 is changed + + - name: delete previous record without mention ttl and value + community.aws.route53: + state: absent + zone: '{{ zone_one }}' + record: 'localhost.{{ zone_one }}' + type: A + register: ttl30 + - name: check if record is deleted + assert: + that: + - ttl30 is changed + + - name: immutable delete previous record without mention ttl and value + community.aws.route53: + state: absent + zone: '{{ zone_one }}' + record: 'localhost.{{ zone_one }}' + type: A + register: ttl30 + - name: check if record was deleted + assert: + that: + - ttl30 is not changed + # Tests on zone two (private zone) - name: Create A record using zone fqdn route53:
route53 cannot delete A record set ### Summary Cannot delete A record without or with TTL value Providing TTL=null results in > An error occurred (InvalidInput) when calling the ChangeResourceRecordSets operation: Invalid request: Expected exactly one of [AliasTarget, all of [TTL, and ResourceRecords], or TrafficPolicyInstanceId], but found none in Change with [Action=DELETE, Name=<>., Type=A, SetIdentifier=null] When not providing TTL, module uses default of 3600 Providing default ttl result in > An error occurred (InvalidChangeBatch) when calling the ChangeResourceRecordSets operation: [Tried to delete resource record set [name='<>.', type='A'] but the rdata provided is invalid] Relevant blogs: https://blog.ryanhalliday.com/2019/09/route53-aliastarget-invalid-request.html ### Issue Type Bug Report ### Component Name route53 ### Ansible Version ```console $ ansible --version ansible [core 2.11.3] config file = None configured module search path = ['/Users/tiger/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /usr/local/lib/python3.9/site-packages/ansible ansible collection location = /Users/tiger/.ansible/collections:/usr/share/ansible/collections executable location = /usr/local/bin/ansible python version = 3.9.7 (default, Sep 3 2021, 12:37:55) [Clang 12.0.5 (clang-1205.0.22.9)] jinja version = 3.0.1 libyaml = True ``` ### Collection Versions ```console $ ansible-galaxy collection list lections Collection Version ----------------------------- ------- amazon.aws 1.5.0 ansible.netcommon 2.2.0 ansible.posix 1.2.0 ansible.utils 2.3.0 ansible.windows 1.7.0 arista.eos 2.2.0 awx.awx 19.2.2 azure.azcollection 1.7.0 check_point.mgmt 2.0.0 chocolatey.chocolatey 1.1.0 cisco.aci 2.0.0 cisco.asa 2.0.2 cisco.intersight 1.0.15 cisco.ios 2.3.0 cisco.iosxr 2.3.0 cisco.meraki 2.4.2 cisco.mso 1.2.0 cisco.nso 1.0.3 cisco.nxos 2.4.0 cisco.ucs 1.6.0 cloudscale_ch.cloud 2.2.0 community.aws 1.5.0 community.azure 1.0.0 community.crypto 1.7.1 community.digitalocean 1.7.0 community.docker 1.8.0 community.fortios 1.0.0 community.general 3.3.0 community.google 1.0.0 community.grafana 1.2.1 community.hashi_vault 1.3.0 community.hrobot 1.1.1 community.kubernetes 1.2.1 community.kubevirt 1.0.0 community.libvirt 1.0.1 community.mongodb 1.2.1 community.mysql 2.1.0 community.network 3.0.0 community.okd 1.1.2 community.postgresql 1.3.0 community.proxysql 1.0.0 community.rabbitmq 1.0.3 community.routeros 1.2.0 community.skydive 1.0.0 community.sops 1.1.0 community.vmware 1.11.0 community.windows 1.5.0 community.zabbix 1.3.0 containers.podman 1.6.1 cyberark.conjur 1.1.0 cyberark.pas 1.0.7 dellemc.enterprise_sonic 1.1.0 dellemc.openmanage 3.5.0 dellemc.os10 1.1.1 dellemc.os6 1.0.7 dellemc.os9 1.0.4 f5networks.f5_modules 1.10.1 fortinet.fortimanager 2.1.2 fortinet.fortios 2.1.1 frr.frr 1.0.3 gluster.gluster 1.0.1 google.cloud 1.0.2 hetzner.hcloud 1.4.3 hpe.nimble 1.1.3 ibm.qradar 1.0.3 infinidat.infinibox 1.2.4 inspur.sm 1.2.0 junipernetworks.junos 2.3.0 kubernetes.core 1.2.1 mellanox.onyx 1.0.0 netapp.aws 21.2.0 netapp.azure 21.7.0 netapp.cloudmanager 21.7.0 netapp.elementsw 21.6.1 netapp.ontap 21.7.0 netapp.um_info 21.6.0 netapp_eseries.santricity 1.2.13 netbox.netbox 3.1.1 ngine_io.cloudstack 2.1.0 ngine_io.exoscale 1.0.0 ngine_io.vultr 1.1.0 openstack.cloud 1.5.0 openvswitch.openvswitch 2.0.0 ovirt.ovirt 1.5.3 purestorage.flasharray 1.8.0 purestorage.flashblade 1.6.0 sensu.sensu_go 1.11.1 servicenow.servicenow 1.0.6 splunk.es 1.0.2 t_systems_mms.icinga_director 1.18.0 theforeman.foreman 2.1.1 vyos.vyos 2.3.1 wti.remote 1.0.1 ``` ### AWS SDK versions ```console $ pip show boto boto3 botocore Name: boto Version: 2.49.0 Summary: Amazon Web Services Library Home-page: https://github.com/boto/boto/ Author: Mitch Garnaat Author-email: [email protected] License: MIT Location: /usr/local/lib/python3.9/site-packages Requires: Required-by: --- Name: boto3 Version: 1.14.43 Summary: The AWS SDK for Python Home-page: https://github.com/boto/boto3 Author: Amazon Web Services Author-email: UNKNOWN License: Apache License 2.0 Location: /usr/local/lib/python3.9/site-packages Requires: botocore, jmespath, s3transfer Required-by: --- Name: botocore Version: 1.17.43 Summary: Low-level, data-driven core of boto 3. Home-page: https://github.com/boto/botocore Author: Amazon Web Services Author-email: UNKNOWN License: Apache License 2.0 Location: /usr/local/lib/python3.9/site-packages Requires: docutils, jmespath, python-dateutil, urllib3 Required-by: boto3, s3transfer ``` ### Configuration ```console (paste below) $ ansible-config dump --only-changed ``` ### OS / Environment macos ### Steps to Reproduce <!--- Paste example playbooks or commands between quotes below --> ```yaml (paste below) - name: Delete openshift api route53 A record community.aws.route53: state: absent aws_access_key: "{{ aws_access_key_id }}" aws_secret_key: "{{ aws_secret_access_key }}" zone: "{{ guid }}.{{ aws_dns_zone_root }}" record: "{{ records.set.record }}" value: "{{ records.set.value }}" ttl: null type: "{{ records.set.type }}" ``` or leave empty ttl.. results in default ttl 3600 used ```yaml - name: Delete openshift api route53 A record community.aws.route53: state: absent aws_access_key: "{{ aws_access_key_id }}" aws_secret_key: "{{ aws_secret_access_key }}" zone: "{{ guid }}.{{ aws_dns_zone_root }}" record: "{{ records.set.record }}" value: "{{ records.set.value }}" type: "{{ records.set.type }}" ``` ### Expected Results A record is deleted without TTL errors ### Actual Results ttl = null ```console (paste below) The full traceback is: Traceback (most recent call last): File "/var/folders/62/wkysd_4n0w57ljl9ycfsd9cc0000gn/T/ansible_community.aws.route53_payload_c4b6fh52/ansible_community.aws.route53_payload.zip/ansible_collections/community/aws/plugins/modules/route53.py", line 652, in main File "/var/folders/62/wkysd_4n0w57ljl9ycfsd9cc0000gn/T/ansible_community.aws.route53_payload_c4b6fh52/ansible_community.aws.route53_payload.zip/ansible_collections/amazon/aws/plugins/module_utils/core.py", line 288, in deciding_wrapper return retrying_wrapper(*args, **kwargs) File "/var/folders/62/wkysd_4n0w57ljl9ycfsd9cc0000gn/T/ansible_community.aws.route53_payload_c4b6fh52/ansible_community.aws.route53_payload.zip/ansible_collections/amazon/aws/plugins/module_utils/cloud.py", line 154, in retry_func raise e File "/var/folders/62/wkysd_4n0w57ljl9ycfsd9cc0000gn/T/ansible_community.aws.route53_payload_c4b6fh52/ansible_community.aws.route53_payload.zip/ansible_collections/amazon/aws/plugins/module_utils/cloud.py", line 144, in retry_func return f(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/botocore/client.py", line 316, in _api_call return self._make_api_call(operation_name, kwargs) File "/usr/local/lib/python3.9/site-packages/botocore/client.py", line 635, in _make_api_call raise error_class(parsed_response, operation_name) botocore.errorfactory.InvalidInput: An error occurred (InvalidInput) when calling the ChangeResourceRecordSets operation: Invalid request: Expected exactly one of [AliasTarget, all of [TTL, and ResourceRecords], or TrafficPolicyInstanceId], but found none in Change with [Action=DELETE, Name=<>., Type=A, SetIdentifier=null] fatal: [localhost]: FAILED! => { "boto3_version": "1.14.43", "botocore_version": "1.17.43", "changed": false, "error": { "code": "InvalidInput", "message": "Invalid request: Expected exactly one of [AliasTarget, all of [TTL, and ResourceRecords], or TrafficPolicyInstanceId], but found none in Change with [Action=DELETE, Name=<>., Type=A, SetIdentifier=null]", "type": "Sender" }, "invocation": { "module_args": { "alias": null, "alias_evaluate_target_health": false, "alias_hosted_zone_id": null, "aws_access_key": "<>", "aws_ca_bundle": null, "aws_config": null, "aws_secret_key": "<>", "debug_botocore_endpoint_logs": false, "ec2_url": null, "failover": null, "health_check": null, "hosted_zone_id": null, "identifier": null, "overwrite": null, "private_zone": false, "profile": null, "record": "<>.", "region": null, "retry_interval": 500, "security_token": null, "state": "absent", "ttl": null, "type": "A", "validate_certs": true, "value": [ "<>" ], "vpc_id": null, "wait": false, "wait_timeout": 300, "weight": null, "zone": "<>" } }, "msg": "Failed to update records: An error occurred (InvalidInput) when calling the ChangeResourceRecordSets operation: Invalid request: Expected exactly one of [AliasTarget, all of [TTL, and ResourceRecords], or TrafficPolicyInstanceId], but found none in Change with [Action=DELETE, Name=<>., Type=A, SetIdentifier=null]", "response_metadata": { "http_headers": { "connection": "close", "content-length": "507", "content-type": "text/xml", "date": "Fri, 12 Nov 2021 14:41:35 GMT", "x-amzn-requestid": <> }, "http_status_code": 400, "request_id": <>, "retry_attempts": 0 } } ``` ttl left to default ```yaml The full traceback is: Traceback (most recent call last): File "/var/folders/62/wkysd_4n0w57ljl9ycfsd9cc0000gn/T/ansible_community.aws.route53_payload_tvoqyvr_/ansible_community.aws.route53_payload.zip/ansible_collections/community/aws/plugins/modules/route53.py", line 652, in main File "/var/folders/62/wkysd_4n0w57ljl9ycfsd9cc0000gn/T/ansible_community.aws.route53_payload_tvoqyvr_/ansible_community.aws.route53_payload.zip/ansible_collections/amazon/aws/plugins/module_utils/core.py", line 288, in deciding_wrapper return retrying_wrapper(*args, **kwargs) File "/var/folders/62/wkysd_4n0w57ljl9ycfsd9cc0000gn/T/ansible_community.aws.route53_payload_tvoqyvr_/ansible_community.aws.route53_payload.zip/ansible_collections/amazon/aws/plugins/module_utils/cloud.py", line 154, in retry_func raise e File "/var/folders/62/wkysd_4n0w57ljl9ycfsd9cc0000gn/T/ansible_community.aws.route53_payload_tvoqyvr_/ansible_community.aws.route53_payload.zip/ansible_collections/amazon/aws/plugins/module_utils/cloud.py", line 144, in retry_func return f(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/botocore/client.py", line 316, in _api_call return self._make_api_call(operation_name, kwargs) File "/usr/local/lib/python3.9/site-packages/botocore/client.py", line 635, in _make_api_call raise error_class(parsed_response, operation_name) botocore.errorfactory.InvalidChangeBatch: An error occurred (InvalidChangeBatch) when calling the ChangeResourceRecordSets operation: [Tried to delete resource record set [name='<>.', type='A'] but the rdata provided is invalid] fatal: [localhost]: FAILED! => { "boto3_version": "1.14.43", "botocore_version": "1.17.43", "changed": false, "error": { "code": "InvalidChangeBatch", "message": "[Tried to delete resource record set [name='<>.', type='A'] but the rdata provided is invalid]", "type": "Sender" }, "invocation": { "module_args": { "alias": null, "alias_evaluate_target_health": false, "alias_hosted_zone_id": null, "aws_access_key": "<>", "aws_ca_bundle": null, "aws_config": null, "aws_secret_key": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER", "debug_botocore_endpoint_logs": false, "ec2_url": null, "failover": null, "health_check": null, "hosted_zone_id": null, "identifier": null, "overwrite": null, "private_zone": false, "profile": null, "record": "<>.", "region": null, "retry_interval": 500, "security_token": null, "state": "absent", "ttl": 3600, "type": "A", "validate_certs": true, "value": [ "<>." ], "vpc_id": null, "wait": false, "wait_timeout": 300, "weight": null, "zone": "<>" } }, "msg": "Failed to update records: An error occurred (InvalidChangeBatch) when calling the ChangeResourceRecordSets operation: [Tried to delete resource record set [name='<>.', type='A'] but the rdata provided is invalid]", "response_metadata": { "http_headers": { "connection": "close", "content-length": "405", "content-type": "text/xml", "date": "Fri, 12 Nov 2021 14:55:42 GMT", "x-amzn-requestid": "<>" }, "http_status_code": 400, "request_id": "<>", "retry_attempts": 0 } } ``` ### Code of Conduct - [X] I agree to follow the Ansible Code of Conduct
Solution would be to make TTL nullable.. and if null.. don't provide TTL in the request. I can confirm. Basically when deleting records, the name and type are sufficient. Everything else does not matter. That's how `community.dns` is handling it imo. However, just leaving it out makes botocore fail ``` "msg": "Failed to update records: An error occurred (InvalidInput) when calling the ChangeResourceRecordSets operation: Invalid request: Expected exactly one of [AliasTarget, all of [TTL, and ResourceRecords], or TrafficPolicyInstanceId], but found none in Change with [Action=DELETE, Name=ansible.xn--mitlinuxwrdasnichtpassiert-ohc.de., Type=A, SetIdentifier=null]", ``` So we must keep the TTL of the existing record. This is kind of a hotfix. But I need to make some more tests later. ```diff diff --git a/plugins/modules/route53.py b/plugins/modules/route53.py index 9640202..e971e18 100644 --- a/plugins/modules/route53.py +++ b/plugins/modules/route53.py @@ -596,17 +596,29 @@ def main(): aws_record = get_record(route53, zone_id, record_in, type_in, identifier_in) - resource_record_set = scrub_none_parameters({ - 'Name': record_in, - 'Type': type_in, - 'Weight': weight_in, - 'Region': region_in, - 'Failover': failover_in, - 'TTL': ttl_in, - 'ResourceRecords': [dict(Value=value) for value in value_in], - 'HealthCheckId': health_check_in, - 'SetIdentifier': identifier_in, - }) + if command_in is not 'delete': + resource_record_set = scrub_none_parameters({ + 'Name': record_in, + 'Type': type_in, + 'Weight': weight_in, + 'Region': region_in, + 'Failover': failover_in, + 'TTL': ttl_in, + 'ResourceRecords': [dict(Value=value) for value in value_in], + 'HealthCheckId': health_check_in, + 'SetIdentifier': identifier_in, + }) + else: + resource_record_set = scrub_none_parameters({ + 'Name': record_in, + 'Type': type_in, + 'Weight': weight_in, + 'Region': region_in, + 'Failover': failover_in, + 'ResourceRecords': [dict(Value=value) for value in value_in], + 'HealthCheckId': health_check_in, + 'TTL': aws_record.get('TTL') + }) if alias_in: resource_record_set['AliasTarget'] = dict( ```
2021-11-12T16:31:50
ansible-collections/community.aws
818
ansible-collections__community.aws-818
[ "817" ]
68aaa7057be46a3ab36f572fd0013d64653af909
diff --git a/plugins/modules/aws_eks_cluster.py b/plugins/modules/aws_eks_cluster.py --- a/plugins/modules/aws_eks_cluster.py +++ b/plugins/modules/aws_eks_cluster.py @@ -204,7 +204,7 @@ def ensure_present(client, module): resourcesVpcConfig=dict( subnetIds=subnets, securityGroupIds=groups), - clientRequestToken='ansible-create-%s' % name) + ) if module.params['version']: params['version'] = module.params['version'] cluster = client.create_cluster(**params)['cluster']
diff --git a/tests/integration/targets/aws_eks_cluster/defaults/main.yml b/tests/integration/targets/aws_eks_cluster/defaults/main.yml --- a/tests/integration/targets/aws_eks_cluster/defaults/main.yml +++ b/tests/integration/targets/aws_eks_cluster/defaults/main.yml @@ -1,4 +1,5 @@ eks_cluster_name: "{{ resource_prefix }}" +eks_cluster_short_name: "{{ lookup('password', '/dev/null chars=ascii_lowercase length=5') }}" eks_subnets: - zone: a cidr: 10.0.1.0/24 diff --git a/tests/integration/targets/aws_eks_cluster/tasks/full_test.yml b/tests/integration/targets/aws_eks_cluster/tasks/full_test.yml --- a/tests/integration/targets/aws_eks_cluster/tasks/full_test.yml +++ b/tests/integration/targets/aws_eks_cluster/tasks/full_test.yml @@ -77,8 +77,8 @@ - name: create EKS cluster aws_eks_cluster: name: "{{ eks_cluster_name }}" - security_groups: "{{ eks_security_groups | community.general.json_query('[].name') }}" - subnets: "{{ setup_subnets.results | community.general.json_query('[].subnet.id') }}" + security_groups: "{{ eks_security_groups | map(attribute='name') }}" + subnets: "{{ setup_subnets.results | map(attribute='subnet.id') }}" role_arn: "{{ iam_role.arn }}" register: eks_create @@ -91,8 +91,8 @@ - name: create EKS cluster with same details but wait for it to become active aws_eks_cluster: name: "{{ eks_cluster_name }}" - security_groups: "{{ eks_security_groups | community.general.json_query('[].name') }}" - subnets: "{{ setup_subnets.results | community.general.json_query('[].subnet.id') }}" + security_groups: "{{ eks_security_groups | map(attribute='name') }}" + subnets: "{{ setup_subnets.results | map(attribute='subnet.id') }}" role_arn: "{{ iam_role.arn }}" wait: yes register: eks_create @@ -111,8 +111,8 @@ - name: create EKS cluster with same details but using SG ids aws_eks_cluster: name: "{{ eks_cluster_name }}" - security_groups: "{{ setup_security_groups.results | community.general.json_query('[].group_id') }}" - subnets: "{{ setup_subnets.results | community.general.json_query('[].subnet.id') }}" + security_groups: "{{ setup_security_groups.results | map(attribute='group_id') }}" + subnets: "{{ setup_subnets.results | map(attribute='subnet.id') }}" role_arn: "{{ iam_role.arn }}" register: eks_create @@ -137,8 +137,8 @@ - name: create EKS cluster with same details but wait for it to become active aws_eks_cluster: name: "{{ eks_cluster_name }}" - security_groups: "{{ eks_security_groups | community.general.json_query('[].name') }}" - subnets: "{{ setup_subnets.results | community.general.json_query('[].subnet.id') }}" + security_groups: "{{ eks_security_groups | map(attribute='name') }}" + subnets: "{{ setup_subnets.results | map(attribute='subnet.id') }}" role_arn: "{{ iam_role.arn }}" wait: yes register: eks_create @@ -160,6 +160,28 @@ that: - eks_delete is changed + - name: create EKS cluster with short name + aws_eks_cluster: + name: "{{ eks_cluster_short_name }}" + security_groups: "{{ eks_security_groups | map(attribute='name') }}" + subnets: "{{ setup_subnets.results | map(attribute='subnet.id') }}" + role_arn: "{{ iam_role.arn }}" + register: eks_create + + - name: check that EKS cluster was created with short name + assert: + that: + - eks_create is changed + - eks_create.name == eks_cluster_short_name + - eks_create is not failed + + - name: remove EKS cluster with short name + aws_eks_cluster: + name: "{{ eks_cluster_short_name }}" + state: absent + wait: yes + register: eks_delete + always: - name: Announce teardown start debug: @@ -173,6 +195,14 @@ register: eks_delete ignore_errors: yes + - name: remove EKS cluster + aws_eks_cluster: + name: "{{ eks_cluster_short_name }}" + state: absent + wait: yes + register: eks_delete + ignore_errors: yes + - debug: msg: "{{ eks_security_groups|reverse|list }}"
The EKS cluster security token must be between 33 and 126 characters long...forcing the length of "name" parameter for aws_eks_cluster module to succeed. ### Summary When leveraging a role that uses the aws_eks_cluster module, I encountered a repeated error about security token length. The issue was 'resolved' when I passed in a very long "name" parameter. ### Issue Type Bug Report ### Component Name aws_eks_cluster ### Ansible Version ```console (paste below) $ ansible --version ansible [core 2.11.4] config file = None configured module search path = ['/Users/jdelapor/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /Library/Python/3.8/site-packages/ansible ansible collection location = /Users/jdelapor/.ansible/collections:/usr/share/ansible/collections executable location = /usr/local/bin/ansible python version = 3.8.2 (default, Dec 21 2020, 15:06:04) [Clang 12.0.0 (clang-1200.0.32.29)] jinja version = 3.0.1 libyaml = True ``` ### Collection Versions ```console (paste below) $ ansible-galaxy collection list # /Library/Python/3.8/site-packages/ansible_collections Collection Version ----------------------------- ------- amazon.aws 1.5.0 ansible.netcommon 2.3.0 ansible.posix 1.2.0 ansible.utils 2.3.1 ansible.windows 1.7.2 arista.eos 2.2.0 awx.awx 19.2.2 azure.azcollection 1.8.0 check_point.mgmt 2.0.0 chocolatey.chocolatey 1.1.0 cisco.aci 2.0.0 cisco.asa 2.0.2 cisco.intersight 1.0.16 cisco.ios 2.3.1 cisco.iosxr 2.4.0 cisco.meraki 2.4.2 cisco.mso 1.2.0 cisco.nso 1.0.3 cisco.nxos 2.5.0 cisco.ucs 1.6.0 cloudscale_ch.cloud 2.2.0 community.aws 1.5.0 community.azure 1.0.0 community.crypto 1.8.0 community.digitalocean 1.8.0 community.docker 1.9.0 community.fortios 1.0.0 community.general 3.5.0 community.google 1.0.0 community.grafana 1.2.1 community.hashi_vault 1.3.2 community.hrobot 1.1.1 community.kubernetes 1.2.1 community.kubevirt 1.0.0 community.libvirt 1.0.2 community.mongodb 1.3.0 community.mysql 2.1.0 community.network 3.0.0 community.okd 1.1.2 community.postgresql 1.4.0 community.proxysql 1.1.0 community.rabbitmq 1.1.0 community.routeros 1.2.0 community.skydive 1.0.0 community.sops 1.1.0 community.vmware 1.12.0 community.windows 1.6.0 community.zabbix 1.4.0 containers.podman 1.6.2 cyberark.conjur 1.1.0 cyberark.pas 1.0.7 dellemc.enterprise_sonic 1.1.0 dellemc.openmanage 3.6.0 dellemc.os10 1.1.1 dellemc.os6 1.0.7 dellemc.os9 1.0.4 f5networks.f5_modules 1.11.0 fortinet.fortimanager 2.1.3 fortinet.fortios 2.1.2 frr.frr 1.0.3 gluster.gluster 1.0.1 google.cloud 1.0.2 hetzner.hcloud 1.4.4 hpe.nimble 1.1.3 ibm.qradar 1.0.3 infinidat.infinibox 1.2.4 inspur.sm 1.2.0 junipernetworks.junos 2.4.0 kubernetes.core 1.2.1 mellanox.onyx 1.0.0 netapp.aws 21.6.0 netapp.azure 21.8.1 netapp.cloudmanager 21.9.0 netapp.elementsw 21.6.1 netapp.ontap 21.9.0 netapp.um_info 21.7.0 netapp_eseries.santricity 1.2.13 netbox.netbox 3.1.1 ngine_io.cloudstack 2.1.0 ngine_io.exoscale 1.0.0 ngine_io.vultr 1.1.0 openstack.cloud 1.5.0 openvswitch.openvswitch 2.0.0 ovirt.ovirt 1.5.4 purestorage.flasharray 1.10.0 purestorage.flashblade 1.6.0 sensu.sensu_go 1.11.1 servicenow.servicenow 1.0.6 splunk.es 1.0.2 t_systems_mms.icinga_director 1.20.0 theforeman.foreman 2.1.2 vyos.vyos 2.5.0 wti.remote 1.0.1 # /Users/jdelapor/.ansible/collections/ansible_collections Collection Version ------------------ ------- amazon.aws 1.5.0 azure.azcollection 1.8.0 community.aws 1.5.0 google.cloud 1.0.2 kubernetes.core 2.1.1 ``` ### AWS SDK versions ```console (paste below) $ pip show boto boto3 botocore Name: boto Version: 2.49.0 Summary: Amazon Web Services Library Home-page: https://github.com/boto/boto/ Author: Mitch Garnaat Author-email: [email protected] License: MIT Location: /Users/jdelapor/Library/Python/3.8/lib/python/site-packages Requires: Required-by: --- Name: boto3 Version: 1.20.17 Summary: The AWS SDK for Python Home-page: https://github.com/boto/boto3 Author: Amazon Web Services Author-email: License: Apache License 2.0 Location: /Users/jdelapor/Library/Python/3.8/lib/python/site-packages Requires: s3transfer, jmespath, botocore Required-by: --- Name: botocore Version: 1.23.17 Summary: Low-level, data-driven core of boto 3. Home-page: https://github.com/boto/botocore Author: Amazon Web Services Author-email: License: Apache License 2.0 Location: /Users/jdelapor/Library/Python/3.8/lib/python/site-packages Requires: jmespath, python-dateutil, urllib3 Required-by: s3transfer, boto3, awscli ``` ### Configuration ```console (paste below) $ ansible-config dump --only-changed null ``` ### OS / Environment EKS ### Steps to Reproduce <!--- Paste example playbooks or commands between quotes below --> Running the playbook from https://github.com/nleiva/ansible-kubernetes, it fails at this task if I use a short cluster name: ```yaml (paste below) - name: Create EKS cluster community.aws.aws_eks_cluster: name: "{{ cluster_name }}" version: "{{ k8s_version }}" role_arn: "{{ eks_role.arn }}" wait: true wait_timeout: "{{ eks_timeout }}" region: "{{ aws_region }}" subnets: - "{{ create_subnet_1.subnet.id }}" - "{{ create_subnet_2.subnet.id }}" security_groups: "{{ ec2_resource_prefix }}-SG" register: create_eks ``` It fails when I use this command to run the playbook: ```console ansible-playbook main.yml -vvv --extra-vars "cloud_provider=aws my_resource_prefix=jdelaportek8s my_cluster_name=jdelaportek81" ``` It succeeds when I run the playbook with this command: ```console ansible-playbook main.yml -vvv --extra-vars "cloud_provider=aws my_resource_prefix=jdelaportek8s my_cluster_name=jdelaportek81isthislongenoughforyouyetbotocore" ``` ### Expected Results I expected a cluster to be created based on any nominally normal cluster name length. There is no length restriction mentioned in the aws_eks_cluster module. The examples show a 10-char name length, which would be too short to succeed. ### Actual Results Using the aws eks role located here: https://github.com/nleiva/ansible-kubernetes ```console (paste below) ansible-playbook main.yml -v --extra-vars "cloud_provider=aws my_resource_prefix=jdelaportek8s my_cluster_name=jdelaportek81" ---- truncated ---- TASK [aws_create_eks : Provision EKS Cluster tasks] ********************************************************************************************************************************************** included: /Users/jdelapor/gitstuff/ansible-kubernetes/roles/aws_create_eks/tasks/create_eks.yml for localhost TASK [aws_create_eks : Create EKS cluster] ******************************************************************************************************************************************************* An exception occurred during task execution. To see the full traceback, use -vvv. The error was: botocore.errorfactory.InvalidParameterException: An error occurred (InvalidParameterException) when calling the CreateCluster operation: The client request token parameter must be between 33 and 126 characters. fatal: [localhost]: FAILED! => { "boto3_version": "1.20.17", "botocore_version": "1.23.17", "changed": false, "error": { "code": "InvalidParameterException", "message": "The client request token parameter must be between 33 and 126 characters." }, "message": "The client request token parameter must be between 33 and 126 characters.", "response_metadata": { "http_headers": { "access-control-allow-headers": ",Authorization,Date,X-Amz-Date,X-Amz-Security-Token,X-Amz-Target,content-type,x-amz-content-sha256,x-amz-user-agent,x-amzn-platform-id,x-amzn-trace-id", "access-control-allow-methods": "GET,HEAD,PUT,POST,DELETE,OPTIONS", "access-control-allow-origin": "", "access-control-expose-headers": "x-amzn-errortype,x-amzn-errormessage,x-amzn-trace-id,x-amzn-requestid,x-amz-apigw-id,date", "connection": "keep-alive", "content-length": "196", "content-type": "application/json", "date": "Wed, 01 Dec 2021 22:55:01 GMT", "x-amz-apigw-id": "JsSC1EIDIAMFT-g=", "x-amzn-errortype": "InvalidParameterException", "x-amzn-requestid": "d6ee553b-0e0f-4b68-81ff-e1c434fde032", "x-amzn-trace-id": "Root=1-61a7fd45-71e15c9a2fab959d278d1075" }, "http_status_code": 400, "request_id": "d6ee553b-0e0f-4b68-81ff-e1c434fde032", "retry_attempts": 0 } } MSG: Couldn't create cluster my-cluster: An error occurred (InvalidParameterException) when calling the CreateCluster operation: The client request token parameter must be between 33 and 126 characters. PLAY RECAP *************************************************************************************************************************************************************************************** localhost : ok=27 changed=12 unreachable=0 failed=1 skipped=7 rescued=0 ignored=0 ``` ### Code of Conduct - [X] I agree to follow the Ansible Code of Conduct
I can confirm this. In your scenario only 5 characters are missing: ```yml --- - hosts: localhost connection: local tasks: - name: Create EKS cluster community.aws.aws_eks_cluster: name: jdelaportek8112345 version: 1.21 role_arn: myEKSClusterRole wait: true region: eu-central-1 subnets: - subnet-d8309db2 - subnet-943ad4d8 security_groups: - sg-f32f0196 register: create_eks ``` This is the bug: https://github.com/ansible-collections/community.aws/blob/main/plugins/modules/aws_eks_cluster.py#L207 > clientRequestToken (string) -- > Unique, case-sensitive identifier you provide to ensure the idempotency of the request. > This field is autopopulated if not provided. This token must be between 33 and 126 characters ... We can remove it to see if our integration tests still pass
2021-12-02T17:37:37
ansible-collections/community.aws
847
ansible-collections__community.aws-847
[ "817" ]
f89696e4ff8bad6250adf5896c260ae2f3d1eb0f
diff --git a/plugins/modules/aws_eks_cluster.py b/plugins/modules/aws_eks_cluster.py --- a/plugins/modules/aws_eks_cluster.py +++ b/plugins/modules/aws_eks_cluster.py @@ -204,7 +204,7 @@ def ensure_present(client, module): resourcesVpcConfig=dict( subnetIds=subnets, securityGroupIds=groups), - clientRequestToken='ansible-create-%s' % name) + ) if module.params['version']: params['version'] = module.params['version'] cluster = client.create_cluster(**params)['cluster']
diff --git a/tests/integration/targets/aws_eks_cluster/defaults/main.yml b/tests/integration/targets/aws_eks_cluster/defaults/main.yml --- a/tests/integration/targets/aws_eks_cluster/defaults/main.yml +++ b/tests/integration/targets/aws_eks_cluster/defaults/main.yml @@ -1,4 +1,5 @@ eks_cluster_name: "{{ resource_prefix }}" +eks_cluster_short_name: "{{ lookup('password', '/dev/null chars=ascii_lowercase length=5') }}" eks_subnets: - zone: a cidr: 10.0.1.0/24 diff --git a/tests/integration/targets/aws_eks_cluster/tasks/full_test.yml b/tests/integration/targets/aws_eks_cluster/tasks/full_test.yml --- a/tests/integration/targets/aws_eks_cluster/tasks/full_test.yml +++ b/tests/integration/targets/aws_eks_cluster/tasks/full_test.yml @@ -77,8 +77,8 @@ - name: create EKS cluster aws_eks_cluster: name: "{{ eks_cluster_name }}" - security_groups: "{{ eks_security_groups | community.general.json_query('[].name') }}" - subnets: "{{ setup_subnets.results | community.general.json_query('[].subnet.id') }}" + security_groups: "{{ eks_security_groups | map(attribute='name') }}" + subnets: "{{ setup_subnets.results | map(attribute='subnet.id') }}" role_arn: "{{ iam_role.arn }}" register: eks_create @@ -91,8 +91,8 @@ - name: create EKS cluster with same details but wait for it to become active aws_eks_cluster: name: "{{ eks_cluster_name }}" - security_groups: "{{ eks_security_groups | community.general.json_query('[].name') }}" - subnets: "{{ setup_subnets.results | community.general.json_query('[].subnet.id') }}" + security_groups: "{{ eks_security_groups | map(attribute='name') }}" + subnets: "{{ setup_subnets.results | map(attribute='subnet.id') }}" role_arn: "{{ iam_role.arn }}" wait: yes register: eks_create @@ -111,8 +111,8 @@ - name: create EKS cluster with same details but using SG ids aws_eks_cluster: name: "{{ eks_cluster_name }}" - security_groups: "{{ setup_security_groups.results | community.general.json_query('[].group_id') }}" - subnets: "{{ setup_subnets.results | community.general.json_query('[].subnet.id') }}" + security_groups: "{{ setup_security_groups.results | map(attribute='group_id') }}" + subnets: "{{ setup_subnets.results | map(attribute='subnet.id') }}" role_arn: "{{ iam_role.arn }}" register: eks_create @@ -137,8 +137,8 @@ - name: create EKS cluster with same details but wait for it to become active aws_eks_cluster: name: "{{ eks_cluster_name }}" - security_groups: "{{ eks_security_groups | community.general.json_query('[].name') }}" - subnets: "{{ setup_subnets.results | community.general.json_query('[].subnet.id') }}" + security_groups: "{{ eks_security_groups | map(attribute='name') }}" + subnets: "{{ setup_subnets.results | map(attribute='subnet.id') }}" role_arn: "{{ iam_role.arn }}" wait: yes register: eks_create @@ -160,6 +160,28 @@ that: - eks_delete is changed + - name: create EKS cluster with short name + aws_eks_cluster: + name: "{{ eks_cluster_short_name }}" + security_groups: "{{ eks_security_groups | map(attribute='name') }}" + subnets: "{{ setup_subnets.results | map(attribute='subnet.id') }}" + role_arn: "{{ iam_role.arn }}" + register: eks_create + + - name: check that EKS cluster was created with short name + assert: + that: + - eks_create is changed + - eks_create.name == eks_cluster_short_name + - eks_create is not failed + + - name: remove EKS cluster with short name + aws_eks_cluster: + name: "{{ eks_cluster_short_name }}" + state: absent + wait: yes + register: eks_delete + always: - name: Announce teardown start debug: @@ -173,6 +195,14 @@ register: eks_delete ignore_errors: yes + - name: remove EKS cluster + aws_eks_cluster: + name: "{{ eks_cluster_short_name }}" + state: absent + wait: yes + register: eks_delete + ignore_errors: yes + - debug: msg: "{{ eks_security_groups|reverse|list }}"
The EKS cluster security token must be between 33 and 126 characters long...forcing the length of "name" parameter for aws_eks_cluster module to succeed. ### Summary When leveraging a role that uses the aws_eks_cluster module, I encountered a repeated error about security token length. The issue was 'resolved' when I passed in a very long "name" parameter. ### Issue Type Bug Report ### Component Name aws_eks_cluster ### Ansible Version ```console (paste below) $ ansible --version ansible [core 2.11.4] config file = None configured module search path = ['/Users/jdelapor/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /Library/Python/3.8/site-packages/ansible ansible collection location = /Users/jdelapor/.ansible/collections:/usr/share/ansible/collections executable location = /usr/local/bin/ansible python version = 3.8.2 (default, Dec 21 2020, 15:06:04) [Clang 12.0.0 (clang-1200.0.32.29)] jinja version = 3.0.1 libyaml = True ``` ### Collection Versions ```console (paste below) $ ansible-galaxy collection list # /Library/Python/3.8/site-packages/ansible_collections Collection Version ----------------------------- ------- amazon.aws 1.5.0 ansible.netcommon 2.3.0 ansible.posix 1.2.0 ansible.utils 2.3.1 ansible.windows 1.7.2 arista.eos 2.2.0 awx.awx 19.2.2 azure.azcollection 1.8.0 check_point.mgmt 2.0.0 chocolatey.chocolatey 1.1.0 cisco.aci 2.0.0 cisco.asa 2.0.2 cisco.intersight 1.0.16 cisco.ios 2.3.1 cisco.iosxr 2.4.0 cisco.meraki 2.4.2 cisco.mso 1.2.0 cisco.nso 1.0.3 cisco.nxos 2.5.0 cisco.ucs 1.6.0 cloudscale_ch.cloud 2.2.0 community.aws 1.5.0 community.azure 1.0.0 community.crypto 1.8.0 community.digitalocean 1.8.0 community.docker 1.9.0 community.fortios 1.0.0 community.general 3.5.0 community.google 1.0.0 community.grafana 1.2.1 community.hashi_vault 1.3.2 community.hrobot 1.1.1 community.kubernetes 1.2.1 community.kubevirt 1.0.0 community.libvirt 1.0.2 community.mongodb 1.3.0 community.mysql 2.1.0 community.network 3.0.0 community.okd 1.1.2 community.postgresql 1.4.0 community.proxysql 1.1.0 community.rabbitmq 1.1.0 community.routeros 1.2.0 community.skydive 1.0.0 community.sops 1.1.0 community.vmware 1.12.0 community.windows 1.6.0 community.zabbix 1.4.0 containers.podman 1.6.2 cyberark.conjur 1.1.0 cyberark.pas 1.0.7 dellemc.enterprise_sonic 1.1.0 dellemc.openmanage 3.6.0 dellemc.os10 1.1.1 dellemc.os6 1.0.7 dellemc.os9 1.0.4 f5networks.f5_modules 1.11.0 fortinet.fortimanager 2.1.3 fortinet.fortios 2.1.2 frr.frr 1.0.3 gluster.gluster 1.0.1 google.cloud 1.0.2 hetzner.hcloud 1.4.4 hpe.nimble 1.1.3 ibm.qradar 1.0.3 infinidat.infinibox 1.2.4 inspur.sm 1.2.0 junipernetworks.junos 2.4.0 kubernetes.core 1.2.1 mellanox.onyx 1.0.0 netapp.aws 21.6.0 netapp.azure 21.8.1 netapp.cloudmanager 21.9.0 netapp.elementsw 21.6.1 netapp.ontap 21.9.0 netapp.um_info 21.7.0 netapp_eseries.santricity 1.2.13 netbox.netbox 3.1.1 ngine_io.cloudstack 2.1.0 ngine_io.exoscale 1.0.0 ngine_io.vultr 1.1.0 openstack.cloud 1.5.0 openvswitch.openvswitch 2.0.0 ovirt.ovirt 1.5.4 purestorage.flasharray 1.10.0 purestorage.flashblade 1.6.0 sensu.sensu_go 1.11.1 servicenow.servicenow 1.0.6 splunk.es 1.0.2 t_systems_mms.icinga_director 1.20.0 theforeman.foreman 2.1.2 vyos.vyos 2.5.0 wti.remote 1.0.1 # /Users/jdelapor/.ansible/collections/ansible_collections Collection Version ------------------ ------- amazon.aws 1.5.0 azure.azcollection 1.8.0 community.aws 1.5.0 google.cloud 1.0.2 kubernetes.core 2.1.1 ``` ### AWS SDK versions ```console (paste below) $ pip show boto boto3 botocore Name: boto Version: 2.49.0 Summary: Amazon Web Services Library Home-page: https://github.com/boto/boto/ Author: Mitch Garnaat Author-email: [email protected] License: MIT Location: /Users/jdelapor/Library/Python/3.8/lib/python/site-packages Requires: Required-by: --- Name: boto3 Version: 1.20.17 Summary: The AWS SDK for Python Home-page: https://github.com/boto/boto3 Author: Amazon Web Services Author-email: License: Apache License 2.0 Location: /Users/jdelapor/Library/Python/3.8/lib/python/site-packages Requires: s3transfer, jmespath, botocore Required-by: --- Name: botocore Version: 1.23.17 Summary: Low-level, data-driven core of boto 3. Home-page: https://github.com/boto/botocore Author: Amazon Web Services Author-email: License: Apache License 2.0 Location: /Users/jdelapor/Library/Python/3.8/lib/python/site-packages Requires: jmespath, python-dateutil, urllib3 Required-by: s3transfer, boto3, awscli ``` ### Configuration ```console (paste below) $ ansible-config dump --only-changed null ``` ### OS / Environment EKS ### Steps to Reproduce <!--- Paste example playbooks or commands between quotes below --> Running the playbook from https://github.com/nleiva/ansible-kubernetes, it fails at this task if I use a short cluster name: ```yaml (paste below) - name: Create EKS cluster community.aws.aws_eks_cluster: name: "{{ cluster_name }}" version: "{{ k8s_version }}" role_arn: "{{ eks_role.arn }}" wait: true wait_timeout: "{{ eks_timeout }}" region: "{{ aws_region }}" subnets: - "{{ create_subnet_1.subnet.id }}" - "{{ create_subnet_2.subnet.id }}" security_groups: "{{ ec2_resource_prefix }}-SG" register: create_eks ``` It fails when I use this command to run the playbook: ```console ansible-playbook main.yml -vvv --extra-vars "cloud_provider=aws my_resource_prefix=jdelaportek8s my_cluster_name=jdelaportek81" ``` It succeeds when I run the playbook with this command: ```console ansible-playbook main.yml -vvv --extra-vars "cloud_provider=aws my_resource_prefix=jdelaportek8s my_cluster_name=jdelaportek81isthislongenoughforyouyetbotocore" ``` ### Expected Results I expected a cluster to be created based on any nominally normal cluster name length. There is no length restriction mentioned in the aws_eks_cluster module. The examples show a 10-char name length, which would be too short to succeed. ### Actual Results Using the aws eks role located here: https://github.com/nleiva/ansible-kubernetes ```console (paste below) ansible-playbook main.yml -v --extra-vars "cloud_provider=aws my_resource_prefix=jdelaportek8s my_cluster_name=jdelaportek81" ---- truncated ---- TASK [aws_create_eks : Provision EKS Cluster tasks] ********************************************************************************************************************************************** included: /Users/jdelapor/gitstuff/ansible-kubernetes/roles/aws_create_eks/tasks/create_eks.yml for localhost TASK [aws_create_eks : Create EKS cluster] ******************************************************************************************************************************************************* An exception occurred during task execution. To see the full traceback, use -vvv. The error was: botocore.errorfactory.InvalidParameterException: An error occurred (InvalidParameterException) when calling the CreateCluster operation: The client request token parameter must be between 33 and 126 characters. fatal: [localhost]: FAILED! => { "boto3_version": "1.20.17", "botocore_version": "1.23.17", "changed": false, "error": { "code": "InvalidParameterException", "message": "The client request token parameter must be between 33 and 126 characters." }, "message": "The client request token parameter must be between 33 and 126 characters.", "response_metadata": { "http_headers": { "access-control-allow-headers": ",Authorization,Date,X-Amz-Date,X-Amz-Security-Token,X-Amz-Target,content-type,x-amz-content-sha256,x-amz-user-agent,x-amzn-platform-id,x-amzn-trace-id", "access-control-allow-methods": "GET,HEAD,PUT,POST,DELETE,OPTIONS", "access-control-allow-origin": "", "access-control-expose-headers": "x-amzn-errortype,x-amzn-errormessage,x-amzn-trace-id,x-amzn-requestid,x-amz-apigw-id,date", "connection": "keep-alive", "content-length": "196", "content-type": "application/json", "date": "Wed, 01 Dec 2021 22:55:01 GMT", "x-amz-apigw-id": "JsSC1EIDIAMFT-g=", "x-amzn-errortype": "InvalidParameterException", "x-amzn-requestid": "d6ee553b-0e0f-4b68-81ff-e1c434fde032", "x-amzn-trace-id": "Root=1-61a7fd45-71e15c9a2fab959d278d1075" }, "http_status_code": 400, "request_id": "d6ee553b-0e0f-4b68-81ff-e1c434fde032", "retry_attempts": 0 } } MSG: Couldn't create cluster my-cluster: An error occurred (InvalidParameterException) when calling the CreateCluster operation: The client request token parameter must be between 33 and 126 characters. PLAY RECAP *************************************************************************************************************************************************************************************** localhost : ok=27 changed=12 unreachable=0 failed=1 skipped=7 rescued=0 ignored=0 ``` ### Code of Conduct - [X] I agree to follow the Ansible Code of Conduct
I can confirm this. In your scenario only 5 characters are missing: ```yml --- - hosts: localhost connection: local tasks: - name: Create EKS cluster community.aws.aws_eks_cluster: name: jdelaportek8112345 version: 1.21 role_arn: myEKSClusterRole wait: true region: eu-central-1 subnets: - subnet-d8309db2 - subnet-943ad4d8 security_groups: - sg-f32f0196 register: create_eks ``` This is the bug: https://github.com/ansible-collections/community.aws/blob/main/plugins/modules/aws_eks_cluster.py#L207 > clientRequestToken (string) -- > Unique, case-sensitive identifier you provide to ensure the idempotency of the request. > This field is autopopulated if not provided. This token must be between 33 and 126 characters ... We can remove it to see if our integration tests still pass I also experienced the same behavior. Could we do something like this? ```python clientRequestToken='ansible-create-something-very-long-just-because-%s' % name) ``` > I also experienced the same behavior. Could we do something like this? > > ```python > clientRequestToken='ansible-create-something-very-long-just-because-%s' % name) > ``` I bet one day someone will come with a name that is longer as 126 characters :) I guess the `clientRequestToken` is not necessary. Integration test pass without it. I will append it with a short name. > I bet one day someone will come with a name that is longer as 126 characters :) > > I guess the `clientRequestToken` is not necessary. Integration test pass without it. I will append it with a short name. That's true. I don't have much context of where this token comes from or what it's for, but if it's not required and it's safe to remove it, then I guess it's ok. Keeping the Token with a longer prefix would be a less 'disruptive' change and we can manage/fail locally in the code and report it with a useful message to the user if the length exceeds 126 characters. I'm ok either way. Thanks From the AWS EKS documentation, the clientRequestToken is not required: https://docs.aws.amazon.com/eks/latest/APIReference/API_CreateCluster.html#AmazonEKS-CreateCluster-request-clientRequestToken It is not clear if it is auto-generated if not provided, but that could be determined by examining the response (cluster) object that is created without a token. It is meant for idempotency, according to the AWS doc. So, it is good to set it when the name is short enough. > It is meant for idempotency, according to the AWS doc. So, it is good to set it when the name is short enough. I wonder what this means in the context of ansible. the `create_cluster` function is requested only once (_when the cluster does not exist_). and in a general context. Even if the token is changing, you can run the `create_cluster` statement only once. ```python import boto3 eks = boto3.client('eks') response = eks.create_cluster( name='b', version='1.21', roleArn='arn:aws:iam::123:role/myEKSClusterRole', resourcesVpcConfig={ 'subnetIds': [ 'subnet-d8309db2', 'subnet-943ad4d8' ], 'securityGroupIds': [ 'sg-f32f0196', ] }, clientRequestToken='stringstringstringstringstringstring' ) print(response) response = eks.create_cluster( name='b', version='1.21', roleArn='arn:aws:iam::123:role/myEKSClusterRole', resourcesVpcConfig={ 'subnetIds': [ 'subnet-d8309db2', 'subnet-943ad4d8' ], 'securityGroupIds': [ 'sg-f32f0196', ] }, clientRequestToken='stringstringstringstringstringstring1' ) print(response) ``` restults in ``` {'ResponseMetadata': {'RequestId': '05bfc8b2-ee3c-4f25-ab24-bd231e5224b8', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Thu, 02 Dec 2021 19:43:59 GMT', 'content-type': 'application/json', 'content-length': '820', 'connection': 'keep-alive', 'x-amzn-requestid': '05bfc8b2-ee3c-4f25-ab24-bd231e5224b8', 'access-control-allow-origin': '*', 'access-control-allow-headers': '*,Authorization,Date,X-Amz-Date,X-Amz-Security-Token,X-Amz-Target,content-type,x-amz-content-sha256,x-amz-user-agent,x-amzn-platform-id,x-amzn-trace-id', 'x-amz-apigw-id': 'JvI_zGeAliAFZrA=', 'access-control-allow-methods': 'GET,HEAD,PUT,POST,DELETE,OPTIONS', 'access-control-expose-headers': 'x-amzn-errortype,x-amzn-errormessage,x-amzn-trace-id,x-amzn-requestid,x-amz-apigw-id,date', 'x-amzn-trace-id': 'Root=1-61a921fe-3529fabd0c39a93b6e9340f6'}, 'RetryAttempts': 0}, 'cluster': {'name': 'b', 'arn': 'arn:aws:eks:eu-central-1:123:cluster/b', 'createdAt': datetime.datetime(2021, 12, 2, 20, 43, 59, 671000, tzinfo=tzlocal()), 'version': '1.21', 'roleArn': 'arn:aws:iam::123:role/myEKSClusterRole', 'resourcesVpcConfig': {'subnetIds': ['subnet-d8309db2', 'subnet-943ad4d8'], 'securityGroupIds': ['sg-f32f0196'], 'vpcId': 'vpc-6731f40d', 'endpointPublicAccess': True, 'endpointPrivateAccess': False, 'publicAccessCidrs': ['0.0.0.0/0']}, 'kubernetesNetworkConfig': {'serviceIpv4Cidr': '10.100.0.0/16'}, 'logging': {'clusterLogging': [{'types': ['api', 'audit', 'authenticator', 'controllerManager', 'scheduler'], 'enabled': False}]}, 'status': 'CREATING', 'certificateAuthority': {}, 'platformVersion': 'eks.3', 'tags': {}}} Traceback (most recent call last): File "/tmp/test_eks.py", line 6, in <module> response = eks.create_cluster( File "/home/m/.local/lib/python3.9/site-packages/botocore/client.py", line 388, in _api_call return self._make_api_call(operation_name, kwargs) File "/home/m/.local/lib/python3.9/site-packages/botocore/client.py", line 708, in _make_api_call raise error_class(parsed_response, operation_name) botocore.errorfactory.ResourceInUseException: An error occurred (ResourceInUseException) when calling the CreateCluster operation: Cluster already exists with name: b ``` > So, it is good to set it when the name is short enough. But yes, we can implement this logic for safety
2022-01-05T10:01:43
ansible-collections/community.aws
857
ansible-collections__community.aws-857
[ "830" ]
5e5f754736f4e851c446a1261cf3a1fd4b51f7b9
diff --git a/plugins/modules/execute_lambda.py b/plugins/modules/execute_lambda.py --- a/plugins/modules/execute_lambda.py +++ b/plugins/modules/execute_lambda.py @@ -202,6 +202,9 @@ def main(): elif name: invoke_params['FunctionName'] = name + if not module.check_mode: + wait_for_lambda(client, module, name) + try: response = client.invoke(**invoke_params) except is_boto3_error_code('ResourceNotFoundException') as nfe: @@ -255,5 +258,15 @@ def main(): module.exit_json(changed=True, result=results) +def wait_for_lambda(client, module, name): + try: + waiter = client.get_waiter('function_active') + waiter.wait(FunctionName=name) + except botocore.exceptions.WaiterError as e: + module.fail_json_aws(e, msg='Timeout while waiting on lambda to be Active') + except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: + module.fail_json_aws(e, msg='Failed while waiting on lambda to be Active') + + if __name__ == '__main__': main() diff --git a/plugins/modules/lambda.py b/plugins/modules/lambda.py --- a/plugins/modules/lambda.py +++ b/plugins/modules/lambda.py @@ -216,7 +216,7 @@ import re try: - from botocore.exceptions import ClientError, BotoCoreError + from botocore.exceptions import ClientError, BotoCoreError, WaiterError except ImportError: pass # protected by AnsibleAWSModule @@ -320,6 +320,18 @@ def set_tag(client, module, tags, function): return changed +def wait_for_lambda(client, module, name): + try: + client_active_waiter = client.get_waiter('function_active') + client_updated_waiter = client.get_waiter('function_updated') + client_active_waiter.wait(FunctionName=name) + client_updated_waiter.wait(FunctionName=name) + except WaiterError as e: + module.fail_json_aws(e, msg='Timeout while waiting on lambda to finish updating') + except (ClientError, BotoCoreError) as e: + module.fail_json_aws(e, msg='Failed while waiting on lambda to finish updating') + + def main(): argument_spec = dict( name=dict(required=True), @@ -453,6 +465,9 @@ def main(): # Upload new configuration if configuration has changed if len(func_kwargs) > 1: + if not check_mode: + wait_for_lambda(client, module, name) + try: if not check_mode: response = client.update_function_configuration(aws_retry=True, **func_kwargs) @@ -494,6 +509,9 @@ def main(): # Upload new code if needed (e.g. code checksum has changed) if len(code_kwargs) > 2: + if not check_mode: + wait_for_lambda(client, module, name) + try: if not check_mode: response = client.update_function_code(aws_retry=True, **code_kwargs)
lambda.py invokes update_function_configuration() and afterwards update_function_code() without checking Configuration.State and Configuration.LastUpdateStatus fields in between ### Summary lambda.py invokes `update_function_configuration()` [here](https://github.com/ansible-collections/community.aws/blob/main/plugins/modules/lambda.py#L458) and `afterwards update_function_code()` [here](https://github.com/ansible-collections/community.aws/blob/main/plugins/modules/lambda.py#L499) without checking `Configuration.State` and `Configuration.LastUpdateStatus` fields in between. If lambda function was updated in scope of the first call an error similar to below one is created during the second call: ``` An exception occurred during task execution. To see the full traceback, use -vvv. The error was: botocore.errorfactory.ResourceConflictException: An error occurred (ResourceConflictException) when calling the UpdateFunctionCode operation: The operation cannot be performed at this time. An update is in progress for resource: arn:aws:lambda:MY_REGION:MY_AWS_ACCOUNT_ID:function:MY_LAMBDA_FUNC_NAME fatal: [localhost]: FAILED! => {"boto3_version": "1.20.22", "botocore_version": "1.23.22", "changed": false, "error": {"code": "ResourceConflictException", "message": "The operation cannot be performed at this time. An update is in progress for resource: arn:aws:lambda:MY_REGION:MY_AWS_ACCOUNT_ID:function:MY_LAMBDA_FUNC_NAME"}, "message": "The operation cannot be performed at this time. An update is in progress for resource: arn:aws:lambda:MY_REGION:MY_AWS_ACCOUNT_ID:function:MY_LAMBDA_FUNC_NAME", "msg": "Trying to upload new code: An error occurred (ResourceConflictException) when calling the UpdateFunctionCode operation: The operation cannot be performed at this time. An update is in progress for resource: arn:aws:lambda:MY_REGION:MY_AWS_ACCOUNT_ID:function:MY_LAMBDA_FUNC_NAME", "response_metadata": {"http_headers": {"connection": "keep-alive", "content-length": "201", "content-type": "application/json", "date": "Thu, 09 Dec 2021 13:23:20 GMT", "x-amzn-errortype": "ResourceConflictException", "x-amzn-requestid": "abfc47a6-6c1c-42e4-b19d-853da87674bc"}, "http_status_code": 409, "request_id": "abfc47a6-6c1c-42e4-b19d-853da87674bc", "retry_attempts": 0}, "type": "User"} ``` ### Issue Type Bug Report ### Component Name lambda ### Ansible Version ```console (paste below) $ ansible --version ansible [core 2.12.0] config file = /home/my_dir/ansible.cfg configured module search path = ['/home/my_dir/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /home/my_dir/.venv/lib/python3.8/site-packages/ansible ansible collection location = /home/my_dir/.ansible/my_company/collections executable location = /home/my_dir/.venv/bin/ansible python version = 3.8.5 (v3.8.5:580fbb018f, Jul 20 2020, 12:11:27) [Clang 6.0 (clang-600.0.57)] jinja version = 2.11.3 libyaml = True``` ### Collection Versions ```console (paste below) $ ansible-galaxy collection list # /home/my_dir/.ansible/my_company/collections/ansible_collections Collection Version --------------------- ------- amazon.aws 3.0.0 ansible.netcommon 1.4.1 ansible.posix 1.3.0 community.aws 2.1.0 community.general 4.0.0 community.hashi_vault 1.3.2 community.kubernetes 1.2.1 community.sops 1.1.0 google.cloud 1.0.1 kubernetes.core 2.2.1 # /home/my_dir/.venv/lib/python3.8/site-packages/ansible_collections Collection Version ----------------------------- ------- amazon.aws 2.1.0 ansible.netcommon 2.4.0 ansible.posix 1.3.0 ansible.utils 2.4.2 ansible.windows 1.8.0 arista.eos 3.1.0 awx.awx 19.4.0 azure.azcollection 1.10.0 check_point.mgmt 2.1.1 chocolatey.chocolatey 1.1.0 cisco.aci 2.1.0 cisco.asa 2.1.0 cisco.intersight 1.0.17 cisco.ios 2.5.0 cisco.iosxr 2.5.0 cisco.ise 1.2.1 cisco.meraki 2.5.0 cisco.mso 1.2.0 cisco.nso 1.0.3 cisco.nxos 2.7.1 cisco.ucs 1.6.0 cloud.common 2.1.0 cloudscale_ch.cloud 2.2.0 community.aws 2.1.0 community.azure 1.1.0 community.ciscosmb 1.0.4 community.crypto 2.0.1 community.digitalocean 1.12.0 community.dns 2.0.3 community.docker 2.0.1 community.fortios 1.0.0 community.general 4.0.2 community.google 1.0.0 community.grafana 1.2.3 community.hashi_vault 2.0.0 community.hrobot 1.2.1 community.kubernetes 2.0.1 community.kubevirt 1.0.0 community.libvirt 1.0.2 community.mongodb 1.3.2 community.mysql 2.3.1 community.network 3.0.0 [0/1887] community.okd 2.1.0 community.postgresql 1.5.0 community.proxysql 1.3.0 community.rabbitmq 1.1.0 community.routeros 2.0.0 community.skydive 1.0.0 community.sops 1.2.0 community.vmware 1.16.0 community.windows 1.8.0 community.zabbix 1.5.0 containers.podman 1.8.2 cyberark.conjur 1.1.0 cyberark.pas 1.0.13 dellemc.enterprise_sonic 1.1.0 dellemc.openmanage 4.2.0 dellemc.os10 1.1.1 dellemc.os6 1.0.7 dellemc.os9 1.0.4 f5networks.f5_modules 1.12.0 fortinet.fortimanager 2.1.4 fortinet.fortios 2.1.3 frr.frr 1.0.3 gluster.gluster 1.0.2 google.cloud 1.0.2 hetzner.hcloud 1.6.0 hpe.nimble 1.1.3 ibm.qradar 1.0.3 infinidat.infinibox 1.3.0 infoblox.nios_modules 1.1.2 inspur.sm 1.3.0 junipernetworks.junos 2.6.0 kubernetes.core 2.2.1 mellanox.onyx 1.0.0 netapp.aws 21.7.0 netapp.azure 21.10.0 netapp.cloudmanager 21.12.0 netapp.elementsw 21.7.0 netapp.ontap 21.13.1 netapp.storagegrid 21.7.0 netapp.um_info 21.8.0 netapp_eseries.santricity 1.2.13 netbox.netbox 3.3.0 ngine_io.cloudstack 2.2.2 ngine_io.exoscale 1.0.0 ngine_io.vultr 1.1.0 openstack.cloud 1.5.3 openvswitch.openvswitch 2.0.2 ovirt.ovirt 1.6.5 purestorage.flasharray 1.11.0 purestorage.flashblade 1.8.1 sensu.sensu_go 1.12.0 servicenow.servicenow 1.0.6 splunk.es 1.0.2 t_systems_mms.icinga_director 1.24.0 theforeman.foreman 2.2.0 vyos.vyos 2.6.0 wti.remote 1.0.3 ``` ### AWS SDK versions ```console (paste below) $ pip show boto boto3 botocore Name: boto Version: 2.49.0 Summary: Amazon Web Services Library Home-page: https://github.com/boto/boto/ Author: Mitch Garnaat Author-email: [email protected] License: MIT Location:/home/my_dir/.venv/lib/python3.8/site-packages Requires: Required-by: --- Name: boto3 Version: 1.20.22 Summary: The AWS SDK for Python Home-page: https://github.com/boto/boto3 Author: Amazon Web Services Author-email: License: Apache License 2.0 Location: /home/my_dir/.venv/lib/python3.8/site-packages Requires: botocore, jmespath, s3transfer Required-by: --- Name: botocore Version: 1.23.22 Summary: Low-level, data-driven core of boto 3. Home-page: https://github.com/boto/botocore Author: Amazon Web Services Author-email: License: Apache License 2.0 Location: /home/my_dir/.venv/lib/python3.8/site-packages Requires: jmespath, python-dateutil, urllib3 Required-by: awscli, boto3, s3transfer ``` ### Configuration ```console (paste below) $ ansible-config dump --only-changed COLLECTIONS_PATHS(/home/my_dir/ansible.cfg) = ['/home/my_dir/.ansible/my_company/collections'] DEFAULT_HOST_LIST(/home/my_dir/ansible.cfg) = ['/dev/null'] DEFAULT_VAULT_PASSWORD_FILE(env: ANSIBLE_VAULT_PASSWORD_FILE) = /home/my_dir/.vault-ansible LOCALHOST_WARNING(/home/my_dir/ansible.cfg) = False RETRY_FILES_ENABLED(/home/my_dir/ansible.cfg) = False ``` ### OS / Environment macOS Big Sur 11.6 ### Steps to Reproduce <!--- Paste example playbooks or commands between quotes below --> 1. Change memory assignment in aws lambda gui to value different than the one set by Ansible 2. Wait until `aws lambda get-function --function-name YOUR_FUNCTION --query 'Configuration.[State, LastUpdateStatus]'` will return ``` [ "Active", "Successful" ] ``` 3. Invoke below ansible snippet ```yaml (paste below) - name: "Deploy lambda function" lambda: dead_letter_arn: "{{ 'arn:aws:sqs:{}:{}:{}-{}-lambda-deadletter'.format(aws_region, account, x, lambda_name) }}" description: "{{ lambda_description }}" environment_variables: "{{ lambda_env }}" handler: "{{ lambda_handler }}" memory_size: "{{ lambda_memory }}" name: "{{ lambda_full_name }}" role: "arn:aws:iam::{{ account }}:role/service-role/{{ lambda_iam_name }}" runtime: "{{ lambda_runtime }}" s3_bucket: "{{ lambda_s3_bucket }}" s3_key: "{{ lambda_s3_url }} timeout: "{{ lambda_timeout }}" vpc_security_group_ids: "{{ group_id }}" vpc_subnet_ids: "{{ subnets }}" region: "{{ aws_region }}" aws_access_key: "{{ access_key }}" aws_secret_key: "{{ secret_key }}" security_token: "{{ session_token }}" ``` ### Expected Results 4. Get the below error due to lambda function being still updated after `update_function_configuration()` call: ``` An exception occurred during task execution. To see the full traceback, use -vvv. The error was: botocore.errorfactory.ResourceConflictException: An error occurred (ResourceConflictException) when calling the UpdateFunctionCode operation: The operation cannot be performed at this time. An update is in progress for resource: arn:aws:lambda:MY_REGION:MY_AWS_ACCOUNT_ID:function:MY_LAMBDA_FUNC_NAME fatal: [localhost]: FAILED! => {"boto3_version": "1.20.22", "botocore_version": "1.23.22", "changed": false, "error": {"code": "ResourceConflictException", "message": "The operation cannot be performed at this time. An update is in progress for resource: arn:aws:lambda:MY_REGION:MY_AWS_ACCOUNT_ID:function:MY_LAMBDA_FUNC_NAME"}, "message": "The operation cannot be performed at this time. An update is in progress for resource: arn:aws:lambda:MY_REGION:MY_AWS_ACCOUNT_ID:function:MY_LAMBDA_FUNC_NAME", "msg": "Trying to upload new code: An error occurred (ResourceConflictException) when calling the UpdateFunctionCode operation: The operation cannot be performed at this time. An update is in progress for resource: arn:aws:lambda:MY_REGION:MY_AWS_ACCOUNT_ID:function:MY_LAMBDA_FUNC_NAME", "response_metadata": {"http_headers": {"connection": "keep-alive", "content-length": "201", "content-type": "application/json", "date": "Thu, 09 Dec 2021 13:23:20 GMT", "x-amzn-errortype": "ResourceConflictException", "x-amzn-requestid": "abfc47a6-6c1c-42e4-b19d-853da87674bc"}, "http_status_code": 409, "request_id": "abfc47a6-6c1c-42e4-b19d-853da87674bc", "retry_attempts": 0}, "type": "User"} ``` ### Actual Results ```console (paste below) ``` ### Code of Conduct - [X] I agree to follow the Ansible Code of Conduct
2022-01-10T22:58:50
ansible-collections/community.aws
859
ansible-collections__community.aws-859
[ "858" ]
c67c890726a512b5bfadf0cfa97f1534ce470711
diff --git a/plugins/module_utils/opensearch.py b/plugins/module_utils/opensearch.py new file mode 100644 --- /dev/null +++ b/plugins/module_utils/opensearch.py @@ -0,0 +1,280 @@ +# This file is part of Ansible +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function + +__metaclass__ = type + +from copy import deepcopy +import datetime +import functools +import time + +try: + import botocore +except ImportError: + pass # caught by AnsibleAWSModule + +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import ( + ansible_dict_to_boto3_tag_list, + camel_dict_to_snake_dict, + compare_aws_tags, +) +from ansible_collections.amazon.aws.plugins.module_utils.core import is_boto3_error_code +from ansible_collections.amazon.aws.plugins.module_utils.tagging import ( + boto3_tag_list_to_ansible_dict, +) +from ansible.module_utils.six import string_types + + +def get_domain_status(client, module, domain_name): + """ + Get the status of an existing OpenSearch cluster. + """ + try: + response = client.describe_domain(DomainName=domain_name) + except is_boto3_error_code("ResourceNotFoundException"): + return None + except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: # pylint: disable=duplicate-except + module.fail_json_aws(e, msg="Couldn't get domain {0}".format(domain_name)) + return response["DomainStatus"] + + +def get_domain_config(client, module, domain_name): + """ + Get the configuration of an existing OpenSearch cluster, convert the data + such that it can be used as input parameter to client.update_domain(). + The status info is removed. + The returned config includes the 'EngineVersion' property, it needs to be removed + from the dict before invoking client.update_domain(). + + Return (domain_config, domain_arn) or (None, None) if the domain does not exist. + """ + try: + response = client.describe_domain_config(DomainName=domain_name) + except is_boto3_error_code("ResourceNotFoundException"): + return (None, None) + except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: # pylint: disable=duplicate-except + module.fail_json_aws(e, msg="Couldn't get domain {0}".format(domain_name)) + domain_config = {} + arn = None + if response is not None: + for k in response["DomainConfig"]: + domain_config[k] = response["DomainConfig"][k]["Options"] + domain_config["DomainName"] = domain_name + # If ES cluster is attached to the Internet, the "VPCOptions" property is not present. + if "VPCOptions" in domain_config: + # The "VPCOptions" returned by the describe_domain_config API has + # additional attributes that would cause an error if sent in the HTTP POST body. + dc = {} + if "SubnetIds" in domain_config["VPCOptions"]: + dc["SubnetIds"] = deepcopy(domain_config["VPCOptions"]["SubnetIds"]) + if "SecurityGroupIds" in domain_config["VPCOptions"]: + dc["SecurityGroupIds"] = deepcopy(domain_config["VPCOptions"]["SecurityGroupIds"]) + domain_config["VPCOptions"] = dc + # The "StartAt" property is converted to datetime, but when doing comparisons it should + # be in the string format "YYYY-MM-DD". + for s in domain_config["AutoTuneOptions"]["MaintenanceSchedules"]: + if isinstance(s["StartAt"], datetime.datetime): + s["StartAt"] = s["StartAt"].strftime("%Y-%m-%d") + # Provisioning of "AdvancedOptions" is not supported by this module yet. + domain_config.pop("AdvancedOptions", None) + + # Get the ARN of the OpenSearch cluster. + domain = get_domain_status(client, module, domain_name) + if domain is not None: + arn = domain["ARN"] + return (domain_config, arn) + + +def normalize_opensearch(client, module, domain): + """ + Merge the input domain object with tags associated with the domain, + convert the attributes from camel case to snake case, and return the object. + """ + try: + domain["Tags"] = boto3_tag_list_to_ansible_dict( + client.list_tags(ARN=domain["ARN"], aws_retry=True)["TagList"] + ) + except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: + module.fail_json_aws( + e, "Couldn't get tags for domain %s" % domain["domain_name"] + ) + except KeyError: + module.fail_json(msg=str(domain)) + + return camel_dict_to_snake_dict(domain, ignore_list=["Tags"]) + + +def wait_for_domain_status(client, module, domain_name, waiter_name): + if not module.params["wait"]: + return + timeout = module.params["wait_timeout"] + deadline = time.time() + timeout + status_msg = "" + while time.time() < deadline: + status = get_domain_status(client, module, domain_name) + if status is None: + status_msg = "Not Found" + if waiter_name == "domain_deleted": + return + else: + status_msg = "Created: {0}. Processing: {1}. UpgradeProcessing: {2}".format( + status["Created"], + status["Processing"], + status["UpgradeProcessing"], + ) + if ( + waiter_name == "domain_available" + and status["Created"] + and not status["Processing"] + and not status["UpgradeProcessing"] + ): + return + time.sleep(15) + # Timeout occured. + module.fail_json( + msg=f"Timeout waiting for wait state '{waiter_name}'. {status_msg}" + ) + + +def parse_version(engine_version): + ''' + Parse the engine version, which should be Elasticsearch_X.Y or OpenSearch_X.Y + Return dict { 'engine_type': engine_type, 'major': major, 'minor': minor } + ''' + version = engine_version.split("_") + if len(version) != 2: + return None + semver = version[1].split(".") + if len(semver) != 2: + return None + engine_type = version[0] + if engine_type not in ['Elasticsearch', 'OpenSearch']: + return None + if not (semver[0].isdigit() and semver[1].isdigit()): + return None + major = int(semver[0]) + minor = int(semver[1]) + return {'engine_type': engine_type, 'major': major, 'minor': minor} + + +def compare_domain_versions(version1, version2): + supported_engines = { + 'Elasticsearch': 1, + 'OpenSearch': 2, + } + if isinstance(version1, string_types): + version1 = parse_version(version1) + if isinstance(version2, string_types): + version2 = parse_version(version2) + if version1 is None and version2 is not None: + return -1 + elif version1 is not None and version2 is None: + return 1 + elif version1 is None and version2 is None: + return 0 + e1 = supported_engines.get(version1.get('engine_type')) + e2 = supported_engines.get(version2.get('engine_type')) + if e1 < e2: + return -1 + elif e1 > e2: + return 1 + else: + if version1.get('major') < version2.get('major'): + return -1 + elif version1.get('major') > version2.get('major'): + return 1 + else: + if version1.get('minor') < version2.get('minor'): + return -1 + elif version1.get('minor') > version2.get('minor'): + return 1 + else: + return 0 + + +def get_target_increment_version(client, module, domain_name, target_version): + """ + Returns the highest compatible version which is less than or equal to target_version. + When upgrading a domain from version V1 to V2, it may not be possible to upgrade + directly from V1 to V2. The domain may have to be upgraded through intermediate versions. + Return None if there is no such version. + For example, it's not possible to upgrade directly from Elasticsearch 5.5 to 7.10. + """ + api_compatible_versions = None + try: + api_compatible_versions = client.get_compatible_versions(DomainName=domain_name) + except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: + module.fail_json_aws( + e, + msg="Couldn't get compatible versions for domain {0}".format( + domain_name), + ) + compat = api_compatible_versions.get('CompatibleVersions') + if compat is None: + module.fail_json( + "Unable to determine list of compatible versions", + compatible_versions=api_compatible_versions) + if len(compat) == 0: + module.fail_json( + "Unable to determine list of compatible versions", + compatible_versions=api_compatible_versions) + if compat[0].get("TargetVersions") is None: + module.fail_json( + "No compatible versions found", + compatible_versions=api_compatible_versions) + compatible_versions = [] + for v in compat[0].get("TargetVersions"): + if target_version == v: + # It's possible to upgrade directly to the target version. + return target_version + semver = parse_version(v) + if semver is not None: + compatible_versions.append(semver) + # No direct upgrade is possible. Upgrade to the highest version available. + compatible_versions = sorted(compatible_versions, key=functools.cmp_to_key(compare_domain_versions)) + # Return the highest compatible version which is lower than target_version + for v in reversed(compatible_versions): + if compare_domain_versions(v, target_version) <= 0: + return v + return None + + +def ensure_tags(client, module, resource_arn, existing_tags, tags, purge_tags): + if tags is None: + return False + tags_to_add, tags_to_remove = compare_aws_tags(existing_tags, tags, purge_tags) + changed = bool(tags_to_add or tags_to_remove) + if tags_to_add: + if module.check_mode: + module.exit_json( + changed=True, msg="Would have added tags to domain if not in check mode" + ) + try: + client.add_tags( + ARN=resource_arn, + TagList=ansible_dict_to_boto3_tag_list(tags_to_add), + ) + except ( + botocore.exceptions.ClientError, + botocore.exceptions.BotoCoreError, + ) as e: + module.fail_json_aws( + e, "Couldn't add tags to domain {0}".format(resource_arn) + ) + if tags_to_remove: + if module.check_mode: + module.exit_json( + changed=True, msg="Would have removed tags if not in check mode" + ) + try: + client.remove_tags(ARN=resource_arn, TagKeys=tags_to_remove) + except ( + botocore.exceptions.ClientError, + botocore.exceptions.BotoCoreError, + ) as e: + module.fail_json_aws( + e, "Couldn't remove tags from domain {0}".format(resource_arn) + ) + return changed diff --git a/plugins/modules/opensearch.py b/plugins/modules/opensearch.py new file mode 100644 --- /dev/null +++ b/plugins/modules/opensearch.py @@ -0,0 +1,1507 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# Copyright: Ansible Project +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + +DOCUMENTATION = """ +--- +module: opensearch +short_description: Creates OpenSearch or ElasticSearch domain. +description: + - Creates or modify a Amazon OpenSearch Service domain. +version_added: 3.1.0 +author: "Sebastien Rosset (@sebastien-rosset)" +options: + state: + description: + - Creates or modifies an existing OpenSearch domain. + - Deletes an OpenSearch domain. + required: false + type: str + choices: ['present', 'absent'] + default: present + domain_name: + description: + - The name of the Amazon OpenSearch/ElasticSearch Service domain. + - Domain names are unique across the domains owned by an account within an AWS region. + required: true + type: str + engine_version: + description: + -> + The engine version to use. For example, 'ElasticSearch_7.10' or 'OpenSearch_1.1'. + -> + If the currently running version is not equal to I(engine_version), + a cluster upgrade is triggered. + -> + It may not be possible to upgrade directly from the currently running version + to I(engine_version). In that case, the upgrade is performed incrementally by + upgrading to the highest compatible version, then repeat the operation until + the cluster is running at the target version. + -> + The upgrade operation fails if there is no path from current version to I(engine_version). + -> + See OpenSearch documentation for upgrade compatibility. + required: false + type: str + allow_intermediate_upgrades: + description: + - > + If true, allow OpenSearch domain to be upgraded through one or more intermediate versions. + - > + If false, do not allow OpenSearch domain to be upgraded through intermediate versions. + The upgrade operation fails if it's not possible to ugrade to I(engine_version) directly. + required: false + type: bool + default: true + cluster_config: + description: + - Parameters for the cluster configuration of an OpenSearch Service domain. + type: dict + suboptions: + instance_type: + description: + - Type of the instances to use for the domain. + required: false + type: str + instance_count: + description: + - Number of instances for the domain. + required: false + type: int + zone_awareness: + description: + - A boolean value to indicate whether zone awareness is enabled. + required: false + type: bool + availability_zone_count: + description: + - > + An integer value to indicate the number of availability zones for a domain when zone awareness is enabled. + This should be equal to number of subnets if VPC endpoints is enabled. + required: false + type: int + dedicated_master: + description: + - A boolean value to indicate whether a dedicated master node is enabled. + required: false + type: bool + dedicated_master_instance_type: + description: + - The instance type for a dedicated master node. + required: false + type: str + dedicated_master_instance_count: + description: + - Total number of dedicated master nodes, active and on standby, for the domain. + required: false + type: int + warm_enabled: + description: + - True to enable UltraWarm storage. + required: false + type: bool + warm_type: + description: + - The instance type for the OpenSearch domain's warm nodes. + required: false + type: str + warm_count: + description: + - The number of UltraWarm nodes in the domain. + required: false + type: int + cold_storage_options: + description: + - Specifies the ColdStorageOptions config for a Domain. + type: dict + suboptions: + enabled: + description: + - True to enable cold storage. Supported on Elasticsearch 7.9 or above. + required: false + type: bool + ebs_options: + description: + - Parameters to configure EBS-based storage for an OpenSearch Service domain. + type: dict + suboptions: + ebs_enabled: + description: + - Specifies whether EBS-based storage is enabled. + required: false + type: bool + volume_type: + description: + - Specifies the volume type for EBS-based storage. "standard"|"gp2"|"io1" + required: false + type: str + volume_size: + description: + - Integer to specify the size of an EBS volume. + required: false + type: int + iops: + description: + - The IOPD for a Provisioned IOPS EBS volume (SSD). + required: false + type: int + vpc_options: + description: + - Options to specify the subnets and security groups for a VPC endpoint. + type: dict + suboptions: + subnets: + description: + - Specifies the subnet ids for VPC endpoint. + required: false + type: list + elements: str + security_groups: + description: + - Specifies the security group ids for VPC endpoint. + required: false + type: list + elements: str + snapshot_options: + description: + - Option to set time, in UTC format, of the daily automated snapshot. + type: dict + suboptions: + automated_snapshot_start_hour: + description: + - > + Integer value from 0 to 23 specifying when the service takes a daily automated snapshot + of the specified Elasticsearch domain. + required: false + type: int + access_policies: + description: + - IAM access policy as a JSON-formatted string. + required: false + type: dict + encryption_at_rest_options: + description: + - Parameters to enable encryption at rest. + type: dict + suboptions: + enabled: + description: + - Should data be encrypted while at rest. + required: false + type: bool + kms_key_id: + description: + - If encryption at rest enabled, this identifies the encryption key to use. + - The value should be a KMS key ARN. It can also be the KMS key id. + required: false + type: str + node_to_node_encryption_options: + description: + - Node-to-node encryption options. + type: dict + suboptions: + enabled: + description: + - True to enable node-to-node encryption. + required: false + type: bool + cognito_options: + description: + - Parameters to configure OpenSearch Service to use Amazon Cognito authentication for OpenSearch Dashboards. + type: dict + suboptions: + enabled: + description: + - The option to enable Cognito for OpenSearch Dashboards authentication. + required: false + type: bool + user_pool_id: + description: + - The Cognito user pool ID for OpenSearch Dashboards authentication. + required: false + type: str + identity_pool_id: + description: + - The Cognito identity pool ID for OpenSearch Dashboards authentication. + required: false + type: str + role_arn: + description: + - The role ARN that provides OpenSearch permissions for accessing Cognito resources. + required: false + type: str + domain_endpoint_options: + description: + - Options to specify configuration that will be applied to the domain endpoint. + type: dict + suboptions: + enforce_https: + description: + - Whether only HTTPS endpoint should be enabled for the domain. + type: bool + tls_security_policy: + description: + - Specify the TLS security policy to apply to the HTTPS endpoint of the domain. + type: str + custom_endpoint_enabled: + description: + - Whether to enable a custom endpoint for the domain. + type: bool + custom_endpoint: + description: + - The fully qualified domain for your custom endpoint. + type: str + custom_endpoint_certificate_arn: + description: + - The ACM certificate ARN for your custom endpoint. + type: str + advanced_security_options: + description: + - Specifies advanced security options. + type: dict + suboptions: + enabled: + description: + - True if advanced security is enabled. + - You must enable node-to-node encryption to use advanced security options. + type: bool + internal_user_database_enabled: + description: + - True if the internal user database is enabled. + type: bool + master_user_options: + description: + - Credentials for the master user, username and password, ARN, or both. + type: dict + suboptions: + master_user_arn: + description: + - ARN for the master user (if IAM is enabled). + type: str + master_user_name: + description: + - The username of the master user, which is stored in the Amazon OpenSearch Service domain internal database. + type: str + master_user_password: + description: + - The password of the master user, which is stored in the Amazon OpenSearch Service domain internal database. + type: str + saml_options: + description: + - The SAML application configuration for the domain. + type: dict + suboptions: + enabled: + description: + - True if SAML is enabled. + - To use SAML authentication, you must enable fine-grained access control. + - You can only enable SAML authentication for OpenSearch Dashboards on existing domains, + not during the creation of new ones. + - Domains only support one Dashboards authentication method at a time. + If you have Amazon Cognito authentication for OpenSearch Dashboards enabled, + you must disable it before you can enable SAML. + type: bool + idp: + description: + - The SAML Identity Provider's information. + type: dict + suboptions: + metadata_content: + description: + - The metadata of the SAML application in XML format. + type: str + entity_id: + description: + - The unique entity ID of the application in SAML identity provider. + type: str + master_user_name: + description: + - The SAML master username, which is stored in the Amazon OpenSearch Service domain internal database. + type: str + master_backend_role: + description: + - The backend role that the SAML master user is mapped to. + type: str + subject_key: + description: + - Element of the SAML assertion to use for username. Default is NameID. + type: str + roles_key: + description: + - Element of the SAML assertion to use for backend roles. Default is roles. + type: str + session_timeout_minutes: + description: + - The duration, in minutes, after which a user session becomes inactive. Acceptable values are between 1 and 1440, and the default value is 60. + type: int + auto_tune_options: + description: + - Specifies Auto-Tune options. + type: dict + suboptions: + desired_state: + description: + - The Auto-Tune desired state. Valid values are ENABLED and DISABLED. + type: str + choices: ['ENABLED', 'DISABLED'] + maintenance_schedules: + description: + - A list of maintenance schedules. + type: list + elements: dict + suboptions: + start_at: + description: + - The timestamp at which the Auto-Tune maintenance schedule starts. + type: str + duration: + description: + - Specifies maintenance schedule duration, duration value and duration unit. + type: dict + suboptions: + value: + description: + - Integer to specify the value of a maintenance schedule duration. + type: int + unit: + description: + - The unit of a maintenance schedule duration. Valid value is HOURS. + choices: ['HOURS'] + type: str + cron_expression_for_recurrence: + description: + - A cron expression for a recurring maintenance schedule. + type: str + wait: + description: + - Whether or not to wait for completion of OpenSearch creation, modification or deletion. + type: bool + default: 'no' + wait_timeout: + description: + - how long before wait gives up, in seconds. + default: 300 + type: int + tags: + description: + - tags dict to apply to an OpenSearch cluster. + type: dict + purge_tags: + description: + - whether to remove tags not present in the C(tags) parameter. + default: True + type: bool +requirements: +- botocore >= 1.21.38 +extends_documentation_fragment: +- amazon.aws.aws +- amazon.aws.ec2 +""" + +EXAMPLES = """ + +- name: Create OpenSearch domain for dev environment, no zone awareness, no dedicated masters + community.aws.opensearch: + domain_name: "dev-cluster" + engine_version: Elasticsearch_1.1 + cluster_config: + instance_type: "t2.small.search" + instance_count: 2 + zone_awareness: false + dedicated_master: false + ebs_options: + ebs_enabled: true + volume_type: "gp2" + volume_size: 10 + access_policies: "{{ lookup('file', 'policy.json') | from_json }}" + +- name: Create OpenSearch domain with dedicated masters + community.aws.opensearch: + domain_name: "my-domain" + engine_version: OpenSearch_1.1 + cluster_config: + instance_type: "t2.small.search" + instance_count: 12 + dedicated_master: true + zone_awareness: true + availability_zone_count: 2 + dedicated_master_instance_type: "t2.small.search" + dedicated_master_instance_count: 3 + warm_enabled: true + warm_type: "ultrawarm1.medium.search" + warm_count: 1 + cold_storage_options: + enabled: false + ebs_options: + ebs_enabled: true + volume_type: "io1" + volume_size: 10 + iops: 1000 + vpc_options: + subnets: + - "subnet-e537d64a" + - "subnet-e537d64b" + security_groups: + - "sg-dd2f13cb" + - "sg-dd2f13cc" + snapshot_options: + automated_snapshot_start_hour: 13 + access_policies: "{{ lookup('file', 'policy.json') | from_json }}" + encryption_at_rest_options: + enabled: false + node_to_node_encryption_options: + enabled: false + auto_tune_options: + enabled: true + maintenance_schedules: + - start_at: "2025-01-12" + duration: + value: 1 + unit: "HOURS" + cron_expression_for_recurrence: "cron(0 12 * * ? *)" + - start_at: "2032-01-12" + duration: + value: 2 + unit: "HOURS" + cron_expression_for_recurrence: "cron(0 12 * * ? *)" + tags: + Environment: Development + Application: Search + wait: true + +- name: Increase size of EBS volumes for existing cluster + community.aws.opensearch: + domain_name: "my-domain" + ebs_options: + volume_size: 5 + wait: true + +- name: Increase instance count for existing cluster + community.aws.opensearch: + domain_name: "my-domain" + cluster_config: + instance_count: 40 + wait: true + +""" + +from copy import deepcopy +import datetime +import json + +try: + import botocore +except ImportError: + pass # handled by AnsibleAWSModule + +from ansible.module_utils.six import string_types + +# import module snippets +from ansible_collections.amazon.aws.plugins.module_utils.core import ( + AnsibleAWSModule, + is_boto3_error_code, +) +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import ( + AWSRetry, + boto3_tag_list_to_ansible_dict, + compare_policies, +) +from ansible_collections.community.aws.plugins.module_utils.opensearch import ( + compare_domain_versions, + ensure_tags, + get_domain_status, + get_domain_config, + get_target_increment_version, + normalize_opensearch, + parse_version, + wait_for_domain_status, +) + + +def ensure_domain_absent(client, module): + domain_name = module.params.get("domain_name") + changed = False + + domain = get_domain_status(client, module, domain_name) + if module.check_mode: + module.exit_json( + changed=True, msg="Would have deleted domain if not in check mode" + ) + try: + client.delete_domain(DomainName=domain_name) + changed = True + except is_boto3_error_code("ResourceNotFoundException"): + # The resource does not exist, or it has already been deleted + return dict(changed=False) + except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: # pylint: disable=duplicate-except + module.fail_json_aws(e, msg="trying to delete domain") + + # If we're not waiting for a delete to complete then we're all done + # so just return + if not domain or not module.params.get("wait"): + return dict(changed=changed) + try: + wait_for_domain_status(client, module, domain_name, "domain_deleted") + return dict(changed=changed) + except is_boto3_error_code("ResourceNotFoundException"): + return dict(changed=changed) + except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: # pylint: disable=duplicate-except + module.fail_json_aws(e, "awaiting domain deletion") + + +def upgrade_domain(client, module, source_version, target_engine_version): + domain_name = module.params.get("domain_name") + # Determine if it's possible to upgrade directly from source version + # to target version, or if it's necessary to upgrade through intermediate major versions. + next_version = target_engine_version + # When perform_check_only is true, indicates that an upgrade eligibility check needs + # to be performed. Does not actually perform the upgrade. + perform_check_only = False + if module.check_mode: + perform_check_only = True + current_version = source_version + while current_version != target_engine_version: + v = get_target_increment_version(client, module, domain_name, target_engine_version) + if v is None: + # There is no compatible version, according to the get_compatible_versions() API. + # The upgrade should fail, but try anyway. + next_version = target_engine_version + if next_version != target_engine_version: + # It's not possible to upgrade directly to the target version. + # Check the module parameters to determine if this is allowed or not. + if not module.params.get("allow_intermediate_upgrades"): + module.fail_json(msg="Cannot upgrade from {0} to version {1}. The highest compatible version is {2}".format( + source_version, target_engine_version, next_version)) + + parameters = { + "DomainName": domain_name, + "TargetVersion": next_version, + "PerformCheckOnly": perform_check_only, + } + + if not module.check_mode: + # If background tasks are in progress, wait until they complete. + # This can take several hours depending on the cluster size and the type of background tasks + # (maybe an upgrade is already in progress). + # It's not possible to upgrade a domain that has background tasks are in progress, + # the call to client.upgrade_domain would fail. + wait_for_domain_status(client, module, domain_name, "domain_available") + + try: + client.upgrade_domain(**parameters) + except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: + # In check mode (=> PerformCheckOnly==True), a ValidationException may be + # raised if it's not possible to upgrade to the target version. + module.fail_json_aws( + e, + msg="Couldn't upgrade domain {0} from {1} to {2}".format( + domain_name, current_version, next_version + ), + ) + + if module.check_mode: + module.exit_json( + changed=True, + msg="Would have upgraded domain from {0} to {1} if not in check mode".format( + current_version, next_version + ), + ) + current_version = next_version + + if module.params.get("wait"): + wait_for_domain_status(client, module, domain_name, "domain_available") + + +def set_cluster_config( + module, current_domain_config, desired_domain_config, change_set +): + changed = False + + cluster_config = desired_domain_config["ClusterConfig"] + cluster_opts = module.params.get("cluster_config") + if cluster_opts is not None: + if cluster_opts.get("instance_type") is not None: + cluster_config["InstanceType"] = cluster_opts.get("instance_type") + if cluster_opts.get("instance_count") is not None: + cluster_config["InstanceCount"] = cluster_opts.get("instance_count") + if cluster_opts.get("zone_awareness") is not None: + cluster_config["ZoneAwarenessEnabled"] = cluster_opts.get("zone_awareness") + if cluster_config["ZoneAwarenessEnabled"]: + if cluster_opts.get("availability_zone_count") is not None: + cluster_config["ZoneAwarenessConfig"] = { + "AvailabilityZoneCount": cluster_opts.get( + "availability_zone_count" + ), + } + + if cluster_opts.get("dedicated_master") is not None: + cluster_config["DedicatedMasterEnabled"] = cluster_opts.get( + "dedicated_master" + ) + if cluster_config["DedicatedMasterEnabled"]: + if cluster_opts.get("dedicated_master_instance_type") is not None: + cluster_config["DedicatedMasterType"] = cluster_opts.get( + "dedicated_master_instance_type" + ) + if cluster_opts.get("dedicated_master_instance_count") is not None: + cluster_config["DedicatedMasterCount"] = cluster_opts.get( + "dedicated_master_instance_count" + ) + + if cluster_opts.get("warm_enabled") is not None: + cluster_config["WarmEnabled"] = cluster_opts.get("warm_enabled") + if cluster_config["WarmEnabled"]: + if cluster_opts.get("warm_type") is not None: + cluster_config["WarmType"] = cluster_opts.get("warm_type") + if cluster_opts.get("warm_count") is not None: + cluster_config["WarmCount"] = cluster_opts.get("warm_count") + + cold_storage_opts = None + if cluster_opts is not None: + cold_storage_opts = cluster_opts.get("cold_storage_options") + if compare_domain_versions(desired_domain_config["EngineVersion"], "Elasticsearch_7.9") < 0: + # If the engine version is ElasticSearch < 7.9, cold storage is not supported. + # When querying a domain < 7.9, the AWS API indicates cold storage is disabled (Enabled: False), + # which makes sense. However, trying to do HTTP POST with Enable: False causes an API error. + # The 'ColdStorageOptions' attribute should not be present in HTTP POST. + if cold_storage_opts is not None and cold_storage_opts.get("enabled"): + module.fail_json(msg="Cold Storage is not supported") + cluster_config.pop("ColdStorageOptions", None) + if ( + current_domain_config is not None + and "ClusterConfig" in current_domain_config + ): + # Remove 'ColdStorageOptions' from the current domain config, otherwise the actual vs desired diff + # will indicate a change must be done. + current_domain_config["ClusterConfig"].pop("ColdStorageOptions", None) + else: + # Elasticsearch 7.9 and above support ColdStorageOptions. + if ( + cold_storage_opts is not None + and cold_storage_opts.get("enabled") is not None + ): + cluster_config["ColdStorageOptions"] = { + "Enabled": cold_storage_opts.get("enabled"), + } + + if ( + current_domain_config is not None + and current_domain_config["ClusterConfig"] != cluster_config + ): + change_set.append( + "ClusterConfig changed from {0} to {1}".format( + current_domain_config["ClusterConfig"], cluster_config + ) + ) + changed = True + return changed + + +def set_ebs_options(module, current_domain_config, desired_domain_config, change_set): + changed = False + ebs_config = desired_domain_config["EBSOptions"] + ebs_opts = module.params.get("ebs_options") + if ebs_opts is None: + return changed + if ebs_opts.get("ebs_enabled") is not None: + ebs_config["EBSEnabled"] = ebs_opts.get("ebs_enabled") + + if not ebs_config["EBSEnabled"]: + desired_domain_config["EBSOptions"] = { + "EBSEnabled": False, + } + else: + if ebs_opts.get("volume_type") is not None: + ebs_config["VolumeType"] = ebs_opts.get("volume_type") + if ebs_opts.get("volume_size") is not None: + ebs_config["VolumeSize"] = ebs_opts.get("volume_size") + if ebs_opts.get("iops") is not None: + ebs_config["Iops"] = ebs_opts.get("iops") + + if ( + current_domain_config is not None + and current_domain_config["EBSOptions"] != ebs_config + ): + change_set.append( + "EBSOptions changed from {0} to {1}".format( + current_domain_config["EBSOptions"], ebs_config + ) + ) + changed = True + return changed + + +def set_encryption_at_rest_options( + module, current_domain_config, desired_domain_config, change_set +): + changed = False + encryption_at_rest_config = desired_domain_config["EncryptionAtRestOptions"] + encryption_at_rest_opts = module.params.get("encryption_at_rest_options") + if encryption_at_rest_opts is None: + return False + if encryption_at_rest_opts.get("enabled") is not None: + encryption_at_rest_config["Enabled"] = encryption_at_rest_opts.get("enabled") + if not encryption_at_rest_config["Enabled"]: + desired_domain_config["EncryptionAtRestOptions"] = { + "Enabled": False, + } + else: + if encryption_at_rest_opts.get("kms_key_id") is not None: + encryption_at_rest_config["KmsKeyId"] = encryption_at_rest_opts.get( + "kms_key_id" + ) + + if ( + current_domain_config is not None + and current_domain_config["EncryptionAtRestOptions"] + != encryption_at_rest_config + ): + change_set.append( + "EncryptionAtRestOptions changed from {0} to {1}".format( + current_domain_config["EncryptionAtRestOptions"], + encryption_at_rest_config, + ) + ) + changed = True + return changed + + +def set_node_to_node_encryption_options( + module, current_domain_config, desired_domain_config, change_set +): + changed = False + node_to_node_encryption_config = desired_domain_config[ + "NodeToNodeEncryptionOptions" + ] + node_to_node_encryption_opts = module.params.get("node_to_node_encryption_options") + if node_to_node_encryption_opts is None: + return changed + if node_to_node_encryption_opts.get("enabled") is not None: + node_to_node_encryption_config["Enabled"] = node_to_node_encryption_opts.get( + "enabled" + ) + + if ( + current_domain_config is not None + and current_domain_config["NodeToNodeEncryptionOptions"] + != node_to_node_encryption_config + ): + change_set.append( + "NodeToNodeEncryptionOptions changed from {0} to {1}".format( + current_domain_config["NodeToNodeEncryptionOptions"], + node_to_node_encryption_config, + ) + ) + changed = True + return changed + + +def set_vpc_options(module, current_domain_config, desired_domain_config, change_set): + changed = False + vpc_config = None + if "VPCOptions" in desired_domain_config: + vpc_config = desired_domain_config["VPCOptions"] + vpc_opts = module.params.get("vpc_options") + if vpc_opts is None: + return changed + vpc_subnets = vpc_opts.get("subnets") + if vpc_subnets is not None: + if vpc_config is None: + vpc_config = {} + desired_domain_config["VPCOptions"] = vpc_config + # OpenSearch cluster is attached to VPC + if isinstance(vpc_subnets, string_types): + vpc_subnets = [x.strip() for x in vpc_subnets.split(",")] + vpc_config["SubnetIds"] = vpc_subnets + + vpc_security_groups = vpc_opts.get("security_groups") + if vpc_security_groups is not None: + if vpc_config is None: + vpc_config = {} + desired_domain_config["VPCOptions"] = vpc_config + if isinstance(vpc_security_groups, string_types): + vpc_security_groups = [x.strip() for x in vpc_security_groups.split(",")] + vpc_config["SecurityGroupIds"] = vpc_security_groups + + if current_domain_config is not None: + # Modify existing cluster. + current_cluster_is_vpc = False + desired_cluster_is_vpc = False + if ( + "VPCOptions" in current_domain_config + and "SubnetIds" in current_domain_config["VPCOptions"] + and len(current_domain_config["VPCOptions"]["SubnetIds"]) > 0 + ): + current_cluster_is_vpc = True + if ( + "VPCOptions" in desired_domain_config + and "SubnetIds" in desired_domain_config["VPCOptions"] + and len(desired_domain_config["VPCOptions"]["SubnetIds"]) > 0 + ): + desired_cluster_is_vpc = True + if current_cluster_is_vpc != desired_cluster_is_vpc: + # AWS does not allow changing the type. Don't fail here so we return the AWS API error. + change_set.append("VPCOptions changed between Internet and VPC") + changed = True + elif desired_cluster_is_vpc is False: + # There are no VPCOptions to configure. + pass + else: + # Note the subnets may be the same but be listed in a different order. + if set(current_domain_config["VPCOptions"]["SubnetIds"]) != set( + vpc_config["SubnetIds"] + ): + change_set.append( + "SubnetIds changed from {0} to {1}".format( + current_domain_config["VPCOptions"]["SubnetIds"], + vpc_config["SubnetIds"], + ) + ) + changed = True + if set(current_domain_config["VPCOptions"]["SecurityGroupIds"]) != set( + vpc_config["SecurityGroupIds"] + ): + change_set.append( + "SecurityGroup changed from {0} to {1}".format( + current_domain_config["VPCOptions"]["SecurityGroupIds"], + vpc_config["SecurityGroupIds"], + ) + ) + changed = True + return changed + + +def set_snapshot_options( + module, current_domain_config, desired_domain_config, change_set +): + changed = False + snapshot_config = desired_domain_config["SnapshotOptions"] + snapshot_opts = module.params.get("snapshot_options") + if snapshot_opts is None: + return changed + if snapshot_opts.get("automated_snapshot_start_hour") is not None: + snapshot_config["AutomatedSnapshotStartHour"] = snapshot_opts.get( + "automated_snapshot_start_hour" + ) + if ( + current_domain_config is not None + and current_domain_config["SnapshotOptions"] != snapshot_config + ): + change_set.append("SnapshotOptions changed") + changed = True + return changed + + +def set_cognito_options( + module, current_domain_config, desired_domain_config, change_set +): + changed = False + cognito_config = desired_domain_config["CognitoOptions"] + cognito_opts = module.params.get("cognito_options") + if cognito_opts is None: + return changed + if cognito_opts.get("enabled") is not None: + cognito_config["Enabled"] = cognito_opts.get("enabled") + if not cognito_config["Enabled"]: + desired_domain_config["CognitoOptions"] = { + "Enabled": False, + } + else: + if cognito_opts.get("cognito_user_pool_id") is not None: + cognito_config["UserPoolId"] = cognito_opts.get("cognito_user_pool_id") + if cognito_opts.get("cognito_identity_pool_id") is not None: + cognito_config["IdentityPoolId"] = cognito_opts.get( + "cognito_identity_pool_id" + ) + if cognito_opts.get("cognito_role_arn") is not None: + cognito_config["RoleArn"] = cognito_opts.get("cognito_role_arn") + + if ( + current_domain_config is not None + and current_domain_config["CognitoOptions"] != cognito_config + ): + change_set.append( + "CognitoOptions changed from {0} to {1}".format( + current_domain_config["CognitoOptions"], cognito_config + ) + ) + changed = True + return changed + + +def set_advanced_security_options( + module, current_domain_config, desired_domain_config, change_set +): + changed = False + advanced_security_config = desired_domain_config["AdvancedSecurityOptions"] + advanced_security_opts = module.params.get("advanced_security_options") + if advanced_security_opts is None: + return changed + if advanced_security_opts.get("enabled") is not None: + advanced_security_config["Enabled"] = advanced_security_opts.get("enabled") + if not advanced_security_config["Enabled"]: + desired_domain_config["AdvancedSecurityOptions"] = { + "Enabled": False, + } + else: + if advanced_security_opts.get("internal_user_database_enabled") is not None: + advanced_security_config[ + "InternalUserDatabaseEnabled" + ] = advanced_security_opts.get("internal_user_database_enabled") + master_user_opts = advanced_security_opts.get("master_user_options") + if master_user_opts is not None: + if master_user_opts.get("master_user_arn") is not None: + advanced_security_config["MasterUserOptions"][ + "MasterUserARN" + ] = master_user_opts.get("master_user_arn") + if master_user_opts.get("master_user_name") is not None: + advanced_security_config["MasterUserOptions"][ + "MasterUserName" + ] = master_user_opts.get("master_user_name") + if master_user_opts.get("master_user_password") is not None: + advanced_security_config["MasterUserOptions"][ + "MasterUserPassword" + ] = master_user_opts.get("master_user_password") + saml_opts = advanced_security_opts.get("saml_options") + if saml_opts is not None: + if saml_opts.get("enabled") is not None: + advanced_security_config["SamlOptions"]["Enabled"] = saml_opts.get( + "enabled" + ) + idp_opts = saml_opts.get("idp") + if idp_opts is not None: + if idp_opts.get("metadata_content") is not None: + advanced_security_config["SamlOptions"]["Idp"][ + "MetadataContent" + ] = idp_opts.get("metadata_content") + if idp_opts.get("entity_id") is not None: + advanced_security_config["SamlOptions"]["Idp"][ + "EntityId" + ] = idp_opts.get("entity_id") + if saml_opts.get("master_user_name") is not None: + advanced_security_config["SamlOptions"][ + "MasterUserName" + ] = saml_opts.get("master_user_name") + if saml_opts.get("master_backend_role") is not None: + advanced_security_config["SamlOptions"][ + "MasterBackendRole" + ] = saml_opts.get("master_backend_role") + if saml_opts.get("subject_key") is not None: + advanced_security_config["SamlOptions"]["SubjectKey"] = saml_opts.get( + "subject_key" + ) + if saml_opts.get("roles_key") is not None: + advanced_security_config["SamlOptions"]["RolesKey"] = saml_opts.get( + "roles_key" + ) + if saml_opts.get("session_timeout_minutes") is not None: + advanced_security_config["SamlOptions"][ + "SessionTimeoutMinutes" + ] = saml_opts.get("session_timeout_minutes") + + if ( + current_domain_config is not None + and current_domain_config["AdvancedSecurityOptions"] != advanced_security_config + ): + change_set.append( + "AdvancedSecurityOptions changed from {0} to {1}".format( + current_domain_config["AdvancedSecurityOptions"], + advanced_security_config, + ) + ) + changed = True + return changed + + +def set_domain_endpoint_options( + module, current_domain_config, desired_domain_config, change_set +): + changed = False + domain_endpoint_config = desired_domain_config["DomainEndpointOptions"] + domain_endpoint_opts = module.params.get("domain_endpoint_options") + if domain_endpoint_opts is None: + return changed + if domain_endpoint_opts.get("enforce_https") is not None: + domain_endpoint_config["EnforceHTTPS"] = domain_endpoint_opts.get( + "enforce_https" + ) + if domain_endpoint_opts.get("tls_security_policy") is not None: + domain_endpoint_config["TLSSecurityPolicy"] = domain_endpoint_opts.get( + "tls_security_policy" + ) + if domain_endpoint_opts.get("custom_endpoint_enabled") is not None: + domain_endpoint_config["CustomEndpointEnabled"] = domain_endpoint_opts.get( + "custom_endpoint_enabled" + ) + if domain_endpoint_config["CustomEndpointEnabled"]: + if domain_endpoint_opts.get("custom_endpoint") is not None: + domain_endpoint_config["CustomEndpoint"] = domain_endpoint_opts.get( + "custom_endpoint" + ) + if domain_endpoint_opts.get("custom_endpoint_certificate_arn") is not None: + domain_endpoint_config[ + "CustomEndpointCertificateArn" + ] = domain_endpoint_opts.get("custom_endpoint_certificate_arn") + + if ( + current_domain_config is not None + and current_domain_config["DomainEndpointOptions"] != domain_endpoint_config + ): + change_set.append( + "DomainEndpointOptions changed from {0} to {1}".format( + current_domain_config["DomainEndpointOptions"], domain_endpoint_config + ) + ) + changed = True + return changed + + +def set_auto_tune_options( + module, current_domain_config, desired_domain_config, change_set +): + changed = False + auto_tune_config = desired_domain_config["AutoTuneOptions"] + auto_tune_opts = module.params.get("auto_tune_options") + if auto_tune_opts is None: + return changed + schedules = auto_tune_opts.get("maintenance_schedules") + if auto_tune_opts.get("desired_state") is not None: + auto_tune_config["DesiredState"] = auto_tune_opts.get("desired_state") + if auto_tune_config["DesiredState"] != "ENABLED": + desired_domain_config["AutoTuneOptions"] = { + "DesiredState": "DISABLED", + } + elif schedules is not None: + auto_tune_config["MaintenanceSchedules"] = [] + for s in schedules: + schedule_entry = {} + start_at = s.get("start_at") + if start_at is not None: + if isinstance(start_at, datetime.datetime): + # The property was parsed from yaml to datetime, but the AWS API wants a string + start_at = start_at.strftime("%Y-%m-%d") + schedule_entry["StartAt"] = start_at + duration_opt = s.get("duration") + if duration_opt is not None: + schedule_entry["Duration"] = {} + if duration_opt.get("value") is not None: + schedule_entry["Duration"]["Value"] = duration_opt.get("value") + if duration_opt.get("unit") is not None: + schedule_entry["Duration"]["Unit"] = duration_opt.get("unit") + if s.get("cron_expression_for_recurrence") is not None: + schedule_entry["CronExpressionForRecurrence"] = s.get( + "cron_expression_for_recurrence" + ) + auto_tune_config["MaintenanceSchedules"].append(schedule_entry) + if current_domain_config is not None: + if ( + current_domain_config["AutoTuneOptions"]["DesiredState"] + != auto_tune_config["DesiredState"] + ): + change_set.append( + "AutoTuneOptions.DesiredState changed from {0} to {1}".format( + current_domain_config["AutoTuneOptions"]["DesiredState"], + auto_tune_config["DesiredState"], + ) + ) + changed = True + if ( + auto_tune_config["MaintenanceSchedules"] + != current_domain_config["AutoTuneOptions"]["MaintenanceSchedules"] + ): + change_set.append( + "AutoTuneOptions.MaintenanceSchedules changed from {0} to {1}".format( + current_domain_config["AutoTuneOptions"]["MaintenanceSchedules"], + auto_tune_config["MaintenanceSchedules"], + ) + ) + changed = True + return changed + + +def set_access_policy(module, current_domain_config, desired_domain_config, change_set): + access_policy_config = None + changed = False + access_policy_opt = module.params.get("access_policies") + if access_policy_opt is None: + return changed + try: + access_policy_config = json.dumps(access_policy_opt) + except Exception as e: + module.fail_json( + msg="Failed to convert the policy into valid JSON: %s" % str(e) + ) + if current_domain_config is not None: + # Updating existing domain + current_access_policy = json.loads(current_domain_config["AccessPolicies"]) + if not compare_policies(current_access_policy, access_policy_opt): + change_set.append( + "AccessPolicy changed from {0} to {1}".format( + current_access_policy, access_policy_opt + ) + ) + changed = True + desired_domain_config["AccessPolicies"] = access_policy_config + else: + # Creating new domain + desired_domain_config["AccessPolicies"] = access_policy_config + return changed + + +def ensure_domain_present(client, module): + domain_name = module.params.get("domain_name") + + # Create default if OpenSearch does not exist. If domain already exists, + # the data is populated by retrieving the current configuration from the API. + desired_domain_config = { + "DomainName": module.params.get("domain_name"), + "EngineVersion": "OpenSearch_1.1", + "ClusterConfig": { + "InstanceType": "t2.small.search", + "InstanceCount": 2, + "ZoneAwarenessEnabled": False, + "DedicatedMasterEnabled": False, + "WarmEnabled": False, + }, + # By default create ES attached to the Internet. + # If the "VPCOptions" property is specified, even if empty, the API server interprets + # as incomplete VPC configuration. + # "VPCOptions": {}, + "EBSOptions": { + "EBSEnabled": False, + }, + "EncryptionAtRestOptions": { + "Enabled": False, + }, + "NodeToNodeEncryptionOptions": { + "Enabled": False, + }, + "SnapshotOptions": { + "AutomatedSnapshotStartHour": 0, + }, + "CognitoOptions": { + "Enabled": False, + }, + "AdvancedSecurityOptions": { + "Enabled": False, + }, + "DomainEndpointOptions": { + "CustomEndpointEnabled": False, + }, + "AutoTuneOptions": { + "DesiredState": "DISABLED", + }, + } + # Determine if OpenSearch domain already exists. + # current_domain_config may be None if the domain does not exist. + (current_domain_config, domain_arn) = get_domain_config(client, module, domain_name) + if current_domain_config is not None: + desired_domain_config = deepcopy(current_domain_config) + + if module.params.get("engine_version") is not None: + # Validate the engine_version + v = parse_version(module.params.get("engine_version")) + if v is None: + module.fail_json( + "Invalid engine_version. Must be Elasticsearch_X.Y or OpenSearch_X.Y" + ) + desired_domain_config["EngineVersion"] = module.params.get("engine_version") + + changed = False + change_set = [] # For check mode purpose + + changed |= set_cluster_config( + module, current_domain_config, desired_domain_config, change_set + ) + changed |= set_ebs_options( + module, current_domain_config, desired_domain_config, change_set + ) + changed |= set_encryption_at_rest_options( + module, current_domain_config, desired_domain_config, change_set + ) + changed |= set_node_to_node_encryption_options( + module, current_domain_config, desired_domain_config, change_set + ) + changed |= set_vpc_options( + module, current_domain_config, desired_domain_config, change_set + ) + changed |= set_snapshot_options( + module, current_domain_config, desired_domain_config, change_set + ) + changed |= set_cognito_options( + module, current_domain_config, desired_domain_config, change_set + ) + changed |= set_advanced_security_options( + module, current_domain_config, desired_domain_config, change_set + ) + changed |= set_domain_endpoint_options( + module, current_domain_config, desired_domain_config, change_set + ) + changed |= set_auto_tune_options( + module, current_domain_config, desired_domain_config, change_set + ) + changed |= set_access_policy( + module, current_domain_config, desired_domain_config, change_set + ) + + if current_domain_config is not None: + if ( + desired_domain_config["EngineVersion"] + != current_domain_config["EngineVersion"] + ): + changed = True + change_set.append("EngineVersion changed") + upgrade_domain( + client, + module, + current_domain_config["EngineVersion"], + desired_domain_config["EngineVersion"], + ) + + if changed: + if module.check_mode: + module.exit_json( + changed=True, + msg=f"Would have updated domain if not in check mode: {change_set}", + ) + # Remove the "EngineVersion" attribute, the AWS API does not accept this attribute. + desired_domain_config.pop("EngineVersion", None) + try: + client.update_domain_config(**desired_domain_config) + except ( + botocore.exceptions.BotoCoreError, + botocore.exceptions.ClientError, + ) as e: + module.fail_json_aws( + e, msg="Couldn't update domain {0}".format(domain_name) + ) + + else: + # Create new OpenSearch cluster + if module.params.get("access_policies") is None: + module.fail_json( + "state is present but the following is missing: access_policies" + ) + + changed = True + if module.check_mode: + module.exit_json( + changed=True, msg="Would have created a domain if not in check mode" + ) + try: + response = client.create_domain(**desired_domain_config) + domain = response["DomainStatus"] + domain_arn = domain["ARN"] + except ( + botocore.exceptions.BotoCoreError, + botocore.exceptions.ClientError, + ) as e: + module.fail_json_aws( + e, msg="Couldn't update domain {0}".format(domain_name) + ) + + try: + existing_tags = boto3_tag_list_to_ansible_dict( + client.list_tags(ARN=domain_arn, aws_retry=True)["TagList"] + ) + except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: + module.fail_json_aws(e, "Couldn't get tags for domain %s" % domain_name) + + desired_tags = module.params["tags"] + purge_tags = module.params["purge_tags"] + changed |= ensure_tags( + client, module, domain_arn, existing_tags, desired_tags, purge_tags + ) + + if module.params.get("wait") and not module.check_mode: + wait_for_domain_status(client, module, domain_name, "domain_available") + + domain = get_domain_status(client, module, domain_name) + + return dict(changed=changed, **normalize_opensearch(client, module, domain)) + + +def main(): + + module = AnsibleAWSModule( + argument_spec=dict( + state=dict(choices=["present", "absent"], default="present"), + domain_name=dict(required=True), + engine_version=dict(), + allow_intermediate_upgrades=dict(required=False, type="bool", default=True), + access_policies=dict(required=False, type="dict"), + cluster_config=dict( + type="dict", + default=None, + options=dict( + instance_type=dict(), + instance_count=dict(required=False, type="int"), + zone_awareness=dict(required=False, type="bool"), + availability_zone_count=dict(required=False, type="int"), + dedicated_master=dict(required=False, type="bool"), + dedicated_master_instance_type=dict(), + dedicated_master_instance_count=dict(type="int"), + warm_enabled=dict(required=False, type="bool"), + warm_type=dict(required=False), + warm_count=dict(required=False, type="int"), + cold_storage_options=dict( + type="dict", + default=None, + options=dict( + enabled=dict(required=False, type="bool"), + ), + ), + ), + ), + snapshot_options=dict( + type="dict", + default=None, + options=dict( + automated_snapshot_start_hour=dict(required=False, type="int"), + ), + ), + ebs_options=dict( + type="dict", + default=None, + options=dict( + ebs_enabled=dict(required=False, type="bool"), + volume_type=dict(required=False), + volume_size=dict(required=False, type="int"), + iops=dict(required=False, type="int"), + ), + ), + vpc_options=dict( + type="dict", + default=None, + options=dict( + subnets=dict(type="list", elements="str", required=False), + security_groups=dict(type="list", elements="str", required=False), + ), + ), + cognito_options=dict( + type="dict", + default=None, + options=dict( + enabled=dict(required=False, type="bool"), + user_pool_id=dict(required=False), + identity_pool_id=dict(required=False), + role_arn=dict(required=False, no_log=False), + ), + ), + encryption_at_rest_options=dict( + type="dict", + default=None, + options=dict( + enabled=dict(type="bool"), + kms_key_id=dict(required=False), + ), + ), + node_to_node_encryption_options=dict( + type="dict", + default=None, + options=dict( + enabled=dict(type="bool"), + ), + ), + domain_endpoint_options=dict( + type="dict", + default=None, + options=dict( + enforce_https=dict(type="bool"), + tls_security_policy=dict(), + custom_endpoint_enabled=dict(type="bool"), + custom_endpoint=dict(), + custom_endpoint_certificate_arn=dict(), + ), + ), + advanced_security_options=dict( + type="dict", + default=None, + options=dict( + enabled=dict(type="bool"), + internal_user_database_enabled=dict(type="bool"), + master_user_options=dict( + type="dict", + default=None, + options=dict( + master_user_arn=dict(), + master_user_name=dict(), + master_user_password=dict(no_log=True), + ), + ), + saml_options=dict( + type="dict", + default=None, + options=dict( + enabled=dict(type="bool"), + idp=dict( + type="dict", + default=None, + options=dict( + metadata_content=dict(), + entity_id=dict(), + ), + ), + master_user_name=dict(), + master_backend_role=dict(), + subject_key=dict(no_log=False), + roles_key=dict(no_log=False), + session_timeout_minutes=dict(type="int"), + ), + ), + ), + ), + auto_tune_options=dict( + type="dict", + default=None, + options=dict( + desired_state=dict(choices=["ENABLED", "DISABLED"]), + maintenance_schedules=dict( + type="list", + elements="dict", + default=None, + options=dict( + start_at=dict(), + duration=dict( + type="dict", + default=None, + options=dict( + value=dict(type="int"), + unit=dict(choices=["HOURS"]), + ), + ), + cron_expression_for_recurrence=dict(), + ), + ), + ), + ), + tags=dict(type="dict"), + purge_tags=dict(type="bool", default=True), + wait=dict(type="bool", default=False), + wait_timeout=dict(type="int", default=300), + ), + supports_check_mode=True, + ) + + module.require_botocore_at_least("1.21.38") + + try: + client = module.client("opensearch", retry_decorator=AWSRetry.jittered_backoff()) + except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: + module.fail_json_aws(e, msg="Failed to connect to AWS opensearch service") + + if module.params["state"] == "absent": + ret_dict = ensure_domain_absent(client, module) + else: + ret_dict = ensure_domain_present(client, module) + + module.exit_json(**ret_dict) + + +if __name__ == "__main__": + main() diff --git a/plugins/modules/opensearch_info.py b/plugins/modules/opensearch_info.py new file mode 100644 --- /dev/null +++ b/plugins/modules/opensearch_info.py @@ -0,0 +1,530 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# Copyright: Ansible Project +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + +DOCUMENTATION = """ +--- +module: opensearch_info +short_description: obtain information about one or more OpenSearch or ElasticSearch domain. +description: + - obtain information about one Amazon OpenSearch Service domain. +version_added: 3.1.0 +author: "Sebastien Rosset (@sebastien-rosset)" +options: + domain_name: + description: + - The name of the Amazon OpenSearch/ElasticSearch Service domain. + required: false + type: str + tags: + description: + - > + A dict of tags that are used to filter OpenSearch domains that match + all tag key, value pairs. + required: false + type: dict +requirements: +- botocore >= 1.21.38 +extends_documentation_fragment: +- amazon.aws.aws +- amazon.aws.ec2 +""" + +EXAMPLES = ''' +- name: Get information about an OpenSearch domain instance + community.aws.opensearch_info: + domain-name: my-search-cluster + register: new_cluster_info + +- name: Get all OpenSearch instances + community.aws.opensearch_info: + +- name: Get all OpenSearch instances that have the specified Key, Value tags + community.aws.opensearch_info: + tags: + Applications: search + Environment: Development +''' + +RETURN = ''' +instances: + description: List of OpenSearch domain instances + returned: always + type: complex + contains: + domain_status: + description: The current status of the OpenSearch domain. + returned: always + type: complex + contains: + arn: + description: The ARN of the OpenSearch domain. + returned: always + type: str + domain_id: + description: The unique identifier for the OpenSearch domain. + returned: always + type: str + domain_name: + description: The name of the OpenSearch domain. + returned: always + type: str + created: + description: + - > + The domain creation status. True if the creation of a domain is complete. + False if domain creation is still in progress. + returned: always + type: bool + deleted: + description: + - > + The domain deletion status. + True if a delete request has been received for the domain but resource cleanup is still in progress. + False if the domain has not been deleted. + Once domain deletion is complete, the status of the domain is no longer returned. + returned: always + type: bool + endpoint: + description: The domain endpoint that you use to submit index and search requests. + returned: always + type: str + endpoints: + description: + - > + Map containing the domain endpoints used to submit index and search requests. + - > + When you create a domain attached to a VPC domain, this propery contains + the DNS endpoint to which service requests are submitted. + - > + If you query the opensearch_info immediately after creating the OpenSearch cluster, + the VPC endpoint may not be returned. It may take several minutes until the + endpoints is available. + type: dict + processing: + description: + - > + The status of the domain configuration. + True if Amazon OpenSearch Service is processing configuration changes. + False if the configuration is active. + returned: always + type: bool + upgrade_processing: + description: true if a domain upgrade operation is in progress. + returned: always + type: bool + engine_version: + description: The version of the OpenSearch domain. + returned: always + type: str + sample: OpenSearch_1.1 + cluster_config: + description: + - Parameters for the cluster configuration of an OpenSearch Service domain. + type: complex + contains: + instance_type: + description: + - Type of the instances to use for the domain. + type: str + instance_count: + description: + - Number of instances for the domain. + type: int + zone_awareness: + description: + - A boolean value to indicate whether zone awareness is enabled. + type: bool + availability_zone_count: + description: + - > + An integer value to indicate the number of availability zones for a domain when zone awareness is enabled. + This should be equal to number of subnets if VPC endpoints is enabled. + type: int + dedicated_master_enabled: + description: + - A boolean value to indicate whether a dedicated master node is enabled. + type: bool + zone_awareness_enabled: + description: + - A boolean value to indicate whether zone awareness is enabled. + type: bool + zone_awareness_config: + description: + - The zone awareness configuration for a domain when zone awareness is enabled. + type: complex + contains: + availability_zone_count: + description: + - An integer value to indicate the number of availability zones for a domain when zone awareness is enabled. + type: int + dedicated_master_type: + description: + - The instance type for a dedicated master node. + type: str + dedicated_master_count: + description: + - Total number of dedicated master nodes, active and on standby, for the domain. + type: int + warm_enabled: + description: + - True to enable UltraWarm storage. + type: bool + warm_type: + description: + - The instance type for the OpenSearch domain's warm nodes. + type: str + warm_count: + description: + - The number of UltraWarm nodes in the domain. + type: int + cold_storage_options: + description: + - Specifies the ColdStorageOptions config for a Domain. + type: complex + contains: + enabled: + description: + - True to enable cold storage. Supported on Elasticsearch 7.9 or above. + type: bool + ebs_options: + description: + - Parameters to configure EBS-based storage for an OpenSearch Service domain. + type: complex + contains: + ebs_enabled: + description: + - Specifies whether EBS-based storage is enabled. + type: bool + volume_type: + description: + - Specifies the volume type for EBS-based storage. "standard"|"gp2"|"io1" + type: str + volume_size: + description: + - Integer to specify the size of an EBS volume. + type: int + iops: + description: + - The IOPD for a Provisioned IOPS EBS volume (SSD). + type: int + vpc_options: + description: + - Options to specify the subnets and security groups for a VPC endpoint. + type: complex + contains: + vpc_id: + description: The VPC ID for the domain. + type: str + subnet_ids: + description: + - Specifies the subnet ids for VPC endpoint. + type: list + elements: str + security_group_ids: + description: + - Specifies the security group ids for VPC endpoint. + type: list + elements: str + availability_zones: + description: + - The Availability Zones for the domain.. + type: list + elements: str + snapshot_options: + description: + - Option to set time, in UTC format, of the daily automated snapshot. + type: complex + contains: + automated_snapshot_start_hour: + description: + - > + Integer value from 0 to 23 specifying when the service takes a daily automated snapshot + of the specified Elasticsearch domain. + type: int + access_policies: + description: + - IAM access policy as a JSON-formatted string. + type: complex + encryption_at_rest_options: + description: + - Parameters to enable encryption at rest. + type: complex + contains: + enabled: + description: + - Should data be encrypted while at rest. + type: bool + kms_key_id: + description: + - If encryption at rest enabled, this identifies the encryption key to use. + - The value should be a KMS key ARN. It can also be the KMS key id. + type: str + node_to_node_encryption_options: + description: + - Node-to-node encryption options. + type: complex + contains: + enabled: + description: + - True to enable node-to-node encryption. + type: bool + cognito_options: + description: + - Parameters to configure OpenSearch Service to use Amazon Cognito authentication for OpenSearch Dashboards. + type: complex + contains: + enabled: + description: + - The option to enable Cognito for OpenSearch Dashboards authentication. + type: bool + user_pool_id: + description: + - The Cognito user pool ID for OpenSearch Dashboards authentication. + type: str + identity_pool_id: + description: + - The Cognito identity pool ID for OpenSearch Dashboards authentication. + type: str + role_arn: + description: + - The role ARN that provides OpenSearch permissions for accessing Cognito resources. + type: str + domain_endpoint_options: + description: + - Options to specify configuration that will be applied to the domain endpoint. + type: complex + contains: + enforce_https: + description: + - Whether only HTTPS endpoint should be enabled for the domain. + type: bool + tls_security_policy: + description: + - Specify the TLS security policy to apply to the HTTPS endpoint of the domain. + type: str + custom_endpoint_enabled: + description: + - Whether to enable a custom endpoint for the domain. + type: bool + custom_endpoint: + description: + - The fully qualified domain for your custom endpoint. + type: str + custom_endpoint_certificate_arn: + description: + - The ACM certificate ARN for your custom endpoint. + type: str + advanced_security_options: + description: + - Specifies advanced security options. + type: complex + contains: + enabled: + description: + - True if advanced security is enabled. + - You must enable node-to-node encryption to use advanced security options. + type: bool + internal_user_database_enabled: + description: + - True if the internal user database is enabled. + type: bool + master_user_options: + description: + - Credentials for the master user, username and password, ARN, or both. + type: complex + contains: + master_user_arn: + description: + - ARN for the master user (if IAM is enabled). + type: str + master_user_name: + description: + - The username of the master user, which is stored in the Amazon OpenSearch Service domain internal database. + type: str + master_user_password: + description: + - The password of the master user, which is stored in the Amazon OpenSearch Service domain internal database. + type: str + saml_options: + description: + - The SAML application configuration for the domain. + type: complex + contains: + enabled: + description: + - True if SAML is enabled. + type: bool + idp: + description: + - The SAML Identity Provider's information. + type: complex + contains: + metadata_content: + description: + - The metadata of the SAML application in XML format. + type: str + entity_id: + description: + - The unique entity ID of the application in SAML identity provider. + type: str + master_user_name: + description: + - The SAML master username, which is stored in the Amazon OpenSearch Service domain internal database. + type: str + master_backend_role: + description: + - The backend role that the SAML master user is mapped to. + type: str + subject_key: + description: + - Element of the SAML assertion to use for username. Default is NameID. + type: str + roles_key: + description: + - Element of the SAML assertion to use for backend roles. Default is roles. + type: str + session_timeout_minutes: + description: + - > + The duration, in minutes, after which a user session becomes inactive. + Acceptable values are between 1 and 1440, and the default value is 60. + type: int + auto_tune_options: + description: + - Specifies Auto-Tune options. + type: complex + contains: + desired_state: + description: + - The Auto-Tune desired state. Valid values are ENABLED and DISABLED. + type: str + maintenance_schedules: + description: + - A list of maintenance schedules. + type: list + elements: dict + contains: + start_at: + description: + - The timestamp at which the Auto-Tune maintenance schedule starts. + type: str + duration: + description: + - Specifies maintenance schedule duration, duration value and duration unit. + type: complex + contains: + value: + description: + - Integer to specify the value of a maintenance schedule duration. + type: int + unit: + description: + - The unit of a maintenance schedule duration. Valid value is HOURS. + type: str + cron_expression_for_recurrence: + description: + - A cron expression for a recurring maintenance schedule. + type: str + domain_config: + description: The OpenSearch domain configuration + returned: always + type: complex + contains: + domain_name: + description: The name of the OpenSearch domain. + returned: always + type: str +''' + + +try: + import botocore +except ImportError: + pass # handled by AnsibleAWSModule + +from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import ( + AWSRetry, + boto3_tag_list_to_ansible_dict, + camel_dict_to_snake_dict, +) +from ansible_collections.community.aws.plugins.module_utils.opensearch import ( + get_domain_config, + get_domain_status, +) + + +def domain_info(client, module): + domain_name = module.params.get('domain_name') + filter_tags = module.params.get('tags') + + domain_list = [] + if domain_name: + domain_status = get_domain_status(client, module, domain_name) + if domain_status: + domain_list.append({'DomainStatus': domain_status}) + else: + domain_summary_list = client.list_domain_names()['DomainNames'] + for d in domain_summary_list: + domain_status = get_domain_status(client, module, d['DomainName']) + if domain_status: + domain_list.append({'DomainStatus': domain_status}) + + # Get the domain tags + for domain in domain_list: + current_domain_tags = None + domain_arn = domain['DomainStatus']['ARN'] + try: + current_domain_tags = client.list_tags(ARN=domain_arn, aws_retry=True)["TagList"] + domain['Tags'] = boto3_tag_list_to_ansible_dict(current_domain_tags) + except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: + # This could potentially happen if a domain is deleted between the time + # its domain status was queried and the tags were queried. + domain['Tags'] = {} + + # Filter by tags + if filter_tags: + for tag_key in filter_tags: + try: + domain_list = [c for c in domain_list if ('Tags' in c) and (tag_key in c['Tags']) and (c['Tags'][tag_key] == filter_tags[tag_key])] + except (TypeError, AttributeError) as e: + module.fail_json(msg="OpenSearch tag filtering error", exception=e) + + # Get the domain config + for idx, domain in enumerate(domain_list): + domain_name = domain['DomainStatus']['DomainName'] + (domain_config, arn) = get_domain_config(client, module, domain_name) + if domain_config: + domain['DomainConfig'] = domain_config + domain_list[idx] = camel_dict_to_snake_dict(domain, + ignore_list=['AdvancedOptions', 'Endpoints', 'Tags']) + + return dict(changed=False, domains=domain_list) + + +def main(): + module = AnsibleAWSModule( + argument_spec=dict( + domain_name=dict(required=False), + tags=dict(type='dict', required=False), + ), + supports_check_mode=True, + ) + module.require_botocore_at_least("1.21.38") + + try: + client = module.client("opensearch", retry_decorator=AWSRetry.jittered_backoff()) + except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: + module.fail_json_aws(e, msg="Failed to connect to AWS opensearch service") + + module.exit_json(**domain_info(client, module)) + + +if __name__ == '__main__': + main()
diff --git a/tests/integration/targets/opensearch/aliases b/tests/integration/targets/opensearch/aliases new file mode 100644 --- /dev/null +++ b/tests/integration/targets/opensearch/aliases @@ -0,0 +1,24 @@ +# reason: slow +# +# The duration of the tasks below was obtained from a single test job. +# There may be significant variations across runs. +# +# OpenSearch Cluster attached to Internet: +# 13 minutes to create ES cluster. Task is not waiting for cluster to become available. +# OpenSearch Cluster attached to VPC: +# 17 minutes to create ES cluster with 2 nodes and dedicated masters. +# 12 minutes to increase size of EBS volumes. +# 12 minutes to increase the node count from 2 to 4. +# 7 minutes to reduce the node count from 4 to 2. +# 35 minutes to upgrade cluster from 7.1 to 7.10. +# 23 minutes to enable node-to-node encryption. +# 36 minutes to enable encryption at rest. +# 30 minutes to enable warm storage. +# 30 minutes to enable cold storage. +# 30 minutes to enable and enforce HTTPS on the domain endpoint. +# 3 minutes to enable auto-tune option. +# 45 minutes to delete cluster. + +disabled + +cloud/aws diff --git a/tests/integration/targets/opensearch/defaults/main.yml b/tests/integration/targets/opensearch/defaults/main.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/opensearch/defaults/main.yml @@ -0,0 +1,2 @@ +--- +# defaults file for opensearch tests diff --git a/tests/integration/targets/opensearch/files/opensearch_policy.json b/tests/integration/targets/opensearch/files/opensearch_policy.json new file mode 100644 --- /dev/null +++ b/tests/integration/targets/opensearch/files/opensearch_policy.json @@ -0,0 +1,16 @@ +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Principal": { + "Service": "opensearch.amazonaws.com" + }, + "Action": [ + "es:*", + "kms:List*", + "kms:Describe*" + ] + } + ] +} diff --git a/tests/integration/targets/opensearch/meta/main.yml b/tests/integration/targets/opensearch/meta/main.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/opensearch/meta/main.yml @@ -0,0 +1,4 @@ +dependencies: + - role: setup_botocore_pip + vars: + botocore_version: "1.21.38" diff --git a/tests/integration/targets/opensearch/tasks/main.yml b/tests/integration/targets/opensearch/tasks/main.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/opensearch/tasks/main.yml @@ -0,0 +1,30 @@ +--- +# tasks file for test_opensearch +- name: Run opensearch integration tests. + + module_defaults: + group/aws: + aws_access_key: "{{ aws_access_key }}" + aws_secret_key: "{{ aws_secret_key }}" + security_token: "{{ security_token | default(omit) }}" + region: "{{ aws_region }}" + route53: + # Route53 is explicitly a global service + region: null + collections: + - amazon.aws + vars: + ansible_python_interpreter: "{{ botocore_virtualenv_interpreter }}" + + block: + # Get some information about who we are before starting our tests + # we'll need this as soon as we start working on the policies + - name: get ARN of calling user + aws_caller_info: + register: aws_caller_info + - include_tasks: test_delete_resources.yml + - include_tasks: test_create_cert.yml + - include_tasks: test_vpc_setup.yml + - include_tasks: test_opensearch.yml + always: + - include_tasks: test_delete_resources.yml diff --git a/tests/integration/targets/opensearch/tasks/test_create_cert.yml b/tests/integration/targets/opensearch/tasks/test_create_cert.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/opensearch/tasks/test_create_cert.yml @@ -0,0 +1,53 @@ +- pip: + name: + # The 'cryptography' module is required by community.crypto.openssl_privatekey + - 'cryptography' + virtualenv: "{{ botocore_virtualenv }}" + virtualenv_command: "{{ botocore_virtualenv_command }}" + virtualenv_site_packages: no +- name: Create temporary directory + ansible.builtin.tempfile: + state: directory + suffix: build + register: tempdir_1 +- name: Generate private key + community.crypto.openssl_privatekey: + path: '{{ tempdir_1.path }}/rsa-private-key.pem' + type: RSA + size: 2048 +- name: Generate an OpenSSL Certificate Signing Request for own certs + community.crypto.openssl_csr: + path: '{{ tempdir_1.path }}/rsa-csr.pem' + privatekey_path: '{{ tempdir_1.path }}/rsa-private-key.pem' + common_name: 'opensearch.ansible-integ-test.com' +- name: Generate a Self Signed certificate + community.crypto.x509_certificate: + provider: selfsigned + path: '{{ tempdir_1.path }}/rsa-certificate.pem' + csr_path: '{{ tempdir_1.path }}/rsa-csr.pem' + privatekey_path: '{{ tempdir_1.path }}/rsa-private-key.pem' + selfsigned_digest: sha256 +- name: import certificate to ACM + aws_acm: + name_tag: 'opensearch.ansible-integ-test.com' + domain_name: 'opensearch.ansible-integ-test.com' + certificate: "{{ lookup('file', tempdir_1.path + '/rsa-certificate.pem') }}" + private_key: "{{ lookup('file', tempdir_1.path + '/rsa-private-key.pem') }}" + state: present + # tags: + # Application: search + # Environment: development + # purge_tags: false + register: upload_cert +- assert: + that: + - upload_cert.certificate.arn is defined + - upload_cert.certificate.domain_name == 'opensearch.ansible-integ-test.com' + - upload_cert.changed + +- set_fact: + opensearch_certificate_arn: "{{ upload_cert.certificate.arn }}" +- name: Delete temporary directory + ansible.builtin.file: + state: absent + path: "{{ tempdir_1.path }}" \ No newline at end of file diff --git a/tests/integration/targets/opensearch/tasks/test_delete_resources.yml b/tests/integration/targets/opensearch/tasks/test_delete_resources.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/opensearch/tasks/test_delete_resources.yml @@ -0,0 +1,61 @@ +- name: Delete all resources that were created in the integration tests + block: + - name: Get list of OpenSearch domains + opensearch_info: + tags: + Environment: "Testing" + Application: "Search" + AnsibleTest: "AnsibleTestOpenSearchCluster" + register: opensearch_domains + + - name: Initiate deletion of all test-related OpenSearch clusters + opensearch: + state: absent + domain_name: "{{ domain_name }}" + with_items: "{{ opensearch_domains.domains }}" + vars: + domain_name: "{{ item.domain_status.domain_name }}" + + # We have to wait until the cluster is deleted before proceeding to delete + # security group, VPC, KMS. Otherwise there will be active references and + # deletion of the security group will fail. + - name: Delete OpenSearch clusters, wait until deletion is complete + opensearch: + state: absent + domain_name: "{{ domain_name }}" + wait: true + wait_timeout: "{{ 60 * 60 }}" + with_items: "{{ opensearch_domains.domains }}" + vars: + domain_name: "{{ item.domain_status.domain_name }}" + + - name: Get VPC info + ec2_vpc_net_info: + filters: + "tag:AnsibleTest": "AnsibleTestVpc" + register: vpc_info + + - name: delete VPC resources + include_tasks: test_delete_vpc_resources.yml + with_items: "{{ vpc_info.vpcs }}" + vars: + vpc_id: "{{ item.vpc_id }}" + vpc_name: "{{ item.tags['Name'] }}" + + - name: collect info about KMS keys used for test purpose + aws_kms_info: + filters: + "tag:AnsibleTest": "AnsibleTestVpc" + register: kms_info + - name: Delete KMS keys that were created for test purpose + aws_kms: + key_id: "{{ kms_arn }}" + state: absent + with_items: "{{ kms_info.kms_keys }}" + vars: + kms_arn: "{{ item.key_arn }}" + + - name: delete certificate from ACM + aws_acm: + name_tag: 'opensearch.ansible-integ-test.com' + state: absent diff --git a/tests/integration/targets/opensearch/tasks/test_delete_vpc_resources.yml b/tests/integration/targets/opensearch/tasks/test_delete_vpc_resources.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/opensearch/tasks/test_delete_vpc_resources.yml @@ -0,0 +1,92 @@ +- debug: + msg: "Deleting resources in VPC name: {{ vpc_name }}, id: {{ vpc_id }}" + +- name: Get the hosted Route53 zones + route53_info: + query: hosted_zone + hosted_zone_method: list + register: route53_zone_info + +- name: Get Route53 zone id + set_fact: + route53_zone_ids: "{{ route53_zone_info.HostedZones | selectattr('Name', 'equalto', 'ansible-integ-test.com.') | map(attribute='Id') | list }}" + +- name: Delete Route53 record + route53: + record: "opensearch.ansible-integ-test.com" + hosted_zone_id: "{{ route53_zone_ids[0] }}" + private_zone: true + type: CNAME + state: absent + vpc_id: '{{ vpc_id }}' + when: route53_zone_ids | length > 0 + +- name: Delete private Route53 zone for the VPC + route53_zone: + zone: "ansible-integ-test.com" + hosted_zone_id: "{{ route53_zone_ids[0] }}" + state: absent + vpc_id: '{{ vpc_id }}' + when: route53_zone_ids | length > 0 + +- name: Get security groups that have been created for test purpose in the VPC + ec2_group_info: + filters: + vpc-id: "{{ vpc_id }}" + register: sg_info + +- name: Delete security groups + ec2_group: + group_id: "{{ sg_id }}" + state: absent + loop_control: + loop_var: sg_item + with_items: "{{ sg_info.security_groups }}" + vars: + sg_id: "{{ sg_item.group_id }}" + sg_name: "{{ sg_item.group_name }}" + when: sg_name != 'default' + +- name: Delete internet gateway + ec2_vpc_igw: + vpc_id: "{{ vpc_id }}" + state: absent + +- name: Delete subnet_1 + ec2_vpc_subnet: + state: absent + vpc_id: "{{ vpc_id }}" + cidr: 10.55.77.0/24 + +- name: Delete subnet_2 + ec2_vpc_subnet: + state: absent + vpc_id: "{{ vpc_id }}" + cidr: 10.55.78.0/24 + +- name: Collect info about routing tables + ec2_vpc_route_table_info: + filters: + vpc-id: "{{ vpc_id }}" + # Exclude the main route table, which should not be deleted explicitly. + # It will be deleted automatically when the VPC is deleted + "tag:AnsibleTest": "AnsibleTestVpc" + register: routing_table_info + +- name: Delete routing tables + ec2_vpc_route_table: + state: absent + lookup: id + route_table_id: "{{ route_table_id }}" + loop_control: + loop_var: route_item + with_items: "{{ routing_table_info.route_tables }}" + vars: + route_table_id: "{{ route_item.id }}" + +- name: Delete VPC for use in testing + ec2_vpc_net: + name: "{{ vpc_name }}" + cidr_block: 10.55.0.0/16 + purge_cidrs: true + state: absent diff --git a/tests/integration/targets/opensearch/tasks/test_opensearch.yml b/tests/integration/targets/opensearch/tasks/test_opensearch.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/opensearch/tasks/test_opensearch.yml @@ -0,0 +1,1252 @@ +- name: Create OpenSearch clusters + block: + - name: test without specifying required module options + opensearch: + engine_version: "Elasticsearch_7.1" + ignore_errors: yes + register: result + + - name: assert domain_name is a required module option + assert: + that: + - "result.msg == 'missing required arguments: domain_name'" + + - name: Create public-facing OpenSearch cluster in check mode + opensearch: + state: present + domain_name: "es-{{ tiny_prefix }}-public" + engine_version: "OpenSearch_1.1" + cluster_config: + instance_type: "t2.small.search" + instance_count: 2 + dedicated_master: false + access_policies: "{{ lookup('file', 'opensearch_policy.json') | from_json }}" + ebs_options: + ebs_enabled: true + volume_size: 10 + tags: + Name: "es-{{ tiny_prefix }}-public" + Environment: Testing + Application: Search + AnsibleTest: "AnsibleTestOpenSearchCluster" + check_mode: true + register: opensearch_domain + - assert: + that: + - "opensearch_domain is changed" + + - name: Create public-facing OpenSearch cluster, changes expected + # This could take 30 minutes + opensearch: + state: present + # Note domain_name must be less than 28 characters and satisfy regex [a-z][a-z0-9\\-]+ + domain_name: "es-{{ tiny_prefix }}-public" + engine_version: "OpenSearch_1.1" + cluster_config: + instance_type: "t2.small.search" + instance_count: 2 + dedicated_master: false + access_policies: "{{ lookup('file', 'opensearch_policy.json') | from_json }}" + ebs_options: + # EBS must be enabled for "t2.small.search" + ebs_enabled: true + volume_size: 10 + tags: + # Note: The domain name must start with a letter, but the tiny prefix may start with + # a digit. + Name: "es-{{ tiny_prefix }}-public" + Environment: Testing + Application: Search + AnsibleTest: "AnsibleTestOpenSearchCluster" + # Intentionally not waiting for cluster to be available. + # All other integration tests are performed with the + # OpenSearch cluster attached to the VPC. + wait: false + register: opensearch_domain + - assert: + that: + - "opensearch_domain.tags | length == 4" + - "opensearch_domain.engine_version == 'OpenSearch_1.1'" + - "opensearch_domain.cluster_config.instance_count == 2" + - "opensearch_domain.cluster_config.instance_type == 't2.small.search'" + - "opensearch_domain.cluster_config.dedicated_master_enabled == false" + - "opensearch_domain.cluster_config.warm_enabled == false" + - "opensearch_domain.ebs_options.ebs_enabled == true" + - "opensearch_domain.ebs_options.volume_size == 10" + # Below should be default settings when not specified as input arguments + - "opensearch_domain.ebs_options.volume_type == 'gp2'" + - "opensearch_domain.advanced_security_options.enabled == false" + - "opensearch_domain.cognito_options.enabled == false" + - "opensearch_domain.domain_endpoint_options.custom_endpoint_enabled == false" + - "opensearch_domain.encryption_at_rest_options.enabled == false" + - "opensearch_domain.node_to_node_encryption_options.enabled == false" + - "opensearch_domain.snapshot_options.automated_snapshot_start_hour == 0" + # Assert task has changed/not changed OpenSearch domain + - "opensearch_domain is changed" + + - name: Create public-facing OpenSearch cluster in check mode again + opensearch: + state: present + domain_name: "es-{{ tiny_prefix }}-public" + engine_version: "OpenSearch_1.1" + cluster_config: + instance_type: "t2.small.search" + instance_count: 2 + dedicated_master: false + access_policies: "{{ lookup('file', 'opensearch_policy.json') | from_json }}" + ebs_options: + ebs_enabled: true + volume_size: 10 + tags: + Name: "es-{{ tiny_prefix }}-public" + Environment: Testing + Application: Search + AnsibleTest: "AnsibleTestOpenSearchCluster" + check_mode: true + register: opensearch_domain + - assert: + that: + - opensearch_domain is not changed + + - name: Create public-facing OpenSearch cluster, no change expected + opensearch: + state: present + domain_name: "es-{{ tiny_prefix }}-public" + engine_version: "OpenSearch_1.1" + cluster_config: + instance_type: "t2.small.search" + instance_count: 2 + dedicated_master: false + access_policies: "{{ lookup('file', 'opensearch_policy.json') | from_json }}" + ebs_options: + ebs_enabled: true + volume_size: 10 + tags: + Name: "es-{{ tiny_prefix }}-public" + Environment: Testing + Application: Search + AnsibleTest: "AnsibleTestOpenSearchCluster" + register: opensearch_domain + - assert: + that: + - opensearch_domain is not changed + + - name: Create VPC-attached OpenSearch cluster, check mode + opensearch: + state: present + domain_name: "es-{{ tiny_prefix }}-vpc" + engine_version: "Elasticsearch_7.1" + cluster_config: + instance_type: "m5.large.search" + instance_count: 2 + zone_awareness: true + availability_zone_count: 2 + dedicated_master: true + dedicated_master_instance_type: "m5.large.search" + dedicated_master_instance_count: 3 + ebs_options: + ebs_enabled: true + volume_type: "gp2" + volume_size: 10 + snapshot_options: + automated_snapshot_start_hour: 12 + access_policies: "{{ lookup('file', 'opensearch_policy.json') | from_json }}" + vpc_options: + subnets: + - "{{ testing_subnet_1.subnet.id }}" + - "{{ testing_subnet_2.subnet.id }}" + security_groups: + - "{{ sg.group_id }}" + encryption_at_rest_options: + enabled: false + tags: + Name: "es-{{ tiny_prefix }}-public" + Environment: Testing + Application: Search + AnsibleTest: "AnsibleTestOpenSearchCluster" + wait: true + check_mode: true + register: opensearch_domain + - assert: + that: + - "opensearch_domain is changed" + + - name: Create VPC-attached OpenSearch cluster, change expected + # Considerations for selecting node instances for test purpose: + # 1) Low cost + # 2) Supports encryption at rest, advanced security options, node-to-node encryption. + # See https://docs.aws.amazon.com/opensearch-service/latest/developerguide/supported-instance-types.html + opensearch: + state: present + domain_name: "es-{{ tiny_prefix }}-vpc" + engine_version: "Elasticsearch_7.1" + cluster_config: + instance_type: "m5.large.search" + instance_count: 2 + zone_awareness: true + availability_zone_count: 2 + dedicated_master: true + dedicated_master_instance_type: "m5.large.search" + dedicated_master_instance_count: 3 + ebs_options: + ebs_enabled: true + volume_type: "gp2" + volume_size: 10 + snapshot_options: + automated_snapshot_start_hour: 12 + access_policies: "{{ lookup('file', 'opensearch_policy.json') | from_json }}" + vpc_options: + subnets: + - "{{ testing_subnet_1.subnet.id }}" + - "{{ testing_subnet_2.subnet.id }}" + security_groups: + - "{{ sg.group_id }}" + encryption_at_rest_options: + enabled: false + tags: + Name: "es-{{ tiny_prefix }}-public" + Environment: Testing + Application: Search + AnsibleTest: "AnsibleTestOpenSearchCluster" + wait: true + # It could take about 45 minutes for the cluster to be created and available. + wait_timeout: "{{ 45 * 60 }}" + register: opensearch_domain + - assert: + that: + - "opensearch_domain.tags | length == 4" + - "opensearch_domain.engine_version == 'Elasticsearch_7.1'" + - "opensearch_domain.cluster_config.instance_count == 2" + - "opensearch_domain.cluster_config.instance_type == 'm5.large.search'" + - "opensearch_domain.cluster_config.dedicated_master_enabled == true" + - "opensearch_domain.cluster_config.dedicated_master_type == 'm5.large.search'" + - "opensearch_domain.cluster_config.dedicated_master_count == 3" + - "opensearch_domain.cluster_config.warm_enabled == false" + - "opensearch_domain.cluster_config.zone_awareness_enabled == true" + - "opensearch_domain.ebs_options.ebs_enabled == true" + - "opensearch_domain.ebs_options.volume_size == 10" + - "opensearch_domain.ebs_options.volume_type == 'gp2'" + - "opensearch_domain.snapshot_options.automated_snapshot_start_hour == 12" + - "opensearch_domain.vpc_options is defined" + - "opensearch_domain.vpc_options.vpc_id is defined" + - "opensearch_domain.vpc_options.vpc_id == testing_vpc.vpc.id" + - "opensearch_domain.vpc_options.subnet_ids is defined" + - "opensearch_domain.vpc_options.subnet_ids | length == 2" + - "opensearch_domain.vpc_options.security_group_ids is defined" + - "opensearch_domain.vpc_options.security_group_ids | length == 1" + # Assert task has changed/not changed OpenSearch domain + - "opensearch_domain is changed" + + - name: Create VPC-attached OpenSearch cluster, check mode again + opensearch: + state: present + domain_name: "es-{{ tiny_prefix }}-vpc" + engine_version: "Elasticsearch_7.1" + cluster_config: + instance_type: "m5.large.search" + instance_count: 2 + zone_awareness: true + availability_zone_count: 2 + dedicated_master: true + dedicated_master_instance_type: "m5.large.search" + dedicated_master_instance_count: 3 + ebs_options: + ebs_enabled: true + volume_type: "gp2" + volume_size: 10 + snapshot_options: + automated_snapshot_start_hour: 12 + access_policies: "{{ lookup('file', 'opensearch_policy.json') | from_json }}" + vpc_options: + subnets: + - "{{ testing_subnet_1.subnet.id }}" + - "{{ testing_subnet_2.subnet.id }}" + security_groups: + - "{{ sg.group_id }}" + encryption_at_rest_options: + enabled: false + tags: + Name: "es-{{ tiny_prefix }}-public" + Environment: Testing + Application: Search + AnsibleTest: "AnsibleTestOpenSearchCluster" + wait: true + check_mode: true + register: opensearch_domain + - assert: + that: + - opensearch_domain is not changed + + - name: Create VPC-attached OpenSearch cluster, no change expected + opensearch: + state: present + domain_name: "es-{{ tiny_prefix }}-vpc" + engine_version: "Elasticsearch_7.1" + cluster_config: + instance_type: "m5.large.search" + instance_count: 2 + zone_awareness: true + availability_zone_count: 2 + dedicated_master: true + dedicated_master_instance_type: "m5.large.search" + dedicated_master_instance_count: 3 + ebs_options: + ebs_enabled: true + volume_type: "gp2" + volume_size: 10 + snapshot_options: + automated_snapshot_start_hour: 12 + access_policies: "{{ lookup('file', 'opensearch_policy.json') | from_json }}" + vpc_options: + subnets: + - "{{ testing_subnet_1.subnet.id }}" + - "{{ testing_subnet_2.subnet.id }}" + security_groups: + - "{{ sg.group_id }}" + encryption_at_rest_options: + enabled: false + tags: + Name: "es-{{ tiny_prefix }}-public" + Environment: Testing + Application: Search + AnsibleTest: "AnsibleTestOpenSearchCluster" + wait: true + register: opensearch_domain + - assert: + that: + - opensearch_domain is not changed + + - name: Get list of OpenSearch domains + opensearch_info: + tags: + Environment: "Testing" + Application: "Search" + AnsibleTest: "AnsibleTestOpenSearchCluster" + register: opensearch_domains_info + - assert: + that: + - opensearch_domains_info.domains is defined + - opensearch_domains_info.domains | length == 2 + + - name: Get OpenSearch domains matching domain name + opensearch_info: + domain_name: "es-{{ tiny_prefix }}-vpc" + register: opensearch_domains_info + - assert: + that: + - opensearch_domains_info is not changed + - opensearch_domains_info.domains is defined + - opensearch_domains_info.domains | length == 1 + - opensearch_domains_info.domains[0].domain_config is defined + - opensearch_domains_info.domains[0].domain_status is defined + # Even after waiting for the OpenSearch cluster to complete installation, + # it may take a few additional minutes for the 'Endpoints' property + # to be present in the AWS API. + # See further down below. The same `opensearch_info` task is invoked + # after running a task that takes time, and that time there is + # an assert on the 'endpoint' property. + #- opensearch_domains_info.domains[0].domain_status.endpoints is defined + #- opensearch_domains_info.domains[0].domain_status.endpoints.vpc is defined + + - name: Tag Opensearch domain, check mode + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + tags: + Name: "es-{{ tiny_prefix }}-public" + Environment: Testing + tag_a: 'value 1' + Application: Search + AnsibleTest: "AnsibleTestOpenSearchCluster" + wait: true + check_mode: true + register: opensearch_domain + - assert: + that: + - opensearch_domain is changed + + - name: Tag Opensearch domain, expect changes + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + tags: + Name: "es-{{ tiny_prefix }}-public" + Environment: Testing + tag_a: 'value 1' + Application: Search + AnsibleTest: "AnsibleTestOpenSearchCluster" + wait: true + register: opensearch_domain + - assert: + that: + - "opensearch_domain.tags | length == 5" + - opensearch_domain is changed + + - name: Tag Opensearch domain, check mode again + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + tags: + Name: "es-{{ tiny_prefix }}-public" + Environment: Testing + tag_a: 'value 1' + Application: Search + AnsibleTest: "AnsibleTestOpenSearchCluster" + wait: true + check_mode: true + register: opensearch_domain + - assert: + that: + - opensearch_domain is not changed + + - name: Tag Opensearch domain, expect no change + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + tags: + Name: "es-{{ tiny_prefix }}-public" + Environment: Testing + tag_a: 'value 1' + Application: Search + AnsibleTest: "AnsibleTestOpenSearchCluster" + wait: true + register: opensearch_domain + - assert: + that: + - "opensearch_domain.tags | length == 5" + - opensearch_domain is not changed + + - name: Add tag_b to Opensearch domain without purging, check mode + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + tags: + tag_b: 'value 2' + purge_tags: false + wait: true + check_mode: true + register: opensearch_domain + - assert: + that: + - opensearch_domain is changed + + - name: Add tag_b to Opensearch domain without purging + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + tags: + tag_b: 'value 2' + purge_tags: false + wait: true + register: opensearch_domain + - assert: + that: + - "opensearch_domain.tags | length == 6" + - opensearch_domain is changed + + - name: Add tag_b to Opensearch domain without purging, check mode again + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + tags: + tag_b: 'value 2' + purge_tags: false + wait: true + check_mode: true + register: opensearch_domain + - assert: + that: + - opensearch_domain is not changed + + - name: Add tag_b to Opensearch domain without purging, no change expected + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + tags: + tag_b: 'value 2' + purge_tags: false + wait: true + register: opensearch_domain + - assert: + that: + - "opensearch_domain.tags | length == 6" + - opensearch_domain is not changed + + - name: Set tags to Opensearch domain and purge tags, check mode + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + tags: + Name: "es-{{ tiny_prefix }}-public" + Environment: Testing + Application: Search + AnsibleTest: "AnsibleTestOpenSearchCluster" + purge_tags: true + wait: true + check_mode: true + register: opensearch_domain + - assert: + that: + - opensearch_domain is changed + + - name: Set tags to Opensearch domain and purge tags + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + tags: + Name: "es-{{ tiny_prefix }}-public" + Environment: Testing + Application: Search + AnsibleTest: "AnsibleTestOpenSearchCluster" + purge_tags: true + wait: true + register: opensearch_domain + - assert: + that: + - "opensearch_domain.tags | length == 4" + - opensearch_domain is changed + + - name: Set tags to Opensearch domain and purge tags, check mode again + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + tags: + Name: "es-{{ tiny_prefix }}-public" + Environment: Testing + Application: Search + AnsibleTest: "AnsibleTestOpenSearchCluster" + purge_tags: true + wait: true + check_mode: true + register: opensearch_domain + - assert: + that: + - opensearch_domain is not changed + + - name: Set tags to Opensearch domain and purge tags, no change expected + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + tags: + Name: "es-{{ tiny_prefix }}-public" + Environment: Testing + Application: Search + AnsibleTest: "AnsibleTestOpenSearchCluster" + purge_tags: true + wait: true + register: opensearch_domain + - assert: + that: + - "opensearch_domain.tags | length == 4" + - opensearch_domain is not changed + +- name: Change EBS storage configuration, snapshot hour, instance count + block: + - name: Increase size of EBS volumes, check mode + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + ebs_options: + volume_size: 12 + wait: true + check_mode: true + register: opensearch_domain + - assert: + that: + - opensearch_domain is changed + + - name: Increase size of EBS volumes, expect changes + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + ebs_options: + volume_size: 12 + wait: true + # It could take 20 minutes to increase the size of the EBS volumes + wait_timeout: "{{ 30 * 60 }}" + register: opensearch_domain + - assert: + that: + - "opensearch_domain.ebs_options.volume_size == 12" + - opensearch_domain is changed + + - name: Increase size of EBS volumes, check mode again + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + ebs_options: + volume_size: 12 + wait: true + check_mode: true + register: opensearch_domain + - assert: + that: + - opensearch_domain is not changed + + - name: Increase size of EBS volumes, expect no change + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + ebs_options: + volume_size: 12 + wait: true + register: opensearch_domain + - assert: + that: + - "opensearch_domain.ebs_options.volume_size == 12" + - opensearch_domain is not changed + + - name: Get OpenSearch domains matching domain name + opensearch_info: + domain_name: "es-{{ tiny_prefix }}-vpc" + register: opensearch_domains_info + - assert: + that: + - opensearch_domains_info is not changed + - opensearch_domains_info.domains is defined + - opensearch_domains_info.domains | length == 1 + - opensearch_domains_info.domains[0].domain_config is defined + - opensearch_domains_info.domains[0].domain_status is defined + # Even after waiting for the OpenSearch cluster to complete installation, + # it may take a few additional minutes for the 'Endpoints' property + # to be present in the AWS API. + - opensearch_domains_info.domains[0].domain_status.endpoints is defined + - opensearch_domains_info.domains[0].domain_status.endpoints.vpc is defined + + - name: Set fact for OpenSearch endpoint FQDN in the VPC + set_fact: + opensearch_vpc_fqdn: "{{ opensearch_domains_info.domains[0].domain_status.endpoints.vpc }}" + + # Create a Route53 CNAME record. + # This CNAME record will be used when configuring a custom endpoint + # for the OpenSearch cluster. + - name: Create CNAME record for the OpenSearch custom endpoint + route53: + state: present + hosted_zone_id: "{{ route53_zone_id }}" + record: "opensearch.ansible-integ-test.com" + private_zone: true + type: CNAME + value: "{{ opensearch_vpc_fqdn }}" + + - name: Change snapshot start hour, check mode + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + snapshot_options: + automated_snapshot_start_hour: 3 + wait: true + check_mode: true + register: opensearch_domain + - assert: + that: + - opensearch_domain is changed + + - name: Change snapshot start hour + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + snapshot_options: + automated_snapshot_start_hour: 3 + wait: true + register: opensearch_domain + - assert: + that: + - "opensearch_domain.snapshot_options.automated_snapshot_start_hour == 3" + - opensearch_domain is changed + + - name: Change snapshot start hour, check mode again + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + snapshot_options: + automated_snapshot_start_hour: 3 + wait: true + check_mode: true + register: opensearch_domain + - assert: + that: + - opensearch_domain is not changed + + - name: Change snapshot start hour, no change expected + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + snapshot_options: + automated_snapshot_start_hour: 3 + wait: true + register: opensearch_domain + - assert: + that: + - opensearch_domain is not changed + + - name: Set instance count to 4 in the OpenSearch cluster, check mode + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + cluster_config: + # It's a 2-AZ deployment, therefore the node count must be even. + instance_count: 4 + wait: true + check_mode: true + register: opensearch_domain + - assert: + that: + - opensearch_domain is changed + + - name: Set instance count to 4 in the OpenSearch cluster, changes expected + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + cluster_config: + # It's a 2-AZ deployment, therefore the node count must be even. + instance_count: 4 + wait: true + # It could take 20 minutes to increase the number of nodes in the cluster + wait_timeout: "{{ 30 * 60 }}" + register: opensearch_domain + - assert: + that: + - "opensearch_domain.cluster_config.instance_count == 4" + - opensearch_domain is changed + + - name: Set instance count to 4 in the OpenSearch cluster, check mode again + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + cluster_config: + # It's a 2-AZ deployment, therefore the node count must be even. + instance_count: 4 + wait: true + check_mode: true + register: opensearch_domain + - assert: + that: + - opensearch_domain is not changed + + - name: Set instance count to 4 in the OpenSearch cluster, no change expected + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + cluster_config: + # It's a 2-AZ deployment, therefore the node count must be even. + instance_count: 4 + wait: true + register: opensearch_domain + - assert: + that: + - opensearch_domain is not changed + + - name: Set instance count to 2 in the OpenSearch cluster, check mode + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + cluster_config: + instance_count: 2 + wait: true + check_mode: true + register: opensearch_domain + - assert: + that: + - opensearch_domain is changed + + - name: Set instance count to 2 in the OpenSearch cluster, changes expected + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + cluster_config: + instance_count: 2 + wait: true + # It could take 20 minutes to decrease the number of nodes in the cluster + wait_timeout: "{{ 30 * 60 }}" + register: opensearch_domain + - assert: + that: + - "opensearch_domain.cluster_config.instance_count == 2" + - opensearch_domain is changed + + - name: Set instance count to 2 in the OpenSearch cluster, check mode again + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + cluster_config: + instance_count: 2 + wait: true + check_mode: true + register: opensearch_domain + - assert: + that: + - opensearch_domain is not changed + + - name: Set instance count to 2 in the OpenSearch cluster, no change expected + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + cluster_config: + instance_count: 2 + wait: true + register: opensearch_domain + - assert: + that: + - "opensearch_domain.cluster_config.instance_count == 2" + - opensearch_domain is not changed + +- name: Upgrade OpenSearch cluster + block: + - name: Upgrade OpenSearch cluster, check mode + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + engine_version: "Elasticsearch_7.10" + check_mode: true + register: opensearch_domain + - assert: + that: + - opensearch_domain is changed + + - name: Upgrade OpenSearch cluster, change expected + # Upgrade from version 7.1 to version 7.10. + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + engine_version: "Elasticsearch_7.10" + wait: true + # It could take 40 minutes to upgrade the cluster + wait_timeout: "{{ 50 * 60 }}" + register: opensearch_domain + - assert: + that: + - "opensearch_domain.engine_version == 'Elasticsearch_7.10'" + - "opensearch_domain.cluster_config.instance_count == 2" + - opensearch_domain is changed + + - name: Upgrade OpenSearch cluster, check mode again + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + engine_version: "Elasticsearch_7.10" + check_mode: true + register: opensearch_domain + - assert: + that: + - opensearch_domain is not changed + + - name: Upgrade OpenSearch cluster, no change expected + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + engine_version: "Elasticsearch_7.10" + register: opensearch_domain + - assert: + that: + - "opensearch_domain.engine_version == 'Elasticsearch_7.10'" + - "opensearch_domain.cluster_config.instance_count == 2" + - opensearch_domain is not changed + +- name: Configure encryption + when: false + block: + - name: Enable node to node encryption, check mode + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + node_to_node_encryption_options: + enabled: true + wait: true + check_mode: true + register: opensearch_domain + - assert: + that: + - opensearch_domain is changed + + - name: Enable node to node encryption, change expected + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + node_to_node_encryption_options: + enabled: true + wait: true + # This may take a long time. + wait_timeout: "{{ 60 * 60 }}" + register: opensearch_domain + - assert: + that: + - "opensearch_domain.node_to_node_encryption_options.enabled == True" + - opensearch_domain is changed + + - name: Enable node to node encryption, check mode again + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + node_to_node_encryption_options: + enabled: true + wait: true + check_mode: true + register: opensearch_domain + - assert: + that: + - opensearch_domain is not changed + + - name: Enable node to node encryption, no change expected + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + node_to_node_encryption_options: + enabled: true + wait: true + register: opensearch_domain + - assert: + that: + - "opensearch_domain.node_to_node_encryption_options.enabled == True" + - opensearch_domain is not changed + + - name: Enable encryption at rest, check mode + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + encryption_at_rest_options: + enabled: true + #kms_key_id: "{{ kms_test_key.key_id }}" + wait: true + check_mode: true + register: opensearch_domain + - assert: + that: + - opensearch_domain is changed + + - name: Enable encryption at rest, change expected + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + encryption_at_rest_options: + enabled: true + # key ARN has the format: + # 'arn:aws:kms:{{region}}:{{account}}:key/{{key_id}}' + # The API docs indicate the value is the KMS key id, which works + # However, the KMS key ARN seems to be a better option because + # the AWS API actually returns the KMS key ARN. + + # Do not set 'kms_key_id' to let AWS manage the key. + #kms_key_id: "{{ kms_test_key.key_arn }}" + wait: true + # It may take a long time for the task to complete. + wait_timeout: "{{ 60 * 60 }}" + register: opensearch_domain + - assert: + that: + - "opensearch_domain.encryption_at_rest_options.enabled == True" + - opensearch_domain is changed + + - name: Enable encryption at rest, check mode again + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + encryption_at_rest_options: + enabled: true + #kms_key_id: "{{ kms_test_key.key_arn }}" + wait: true + check_mode: true + register: opensearch_domain + - assert: + that: + - opensearch_domain is not changed + + - name: Enable encryption at rest, no change expected + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + encryption_at_rest_options: + enabled: true + #kms_key_id: "{{ kms_test_key.key_arn }}" + wait: true + register: opensearch_domain + - assert: + that: + - opensearch_domain is not changed + +- name: Configure HTTPs endpoint + when: false + block: + - name: Enforce HTTPS for OpenSearch endpoint, check mode + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + domain_endpoint_options: + enforce_https: true + tls_security_policy: "Policy-Min-TLS-1-0-2019-07" + wait: true + check_mode: true + register: opensearch_domain + - assert: + that: + - opensearch_domain is changed + + - name: Enforce HTTPS for OpenSearch endpoint, changes expected + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + domain_endpoint_options: + enforce_https: true + tls_security_policy: "Policy-Min-TLS-1-0-2019-07" + # Refer to CNAME that was defined in the previous tasks. + custom_endpoint_enabled: true + custom_endpoint: "opensearch.ansible-integ-test.com" + # TODO: create a certificate. There is a dependency on the aws_acm module + # which does not support certificates issued by AWS. + # The OpenSearch endpoint should have a certificate issued by a trusted CA + # otherwise clients to the OpenSearch cluster will not be able to validate + # the x.509 certificate of the OpenSearch endpoint. + custom_endpoint_certificate_arn: "{{ opensearch_certificate_arn }}" + wait: true + wait_timeout: "{{ 60 * 60 }}" + register: opensearch_domain + until: opensearch_domain is not failed + ignore_errors: yes + retries: 10 + # After enabling at rest encryption, there is a period during which the API fails, so retry. + delay: 30 + - assert: + that: + - "opensearch_domain.domain_endpoint_options.enforce_https == True" + - "opensearch_domain.domain_endpoint_options.tls_security_policy == 'Policy-Min-TLS-1-0-2019-07'" + #- "opensearch_domain.domain_endpoint_options.custom_endpoint_enabled == True" + - opensearch_domain is changed + + - name: Change TLS policy, check mode + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + domain_endpoint_options: + tls_security_policy: "Policy-Min-TLS-1-2-2019-07" + wait: true + check_mode: true + register: opensearch_domain + - assert: + that: + - opensearch_domain is changed + + - name: Change TLS policy, change expected + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + domain_endpoint_options: + tls_security_policy: "Policy-Min-TLS-1-2-2019-07" + wait: true + wait_timeout: "{{ 60 * 60 }}" + register: opensearch_domain + - assert: + that: + - "opensearch_domain.domain_endpoint_options.enforce_https == True" + - "opensearch_domain.domain_endpoint_options.tls_security_policy == 'Policy-Min-TLS-1-2-2019-07'" + - opensearch_domain is changed + +- name: Configure advanced security + block: + - name: Enable advanced security, check mode + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + advanced_security_options: + enabled: true + wait: true + check_mode: true + register: opensearch_domain + - assert: + that: + - opensearch_domain is changed + + # Pre-requisites before enabling advanced security options: + # 1) node-to-node encryption must be enabled. + # 2) encryption at rest to must be enabled. + # 3) Enforce HTTPS in the domain endpoint options. + - name: Enable advanced security, change expected + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + advanced_security_options: + enabled: true + wait: true + wait_timeout: "{{ 60 * 60 }}" + register: opensearch_domain + - assert: + that: + - "opensearch_domain.advanced_security_options.enabled == True" + - opensearch_domain is changed + + - name: Enable advanced security, check mode again + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + advanced_security_options: + enabled: true + wait: true + check_mode: true + register: opensearch_domain + - assert: + that: + - opensearch_domain is not changed + + - name: Enable advanced security, no change expected + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + advanced_security_options: + enabled: true + wait: true + register: opensearch_domain + - assert: + that: + - "opensearch_domain.advanced_security_options.enabled == True" + - opensearch_domain is not changed + +- name: Configure warm and cold storage + block: + - name: Enable warm storage in check mode + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + cluster_config: + warm_enabled: true + warm_type: "ultrawarm1.medium.search" + warm_count: 2 + wait: true + check_mode: true + register: opensearch_domain + - assert: + that: + - opensearch_domain is changed + + - name: Enable warm storage, change expected + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + cluster_config: + warm_enabled: true + warm_type: "ultrawarm1.medium.search" + warm_count: 2 + wait: true + # Adding warm storage may take a long time. + wait_timeout: "{{ 45 * 60 }}" + register: opensearch_domain + - assert: + that: + - "opensearch_domain.cluster_config.warm_enabled == True" + - "opensearch_domain.cluster_config.warm_count == 2" + - "opensearch_domain.cluster_config.warm_type == 'ultrawarm1.medium.search'" + - opensearch_domain is changed + + - name: Enable warm storage in check mode again + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + cluster_config: + warm_enabled: true + warm_type: "ultrawarm1.medium.search" + warm_count: 2 + wait: true + check_mode: true + register: opensearch_domain + - assert: + that: + - opensearch_domain is not changed + + - name: Enable warm storage, no change expected + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + cluster_config: + warm_enabled: true + warm_type: "ultrawarm1.medium.search" + warm_count: 2 + wait: true + register: opensearch_domain + - assert: + that: + - "opensearch_domain.cluster_config.warm_enabled == True" + - "opensearch_domain.cluster_config.warm_count == 2" + - opensearch_domain is not changed + + - name: Enable cold storage in check mode + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + cluster_config: + cold_storage_options: + enabled: true + wait: true + check_mode: true + register: opensearch_domain + - assert: + that: + - opensearch_domain is changed + + - name: Enable cold storage, change expected + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + cluster_config: + cold_storage_options: + enabled: true + wait: true + # Adding cold storage may take a long time. + wait_timeout: "{{ 45 * 60 }}" + register: opensearch_domain + - assert: + that: + - "opensearch_domain.cluster_config.cold_storage_options.enabled == True" + - opensearch_domain is changed + + - name: Enable cold storage in check mode again + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + cluster_config: + cold_storage_options: + enabled: true + wait: true + check_mode: true + register: opensearch_domain + - assert: + that: + - opensearch_domain is not changed + + - name: Enable cold storage, no change expected + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + cluster_config: + cold_storage_options: + enabled: true + wait: true + register: opensearch_domain + - assert: + that: + - "opensearch_domain.cluster_config.cold_storage_options.enabled == True" + - opensearch_domain is not changed + +- name: Configure auto-tune options + block: + - name: Enable auto-tune options in check mode + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + auto_tune_options: + desired_state: "ENABLED" + maintenance_schedules: + - start_at: "{{ ansible_date_time.year|int + 1 }}-01-01" + duration: + value: 10 + unit: "HOURS" + cron_expression_for_recurrence: "cron(0 12 * * ? *)" + wait: true + check_mode: true + register: opensearch_domain + - assert: + that: + - opensearch_domain is changed + + - name: Enable auto-tune options, changes expected + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + auto_tune_options: + desired_state: "ENABLED" + maintenance_schedules: + # Create a schedule one year from the date we start the test. + # If we hard code the date, we have to pick a date, but the API will fail + # if start_at is in the past. + - start_at: "{{ ansible_date_time.year|int + 1 }}-01-01" + duration: + value: 10 + unit: "HOURS" + cron_expression_for_recurrence: "cron(0 12 * * ? *)" + # I have observed that at least during one test run, + # the cluster status was stuck in 'processing=true' for over 24 hours + # after enabling auto-tune options. + # This does not seem right. From a test perspective, that means we cannot + # execute any change that needs to wait until the cluster is not processing + # background tasks. + wait: false + register: opensearch_domain + - assert: + that: + - "opensearch_domain.auto_tune_options.state == 'ENABLED'" + - opensearch_domain is changed + + - name: Enable auto-tune options in check mode again + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + auto_tune_options: + desired_state: "ENABLED" + maintenance_schedules: + - start_at: "{{ ansible_date_time.year|int + 1 }}-01-01" + duration: + value: 10 + unit: "HOURS" + cron_expression_for_recurrence: "cron(0 12 * * ? *)" + wait: false + check_mode: true + register: opensearch_domain + - assert: + that: + - opensearch_domain is not changed + + - name: Enable auto-tune options, no change expected + opensearch: + domain_name: "es-{{ tiny_prefix }}-vpc" + auto_tune_options: + desired_state: "ENABLED" + maintenance_schedules: + - start_at: "{{ ansible_date_time.year|int + 1 }}-01-01" + duration: + value: 10 + unit: "HOURS" + cron_expression_for_recurrence: "cron(0 12 * * ? *)" + wait: false + register: opensearch_domain + - assert: + that: + - "opensearch_domain.auto_tune_options.state == 'ENABLED'" + - opensearch_domain is not changed diff --git a/tests/integration/targets/opensearch/tasks/test_vpc_setup.yml b/tests/integration/targets/opensearch/tasks/test_vpc_setup.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/opensearch/tasks/test_vpc_setup.yml @@ -0,0 +1,134 @@ +- name: Configure pre-requisites for test, VPC and KMS resources + block: + - name: Create VPC for use in testing + ec2_vpc_net: + name: "{{ tiny_prefix }}-vpc" + state: present + cidr_block: 10.55.0.0/16 + tenancy: default + tags: + AnsibleEIPTest: "{{ tiny_prefix }}-vpc" + AnsibleTest: AnsibleTestVpc + register: testing_vpc + + - name: Wait until VPC is created. + ec2_vpc_net_info: + filters: + tag:AnsibleEIPTest: + - "{{ tiny_prefix }}-vpc" + register: vpc_info + retries: 120 + delay: 5 + until: + - vpc_info.vpcs | length > 0 + - vpc_info.vpcs[0].state == 'available' + + - name: Create internet gateway for use in testing + ec2_vpc_igw: + vpc_id: "{{ testing_vpc.vpc.id }}" + state: present + resource_tags: + Name: "{{ tiny_prefix }}-igw" + AnsibleTest: AnsibleTestVpc + register: igw + + # The list of AZs varies across regions and accounts. + # Gather info and pick two AZs for test purpose. + - name: gather AZ info in VPC for test purpose + amazon.aws.aws_az_info: + region: "{{ aws_region }}" + register: az_info + - assert: + that: + # We cannot run the test if this region does not have at least 2 AZs + - "az_info.availability_zones | length >= 2" + - set_fact: + test_az_zone1: "{{ az_info.availability_zones[0].zone_name }}" + test_az_zone2: "{{ az_info.availability_zones[1].zone_name }}" + - name: Create subnet_1 for use in testing + ec2_vpc_subnet: + state: present + vpc_id: "{{ testing_vpc.vpc.id }}" + cidr: 10.55.77.0/24 + az: "{{ test_az_zone1 }}" + resource_tags: + Name: "{{ tiny_prefix }}-subnet_1" + AnsibleTest: AnsibleTestVpc + wait: true + register: testing_subnet_1 + + - name: Create subnet_2 for use in testing + ec2_vpc_subnet: + state: present + vpc_id: "{{ testing_vpc.vpc.id }}" + cidr: 10.55.78.0/24 + az: "{{ test_az_zone2 }}" + resource_tags: + Name: "{{ tiny_prefix }}-subnet_2" + AnsibleTest: AnsibleTestVpc + wait: true + register: testing_subnet_2 + + - name: Create routing rules + ec2_vpc_route_table: + vpc_id: "{{ testing_vpc.vpc.id }}" + routes: + - dest: 0.0.0.0/0 + gateway_id: "{{ igw.gateway_id }}" + subnets: + - "{{ testing_subnet_1.subnet.id }}" + - "{{ testing_subnet_2.subnet.id }}" + tags: + Name: "{{ tiny_prefix }}-route" + AnsibleTest: AnsibleTestVpc + + - name: Create security group for use in testing + ec2_group: + name: "{{ tiny_prefix }}-sg" + description: a security group for ansible tests + vpc_id: "{{ testing_vpc.vpc.id }}" + tags: + Name: "{{ tiny_prefix }}-sg" + AnsibleTest: AnsibleTestVpc + rules: + - proto: tcp + from_port: 22 + to_port: 22 + cidr_ip: 0.0.0.0/0 + - proto: tcp + from_port: 80 + to_port: 80 + cidr_ip: 0.0.0.0/0 + register: sg + + # A private route53 zone is needed to configure a custom endpoint in the OpenSearch cluster. + # See https://docs.aws.amazon.com/opensearch-service/latest/developerguide/customendpoint.html + - name: Create private Route53 zone for the VPC + register: route53_zone + route53_zone: + comment: "zone for ansible integration tests" + zone: "ansible-integ-test.com" + state: present + vpc_id: '{{ testing_vpc.vpc.id }}' + tags: + Name: "{{ tiny_prefix }}-zone" + AnsibleTest: AnsibleTestVpc + + - name: Set fact for route53 zone id + set_fact: + route53_zone_id: "{{ route53_zone.result.zone_id }}" + + - name: Create KMS key for test purpose + # The key is needed for OpenSearch encryption at rest. + aws_kms: + alias: "{{ tiny_prefix }}-kms" + description: a key used for encryption at rest in test OpenSearch cluster + state: present + enabled: yes + key_spec: SYMMETRIC_DEFAULT + key_usage: ENCRYPT_DECRYPT + policy: "{{ lookup('template', 'kms_policy.j2') }}" + tags: + Name: "{{ tiny_prefix }}-kms" + AnsibleTest: AnsibleTestVpc + register: kms_test_key diff --git a/tests/integration/targets/opensearch/templates/kms_policy.j2 b/tests/integration/targets/opensearch/templates/kms_policy.j2 new file mode 100644 --- /dev/null +++ b/tests/integration/targets/opensearch/templates/kms_policy.j2 @@ -0,0 +1,68 @@ +{ + "Id": "key-ansible-test-policy-123", + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "Allow access for root user", + "Effect": "Allow", + "Principal": { + "AWS": "arn:aws:iam::{{ aws_caller_info.account }}:root" + }, + "Action": "kms:*", + "Resource": "*" + }, + { + "Sid": "AnsibleTestManage", + "Effect": "Allow", + "Principal": { + "AWS": "{{ aws_caller_info.arn }}" + }, + "Action": "kms:*", + "Resource": "*" + }, + { + "Sid": "Allow access for Key Administrators", + "Effect": "Allow", + "Principal": { + "AWS": "arn:aws:iam::{{ aws_caller_info.account }}:role/admin" + }, + "Action": "kms:*", + "Resource": "*" + }, + { + "Sid": "Allow access through OpenSearch Service for all principals in the account that are authorized to use OpenSearch Service", + "Effect": "Allow", + "Principal": { + "AWS": "*" + }, + "Action": [ + "kms:Encrypt", + "kms:Decrypt", + "kms:ReEncrypt*", + "kms:GenerateDataKey*", + "kms:CreateGrant", + "kms:DescribeKey" + ], + "Resource": "*", + "Condition": { + "StringEquals": { + "kms:CallerAccount": "{{ aws_caller_info.account }}", + "kms:ViaService": "es.{{ aws_region }}.amazonaws.com" + } + } + }, + { + "Sid": "Allow OpenSearch service principals to describe the key directly", + "Effect": "Allow", + "Principal": { + "Service": "es.amazonaws.com" + }, + "Action": [ + "kms:Describe*", + "kms:Get*", + "kms:List*" + ], + "Resource": "*" + } + ] +} diff --git a/tests/unit/plugins/modules/test_opensearch.py b/tests/unit/plugins/modules/test_opensearch.py new file mode 100644 --- /dev/null +++ b/tests/unit/plugins/modules/test_opensearch.py @@ -0,0 +1,86 @@ +# Copyright: Ansible Project +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + +import functools +from ansible_collections.community.aws.plugins.module_utils.opensearch import ( + compare_domain_versions, + parse_version, +) + + +def test_parse_version(): + test_versions = [ + ['Elasticsearch_5.5', {'engine_type': 'Elasticsearch', 'major': 5, 'minor': 5}], + ['Elasticsearch_7.1', {'engine_type': 'Elasticsearch', 'major': 7, 'minor': 1}], + ['Elasticsearch_7.10', {'engine_type': 'Elasticsearch', 'major': 7, 'minor': 10}], + ['OpenSearch_1.0', {'engine_type': 'OpenSearch', 'major': 1, 'minor': 0}], + ['OpenSearch_1.1', {'engine_type': 'OpenSearch', 'major': 1, 'minor': 1}], + ['OpenSearch_a.b', None], + ['OpenSearch_1.b', None], + ['OpenSearch_1-1', None], + ['OpenSearch_1.1.2', None], + ['OpenSearch_foo_1.1', None], + ['OpenSearch_1', None], + ['OpenSearch-1.0', None], + ['Foo_1.0', None], + ] + for expected in test_versions: + ret = parse_version(expected[0]) + if ret != expected[1]: + raise AssertionError( + f"parse_version({expected[0]} returned {ret}, expected {expected[1]}") + + +def test_version_compare(): + test_versions = [ + ['Elasticsearch_5.5', 'Elasticsearch_5.5', 0], + ['Elasticsearch_5.5', 'Elasticsearch_7.1', -1], + ['Elasticsearch_7.1', 'Elasticsearch_7.1', 0], + ['Elasticsearch_7.1', 'Elasticsearch_7.2', -1], + ['Elasticsearch_7.1', 'Elasticsearch_7.10', -1], + ['Elasticsearch_7.2', 'Elasticsearch_7.10', -1], + ['Elasticsearch_7.10', 'Elasticsearch_7.2', 1], + ['Elasticsearch_7.2', 'Elasticsearch_5.5', 1], + ['Elasticsearch_7.2', 'OpenSearch_1.0', -1], + ['Elasticsearch_7.2', 'OpenSearch_1.1', -1], + ['OpenSearch_1.1', 'OpenSearch_1.1', 0], + ['OpenSearch_1.0', 'OpenSearch_1.1', -1], + ['OpenSearch_1.1', 'OpenSearch_1.0', 1], + ['foo_1.1', 'OpenSearch_1.0', -1], + ['Elasticsearch_5.5', 'foo_1.0', 1], + ] + for v in test_versions: + ret = compare_domain_versions(v[0], v[1]) + if ret != v[2]: + raise AssertionError( + f"compare({v[0]}, {v[1]} returned {ret}, expected {v[2]}") + + +def test_sort_versions(): + input_versions = [ + 'Elasticsearch_5.6', + 'Elasticsearch_5.5', + 'Elasticsearch_7.10', + 'Elasticsearch_7.2', + 'foo_10.5', + 'OpenSearch_1.1', + 'OpenSearch_1.0', + 'Elasticsearch_7.3', + ] + expected_versions = [ + 'foo_10.5', + 'Elasticsearch_5.5', + 'Elasticsearch_5.6', + 'Elasticsearch_7.2', + 'Elasticsearch_7.3', + 'Elasticsearch_7.10', + 'OpenSearch_1.0', + 'OpenSearch_1.1', + ] + input_versions = sorted(input_versions, key=functools.cmp_to_key(compare_domain_versions)) + if input_versions != expected_versions: + raise AssertionError( + f"Expected {expected_versions}, got {input_versions}")
OpenSearch, ElasticSearch module ### Summary It would be useful to have a `ec2_opensearch` module to deploy opensearch/elasticsearch clusters. Is it missing because nobody from the community submitted a PR? Or was it intentionally not added? Some other reason? There is one module outside this repo (https://github.com/fiunchinho/ansible-aws-elasticsearch-module), but it hasn't been updated in the last 3 years. ### Issue Type Feature Idea ### Component Name opensearch ### Additional Information <!--- Paste example playbooks or commands between quotes below --> ```yaml (paste below) ``` ### Code of Conduct - [X] I agree to follow the Ansible Code of Conduct
@sebastien-rosset Thank you for this idea. Would you be willing to work on this module and submit a PR? > @sebastien-rosset Thank you for this idea. Would you be willing to work on this module and submit a PR? Yes @sebastien-rosset Awesome! Please feel free to work on it! :-) I guess you have to open the PR inside this collection https://github.com/ansible-collections/community.aws. cc @jillr I agree with @alinabuzachis, the new module would go into community.aws. It should be named `opensearch` rather than `ec2_opensearch` as this service does not use the EC2 API. > I agree with @alinabuzachis, the new module would go into community.aws. It should be named `opensearch` rather than `ec2_opensearch` as this service does not use the EC2 API. Thanks. So it will be `community.aws/plugins/modules/opensearch.py`, right? I see some modules are prefixed with aws, some don't. > Is it missing because nobody from the community submitted a PR? Or was it intentionally not added? Some other reason? > I see some modules are prefixed with aws, some don't. I would call it: "grown historically" :) > Thanks. So it will be community.aws/plugins/modules/opensearch.py, right? right.
2022-01-12T02:25:50
ansible-collections/community.aws
864
ansible-collections__community.aws-864
[ "365" ]
0450a7997cdc0f73cde68bd0c3e84452abeee340
diff --git a/plugins/modules/s3_lifecycle.py b/plugins/modules/s3_lifecycle.py --- a/plugins/modules/s3_lifecycle.py +++ b/plugins/modules/s3_lifecycle.py @@ -23,16 +23,30 @@ - Name of the S3 bucket. required: true type: str + abort_incomplete_multipart_upload_days: + description: + - Specifies the days since the initiation of an incomplete multipart upload that Amazon S3 will wait before permanently removing all parts of the upload. + type: int + version_added: 2.2.0 expiration_date: description: - Indicates the lifetime of the objects that are subject to the rule by the date they will expire. - The value must be ISO-8601 format, the time must be midnight and a GMT timezone must be specified. + - This cannot be specified with I(expire_object_delete_marker) type: str expiration_days: description: - Indicates the lifetime, in days, of the objects that are subject to the rule. - The value must be a non-zero positive integer. + - This cannot be specified with I(expire_object_delete_marker) type: int + expire_object_delete_marker: + description: + - Indicates whether Amazon S3 will remove a delete marker with no noncurrent versions. + - If set to C(true), the delete marker will be expired; if set to C(false) the policy takes no action. + - This cannot be specified with I(expiration_days) or I(expiration_date). + type: bool + version_added: 2.2.0 prefix: description: - Prefix identifying one or more objects to which the rule applies. @@ -250,8 +264,10 @@ def fetch_rules(client, module, name): def build_rule(client, module): name = module.params.get("name") + abort_incomplete_multipart_upload_days = module.params.get("abort_incomplete_multipart_upload_days") expiration_date = parse_date(module.params.get("expiration_date")) expiration_days = module.params.get("expiration_days") + expire_object_delete_marker = module.params.get("expire_object_delete_marker") noncurrent_version_expiration_days = module.params.get("noncurrent_version_expiration_days") noncurrent_version_transition_days = module.params.get("noncurrent_version_transition_days") noncurrent_version_transitions = module.params.get("noncurrent_version_transitions") @@ -268,11 +284,19 @@ def build_rule(client, module): rule = dict(Filter=dict(Prefix=prefix), Status=status.title()) if rule_id is not None: rule['ID'] = rule_id + + if abort_incomplete_multipart_upload_days: + rule['AbortIncompleteMultipartUpload'] = { + 'DaysAfterInitiation': abort_incomplete_multipart_upload_days + } + # Create expiration if expiration_days is not None: rule['Expiration'] = dict(Days=expiration_days) elif expiration_date is not None: rule['Expiration'] = dict(Date=expiration_date.isoformat()) + elif expire_object_delete_marker is not None: + rule['Expiration'] = dict(ExpiredObjectDeleteMarker=expire_object_delete_marker) if noncurrent_version_expiration_days is not None: rule['NoncurrentVersionExpiration'] = dict(NoncurrentDays=noncurrent_version_expiration_days) @@ -525,8 +549,10 @@ def main(): s3_storage_class = ['glacier', 'onezone_ia', 'standard_ia', 'intelligent_tiering', 'deep_archive'] argument_spec = dict( name=dict(required=True, type='str'), + abort_incomplete_multipart_upload_days=dict(type='int'), expiration_days=dict(type='int'), expiration_date=dict(), + expire_object_delete_marker=dict(type='bool'), noncurrent_version_expiration_days=dict(type='int'), noncurrent_version_storage_class=dict(default='glacier', type='str', choices=s3_storage_class), noncurrent_version_transition_days=dict(type='int'), @@ -546,7 +572,7 @@ def main(): module = AnsibleAWSModule(argument_spec=argument_spec, mutually_exclusive=[ - ['expiration_days', 'expiration_date'], + ['expiration_days', 'expiration_date', 'expire_object_delete_marker'], ['expiration_days', 'transition_date'], ['transition_days', 'transition_date'], ['transition_days', 'expiration_date'], @@ -563,8 +589,10 @@ def main(): if state == 'present' and module.params["status"] == "enabled": # allow deleting/disabling a rule by id/prefix - required_when_present = ('expiration_date', 'expiration_days', 'transition_date', - 'transition_days', 'transitions', 'noncurrent_version_expiration_days', + required_when_present = ('abort_incomplete_multipart_upload_days', + 'expiration_date', 'expiration_days', 'expire_object_delete_marker', + 'transition_date', 'transition_days', 'transitions', + 'noncurrent_version_expiration_days', 'noncurrent_version_transition_days', 'noncurrent_version_transitions') for param in required_when_present:
diff --git a/tests/integration/targets/s3_lifecycle/tasks/main.yml b/tests/integration/targets/s3_lifecycle/tasks/main.yml --- a/tests/integration/targets/s3_lifecycle/tasks/main.yml +++ b/tests/integration/targets/s3_lifecycle/tasks/main.yml @@ -327,6 +327,54 @@ that: - output is not changed + # ============================================================ + - name: Create a lifecycle policy, with abort_incomplete_multipart_upload + s3_lifecycle: + name: '{{ bucket_name }}' + abort_incomplete_multipart_upload_days: 1 + prefix: /something + register: output + + - assert: + that: + - output is changed + + # ============================================================ + - name: Create a lifecycle policy, with abort_incomplete_multipart_upload (idempotency) + s3_lifecycle: + name: '{{ bucket_name }}' + abort_incomplete_multipart_upload_days: 1 + prefix: /something + register: output + + - assert: + that: + - output is not changed + + # ============================================================ + - name: Create a lifecycle policy, with expired_object_delete_marker + s3_lifecycle: + name: '{{ bucket_name }}' + expire_object_delete_marker: True + prefix: /something + register: output + + - assert: + that: + - output is changed + + # ============================================================ + - name: Create a lifecycle policy, with expired_object_delete_marker (idempotency) + s3_lifecycle: + name: '{{ bucket_name }}' + expire_object_delete_marker: True + prefix: /something + register: output + + - assert: + that: + - output is not changed + # ============================================================ # test all the examples # Configure a lifecycle rule on a bucket to expire (delete) items with a prefix of /logs/ after 30 days
s3_lifecycle - add abort_incomplete_multipart_upload and expired_object_delete_marker parameter <!--- Verify first that your feature was not already discussed on GitHub --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY I would like to apply a bucket lifecycle configuration with ~s3_bucket~ `s3_lifecycle`. My specific use case is configuring the bucket to abort abandoned multi-part uploads. (Otherwise you can end up paying for storage of data which is not visible in the bucket.) ##### ISSUE TYPE - Feature Idea ##### COMPONENT NAME ~s3_bucket~ s3_lifecycle ##### ADDITIONAL INFORMATION <!--- Describe how the feature would be used, why it is needed and what it would solve --> The bucket policy itself is supposed to be xml. <!--- Paste example playbooks or commands between quotes below --> ``` - amazon.aws.s3_bucket: name: mys3bucket state: present lifecycle_configuration: rules: - id: sample-rule</ID> status: Enabled AbortIncompleteMultipartUpload: DaysAfterInitiation: 7 ``` I'm unsure whether the module should use the same capitalisation as the API (`AbortIncompleteMultipartUpload`), or if we should rename to be consistent with Ansible (`abort_incomplete_multipart_upload`) and then convert it. I suspect using CamelCase would be better.
Files identified in the description: * [`plugins/modules/s3_bucket.py`](https://github.com/['ansible-collections/amazon.aws', 'ansible-collections/community.aws', 'ansible-collections/community.vmware']/blob/main/plugins/modules/s3_bucket.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @jillr @s-hertel @tremble @wimnat [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> Note: ansibullbot seems a bit broken. That list of links isn't rendering as expected. There's possibly some issue with the markdown. How do we get ansibullbot fixed? Hi @mdavis-xyz, This is a good idea, but we would suggest to prepare a new dedicated module `s3_bucket_lifecycle_configuration`. Since it's a new module, it should be created first in `community.aws` collection. Files identified in the description: * [`plugins/modules/s3_bucket_notification.py`](https://github.com/['ansible-collections/amazon.aws', 'ansible-collections/community.aws', 'ansible-collections/community.vmware']/blob/main/plugins/modules/s3_bucket_notification.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @aljazkosir @miha-plesko @xlab-si [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> Ok, I can try to make a new module. What's the process long term? Will this remain a new module forever? Or is that just a short-term location to ensure the code is correct, with a view to move it to the amazon.aws collection as a standalone module, or to that collection as part of the bucket module? @mdavis-xyz We follow the UNIX philosophy - "Make each program do one thing well.". Since we are managing the lifecycle configuration of S3 bucket, I feel this makes sense to have a separate module that is easy to maintain and future-proof. As a short-term goal, this new module will stay with the "community" collection. Once that matures, we can promote it to the "amazon.aws" collection (which is supported content). Hope this makes sense. I'm a bit confused by this request, since there is already the [`community.aws.s3_lifecycle` module ](https://github.com/ansible-collections/community.aws/blob/main/plugins/modules/s3_lifecycle.py)doing this. The only thing missing in that module is the `AbortIncompleteMultipartUpload` and `ExpiredObjectDeleteMarker` settings. This was already mentioned in this issue https://github.com/ansible/ansible/issues/43434 prior to the migration. To be able to manage this in the meantime, I've created a couple of tasks that calls the aws-cli. Something I've notice and that I think it's important to mention here: The `AbortIncompleteMultipartUpload` and `ExpiredObjectDeleteMarker` settings cannot be manage separately. They can only be one lifecycle configuration for a given prefix and those two settings are part of a lifecyle configuration. My original idea was to create a separate lifecycle for those two settings, but I was not able to for this reason. Should we adjust this issue title and description to reflect the situation or should I create a new issue that better describe this? Let me know what you think is better. cc @markuman [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> I fully agree @pgrenaud, thx for summarize and clearify the situation. * https://docs.ansible.com/ansible/latest/collections/community/aws/s3_lifecycle_module.html * https://github.com/ansible-collections/community.aws/blob/main/plugins/modules/s3_lifecycle.py * https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.put_bucket_lifecycle I guess expanding the existing module with two more parameters is not a big task. Is anyone of you (@pgrenaud @mdavis-xyz ) interesting to provide a PR? How should we structure the interface? Like this? ``` - name: Create a lifecycle policy, with abort_incomplete_multipart_upload (idempotency) s3_lifecycle: name: '{{ bucket_name }}' abort_incomplete_multipart_upload: days_after_initiation: 1 prefix: /something ``` Is it too verbose to have: ``` abort_incomplete_multipart_upload: days_after_initiation: 1 ``` (That matches [the underlying API](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.BucketLifecycleConfiguration.put)) Or should I make it like: ``` abort_incomplete_multipart_upload_days: 1 ``` i.e. do I try to make it simplify the API in an opinionated way, which is less verbose, or do I make it match the underlying API as closely as possible, which makes adapting to new features in the API easier? For expiry, the existing `expiration_days` and `expiration_date` args are top level, whereas the API nests them, along with expire object delete marker. So should I promote the object delete market to the top level? What do I call it? `expiration_expired_object_delete_marker` matches the naming of the existing arguments, but sounds a bit verbose. `expire_object_delete_marker` sounds more sensible, although that uses the word `expire` when the underlying API is about `expiration` and `expired`. Is that ok? The API doesn't let you do expired object delete marker, as well as expire days. Should I try to implement that exclusion behavior when validating input arguments? Or just pass it through and rely on AWS to reject the bad input? Also, when submitting a PR, do I need to update a changelog file somewhere? > How should we structure the interface? Imo, keeping the API structure makes it easier to maintain the code along to boto3 and to add more features. Maybe there comes more features under key `abort_incomplete_multipart_upload`, but maybe not. We don't know :) > `expiration_expired_object_delete_marker` matches the naming of the existing arguments, but sounds a bit verbose. `expire_object_delete_marker` sounds more sensible I agree. Optional you can keep the origin key as an alias parameter. > The API doesn't let you do expired object delete marker, as well as expire days. Should I try to implement that exclusion behavior when validating input arguments? Or just pass it through and rely on AWS to reject the bad input? If you see this usecase/this errors already. Maybe yes. But it also must be documented. > Also, when submitting a PR, do I need to update a changelog file somewhere? Yes, when adding new features, you also need to a a `changelog/fragments/` file. See: https://docs.ansible.com/ansible/latest/community/development_process.html#creating-a-changelog-fragment If we want the multipart abort to match the API, should we also change expiration to match the API? Instead of: ``` expiration_days: expiration_date: expire_object_delete_marker: ``` It would match more closely if we did: ``` expiration: date: days: expired_object_delete_marker: ``` That requires care to make the change backwards compatible. Currently you can only specify one of these 3 anyway. So should I keep the pattern for `expire` of not matching the API, and add abort in a way that matches the API? > That requires care to make the change backwards compatible. hm, what did you mean? Atm `s3_bucket` does not support any `expire_` parameters. And I noticed that the module has moved to `amazon.aws` collection. So the Issue will be moved to https://github.com/ansible-collections/amazon.aws @markuman The slightly confusing thing here is that s3_lifecycle (which manages the lifecycle configuration of s3 buckets) lives in community.aws, whereas s3_bucket (which creates the buckets) lives in amazon.aws. In my opinion it's better for us to split out some of this configuration as massive monolithic modules become very difficult to properly test, and as such tend to be less reliable, compared to splitting the functionality out. This becomes even more pronounced when you can apply multiple lifecycle rules based on the folders within a bucket. At some point Amazon will propably replace boto3 with something incompatible, migrating small modules with well defined scope is *massively* simpler than a monolith that does "all things s3" (see also iam, ec2, etc). Ah oh boy. Blame me. 🙈 I was confused because the inition post included still `s3_bucket`. [But it's right. as mentioned above, the functionality must be included `s3_lifecycle`](https://github.com/ansible-collections/community.aws/issues/796#issuecomment-947901889) So the issue musst moved back to `community.aws`. Sorry :D > If we want the multipart abort to match the API, should we also change expiration to match the API? > > Instead of: > > ``` > expiration_days: > expiration_date: > expire_object_delete_marker: > ``` > > It would match more closely if we did: > > ``` > expiration: > date: > days: > expired_object_delete_marker: > ``` > > That requires care to make the change backwards compatible. Currently you can only specify one of these 3 anyway. So should I keep the pattern for `expire` of not matching the API, and add abort in a way that matches the API? Imo to not break backwards compatibility, it's better to keep the existing structure imo. There's two options: 1) Keep the current structure 2) *Deprecate* the current structure and use something closer to the API I would actually lean towards 2 as it feels slightly cleaner, but I would be tempted to do something like ``` expiration: date: days: delete_marker: (with an alias of expired_object_delete_marker) ``` I've submitted a pull request with two new top-level arguments. I'm not sure how a decision like this is usually made. It sounds like there are two maintainers with differing opinions. Just tell me which approach you want and I'll change my PR if needed. If you want to change the existing expiration fields, please name another module that uses an alias with a nested parameter, so I can go see how that can be done. I'm fine with both :)
2022-01-14T12:06:55
ansible-collections/community.aws
872
ansible-collections__community.aws-872
[ "808" ]
99c64a6e9993aed6a825798079a2b964904beb72
diff --git a/plugins/modules/ec2_placement_group.py b/plugins/modules/ec2_placement_group.py --- a/plugins/modules/ec2_placement_group.py +++ b/plugins/modules/ec2_placement_group.py @@ -23,6 +23,13 @@ - The name for the placement group. required: true type: str + partition_count: + description: + - The number of partitions. + - Valid only when I(Strategy) is set to C(partition). + - Must be a value between C(1) and C(7). + type: int + version_added: 3.1.0 state: description: - Create or delete placement group. @@ -35,7 +42,7 @@ low-latency group in a single Availability Zone, while Spread spreads instances across underlying hardware. default: cluster - choices: [ 'cluster', 'spread' ] + choices: [ 'cluster', 'spread', 'partition' ] type: str extends_documentation_fragment: - amazon.aws.aws @@ -58,6 +65,13 @@ state: present strategy: spread +- name: Create a Partition strategy placement group. + community.aws.ec2_placement_group: + name: my-cluster + state: present + strategy: partition + partition_count: 3 + - name: Delete a placement group. community.aws.ec2_placement_group: name: my-cluster @@ -126,10 +140,21 @@ def get_placement_group_details(connection, module): def create_placement_group(connection, module): name = module.params.get("name") strategy = module.params.get("strategy") + partition_count = module.params.get("partition_count") + + if strategy != 'partition' and partition_count: + module.fail_json( + msg="'partition_count' can only be set when strategy is set to 'partition'.") + + params = {} + params['GroupName'] = name + params['Strategy'] = strategy + if partition_count: + params['PartitionCount'] = partition_count + params['DryRun'] = module.check_mode try: - connection.create_placement_group( - GroupName=name, Strategy=strategy, DryRun=module.check_mode) + connection.create_placement_group(**params) except is_boto3_error_code('DryRunOperation'): module.exit_json(changed=True, placement_group={ "name": name, @@ -165,8 +190,9 @@ def delete_placement_group(connection, module): def main(): argument_spec = dict( name=dict(required=True, type='str'), + partition_count=dict(type='int'), state=dict(default='present', choices=['present', 'absent']), - strategy=dict(default='cluster', choices=['cluster', 'spread']) + strategy=dict(default='cluster', choices=['cluster', 'spread', 'partition']) ) module = AnsibleAWSModule(
diff --git a/tests/integration/targets/ec2_placement_group/aliases b/tests/integration/targets/ec2_placement_group/aliases new file mode 100644 --- /dev/null +++ b/tests/integration/targets/ec2_placement_group/aliases @@ -0,0 +1,3 @@ +cloud/aws + +ec2_placement_group_info diff --git a/tests/integration/targets/ec2_placement_group/defaults/main.yml b/tests/integration/targets/ec2_placement_group/defaults/main.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/ec2_placement_group/defaults/main.yml @@ -0,0 +1 @@ +--- diff --git a/tests/integration/targets/ec2_placement_group/meta/main.yml b/tests/integration/targets/ec2_placement_group/meta/main.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/ec2_placement_group/meta/main.yml @@ -0,0 +1 @@ +--- diff --git a/tests/integration/targets/ec2_placement_group/tasks/env_cleanup.yml b/tests/integration/targets/ec2_placement_group/tasks/env_cleanup.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/ec2_placement_group/tasks/env_cleanup.yml @@ -0,0 +1,94 @@ +- name: remove any instances in the test VPC + ec2_instance: + filters: + vpc_id: "{{ testing_vpc.vpc.id }}" + state: absent + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10 + +- name: Get ENIs + ec2_eni_info: + filters: + vpc-id: "{{ testing_vpc.vpc.id }}" + register: enis + +- name: delete all ENIs + ec2_eni: + eni_id: "{{ item.id }}" + state: absent + until: removed is not failed + with_items: "{{ enis.network_interfaces }}" + ignore_errors: yes + retries: 10 + +- name: remove the security group + ec2_group: + name: "{{ resource_prefix }}-sg" + description: a security group for ansible tests + vpc_id: "{{ testing_vpc.vpc.id }}" + state: absent + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10 + +- name: remove routing rules + ec2_vpc_route_table: + state: absent + vpc_id: "{{ testing_vpc.vpc.id }}" + tags: + created: "{{ resource_prefix }}-route" + routes: + - dest: 0.0.0.0/0 + gateway_id: "{{ igw.gateway_id }}" + subnets: + - "{{ testing_subnet_a.subnet.id }}" + - "{{ testing_subnet_b.subnet.id }}" + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10 + +- name: remove internet gateway + ec2_vpc_igw: + vpc_id: "{{ testing_vpc.vpc.id }}" + state: absent + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10 + +- name: remove subnet A + ec2_vpc_subnet: + state: absent + vpc_id: "{{ testing_vpc.vpc.id }}" + cidr: 10.22.32.0/24 + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10 + +- name: remove subnet B + ec2_vpc_subnet: + state: absent + vpc_id: "{{ testing_vpc.vpc.id }}" + cidr: 10.22.33.0/24 + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10 + +- name: remove the VPC + ec2_vpc_net: + name: "{{ resource_prefix }}-vpc" + cidr_block: 10.22.32.0/23 + state: absent + tags: + Name: Ansible Testing VPC + tenancy: default + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10 diff --git a/tests/integration/targets/ec2_placement_group/tasks/env_setup.yml b/tests/integration/targets/ec2_placement_group/tasks/env_setup.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/ec2_placement_group/tasks/env_setup.yml @@ -0,0 +1,64 @@ +- name: Create VPC for use in testing + ec2_vpc_net: + name: "{{ resource_prefix }}-vpc" + cidr_block: 10.22.32.0/23 + tags: + Name: Ansible ec2_lc Testing VPC + tenancy: default + register: testing_vpc + +- name: Create internet gateway for use in testing + ec2_vpc_igw: + vpc_id: "{{ testing_vpc.vpc.id }}" + state: present + tags: + Name: Ansible ec2_lc Testing gateway + register: igw + +- name: Create default subnet in zone A + ec2_vpc_subnet: + state: present + vpc_id: "{{ testing_vpc.vpc.id }}" + cidr: 10.22.32.0/24 + az: "{{ aws_region }}a" + resource_tags: + Name: "{{ resource_prefix }}-subnet-a" + register: testing_subnet_a + +- name: Create secondary subnet in zone B + ec2_vpc_subnet: + state: present + vpc_id: "{{ testing_vpc.vpc.id }}" + cidr: 10.22.33.0/24 + az: "{{ aws_region }}b" + resource_tags: + Name: "{{ resource_prefix }}-subnet-b" + register: testing_subnet_b + +- name: create routing rules + ec2_vpc_route_table: + vpc_id: "{{ testing_vpc.vpc.id }}" + tags: + created: "{{ resource_prefix }}-route" + routes: + - dest: 0.0.0.0/0 + gateway_id: "{{ igw.gateway_id }}" + subnets: + - "{{ testing_subnet_a.subnet.id }}" + - "{{ testing_subnet_b.subnet.id }}" + +- name: create a security group with the vpc + ec2_group: + name: "{{ resource_prefix }}-sg" + description: a security group for ansible tests + vpc_id: "{{ testing_vpc.vpc.id }}" + rules: + - proto: tcp + from_port: 22 + to_port: 22 + cidr_ip: 0.0.0.0/0 + - proto: tcp + from_port: 80 + to_port: 80 + cidr_ip: 0.0.0.0/0 + register: sg diff --git a/tests/integration/targets/ec2_placement_group/tasks/main.yml b/tests/integration/targets/ec2_placement_group/tasks/main.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/ec2_placement_group/tasks/main.yml @@ -0,0 +1,408 @@ +- name: run ec2_placement_group tests + module_defaults: + group/aws: + aws_access_key: "{{ aws_access_key }}" + aws_secret_key: "{{ aws_secret_key }}" + security_token: "{{ security_token | default(omit) }}" + region: "{{ aws_region }}" + collections: + - amazon.aws + vars: + placement_group_names: [] + + block: + + - name: set up environment for testing. + include_tasks: env_setup.yml + + - name: Create a placement group 1 - check_mode + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg1' + state: present + check_mode: true + register: pg_1_create_check_mode + + - assert: + that: + - pg_1_create_check_mode is changed + - pg_1_create_check_mode.placement_group.name == '{{ resource_prefix }}-pg1' + - pg_1_create_check_mode.placement_group.state == "DryRun" + - '"ec2:CreatePlacementGroup" in pg_1_create_check_mode.resource_actions' + + - name: Create a placement group 1 + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg1' + state: present + register: pg_1_create + + - set_fact: + placement_group_names: "{{ placement_group_names + [pg_1_create.placement_group.name] }}" + + - assert: + that: + - pg_1_create is changed + - pg_1_create.placement_group.name == '{{ resource_prefix }}-pg1' + - pg_1_create.placement_group.state == "available" + - '"ec2:CreatePlacementGroup" in pg_1_create.resource_actions' + + - name: Gather information about placement group 1 + community.aws.ec2_placement_group_info: + names: + - '{{ resource_prefix }}-pg1' + register: pg_1_info_result + + - assert: + that: + - pg_1_info_result is not changed + - pg_1_info_result.placement_groups[0].name == '{{ resource_prefix }}-pg1' + - pg_1_info_result.placement_groups[0].state == "available" + - pg_1_info_result.placement_groups[0].strategy == "cluster" + - '"ec2:DescribePlacementGroups" in pg_1_info_result.resource_actions' + + - name: Create a placement group 1 - Idempotency + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg1' + state: present + register: pg_1_create + + - assert: + that: + - pg_1_create is not changed + - pg_1_create.placement_group.name == '{{ resource_prefix }}-pg1' + - pg_1_create.placement_group.state == "available" + - '"ec2:CreatePlacementGroup" not in pg_1_create.resource_actions' + + - name: Create a placement group 1 - check_mode Idempotency + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg1' + state: present + check_mode: true + register: pg_1_create_check_mode_idem + + - assert: + that: + - pg_1_create_check_mode_idem is not changed + - pg_1_create_check_mode_idem.placement_group.name == '{{ resource_prefix }}-pg1' + - pg_1_create_check_mode_idem.placement_group.state == "available" + - '"ec2:CreatePlacementGroup" not in pg_1_create_check_mode_idem.resource_actions' + + - name: Create a placement group 2 - check_mode + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg2' + state: present + strategy: spread + check_mode: true + register: pg_2_create_check_mode + + - assert: + that: + - pg_2_create_check_mode is changed + - pg_2_create_check_mode.placement_group.name == '{{ resource_prefix }}-pg2' + - pg_2_create_check_mode.placement_group.state == "DryRun" + - '"ec2:CreatePlacementGroup" in pg_2_create_check_mode.resource_actions' + + - name: Create a placement group 2 with spread strategy + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg2' + state: present + strategy: spread + register: pg_2_create + + - assert: + that: + - pg_2_create is changed + - pg_2_create.placement_group.name == '{{ resource_prefix }}-pg2' + - pg_2_create.placement_group.state == "available" + - '"ec2:CreatePlacementGroup" in pg_2_create.resource_actions' + + - set_fact: + placement_group_names: "{{ placement_group_names + [pg_2_create.placement_group.name] }}" + + - name: Gather information about placement group 2 + community.aws.ec2_placement_group_info: + names: + - '{{ resource_prefix }}-pg2' + register: pg_2_info_result + + - assert: + that: + - pg_2_info_result is not changed + - pg_2_info_result.placement_groups[0].name == '{{ resource_prefix }}-pg2' + - pg_2_info_result.placement_groups[0].state == "available" + - pg_2_info_result.placement_groups[0].strategy == "spread" + - '"ec2:DescribePlacementGroups" in pg_2_info_result.resource_actions' + + - name: Create a placement group 2 with spread strategy - Idempotency + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg2' + state: present + strategy: spread + register: pg_2_create + + - assert: + that: + - pg_2_create is not changed + - pg_2_create.placement_group.name == '{{ resource_prefix }}-pg2' + - pg_2_create.placement_group.state == "available" + - '"ec2:CreatePlacementGroup" not in pg_2_create.resource_actions' + + - name: Create a placement group 2 - check_mode Idempotency + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg2' + state: present + strategy: spread + check_mode: true + register: pg_2_create_check_mode_idem + + - assert: + that: + - pg_2_create_check_mode_idem is not changed + - pg_2_create_check_mode_idem.placement_group.name == '{{ resource_prefix }}-pg2' + - pg_2_create_check_mode_idem.placement_group.state == "available" + - '"ec2:CreatePlacementGroup" not in pg_2_create_check_mode_idem.resource_actions' + + - name: Create a placement group 3 - check_mode + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg3' + state: present + strategy: partition + partition_count: 4 + check_mode: true + register: pg_3_create_check_mode + + - assert: + that: + - pg_3_create_check_mode is changed + - pg_3_create_check_mode.placement_group.name == '{{ resource_prefix }}-pg3' + - pg_3_create_check_mode.placement_group.state == "DryRun" + - '"ec2:CreatePlacementGroup" in pg_3_create_check_mode.resource_actions' + + - name: Create a placement group 3 with Partition strategy + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg3' + state: present + strategy: partition + partition_count: 4 + register: pg_3_create + + - assert: + that: + - pg_3_create is changed + - pg_3_create.placement_group.name == '{{ resource_prefix }}-pg3' + - pg_3_create.placement_group.state == "available" + - '"ec2:CreatePlacementGroup" in pg_3_create.resource_actions' + + - set_fact: + placement_group_names: "{{ placement_group_names + [pg_3_create.placement_group.name] }}" + + + - name: Gather information about placement group 3 + community.aws.ec2_placement_group_info: + names: + - '{{ resource_prefix }}-pg3' + register: pg_3_info_result + + - assert: + that: + - pg_3_info_result is not changed + - pg_3_info_result.placement_groups[0].name == '{{ resource_prefix }}-pg3' + - pg_3_info_result.placement_groups[0].state == "available" + - pg_3_info_result.placement_groups[0].strategy == "partition" + - '"ec2:DescribePlacementGroups" in pg_3_info_result.resource_actions' + + - name: Create a placement group 3 with Partition strategy - Idempotency + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg3' + state: present + strategy: partition + partition_count: 4 + register: pg_3_create + + - assert: + that: + - pg_3_create is not changed + - pg_3_create.placement_group.name == '{{ resource_prefix }}-pg3' + - pg_3_create.placement_group.state == "available" + - '"ec2:CreatePlacementGroup" not in pg_3_create.resource_actions' + + - name: Create a placement group 3 - check_mode Idempotency + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg3' + state: present + strategy: partition + partition_count: 4 + check_mode: true + register: pg_3_create_check_mode_idem + + - assert: + that: + - pg_3_create_check_mode_idem is not changed + - pg_3_create_check_mode_idem.placement_group.name == '{{ resource_prefix }}-pg3' + - pg_3_create_check_mode_idem.placement_group.state == "available" + - '"ec2:CreatePlacementGroup" not in pg_3_create_check_mode_idem.resource_actions' + + - name: List all placement groups. + community.aws.ec2_placement_group_info: + register: all_ec2_placement_groups + +# Delete Placement Group ========================================== + + # On using check_mode for delete placement group operation + # If operation would have succeeded, the error response is DryRunOperation. + # Otherwise, it is UnauthorizedOperation . + - name: Delete a placement group 1 - check_mode + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg1' + state: absent + check_mode: true + register: pg_1_delete_check_mode + ignore_errors: true + + - assert: + that: + - pg_1_delete_check_mode is not changed + - pg_1_delete_check_mode.error.code == 'DryRunOperation' + - '"ec2:DeletePlacementGroup" in pg_1_delete_check_mode.resource_actions' + + - name: Delete a placement group 1 + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg1' + state: absent + register: pg_1_delete + + - assert: + that: + - pg_1_delete is changed + - '"ec2:DeletePlacementGroup" in pg_1_delete.resource_actions' + + - name: Delete a placement group 1 - Idempotency + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg1' + state: absent + register: pg_1_delete + + - assert: + that: + - pg_1_delete is not changed + - '"ec2:DeletePlacementGroup" not in pg_1_delete.resource_actions' + + - name: Delete a placement group 1 - check_mode Idempotency + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg1' + state: absent + check_mode: true + register: pg_1_delete_check_mode_idem + ignore_errors: true + + - assert: + that: + - pg_1_delete_check_mode_idem is not changed + - '"ec2:DeletePlacementGroup" not in pg_1_delete_check_mode_idem.resource_actions' + + - name: Delete a placement group 2 - check_mode + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg2' + state: absent + check_mode: true + register: pg_2_delete_check_mode + ignore_errors: true + + - assert: + that: + - pg_2_delete_check_mode is not changed + - pg_2_delete_check_mode.error.code == 'DryRunOperation' + - '"ec2:DeletePlacementGroup" in pg_2_delete_check_mode.resource_actions' + + - name: Delete a placement group 2 + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg2' + state: absent + register: pg_2_delete + + - assert: + that: + - pg_2_delete is changed + - '"ec2:DeletePlacementGroup" in pg_2_delete.resource_actions' + + - name: Delete a placement group 2 - Idempotency + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg2' + state: absent + register: pg_2_delete + + - assert: + that: + - pg_2_delete is not changed + - '"ec2:DeletePlacementGroup" not in pg_2_delete.resource_actions' + + - name: Delete a placement group 2 - check_mode Idempotency + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg2' + state: absent + check_mode: true + register: pg_2_delete_check_mode_idem + ignore_errors: true + + - assert: + that: + - pg_2_delete_check_mode_idem is not changed + - '"ec2:DeletePlacementGroup" not in pg_2_delete_check_mode_idem.resource_actions' + + - name: Delete a placement group 3 - check_mode + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg3' + state: absent + check_mode: true + register: pg_3_delete_check_mode + ignore_errors: true + + - assert: + that: + - pg_3_delete_check_mode is not changed + - pg_3_delete_check_mode.error.code == 'DryRunOperation' + - '"ec2:DeletePlacementGroup" in pg_3_delete_check_mode.resource_actions' + + - name: Delete a placement group 3 + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg3' + state: absent + register: pg_3_delete + + - assert: + that: + - pg_3_delete is changed + - '"ec2:DeletePlacementGroup" in pg_3_delete.resource_actions' + + - name: Delete a placement group 3 - Idempotency + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg3' + state: absent + register: pg_3_delete + + - assert: + that: + - pg_3_delete is not changed + - '"ec2:DeletePlacementGroup" not in pg_3_delete.resource_actions' + + - name: Delete a placement group 3 - check_mode Idempotency + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg3' + state: absent + check_mode: true + register: pg_3_delete_check_mode_idem + ignore_errors: true + + - assert: + that: + - pg_3_delete_check_mode_idem is not changed + - '"ec2:DeletePlacementGroup" not in pg_3_delete_check_mode_idem.resource_actions' + + always: + + - name: Make sure placement groups created during test are deleted + community.aws.ec2_placement_group: + name: '{{ item }}' + state: absent + with_items: '{{ placement_group_names }}' + + - include_tasks: env_cleanup.yml diff --git a/tests/integration/targets/ec2_placement_group/vars/main.yml b/tests/integration/targets/ec2_placement_group/vars/main.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/ec2_placement_group/vars/main.yml @@ -0,0 +1 @@ +---
Add partition strategy to placement groups module ### Summary Add partition as a strategy for the community.aws.ec2_placement_group module. Also add an option to choose the actual number of partitions (min 2 which is the default and a max of 7). This option would be taken into account when the strategy is set to partition. ### Issue Type Feature Idea ### Component Name ec2_placement_group ### Additional Information Possible module definition ```yaml (paste below) - name: Create a Spread placement group. community.aws.ec2_placement_group: name: my-cluster state: present strategy: partition partition_number: 4 ``` ### Code of Conduct - [X] I agree to follow the Ansible Code of Conduct
@hferreira23, thank you for this feature idea. Would you be willing to open a PR to implement this feature?
2022-01-17T10:48:33
ansible-collections/community.aws
904
ansible-collections__community.aws-904
[ "830" ]
776bbb32433462ccafe84b8e3f2c1d475068d576
diff --git a/plugins/modules/execute_lambda.py b/plugins/modules/execute_lambda.py --- a/plugins/modules/execute_lambda.py +++ b/plugins/modules/execute_lambda.py @@ -202,6 +202,9 @@ def main(): elif name: invoke_params['FunctionName'] = name + if not module.check_mode: + wait_for_lambda(client, module, name) + try: response = client.invoke(**invoke_params) except is_boto3_error_code('ResourceNotFoundException') as nfe: @@ -255,5 +258,15 @@ def main(): module.exit_json(changed=True, result=results) +def wait_for_lambda(client, module, name): + try: + waiter = client.get_waiter('function_active') + waiter.wait(FunctionName=name) + except botocore.exceptions.WaiterError as e: + module.fail_json_aws(e, msg='Timeout while waiting on lambda to be Active') + except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: + module.fail_json_aws(e, msg='Failed while waiting on lambda to be Active') + + if __name__ == '__main__': main() diff --git a/plugins/modules/lambda.py b/plugins/modules/lambda.py --- a/plugins/modules/lambda.py +++ b/plugins/modules/lambda.py @@ -216,7 +216,7 @@ import re try: - from botocore.exceptions import ClientError, BotoCoreError + from botocore.exceptions import ClientError, BotoCoreError, WaiterError except ImportError: pass # protected by AnsibleAWSModule @@ -320,6 +320,18 @@ def set_tag(client, module, tags, function): return changed +def wait_for_lambda(client, module, name): + try: + client_active_waiter = client.get_waiter('function_active') + client_updated_waiter = client.get_waiter('function_updated') + client_active_waiter.wait(FunctionName=name) + client_updated_waiter.wait(FunctionName=name) + except WaiterError as e: + module.fail_json_aws(e, msg='Timeout while waiting on lambda to finish updating') + except (ClientError, BotoCoreError) as e: + module.fail_json_aws(e, msg='Failed while waiting on lambda to finish updating') + + def main(): argument_spec = dict( name=dict(required=True), @@ -453,6 +465,9 @@ def main(): # Upload new configuration if configuration has changed if len(func_kwargs) > 1: + if not check_mode: + wait_for_lambda(client, module, name) + try: if not check_mode: response = client.update_function_configuration(aws_retry=True, **func_kwargs) @@ -494,6 +509,9 @@ def main(): # Upload new code if needed (e.g. code checksum has changed) if len(code_kwargs) > 2: + if not check_mode: + wait_for_lambda(client, module, name) + try: if not check_mode: response = client.update_function_code(aws_retry=True, **code_kwargs)
lambda.py invokes update_function_configuration() and afterwards update_function_code() without checking Configuration.State and Configuration.LastUpdateStatus fields in between ### Summary lambda.py invokes `update_function_configuration()` [here](https://github.com/ansible-collections/community.aws/blob/main/plugins/modules/lambda.py#L458) and `afterwards update_function_code()` [here](https://github.com/ansible-collections/community.aws/blob/main/plugins/modules/lambda.py#L499) without checking `Configuration.State` and `Configuration.LastUpdateStatus` fields in between. If lambda function was updated in scope of the first call an error similar to below one is created during the second call: ``` An exception occurred during task execution. To see the full traceback, use -vvv. The error was: botocore.errorfactory.ResourceConflictException: An error occurred (ResourceConflictException) when calling the UpdateFunctionCode operation: The operation cannot be performed at this time. An update is in progress for resource: arn:aws:lambda:MY_REGION:MY_AWS_ACCOUNT_ID:function:MY_LAMBDA_FUNC_NAME fatal: [localhost]: FAILED! => {"boto3_version": "1.20.22", "botocore_version": "1.23.22", "changed": false, "error": {"code": "ResourceConflictException", "message": "The operation cannot be performed at this time. An update is in progress for resource: arn:aws:lambda:MY_REGION:MY_AWS_ACCOUNT_ID:function:MY_LAMBDA_FUNC_NAME"}, "message": "The operation cannot be performed at this time. An update is in progress for resource: arn:aws:lambda:MY_REGION:MY_AWS_ACCOUNT_ID:function:MY_LAMBDA_FUNC_NAME", "msg": "Trying to upload new code: An error occurred (ResourceConflictException) when calling the UpdateFunctionCode operation: The operation cannot be performed at this time. An update is in progress for resource: arn:aws:lambda:MY_REGION:MY_AWS_ACCOUNT_ID:function:MY_LAMBDA_FUNC_NAME", "response_metadata": {"http_headers": {"connection": "keep-alive", "content-length": "201", "content-type": "application/json", "date": "Thu, 09 Dec 2021 13:23:20 GMT", "x-amzn-errortype": "ResourceConflictException", "x-amzn-requestid": "abfc47a6-6c1c-42e4-b19d-853da87674bc"}, "http_status_code": 409, "request_id": "abfc47a6-6c1c-42e4-b19d-853da87674bc", "retry_attempts": 0}, "type": "User"} ``` ### Issue Type Bug Report ### Component Name lambda ### Ansible Version ```console (paste below) $ ansible --version ansible [core 2.12.0] config file = /home/my_dir/ansible.cfg configured module search path = ['/home/my_dir/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /home/my_dir/.venv/lib/python3.8/site-packages/ansible ansible collection location = /home/my_dir/.ansible/my_company/collections executable location = /home/my_dir/.venv/bin/ansible python version = 3.8.5 (v3.8.5:580fbb018f, Jul 20 2020, 12:11:27) [Clang 6.0 (clang-600.0.57)] jinja version = 2.11.3 libyaml = True``` ### Collection Versions ```console (paste below) $ ansible-galaxy collection list # /home/my_dir/.ansible/my_company/collections/ansible_collections Collection Version --------------------- ------- amazon.aws 3.0.0 ansible.netcommon 1.4.1 ansible.posix 1.3.0 community.aws 2.1.0 community.general 4.0.0 community.hashi_vault 1.3.2 community.kubernetes 1.2.1 community.sops 1.1.0 google.cloud 1.0.1 kubernetes.core 2.2.1 # /home/my_dir/.venv/lib/python3.8/site-packages/ansible_collections Collection Version ----------------------------- ------- amazon.aws 2.1.0 ansible.netcommon 2.4.0 ansible.posix 1.3.0 ansible.utils 2.4.2 ansible.windows 1.8.0 arista.eos 3.1.0 awx.awx 19.4.0 azure.azcollection 1.10.0 check_point.mgmt 2.1.1 chocolatey.chocolatey 1.1.0 cisco.aci 2.1.0 cisco.asa 2.1.0 cisco.intersight 1.0.17 cisco.ios 2.5.0 cisco.iosxr 2.5.0 cisco.ise 1.2.1 cisco.meraki 2.5.0 cisco.mso 1.2.0 cisco.nso 1.0.3 cisco.nxos 2.7.1 cisco.ucs 1.6.0 cloud.common 2.1.0 cloudscale_ch.cloud 2.2.0 community.aws 2.1.0 community.azure 1.1.0 community.ciscosmb 1.0.4 community.crypto 2.0.1 community.digitalocean 1.12.0 community.dns 2.0.3 community.docker 2.0.1 community.fortios 1.0.0 community.general 4.0.2 community.google 1.0.0 community.grafana 1.2.3 community.hashi_vault 2.0.0 community.hrobot 1.2.1 community.kubernetes 2.0.1 community.kubevirt 1.0.0 community.libvirt 1.0.2 community.mongodb 1.3.2 community.mysql 2.3.1 community.network 3.0.0 [0/1887] community.okd 2.1.0 community.postgresql 1.5.0 community.proxysql 1.3.0 community.rabbitmq 1.1.0 community.routeros 2.0.0 community.skydive 1.0.0 community.sops 1.2.0 community.vmware 1.16.0 community.windows 1.8.0 community.zabbix 1.5.0 containers.podman 1.8.2 cyberark.conjur 1.1.0 cyberark.pas 1.0.13 dellemc.enterprise_sonic 1.1.0 dellemc.openmanage 4.2.0 dellemc.os10 1.1.1 dellemc.os6 1.0.7 dellemc.os9 1.0.4 f5networks.f5_modules 1.12.0 fortinet.fortimanager 2.1.4 fortinet.fortios 2.1.3 frr.frr 1.0.3 gluster.gluster 1.0.2 google.cloud 1.0.2 hetzner.hcloud 1.6.0 hpe.nimble 1.1.3 ibm.qradar 1.0.3 infinidat.infinibox 1.3.0 infoblox.nios_modules 1.1.2 inspur.sm 1.3.0 junipernetworks.junos 2.6.0 kubernetes.core 2.2.1 mellanox.onyx 1.0.0 netapp.aws 21.7.0 netapp.azure 21.10.0 netapp.cloudmanager 21.12.0 netapp.elementsw 21.7.0 netapp.ontap 21.13.1 netapp.storagegrid 21.7.0 netapp.um_info 21.8.0 netapp_eseries.santricity 1.2.13 netbox.netbox 3.3.0 ngine_io.cloudstack 2.2.2 ngine_io.exoscale 1.0.0 ngine_io.vultr 1.1.0 openstack.cloud 1.5.3 openvswitch.openvswitch 2.0.2 ovirt.ovirt 1.6.5 purestorage.flasharray 1.11.0 purestorage.flashblade 1.8.1 sensu.sensu_go 1.12.0 servicenow.servicenow 1.0.6 splunk.es 1.0.2 t_systems_mms.icinga_director 1.24.0 theforeman.foreman 2.2.0 vyos.vyos 2.6.0 wti.remote 1.0.3 ``` ### AWS SDK versions ```console (paste below) $ pip show boto boto3 botocore Name: boto Version: 2.49.0 Summary: Amazon Web Services Library Home-page: https://github.com/boto/boto/ Author: Mitch Garnaat Author-email: [email protected] License: MIT Location:/home/my_dir/.venv/lib/python3.8/site-packages Requires: Required-by: --- Name: boto3 Version: 1.20.22 Summary: The AWS SDK for Python Home-page: https://github.com/boto/boto3 Author: Amazon Web Services Author-email: License: Apache License 2.0 Location: /home/my_dir/.venv/lib/python3.8/site-packages Requires: botocore, jmespath, s3transfer Required-by: --- Name: botocore Version: 1.23.22 Summary: Low-level, data-driven core of boto 3. Home-page: https://github.com/boto/botocore Author: Amazon Web Services Author-email: License: Apache License 2.0 Location: /home/my_dir/.venv/lib/python3.8/site-packages Requires: jmespath, python-dateutil, urllib3 Required-by: awscli, boto3, s3transfer ``` ### Configuration ```console (paste below) $ ansible-config dump --only-changed COLLECTIONS_PATHS(/home/my_dir/ansible.cfg) = ['/home/my_dir/.ansible/my_company/collections'] DEFAULT_HOST_LIST(/home/my_dir/ansible.cfg) = ['/dev/null'] DEFAULT_VAULT_PASSWORD_FILE(env: ANSIBLE_VAULT_PASSWORD_FILE) = /home/my_dir/.vault-ansible LOCALHOST_WARNING(/home/my_dir/ansible.cfg) = False RETRY_FILES_ENABLED(/home/my_dir/ansible.cfg) = False ``` ### OS / Environment macOS Big Sur 11.6 ### Steps to Reproduce <!--- Paste example playbooks or commands between quotes below --> 1. Change memory assignment in aws lambda gui to value different than the one set by Ansible 2. Wait until `aws lambda get-function --function-name YOUR_FUNCTION --query 'Configuration.[State, LastUpdateStatus]'` will return ``` [ "Active", "Successful" ] ``` 3. Invoke below ansible snippet ```yaml (paste below) - name: "Deploy lambda function" lambda: dead_letter_arn: "{{ 'arn:aws:sqs:{}:{}:{}-{}-lambda-deadletter'.format(aws_region, account, x, lambda_name) }}" description: "{{ lambda_description }}" environment_variables: "{{ lambda_env }}" handler: "{{ lambda_handler }}" memory_size: "{{ lambda_memory }}" name: "{{ lambda_full_name }}" role: "arn:aws:iam::{{ account }}:role/service-role/{{ lambda_iam_name }}" runtime: "{{ lambda_runtime }}" s3_bucket: "{{ lambda_s3_bucket }}" s3_key: "{{ lambda_s3_url }} timeout: "{{ lambda_timeout }}" vpc_security_group_ids: "{{ group_id }}" vpc_subnet_ids: "{{ subnets }}" region: "{{ aws_region }}" aws_access_key: "{{ access_key }}" aws_secret_key: "{{ secret_key }}" security_token: "{{ session_token }}" ``` ### Expected Results 4. Get the below error due to lambda function being still updated after `update_function_configuration()` call: ``` An exception occurred during task execution. To see the full traceback, use -vvv. The error was: botocore.errorfactory.ResourceConflictException: An error occurred (ResourceConflictException) when calling the UpdateFunctionCode operation: The operation cannot be performed at this time. An update is in progress for resource: arn:aws:lambda:MY_REGION:MY_AWS_ACCOUNT_ID:function:MY_LAMBDA_FUNC_NAME fatal: [localhost]: FAILED! => {"boto3_version": "1.20.22", "botocore_version": "1.23.22", "changed": false, "error": {"code": "ResourceConflictException", "message": "The operation cannot be performed at this time. An update is in progress for resource: arn:aws:lambda:MY_REGION:MY_AWS_ACCOUNT_ID:function:MY_LAMBDA_FUNC_NAME"}, "message": "The operation cannot be performed at this time. An update is in progress for resource: arn:aws:lambda:MY_REGION:MY_AWS_ACCOUNT_ID:function:MY_LAMBDA_FUNC_NAME", "msg": "Trying to upload new code: An error occurred (ResourceConflictException) when calling the UpdateFunctionCode operation: The operation cannot be performed at this time. An update is in progress for resource: arn:aws:lambda:MY_REGION:MY_AWS_ACCOUNT_ID:function:MY_LAMBDA_FUNC_NAME", "response_metadata": {"http_headers": {"connection": "keep-alive", "content-length": "201", "content-type": "application/json", "date": "Thu, 09 Dec 2021 13:23:20 GMT", "x-amzn-errortype": "ResourceConflictException", "x-amzn-requestid": "abfc47a6-6c1c-42e4-b19d-853da87674bc"}, "http_status_code": 409, "request_id": "abfc47a6-6c1c-42e4-b19d-853da87674bc", "retry_attempts": 0}, "type": "User"} ``` ### Actual Results ```console (paste below) ``` ### Code of Conduct - [X] I agree to follow the Ansible Code of Conduct
2022-01-30T01:11:23
ansible-collections/community.aws
905
ansible-collections__community.aws-905
[ "830" ]
99c64a6e9993aed6a825798079a2b964904beb72
diff --git a/plugins/modules/execute_lambda.py b/plugins/modules/execute_lambda.py --- a/plugins/modules/execute_lambda.py +++ b/plugins/modules/execute_lambda.py @@ -202,6 +202,9 @@ def main(): elif name: invoke_params['FunctionName'] = name + if not module.check_mode: + wait_for_lambda(client, module, name) + try: response = client.invoke(**invoke_params) except is_boto3_error_code('ResourceNotFoundException') as nfe: @@ -255,5 +258,15 @@ def main(): module.exit_json(changed=True, result=results) +def wait_for_lambda(client, module, name): + try: + waiter = client.get_waiter('function_active') + waiter.wait(FunctionName=name) + except botocore.exceptions.WaiterError as e: + module.fail_json_aws(e, msg='Timeout while waiting on lambda to be Active') + except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: + module.fail_json_aws(e, msg='Failed while waiting on lambda to be Active') + + if __name__ == '__main__': main() diff --git a/plugins/modules/lambda.py b/plugins/modules/lambda.py --- a/plugins/modules/lambda.py +++ b/plugins/modules/lambda.py @@ -216,7 +216,7 @@ import re try: - from botocore.exceptions import ClientError, BotoCoreError + from botocore.exceptions import ClientError, BotoCoreError, WaiterError except ImportError: pass # protected by AnsibleAWSModule @@ -320,6 +320,18 @@ def set_tag(client, module, tags, function): return changed +def wait_for_lambda(client, module, name): + try: + client_active_waiter = client.get_waiter('function_active') + client_updated_waiter = client.get_waiter('function_updated') + client_active_waiter.wait(FunctionName=name) + client_updated_waiter.wait(FunctionName=name) + except WaiterError as e: + module.fail_json_aws(e, msg='Timeout while waiting on lambda to finish updating') + except (ClientError, BotoCoreError) as e: + module.fail_json_aws(e, msg='Failed while waiting on lambda to finish updating') + + def main(): argument_spec = dict( name=dict(required=True), @@ -453,6 +465,9 @@ def main(): # Upload new configuration if configuration has changed if len(func_kwargs) > 1: + if not check_mode: + wait_for_lambda(client, module, name) + try: if not check_mode: response = client.update_function_configuration(aws_retry=True, **func_kwargs) @@ -494,6 +509,9 @@ def main(): # Upload new code if needed (e.g. code checksum has changed) if len(code_kwargs) > 2: + if not check_mode: + wait_for_lambda(client, module, name) + try: if not check_mode: response = client.update_function_code(aws_retry=True, **code_kwargs)
lambda.py invokes update_function_configuration() and afterwards update_function_code() without checking Configuration.State and Configuration.LastUpdateStatus fields in between ### Summary lambda.py invokes `update_function_configuration()` [here](https://github.com/ansible-collections/community.aws/blob/main/plugins/modules/lambda.py#L458) and `afterwards update_function_code()` [here](https://github.com/ansible-collections/community.aws/blob/main/plugins/modules/lambda.py#L499) without checking `Configuration.State` and `Configuration.LastUpdateStatus` fields in between. If lambda function was updated in scope of the first call an error similar to below one is created during the second call: ``` An exception occurred during task execution. To see the full traceback, use -vvv. The error was: botocore.errorfactory.ResourceConflictException: An error occurred (ResourceConflictException) when calling the UpdateFunctionCode operation: The operation cannot be performed at this time. An update is in progress for resource: arn:aws:lambda:MY_REGION:MY_AWS_ACCOUNT_ID:function:MY_LAMBDA_FUNC_NAME fatal: [localhost]: FAILED! => {"boto3_version": "1.20.22", "botocore_version": "1.23.22", "changed": false, "error": {"code": "ResourceConflictException", "message": "The operation cannot be performed at this time. An update is in progress for resource: arn:aws:lambda:MY_REGION:MY_AWS_ACCOUNT_ID:function:MY_LAMBDA_FUNC_NAME"}, "message": "The operation cannot be performed at this time. An update is in progress for resource: arn:aws:lambda:MY_REGION:MY_AWS_ACCOUNT_ID:function:MY_LAMBDA_FUNC_NAME", "msg": "Trying to upload new code: An error occurred (ResourceConflictException) when calling the UpdateFunctionCode operation: The operation cannot be performed at this time. An update is in progress for resource: arn:aws:lambda:MY_REGION:MY_AWS_ACCOUNT_ID:function:MY_LAMBDA_FUNC_NAME", "response_metadata": {"http_headers": {"connection": "keep-alive", "content-length": "201", "content-type": "application/json", "date": "Thu, 09 Dec 2021 13:23:20 GMT", "x-amzn-errortype": "ResourceConflictException", "x-amzn-requestid": "abfc47a6-6c1c-42e4-b19d-853da87674bc"}, "http_status_code": 409, "request_id": "abfc47a6-6c1c-42e4-b19d-853da87674bc", "retry_attempts": 0}, "type": "User"} ``` ### Issue Type Bug Report ### Component Name lambda ### Ansible Version ```console (paste below) $ ansible --version ansible [core 2.12.0] config file = /home/my_dir/ansible.cfg configured module search path = ['/home/my_dir/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /home/my_dir/.venv/lib/python3.8/site-packages/ansible ansible collection location = /home/my_dir/.ansible/my_company/collections executable location = /home/my_dir/.venv/bin/ansible python version = 3.8.5 (v3.8.5:580fbb018f, Jul 20 2020, 12:11:27) [Clang 6.0 (clang-600.0.57)] jinja version = 2.11.3 libyaml = True``` ### Collection Versions ```console (paste below) $ ansible-galaxy collection list # /home/my_dir/.ansible/my_company/collections/ansible_collections Collection Version --------------------- ------- amazon.aws 3.0.0 ansible.netcommon 1.4.1 ansible.posix 1.3.0 community.aws 2.1.0 community.general 4.0.0 community.hashi_vault 1.3.2 community.kubernetes 1.2.1 community.sops 1.1.0 google.cloud 1.0.1 kubernetes.core 2.2.1 # /home/my_dir/.venv/lib/python3.8/site-packages/ansible_collections Collection Version ----------------------------- ------- amazon.aws 2.1.0 ansible.netcommon 2.4.0 ansible.posix 1.3.0 ansible.utils 2.4.2 ansible.windows 1.8.0 arista.eos 3.1.0 awx.awx 19.4.0 azure.azcollection 1.10.0 check_point.mgmt 2.1.1 chocolatey.chocolatey 1.1.0 cisco.aci 2.1.0 cisco.asa 2.1.0 cisco.intersight 1.0.17 cisco.ios 2.5.0 cisco.iosxr 2.5.0 cisco.ise 1.2.1 cisco.meraki 2.5.0 cisco.mso 1.2.0 cisco.nso 1.0.3 cisco.nxos 2.7.1 cisco.ucs 1.6.0 cloud.common 2.1.0 cloudscale_ch.cloud 2.2.0 community.aws 2.1.0 community.azure 1.1.0 community.ciscosmb 1.0.4 community.crypto 2.0.1 community.digitalocean 1.12.0 community.dns 2.0.3 community.docker 2.0.1 community.fortios 1.0.0 community.general 4.0.2 community.google 1.0.0 community.grafana 1.2.3 community.hashi_vault 2.0.0 community.hrobot 1.2.1 community.kubernetes 2.0.1 community.kubevirt 1.0.0 community.libvirt 1.0.2 community.mongodb 1.3.2 community.mysql 2.3.1 community.network 3.0.0 [0/1887] community.okd 2.1.0 community.postgresql 1.5.0 community.proxysql 1.3.0 community.rabbitmq 1.1.0 community.routeros 2.0.0 community.skydive 1.0.0 community.sops 1.2.0 community.vmware 1.16.0 community.windows 1.8.0 community.zabbix 1.5.0 containers.podman 1.8.2 cyberark.conjur 1.1.0 cyberark.pas 1.0.13 dellemc.enterprise_sonic 1.1.0 dellemc.openmanage 4.2.0 dellemc.os10 1.1.1 dellemc.os6 1.0.7 dellemc.os9 1.0.4 f5networks.f5_modules 1.12.0 fortinet.fortimanager 2.1.4 fortinet.fortios 2.1.3 frr.frr 1.0.3 gluster.gluster 1.0.2 google.cloud 1.0.2 hetzner.hcloud 1.6.0 hpe.nimble 1.1.3 ibm.qradar 1.0.3 infinidat.infinibox 1.3.0 infoblox.nios_modules 1.1.2 inspur.sm 1.3.0 junipernetworks.junos 2.6.0 kubernetes.core 2.2.1 mellanox.onyx 1.0.0 netapp.aws 21.7.0 netapp.azure 21.10.0 netapp.cloudmanager 21.12.0 netapp.elementsw 21.7.0 netapp.ontap 21.13.1 netapp.storagegrid 21.7.0 netapp.um_info 21.8.0 netapp_eseries.santricity 1.2.13 netbox.netbox 3.3.0 ngine_io.cloudstack 2.2.2 ngine_io.exoscale 1.0.0 ngine_io.vultr 1.1.0 openstack.cloud 1.5.3 openvswitch.openvswitch 2.0.2 ovirt.ovirt 1.6.5 purestorage.flasharray 1.11.0 purestorage.flashblade 1.8.1 sensu.sensu_go 1.12.0 servicenow.servicenow 1.0.6 splunk.es 1.0.2 t_systems_mms.icinga_director 1.24.0 theforeman.foreman 2.2.0 vyos.vyos 2.6.0 wti.remote 1.0.3 ``` ### AWS SDK versions ```console (paste below) $ pip show boto boto3 botocore Name: boto Version: 2.49.0 Summary: Amazon Web Services Library Home-page: https://github.com/boto/boto/ Author: Mitch Garnaat Author-email: [email protected] License: MIT Location:/home/my_dir/.venv/lib/python3.8/site-packages Requires: Required-by: --- Name: boto3 Version: 1.20.22 Summary: The AWS SDK for Python Home-page: https://github.com/boto/boto3 Author: Amazon Web Services Author-email: License: Apache License 2.0 Location: /home/my_dir/.venv/lib/python3.8/site-packages Requires: botocore, jmespath, s3transfer Required-by: --- Name: botocore Version: 1.23.22 Summary: Low-level, data-driven core of boto 3. Home-page: https://github.com/boto/botocore Author: Amazon Web Services Author-email: License: Apache License 2.0 Location: /home/my_dir/.venv/lib/python3.8/site-packages Requires: jmespath, python-dateutil, urllib3 Required-by: awscli, boto3, s3transfer ``` ### Configuration ```console (paste below) $ ansible-config dump --only-changed COLLECTIONS_PATHS(/home/my_dir/ansible.cfg) = ['/home/my_dir/.ansible/my_company/collections'] DEFAULT_HOST_LIST(/home/my_dir/ansible.cfg) = ['/dev/null'] DEFAULT_VAULT_PASSWORD_FILE(env: ANSIBLE_VAULT_PASSWORD_FILE) = /home/my_dir/.vault-ansible LOCALHOST_WARNING(/home/my_dir/ansible.cfg) = False RETRY_FILES_ENABLED(/home/my_dir/ansible.cfg) = False ``` ### OS / Environment macOS Big Sur 11.6 ### Steps to Reproduce <!--- Paste example playbooks or commands between quotes below --> 1. Change memory assignment in aws lambda gui to value different than the one set by Ansible 2. Wait until `aws lambda get-function --function-name YOUR_FUNCTION --query 'Configuration.[State, LastUpdateStatus]'` will return ``` [ "Active", "Successful" ] ``` 3. Invoke below ansible snippet ```yaml (paste below) - name: "Deploy lambda function" lambda: dead_letter_arn: "{{ 'arn:aws:sqs:{}:{}:{}-{}-lambda-deadletter'.format(aws_region, account, x, lambda_name) }}" description: "{{ lambda_description }}" environment_variables: "{{ lambda_env }}" handler: "{{ lambda_handler }}" memory_size: "{{ lambda_memory }}" name: "{{ lambda_full_name }}" role: "arn:aws:iam::{{ account }}:role/service-role/{{ lambda_iam_name }}" runtime: "{{ lambda_runtime }}" s3_bucket: "{{ lambda_s3_bucket }}" s3_key: "{{ lambda_s3_url }} timeout: "{{ lambda_timeout }}" vpc_security_group_ids: "{{ group_id }}" vpc_subnet_ids: "{{ subnets }}" region: "{{ aws_region }}" aws_access_key: "{{ access_key }}" aws_secret_key: "{{ secret_key }}" security_token: "{{ session_token }}" ``` ### Expected Results 4. Get the below error due to lambda function being still updated after `update_function_configuration()` call: ``` An exception occurred during task execution. To see the full traceback, use -vvv. The error was: botocore.errorfactory.ResourceConflictException: An error occurred (ResourceConflictException) when calling the UpdateFunctionCode operation: The operation cannot be performed at this time. An update is in progress for resource: arn:aws:lambda:MY_REGION:MY_AWS_ACCOUNT_ID:function:MY_LAMBDA_FUNC_NAME fatal: [localhost]: FAILED! => {"boto3_version": "1.20.22", "botocore_version": "1.23.22", "changed": false, "error": {"code": "ResourceConflictException", "message": "The operation cannot be performed at this time. An update is in progress for resource: arn:aws:lambda:MY_REGION:MY_AWS_ACCOUNT_ID:function:MY_LAMBDA_FUNC_NAME"}, "message": "The operation cannot be performed at this time. An update is in progress for resource: arn:aws:lambda:MY_REGION:MY_AWS_ACCOUNT_ID:function:MY_LAMBDA_FUNC_NAME", "msg": "Trying to upload new code: An error occurred (ResourceConflictException) when calling the UpdateFunctionCode operation: The operation cannot be performed at this time. An update is in progress for resource: arn:aws:lambda:MY_REGION:MY_AWS_ACCOUNT_ID:function:MY_LAMBDA_FUNC_NAME", "response_metadata": {"http_headers": {"connection": "keep-alive", "content-length": "201", "content-type": "application/json", "date": "Thu, 09 Dec 2021 13:23:20 GMT", "x-amzn-errortype": "ResourceConflictException", "x-amzn-requestid": "abfc47a6-6c1c-42e4-b19d-853da87674bc"}, "http_status_code": 409, "request_id": "abfc47a6-6c1c-42e4-b19d-853da87674bc", "retry_attempts": 0}, "type": "User"} ``` ### Actual Results ```console (paste below) ``` ### Code of Conduct - [X] I agree to follow the Ansible Code of Conduct
2022-01-30T01:11:30
ansible-collections/community.aws
928
ansible-collections__community.aws-928
[ "808" ]
c46b0a44a43ce83d65898bb465791cd6ef1c2b7d
diff --git a/plugins/modules/ec2_placement_group.py b/plugins/modules/ec2_placement_group.py --- a/plugins/modules/ec2_placement_group.py +++ b/plugins/modules/ec2_placement_group.py @@ -23,6 +23,13 @@ - The name for the placement group. required: true type: str + partition_count: + description: + - The number of partitions. + - Valid only when I(Strategy) is set to C(partition). + - Must be a value between C(1) and C(7). + type: int + version_added: 3.1.0 state: description: - Create or delete placement group. @@ -35,7 +42,7 @@ low-latency group in a single Availability Zone, while Spread spreads instances across underlying hardware. default: cluster - choices: [ 'cluster', 'spread' ] + choices: [ 'cluster', 'spread', 'partition' ] type: str extends_documentation_fragment: - amazon.aws.aws @@ -58,6 +65,13 @@ state: present strategy: spread +- name: Create a Partition strategy placement group. + community.aws.ec2_placement_group: + name: my-cluster + state: present + strategy: partition + partition_count: 3 + - name: Delete a placement group. community.aws.ec2_placement_group: name: my-cluster @@ -126,10 +140,21 @@ def get_placement_group_details(connection, module): def create_placement_group(connection, module): name = module.params.get("name") strategy = module.params.get("strategy") + partition_count = module.params.get("partition_count") + + if strategy != 'partition' and partition_count: + module.fail_json( + msg="'partition_count' can only be set when strategy is set to 'partition'.") + + params = {} + params['GroupName'] = name + params['Strategy'] = strategy + if partition_count: + params['PartitionCount'] = partition_count + params['DryRun'] = module.check_mode try: - connection.create_placement_group( - GroupName=name, Strategy=strategy, DryRun=module.check_mode) + connection.create_placement_group(**params) except is_boto3_error_code('DryRunOperation'): module.exit_json(changed=True, placement_group={ "name": name, @@ -165,8 +190,9 @@ def delete_placement_group(connection, module): def main(): argument_spec = dict( name=dict(required=True, type='str'), + partition_count=dict(type='int'), state=dict(default='present', choices=['present', 'absent']), - strategy=dict(default='cluster', choices=['cluster', 'spread']) + strategy=dict(default='cluster', choices=['cluster', 'spread', 'partition']) ) module = AnsibleAWSModule(
diff --git a/tests/integration/targets/ec2_placement_group/aliases b/tests/integration/targets/ec2_placement_group/aliases new file mode 100644 --- /dev/null +++ b/tests/integration/targets/ec2_placement_group/aliases @@ -0,0 +1,3 @@ +cloud/aws + +ec2_placement_group_info diff --git a/tests/integration/targets/ec2_placement_group/defaults/main.yml b/tests/integration/targets/ec2_placement_group/defaults/main.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/ec2_placement_group/defaults/main.yml @@ -0,0 +1 @@ +--- diff --git a/tests/integration/targets/ec2_placement_group/meta/main.yml b/tests/integration/targets/ec2_placement_group/meta/main.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/ec2_placement_group/meta/main.yml @@ -0,0 +1 @@ +--- diff --git a/tests/integration/targets/ec2_placement_group/tasks/env_cleanup.yml b/tests/integration/targets/ec2_placement_group/tasks/env_cleanup.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/ec2_placement_group/tasks/env_cleanup.yml @@ -0,0 +1,94 @@ +- name: remove any instances in the test VPC + ec2_instance: + filters: + vpc_id: "{{ testing_vpc.vpc.id }}" + state: absent + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10 + +- name: Get ENIs + ec2_eni_info: + filters: + vpc-id: "{{ testing_vpc.vpc.id }}" + register: enis + +- name: delete all ENIs + ec2_eni: + eni_id: "{{ item.id }}" + state: absent + until: removed is not failed + with_items: "{{ enis.network_interfaces }}" + ignore_errors: yes + retries: 10 + +- name: remove the security group + ec2_group: + name: "{{ resource_prefix }}-sg" + description: a security group for ansible tests + vpc_id: "{{ testing_vpc.vpc.id }}" + state: absent + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10 + +- name: remove routing rules + ec2_vpc_route_table: + state: absent + vpc_id: "{{ testing_vpc.vpc.id }}" + tags: + created: "{{ resource_prefix }}-route" + routes: + - dest: 0.0.0.0/0 + gateway_id: "{{ igw.gateway_id }}" + subnets: + - "{{ testing_subnet_a.subnet.id }}" + - "{{ testing_subnet_b.subnet.id }}" + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10 + +- name: remove internet gateway + ec2_vpc_igw: + vpc_id: "{{ testing_vpc.vpc.id }}" + state: absent + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10 + +- name: remove subnet A + ec2_vpc_subnet: + state: absent + vpc_id: "{{ testing_vpc.vpc.id }}" + cidr: 10.22.32.0/24 + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10 + +- name: remove subnet B + ec2_vpc_subnet: + state: absent + vpc_id: "{{ testing_vpc.vpc.id }}" + cidr: 10.22.33.0/24 + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10 + +- name: remove the VPC + ec2_vpc_net: + name: "{{ resource_prefix }}-vpc" + cidr_block: 10.22.32.0/23 + state: absent + tags: + Name: Ansible Testing VPC + tenancy: default + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10 diff --git a/tests/integration/targets/ec2_placement_group/tasks/env_setup.yml b/tests/integration/targets/ec2_placement_group/tasks/env_setup.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/ec2_placement_group/tasks/env_setup.yml @@ -0,0 +1,64 @@ +- name: Create VPC for use in testing + ec2_vpc_net: + name: "{{ resource_prefix }}-vpc" + cidr_block: 10.22.32.0/23 + tags: + Name: Ansible ec2_lc Testing VPC + tenancy: default + register: testing_vpc + +- name: Create internet gateway for use in testing + ec2_vpc_igw: + vpc_id: "{{ testing_vpc.vpc.id }}" + state: present + tags: + Name: Ansible ec2_lc Testing gateway + register: igw + +- name: Create default subnet in zone A + ec2_vpc_subnet: + state: present + vpc_id: "{{ testing_vpc.vpc.id }}" + cidr: 10.22.32.0/24 + az: "{{ aws_region }}a" + resource_tags: + Name: "{{ resource_prefix }}-subnet-a" + register: testing_subnet_a + +- name: Create secondary subnet in zone B + ec2_vpc_subnet: + state: present + vpc_id: "{{ testing_vpc.vpc.id }}" + cidr: 10.22.33.0/24 + az: "{{ aws_region }}b" + resource_tags: + Name: "{{ resource_prefix }}-subnet-b" + register: testing_subnet_b + +- name: create routing rules + ec2_vpc_route_table: + vpc_id: "{{ testing_vpc.vpc.id }}" + tags: + created: "{{ resource_prefix }}-route" + routes: + - dest: 0.0.0.0/0 + gateway_id: "{{ igw.gateway_id }}" + subnets: + - "{{ testing_subnet_a.subnet.id }}" + - "{{ testing_subnet_b.subnet.id }}" + +- name: create a security group with the vpc + ec2_group: + name: "{{ resource_prefix }}-sg" + description: a security group for ansible tests + vpc_id: "{{ testing_vpc.vpc.id }}" + rules: + - proto: tcp + from_port: 22 + to_port: 22 + cidr_ip: 0.0.0.0/0 + - proto: tcp + from_port: 80 + to_port: 80 + cidr_ip: 0.0.0.0/0 + register: sg diff --git a/tests/integration/targets/ec2_placement_group/tasks/main.yml b/tests/integration/targets/ec2_placement_group/tasks/main.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/ec2_placement_group/tasks/main.yml @@ -0,0 +1,408 @@ +- name: run ec2_placement_group tests + module_defaults: + group/aws: + aws_access_key: "{{ aws_access_key }}" + aws_secret_key: "{{ aws_secret_key }}" + security_token: "{{ security_token | default(omit) }}" + region: "{{ aws_region }}" + collections: + - amazon.aws + vars: + placement_group_names: [] + + block: + + - name: set up environment for testing. + include_tasks: env_setup.yml + + - name: Create a placement group 1 - check_mode + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg1' + state: present + check_mode: true + register: pg_1_create_check_mode + + - assert: + that: + - pg_1_create_check_mode is changed + - pg_1_create_check_mode.placement_group.name == '{{ resource_prefix }}-pg1' + - pg_1_create_check_mode.placement_group.state == "DryRun" + - '"ec2:CreatePlacementGroup" in pg_1_create_check_mode.resource_actions' + + - name: Create a placement group 1 + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg1' + state: present + register: pg_1_create + + - set_fact: + placement_group_names: "{{ placement_group_names + [pg_1_create.placement_group.name] }}" + + - assert: + that: + - pg_1_create is changed + - pg_1_create.placement_group.name == '{{ resource_prefix }}-pg1' + - pg_1_create.placement_group.state == "available" + - '"ec2:CreatePlacementGroup" in pg_1_create.resource_actions' + + - name: Gather information about placement group 1 + community.aws.ec2_placement_group_info: + names: + - '{{ resource_prefix }}-pg1' + register: pg_1_info_result + + - assert: + that: + - pg_1_info_result is not changed + - pg_1_info_result.placement_groups[0].name == '{{ resource_prefix }}-pg1' + - pg_1_info_result.placement_groups[0].state == "available" + - pg_1_info_result.placement_groups[0].strategy == "cluster" + - '"ec2:DescribePlacementGroups" in pg_1_info_result.resource_actions' + + - name: Create a placement group 1 - Idempotency + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg1' + state: present + register: pg_1_create + + - assert: + that: + - pg_1_create is not changed + - pg_1_create.placement_group.name == '{{ resource_prefix }}-pg1' + - pg_1_create.placement_group.state == "available" + - '"ec2:CreatePlacementGroup" not in pg_1_create.resource_actions' + + - name: Create a placement group 1 - check_mode Idempotency + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg1' + state: present + check_mode: true + register: pg_1_create_check_mode_idem + + - assert: + that: + - pg_1_create_check_mode_idem is not changed + - pg_1_create_check_mode_idem.placement_group.name == '{{ resource_prefix }}-pg1' + - pg_1_create_check_mode_idem.placement_group.state == "available" + - '"ec2:CreatePlacementGroup" not in pg_1_create_check_mode_idem.resource_actions' + + - name: Create a placement group 2 - check_mode + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg2' + state: present + strategy: spread + check_mode: true + register: pg_2_create_check_mode + + - assert: + that: + - pg_2_create_check_mode is changed + - pg_2_create_check_mode.placement_group.name == '{{ resource_prefix }}-pg2' + - pg_2_create_check_mode.placement_group.state == "DryRun" + - '"ec2:CreatePlacementGroup" in pg_2_create_check_mode.resource_actions' + + - name: Create a placement group 2 with spread strategy + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg2' + state: present + strategy: spread + register: pg_2_create + + - assert: + that: + - pg_2_create is changed + - pg_2_create.placement_group.name == '{{ resource_prefix }}-pg2' + - pg_2_create.placement_group.state == "available" + - '"ec2:CreatePlacementGroup" in pg_2_create.resource_actions' + + - set_fact: + placement_group_names: "{{ placement_group_names + [pg_2_create.placement_group.name] }}" + + - name: Gather information about placement group 2 + community.aws.ec2_placement_group_info: + names: + - '{{ resource_prefix }}-pg2' + register: pg_2_info_result + + - assert: + that: + - pg_2_info_result is not changed + - pg_2_info_result.placement_groups[0].name == '{{ resource_prefix }}-pg2' + - pg_2_info_result.placement_groups[0].state == "available" + - pg_2_info_result.placement_groups[0].strategy == "spread" + - '"ec2:DescribePlacementGroups" in pg_2_info_result.resource_actions' + + - name: Create a placement group 2 with spread strategy - Idempotency + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg2' + state: present + strategy: spread + register: pg_2_create + + - assert: + that: + - pg_2_create is not changed + - pg_2_create.placement_group.name == '{{ resource_prefix }}-pg2' + - pg_2_create.placement_group.state == "available" + - '"ec2:CreatePlacementGroup" not in pg_2_create.resource_actions' + + - name: Create a placement group 2 - check_mode Idempotency + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg2' + state: present + strategy: spread + check_mode: true + register: pg_2_create_check_mode_idem + + - assert: + that: + - pg_2_create_check_mode_idem is not changed + - pg_2_create_check_mode_idem.placement_group.name == '{{ resource_prefix }}-pg2' + - pg_2_create_check_mode_idem.placement_group.state == "available" + - '"ec2:CreatePlacementGroup" not in pg_2_create_check_mode_idem.resource_actions' + + - name: Create a placement group 3 - check_mode + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg3' + state: present + strategy: partition + partition_count: 4 + check_mode: true + register: pg_3_create_check_mode + + - assert: + that: + - pg_3_create_check_mode is changed + - pg_3_create_check_mode.placement_group.name == '{{ resource_prefix }}-pg3' + - pg_3_create_check_mode.placement_group.state == "DryRun" + - '"ec2:CreatePlacementGroup" in pg_3_create_check_mode.resource_actions' + + - name: Create a placement group 3 with Partition strategy + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg3' + state: present + strategy: partition + partition_count: 4 + register: pg_3_create + + - assert: + that: + - pg_3_create is changed + - pg_3_create.placement_group.name == '{{ resource_prefix }}-pg3' + - pg_3_create.placement_group.state == "available" + - '"ec2:CreatePlacementGroup" in pg_3_create.resource_actions' + + - set_fact: + placement_group_names: "{{ placement_group_names + [pg_3_create.placement_group.name] }}" + + + - name: Gather information about placement group 3 + community.aws.ec2_placement_group_info: + names: + - '{{ resource_prefix }}-pg3' + register: pg_3_info_result + + - assert: + that: + - pg_3_info_result is not changed + - pg_3_info_result.placement_groups[0].name == '{{ resource_prefix }}-pg3' + - pg_3_info_result.placement_groups[0].state == "available" + - pg_3_info_result.placement_groups[0].strategy == "partition" + - '"ec2:DescribePlacementGroups" in pg_3_info_result.resource_actions' + + - name: Create a placement group 3 with Partition strategy - Idempotency + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg3' + state: present + strategy: partition + partition_count: 4 + register: pg_3_create + + - assert: + that: + - pg_3_create is not changed + - pg_3_create.placement_group.name == '{{ resource_prefix }}-pg3' + - pg_3_create.placement_group.state == "available" + - '"ec2:CreatePlacementGroup" not in pg_3_create.resource_actions' + + - name: Create a placement group 3 - check_mode Idempotency + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg3' + state: present + strategy: partition + partition_count: 4 + check_mode: true + register: pg_3_create_check_mode_idem + + - assert: + that: + - pg_3_create_check_mode_idem is not changed + - pg_3_create_check_mode_idem.placement_group.name == '{{ resource_prefix }}-pg3' + - pg_3_create_check_mode_idem.placement_group.state == "available" + - '"ec2:CreatePlacementGroup" not in pg_3_create_check_mode_idem.resource_actions' + + - name: List all placement groups. + community.aws.ec2_placement_group_info: + register: all_ec2_placement_groups + +# Delete Placement Group ========================================== + + # On using check_mode for delete placement group operation + # If operation would have succeeded, the error response is DryRunOperation. + # Otherwise, it is UnauthorizedOperation . + - name: Delete a placement group 1 - check_mode + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg1' + state: absent + check_mode: true + register: pg_1_delete_check_mode + ignore_errors: true + + - assert: + that: + - pg_1_delete_check_mode is not changed + - pg_1_delete_check_mode.error.code == 'DryRunOperation' + - '"ec2:DeletePlacementGroup" in pg_1_delete_check_mode.resource_actions' + + - name: Delete a placement group 1 + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg1' + state: absent + register: pg_1_delete + + - assert: + that: + - pg_1_delete is changed + - '"ec2:DeletePlacementGroup" in pg_1_delete.resource_actions' + + - name: Delete a placement group 1 - Idempotency + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg1' + state: absent + register: pg_1_delete + + - assert: + that: + - pg_1_delete is not changed + - '"ec2:DeletePlacementGroup" not in pg_1_delete.resource_actions' + + - name: Delete a placement group 1 - check_mode Idempotency + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg1' + state: absent + check_mode: true + register: pg_1_delete_check_mode_idem + ignore_errors: true + + - assert: + that: + - pg_1_delete_check_mode_idem is not changed + - '"ec2:DeletePlacementGroup" not in pg_1_delete_check_mode_idem.resource_actions' + + - name: Delete a placement group 2 - check_mode + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg2' + state: absent + check_mode: true + register: pg_2_delete_check_mode + ignore_errors: true + + - assert: + that: + - pg_2_delete_check_mode is not changed + - pg_2_delete_check_mode.error.code == 'DryRunOperation' + - '"ec2:DeletePlacementGroup" in pg_2_delete_check_mode.resource_actions' + + - name: Delete a placement group 2 + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg2' + state: absent + register: pg_2_delete + + - assert: + that: + - pg_2_delete is changed + - '"ec2:DeletePlacementGroup" in pg_2_delete.resource_actions' + + - name: Delete a placement group 2 - Idempotency + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg2' + state: absent + register: pg_2_delete + + - assert: + that: + - pg_2_delete is not changed + - '"ec2:DeletePlacementGroup" not in pg_2_delete.resource_actions' + + - name: Delete a placement group 2 - check_mode Idempotency + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg2' + state: absent + check_mode: true + register: pg_2_delete_check_mode_idem + ignore_errors: true + + - assert: + that: + - pg_2_delete_check_mode_idem is not changed + - '"ec2:DeletePlacementGroup" not in pg_2_delete_check_mode_idem.resource_actions' + + - name: Delete a placement group 3 - check_mode + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg3' + state: absent + check_mode: true + register: pg_3_delete_check_mode + ignore_errors: true + + - assert: + that: + - pg_3_delete_check_mode is not changed + - pg_3_delete_check_mode.error.code == 'DryRunOperation' + - '"ec2:DeletePlacementGroup" in pg_3_delete_check_mode.resource_actions' + + - name: Delete a placement group 3 + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg3' + state: absent + register: pg_3_delete + + - assert: + that: + - pg_3_delete is changed + - '"ec2:DeletePlacementGroup" in pg_3_delete.resource_actions' + + - name: Delete a placement group 3 - Idempotency + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg3' + state: absent + register: pg_3_delete + + - assert: + that: + - pg_3_delete is not changed + - '"ec2:DeletePlacementGroup" not in pg_3_delete.resource_actions' + + - name: Delete a placement group 3 - check_mode Idempotency + community.aws.ec2_placement_group: + name: '{{ resource_prefix }}-pg3' + state: absent + check_mode: true + register: pg_3_delete_check_mode_idem + ignore_errors: true + + - assert: + that: + - pg_3_delete_check_mode_idem is not changed + - '"ec2:DeletePlacementGroup" not in pg_3_delete_check_mode_idem.resource_actions' + + always: + + - name: Make sure placement groups created during test are deleted + community.aws.ec2_placement_group: + name: '{{ item }}' + state: absent + with_items: '{{ placement_group_names }}' + + - include_tasks: env_cleanup.yml diff --git a/tests/integration/targets/ec2_placement_group/vars/main.yml b/tests/integration/targets/ec2_placement_group/vars/main.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/ec2_placement_group/vars/main.yml @@ -0,0 +1 @@ +---
Add partition strategy to placement groups module ### Summary Add partition as a strategy for the community.aws.ec2_placement_group module. Also add an option to choose the actual number of partitions (min 2 which is the default and a max of 7). This option would be taken into account when the strategy is set to partition. ### Issue Type Feature Idea ### Component Name ec2_placement_group ### Additional Information Possible module definition ```yaml (paste below) - name: Create a Spread placement group. community.aws.ec2_placement_group: name: my-cluster state: present strategy: partition partition_number: 4 ``` ### Code of Conduct - [X] I agree to follow the Ansible Code of Conduct
@hferreira23, thank you for this feature idea. Would you be willing to open a PR to implement this feature?
2022-02-04T19:33:34
ansible-collections/community.aws
936
ansible-collections__community.aws-936
[ "159" ]
44daa2ded8dc9f1dab0f7a4643176fe668a2a89c
diff --git a/plugins/modules/ec2_eip.py b/plugins/modules/ec2_eip.py --- a/plugins/modules/ec2_eip.py +++ b/plugins/modules/ec2_eip.py @@ -27,8 +27,8 @@ public_ip: description: - The IP address of a previously allocated EIP. - - When I(public_ip=present) and device is specified, the EIP is associated with the device. - - When I(public_ip=absent) and device is specified, the EIP is disassociated from the device. + - When I(state=present) and device is specified, the EIP is associated with the device. + - When I(state=absent) and device is specified, the EIP is disassociated from the device. aliases: [ ip ] type: str state: @@ -328,7 +328,7 @@ def find_address(ec2, module, public_ip, device_id, is_instance=True): except is_boto3_error_code('InvalidAddress.NotFound') as e: # If we're releasing and we can't find it, it's already gone... if module.params.get('state') == 'absent': - module.exit_json(changed=False) + module.exit_json(changed=False, disassociated=False, released=False) module.fail_json_aws(e, msg="Couldn't obtain list of existing Elastic IP addresses") addresses = addresses["Addresses"] @@ -385,6 +385,8 @@ def allocate_address(ec2, module, domain, reuse_existing_ip_allowed, check_mode, return allocate_address_from_pool(ec2, module, domain, check_mode, public_ipv4_pool), True try: + if check_mode: + return None, True result = ec2.allocate_address(Domain=domain, aws_retry=True), True except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: module.fail_json_aws(e, msg="Couldn't allocate Elastic IP address") @@ -493,8 +495,11 @@ def ensure_absent(ec2, module, address, device_id, check_mode, is_instance=True) def allocate_address_from_pool(ec2, module, domain, check_mode, public_ipv4_pool): - # type: (EC2Connection, str, bool, str) -> Address + # type: (EC2Connection, AnsibleAWSModule, str, bool, str) -> Address """ Overrides botocore's allocate_address function to support BYOIP """ + if check_mode: + return None + params = {} if domain is not None: @@ -503,9 +508,6 @@ def allocate_address_from_pool(ec2, module, domain, check_mode, public_ipv4_pool if public_ipv4_pool is not None: params['PublicIpv4Pool'] = public_ipv4_pool - if check_mode: - params['DryRun'] = 'true' - try: result = ec2.allocate_address(aws_retry=True, **params) except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: @@ -606,19 +608,33 @@ def main(): reuse_existing_ip_allowed, allow_reassociation, module.check_mode, is_instance=is_instance ) + if 'allocation_id' not in result: + # Don't check tags on check_mode here - no EIP to pass through + module.exit_json(**result) else: if address: - changed = False + result = { + 'changed': False, + 'public_ip': address['PublicIp'], + 'allocation_id': address['AllocationId'] + } else: address, changed = allocate_address( ec2, module, domain, reuse_existing_ip_allowed, module.check_mode, tag_dict, public_ipv4_pool ) - result = { - 'changed': changed, - 'public_ip': address['PublicIp'], - 'allocation_id': address['AllocationId'] - } + if address: + result = { + 'changed': changed, + 'public_ip': address['PublicIp'], + 'allocation_id': address['AllocationId'] + } + else: + # Don't check tags on check_mode here - no EIP to pass through + result = { + 'changed': changed + } + module.exit_json(**result) result['changed'] |= ensure_ec2_tags( ec2, module, result['allocation_id'], @@ -633,21 +649,21 @@ def main(): released = release_address(ec2, module, address, module.check_mode) result = { 'changed': True, - 'disassociated': disassociated, - 'released': released + 'disassociated': disassociated['changed'], + 'released': released['changed'] } else: result = { 'changed': disassociated['changed'], - 'disassociated': disassociated, - 'released': {'changed': False} + 'disassociated': disassociated['changed'], + 'released': False } else: released = release_address(ec2, module, address, module.check_mode) result = { 'changed': released['changed'], - 'disassociated': {'changed': False}, - 'released': released + 'disassociated': False, + 'released': released['changed'] } except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: diff --git a/plugins/modules/ec2_eip_info.py b/plugins/modules/ec2_eip_info.py --- a/plugins/modules/ec2_eip_info.py +++ b/plugins/modules/ec2_eip_info.py @@ -44,7 +44,7 @@ register: my_vm_eips - ansible.builtin.debug: - msg: "{{ my_vm_eips.addresses | json_query(\"[?private_ip_address=='10.0.0.5']\") }}" + msg: "{{ my_vm_eips.addresses | selectattr('private_ip_address', 'equalto', '10.0.0.5') }}" - name: List all EIP addresses for several VMs. community.aws.ec2_eip_info:
diff --git a/tests/integration/targets/ec2_eip/aliases b/tests/integration/targets/ec2_eip/aliases --- a/tests/integration/targets/ec2_eip/aliases +++ b/tests/integration/targets/ec2_eip/aliases @@ -1,4 +1,5 @@ # https://github.com/ansible-collections/community.aws/issues/159 -unstable +# unstable cloud/aws +ec2_eip_info \ No newline at end of file diff --git a/tests/integration/targets/ec2_eip/tasks/main.yml b/tests/integration/targets/ec2_eip/tasks/main.yml --- a/tests/integration/targets/ec2_eip/tasks/main.yml +++ b/tests/integration/targets/ec2_eip/tasks/main.yml @@ -1,4 +1,7 @@ - name: Integration testing for ec2_eip + collections: + - amazon.aws + module_defaults: group/aws: aws_access_key: '{{ aws_access_key }}' @@ -7,922 +10,1389 @@ region: '{{ aws_region }}' ec2_eip: in_vpc: true - collections: - - amazon.aws + block: - # ===================================================== - - name: Get the current caller identity facts - aws_caller_info: null - register: caller_info - - name: list available AZs - aws_az_info: null - register: region_azs - - name: create a VPC - ec2_vpc_net: - name: '{{ resource_prefix }}-vpc' - state: present - cidr_block: '{{ vpc_cidr }}' - tags: - AnsibleEIPTest: Pending - AnsibleEIPTestPrefix: '{{ resource_prefix }}' - register: vpc_result - - name: create subnet - ec2_vpc_subnet: - cidr: '{{ subnet_cidr }}' - az: '{{ subnet_az }}' - vpc_id: '{{ vpc_result.vpc.id }}' - state: present - register: vpc_subnet_create - - ec2_vpc_igw: - state: present - vpc_id: '{{ vpc_result.vpc.id }}' - register: vpc_igw - - name: "create a security group" - ec2_group: - state: present - name: '{{ resource_prefix }}-sg' - description: a security group for ansible tests - vpc_id: '{{ vpc_result.vpc.id }}' - rules: - - proto: tcp - from_port: 22 - to_port: 22 - cidr_ip: 0.0.0.0/0 - register: security_group - - name: Create instance for attaching - ec2_instance: - name: '{{ resource_prefix }}-instance' - image_id: '{{ ec2_ami_id }}' - security_group: '{{ security_group.group_id }}' - vpc_subnet_id: '{{ vpc_subnet_create.subnet.id }}' - wait: yes - state: running - register: create_ec2_instance_result - - # ===================================================== - - name: Look for signs of concurrent EIP tests. Pause if they are running or their prefix comes before ours. - vars: - running_query: vpcs[?tags.AnsibleEIPTest=='Running'] - pending_query: vpcs[?tags.AnsibleEIPTest=='Pending'].tags.AnsibleEIPTestPrefix - ec2_vpc_net_info: - filters: - tag:AnsibleEIPTest: - - Pending - - Running - register: vpc_info - retries: 120 - delay: 5 - until: - - ( vpc_info | community.general.json_query(running_query) | length == 0 ) - - ( vpc_info | community.general.json_query(pending_query) | sort | first == resource_prefix ) - - name: Make a crude lock - ec2_vpc_net: - name: '{{ resource_prefix }}-vpc' - state: present - cidr_block: '{{ vpc_cidr }}' - tags: - AnsibleEIPTest: Running - AnsibleEIPTestPrefix: '{{ resource_prefix }}' - - # ===================================================== - - name: Get current state of EIPs - ec2_eip_info: null - register: eip_info_start - - name: Require that there are no free IPs when we start, otherwise we can't test things properly - assert: - that: - - eip_info_start is defined - - '"addresses" in eip_info_start' - - ( eip_info_start.addresses | length ) == ( eip_info_start | community.general.json_query("addresses[].association_id") | length ) - - - name: Allocate a new eip (no conditions) - ec2_eip: - state: present - tags: - AnsibleEIPTestPrefix: '{{ resource_prefix }}' - register: eip - - - ec2_eip_info: null - register: eip_info - - assert: - that: - - eip is defined - - eip is changed - - eip.public_ip is defined and ( eip.public_ip | ansible.utils.ipaddr ) - - eip.allocation_id is defined and eip.allocation_id.startswith("eipalloc-") - - ( eip_info_start.addresses | length ) + 1 == ( eip_info.addresses | length ) - - - ec2_eip_info: - filters: - public-ip: '{{ eip.public_ip }}' - - assert: - that: - - '"addresses" in eip_info' - - eip_info.addresses | length == 1 - - eip_info.addresses[0].allocation_id == eip.allocation_id - - eip_info.addresses[0].domain == "vpc" - - eip_info.addresses[0].public_ip == eip.public_ip - - '"AnsibleEIPTestPrefix" in eip_info.addresses[0].tags' - - eip_info.addresses[0].tags['AnsibleEIPTestPrefix'] == resource_prefix - - - ec2_eip_info: - filters: - allocation-id: '{{ eip.allocation_id }}' - - assert: - that: - - '"addresses" in eip_info' - - eip_info.addresses | length == 1 - - eip_info.addresses[0].allocation_id == eip.allocation_id - - eip_info.addresses[0].domain == "vpc" - - eip_info.addresses[0].public_ip == eip.public_ip - - - name: Release eip - ec2_eip: - state: absent - public_ip: '{{ eip.public_ip }}' - register: eip_release - - ec2_eip_info: null - register: eip_info - - assert: - that: - - eip_release is defined - - eip_release is changed - - ( eip_info_start.addresses | length ) == ( eip_info.addresses | length ) - - - name: Allocate a new eip - attempt reusing unallocated ones (none available) - ec2_eip: - state: present - reuse_existing_ip_allowed: true - register: eip - - ec2_eip_info: null - register: eip_info - - assert: - that: - - eip is defined - - eip is changed - - eip.public_ip is defined and ( eip.public_ip | ansible.utils.ipaddr ) - - eip.allocation_id is defined and eip.allocation_id.startswith("eipalloc-") - - ( eip_info_start.addresses | length ) + 1 == ( eip_info.addresses | length ) - - - name: Re-Allocate a new eip - attempt reusing unallocated ones (one available) - ec2_eip: - state: present - reuse_existing_ip_allowed: true - register: reallocate_eip - - ec2_eip_info: null - register: eip_info - - assert: - that: - - reallocate_eip is defined - - reallocate_eip is not changed - - reallocate_eip.public_ip is defined and ( reallocate_eip.public_ip | ansible.utils.ipaddr ) - - reallocate_eip.allocation_id is defined and reallocate_eip.allocation_id.startswith("eipalloc-") - - ( eip_info_start.addresses | length ) + 1 == ( eip_info.addresses | length ) - - - name: Release eip - ec2_eip: - state: absent - public_ip: '{{ eip.public_ip }}' - register: eip_release - - ec2_eip_info: null - register: eip_info - - assert: - that: - - ( eip_info_start.addresses | length ) == ( eip_info.addresses | length ) - - eip_release is defined - - eip_release is changed - - - name: Allocate a new eip - ec2_eip: - state: present - register: eip - - ec2_eip_info: null - register: eip_info - - assert: - that: - - eip is defined - - eip is changed - - eip.public_ip is defined and ( eip.public_ip | ansible.utils.ipaddr ) - - eip.allocation_id is defined and eip.allocation_id.startswith("eipalloc-") - - ( eip_info_start.addresses | length ) + 1 == ( eip_info.addresses | length ) - - - name: Match an existing eip (changed == false) - ec2_eip: - state: present - public_ip: '{{ eip.public_ip }}' - register: reallocate_eip - - ec2_eip_info: null - register: eip_info - - assert: - that: - - reallocate_eip is defined - - reallocate_eip is not changed - - reallocate_eip.public_ip is defined and ( reallocate_eip.public_ip | ansible.utils.ipaddr ) - - reallocate_eip.allocation_id is defined and reallocate_eip.allocation_id.startswith("eipalloc-") - - ( eip_info_start.addresses | length ) + 1 == ( eip_info.addresses | length ) - - - name: Release eip - ec2_eip: - state: absent - public_ip: '{{ eip.public_ip }}' - register: eip_release - - ec2_eip_info: null - register: eip_info - - assert: - that: - - eip_release is defined - - eip_release is changed - - ( eip_info_start.addresses | length ) == ( eip_info.addresses | length ) - - - name: Allocate a new eip (no tags) - ec2_eip: - state: present - register: eip - - ec2_eip_info: null - register: eip_info - - assert: - that: - - eip is defined - - eip is changed - - eip.public_ip is defined and ( eip.public_ip | ansible.utils.ipaddr ) - - eip.allocation_id is defined and eip.allocation_id.startswith("eipalloc-") - - ( eip_info_start.addresses | length ) + 1 == ( eip_info.addresses | length ) - - - name: attempt reusing an existing eip with a tag (No match available) - ec2_eip: - state: present - reuse_existing_ip_allowed: true - tag_name: Team - register: no_tagged_eip - - ec2_eip_info: null - register: eip_info - - assert: - that: - - no_tagged_eip is defined - - no_tagged_eip is changed - - no_tagged_eip.public_ip is defined and ( no_tagged_eip.public_ip | ansible.utils.ipaddr ) - - no_tagged_eip.allocation_id is defined and no_tagged_eip.allocation_id.startswith("eipalloc-") - - ( eip_info_start.addresses | length ) + 2 == ( eip_info.addresses | length ) - - - name: tag eip so we can try matching it - ec2_eip: - state: present - public_ip: '{{ eip.public_ip }}' - tags: - Team: Frontend + - name: Get the current caller identity facts + aws_caller_info: + register: caller_info - - name: attempt reusing an existing eip with a tag (Match available) - ec2_eip: - state: present - reuse_existing_ip_allowed: true - tag_name: Team - register: reallocate_eip - - ec2_eip_info: null - register: eip_info - - assert: - that: - - reallocate_eip is defined - - reallocate_eip is not changed - - reallocate_eip.public_ip is defined and ( reallocate_eip.public_ip | ansible.utils.ipaddr ) - - reallocate_eip.allocation_id is defined and reallocate_eip.allocation_id.startswith("eipalloc-") - - ( eip_info_start.addresses | length ) + 2 == ( eip_info.addresses | length ) - - - name: attempt reusing an existing eip with a tag and it's value (no match available) - ec2_eip: - state: present - reuse_existing_ip_allowed: true - tag_name: Team - tag_value: Backend - register: backend_eip - - ec2_eip_info: null - register: eip_info - - assert: - that: - - backend_eip is defined - - backend_eip is changed - - backend_eip.public_ip is defined and ( backend_eip.public_ip | ansible.utils.ipaddr ) - - backend_eip.allocation_id is defined and backend_eip.allocation_id.startswith("eipalloc-") - - ( eip_info_start.addresses | length ) + 3 == ( eip_info.addresses | length ) - - - name: tag eip so we can try matching it - ec2_eip: - state: present - public_ip: '{{ eip.public_ip }}' - tags: - Team: Backend + - name: List available AZs + aws_az_info: + register: region_azs - - name: attempt reusing an existing eip with a tag and it's value (match available) - ec2_eip: - state: present - reuse_existing_ip_allowed: true - tag_name: Team - tag_value: Backend - register: reallocate_eip - - ec2_eip_info: null - register: eip_info - - assert: - that: - - reallocate_eip is defined - - reallocate_eip is not changed - - reallocate_eip.public_ip is defined and reallocate_eip.public_ip != "" - - reallocate_eip.allocation_id is defined and reallocate_eip.allocation_id != "" - - ( eip_info_start.addresses | length ) + 3 == ( eip_info.addresses | length ) - - - name: Release backend_eip - ec2_eip: - state: absent - public_ip: '{{ backend_eip.public_ip }}' - register: eip_release - - ec2_eip_info: null - register: eip_info - - assert: - that: - - eip_release is defined - - eip_release is changed - - ( eip_info_start.addresses | length ) + 2 == ( eip_info.addresses | length ) - - - name: Release no_tagged_eip - ec2_eip: - state: absent - public_ip: '{{ no_tagged_eip.public_ip }}' - register: eip_release - - ec2_eip_info: null - register: eip_info - - assert: - that: - - eip_release is defined - - eip_release is changed - - ( eip_info_start.addresses | length ) + 1 == ( eip_info.addresses | length ) - - - name: Release eip - ec2_eip: - state: absent - public_ip: '{{ eip.public_ip }}' - register: eip_release - - ec2_eip_info: null - register: eip_info - - assert: - that: - - eip_release is defined - - eip_release is changed - - ( eip_info_start.addresses | length ) == ( eip_info.addresses | length ) - - - name: allocate a new eip from a pool - ec2_eip: - state: present - public_ipv4_pool: amazon - register: eip - - ec2_eip_info: null - register: eip_info - - assert: - that: - - eip is defined - - eip is changed - - eip.public_ip is defined and ( eip.public_ip | ansible.utils.ipaddr ) - - eip.allocation_id is defined and eip.allocation_id.startswith("eipalloc-") - - ( eip_info_start.addresses | length ) + 1 == ( eip_info.addresses | length ) - - - name: create ENI A - ec2_eni: - subnet_id: '{{ vpc_subnet_create.subnet.id }}' - register: eni_create_a - - - name: create ENI B - ec2_eni: - subnet_id: '{{ vpc_subnet_create.subnet.id }}' - register: eni_create_b - - - name: Attach EIP to ENI A - ec2_eip: - public_ip: '{{ eip.public_ip }}' - device_id: '{{ eni_create_a.interface.id }}' - register: associate_eip - - ec2_eip_info: - filters: - public-ip: '{{ eip.public_ip }}' - register: eip_info - - assert: - that: - - associate_eip is defined - - associate_eip is changed - - eip_info.addresses | length == 1 - - associate_eip.public_ip is defined and eip.public_ip == associate_eip.public_ip - - associate_eip.allocation_id is defined and eip.allocation_id == associate_eip.allocation_id - - eip_info.addresses[0].allocation_id == eip.allocation_id - - eip_info.addresses[0].domain == "vpc" - - eip_info.addresses[0].public_ip == eip.public_ip - - eip_info.addresses[0].association_id is defined and eip_info.addresses[0].association_id.startswith("eipassoc-") - - eip_info.addresses[0].network_interface_id == eni_create_a.interface.id - - eip_info.addresses[0].private_ip_address is defined and ( eip_info.addresses[0].private_ip_address | ansible.utils.ipaddr ) - - eip_info.addresses[0].network_interface_owner_id == caller_info.account - - - name: Re-Attach EIP to ENI A (no change) - ec2_eip: - public_ip: '{{ eip.public_ip }}' - device_id: '{{ eni_create_a.interface.id }}' - register: associate_eip - - ec2_eip_info: - filters: - public-ip: '{{ eip.public_ip }}' - register: eip_info - - assert: - that: - - associate_eip is defined - - associate_eip is not changed - - associate_eip.public_ip is defined and eip.public_ip == associate_eip.public_ip - - associate_eip.allocation_id is defined and eip.allocation_id == associate_eip.allocation_id - - eip_info.addresses | length == 1 - - eip_info.addresses[0].allocation_id == eip.allocation_id - - eip_info.addresses[0].domain == "vpc" - - eip_info.addresses[0].public_ip == eip.public_ip - - eip_info.addresses[0].association_id is defined and eip_info.addresses[0].association_id.startswith("eipassoc-") - - eip_info.addresses[0].network_interface_id == eni_create_a.interface.id - - eip_info.addresses[0].private_ip_address is defined and ( eip_info.addresses[0].private_ip_address | ansible.utils.ipaddr ) - - - name: Attach EIP to ENI B (should fail, already associated) - ec2_eip: - public_ip: '{{ eip.public_ip }}' - device_id: '{{ eni_create_b.interface.id }}' - register: associate_eip - ignore_errors: true - - ec2_eip_info: - filters: - public-ip: '{{ eip.public_ip }}' - register: eip_info - - assert: - that: - - associate_eip is defined - - associate_eip is failed - - eip_info.addresses | length == 1 - - eip_info.addresses[0].allocation_id == eip.allocation_id - - eip_info.addresses[0].domain == "vpc" - - eip_info.addresses[0].public_ip == eip.public_ip - - eip_info.addresses[0].association_id is defined and eip_info.addresses[0].association_id.startswith("eipassoc-") - - eip_info.addresses[0].network_interface_id == eni_create_a.interface.id - - eip_info.addresses[0].private_ip_address is defined and ( eip_info.addresses[0].private_ip_address | ansible.utils.ipaddr ) - - - name: Attach EIP to ENI B - ec2_eip: - public_ip: '{{ eip.public_ip }}' - device_id: '{{ eni_create_b.interface.id }}' - allow_reassociation: true - register: associate_eip - - ec2_eip_info: - filters: - public-ip: '{{ eip.public_ip }}' - register: eip_info - - assert: - that: - - associate_eip is defined - - associate_eip is changed - - associate_eip.public_ip is defined and eip.public_ip == associate_eip.public_ip - - associate_eip.allocation_id is defined and eip.allocation_id == associate_eip.allocation_id - - eip_info.addresses | length == 1 - - eip_info.addresses[0].allocation_id == eip.allocation_id - - eip_info.addresses[0].domain == "vpc" - - eip_info.addresses[0].public_ip == eip.public_ip - - eip_info.addresses[0].association_id is defined and eip_info.addresses[0].association_id.startswith("eipassoc-") - - eip_info.addresses[0].network_interface_id == eni_create_b.interface.id - - eip_info.addresses[0].private_ip_address is defined and ( eip_info.addresses[0].private_ip_address | ansible.utils.ipaddr ) - - - name: Detach EIP from ENI B, without enabling release on disassociation - ec2_eip: - state: absent - public_ip: '{{ eip.public_ip }}' - device_id: '{{ eni_create_b.interface.id }}' - register: disassociate_eip - - ec2_eip_info: - filters: - public-ip: '{{ eip.public_ip }}' - register: eip_info - - assert: - that: - - associate_eip is defined - - associate_eip is changed - - eip_info.addresses | length == 1 - - - name: Re-detach EIP from ENI B, without enabling release on disassociation - ec2_eip: - state: absent - public_ip: '{{ eip.public_ip }}' - device_id: '{{ eni_create_b.interface.id }}' - register: associate_eip - - ec2_eip_info: - filters: - public-ip: '{{ eip.public_ip }}' - register: eip_info - - assert: - that: - - associate_eip is defined - - associate_eip is not changed - - eip_info.addresses | length == 1 - - - name: Attach EIP to ENI A - ec2_eip: - public_ip: '{{ eip.public_ip }}' - device_id: '{{ eni_create_a.interface.id }}' - register: associate_eip - - ec2_eip_info: - filters: - public-ip: '{{ eip.public_ip }}' - register: eip_info - - assert: - that: - - associate_eip is defined - - associate_eip is changed - - associate_eip.public_ip is defined and eip.public_ip == associate_eip.public_ip - - associate_eip.allocation_id is defined and eip.allocation_id == associate_eip.allocation_id - - eip_info.addresses[0].network_interface_id == eni_create_a.interface.id - - - name: Detach EIP from ENI A, enabling release on disassociation - ec2_eip: - state: absent - public_ip: '{{ eip.public_ip }}' - device_id: '{{ eni_create_a.interface.id }}' - release_on_disassociation: true - register: disassociate_eip - - ec2_eip_info: - filters: - public-ip: '{{ eip.public_ip }}' - register: eip_info - - assert: - that: - - associate_eip is defined - - associate_eip is changed - - eip_info.addresses | length == 0 - - - name: Re-detach EIP from ENI A, enabling release on disassociation - ec2_eip: - state: absent - public_ip: '{{ eip.public_ip }}' - device_id: '{{ eni_create_a.interface.id }}' - release_on_disassociation: true - register: associate_eip - - ec2_eip_info: - filters: - public-ip: '{{ eip.public_ip }}' - register: eip_info - - assert: - that: - - associate_eip is defined - - associate_eip is not changed - - eip_info.addresses | length == 0 - - - ec2_eip_info: null - register: eip_info - - assert: - that: - - ( eip_info_start.addresses | length ) == ( eip_info.addresses | length ) - - - name: Cleanup ENI B - ec2_eni: - state: absent - eni_id: '{{ eni_create_b.interface.id }}' - - - name: Cleanup ENI A - ec2_eni: - state: absent - eni_id: '{{ eni_create_a.interface.id }}' - - - name: Attach eip to an EC2 instance - ec2_eip: - device_id: '{{ create_ec2_instance_result.instance_ids[0] }}' - state: present - release_on_disassociation: yes - register: instance_eip - - ec2_eip_info: - filters: - public-ip: '{{ instance_eip.public_ip }}' - register: eip_info - - assert: - that: - - instance_eip is success - - eip_info.addresses[0].allocation_id is defined - - eip_info.addresses[0].instance_id == '{{ create_ec2_instance_result.instance_ids[0] }}' - - - name: Attach eip to an EC2 instance with private Ip specified - ec2_eip: - device_id: '{{ create_ec2_instance_result.instance_ids[0] }}' - private_ip_address: '{{ create_ec2_instance_result.instances[0].private_ip_address }}' - state: present - release_on_disassociation: yes - register: instance_eip - - ec2_eip_info: - filters: - public-ip: '{{ instance_eip.public_ip }}' - register: eip_info - - assert: - that: - - instance_eip is success - - eip_info.addresses[0].allocation_id is defined - - eip_info.addresses[0].instance_id == '{{ create_ec2_instance_result.instance_ids[0] }}' - - # ===================================================== - - - name: Cleanup instance - ec2_instance: - instance_ids: '{{ create_ec2_instance_result.instance_ids }}' - state: absent - - - name: Cleanup instance eip - ec2_eip: - state: absent - public_ip: '{{ instance_eip.public_ip }}' - register: eip_cleanup - retries: 5 - delay: 5 - until: eip_cleanup is successful - - - name: Cleanup IGW - ec2_vpc_igw: - state: absent - vpc_id: '{{ vpc_result.vpc.id }}' - register: vpc_igw - - - name: Cleanup security group - ec2_group: - state: absent - name: '{{ resource_prefix }}-sg' - - - name: Cleanup Subnet - ec2_vpc_subnet: - state: absent - cidr: '{{ subnet_cidr }}' - vpc_id: '{{ vpc_result.vpc.id }}' - - - name: Release eip - ec2_eip: - state: absent - public_ip: '{{ eip.public_ip }}' - register: eip_release - ignore_errors: true + - name: Create a VPC + ec2_vpc_net: + name: '{{ resource_prefix }}-vpc' + state: present + cidr_block: '{{ vpc_cidr }}' + tags: + AnsibleEIPTest: Pending + AnsibleEIPTestPrefix: '{{ resource_prefix }}' + register: vpc_result + + - name: Look for signs of concurrent EIP tests. Pause if they are running or their prefix comes before ours. + vars: + running_query: vpcs[?tags.AnsibleEIPTest=='Running'] + pending_query: vpcs[?tags.AnsibleEIPTest=='Pending'].tags.AnsibleEIPTestPrefix + ec2_vpc_net_info: + filters: + tag:AnsibleEIPTest: + - Pending + - Running + register: vpc_info + retries: 10 + delay: 5 + until: + - ( vpc_info.vpcs | map(attribute='tags') | selectattr('AnsibleEIPTest', 'equalto', 'Running') | length == 0 ) + - ( vpc_info.vpcs | map(attribute='tags') | selectattr('AnsibleEIPTest', 'equalto', 'Pending') | map(attribute='AnsibleEIPTestPrefix') | sort | first == resource_prefix ) + + - name: Create subnet + ec2_vpc_subnet: + cidr: '{{ subnet_cidr }}' + az: '{{ subnet_az }}' + vpc_id: '{{ vpc_result.vpc.id }}' + state: present + register: vpc_subnet_create + + - name: Create internet gateway + amazon.aws.ec2_vpc_igw: + state: present + vpc_id: '{{ vpc_result.vpc.id }}' + register: vpc_igw + + - name: Create security group + ec2_group: + state: present + name: '{{ resource_prefix }}-sg' + description: a security group for ansible tests + vpc_id: '{{ vpc_result.vpc.id }}' + rules: + - proto: tcp + from_port: 22 + to_port: 22 + cidr_ip: 0.0.0.0/0 + register: security_group + + - name: Create instance for attaching + ec2_instance: + name: '{{ resource_prefix }}-instance' + image_id: '{{ ec2_ami_id }}' + security_group: '{{ security_group.group_id }}' + vpc_subnet_id: '{{ vpc_subnet_create.subnet.id }}' + wait: yes + state: running + register: create_ec2_instance_result + + - name: Create ENI A + ec2_eni: + subnet_id: '{{ vpc_subnet_create.subnet.id }}' + register: eni_create_a + + - name: Create ENI B + ec2_eni: + subnet_id: '{{ vpc_subnet_create.subnet.id }}' + register: eni_create_b + + - name: Make a crude lock + ec2_vpc_net: + name: '{{ resource_prefix }}-vpc' + state: present + cidr_block: '{{ vpc_cidr }}' + tags: + AnsibleEIPTest: Running + AnsibleEIPTestPrefix: '{{ resource_prefix }}' + + - name: Get current state of EIPs + ec2_eip_info: + register: eip_info_start + + - name: Require that there are no free IPs when we start, otherwise we can't test things properly + assert: + that: + - '"addresses" in eip_info_start' + - ( eip_info_start.addresses | length ) == ( eip_info_start.addresses | select('match', 'association_id') | length ) + + # ------------------------------------------------------------------------------------------ + + - name: Allocate a new EIP with no conditions - check_mode + ec2_eip: + state: present + tags: + AnsibleEIPTestPrefix: '{{ resource_prefix }}' + register: eip + check_mode: yes + + - assert: + that: + - eip is changed + + - name: Allocate a new EIP with no conditions + ec2_eip: + state: present + tags: + AnsibleEIPTestPrefix: '{{ resource_prefix }}' + register: eip + + - ec2_eip_info: + register: eip_info + check_mode: yes + + - assert: + that: + - eip is changed + - eip.public_ip is defined and ( eip.public_ip | ansible.utils.ipaddr ) + - eip.allocation_id is defined and eip.allocation_id.startswith("eipalloc-") + - ( eip_info_start.addresses | length ) + 1 == ( eip_info.addresses | length ) + + - name: Get EIP info via public ip + ec2_eip_info: + filters: + public-ip: '{{ eip.public_ip }}' + register: eip_info + + - assert: + that: + - '"addresses" in eip_info' + - eip_info.addresses | length == 1 + - eip_info.addresses[0].allocation_id == eip.allocation_id + - eip_info.addresses[0].domain == "vpc" + - eip_info.addresses[0].public_ip == eip.public_ip + - '"AnsibleEIPTestPrefix" in eip_info.addresses[0].tags' + - eip_info.addresses[0].tags['AnsibleEIPTestPrefix'] == resource_prefix + + - name: Get EIP info via allocation id + ec2_eip_info: + filters: + allocation-id: '{{ eip.allocation_id }}' + register: eip_info + + - assert: + that: + - '"addresses" in eip_info' + - eip_info.addresses | length == 1 + - eip_info.addresses[0].allocation_id == eip.allocation_id + - eip_info.addresses[0].domain == "vpc" + - eip_info.addresses[0].public_ip == eip.public_ip + - '"AnsibleEIPTestPrefix" in eip_info.addresses[0].tags' + - eip_info.addresses[0].tags['AnsibleEIPTestPrefix'] == resource_prefix + + - name: Allocate a new ip (idempotence) - check_mode + ec2_eip: + state: present + public_ip: '{{ eip.public_ip }}' + register: eip + check_mode: yes + + - assert: + that: + - eip is not changed + + - name: Allocate a new ip (idempotence) + ec2_eip: + state: present + public_ip: '{{ eip.public_ip }}' + register: eip + + - ec2_eip_info: + register: eip_info + + - assert: + that: + - eip is not changed + - eip.public_ip is defined and ( eip.public_ip | ansible.utils.ipaddr ) + - eip.allocation_id is defined and eip.allocation_id.startswith("eipalloc-") + - ( eip_info_start.addresses | length ) + 1 == ( eip_info.addresses | length ) + + # ------------------------------------------------------------------------------------------ + + - name: Release EIP - check_mode + ec2_eip: + state: absent + public_ip: '{{ eip.public_ip }}' + register: eip_release + check_mode: yes + + - assert: + that: + - eip_release.changed + + - name: Release eip + ec2_eip: + state: absent + public_ip: '{{ eip.public_ip }}' + register: eip_release + + - ec2_eip_info: + register: eip_info + + - assert: + that: + - eip_release.changed + - not eip_release.disassociated + - eip_release.released + - ( eip_info_start.addresses | length ) == ( eip_info.addresses | length ) + + - name: Release EIP (idempotence) - check_mode + ec2_eip: + state: absent + public_ip: '{{ eip.public_ip }}' + register: eip_release + check_mode: yes + + - assert: + that: + - eip_release is not changed + + - name: Release EIP (idempotence) + ec2_eip: + state: absent + public_ip: '{{ eip.public_ip }}' + register: eip_release + + - ec2_eip_info: + register: eip_info + + - assert: + that: + - not eip_release.changed + - not eip_release.disassociated + - not eip_release.released + - ( eip_info_start.addresses | length ) == ( eip_info.addresses | length ) + + # ------------------------------------------------------------------------------------------ + + - name: Allocate a new EIP - attempt reusing unallocated ones (none available) - check_mode + ec2_eip: + state: present + reuse_existing_ip_allowed: true + register: eip + check_mode: yes + + - assert: + that: + - eip is changed + + - name: Allocate a new EIP - attempt reusing unallocated ones (none available) + ec2_eip: + state: present + reuse_existing_ip_allowed: true + register: eip + + - ec2_eip_info: + register: eip_info + + - assert: + that: + - eip is changed + - eip.public_ip is defined and ( eip.public_ip | ansible.utils.ipaddr ) + - eip.allocation_id is defined and eip.allocation_id.startswith("eipalloc-") + - ( eip_info_start.addresses | length ) + 1 == ( eip_info.addresses | length ) + + - name: Re-Allocate a new EIP - attempt reusing unallocated ones (one available) - check_mode + ec2_eip: + state: present + reuse_existing_ip_allowed: true + register: reallocate_eip + check_mode: yes + + - assert: + that: + - reallocate_eip is not changed + + - name: Re-Allocate a new EIP - attempt reusing unallocated ones (one available) + ec2_eip: + state: present + reuse_existing_ip_allowed: true + register: reallocate_eip + + - ec2_eip_info: + register: eip_info + + - assert: + that: + - reallocate_eip is not changed + - reallocate_eip.public_ip is defined and ( reallocate_eip.public_ip | ansible.utils.ipaddr ) + - reallocate_eip.allocation_id is defined and reallocate_eip.allocation_id.startswith("eipalloc-") + - ( eip_info_start.addresses | length ) + 1 == ( eip_info.addresses | length ) + + # ------------------------------------------------------------------------------------------ + + - name: attempt reusing an existing EIP with a tag (No match available) - check_mode + ec2_eip: + state: present + reuse_existing_ip_allowed: true + tag_name: Team + register: no_tagged_eip + check_mode: yes + + - assert: + that: + - no_tagged_eip is changed + + - name: attempt reusing an existing EIP with a tag (No match available) + ec2_eip: + state: present + reuse_existing_ip_allowed: true + tag_name: Team + register: no_tagged_eip + + - ec2_eip_info: + register: eip_info + + - assert: + that: + - no_tagged_eip is changed + - no_tagged_eip.public_ip is defined and ( no_tagged_eip.public_ip | ansible.utils.ipaddr ) + - no_tagged_eip.allocation_id is defined and no_tagged_eip.allocation_id.startswith("eipalloc-") + - ( eip_info_start.addresses | length ) + 2 == ( eip_info.addresses | length ) + + # ------------------------------------------------------------------------------------------ + + - name: Tag EIP so we can try matching it + ec2_eip: + state: present + public_ip: '{{ eip.public_ip }}' + tags: + Team: Frontend + + - name: Attempt reusing an existing EIP with a tag (Match available) - check_mode + ec2_eip: + state: present + reuse_existing_ip_allowed: true + tag_name: Team + register: reallocate_eip + check_mode: yes + + - assert: + that: + - reallocate_eip is not changed + + - name: Attempt reusing an existing EIP with a tag (Match available) + ec2_eip: + state: present + reuse_existing_ip_allowed: true + tag_name: Team + register: reallocate_eip + + - ec2_eip_info: + register: eip_info + + - assert: + that: + - reallocate_eip is not changed + - reallocate_eip.public_ip is defined and ( reallocate_eip.public_ip | ansible.utils.ipaddr ) + - reallocate_eip.allocation_id is defined and reallocate_eip.allocation_id.startswith("eipalloc-") + - ( eip_info_start.addresses | length ) + 2 == ( eip_info.addresses | length ) + + - name: Attempt reusing an existing EIP with a tag and it's value (no match available) - check_mode + ec2_eip: + state: present + reuse_existing_ip_allowed: true + tag_name: Team + tag_value: Backend + register: backend_eip + check_mode: yes + + - assert: + that: + - backend_eip is changed + + - name: Attempt reusing an existing EIP with a tag and it's value (no match available) + ec2_eip: + state: present + reuse_existing_ip_allowed: true + tag_name: Team + tag_value: Backend + register: backend_eip + + - ec2_eip_info: + register: eip_info + + - assert: + that: + - backend_eip is changed + - backend_eip.public_ip is defined and ( backend_eip.public_ip | ansible.utils.ipaddr ) + - backend_eip.allocation_id is defined and backend_eip.allocation_id.startswith("eipalloc-") + - ( eip_info_start.addresses | length ) + 3 == ( eip_info.addresses | length ) + + # ------------------------------------------------------------------------------------------ + + - name: Tag EIP so we can try matching it + ec2_eip: + state: present + public_ip: '{{ eip.public_ip }}' + tags: + Team: Backend + + - name: Attempt reusing an existing EIP with a tag and it's value (match available) - check_mode + ec2_eip: + state: present + reuse_existing_ip_allowed: true + tag_name: Team + tag_value: Backend + register: reallocate_eip + check_mode: yes + + - assert: + that: + - reallocate_eip is not changed + + - name: Attempt reusing an existing EIP with a tag and it's value (match available) + ec2_eip: + state: present + reuse_existing_ip_allowed: true + tag_name: Team + tag_value: Backend + register: reallocate_eip + + - ec2_eip_info: + register: eip_info + + - assert: + that: + - reallocate_eip is not changed + - reallocate_eip.public_ip is defined and reallocate_eip.public_ip != "" + - reallocate_eip.allocation_id is defined and reallocate_eip.allocation_id != "" + - ( eip_info_start.addresses | length ) + 3 == ( eip_info.addresses | length ) + + - name: Release backend_eip + ec2_eip: + state: absent + public_ip: '{{ backend_eip.public_ip }}' + + - name: Release no_tagged_eip + ec2_eip: + state: absent + public_ip: '{{ no_tagged_eip.public_ip }}' + + - name: Release eip + ec2_eip: + state: absent + public_ip: '{{ eip.public_ip }}' + + - ec2_eip_info: + register: eip_info + + - assert: + that: + - ( eip_info_start.addresses | length ) == ( eip_info.addresses | length ) + + # ------------------------------------------------------------------------------------------ + + - name: Allocate a new EIP from a pool - check_mode + ec2_eip: + state: present + public_ipv4_pool: amazon + register: eip + check_mode: yes + + - assert: + that: + - eip is changed + + - name: Allocate a new EIP from a pool + ec2_eip: + state: present + public_ipv4_pool: amazon + register: eip + + - ec2_eip_info: + register: eip_info + + - assert: + that: + - eip is changed + - eip.public_ip is defined and ( eip.public_ip | ansible.utils.ipaddr ) + - eip.allocation_id is defined and eip.allocation_id.startswith("eipalloc-") + - ( eip_info_start.addresses | length ) + 1 == ( eip_info.addresses | length ) + + # ------------------------------------------------------------------------------------------ + + - name: Attach EIP to ENI A - check_mode + ec2_eip: + public_ip: '{{ eip.public_ip }}' + device_id: '{{ eni_create_a.interface.id }}' + register: associate_eip + check_mode: yes + + - assert: + that: + - associate_eip is changed + + - name: Attach EIP to ENI A + ec2_eip: + public_ip: '{{ eip.public_ip }}' + device_id: '{{ eni_create_a.interface.id }}' + register: associate_eip + + - ec2_eip_info: + filters: + public-ip: '{{ eip.public_ip }}' + register: eip_info + + - assert: + that: + - associate_eip is changed + - eip_info.addresses | length == 1 + - associate_eip.public_ip is defined and eip.public_ip == associate_eip.public_ip + - associate_eip.allocation_id is defined and eip.allocation_id == associate_eip.allocation_id + - eip_info.addresses[0].allocation_id == eip.allocation_id + - eip_info.addresses[0].domain == "vpc" + - eip_info.addresses[0].public_ip == eip.public_ip + - eip_info.addresses[0].association_id is defined and eip_info.addresses[0].association_id.startswith("eipassoc-") + - eip_info.addresses[0].network_interface_id == eni_create_a.interface.id + - eip_info.addresses[0].private_ip_address is defined and ( eip_info.addresses[0].private_ip_address | ansible.utils.ipaddr ) + - eip_info.addresses[0].network_interface_owner_id == caller_info.account + + - name: Attach EIP to ENI A (idempotence) - check_mode + ec2_eip: + public_ip: '{{ eip.public_ip }}' + device_id: '{{ eni_create_a.interface.id }}' + register: associate_eip + check_mode: yes + + - assert: + that: + - associate_eip is not changed + + - name: Attach EIP to ENI A (idempotence) + ec2_eip: + public_ip: '{{ eip.public_ip }}' + device_id: '{{ eni_create_a.interface.id }}' + register: associate_eip + + - ec2_eip_info: + filters: + public-ip: '{{ eip.public_ip }}' + register: eip_info + + - assert: + that: + - associate_eip is not changed + - associate_eip.public_ip is defined and eip.public_ip == associate_eip.public_ip + - associate_eip.allocation_id is defined and eip.allocation_id == associate_eip.allocation_id + - eip_info.addresses | length == 1 + - eip_info.addresses[0].allocation_id == eip.allocation_id + - eip_info.addresses[0].domain == "vpc" + - eip_info.addresses[0].public_ip == eip.public_ip + - eip_info.addresses[0].association_id is defined and eip_info.addresses[0].association_id.startswith("eipassoc-") + - eip_info.addresses[0].network_interface_id == eni_create_a.interface.id + - eip_info.addresses[0].private_ip_address is defined and ( eip_info.addresses[0].private_ip_address | ansible.utils.ipaddr ) + + # ------------------------------------------------------------------------------------------ + + - name: Attach EIP to ENI B (should fail, already associated) + ec2_eip: + public_ip: '{{ eip.public_ip }}' + device_id: '{{ eni_create_b.interface.id }}' + register: associate_eip + ignore_errors: true + + - ec2_eip_info: + filters: + public-ip: '{{ eip.public_ip }}' + register: eip_info + + - assert: + that: + - associate_eip is failed + - eip_info.addresses | length == 1 + - eip_info.addresses[0].allocation_id == eip.allocation_id + - eip_info.addresses[0].domain == "vpc" + - eip_info.addresses[0].public_ip == eip.public_ip + - eip_info.addresses[0].association_id is defined and eip_info.addresses[0].association_id.startswith("eipassoc-") + - eip_info.addresses[0].network_interface_id == eni_create_a.interface.id + - eip_info.addresses[0].private_ip_address is defined and ( eip_info.addresses[0].private_ip_address | ansible.utils.ipaddr ) + + - name: Attach EIP to ENI B - check_mode + ec2_eip: + public_ip: '{{ eip.public_ip }}' + device_id: '{{ eni_create_b.interface.id }}' + allow_reassociation: true + register: associate_eip + check_mode: yes + + - assert: + that: + - associate_eip is changed + + - name: Attach EIP to ENI B + ec2_eip: + public_ip: '{{ eip.public_ip }}' + device_id: '{{ eni_create_b.interface.id }}' + allow_reassociation: true + register: associate_eip + + - ec2_eip_info: + filters: + public-ip: '{{ eip.public_ip }}' + register: eip_info + + - assert: + that: + - associate_eip is changed + - associate_eip.public_ip is defined and eip.public_ip == associate_eip.public_ip + - associate_eip.allocation_id is defined and eip.allocation_id == associate_eip.allocation_id + - eip_info.addresses | length == 1 + - eip_info.addresses[0].allocation_id == eip.allocation_id + - eip_info.addresses[0].domain == "vpc" + - eip_info.addresses[0].public_ip == eip.public_ip + - eip_info.addresses[0].association_id is defined and eip_info.addresses[0].association_id.startswith("eipassoc-") + - eip_info.addresses[0].network_interface_id == eni_create_b.interface.id + - eip_info.addresses[0].private_ip_address is defined and ( eip_info.addresses[0].private_ip_address | ansible.utils.ipaddr ) + + - name: Attach EIP to ENI B (idempotence) - check_mode + ec2_eip: + public_ip: '{{ eip.public_ip }}' + device_id: '{{ eni_create_b.interface.id }}' + allow_reassociation: true + register: associate_eip + check_mode: yes + + - assert: + that: + - associate_eip is not changed + + - name: Attach EIP to ENI B (idempotence) + ec2_eip: + public_ip: '{{ eip.public_ip }}' + device_id: '{{ eni_create_b.interface.id }}' + allow_reassociation: true + register: associate_eip + + - ec2_eip_info: + filters: + public-ip: '{{ eip.public_ip }}' + register: eip_info + + - assert: + that: + - associate_eip is not changed + - associate_eip.public_ip is defined and eip.public_ip == associate_eip.public_ip + - associate_eip.allocation_id is defined and eip.allocation_id == associate_eip.allocation_id + - eip_info.addresses | length == 1 + - eip_info.addresses[0].allocation_id == eip.allocation_id + - eip_info.addresses[0].domain == "vpc" + - eip_info.addresses[0].public_ip == eip.public_ip + - eip_info.addresses[0].association_id is defined and eip_info.addresses[0].association_id.startswith("eipassoc-") + - eip_info.addresses[0].network_interface_id == eni_create_b.interface.id + - eip_info.addresses[0].private_ip_address is defined and ( eip_info.addresses[0].private_ip_address | ansible.utils.ipaddr ) + + # ------------------------------------------------------------------------------------------ + + - name: Detach EIP from ENI B, without enabling release on disassociation - check_mode + ec2_eip: + state: absent + public_ip: '{{ eip.public_ip }}' + device_id: '{{ eni_create_b.interface.id }}' + register: disassociate_eip + check_mode: yes + + - assert: + that: + - disassociate_eip is changed + + - name: Detach EIP from ENI B, without enabling release on disassociation + ec2_eip: + state: absent + public_ip: '{{ eip.public_ip }}' + device_id: '{{ eni_create_b.interface.id }}' + register: disassociate_eip + + - ec2_eip_info: + filters: + public-ip: '{{ eip.public_ip }}' + register: eip_info + + - assert: + that: + - disassociate_eip.changed + - disassociate_eip.disassociated + - not disassociate_eip.released + - eip_info.addresses | length == 1 + + - name: Detach EIP from ENI B, without enabling release on disassociation (idempotence) - check_mode + ec2_eip: + state: absent + public_ip: '{{ eip.public_ip }}' + device_id: '{{ eni_create_b.interface.id }}' + register: disassociate_eip + check_mode: yes + + - assert: + that: + - disassociate_eip is not changed + + - name: Detach EIP from ENI B, without enabling release on disassociation (idempotence) + ec2_eip: + state: absent + public_ip: '{{ eip.public_ip }}' + device_id: '{{ eni_create_b.interface.id }}' + register: disassociate_eip + + - ec2_eip_info: + filters: + public-ip: '{{ eip.public_ip }}' + register: eip_info + + - assert: + that: + - not disassociate_eip.changed + - not disassociate_eip.disassociated + - not disassociate_eip.released + - eip_info.addresses | length == 1 + + # ------------------------------------------------------------------------------------------ + + - name: Attach EIP to ENI A + ec2_eip: + public_ip: '{{ eip.public_ip }}' + device_id: '{{ eni_create_a.interface.id }}' + register: associate_eip + + - name: Detach EIP from ENI A, enabling release on disassociation - check_mode + ec2_eip: + state: absent + public_ip: '{{ eip.public_ip }}' + device_id: '{{ eni_create_a.interface.id }}' + release_on_disassociation: true + register: disassociate_eip + check_mode: yes + + - assert: + that: + - disassociate_eip is changed + + - name: Detach EIP from ENI A, enabling release on disassociation + ec2_eip: + state: absent + public_ip: '{{ eip.public_ip }}' + device_id: '{{ eni_create_a.interface.id }}' + release_on_disassociation: true + register: disassociate_eip + + - ec2_eip_info: + filters: + public-ip: '{{ eip.public_ip }}' + register: eip_info + + - assert: + that: + - disassociate_eip.changed + - disassociate_eip.disassociated + - disassociate_eip.released + - eip_info.addresses | length == 0 + + - name: Detach EIP from ENI A, enabling release on disassociation (idempotence) - check_mode + ec2_eip: + state: absent + public_ip: '{{ eip.public_ip }}' + device_id: '{{ eni_create_a.interface.id }}' + release_on_disassociation: true + register: disassociate_eip + check_mode: yes + + - assert: + that: + - disassociate_eip is not changed + + - name: Detach EIP from ENI A, enabling release on disassociation (idempotence) + ec2_eip: + state: absent + public_ip: '{{ eip.public_ip }}' + device_id: '{{ eni_create_a.interface.id }}' + release_on_disassociation: true + register: disassociate_eip + + - ec2_eip_info: + filters: + public-ip: '{{ eip.public_ip }}' + register: eip_info + + - assert: + that: + - not disassociate_eip.changed + - not disassociate_eip.disassociated + - not disassociate_eip.released + - eip_info.addresses | length == 0 + + # ------------------------------------------------------------------------------------------ + + - name: Attach EIP to an EC2 instance - check_mode + ec2_eip: + device_id: '{{ create_ec2_instance_result.instance_ids[0] }}' + state: present + release_on_disassociation: yes + register: instance_eip + check_mode: yes + + - assert: + that: + - instance_eip is changed + + - name: Attach EIP to an EC2 instance + ec2_eip: + device_id: '{{ create_ec2_instance_result.instance_ids[0] }}' + state: present + release_on_disassociation: yes + register: instance_eip + + - ec2_eip_info: + filters: + public-ip: '{{ instance_eip.public_ip }}' + register: eip_info + + - assert: + that: + - instance_eip is changed + - eip_info.addresses[0].allocation_id is defined + - eip_info.addresses[0].instance_id == '{{ create_ec2_instance_result.instance_ids[0] }}' + + - name: Attach EIP to an EC2 instance (idempotence) - check_mode + ec2_eip: + device_id: '{{ create_ec2_instance_result.instance_ids[0] }}' + state: present + release_on_disassociation: yes + register: instance_eip + check_mode: yes + + - assert: + that: + - instance_eip is not changed + + - name: Attach EIP to an EC2 instance (idempotence) + ec2_eip: + device_id: '{{ create_ec2_instance_result.instance_ids[0] }}' + state: present + release_on_disassociation: yes + register: instance_eip + + - ec2_eip_info: + filters: + public-ip: '{{ instance_eip.public_ip }}' + register: eip_info + + - assert: + that: + - instance_eip is not changed + - eip_info.addresses[0].allocation_id is defined + - eip_info.addresses[0].instance_id == '{{ create_ec2_instance_result.instance_ids[0] }}' + + # ------------------------------------------------------------------------------------------ + + - name: Detach EIP from EC2 instance, without enabling release on disassociation - check_mode + ec2_eip: + state: absent + device_id: '{{ create_ec2_instance_result.instance_ids[0] }}' + register: detach_eip + check_mode: yes + + - assert: + that: + - detach_eip is changed + + - name: Detach EIP from EC2 instance, without enabling release on disassociation + ec2_eip: + state: absent + device_id: '{{ create_ec2_instance_result.instance_ids[0] }}' + register: detach_eip + + - ec2_eip_info: + filters: + public-ip: '{{ instance_eip.public_ip }}' + register: eip_info + + - assert: + that: + - detach_eip.changed + - detach_eip.disassociated + - not detach_eip.released + - eip_info.addresses | length == 1 + + - name: Detach EIP from EC2 instance, without enabling release on disassociation (idempotence) - check_mode + ec2_eip: + state: absent + device_id: '{{ create_ec2_instance_result.instance_ids[0] }}' + register: detach_eip + check_mode: yes + + - assert: + that: + - detach_eip is not changed + + - name: Detach EIP from EC2 instance, without enabling release on disassociation (idempotence) + ec2_eip: + state: absent + device_id: '{{ create_ec2_instance_result.instance_ids[0] }}' + register: detach_eip + + - ec2_eip_info: + filters: + public-ip: '{{ instance_eip.public_ip }}' + register: eip_info + + - assert: + that: + - not detach_eip.changed + - not detach_eip.disassociated + - not detach_eip.released + - eip_info.addresses | length == 1 + + - name: Release EIP + ec2_eip: + state: absent + public_ip: '{{ instance_eip.public_ip }}' + + # ------------------------------------------------------------------------------------------ + + - name: Attach EIP to an EC2 instance with private Ip specified - check_mode + ec2_eip: + device_id: '{{ create_ec2_instance_result.instance_ids[0] }}' + private_ip_address: '{{ create_ec2_instance_result.instances[0].private_ip_address }}' + state: present + release_on_disassociation: yes + register: instance_eip + check_mode: yes + + - assert: + that: + - instance_eip is changed + + - name: Attach EIP to an EC2 instance with private Ip specified + ec2_eip: + device_id: '{{ create_ec2_instance_result.instance_ids[0] }}' + private_ip_address: '{{ create_ec2_instance_result.instances[0].private_ip_address }}' + state: present + release_on_disassociation: yes + register: instance_eip + + - ec2_eip_info: + filters: + public-ip: '{{ instance_eip.public_ip }}' + register: eip_info + + - assert: + that: + - instance_eip is changed + - eip_info.addresses[0].allocation_id is defined + - eip_info.addresses[0].instance_id == '{{ create_ec2_instance_result.instance_ids[0] }}' + + - name: Attach EIP to an EC2 instance with private Ip specified (idempotence) - check_mode + ec2_eip: + device_id: '{{ create_ec2_instance_result.instance_ids[0] }}' + private_ip_address: '{{ create_ec2_instance_result.instances[0].private_ip_address }}' + state: present + release_on_disassociation: yes + register: instance_eip + check_mode: yes + + - assert: + that: + - instance_eip is not changed + + - name: Attach EIP to an EC2 instance with private Ip specified (idempotence) + ec2_eip: + device_id: '{{ create_ec2_instance_result.instance_ids[0] }}' + private_ip_address: '{{ create_ec2_instance_result.instances[0].private_ip_address }}' + state: present + release_on_disassociation: yes + register: instance_eip + + - ec2_eip_info: + filters: + public-ip: '{{ instance_eip.public_ip }}' + register: eip_info + + - assert: + that: + - instance_eip is not changed + - eip_info.addresses[0].allocation_id is defined + - eip_info.addresses[0].instance_id == '{{ create_ec2_instance_result.instance_ids[0] }}' + + # ------------------------------------------------------------------------------------------ + + - name: Detach EIP from EC2 instance, enabling release on disassociation - check_mode + ec2_eip: + state: absent + device_id: '{{ create_ec2_instance_result.instance_ids[0] }}' + release_on_disassociation: yes + register: disassociate_eip + check_mode: yes + + - assert: + that: + - disassociate_eip is changed + + - name: Detach EIP from EC2 instance, enabling release on disassociation + ec2_eip: + state: absent + device_id: '{{ create_ec2_instance_result.instance_ids[0] }}' + release_on_disassociation: yes + register: disassociate_eip + + - ec2_eip_info: + filters: + public-ip: '{{ instance_eip.public_ip }}' + register: eip_info + + - assert: + that: + - disassociate_eip.changed + - disassociate_eip.disassociated + - disassociate_eip.released + - eip_info.addresses | length == 0 + + - name: Detach EIP from EC2 instance, enabling release on disassociation (idempotence) - check_mode + ec2_eip: + state: absent + device_id: '{{ create_ec2_instance_result.instance_ids[0] }}' + release_on_disassociation: yes + register: disassociate_eip + check_mode: yes + + - assert: + that: + - disassociate_eip is not changed + + - name: Detach EIP from EC2 instance, enabling release on disassociation (idempotence) + ec2_eip: + state: absent + device_id: '{{ create_ec2_instance_result.instance_ids[0] }}' + release_on_disassociation: yes + register: disassociate_eip + + - ec2_eip_info: + filters: + public-ip: '{{ instance_eip.public_ip }}' + register: eip_info + + - assert: + that: + - not disassociate_eip.changed + - not disassociate_eip.disassociated + - not disassociate_eip.released + - eip_info.addresses | length == 0 + + # ------------------------------------------------------------------------------------------ + + - name: Allocate a new eip + ec2_eip: + state: present + register: eip + + - name: Tag EIP - check_mode + ec2_eip: + state: present + public_ip: '{{ eip.public_ip }}' + tags: + AnsibleEIPTestPrefix: '{{ resource_prefix }}' + another_tag: 'another Value {{ resource_prefix }}' + register: tag_eip + check_mode: yes + + - assert: + that: + - tag_eip is changed + + - name: Tag EIP + ec2_eip: + state: present + public_ip: '{{ eip.public_ip }}' + tags: + AnsibleEIPTestPrefix: '{{ resource_prefix }}' + another_tag: 'another Value {{ resource_prefix }}' + register: tag_eip + + - ec2_eip_info: + filters: + public-ip: '{{ eip.public_ip }}' + register: eip_info + + - assert: + that: + - tag_eip is changed + - '"AnsibleEIPTestPrefix" in eip_info.addresses[0].tags' + - '"another_tag" in eip_info.addresses[0].tags' + - eip_info.addresses[0].tags['AnsibleEIPTestPrefix'] == resource_prefix + - eip_info.addresses[0].tags['another_tag'] == 'another Value ' + resource_prefix + - ( eip_info_start.addresses | length ) + 1 == ( eip_info.addresses | length ) + + - name: Tag EIP (idempotence) - check_mode + ec2_eip: + state: present + public_ip: '{{ eip.public_ip }}' + tags: + AnsibleEIPTestPrefix: '{{ resource_prefix }}' + another_tag: 'another Value {{ resource_prefix }}' + register: tag_eip + check_mode: yes + + - assert: + that: + - tag_eip is not changed + + - name: Tag EIP (idempotence) + ec2_eip: + state: present + public_ip: '{{ eip.public_ip }}' + tags: + AnsibleEIPTestPrefix: '{{ resource_prefix }}' + another_tag: 'another Value {{ resource_prefix }}' + register: tag_eip + + - ec2_eip_info: + filters: + public-ip: '{{ eip.public_ip }}' + register: eip_info + + - assert: + that: + - tag_eip is not changed + - '"AnsibleEIPTestPrefix" in eip_info.addresses[0].tags' + - '"another_tag" in eip_info.addresses[0].tags' + - eip_info.addresses[0].tags['AnsibleEIPTestPrefix'] == resource_prefix + - eip_info.addresses[0].tags['another_tag'] == 'another Value ' + resource_prefix + - ( eip_info_start.addresses | length ) + 1 == ( eip_info.addresses | length ) + + # ------------------------------------------------------------------------------------------ + + - name: Add another Tag - check_mode + ec2_eip: + state: present + public_ip: '{{ eip.public_ip }}' + tags: + "third tag": 'Third tag - {{ resource_prefix }}' + purge_tags: False + register: tag_eip + check_mode: yes + + - assert: + that: + - tag_eip is changed + + - name: Add another Tag + ec2_eip: + state: present + public_ip: '{{ eip.public_ip }}' + tags: + "third tag": 'Third tag - {{ resource_prefix }}' + purge_tags: False + register: tag_eip + + - ec2_eip_info: + filters: + public-ip: '{{ eip.public_ip }}' + register: eip_info + + - assert: + that: + - tag_eip is changed + - '"AnsibleEIPTestPrefix" in eip_info.addresses[0].tags' + - '"another_tag" in eip_info.addresses[0].tags' + - '"third tag" in eip_info.addresses[0].tags' + - eip_info.addresses[0].tags['AnsibleEIPTestPrefix'] == resource_prefix + - eip_info.addresses[0].tags['another_tag'] == 'another Value ' + resource_prefix + - eip_info.addresses[0].tags['third tag'] == 'Third tag - ' + resource_prefix + - ( eip_info_start.addresses | length ) + 1 == ( eip_info.addresses | length ) + + - name: Add another Tag (idempotence) - check_mode + ec2_eip: + state: present + public_ip: '{{ eip.public_ip }}' + tags: + "third tag": 'Third tag - {{ resource_prefix }}' + purge_tags: False + register: tag_eip + check_mode: yes + + - assert: + that: + - tag_eip is not changed + + - name: Add another Tag (idempotence) + ec2_eip: + state: present + public_ip: '{{ eip.public_ip }}' + tags: + "third tag": 'Third tag - {{ resource_prefix }}' + purge_tags: False + register: tag_eip + + - ec2_eip_info: + filters: + public-ip: '{{ eip.public_ip }}' + register: eip_info + + - assert: + that: + - tag_eip is not changed + - '"AnsibleEIPTestPrefix" in eip_info.addresses[0].tags' + - '"another_tag" in eip_info.addresses[0].tags' + - '"third tag" in eip_info.addresses[0].tags' + - eip_info.addresses[0].tags['AnsibleEIPTestPrefix'] == resource_prefix + - eip_info.addresses[0].tags['another_tag'] == 'another Value ' + resource_prefix + - eip_info.addresses[0].tags['third tag'] == 'Third tag - ' + resource_prefix + + # ------------------------------------------------------------------------------------------ + + - name: Purge tags - check_mode + ec2_eip: + state: present + public_ip: '{{ eip.public_ip }}' + tags: + "third tag": 'Third tag - {{ resource_prefix }}' + purge_tags: True + register: tag_eip + check_mode: yes + + - assert: + that: + - tag_eip is changed + + - name: Purge tags + ec2_eip: + state: present + public_ip: '{{ eip.public_ip }}' + tags: + "third tag": 'Third tag - {{ resource_prefix }}' + purge_tags: True + register: tag_eip + + - ec2_eip_info: + filters: + public-ip: '{{ eip.public_ip }}' + register: eip_info + + - assert: + that: + - tag_eip is changed + - '"AnsibleEIPTestPrefix" not in eip_info.addresses[0].tags' + - '"another_tag" not in eip_info.addresses[0].tags' + - '"third tag" in eip_info.addresses[0].tags' + - eip_info.addresses[0].tags['third tag'] == 'Third tag - ' + resource_prefix + + - name: Purge tags (idempotence) - check_mode + ec2_eip: + state: present + public_ip: '{{ eip.public_ip }}' + tags: + "third tag": 'Third tag - {{ resource_prefix }}' + purge_tags: True + register: tag_eip + check_mode: yes + + - assert: + that: + - tag_eip is not changed + + - name: Purge tags (idempotence) + ec2_eip: + state: present + public_ip: '{{ eip.public_ip }}' + tags: + "third tag": 'Third tag - {{ resource_prefix }}' + purge_tags: True + register: tag_eip + + - ec2_eip_info: + filters: + public-ip: '{{ eip.public_ip }}' + register: eip_info + + - assert: + that: + - tag_eip is not changed + - '"AnsibleEIPTestPrefix" not in eip_info.addresses[0].tags' + - '"another_tag" not in eip_info.addresses[0].tags' + - '"third tag" in eip_info.addresses[0].tags' + - eip_info.addresses[0].tags['third tag'] == 'Third tag - ' + resource_prefix + + # ----- Cleanup ------------------------------------------------------------------------------ - - name: allocate a new eip - ec2_eip: - state: present - register: eip - - ec2_eip_info: null - register: eip_info - - assert: - that: - - eip is defined - - eip is changed - - eip.public_ip is defined and ( eip.public_ip | ansible.utils.ipaddr ) - - eip.allocation_id is defined and eip.allocation_id.startswith("eipalloc-") - - ( eip_info_start.addresses | length ) + 1 == ( eip_info.addresses | length ) - - ############################################################################################# - - - name: Tag EIP - ec2_eip: - state: present - public_ip: '{{ eip.public_ip }}' - tags: - AnsibleEIPTestPrefix: '{{ resource_prefix }}' - another_tag: 'another Value {{ resource_prefix }}' - register: tag_eip - - ec2_eip_info: null - register: eip_info - - assert: - that: - - tag_eip is defined - - tag_eip is changed - - '"AnsibleEIPTestPrefix" in eip_info.addresses[0].tags' - - '"another_tag" in eip_info.addresses[0].tags' - - eip_info.addresses[0].tags['AnsibleEIPTestPrefix'] == resource_prefix - - eip_info.addresses[0].tags['another_tag'] == 'another Value ' + resource_prefix - - - name: Tag EIP - ec2_eip: - state: present - public_ip: '{{ eip.public_ip }}' - tags: - AnsibleEIPTestPrefix: '{{ resource_prefix }}' - another_tag: 'another Value {{ resource_prefix }}' - register: tag_eip - - ec2_eip_info: null - register: eip_info - - assert: - that: - - tag_eip is defined - - tag_eip is not changed - - '"AnsibleEIPTestPrefix" in eip_info.addresses[0].tags' - - '"another_tag" in eip_info.addresses[0].tags' - - eip_info.addresses[0].tags['AnsibleEIPTestPrefix'] == resource_prefix - - eip_info.addresses[0].tags['another_tag'] == 'another Value ' + resource_prefix - - - name: Add another Tag - ec2_eip: - state: present - public_ip: '{{ eip.public_ip }}' - tags: - "third tag": 'Third tag - {{ resource_prefix }}' - purge_tags: False - register: tag_eip - - ec2_eip_info: null - register: eip_info - - assert: - that: - - tag_eip is defined - - tag_eip is changed - - '"AnsibleEIPTestPrefix" in eip_info.addresses[0].tags' - - '"another_tag" in eip_info.addresses[0].tags' - - '"third tag" in eip_info.addresses[0].tags' - - eip_info.addresses[0].tags['AnsibleEIPTestPrefix'] == resource_prefix - - eip_info.addresses[0].tags['another_tag'] == 'another Value ' + resource_prefix - - eip_info.addresses[0].tags['third tag'] == 'Third tag - ' + resource_prefix - - - name: Add another Tag - ec2_eip: - state: present - public_ip: '{{ eip.public_ip }}' - tags: - "third tag": 'Third tag - {{ resource_prefix }}' - purge_tags: False - register: tag_eip - - ec2_eip_info: null - register: eip_info - - assert: - that: - - tag_eip is defined - - tag_eip is not changed - - '"AnsibleEIPTestPrefix" in eip_info.addresses[0].tags' - - '"another_tag" in eip_info.addresses[0].tags' - - '"third tag" in eip_info.addresses[0].tags' - - eip_info.addresses[0].tags['AnsibleEIPTestPrefix'] == resource_prefix - - eip_info.addresses[0].tags['another_tag'] == 'another Value ' + resource_prefix - - eip_info.addresses[0].tags['third tag'] == 'Third tag - ' + resource_prefix - - - name: Purge most tags - ec2_eip: - state: present - public_ip: '{{ eip.public_ip }}' - tags: - "third tag": 'Third tag - {{ resource_prefix }}' - purge_tags: True - register: tag_eip - - ec2_eip_info: null - register: eip_info - - assert: - that: - - tag_eip is defined - - tag_eip is changed - - '"AnsibleEIPTestPrefix" not in eip_info.addresses[0].tags' - - '"another_tag" not in eip_info.addresses[0].tags' - - '"third tag" in eip_info.addresses[0].tags' - - eip_info.addresses[0].tags['third tag'] == 'Third tag - ' + resource_prefix - - - name: Purge most tags - ec2_eip: - state: present - public_ip: '{{ eip.public_ip }}' - tags: - "third tag": 'Third tag - {{ resource_prefix }}' - purge_tags: True - register: tag_eip - - ec2_eip_info: null - register: eip_info - - assert: - that: - - tag_eip is defined - - tag_eip is not changed - - '"AnsibleEIPTestPrefix" not in eip_info.addresses[0].tags' - - '"another_tag" not in eip_info.addresses[0].tags' - - '"third tag" in eip_info.addresses[0].tags' - - eip_info.addresses[0].tags['third tag'] == 'Third tag - ' + resource_prefix - - ############################################################################################# - - - name: Release eip - ec2_eip: - state: absent - public_ip: '{{ eip.public_ip }}' - register: eip_release - - ec2_eip_info: null - register: eip_info - - assert: - that: - - eip_release is defined - - eip_release is changed - - ( eip_info_start.addresses | length ) == ( eip_info.addresses | length ) - - name: Rerelease eip (no change) - ec2_eip: - state: absent - public_ip: '{{ eip.public_ip }}' - register: eip_release - - ec2_eip_info: null - register: eip_info - - assert: - that: - - eip_release is defined - - eip_release is not changed - - ( eip_info_start.addresses | length ) == ( eip_info.addresses | length ) - - name: Cleanup VPC - ec2_vpc_net: - state: absent - name: '{{ resource_prefix }}-vpc' - cidr_block: '{{ vpc_cidr }}' - - - name: Create an EIP outside a VPC - ec2_eip: - state: present - in_vpc: '{{ omit }}' - register: unbound_eip - - assert: - that: - - unbound_eip is successful - - unbound_eip is changed - - name: Release EIP - ec2_eip: - state: absent - public_ip: '{{ unbound_eip.public_ip }}' - register: release_unbound_eip - - assert: - that: - - release_unbound_eip is successful - - release_unbound_eip is changed - # ===================================================== always: - - name: Cleanup instance (by id) - ec2_instance: - instance_ids: '{{ create_ec2_instance_result.instance_ids }}' - state: absent - wait: true - ignore_errors: true - - name: Cleanup instance (by name) - ec2_instance: - name: '{{ resource_prefix }}-instance' - state: absent - wait: true - ignore_errors: true - - name: Cleanup ENI A - ec2_eni: - state: absent - eni_id: '{{ eni_create_a.interface.id }}' - ignore_errors: true - - name: Cleanup ENI B - ec2_eni: - state: absent - eni_id: '{{ eni_create_b.interface.id }}' - ignore_errors: true - - name: Cleanup instance eip - ec2_eip: - state: absent - public_ip: '{{ instance_eip.public_ip }}' - retries: 5 - delay: 5 - until: eip_cleanup is successful - ignore_errors: true - - name: Cleanup IGW - ec2_vpc_igw: - state: absent - vpc_id: '{{ vpc_result.vpc.id }}' - register: vpc_igw - ignore_errors: true - - name: Cleanup security group - ec2_group: - state: absent - name: '{{ resource_prefix }}-sg' - ignore_errors: true - - name: Cleanup Subnet - ec2_vpc_subnet: - state: absent - cidr: '{{ subnet_cidr }}' - vpc_id: '{{ vpc_result.vpc.id }}' - ignore_errors: true - - name: Cleanup eip - ec2_eip: - state: absent - public_ip: '{{ eip.public_ip }}' - when: eip is changed - ignore_errors: true - - name: Cleanup reallocate_eip - ec2_eip: - state: absent - public_ip: '{{ reallocate_eip.public_ip }}' - when: reallocate_eip is changed - ignore_errors: true - - name: Cleanup backend_eip - ec2_eip: - state: absent - public_ip: '{{ backend_eip.public_ip }}' - when: backend_eip is changed - ignore_errors: true - - name: Cleanup no_tagged_eip - ec2_eip: - state: absent - public_ip: '{{ no_tagged_eip.public_ip }}' - when: no_tagged_eip is changed - ignore_errors: true - - name: Cleanup unbound_eip - ec2_eip: - state: absent - public_ip: '{{ unbound_eip.public_ip }}' - when: unbound_eip is changed - ignore_errors: true - - name: Cleanup VPC - ec2_vpc_net: - state: absent - name: '{{ resource_prefix }}-vpc' - cidr_block: '{{ vpc_cidr }}' - ignore_errors: true + + - name: Cleanup instance (by id) + ec2_instance: + instance_ids: '{{ create_ec2_instance_result.instance_ids }}' + state: absent + wait: true + ignore_errors: true + + - name: Cleanup instance (by name) + ec2_instance: + name: '{{ resource_prefix }}-instance' + state: absent + wait: true + ignore_errors: true + + - name: Cleanup ENI A + ec2_eni: + state: absent + eni_id: '{{ eni_create_a.interface.id }}' + ignore_errors: true + + - name: Cleanup ENI B + ec2_eni: + state: absent + eni_id: '{{ eni_create_b.interface.id }}' + ignore_errors: true + + - name: Cleanup instance eip + ec2_eip: + state: absent + public_ip: '{{ instance_eip.public_ip }}' + retries: 5 + delay: 5 + until: eip_cleanup is successful + ignore_errors: true + + - name: Cleanup IGW + ec2_vpc_igw: + state: absent + vpc_id: '{{ vpc_result.vpc.id }}' + register: vpc_igw + ignore_errors: true + + - name: Cleanup security group + ec2_group: + state: absent + name: '{{ resource_prefix }}-sg' + ignore_errors: true + + - name: Cleanup Subnet + ec2_vpc_subnet: + state: absent + cidr: '{{ subnet_cidr }}' + vpc_id: '{{ vpc_result.vpc.id }}' + ignore_errors: true + + - name: Cleanup eip + ec2_eip: + state: absent + public_ip: '{{ eip.public_ip }}' + ignore_errors: true + + - name: Cleanup reallocate_eip + ec2_eip: + state: absent + public_ip: '{{ reallocate_eip.public_ip }}' + ignore_errors: true + + - name: Cleanup backend_eip + ec2_eip: + state: absent + public_ip: '{{ backend_eip.public_ip }}' + ignore_errors: true + + - name: Cleanup no_tagged_eip + ec2_eip: + state: absent + public_ip: '{{ no_tagged_eip.public_ip }}' + ignore_errors: true + + - name: Cleanup VPC + ec2_vpc_net: + state: absent + name: '{{ resource_prefix }}-vpc' + cidr_block: '{{ vpc_cidr }}' + ignore_errors: true
Unstable integration tests ec2_eip Test is susceptible to race conditions when running concurrently in the same Region https://app.shippable.com/github/ansible-collections/community.aws/runs/438/27/tests https://app.shippable.com/github/ansible-collections/community.aws/runs/438/23/tests https://app.shippable.com/github/ansible-collections/community.aws/runs/438/24/tests https://app.shippable.com/github/ansible-collections/community.aws/runs/439/27/tests https://app.shippable.com/github/ansible-collections/community.aws/runs/440/23/tests https://app.shippable.com/github/ansible-collections/community.aws/runs/440/26/tests
Files identified in the description: None If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> @tremble: Greetings! Thanks for taking the time to open this issue. In order for the community to handle your issue effectively, we need a bit more information. Here are the items we could not find in your description: - issue type - ansible version - component name Please set the description of this issue with this template: https://raw.githubusercontent.com/ansible/ansible/devel/.github/ISSUE_TEMPLATE/bug_report.md [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: issue_missing_data --->
2022-02-11T03:05:24
ansible-collections/community.aws
945
ansible-collections__community.aws-945
[ "877" ]
d0596e3734170873b0166aae01630eb51f880b4f
diff --git a/plugins/modules/cloudfront_distribution.py b/plugins/modules/cloudfront_distribution.py --- a/plugins/modules/cloudfront_distribution.py +++ b/plugins/modules/cloudfront_distribution.py @@ -200,6 +200,10 @@ - The ID of the origin that you want CloudFront to route requests to by default. type: str + response_headers_policy_id: + description: + - The ID of the header policy that CloudFront adds to responses that it sends to viewers. + type: str forwarded_values: description: - A dict that specifies how CloudFront handles query strings and cookies. @@ -317,6 +321,10 @@ - The ID of the origin that you want CloudFront to route requests to by default. type: str + response_headers_policy_id: + description: + - The ID of the header policy that CloudFront adds to responses that it sends to viewers. + type: str forwarded_values: description: - A dict that specifies how CloudFront handles query strings and cookies.
Add support for setting response header policy id in cache behavior ### Summary Add support for setting cache and origin request policy ids in the cache behaviors block when creating a distribution in cloudfront_distribution. ### Issue Type Feature Idea ### Component Name cloudfront_distribution ### Additional Information Currently we are unable to set response header policy ids in the cache behaviors section so that they are added to a cloudfront distribution. Example playbook code: cache_behaviors: - path_pattern: "*/" target_origin_id: "" field_level_encryption_id: "" response_headers_policy_id: "{{ response_headers_policy_id }}" Example python code: cache_behavior['response_headers_policy_id'] = cache_behavior.get('response_headers_policy_id', config.get('response_headers_policy_id')) cache_behavior['response_headers_policy_id'] = cache_behavior.get('response_headers_policy_id', config.get('origin_request_policy_id')) ### Code of Conduct - [X] I agree to follow the Ansible Code of Conduct
This works already :) ```yml - field_level_encryption_id: "" path_pattern: mbmbmbmbmbmbmbmbmbmbmbmbmb-test-wow viewer_protocol_policy: "redirect-to-https" max_ttl: 31536000 min_ttl: 0 default_ttl: 86400 smooth_streaming: no compress: yes target_origin_id: Custom-cdn.test.blaaaaaaaaa.de response_headers_policy_id: 60669652-455b-4ae9-85a4-c4c02393f86c trusted_signers: enabled: no allowed_methods: items: - GET - HEAD cached_methods: - GET - HEAD forwarded_values: query_string: true cookies: forward: all headers: - "Host" ``` The code supports maybe every element in the `cache_behaviour` item. It's just a lack of documentation. cc @jillr @s-hertel @tremble @wilvk [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify --->
2022-02-22T10:00:58
ansible-collections/community.aws
946
ansible-collections__community.aws-946
[ "159" ]
9ccdbdfb12ee159ce55046c57cc53d028e47684a
diff --git a/plugins/modules/ec2_eip.py b/plugins/modules/ec2_eip.py --- a/plugins/modules/ec2_eip.py +++ b/plugins/modules/ec2_eip.py @@ -27,8 +27,8 @@ public_ip: description: - The IP address of a previously allocated EIP. - - When I(public_ip=present) and device is specified, the EIP is associated with the device. - - When I(public_ip=absent) and device is specified, the EIP is disassociated from the device. + - When I(state=present) and device is specified, the EIP is associated with the device. + - When I(state=absent) and device is specified, the EIP is disassociated from the device. aliases: [ ip ] type: str state: @@ -328,7 +328,7 @@ def find_address(ec2, module, public_ip, device_id, is_instance=True): except is_boto3_error_code('InvalidAddress.NotFound') as e: # If we're releasing and we can't find it, it's already gone... if module.params.get('state') == 'absent': - module.exit_json(changed=False) + module.exit_json(changed=False, disassociated=False, released=False) module.fail_json_aws(e, msg="Couldn't obtain list of existing Elastic IP addresses") addresses = addresses["Addresses"] @@ -385,6 +385,8 @@ def allocate_address(ec2, module, domain, reuse_existing_ip_allowed, check_mode, return allocate_address_from_pool(ec2, module, domain, check_mode, public_ipv4_pool), True try: + if check_mode: + return None, True result = ec2.allocate_address(Domain=domain, aws_retry=True), True except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: module.fail_json_aws(e, msg="Couldn't allocate Elastic IP address") @@ -493,8 +495,11 @@ def ensure_absent(ec2, module, address, device_id, check_mode, is_instance=True) def allocate_address_from_pool(ec2, module, domain, check_mode, public_ipv4_pool): - # type: (EC2Connection, str, bool, str) -> Address - """ Overrides boto's allocate_address function to support BYOIP """ + # type: (EC2Connection, AnsibleAWSModule, str, bool, str) -> Address + """ Overrides botocore's allocate_address function to support BYOIP """ + if check_mode: + return None + params = {} if domain is not None: @@ -503,9 +508,6 @@ def allocate_address_from_pool(ec2, module, domain, check_mode, public_ipv4_pool if public_ipv4_pool is not None: params['PublicIpv4Pool'] = public_ipv4_pool - if check_mode: - params['DryRun'] = 'true' - try: result = ec2.allocate_address(aws_retry=True, **params) except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: @@ -606,19 +608,33 @@ def main(): reuse_existing_ip_allowed, allow_reassociation, module.check_mode, is_instance=is_instance ) + if 'allocation_id' not in result: + # Don't check tags on check_mode here - no EIP to pass through + module.exit_json(**result) else: if address: - changed = False + result = { + 'changed': False, + 'public_ip': address['PublicIp'], + 'allocation_id': address['AllocationId'] + } else: address, changed = allocate_address( ec2, module, domain, reuse_existing_ip_allowed, module.check_mode, tag_dict, public_ipv4_pool ) - result = { - 'changed': changed, - 'public_ip': address['PublicIp'], - 'allocation_id': address['AllocationId'] - } + if address: + result = { + 'changed': changed, + 'public_ip': address['PublicIp'], + 'allocation_id': address['AllocationId'] + } + else: + # Don't check tags on check_mode here - no EIP to pass through + result = { + 'changed': changed + } + module.exit_json(**result) result['changed'] |= ensure_ec2_tags( ec2, module, result['allocation_id'], @@ -633,21 +649,21 @@ def main(): released = release_address(ec2, module, address, module.check_mode) result = { 'changed': True, - 'disassociated': disassociated, - 'released': released + 'disassociated': disassociated['changed'], + 'released': released['changed'] } else: result = { 'changed': disassociated['changed'], - 'disassociated': disassociated, - 'released': {'changed': False} + 'disassociated': disassociated['changed'], + 'released': False } else: released = release_address(ec2, module, address, module.check_mode) result = { 'changed': released['changed'], - 'disassociated': {'changed': False}, - 'released': released + 'disassociated': False, + 'released': released['changed'] } except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: diff --git a/plugins/modules/ec2_eip_info.py b/plugins/modules/ec2_eip_info.py --- a/plugins/modules/ec2_eip_info.py +++ b/plugins/modules/ec2_eip_info.py @@ -44,7 +44,7 @@ register: my_vm_eips - ansible.builtin.debug: - msg: "{{ my_vm_eips.addresses | json_query(\"[?private_ip_address=='10.0.0.5']\") }}" + msg: "{{ my_vm_eips.addresses | selectattr('private_ip_address', 'equalto', '10.0.0.5') }}" - name: List all EIP addresses for several VMs. community.aws.ec2_eip_info:
diff --git a/tests/integration/targets/ec2_eip/aliases b/tests/integration/targets/ec2_eip/aliases --- a/tests/integration/targets/ec2_eip/aliases +++ b/tests/integration/targets/ec2_eip/aliases @@ -1,4 +1,5 @@ # https://github.com/ansible-collections/community.aws/issues/159 -unstable +# unstable cloud/aws +ec2_eip_info \ No newline at end of file diff --git a/tests/integration/targets/ec2_eip/tasks/main.yml b/tests/integration/targets/ec2_eip/tasks/main.yml --- a/tests/integration/targets/ec2_eip/tasks/main.yml +++ b/tests/integration/targets/ec2_eip/tasks/main.yml @@ -1,4 +1,7 @@ - name: Integration testing for ec2_eip + collections: + - amazon.aws + module_defaults: group/aws: aws_access_key: '{{ aws_access_key }}' @@ -7,922 +10,1389 @@ region: '{{ aws_region }}' ec2_eip: in_vpc: true - collections: - - amazon.aws + block: - # ===================================================== - - name: Get the current caller identity facts - aws_caller_info: null - register: caller_info - - name: list available AZs - aws_az_info: null - register: region_azs - - name: create a VPC - ec2_vpc_net: - name: '{{ resource_prefix }}-vpc' - state: present - cidr_block: '{{ vpc_cidr }}' - tags: - AnsibleEIPTest: Pending - AnsibleEIPTestPrefix: '{{ resource_prefix }}' - register: vpc_result - - name: create subnet - ec2_vpc_subnet: - cidr: '{{ subnet_cidr }}' - az: '{{ subnet_az }}' - vpc_id: '{{ vpc_result.vpc.id }}' - state: present - register: vpc_subnet_create - - ec2_vpc_igw: - state: present - vpc_id: '{{ vpc_result.vpc.id }}' - register: vpc_igw - - name: "create a security group" - ec2_group: - state: present - name: '{{ resource_prefix }}-sg' - description: a security group for ansible tests - vpc_id: '{{ vpc_result.vpc.id }}' - rules: - - proto: tcp - from_port: 22 - to_port: 22 - cidr_ip: 0.0.0.0/0 - register: security_group - - name: Create instance for attaching - ec2_instance: - name: '{{ resource_prefix }}-instance' - image_id: '{{ ec2_ami_id }}' - security_group: '{{ security_group.group_id }}' - vpc_subnet_id: '{{ vpc_subnet_create.subnet.id }}' - wait: yes - state: running - register: create_ec2_instance_result - - # ===================================================== - - name: Look for signs of concurrent EIP tests. Pause if they are running or their prefix comes before ours. - vars: - running_query: vpcs[?tags.AnsibleEIPTest=='Running'] - pending_query: vpcs[?tags.AnsibleEIPTest=='Pending'].tags.AnsibleEIPTestPrefix - ec2_vpc_net_info: - filters: - tag:AnsibleEIPTest: - - Pending - - Running - register: vpc_info - retries: 120 - delay: 5 - until: - - ( vpc_info | community.general.json_query(running_query) | length == 0 ) - - ( vpc_info | community.general.json_query(pending_query) | sort | first == resource_prefix ) - - name: Make a crude lock - ec2_vpc_net: - name: '{{ resource_prefix }}-vpc' - state: present - cidr_block: '{{ vpc_cidr }}' - tags: - AnsibleEIPTest: Running - AnsibleEIPTestPrefix: '{{ resource_prefix }}' - - # ===================================================== - - name: Get current state of EIPs - ec2_eip_info: null - register: eip_info_start - - name: Require that there are no free IPs when we start, otherwise we can't test things properly - assert: - that: - - eip_info_start is defined - - '"addresses" in eip_info_start' - - ( eip_info_start.addresses | length ) == ( eip_info_start | community.general.json_query("addresses[].association_id") | length ) - - - name: Allocate a new eip (no conditions) - ec2_eip: - state: present - tags: - AnsibleEIPTestPrefix: '{{ resource_prefix }}' - register: eip - - - ec2_eip_info: null - register: eip_info - - assert: - that: - - eip is defined - - eip is changed - - eip.public_ip is defined and ( eip.public_ip | ansible.utils.ipaddr ) - - eip.allocation_id is defined and eip.allocation_id.startswith("eipalloc-") - - ( eip_info_start.addresses | length ) + 1 == ( eip_info.addresses | length ) - - - ec2_eip_info: - filters: - public-ip: '{{ eip.public_ip }}' - - assert: - that: - - '"addresses" in eip_info' - - eip_info.addresses | length == 1 - - eip_info.addresses[0].allocation_id == eip.allocation_id - - eip_info.addresses[0].domain == "vpc" - - eip_info.addresses[0].public_ip == eip.public_ip - - '"AnsibleEIPTestPrefix" in eip_info.addresses[0].tags' - - eip_info.addresses[0].tags['AnsibleEIPTestPrefix'] == resource_prefix - - - ec2_eip_info: - filters: - allocation-id: '{{ eip.allocation_id }}' - - assert: - that: - - '"addresses" in eip_info' - - eip_info.addresses | length == 1 - - eip_info.addresses[0].allocation_id == eip.allocation_id - - eip_info.addresses[0].domain == "vpc" - - eip_info.addresses[0].public_ip == eip.public_ip - - - name: Release eip - ec2_eip: - state: absent - public_ip: '{{ eip.public_ip }}' - register: eip_release - - ec2_eip_info: null - register: eip_info - - assert: - that: - - eip_release is defined - - eip_release is changed - - ( eip_info_start.addresses | length ) == ( eip_info.addresses | length ) - - - name: Allocate a new eip - attempt reusing unallocated ones (none available) - ec2_eip: - state: present - reuse_existing_ip_allowed: true - register: eip - - ec2_eip_info: null - register: eip_info - - assert: - that: - - eip is defined - - eip is changed - - eip.public_ip is defined and ( eip.public_ip | ansible.utils.ipaddr ) - - eip.allocation_id is defined and eip.allocation_id.startswith("eipalloc-") - - ( eip_info_start.addresses | length ) + 1 == ( eip_info.addresses | length ) - - - name: Re-Allocate a new eip - attempt reusing unallocated ones (one available) - ec2_eip: - state: present - reuse_existing_ip_allowed: true - register: reallocate_eip - - ec2_eip_info: null - register: eip_info - - assert: - that: - - reallocate_eip is defined - - reallocate_eip is not changed - - reallocate_eip.public_ip is defined and ( reallocate_eip.public_ip | ansible.utils.ipaddr ) - - reallocate_eip.allocation_id is defined and reallocate_eip.allocation_id.startswith("eipalloc-") - - ( eip_info_start.addresses | length ) + 1 == ( eip_info.addresses | length ) - - - name: Release eip - ec2_eip: - state: absent - public_ip: '{{ eip.public_ip }}' - register: eip_release - - ec2_eip_info: null - register: eip_info - - assert: - that: - - ( eip_info_start.addresses | length ) == ( eip_info.addresses | length ) - - eip_release is defined - - eip_release is changed - - - name: Allocate a new eip - ec2_eip: - state: present - register: eip - - ec2_eip_info: null - register: eip_info - - assert: - that: - - eip is defined - - eip is changed - - eip.public_ip is defined and ( eip.public_ip | ansible.utils.ipaddr ) - - eip.allocation_id is defined and eip.allocation_id.startswith("eipalloc-") - - ( eip_info_start.addresses | length ) + 1 == ( eip_info.addresses | length ) - - - name: Match an existing eip (changed == false) - ec2_eip: - state: present - public_ip: '{{ eip.public_ip }}' - register: reallocate_eip - - ec2_eip_info: null - register: eip_info - - assert: - that: - - reallocate_eip is defined - - reallocate_eip is not changed - - reallocate_eip.public_ip is defined and ( reallocate_eip.public_ip | ansible.utils.ipaddr ) - - reallocate_eip.allocation_id is defined and reallocate_eip.allocation_id.startswith("eipalloc-") - - ( eip_info_start.addresses | length ) + 1 == ( eip_info.addresses | length ) - - - name: Release eip - ec2_eip: - state: absent - public_ip: '{{ eip.public_ip }}' - register: eip_release - - ec2_eip_info: null - register: eip_info - - assert: - that: - - eip_release is defined - - eip_release is changed - - ( eip_info_start.addresses | length ) == ( eip_info.addresses | length ) - - - name: Allocate a new eip (no tags) - ec2_eip: - state: present - register: eip - - ec2_eip_info: null - register: eip_info - - assert: - that: - - eip is defined - - eip is changed - - eip.public_ip is defined and ( eip.public_ip | ansible.utils.ipaddr ) - - eip.allocation_id is defined and eip.allocation_id.startswith("eipalloc-") - - ( eip_info_start.addresses | length ) + 1 == ( eip_info.addresses | length ) - - - name: attempt reusing an existing eip with a tag (No match available) - ec2_eip: - state: present - reuse_existing_ip_allowed: true - tag_name: Team - register: no_tagged_eip - - ec2_eip_info: null - register: eip_info - - assert: - that: - - no_tagged_eip is defined - - no_tagged_eip is changed - - no_tagged_eip.public_ip is defined and ( no_tagged_eip.public_ip | ansible.utils.ipaddr ) - - no_tagged_eip.allocation_id is defined and no_tagged_eip.allocation_id.startswith("eipalloc-") - - ( eip_info_start.addresses | length ) + 2 == ( eip_info.addresses | length ) - - - name: tag eip so we can try matching it - ec2_eip: - state: present - public_ip: '{{ eip.public_ip }}' - tags: - Team: Frontend + - name: Get the current caller identity facts + aws_caller_info: + register: caller_info - - name: attempt reusing an existing eip with a tag (Match available) - ec2_eip: - state: present - reuse_existing_ip_allowed: true - tag_name: Team - register: reallocate_eip - - ec2_eip_info: null - register: eip_info - - assert: - that: - - reallocate_eip is defined - - reallocate_eip is not changed - - reallocate_eip.public_ip is defined and ( reallocate_eip.public_ip | ansible.utils.ipaddr ) - - reallocate_eip.allocation_id is defined and reallocate_eip.allocation_id.startswith("eipalloc-") - - ( eip_info_start.addresses | length ) + 2 == ( eip_info.addresses | length ) - - - name: attempt reusing an existing eip with a tag and it's value (no match available) - ec2_eip: - state: present - reuse_existing_ip_allowed: true - tag_name: Team - tag_value: Backend - register: backend_eip - - ec2_eip_info: null - register: eip_info - - assert: - that: - - backend_eip is defined - - backend_eip is changed - - backend_eip.public_ip is defined and ( backend_eip.public_ip | ansible.utils.ipaddr ) - - backend_eip.allocation_id is defined and backend_eip.allocation_id.startswith("eipalloc-") - - ( eip_info_start.addresses | length ) + 3 == ( eip_info.addresses | length ) - - - name: tag eip so we can try matching it - ec2_eip: - state: present - public_ip: '{{ eip.public_ip }}' - tags: - Team: Backend + - name: List available AZs + aws_az_info: + register: region_azs - - name: attempt reusing an existing eip with a tag and it's value (match available) - ec2_eip: - state: present - reuse_existing_ip_allowed: true - tag_name: Team - tag_value: Backend - register: reallocate_eip - - ec2_eip_info: null - register: eip_info - - assert: - that: - - reallocate_eip is defined - - reallocate_eip is not changed - - reallocate_eip.public_ip is defined and reallocate_eip.public_ip != "" - - reallocate_eip.allocation_id is defined and reallocate_eip.allocation_id != "" - - ( eip_info_start.addresses | length ) + 3 == ( eip_info.addresses | length ) - - - name: Release backend_eip - ec2_eip: - state: absent - public_ip: '{{ backend_eip.public_ip }}' - register: eip_release - - ec2_eip_info: null - register: eip_info - - assert: - that: - - eip_release is defined - - eip_release is changed - - ( eip_info_start.addresses | length ) + 2 == ( eip_info.addresses | length ) - - - name: Release no_tagged_eip - ec2_eip: - state: absent - public_ip: '{{ no_tagged_eip.public_ip }}' - register: eip_release - - ec2_eip_info: null - register: eip_info - - assert: - that: - - eip_release is defined - - eip_release is changed - - ( eip_info_start.addresses | length ) + 1 == ( eip_info.addresses | length ) - - - name: Release eip - ec2_eip: - state: absent - public_ip: '{{ eip.public_ip }}' - register: eip_release - - ec2_eip_info: null - register: eip_info - - assert: - that: - - eip_release is defined - - eip_release is changed - - ( eip_info_start.addresses | length ) == ( eip_info.addresses | length ) - - - name: allocate a new eip from a pool - ec2_eip: - state: present - public_ipv4_pool: amazon - register: eip - - ec2_eip_info: null - register: eip_info - - assert: - that: - - eip is defined - - eip is changed - - eip.public_ip is defined and ( eip.public_ip | ansible.utils.ipaddr ) - - eip.allocation_id is defined and eip.allocation_id.startswith("eipalloc-") - - ( eip_info_start.addresses | length ) + 1 == ( eip_info.addresses | length ) - - - name: create ENI A - ec2_eni: - subnet_id: '{{ vpc_subnet_create.subnet.id }}' - register: eni_create_a - - - name: create ENI B - ec2_eni: - subnet_id: '{{ vpc_subnet_create.subnet.id }}' - register: eni_create_b - - - name: Attach EIP to ENI A - ec2_eip: - public_ip: '{{ eip.public_ip }}' - device_id: '{{ eni_create_a.interface.id }}' - register: associate_eip - - ec2_eip_info: - filters: - public-ip: '{{ eip.public_ip }}' - register: eip_info - - assert: - that: - - associate_eip is defined - - associate_eip is changed - - eip_info.addresses | length == 1 - - associate_eip.public_ip is defined and eip.public_ip == associate_eip.public_ip - - associate_eip.allocation_id is defined and eip.allocation_id == associate_eip.allocation_id - - eip_info.addresses[0].allocation_id == eip.allocation_id - - eip_info.addresses[0].domain == "vpc" - - eip_info.addresses[0].public_ip == eip.public_ip - - eip_info.addresses[0].association_id is defined and eip_info.addresses[0].association_id.startswith("eipassoc-") - - eip_info.addresses[0].network_interface_id == eni_create_a.interface.id - - eip_info.addresses[0].private_ip_address is defined and ( eip_info.addresses[0].private_ip_address | ansible.utils.ipaddr ) - - eip_info.addresses[0].network_interface_owner_id == caller_info.account - - - name: Re-Attach EIP to ENI A (no change) - ec2_eip: - public_ip: '{{ eip.public_ip }}' - device_id: '{{ eni_create_a.interface.id }}' - register: associate_eip - - ec2_eip_info: - filters: - public-ip: '{{ eip.public_ip }}' - register: eip_info - - assert: - that: - - associate_eip is defined - - associate_eip is not changed - - associate_eip.public_ip is defined and eip.public_ip == associate_eip.public_ip - - associate_eip.allocation_id is defined and eip.allocation_id == associate_eip.allocation_id - - eip_info.addresses | length == 1 - - eip_info.addresses[0].allocation_id == eip.allocation_id - - eip_info.addresses[0].domain == "vpc" - - eip_info.addresses[0].public_ip == eip.public_ip - - eip_info.addresses[0].association_id is defined and eip_info.addresses[0].association_id.startswith("eipassoc-") - - eip_info.addresses[0].network_interface_id == eni_create_a.interface.id - - eip_info.addresses[0].private_ip_address is defined and ( eip_info.addresses[0].private_ip_address | ansible.utils.ipaddr ) - - - name: Attach EIP to ENI B (should fail, already associated) - ec2_eip: - public_ip: '{{ eip.public_ip }}' - device_id: '{{ eni_create_b.interface.id }}' - register: associate_eip - ignore_errors: true - - ec2_eip_info: - filters: - public-ip: '{{ eip.public_ip }}' - register: eip_info - - assert: - that: - - associate_eip is defined - - associate_eip is failed - - eip_info.addresses | length == 1 - - eip_info.addresses[0].allocation_id == eip.allocation_id - - eip_info.addresses[0].domain == "vpc" - - eip_info.addresses[0].public_ip == eip.public_ip - - eip_info.addresses[0].association_id is defined and eip_info.addresses[0].association_id.startswith("eipassoc-") - - eip_info.addresses[0].network_interface_id == eni_create_a.interface.id - - eip_info.addresses[0].private_ip_address is defined and ( eip_info.addresses[0].private_ip_address | ansible.utils.ipaddr ) - - - name: Attach EIP to ENI B - ec2_eip: - public_ip: '{{ eip.public_ip }}' - device_id: '{{ eni_create_b.interface.id }}' - allow_reassociation: true - register: associate_eip - - ec2_eip_info: - filters: - public-ip: '{{ eip.public_ip }}' - register: eip_info - - assert: - that: - - associate_eip is defined - - associate_eip is changed - - associate_eip.public_ip is defined and eip.public_ip == associate_eip.public_ip - - associate_eip.allocation_id is defined and eip.allocation_id == associate_eip.allocation_id - - eip_info.addresses | length == 1 - - eip_info.addresses[0].allocation_id == eip.allocation_id - - eip_info.addresses[0].domain == "vpc" - - eip_info.addresses[0].public_ip == eip.public_ip - - eip_info.addresses[0].association_id is defined and eip_info.addresses[0].association_id.startswith("eipassoc-") - - eip_info.addresses[0].network_interface_id == eni_create_b.interface.id - - eip_info.addresses[0].private_ip_address is defined and ( eip_info.addresses[0].private_ip_address | ansible.utils.ipaddr ) - - - name: Detach EIP from ENI B, without enabling release on disassociation - ec2_eip: - state: absent - public_ip: '{{ eip.public_ip }}' - device_id: '{{ eni_create_b.interface.id }}' - register: disassociate_eip - - ec2_eip_info: - filters: - public-ip: '{{ eip.public_ip }}' - register: eip_info - - assert: - that: - - associate_eip is defined - - associate_eip is changed - - eip_info.addresses | length == 1 - - - name: Re-detach EIP from ENI B, without enabling release on disassociation - ec2_eip: - state: absent - public_ip: '{{ eip.public_ip }}' - device_id: '{{ eni_create_b.interface.id }}' - register: associate_eip - - ec2_eip_info: - filters: - public-ip: '{{ eip.public_ip }}' - register: eip_info - - assert: - that: - - associate_eip is defined - - associate_eip is not changed - - eip_info.addresses | length == 1 - - - name: Attach EIP to ENI A - ec2_eip: - public_ip: '{{ eip.public_ip }}' - device_id: '{{ eni_create_a.interface.id }}' - register: associate_eip - - ec2_eip_info: - filters: - public-ip: '{{ eip.public_ip }}' - register: eip_info - - assert: - that: - - associate_eip is defined - - associate_eip is changed - - associate_eip.public_ip is defined and eip.public_ip == associate_eip.public_ip - - associate_eip.allocation_id is defined and eip.allocation_id == associate_eip.allocation_id - - eip_info.addresses[0].network_interface_id == eni_create_a.interface.id - - - name: Detach EIP from ENI A, enabling release on disassociation - ec2_eip: - state: absent - public_ip: '{{ eip.public_ip }}' - device_id: '{{ eni_create_a.interface.id }}' - release_on_disassociation: true - register: disassociate_eip - - ec2_eip_info: - filters: - public-ip: '{{ eip.public_ip }}' - register: eip_info - - assert: - that: - - associate_eip is defined - - associate_eip is changed - - eip_info.addresses | length == 0 - - - name: Re-detach EIP from ENI A, enabling release on disassociation - ec2_eip: - state: absent - public_ip: '{{ eip.public_ip }}' - device_id: '{{ eni_create_a.interface.id }}' - release_on_disassociation: true - register: associate_eip - - ec2_eip_info: - filters: - public-ip: '{{ eip.public_ip }}' - register: eip_info - - assert: - that: - - associate_eip is defined - - associate_eip is not changed - - eip_info.addresses | length == 0 - - - ec2_eip_info: null - register: eip_info - - assert: - that: - - ( eip_info_start.addresses | length ) == ( eip_info.addresses | length ) - - - name: Cleanup ENI B - ec2_eni: - state: absent - eni_id: '{{ eni_create_b.interface.id }}' - - - name: Cleanup ENI A - ec2_eni: - state: absent - eni_id: '{{ eni_create_a.interface.id }}' - - - name: Attach eip to an EC2 instance - ec2_eip: - device_id: '{{ create_ec2_instance_result.instance_ids[0] }}' - state: present - release_on_disassociation: yes - register: instance_eip - - ec2_eip_info: - filters: - public-ip: '{{ instance_eip.public_ip }}' - register: eip_info - - assert: - that: - - instance_eip is success - - eip_info.addresses[0].allocation_id is defined - - eip_info.addresses[0].instance_id == '{{ create_ec2_instance_result.instance_ids[0] }}' - - - name: Attach eip to an EC2 instance with private Ip specified - ec2_eip: - device_id: '{{ create_ec2_instance_result.instance_ids[0] }}' - private_ip_address: '{{ create_ec2_instance_result.instances[0].private_ip_address }}' - state: present - release_on_disassociation: yes - register: instance_eip - - ec2_eip_info: - filters: - public-ip: '{{ instance_eip.public_ip }}' - register: eip_info - - assert: - that: - - instance_eip is success - - eip_info.addresses[0].allocation_id is defined - - eip_info.addresses[0].instance_id == '{{ create_ec2_instance_result.instance_ids[0] }}' - - # ===================================================== - - - name: Cleanup instance - ec2_instance: - instance_ids: '{{ create_ec2_instance_result.instance_ids }}' - state: absent - - - name: Cleanup instance eip - ec2_eip: - state: absent - public_ip: '{{ instance_eip.public_ip }}' - register: eip_cleanup - retries: 5 - delay: 5 - until: eip_cleanup is successful - - - name: Cleanup IGW - ec2_vpc_igw: - state: absent - vpc_id: '{{ vpc_result.vpc.id }}' - register: vpc_igw - - - name: Cleanup security group - ec2_group: - state: absent - name: '{{ resource_prefix }}-sg' - - - name: Cleanup Subnet - ec2_vpc_subnet: - state: absent - cidr: '{{ subnet_cidr }}' - vpc_id: '{{ vpc_result.vpc.id }}' - - - name: Release eip - ec2_eip: - state: absent - public_ip: '{{ eip.public_ip }}' - register: eip_release - ignore_errors: true + - name: Create a VPC + ec2_vpc_net: + name: '{{ resource_prefix }}-vpc' + state: present + cidr_block: '{{ vpc_cidr }}' + tags: + AnsibleEIPTest: Pending + AnsibleEIPTestPrefix: '{{ resource_prefix }}' + register: vpc_result + + - name: Look for signs of concurrent EIP tests. Pause if they are running or their prefix comes before ours. + vars: + running_query: vpcs[?tags.AnsibleEIPTest=='Running'] + pending_query: vpcs[?tags.AnsibleEIPTest=='Pending'].tags.AnsibleEIPTestPrefix + ec2_vpc_net_info: + filters: + tag:AnsibleEIPTest: + - Pending + - Running + register: vpc_info + retries: 10 + delay: 5 + until: + - ( vpc_info.vpcs | map(attribute='tags') | selectattr('AnsibleEIPTest', 'equalto', 'Running') | length == 0 ) + - ( vpc_info.vpcs | map(attribute='tags') | selectattr('AnsibleEIPTest', 'equalto', 'Pending') | map(attribute='AnsibleEIPTestPrefix') | sort | first == resource_prefix ) + + - name: Create subnet + ec2_vpc_subnet: + cidr: '{{ subnet_cidr }}' + az: '{{ subnet_az }}' + vpc_id: '{{ vpc_result.vpc.id }}' + state: present + register: vpc_subnet_create + + - name: Create internet gateway + amazon.aws.ec2_vpc_igw: + state: present + vpc_id: '{{ vpc_result.vpc.id }}' + register: vpc_igw + + - name: Create security group + ec2_group: + state: present + name: '{{ resource_prefix }}-sg' + description: a security group for ansible tests + vpc_id: '{{ vpc_result.vpc.id }}' + rules: + - proto: tcp + from_port: 22 + to_port: 22 + cidr_ip: 0.0.0.0/0 + register: security_group + + - name: Create instance for attaching + ec2_instance: + name: '{{ resource_prefix }}-instance' + image_id: '{{ ec2_ami_id }}' + security_group: '{{ security_group.group_id }}' + vpc_subnet_id: '{{ vpc_subnet_create.subnet.id }}' + wait: yes + state: running + register: create_ec2_instance_result + + - name: Create ENI A + ec2_eni: + subnet_id: '{{ vpc_subnet_create.subnet.id }}' + register: eni_create_a + + - name: Create ENI B + ec2_eni: + subnet_id: '{{ vpc_subnet_create.subnet.id }}' + register: eni_create_b + + - name: Make a crude lock + ec2_vpc_net: + name: '{{ resource_prefix }}-vpc' + state: present + cidr_block: '{{ vpc_cidr }}' + tags: + AnsibleEIPTest: Running + AnsibleEIPTestPrefix: '{{ resource_prefix }}' + + - name: Get current state of EIPs + ec2_eip_info: + register: eip_info_start + + - name: Require that there are no free IPs when we start, otherwise we can't test things properly + assert: + that: + - '"addresses" in eip_info_start' + - ( eip_info_start.addresses | length ) == ( eip_info_start.addresses | select('match', 'association_id') | length ) + + # ------------------------------------------------------------------------------------------ + + - name: Allocate a new EIP with no conditions - check_mode + ec2_eip: + state: present + tags: + AnsibleEIPTestPrefix: '{{ resource_prefix }}' + register: eip + check_mode: yes + + - assert: + that: + - eip is changed + + - name: Allocate a new EIP with no conditions + ec2_eip: + state: present + tags: + AnsibleEIPTestPrefix: '{{ resource_prefix }}' + register: eip + + - ec2_eip_info: + register: eip_info + check_mode: yes + + - assert: + that: + - eip is changed + - eip.public_ip is defined and ( eip.public_ip | ansible.utils.ipaddr ) + - eip.allocation_id is defined and eip.allocation_id.startswith("eipalloc-") + - ( eip_info_start.addresses | length ) + 1 == ( eip_info.addresses | length ) + + - name: Get EIP info via public ip + ec2_eip_info: + filters: + public-ip: '{{ eip.public_ip }}' + register: eip_info + + - assert: + that: + - '"addresses" in eip_info' + - eip_info.addresses | length == 1 + - eip_info.addresses[0].allocation_id == eip.allocation_id + - eip_info.addresses[0].domain == "vpc" + - eip_info.addresses[0].public_ip == eip.public_ip + - '"AnsibleEIPTestPrefix" in eip_info.addresses[0].tags' + - eip_info.addresses[0].tags['AnsibleEIPTestPrefix'] == resource_prefix + + - name: Get EIP info via allocation id + ec2_eip_info: + filters: + allocation-id: '{{ eip.allocation_id }}' + register: eip_info + + - assert: + that: + - '"addresses" in eip_info' + - eip_info.addresses | length == 1 + - eip_info.addresses[0].allocation_id == eip.allocation_id + - eip_info.addresses[0].domain == "vpc" + - eip_info.addresses[0].public_ip == eip.public_ip + - '"AnsibleEIPTestPrefix" in eip_info.addresses[0].tags' + - eip_info.addresses[0].tags['AnsibleEIPTestPrefix'] == resource_prefix + + - name: Allocate a new ip (idempotence) - check_mode + ec2_eip: + state: present + public_ip: '{{ eip.public_ip }}' + register: eip + check_mode: yes + + - assert: + that: + - eip is not changed + + - name: Allocate a new ip (idempotence) + ec2_eip: + state: present + public_ip: '{{ eip.public_ip }}' + register: eip + + - ec2_eip_info: + register: eip_info + + - assert: + that: + - eip is not changed + - eip.public_ip is defined and ( eip.public_ip | ansible.utils.ipaddr ) + - eip.allocation_id is defined and eip.allocation_id.startswith("eipalloc-") + - ( eip_info_start.addresses | length ) + 1 == ( eip_info.addresses | length ) + + # ------------------------------------------------------------------------------------------ + + - name: Release EIP - check_mode + ec2_eip: + state: absent + public_ip: '{{ eip.public_ip }}' + register: eip_release + check_mode: yes + + - assert: + that: + - eip_release.changed + + - name: Release eip + ec2_eip: + state: absent + public_ip: '{{ eip.public_ip }}' + register: eip_release + + - ec2_eip_info: + register: eip_info + + - assert: + that: + - eip_release.changed + - not eip_release.disassociated + - eip_release.released + - ( eip_info_start.addresses | length ) == ( eip_info.addresses | length ) + + - name: Release EIP (idempotence) - check_mode + ec2_eip: + state: absent + public_ip: '{{ eip.public_ip }}' + register: eip_release + check_mode: yes + + - assert: + that: + - eip_release is not changed + + - name: Release EIP (idempotence) + ec2_eip: + state: absent + public_ip: '{{ eip.public_ip }}' + register: eip_release + + - ec2_eip_info: + register: eip_info + + - assert: + that: + - not eip_release.changed + - not eip_release.disassociated + - not eip_release.released + - ( eip_info_start.addresses | length ) == ( eip_info.addresses | length ) + + # ------------------------------------------------------------------------------------------ + + - name: Allocate a new EIP - attempt reusing unallocated ones (none available) - check_mode + ec2_eip: + state: present + reuse_existing_ip_allowed: true + register: eip + check_mode: yes + + - assert: + that: + - eip is changed + + - name: Allocate a new EIP - attempt reusing unallocated ones (none available) + ec2_eip: + state: present + reuse_existing_ip_allowed: true + register: eip + + - ec2_eip_info: + register: eip_info + + - assert: + that: + - eip is changed + - eip.public_ip is defined and ( eip.public_ip | ansible.utils.ipaddr ) + - eip.allocation_id is defined and eip.allocation_id.startswith("eipalloc-") + - ( eip_info_start.addresses | length ) + 1 == ( eip_info.addresses | length ) + + - name: Re-Allocate a new EIP - attempt reusing unallocated ones (one available) - check_mode + ec2_eip: + state: present + reuse_existing_ip_allowed: true + register: reallocate_eip + check_mode: yes + + - assert: + that: + - reallocate_eip is not changed + + - name: Re-Allocate a new EIP - attempt reusing unallocated ones (one available) + ec2_eip: + state: present + reuse_existing_ip_allowed: true + register: reallocate_eip + + - ec2_eip_info: + register: eip_info + + - assert: + that: + - reallocate_eip is not changed + - reallocate_eip.public_ip is defined and ( reallocate_eip.public_ip | ansible.utils.ipaddr ) + - reallocate_eip.allocation_id is defined and reallocate_eip.allocation_id.startswith("eipalloc-") + - ( eip_info_start.addresses | length ) + 1 == ( eip_info.addresses | length ) + + # ------------------------------------------------------------------------------------------ + + - name: attempt reusing an existing EIP with a tag (No match available) - check_mode + ec2_eip: + state: present + reuse_existing_ip_allowed: true + tag_name: Team + register: no_tagged_eip + check_mode: yes + + - assert: + that: + - no_tagged_eip is changed + + - name: attempt reusing an existing EIP with a tag (No match available) + ec2_eip: + state: present + reuse_existing_ip_allowed: true + tag_name: Team + register: no_tagged_eip + + - ec2_eip_info: + register: eip_info + + - assert: + that: + - no_tagged_eip is changed + - no_tagged_eip.public_ip is defined and ( no_tagged_eip.public_ip | ansible.utils.ipaddr ) + - no_tagged_eip.allocation_id is defined and no_tagged_eip.allocation_id.startswith("eipalloc-") + - ( eip_info_start.addresses | length ) + 2 == ( eip_info.addresses | length ) + + # ------------------------------------------------------------------------------------------ + + - name: Tag EIP so we can try matching it + ec2_eip: + state: present + public_ip: '{{ eip.public_ip }}' + tags: + Team: Frontend + + - name: Attempt reusing an existing EIP with a tag (Match available) - check_mode + ec2_eip: + state: present + reuse_existing_ip_allowed: true + tag_name: Team + register: reallocate_eip + check_mode: yes + + - assert: + that: + - reallocate_eip is not changed + + - name: Attempt reusing an existing EIP with a tag (Match available) + ec2_eip: + state: present + reuse_existing_ip_allowed: true + tag_name: Team + register: reallocate_eip + + - ec2_eip_info: + register: eip_info + + - assert: + that: + - reallocate_eip is not changed + - reallocate_eip.public_ip is defined and ( reallocate_eip.public_ip | ansible.utils.ipaddr ) + - reallocate_eip.allocation_id is defined and reallocate_eip.allocation_id.startswith("eipalloc-") + - ( eip_info_start.addresses | length ) + 2 == ( eip_info.addresses | length ) + + - name: Attempt reusing an existing EIP with a tag and it's value (no match available) - check_mode + ec2_eip: + state: present + reuse_existing_ip_allowed: true + tag_name: Team + tag_value: Backend + register: backend_eip + check_mode: yes + + - assert: + that: + - backend_eip is changed + + - name: Attempt reusing an existing EIP with a tag and it's value (no match available) + ec2_eip: + state: present + reuse_existing_ip_allowed: true + tag_name: Team + tag_value: Backend + register: backend_eip + + - ec2_eip_info: + register: eip_info + + - assert: + that: + - backend_eip is changed + - backend_eip.public_ip is defined and ( backend_eip.public_ip | ansible.utils.ipaddr ) + - backend_eip.allocation_id is defined and backend_eip.allocation_id.startswith("eipalloc-") + - ( eip_info_start.addresses | length ) + 3 == ( eip_info.addresses | length ) + + # ------------------------------------------------------------------------------------------ + + - name: Tag EIP so we can try matching it + ec2_eip: + state: present + public_ip: '{{ eip.public_ip }}' + tags: + Team: Backend + + - name: Attempt reusing an existing EIP with a tag and it's value (match available) - check_mode + ec2_eip: + state: present + reuse_existing_ip_allowed: true + tag_name: Team + tag_value: Backend + register: reallocate_eip + check_mode: yes + + - assert: + that: + - reallocate_eip is not changed + + - name: Attempt reusing an existing EIP with a tag and it's value (match available) + ec2_eip: + state: present + reuse_existing_ip_allowed: true + tag_name: Team + tag_value: Backend + register: reallocate_eip + + - ec2_eip_info: + register: eip_info + + - assert: + that: + - reallocate_eip is not changed + - reallocate_eip.public_ip is defined and reallocate_eip.public_ip != "" + - reallocate_eip.allocation_id is defined and reallocate_eip.allocation_id != "" + - ( eip_info_start.addresses | length ) + 3 == ( eip_info.addresses | length ) + + - name: Release backend_eip + ec2_eip: + state: absent + public_ip: '{{ backend_eip.public_ip }}' + + - name: Release no_tagged_eip + ec2_eip: + state: absent + public_ip: '{{ no_tagged_eip.public_ip }}' + + - name: Release eip + ec2_eip: + state: absent + public_ip: '{{ eip.public_ip }}' + + - ec2_eip_info: + register: eip_info + + - assert: + that: + - ( eip_info_start.addresses | length ) == ( eip_info.addresses | length ) + + # ------------------------------------------------------------------------------------------ + + - name: Allocate a new EIP from a pool - check_mode + ec2_eip: + state: present + public_ipv4_pool: amazon + register: eip + check_mode: yes + + - assert: + that: + - eip is changed + + - name: Allocate a new EIP from a pool + ec2_eip: + state: present + public_ipv4_pool: amazon + register: eip + + - ec2_eip_info: + register: eip_info + + - assert: + that: + - eip is changed + - eip.public_ip is defined and ( eip.public_ip | ansible.utils.ipaddr ) + - eip.allocation_id is defined and eip.allocation_id.startswith("eipalloc-") + - ( eip_info_start.addresses | length ) + 1 == ( eip_info.addresses | length ) + + # ------------------------------------------------------------------------------------------ + + - name: Attach EIP to ENI A - check_mode + ec2_eip: + public_ip: '{{ eip.public_ip }}' + device_id: '{{ eni_create_a.interface.id }}' + register: associate_eip + check_mode: yes + + - assert: + that: + - associate_eip is changed + + - name: Attach EIP to ENI A + ec2_eip: + public_ip: '{{ eip.public_ip }}' + device_id: '{{ eni_create_a.interface.id }}' + register: associate_eip + + - ec2_eip_info: + filters: + public-ip: '{{ eip.public_ip }}' + register: eip_info + + - assert: + that: + - associate_eip is changed + - eip_info.addresses | length == 1 + - associate_eip.public_ip is defined and eip.public_ip == associate_eip.public_ip + - associate_eip.allocation_id is defined and eip.allocation_id == associate_eip.allocation_id + - eip_info.addresses[0].allocation_id == eip.allocation_id + - eip_info.addresses[0].domain == "vpc" + - eip_info.addresses[0].public_ip == eip.public_ip + - eip_info.addresses[0].association_id is defined and eip_info.addresses[0].association_id.startswith("eipassoc-") + - eip_info.addresses[0].network_interface_id == eni_create_a.interface.id + - eip_info.addresses[0].private_ip_address is defined and ( eip_info.addresses[0].private_ip_address | ansible.utils.ipaddr ) + - eip_info.addresses[0].network_interface_owner_id == caller_info.account + + - name: Attach EIP to ENI A (idempotence) - check_mode + ec2_eip: + public_ip: '{{ eip.public_ip }}' + device_id: '{{ eni_create_a.interface.id }}' + register: associate_eip + check_mode: yes + + - assert: + that: + - associate_eip is not changed + + - name: Attach EIP to ENI A (idempotence) + ec2_eip: + public_ip: '{{ eip.public_ip }}' + device_id: '{{ eni_create_a.interface.id }}' + register: associate_eip + + - ec2_eip_info: + filters: + public-ip: '{{ eip.public_ip }}' + register: eip_info + + - assert: + that: + - associate_eip is not changed + - associate_eip.public_ip is defined and eip.public_ip == associate_eip.public_ip + - associate_eip.allocation_id is defined and eip.allocation_id == associate_eip.allocation_id + - eip_info.addresses | length == 1 + - eip_info.addresses[0].allocation_id == eip.allocation_id + - eip_info.addresses[0].domain == "vpc" + - eip_info.addresses[0].public_ip == eip.public_ip + - eip_info.addresses[0].association_id is defined and eip_info.addresses[0].association_id.startswith("eipassoc-") + - eip_info.addresses[0].network_interface_id == eni_create_a.interface.id + - eip_info.addresses[0].private_ip_address is defined and ( eip_info.addresses[0].private_ip_address | ansible.utils.ipaddr ) + + # ------------------------------------------------------------------------------------------ + + - name: Attach EIP to ENI B (should fail, already associated) + ec2_eip: + public_ip: '{{ eip.public_ip }}' + device_id: '{{ eni_create_b.interface.id }}' + register: associate_eip + ignore_errors: true + + - ec2_eip_info: + filters: + public-ip: '{{ eip.public_ip }}' + register: eip_info + + - assert: + that: + - associate_eip is failed + - eip_info.addresses | length == 1 + - eip_info.addresses[0].allocation_id == eip.allocation_id + - eip_info.addresses[0].domain == "vpc" + - eip_info.addresses[0].public_ip == eip.public_ip + - eip_info.addresses[0].association_id is defined and eip_info.addresses[0].association_id.startswith("eipassoc-") + - eip_info.addresses[0].network_interface_id == eni_create_a.interface.id + - eip_info.addresses[0].private_ip_address is defined and ( eip_info.addresses[0].private_ip_address | ansible.utils.ipaddr ) + + - name: Attach EIP to ENI B - check_mode + ec2_eip: + public_ip: '{{ eip.public_ip }}' + device_id: '{{ eni_create_b.interface.id }}' + allow_reassociation: true + register: associate_eip + check_mode: yes + + - assert: + that: + - associate_eip is changed + + - name: Attach EIP to ENI B + ec2_eip: + public_ip: '{{ eip.public_ip }}' + device_id: '{{ eni_create_b.interface.id }}' + allow_reassociation: true + register: associate_eip + + - ec2_eip_info: + filters: + public-ip: '{{ eip.public_ip }}' + register: eip_info + + - assert: + that: + - associate_eip is changed + - associate_eip.public_ip is defined and eip.public_ip == associate_eip.public_ip + - associate_eip.allocation_id is defined and eip.allocation_id == associate_eip.allocation_id + - eip_info.addresses | length == 1 + - eip_info.addresses[0].allocation_id == eip.allocation_id + - eip_info.addresses[0].domain == "vpc" + - eip_info.addresses[0].public_ip == eip.public_ip + - eip_info.addresses[0].association_id is defined and eip_info.addresses[0].association_id.startswith("eipassoc-") + - eip_info.addresses[0].network_interface_id == eni_create_b.interface.id + - eip_info.addresses[0].private_ip_address is defined and ( eip_info.addresses[0].private_ip_address | ansible.utils.ipaddr ) + + - name: Attach EIP to ENI B (idempotence) - check_mode + ec2_eip: + public_ip: '{{ eip.public_ip }}' + device_id: '{{ eni_create_b.interface.id }}' + allow_reassociation: true + register: associate_eip + check_mode: yes + + - assert: + that: + - associate_eip is not changed + + - name: Attach EIP to ENI B (idempotence) + ec2_eip: + public_ip: '{{ eip.public_ip }}' + device_id: '{{ eni_create_b.interface.id }}' + allow_reassociation: true + register: associate_eip + + - ec2_eip_info: + filters: + public-ip: '{{ eip.public_ip }}' + register: eip_info + + - assert: + that: + - associate_eip is not changed + - associate_eip.public_ip is defined and eip.public_ip == associate_eip.public_ip + - associate_eip.allocation_id is defined and eip.allocation_id == associate_eip.allocation_id + - eip_info.addresses | length == 1 + - eip_info.addresses[0].allocation_id == eip.allocation_id + - eip_info.addresses[0].domain == "vpc" + - eip_info.addresses[0].public_ip == eip.public_ip + - eip_info.addresses[0].association_id is defined and eip_info.addresses[0].association_id.startswith("eipassoc-") + - eip_info.addresses[0].network_interface_id == eni_create_b.interface.id + - eip_info.addresses[0].private_ip_address is defined and ( eip_info.addresses[0].private_ip_address | ansible.utils.ipaddr ) + + # ------------------------------------------------------------------------------------------ + + - name: Detach EIP from ENI B, without enabling release on disassociation - check_mode + ec2_eip: + state: absent + public_ip: '{{ eip.public_ip }}' + device_id: '{{ eni_create_b.interface.id }}' + register: disassociate_eip + check_mode: yes + + - assert: + that: + - disassociate_eip is changed + + - name: Detach EIP from ENI B, without enabling release on disassociation + ec2_eip: + state: absent + public_ip: '{{ eip.public_ip }}' + device_id: '{{ eni_create_b.interface.id }}' + register: disassociate_eip + + - ec2_eip_info: + filters: + public-ip: '{{ eip.public_ip }}' + register: eip_info + + - assert: + that: + - disassociate_eip.changed + - disassociate_eip.disassociated + - not disassociate_eip.released + - eip_info.addresses | length == 1 + + - name: Detach EIP from ENI B, without enabling release on disassociation (idempotence) - check_mode + ec2_eip: + state: absent + public_ip: '{{ eip.public_ip }}' + device_id: '{{ eni_create_b.interface.id }}' + register: disassociate_eip + check_mode: yes + + - assert: + that: + - disassociate_eip is not changed + + - name: Detach EIP from ENI B, without enabling release on disassociation (idempotence) + ec2_eip: + state: absent + public_ip: '{{ eip.public_ip }}' + device_id: '{{ eni_create_b.interface.id }}' + register: disassociate_eip + + - ec2_eip_info: + filters: + public-ip: '{{ eip.public_ip }}' + register: eip_info + + - assert: + that: + - not disassociate_eip.changed + - not disassociate_eip.disassociated + - not disassociate_eip.released + - eip_info.addresses | length == 1 + + # ------------------------------------------------------------------------------------------ + + - name: Attach EIP to ENI A + ec2_eip: + public_ip: '{{ eip.public_ip }}' + device_id: '{{ eni_create_a.interface.id }}' + register: associate_eip + + - name: Detach EIP from ENI A, enabling release on disassociation - check_mode + ec2_eip: + state: absent + public_ip: '{{ eip.public_ip }}' + device_id: '{{ eni_create_a.interface.id }}' + release_on_disassociation: true + register: disassociate_eip + check_mode: yes + + - assert: + that: + - disassociate_eip is changed + + - name: Detach EIP from ENI A, enabling release on disassociation + ec2_eip: + state: absent + public_ip: '{{ eip.public_ip }}' + device_id: '{{ eni_create_a.interface.id }}' + release_on_disassociation: true + register: disassociate_eip + + - ec2_eip_info: + filters: + public-ip: '{{ eip.public_ip }}' + register: eip_info + + - assert: + that: + - disassociate_eip.changed + - disassociate_eip.disassociated + - disassociate_eip.released + - eip_info.addresses | length == 0 + + - name: Detach EIP from ENI A, enabling release on disassociation (idempotence) - check_mode + ec2_eip: + state: absent + public_ip: '{{ eip.public_ip }}' + device_id: '{{ eni_create_a.interface.id }}' + release_on_disassociation: true + register: disassociate_eip + check_mode: yes + + - assert: + that: + - disassociate_eip is not changed + + - name: Detach EIP from ENI A, enabling release on disassociation (idempotence) + ec2_eip: + state: absent + public_ip: '{{ eip.public_ip }}' + device_id: '{{ eni_create_a.interface.id }}' + release_on_disassociation: true + register: disassociate_eip + + - ec2_eip_info: + filters: + public-ip: '{{ eip.public_ip }}' + register: eip_info + + - assert: + that: + - not disassociate_eip.changed + - not disassociate_eip.disassociated + - not disassociate_eip.released + - eip_info.addresses | length == 0 + + # ------------------------------------------------------------------------------------------ + + - name: Attach EIP to an EC2 instance - check_mode + ec2_eip: + device_id: '{{ create_ec2_instance_result.instance_ids[0] }}' + state: present + release_on_disassociation: yes + register: instance_eip + check_mode: yes + + - assert: + that: + - instance_eip is changed + + - name: Attach EIP to an EC2 instance + ec2_eip: + device_id: '{{ create_ec2_instance_result.instance_ids[0] }}' + state: present + release_on_disassociation: yes + register: instance_eip + + - ec2_eip_info: + filters: + public-ip: '{{ instance_eip.public_ip }}' + register: eip_info + + - assert: + that: + - instance_eip is changed + - eip_info.addresses[0].allocation_id is defined + - eip_info.addresses[0].instance_id == '{{ create_ec2_instance_result.instance_ids[0] }}' + + - name: Attach EIP to an EC2 instance (idempotence) - check_mode + ec2_eip: + device_id: '{{ create_ec2_instance_result.instance_ids[0] }}' + state: present + release_on_disassociation: yes + register: instance_eip + check_mode: yes + + - assert: + that: + - instance_eip is not changed + + - name: Attach EIP to an EC2 instance (idempotence) + ec2_eip: + device_id: '{{ create_ec2_instance_result.instance_ids[0] }}' + state: present + release_on_disassociation: yes + register: instance_eip + + - ec2_eip_info: + filters: + public-ip: '{{ instance_eip.public_ip }}' + register: eip_info + + - assert: + that: + - instance_eip is not changed + - eip_info.addresses[0].allocation_id is defined + - eip_info.addresses[0].instance_id == '{{ create_ec2_instance_result.instance_ids[0] }}' + + # ------------------------------------------------------------------------------------------ + + - name: Detach EIP from EC2 instance, without enabling release on disassociation - check_mode + ec2_eip: + state: absent + device_id: '{{ create_ec2_instance_result.instance_ids[0] }}' + register: detach_eip + check_mode: yes + + - assert: + that: + - detach_eip is changed + + - name: Detach EIP from EC2 instance, without enabling release on disassociation + ec2_eip: + state: absent + device_id: '{{ create_ec2_instance_result.instance_ids[0] }}' + register: detach_eip + + - ec2_eip_info: + filters: + public-ip: '{{ instance_eip.public_ip }}' + register: eip_info + + - assert: + that: + - detach_eip.changed + - detach_eip.disassociated + - not detach_eip.released + - eip_info.addresses | length == 1 + + - name: Detach EIP from EC2 instance, without enabling release on disassociation (idempotence) - check_mode + ec2_eip: + state: absent + device_id: '{{ create_ec2_instance_result.instance_ids[0] }}' + register: detach_eip + check_mode: yes + + - assert: + that: + - detach_eip is not changed + + - name: Detach EIP from EC2 instance, without enabling release on disassociation (idempotence) + ec2_eip: + state: absent + device_id: '{{ create_ec2_instance_result.instance_ids[0] }}' + register: detach_eip + + - ec2_eip_info: + filters: + public-ip: '{{ instance_eip.public_ip }}' + register: eip_info + + - assert: + that: + - not detach_eip.changed + - not detach_eip.disassociated + - not detach_eip.released + - eip_info.addresses | length == 1 + + - name: Release EIP + ec2_eip: + state: absent + public_ip: '{{ instance_eip.public_ip }}' + + # ------------------------------------------------------------------------------------------ + + - name: Attach EIP to an EC2 instance with private Ip specified - check_mode + ec2_eip: + device_id: '{{ create_ec2_instance_result.instance_ids[0] }}' + private_ip_address: '{{ create_ec2_instance_result.instances[0].private_ip_address }}' + state: present + release_on_disassociation: yes + register: instance_eip + check_mode: yes + + - assert: + that: + - instance_eip is changed + + - name: Attach EIP to an EC2 instance with private Ip specified + ec2_eip: + device_id: '{{ create_ec2_instance_result.instance_ids[0] }}' + private_ip_address: '{{ create_ec2_instance_result.instances[0].private_ip_address }}' + state: present + release_on_disassociation: yes + register: instance_eip + + - ec2_eip_info: + filters: + public-ip: '{{ instance_eip.public_ip }}' + register: eip_info + + - assert: + that: + - instance_eip is changed + - eip_info.addresses[0].allocation_id is defined + - eip_info.addresses[0].instance_id == '{{ create_ec2_instance_result.instance_ids[0] }}' + + - name: Attach EIP to an EC2 instance with private Ip specified (idempotence) - check_mode + ec2_eip: + device_id: '{{ create_ec2_instance_result.instance_ids[0] }}' + private_ip_address: '{{ create_ec2_instance_result.instances[0].private_ip_address }}' + state: present + release_on_disassociation: yes + register: instance_eip + check_mode: yes + + - assert: + that: + - instance_eip is not changed + + - name: Attach EIP to an EC2 instance with private Ip specified (idempotence) + ec2_eip: + device_id: '{{ create_ec2_instance_result.instance_ids[0] }}' + private_ip_address: '{{ create_ec2_instance_result.instances[0].private_ip_address }}' + state: present + release_on_disassociation: yes + register: instance_eip + + - ec2_eip_info: + filters: + public-ip: '{{ instance_eip.public_ip }}' + register: eip_info + + - assert: + that: + - instance_eip is not changed + - eip_info.addresses[0].allocation_id is defined + - eip_info.addresses[0].instance_id == '{{ create_ec2_instance_result.instance_ids[0] }}' + + # ------------------------------------------------------------------------------------------ + + - name: Detach EIP from EC2 instance, enabling release on disassociation - check_mode + ec2_eip: + state: absent + device_id: '{{ create_ec2_instance_result.instance_ids[0] }}' + release_on_disassociation: yes + register: disassociate_eip + check_mode: yes + + - assert: + that: + - disassociate_eip is changed + + - name: Detach EIP from EC2 instance, enabling release on disassociation + ec2_eip: + state: absent + device_id: '{{ create_ec2_instance_result.instance_ids[0] }}' + release_on_disassociation: yes + register: disassociate_eip + + - ec2_eip_info: + filters: + public-ip: '{{ instance_eip.public_ip }}' + register: eip_info + + - assert: + that: + - disassociate_eip.changed + - disassociate_eip.disassociated + - disassociate_eip.released + - eip_info.addresses | length == 0 + + - name: Detach EIP from EC2 instance, enabling release on disassociation (idempotence) - check_mode + ec2_eip: + state: absent + device_id: '{{ create_ec2_instance_result.instance_ids[0] }}' + release_on_disassociation: yes + register: disassociate_eip + check_mode: yes + + - assert: + that: + - disassociate_eip is not changed + + - name: Detach EIP from EC2 instance, enabling release on disassociation (idempotence) + ec2_eip: + state: absent + device_id: '{{ create_ec2_instance_result.instance_ids[0] }}' + release_on_disassociation: yes + register: disassociate_eip + + - ec2_eip_info: + filters: + public-ip: '{{ instance_eip.public_ip }}' + register: eip_info + + - assert: + that: + - not disassociate_eip.changed + - not disassociate_eip.disassociated + - not disassociate_eip.released + - eip_info.addresses | length == 0 + + # ------------------------------------------------------------------------------------------ + + - name: Allocate a new eip + ec2_eip: + state: present + register: eip + + - name: Tag EIP - check_mode + ec2_eip: + state: present + public_ip: '{{ eip.public_ip }}' + tags: + AnsibleEIPTestPrefix: '{{ resource_prefix }}' + another_tag: 'another Value {{ resource_prefix }}' + register: tag_eip + check_mode: yes + + - assert: + that: + - tag_eip is changed + + - name: Tag EIP + ec2_eip: + state: present + public_ip: '{{ eip.public_ip }}' + tags: + AnsibleEIPTestPrefix: '{{ resource_prefix }}' + another_tag: 'another Value {{ resource_prefix }}' + register: tag_eip + + - ec2_eip_info: + filters: + public-ip: '{{ eip.public_ip }}' + register: eip_info + + - assert: + that: + - tag_eip is changed + - '"AnsibleEIPTestPrefix" in eip_info.addresses[0].tags' + - '"another_tag" in eip_info.addresses[0].tags' + - eip_info.addresses[0].tags['AnsibleEIPTestPrefix'] == resource_prefix + - eip_info.addresses[0].tags['another_tag'] == 'another Value ' + resource_prefix + - ( eip_info_start.addresses | length ) + 1 == ( eip_info.addresses | length ) + + - name: Tag EIP (idempotence) - check_mode + ec2_eip: + state: present + public_ip: '{{ eip.public_ip }}' + tags: + AnsibleEIPTestPrefix: '{{ resource_prefix }}' + another_tag: 'another Value {{ resource_prefix }}' + register: tag_eip + check_mode: yes + + - assert: + that: + - tag_eip is not changed + + - name: Tag EIP (idempotence) + ec2_eip: + state: present + public_ip: '{{ eip.public_ip }}' + tags: + AnsibleEIPTestPrefix: '{{ resource_prefix }}' + another_tag: 'another Value {{ resource_prefix }}' + register: tag_eip + + - ec2_eip_info: + filters: + public-ip: '{{ eip.public_ip }}' + register: eip_info + + - assert: + that: + - tag_eip is not changed + - '"AnsibleEIPTestPrefix" in eip_info.addresses[0].tags' + - '"another_tag" in eip_info.addresses[0].tags' + - eip_info.addresses[0].tags['AnsibleEIPTestPrefix'] == resource_prefix + - eip_info.addresses[0].tags['another_tag'] == 'another Value ' + resource_prefix + - ( eip_info_start.addresses | length ) + 1 == ( eip_info.addresses | length ) + + # ------------------------------------------------------------------------------------------ + + - name: Add another Tag - check_mode + ec2_eip: + state: present + public_ip: '{{ eip.public_ip }}' + tags: + "third tag": 'Third tag - {{ resource_prefix }}' + purge_tags: False + register: tag_eip + check_mode: yes + + - assert: + that: + - tag_eip is changed + + - name: Add another Tag + ec2_eip: + state: present + public_ip: '{{ eip.public_ip }}' + tags: + "third tag": 'Third tag - {{ resource_prefix }}' + purge_tags: False + register: tag_eip + + - ec2_eip_info: + filters: + public-ip: '{{ eip.public_ip }}' + register: eip_info + + - assert: + that: + - tag_eip is changed + - '"AnsibleEIPTestPrefix" in eip_info.addresses[0].tags' + - '"another_tag" in eip_info.addresses[0].tags' + - '"third tag" in eip_info.addresses[0].tags' + - eip_info.addresses[0].tags['AnsibleEIPTestPrefix'] == resource_prefix + - eip_info.addresses[0].tags['another_tag'] == 'another Value ' + resource_prefix + - eip_info.addresses[0].tags['third tag'] == 'Third tag - ' + resource_prefix + - ( eip_info_start.addresses | length ) + 1 == ( eip_info.addresses | length ) + + - name: Add another Tag (idempotence) - check_mode + ec2_eip: + state: present + public_ip: '{{ eip.public_ip }}' + tags: + "third tag": 'Third tag - {{ resource_prefix }}' + purge_tags: False + register: tag_eip + check_mode: yes + + - assert: + that: + - tag_eip is not changed + + - name: Add another Tag (idempotence) + ec2_eip: + state: present + public_ip: '{{ eip.public_ip }}' + tags: + "third tag": 'Third tag - {{ resource_prefix }}' + purge_tags: False + register: tag_eip + + - ec2_eip_info: + filters: + public-ip: '{{ eip.public_ip }}' + register: eip_info + + - assert: + that: + - tag_eip is not changed + - '"AnsibleEIPTestPrefix" in eip_info.addresses[0].tags' + - '"another_tag" in eip_info.addresses[0].tags' + - '"third tag" in eip_info.addresses[0].tags' + - eip_info.addresses[0].tags['AnsibleEIPTestPrefix'] == resource_prefix + - eip_info.addresses[0].tags['another_tag'] == 'another Value ' + resource_prefix + - eip_info.addresses[0].tags['third tag'] == 'Third tag - ' + resource_prefix + + # ------------------------------------------------------------------------------------------ + + - name: Purge tags - check_mode + ec2_eip: + state: present + public_ip: '{{ eip.public_ip }}' + tags: + "third tag": 'Third tag - {{ resource_prefix }}' + purge_tags: True + register: tag_eip + check_mode: yes + + - assert: + that: + - tag_eip is changed + + - name: Purge tags + ec2_eip: + state: present + public_ip: '{{ eip.public_ip }}' + tags: + "third tag": 'Third tag - {{ resource_prefix }}' + purge_tags: True + register: tag_eip + + - ec2_eip_info: + filters: + public-ip: '{{ eip.public_ip }}' + register: eip_info + + - assert: + that: + - tag_eip is changed + - '"AnsibleEIPTestPrefix" not in eip_info.addresses[0].tags' + - '"another_tag" not in eip_info.addresses[0].tags' + - '"third tag" in eip_info.addresses[0].tags' + - eip_info.addresses[0].tags['third tag'] == 'Third tag - ' + resource_prefix + + - name: Purge tags (idempotence) - check_mode + ec2_eip: + state: present + public_ip: '{{ eip.public_ip }}' + tags: + "third tag": 'Third tag - {{ resource_prefix }}' + purge_tags: True + register: tag_eip + check_mode: yes + + - assert: + that: + - tag_eip is not changed + + - name: Purge tags (idempotence) + ec2_eip: + state: present + public_ip: '{{ eip.public_ip }}' + tags: + "third tag": 'Third tag - {{ resource_prefix }}' + purge_tags: True + register: tag_eip + + - ec2_eip_info: + filters: + public-ip: '{{ eip.public_ip }}' + register: eip_info + + - assert: + that: + - tag_eip is not changed + - '"AnsibleEIPTestPrefix" not in eip_info.addresses[0].tags' + - '"another_tag" not in eip_info.addresses[0].tags' + - '"third tag" in eip_info.addresses[0].tags' + - eip_info.addresses[0].tags['third tag'] == 'Third tag - ' + resource_prefix + + # ----- Cleanup ------------------------------------------------------------------------------ - - name: allocate a new eip - ec2_eip: - state: present - register: eip - - ec2_eip_info: null - register: eip_info - - assert: - that: - - eip is defined - - eip is changed - - eip.public_ip is defined and ( eip.public_ip | ansible.utils.ipaddr ) - - eip.allocation_id is defined and eip.allocation_id.startswith("eipalloc-") - - ( eip_info_start.addresses | length ) + 1 == ( eip_info.addresses | length ) - - ############################################################################################# - - - name: Tag EIP - ec2_eip: - state: present - public_ip: '{{ eip.public_ip }}' - tags: - AnsibleEIPTestPrefix: '{{ resource_prefix }}' - another_tag: 'another Value {{ resource_prefix }}' - register: tag_eip - - ec2_eip_info: null - register: eip_info - - assert: - that: - - tag_eip is defined - - tag_eip is changed - - '"AnsibleEIPTestPrefix" in eip_info.addresses[0].tags' - - '"another_tag" in eip_info.addresses[0].tags' - - eip_info.addresses[0].tags['AnsibleEIPTestPrefix'] == resource_prefix - - eip_info.addresses[0].tags['another_tag'] == 'another Value ' + resource_prefix - - - name: Tag EIP - ec2_eip: - state: present - public_ip: '{{ eip.public_ip }}' - tags: - AnsibleEIPTestPrefix: '{{ resource_prefix }}' - another_tag: 'another Value {{ resource_prefix }}' - register: tag_eip - - ec2_eip_info: null - register: eip_info - - assert: - that: - - tag_eip is defined - - tag_eip is not changed - - '"AnsibleEIPTestPrefix" in eip_info.addresses[0].tags' - - '"another_tag" in eip_info.addresses[0].tags' - - eip_info.addresses[0].tags['AnsibleEIPTestPrefix'] == resource_prefix - - eip_info.addresses[0].tags['another_tag'] == 'another Value ' + resource_prefix - - - name: Add another Tag - ec2_eip: - state: present - public_ip: '{{ eip.public_ip }}' - tags: - "third tag": 'Third tag - {{ resource_prefix }}' - purge_tags: False - register: tag_eip - - ec2_eip_info: null - register: eip_info - - assert: - that: - - tag_eip is defined - - tag_eip is changed - - '"AnsibleEIPTestPrefix" in eip_info.addresses[0].tags' - - '"another_tag" in eip_info.addresses[0].tags' - - '"third tag" in eip_info.addresses[0].tags' - - eip_info.addresses[0].tags['AnsibleEIPTestPrefix'] == resource_prefix - - eip_info.addresses[0].tags['another_tag'] == 'another Value ' + resource_prefix - - eip_info.addresses[0].tags['third tag'] == 'Third tag - ' + resource_prefix - - - name: Add another Tag - ec2_eip: - state: present - public_ip: '{{ eip.public_ip }}' - tags: - "third tag": 'Third tag - {{ resource_prefix }}' - purge_tags: False - register: tag_eip - - ec2_eip_info: null - register: eip_info - - assert: - that: - - tag_eip is defined - - tag_eip is not changed - - '"AnsibleEIPTestPrefix" in eip_info.addresses[0].tags' - - '"another_tag" in eip_info.addresses[0].tags' - - '"third tag" in eip_info.addresses[0].tags' - - eip_info.addresses[0].tags['AnsibleEIPTestPrefix'] == resource_prefix - - eip_info.addresses[0].tags['another_tag'] == 'another Value ' + resource_prefix - - eip_info.addresses[0].tags['third tag'] == 'Third tag - ' + resource_prefix - - - name: Purge most tags - ec2_eip: - state: present - public_ip: '{{ eip.public_ip }}' - tags: - "third tag": 'Third tag - {{ resource_prefix }}' - purge_tags: True - register: tag_eip - - ec2_eip_info: null - register: eip_info - - assert: - that: - - tag_eip is defined - - tag_eip is changed - - '"AnsibleEIPTestPrefix" not in eip_info.addresses[0].tags' - - '"another_tag" not in eip_info.addresses[0].tags' - - '"third tag" in eip_info.addresses[0].tags' - - eip_info.addresses[0].tags['third tag'] == 'Third tag - ' + resource_prefix - - - name: Purge most tags - ec2_eip: - state: present - public_ip: '{{ eip.public_ip }}' - tags: - "third tag": 'Third tag - {{ resource_prefix }}' - purge_tags: True - register: tag_eip - - ec2_eip_info: null - register: eip_info - - assert: - that: - - tag_eip is defined - - tag_eip is not changed - - '"AnsibleEIPTestPrefix" not in eip_info.addresses[0].tags' - - '"another_tag" not in eip_info.addresses[0].tags' - - '"third tag" in eip_info.addresses[0].tags' - - eip_info.addresses[0].tags['third tag'] == 'Third tag - ' + resource_prefix - - ############################################################################################# - - - name: Release eip - ec2_eip: - state: absent - public_ip: '{{ eip.public_ip }}' - register: eip_release - - ec2_eip_info: null - register: eip_info - - assert: - that: - - eip_release is defined - - eip_release is changed - - ( eip_info_start.addresses | length ) == ( eip_info.addresses | length ) - - name: Rerelease eip (no change) - ec2_eip: - state: absent - public_ip: '{{ eip.public_ip }}' - register: eip_release - - ec2_eip_info: null - register: eip_info - - assert: - that: - - eip_release is defined - - eip_release is not changed - - ( eip_info_start.addresses | length ) == ( eip_info.addresses | length ) - - name: Cleanup VPC - ec2_vpc_net: - state: absent - name: '{{ resource_prefix }}-vpc' - cidr_block: '{{ vpc_cidr }}' - - - name: Create an EIP outside a VPC - ec2_eip: - state: present - in_vpc: '{{ omit }}' - register: unbound_eip - - assert: - that: - - unbound_eip is successful - - unbound_eip is changed - - name: Release EIP - ec2_eip: - state: absent - public_ip: '{{ unbound_eip.public_ip }}' - register: release_unbound_eip - - assert: - that: - - release_unbound_eip is successful - - release_unbound_eip is changed - # ===================================================== always: - - name: Cleanup instance (by id) - ec2_instance: - instance_ids: '{{ create_ec2_instance_result.instance_ids }}' - state: absent - wait: true - ignore_errors: true - - name: Cleanup instance (by name) - ec2_instance: - name: '{{ resource_prefix }}-instance' - state: absent - wait: true - ignore_errors: true - - name: Cleanup ENI A - ec2_eni: - state: absent - eni_id: '{{ eni_create_a.interface.id }}' - ignore_errors: true - - name: Cleanup ENI B - ec2_eni: - state: absent - eni_id: '{{ eni_create_b.interface.id }}' - ignore_errors: true - - name: Cleanup instance eip - ec2_eip: - state: absent - public_ip: '{{ instance_eip.public_ip }}' - retries: 5 - delay: 5 - until: eip_cleanup is successful - ignore_errors: true - - name: Cleanup IGW - ec2_vpc_igw: - state: absent - vpc_id: '{{ vpc_result.vpc.id }}' - register: vpc_igw - ignore_errors: true - - name: Cleanup security group - ec2_group: - state: absent - name: '{{ resource_prefix }}-sg' - ignore_errors: true - - name: Cleanup Subnet - ec2_vpc_subnet: - state: absent - cidr: '{{ subnet_cidr }}' - vpc_id: '{{ vpc_result.vpc.id }}' - ignore_errors: true - - name: Cleanup eip - ec2_eip: - state: absent - public_ip: '{{ eip.public_ip }}' - when: eip is changed - ignore_errors: true - - name: Cleanup reallocate_eip - ec2_eip: - state: absent - public_ip: '{{ reallocate_eip.public_ip }}' - when: reallocate_eip is changed - ignore_errors: true - - name: Cleanup backend_eip - ec2_eip: - state: absent - public_ip: '{{ backend_eip.public_ip }}' - when: backend_eip is changed - ignore_errors: true - - name: Cleanup no_tagged_eip - ec2_eip: - state: absent - public_ip: '{{ no_tagged_eip.public_ip }}' - when: no_tagged_eip is changed - ignore_errors: true - - name: Cleanup unbound_eip - ec2_eip: - state: absent - public_ip: '{{ unbound_eip.public_ip }}' - when: unbound_eip is changed - ignore_errors: true - - name: Cleanup VPC - ec2_vpc_net: - state: absent - name: '{{ resource_prefix }}-vpc' - cidr_block: '{{ vpc_cidr }}' - ignore_errors: true + + - name: Cleanup instance (by id) + ec2_instance: + instance_ids: '{{ create_ec2_instance_result.instance_ids }}' + state: absent + wait: true + ignore_errors: true + + - name: Cleanup instance (by name) + ec2_instance: + name: '{{ resource_prefix }}-instance' + state: absent + wait: true + ignore_errors: true + + - name: Cleanup ENI A + ec2_eni: + state: absent + eni_id: '{{ eni_create_a.interface.id }}' + ignore_errors: true + + - name: Cleanup ENI B + ec2_eni: + state: absent + eni_id: '{{ eni_create_b.interface.id }}' + ignore_errors: true + + - name: Cleanup instance eip + ec2_eip: + state: absent + public_ip: '{{ instance_eip.public_ip }}' + retries: 5 + delay: 5 + until: eip_cleanup is successful + ignore_errors: true + + - name: Cleanup IGW + ec2_vpc_igw: + state: absent + vpc_id: '{{ vpc_result.vpc.id }}' + register: vpc_igw + ignore_errors: true + + - name: Cleanup security group + ec2_group: + state: absent + name: '{{ resource_prefix }}-sg' + ignore_errors: true + + - name: Cleanup Subnet + ec2_vpc_subnet: + state: absent + cidr: '{{ subnet_cidr }}' + vpc_id: '{{ vpc_result.vpc.id }}' + ignore_errors: true + + - name: Cleanup eip + ec2_eip: + state: absent + public_ip: '{{ eip.public_ip }}' + ignore_errors: true + + - name: Cleanup reallocate_eip + ec2_eip: + state: absent + public_ip: '{{ reallocate_eip.public_ip }}' + ignore_errors: true + + - name: Cleanup backend_eip + ec2_eip: + state: absent + public_ip: '{{ backend_eip.public_ip }}' + ignore_errors: true + + - name: Cleanup no_tagged_eip + ec2_eip: + state: absent + public_ip: '{{ no_tagged_eip.public_ip }}' + ignore_errors: true + + - name: Cleanup VPC + ec2_vpc_net: + state: absent + name: '{{ resource_prefix }}-vpc' + cidr_block: '{{ vpc_cidr }}' + ignore_errors: true
Unstable integration tests ec2_eip Test is susceptible to race conditions when running concurrently in the same Region https://app.shippable.com/github/ansible-collections/community.aws/runs/438/27/tests https://app.shippable.com/github/ansible-collections/community.aws/runs/438/23/tests https://app.shippable.com/github/ansible-collections/community.aws/runs/438/24/tests https://app.shippable.com/github/ansible-collections/community.aws/runs/439/27/tests https://app.shippable.com/github/ansible-collections/community.aws/runs/440/23/tests https://app.shippable.com/github/ansible-collections/community.aws/runs/440/26/tests
Files identified in the description: None If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> @tremble: Greetings! Thanks for taking the time to open this issue. In order for the community to handle your issue effectively, we need a bit more information. Here are the items we could not find in your description: - issue type - ansible version - component name Please set the description of this issue with this template: https://raw.githubusercontent.com/ansible/ansible/devel/.github/ISSUE_TEMPLATE/bug_report.md [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: issue_missing_data ---> @tremble @jillr @alinabuzachis what's a good way to validate that this is fixed? I updated the integration tests and am not running into this issue, but unsure if it's actually fixed or not > @tremble @jillr @alinabuzachis what's a good way to validate that this is fixed? I updated the integration tests and am not running into this issue, but unsure if it's actually fixed or not I would probably go through the CI logs tremble listed there and check if that issues are solved or still happen with your changes. Thanks! I didn't run into any of those failures so I'll go ahead and link it
2022-02-22T10:33:36
ansible-collections/community.aws
949
ansible-collections__community.aws-949
[ "296" ]
f09467f4e0bddc12258f128b4176ffc05b64b1eb
diff --git a/plugins/modules/cloudfront_distribution.py b/plugins/modules/cloudfront_distribution.py --- a/plugins/modules/cloudfront_distribution.py +++ b/plugins/modules/cloudfront_distribution.py @@ -1378,7 +1378,7 @@ from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule from ansible_collections.amazon.aws.plugins.module_utils.cloudfront_facts import CloudFrontFactsServiceManager from ansible.module_utils.common.dict_transformations import recursive_diff -from ansible_collections.amazon.aws.plugins.module_utils.ec2 import compare_aws_tags, ansible_dict_to_boto3_tag_list, boto3_tag_list_to_ansible_dict +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AWSRetry, compare_aws_tags, ansible_dict_to_boto3_tag_list, boto3_tag_list_to_ansible_dict from ansible_collections.amazon.aws.plugins.module_utils.ec2 import camel_dict_to_snake_dict, snake_dict_to_camel_dict import datetime @@ -1433,7 +1433,7 @@ def ansible_list_to_cloudfront_list(list_items=None, include_quantity=True): def create_distribution(client, module, config, tags): try: if not tags: - return client.create_distribution(DistributionConfig=config)['Distribution'] + return client.create_distribution(aws_retry=True, DistributionConfig=config)['Distribution'] else: distribution_config_with_tags = { 'DistributionConfig': config, @@ -1441,42 +1441,42 @@ def create_distribution(client, module, config, tags): 'Items': tags } } - return client.create_distribution_with_tags(DistributionConfigWithTags=distribution_config_with_tags)['Distribution'] + return client.create_distribution_with_tags(aws_retry=True, DistributionConfigWithTags=distribution_config_with_tags)['Distribution'] except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: module.fail_json_aws(e, msg="Error creating distribution") def delete_distribution(client, module, distribution): try: - return client.delete_distribution(Id=distribution['Distribution']['Id'], IfMatch=distribution['ETag']) + return client.delete_distribution(aws_retry=True, Id=distribution['Distribution']['Id'], IfMatch=distribution['ETag']) except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: module.fail_json_aws(e, msg="Error deleting distribution %s" % to_native(distribution['Distribution'])) def update_distribution(client, module, config, distribution_id, e_tag): try: - return client.update_distribution(DistributionConfig=config, Id=distribution_id, IfMatch=e_tag)['Distribution'] + return client.update_distribution(aws_retry=True, DistributionConfig=config, Id=distribution_id, IfMatch=e_tag)['Distribution'] except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: module.fail_json_aws(e, msg="Error updating distribution to %s" % to_native(config)) def tag_resource(client, module, arn, tags): try: - return client.tag_resource(Resource=arn, Tags=dict(Items=tags)) + return client.tag_resource(aws_retry=True, Resource=arn, Tags=dict(Items=tags)) except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: module.fail_json_aws(e, msg="Error tagging resource") def untag_resource(client, module, arn, tag_keys): try: - return client.untag_resource(Resource=arn, TagKeys=dict(Items=tag_keys)) + return client.untag_resource(aws_retry=True, Resource=arn, TagKeys=dict(Items=tag_keys)) except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: module.fail_json_aws(e, msg="Error untagging resource") def list_tags_for_resource(client, module, arn): try: - response = client.list_tags_for_resource(Resource=arn) + response = client.list_tags_for_resource(aws_retry=True, Resource=arn) return boto3_tag_list_to_ansible_dict(response.get('Tags').get('Items')) except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: module.fail_json_aws(e, msg="Error listing tags for resource") @@ -2152,7 +2152,7 @@ def main(): ] ) - client = module.client('cloudfront') + client = module.client('cloudfront', retry_decorator=AWSRetry.jittered_backoff()) validation_mgr = CloudFrontValidationManager(module)
diff --git a/tests/integration/targets/cloudfront_distribution/tasks/main.yml b/tests/integration/targets/cloudfront_distribution/tasks/main.yml --- a/tests/integration/targets/cloudfront_distribution/tasks/main.yml +++ b/tests/integration/targets/cloudfront_distribution/tasks/main.yml @@ -240,6 +240,17 @@ state: present register: cf_update_default_root_object + - name: update default_root_object of existing distribution with retries + cloudfront_distribution: + distribution_id: "{{ distribution_id }}" + origins: + - domain_name: "{{ resource_prefix }}2.example.com" + default_root_object: index.php + state: present + retries: 3 + delay: 3 + register: cf_update_default_root_object + - name: ensure origin was updated assert: that:
Cloudfront - Update Distribution - max retries exceeded I'm using your module to update the path of an origin for a cloudfront distribution. It was working fine but now I get this error: ``` An exception occurred during task execution. To see the full traceback, use -vvv. The error was: botocore.exceptions.ClientError: An error occurred (Throttling) when calling the UpdateDistribution operation (reached max retries: 4): Rate exceeded fatal: [10.63.56.237]: FAILED! => {"boto3_version": "1.16.13", "botocore_version": "1.19.13", "changed": false, "error": {"code": "Throttling", "message": "Rate exceeded" ``` I contacted AWS Support but the issue can not be fixed increasing any limit, apparently we are calling UpdateDistribution 2 or 3 times in less than one minute. In my side I only do one call, like this: ``` - name: "Update onorigin_path from cloudfront distribution" community.aws.cloudfront_distribution: state: present distribution_id: "{{ cdn_cloudfront }}" origins: - id: "{{ cdn_cloudfront_origin_id }}" domain_name: "{{ cdn_cloudfront_origin_domain }}" origin_path: "/{{ deploy_helper.new_release }}" default_cache_behavior: target_origin_id: "{{ cdn_cloudfront_origin_id }}" ``` Any idea of how can be fixed? ##### ISSUE TYPE - Bug Report ##### ANSIBLE VERSION 2.10 ##### COMPONENT NAME cloudfront_distribution
Programmatically the way around this is to add the AWSRetry decorator to the 'client' calls: An example of this can be found in: https://github.com/ansible-collections/amazon.aws/pull/103/files#diff-17496fe80d361b6e7fa1af8cbdefaa96e1003031e89f6b4767fb73171f822c83 (this example calls the variable 'connection' rather than 'client' but it's the same sort of boto3 object) The reason there are multiple update calls is that boto3 (the library used to connect to AWS) has a very simplistic retry model built in, however with busy AWS accounts it's often insufficient. Thanks Mark, that's very helpful 👍 That decorator can be added in my yaml file or I need to modify the python library? You need to modify the ansible python module (plugins/modules/cloudfront_distribution.py). If you're able to get it working and are able to open a pull request I should be able to review and get it merged. Hi Mark, I did the changes here https://github.com/ansible-collections/community.aws/pull/297 the retry works because now it takes much longer to throw the error but I still get the same error from AWS. Any idea what can be happening? It's tough to say, one option is to increase the initial delay (`delay=3` in your PR currently), it's also worth making sure that it's more than just the update call that you retry on. The trouble is that most of the time when you're hitting this problem it's because you've got a very busy account. To reduce issues like this we (${DAYJOB}) have been spreading our services across multiple accounts (See also AWS Organisations) and using SAML or Cross-Account trusts for authentication. This has the added benefit of helping to segregate some of the access controls. Hi Mark, I spoke with AWS support and share screen and look at logs with them. Even implementing jittered_backoff or exponential_backoff still can see 2 requests at the same time in less than one second. Then those retries have the gaps in between as the backoff works fine. From our side we will execute "update-distribution" using the aws cli from command shell. I don't know if still useful the opened PR or should we see why there are always 2 calls in less than 2 seconds. Thank you very much In my opinion PRs going through and adding the retries are valuable, if you're willing to add the extra `aws_retry=True` parameters I'd be happy to get them merged... sure! I will, I just need to put few things together before ;) @fnavarrodev: Greetings! Thanks for taking the time to open this issue. In order for the community to handle your issue effectively, we need a bit more information. Here are the items we could not find in your description: - ansible version - component name Please set the description of this issue with this template: https://raw.githubusercontent.com/ansible/ansible/devel/.github/ISSUE_TEMPLATE/bug_report.md [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: issue_missing_data ---> cc @jillr @s-hertel @willthames @wilvk @wimnat [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> ##### COMPONENT NAME community.aws.cloudfront_distribution ##### ANSIBLE VERSION ``` ansible 2.9.15 ```
2022-02-23T20:35:24
ansible-collections/community.aws
950
ansible-collections__community.aws-950
[ "296" ]
a54d252d95b606bf1fac1a048b99959071f7ff23
diff --git a/plugins/modules/cloudfront_distribution.py b/plugins/modules/cloudfront_distribution.py --- a/plugins/modules/cloudfront_distribution.py +++ b/plugins/modules/cloudfront_distribution.py @@ -1378,7 +1378,7 @@ from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule from ansible_collections.amazon.aws.plugins.module_utils.cloudfront_facts import CloudFrontFactsServiceManager from ansible.module_utils.common.dict_transformations import recursive_diff -from ansible_collections.amazon.aws.plugins.module_utils.ec2 import compare_aws_tags, ansible_dict_to_boto3_tag_list, boto3_tag_list_to_ansible_dict +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AWSRetry, compare_aws_tags, ansible_dict_to_boto3_tag_list, boto3_tag_list_to_ansible_dict from ansible_collections.amazon.aws.plugins.module_utils.ec2 import camel_dict_to_snake_dict, snake_dict_to_camel_dict import datetime @@ -1433,7 +1433,7 @@ def ansible_list_to_cloudfront_list(list_items=None, include_quantity=True): def create_distribution(client, module, config, tags): try: if not tags: - return client.create_distribution(DistributionConfig=config)['Distribution'] + return client.create_distribution(aws_retry=True, DistributionConfig=config)['Distribution'] else: distribution_config_with_tags = { 'DistributionConfig': config, @@ -1441,42 +1441,42 @@ def create_distribution(client, module, config, tags): 'Items': tags } } - return client.create_distribution_with_tags(DistributionConfigWithTags=distribution_config_with_tags)['Distribution'] + return client.create_distribution_with_tags(aws_retry=True, DistributionConfigWithTags=distribution_config_with_tags)['Distribution'] except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: module.fail_json_aws(e, msg="Error creating distribution") def delete_distribution(client, module, distribution): try: - return client.delete_distribution(Id=distribution['Distribution']['Id'], IfMatch=distribution['ETag']) + return client.delete_distribution(aws_retry=True, Id=distribution['Distribution']['Id'], IfMatch=distribution['ETag']) except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: module.fail_json_aws(e, msg="Error deleting distribution %s" % to_native(distribution['Distribution'])) def update_distribution(client, module, config, distribution_id, e_tag): try: - return client.update_distribution(DistributionConfig=config, Id=distribution_id, IfMatch=e_tag)['Distribution'] + return client.update_distribution(aws_retry=True, DistributionConfig=config, Id=distribution_id, IfMatch=e_tag)['Distribution'] except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: module.fail_json_aws(e, msg="Error updating distribution to %s" % to_native(config)) def tag_resource(client, module, arn, tags): try: - return client.tag_resource(Resource=arn, Tags=dict(Items=tags)) + return client.tag_resource(aws_retry=True, Resource=arn, Tags=dict(Items=tags)) except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: module.fail_json_aws(e, msg="Error tagging resource") def untag_resource(client, module, arn, tag_keys): try: - return client.untag_resource(Resource=arn, TagKeys=dict(Items=tag_keys)) + return client.untag_resource(aws_retry=True, Resource=arn, TagKeys=dict(Items=tag_keys)) except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: module.fail_json_aws(e, msg="Error untagging resource") def list_tags_for_resource(client, module, arn): try: - response = client.list_tags_for_resource(Resource=arn) + response = client.list_tags_for_resource(aws_retry=True, Resource=arn) return boto3_tag_list_to_ansible_dict(response.get('Tags').get('Items')) except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: module.fail_json_aws(e, msg="Error listing tags for resource") @@ -2152,7 +2152,7 @@ def main(): ] ) - client = module.client('cloudfront') + client = module.client('cloudfront', retry_decorator=AWSRetry.jittered_backoff()) validation_mgr = CloudFrontValidationManager(module)
diff --git a/tests/integration/targets/cloudfront_distribution/tasks/main.yml b/tests/integration/targets/cloudfront_distribution/tasks/main.yml --- a/tests/integration/targets/cloudfront_distribution/tasks/main.yml +++ b/tests/integration/targets/cloudfront_distribution/tasks/main.yml @@ -240,6 +240,17 @@ state: present register: cf_update_default_root_object + - name: update default_root_object of existing distribution with retries + cloudfront_distribution: + distribution_id: "{{ distribution_id }}" + origins: + - domain_name: "{{ resource_prefix }}2.example.com" + default_root_object: index.php + state: present + retries: 3 + delay: 3 + register: cf_update_default_root_object + - name: ensure origin was updated assert: that:
Cloudfront - Update Distribution - max retries exceeded I'm using your module to update the path of an origin for a cloudfront distribution. It was working fine but now I get this error: ``` An exception occurred during task execution. To see the full traceback, use -vvv. The error was: botocore.exceptions.ClientError: An error occurred (Throttling) when calling the UpdateDistribution operation (reached max retries: 4): Rate exceeded fatal: [10.63.56.237]: FAILED! => {"boto3_version": "1.16.13", "botocore_version": "1.19.13", "changed": false, "error": {"code": "Throttling", "message": "Rate exceeded" ``` I contacted AWS Support but the issue can not be fixed increasing any limit, apparently we are calling UpdateDistribution 2 or 3 times in less than one minute. In my side I only do one call, like this: ``` - name: "Update onorigin_path from cloudfront distribution" community.aws.cloudfront_distribution: state: present distribution_id: "{{ cdn_cloudfront }}" origins: - id: "{{ cdn_cloudfront_origin_id }}" domain_name: "{{ cdn_cloudfront_origin_domain }}" origin_path: "/{{ deploy_helper.new_release }}" default_cache_behavior: target_origin_id: "{{ cdn_cloudfront_origin_id }}" ``` Any idea of how can be fixed? ##### ISSUE TYPE - Bug Report ##### ANSIBLE VERSION 2.10 ##### COMPONENT NAME cloudfront_distribution
Programmatically the way around this is to add the AWSRetry decorator to the 'client' calls: An example of this can be found in: https://github.com/ansible-collections/amazon.aws/pull/103/files#diff-17496fe80d361b6e7fa1af8cbdefaa96e1003031e89f6b4767fb73171f822c83 (this example calls the variable 'connection' rather than 'client' but it's the same sort of boto3 object) The reason there are multiple update calls is that boto3 (the library used to connect to AWS) has a very simplistic retry model built in, however with busy AWS accounts it's often insufficient. Thanks Mark, that's very helpful 👍 That decorator can be added in my yaml file or I need to modify the python library? You need to modify the ansible python module (plugins/modules/cloudfront_distribution.py). If you're able to get it working and are able to open a pull request I should be able to review and get it merged. Hi Mark, I did the changes here https://github.com/ansible-collections/community.aws/pull/297 the retry works because now it takes much longer to throw the error but I still get the same error from AWS. Any idea what can be happening? It's tough to say, one option is to increase the initial delay (`delay=3` in your PR currently), it's also worth making sure that it's more than just the update call that you retry on. The trouble is that most of the time when you're hitting this problem it's because you've got a very busy account. To reduce issues like this we (${DAYJOB}) have been spreading our services across multiple accounts (See also AWS Organisations) and using SAML or Cross-Account trusts for authentication. This has the added benefit of helping to segregate some of the access controls. Hi Mark, I spoke with AWS support and share screen and look at logs with them. Even implementing jittered_backoff or exponential_backoff still can see 2 requests at the same time in less than one second. Then those retries have the gaps in between as the backoff works fine. From our side we will execute "update-distribution" using the aws cli from command shell. I don't know if still useful the opened PR or should we see why there are always 2 calls in less than 2 seconds. Thank you very much In my opinion PRs going through and adding the retries are valuable, if you're willing to add the extra `aws_retry=True` parameters I'd be happy to get them merged... sure! I will, I just need to put few things together before ;) @fnavarrodev: Greetings! Thanks for taking the time to open this issue. In order for the community to handle your issue effectively, we need a bit more information. Here are the items we could not find in your description: - ansible version - component name Please set the description of this issue with this template: https://raw.githubusercontent.com/ansible/ansible/devel/.github/ISSUE_TEMPLATE/bug_report.md [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: issue_missing_data ---> cc @jillr @s-hertel @willthames @wilvk @wimnat [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> ##### COMPONENT NAME community.aws.cloudfront_distribution ##### ANSIBLE VERSION ``` ansible 2.9.15 ```
2022-02-23T20:35:34
ansible-collections/community.aws
954
ansible-collections__community.aws-954
[ "877" ]
4baf9afd92cd08777ea70dba0dc0d39dd923168c
diff --git a/plugins/modules/cloudfront_distribution.py b/plugins/modules/cloudfront_distribution.py --- a/plugins/modules/cloudfront_distribution.py +++ b/plugins/modules/cloudfront_distribution.py @@ -200,6 +200,10 @@ - The ID of the origin that you want CloudFront to route requests to by default. type: str + response_headers_policy_id: + description: + - The ID of the header policy that CloudFront adds to responses that it sends to viewers. + type: str forwarded_values: description: - A dict that specifies how CloudFront handles query strings and cookies. @@ -317,6 +321,10 @@ - The ID of the origin that you want CloudFront to route requests to by default. type: str + response_headers_policy_id: + description: + - The ID of the header policy that CloudFront adds to responses that it sends to viewers. + type: str forwarded_values: description: - A dict that specifies how CloudFront handles query strings and cookies.
Add support for setting response header policy id in cache behavior ### Summary Add support for setting cache and origin request policy ids in the cache behaviors block when creating a distribution in cloudfront_distribution. ### Issue Type Feature Idea ### Component Name cloudfront_distribution ### Additional Information Currently we are unable to set response header policy ids in the cache behaviors section so that they are added to a cloudfront distribution. Example playbook code: cache_behaviors: - path_pattern: "*/" target_origin_id: "" field_level_encryption_id: "" response_headers_policy_id: "{{ response_headers_policy_id }}" Example python code: cache_behavior['response_headers_policy_id'] = cache_behavior.get('response_headers_policy_id', config.get('response_headers_policy_id')) cache_behavior['response_headers_policy_id'] = cache_behavior.get('response_headers_policy_id', config.get('origin_request_policy_id')) ### Code of Conduct - [X] I agree to follow the Ansible Code of Conduct
This works already :) ```yml - field_level_encryption_id: "" path_pattern: mbmbmbmbmbmbmbmbmbmbmbmbmb-test-wow viewer_protocol_policy: "redirect-to-https" max_ttl: 31536000 min_ttl: 0 default_ttl: 86400 smooth_streaming: no compress: yes target_origin_id: Custom-cdn.test.blaaaaaaaaa.de response_headers_policy_id: 60669652-455b-4ae9-85a4-c4c02393f86c trusted_signers: enabled: no allowed_methods: items: - GET - HEAD cached_methods: - GET - HEAD forwarded_values: query_string: true cookies: forward: all headers: - "Host" ``` The code supports maybe every element in the `cache_behaviour` item. It's just a lack of documentation. cc @jillr @s-hertel @tremble @wilvk [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify --->
2022-03-01T10:55:42
ansible-collections/community.aws
955
ansible-collections__community.aws-955
[ "877" ]
91cb879820ad3e37f4ec7995fff78c3b10417717
diff --git a/plugins/modules/cloudfront_distribution.py b/plugins/modules/cloudfront_distribution.py --- a/plugins/modules/cloudfront_distribution.py +++ b/plugins/modules/cloudfront_distribution.py @@ -200,6 +200,10 @@ - The ID of the origin that you want CloudFront to route requests to by default. type: str + response_headers_policy_id: + description: + - The ID of the header policy that CloudFront adds to responses that it sends to viewers. + type: str forwarded_values: description: - A dict that specifies how CloudFront handles query strings and cookies. @@ -317,6 +321,10 @@ - The ID of the origin that you want CloudFront to route requests to by default. type: str + response_headers_policy_id: + description: + - The ID of the header policy that CloudFront adds to responses that it sends to viewers. + type: str forwarded_values: description: - A dict that specifies how CloudFront handles query strings and cookies.
Add support for setting response header policy id in cache behavior ### Summary Add support for setting cache and origin request policy ids in the cache behaviors block when creating a distribution in cloudfront_distribution. ### Issue Type Feature Idea ### Component Name cloudfront_distribution ### Additional Information Currently we are unable to set response header policy ids in the cache behaviors section so that they are added to a cloudfront distribution. Example playbook code: cache_behaviors: - path_pattern: "*/" target_origin_id: "" field_level_encryption_id: "" response_headers_policy_id: "{{ response_headers_policy_id }}" Example python code: cache_behavior['response_headers_policy_id'] = cache_behavior.get('response_headers_policy_id', config.get('response_headers_policy_id')) cache_behavior['response_headers_policy_id'] = cache_behavior.get('response_headers_policy_id', config.get('origin_request_policy_id')) ### Code of Conduct - [X] I agree to follow the Ansible Code of Conduct
This works already :) ```yml - field_level_encryption_id: "" path_pattern: mbmbmbmbmbmbmbmbmbmbmbmbmb-test-wow viewer_protocol_policy: "redirect-to-https" max_ttl: 31536000 min_ttl: 0 default_ttl: 86400 smooth_streaming: no compress: yes target_origin_id: Custom-cdn.test.blaaaaaaaaa.de response_headers_policy_id: 60669652-455b-4ae9-85a4-c4c02393f86c trusted_signers: enabled: no allowed_methods: items: - GET - HEAD cached_methods: - GET - HEAD forwarded_values: query_string: true cookies: forward: all headers: - "Host" ``` The code supports maybe every element in the `cache_behaviour` item. It's just a lack of documentation. cc @jillr @s-hertel @tremble @wilvk [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify --->
2022-03-01T10:55:51
ansible-collections/community.aws
960
ansible-collections__community.aws-960
[ "481" ]
d649e372c993e65de2740e157f6e18c4d6f7201b
diff --git a/plugins/modules/ec2_asg.py b/plugins/modules/ec2_asg.py --- a/plugins/modules/ec2_asg.py +++ b/plugins/modules/ec2_asg.py @@ -220,6 +220,13 @@ - When I(propagate_at_launch) is true the tags will be propagated to the Instances created. type: list elements: dict + purge_tags: + description: + - If C(true), existing tags will be purged from the resource to match exactly what is defined by I(tags) parameter. + - If the I(tags) parameter is not set then tags will not be modified. + default: true + type: bool + version_added: 3.2.0 health_check_period: description: - Length of time in seconds after a new EC2 instance comes into service that Auto Scaling starts checking its health. @@ -645,6 +652,7 @@ from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AWSRetry from ansible_collections.amazon.aws.plugins.module_utils.ec2 import snake_dict_to_camel_dict from ansible_collections.amazon.aws.plugins.module_utils.ec2 import camel_dict_to_snake_dict +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import ansible_dict_to_boto3_filter_list ASG_ATTRIBUTES = ('AvailabilityZones', 'DefaultCooldown', 'DesiredCapacity', 'HealthCheckGracePeriod', 'HealthCheckType', 'LaunchConfigurationName', @@ -1097,6 +1105,7 @@ def create_autoscaling_group(connection): desired_capacity = module.params.get('desired_capacity') vpc_zone_identifier = module.params.get('vpc_zone_identifier') set_tags = module.params.get('tags') + purge_tags = module.params.get('purge_tags') health_check_period = module.params.get('health_check_period') health_check_type = module.params.get('health_check_type') default_cooldown = module.params.get('default_cooldown') @@ -1205,9 +1214,12 @@ def create_autoscaling_group(connection): changed = True # process tag changes + have_tags = as_group.get('Tags') + want_tags = asg_tags + if purge_tags and not want_tags and have_tags: + connection.delete_tags(Tags=list(have_tags)) + if len(set_tags) > 0: - have_tags = as_group.get('Tags') - want_tags = asg_tags if have_tags: have_tags.sort(key=lambda x: x["Key"]) if want_tags: @@ -1218,9 +1230,11 @@ def create_autoscaling_group(connection): for dead_tag in set(have_tag_keyvals).difference(want_tag_keyvals): changed = True - dead_tags.append(dict(ResourceId=as_group['AutoScalingGroupName'], - ResourceType='auto-scaling-group', Key=dead_tag)) + if purge_tags: + dead_tags.append(dict( + ResourceId=as_group['AutoScalingGroupName'], ResourceType='auto-scaling-group', Key=dead_tag)) have_tags = [have_tag for have_tag in have_tags if have_tag['Key'] != dead_tag] + if dead_tags: connection.delete_tags(Tags=dead_tags) @@ -1838,6 +1852,7 @@ def main(): wait_timeout=dict(type='int', default=300), state=dict(default='present', choices=['present', 'absent']), tags=dict(type='list', default=[], elements='dict'), + purge_tags=dict(type='bool', default=True), health_check_period=dict(type='int', default=300), health_check_type=dict(default='EC2', choices=['EC2', 'ELB']), default_cooldown=dict(type='int', default=300),
diff --git a/tests/integration/targets/ec2_asg/tasks/instance_detach.yml b/tests/integration/targets/ec2_asg/tasks/instance_detach.yml --- a/tests/integration/targets/ec2_asg/tasks/instance_detach.yml +++ b/tests/integration/targets/ec2_asg/tasks/instance_detach.yml @@ -83,7 +83,7 @@ - '{{ init_instance_2 }}' # pause to allow completion of instance replacement - - name: Pause for 1 minute + - name: Pause for 30 seconds pause: seconds: 30 @@ -137,7 +137,7 @@ - '{{ instance_replace_1 }}' - '{{ instance_replace_2 }}' - - name: Pause for 1 minute to allow completion of above task + - name: Pause for 30 seconds to allow completion of above task pause: seconds: 30 diff --git a/tests/integration/targets/ec2_asg/tasks/main.yml b/tests/integration/targets/ec2_asg/tasks/main.yml --- a/tests/integration/targets/ec2_asg/tasks/main.yml +++ b/tests/integration/targets/ec2_asg/tasks/main.yml @@ -97,6 +97,8 @@ cidr_ip: 0.0.0.0/0 register: sg + - include_tasks: tag_operations.yml + - include_tasks: instance_detach.yml - name: ensure launch configs exist @@ -136,62 +138,6 @@ that: - "output.viable_instances == 1" - - name: Tag asg - ec2_asg: - name: "{{ resource_prefix }}-asg" - tags: - - tag_a: 'value 1' - propagate_at_launch: no - - tag_b: 'value 2' - propagate_at_launch: yes - register: output - - - assert: - that: - - "output.tags | length == 2" - - output is changed - - - name: Re-Tag asg (different order) - ec2_asg: - name: "{{ resource_prefix }}-asg" - tags: - - tag_b: 'value 2' - propagate_at_launch: yes - - tag_a: 'value 1' - propagate_at_launch: no - register: output - - - assert: - that: - - "output.tags | length == 2" - - output is not changed - - - name: Re-Tag asg new tags - ec2_asg: - name: "{{ resource_prefix }}-asg" - tags: - - tag_c: 'value 3' - propagate_at_launch: no - register: output - - - assert: - that: - - "output.tags | length == 1" - - output is changed - - - name: Re-Tag asg update propagate_at_launch - ec2_asg: - name: "{{ resource_prefix }}-asg" - tags: - - tag_c: 'value 3' - propagate_at_launch: yes - register: output - - - assert: - that: - - "output.tags | length == 1" - - output is changed - - name: Enable metrics collection ec2_asg: name: "{{ resource_prefix }}-asg" diff --git a/tests/integration/targets/ec2_asg/tasks/tag_operations.yml b/tests/integration/targets/ec2_asg/tasks/tag_operations.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/ec2_asg/tasks/tag_operations.yml @@ -0,0 +1,352 @@ +- name: Running AutoScalingGroup Tag operations test + block: + #---------------------------------------------------------------------- + - name: create a launch configuration + ec2_lc: + name: "{{ resource_prefix }}-lc-tag-test" + image_id: "{{ ec2_ami_image }}" + region: "{{ aws_region }}" + instance_type: t2.micro + assign_public_ip: yes + register: create_lc + + - name: ensure that lc is created + assert: + that: + - create_lc is changed + - create_lc.failed is false + - '"autoscaling:CreateLaunchConfiguration" in create_lc.resource_actions' + + #---------------------------------------------------------------------- + - name: create a AutoScalingGroup to be used for tag_operations test + ec2_asg: + name: "{{ resource_prefix }}-asg-tag-test" + launch_config_name: "{{ resource_prefix }}-lc-tag-test" + health_check_period: 60 + health_check_type: ELB + replace_all_instances: yes + min_size: 1 + max_size: 1 + desired_capacity: 1 + region: "{{ aws_region }}" + register: create_asg + + - name: ensure that AutoScalingGroup is created + assert: + that: + - create_asg is changed + - create_asg.failed is false + - '"autoscaling:CreateAutoScalingGroup" in create_asg.resource_actions' + + #---------------------------------------------------------------------- + + - name: Get asg info + ec2_asg_info: + name: "{{ resource_prefix }}-asg-tag-test" + register: info_result + + - assert: + that: + - info_result.results[0].tags | length == 0 + + - name: Tag asg + ec2_asg: + name: "{{ resource_prefix }}-asg-tag-test" + tags: + - tag_a: 'value 1' + propagate_at_launch: no + - tag_b: 'value 2' + propagate_at_launch: yes + register: output + + - assert: + that: + - "output.tags | length == 2" + - output is changed + + - name: Re-Tag asg (different order) + ec2_asg: + name: "{{ resource_prefix }}-asg-tag-test" + tags: + - tag_b: 'value 2' + propagate_at_launch: yes + - tag_a: 'value 1' + propagate_at_launch: no + register: output + + - assert: + that: + - "output.tags | length == 2" + - output is not changed + + - name: Re-Tag asg new tags + ec2_asg: + name: "{{ resource_prefix }}-asg-tag-test" + tags: + - tag_c: 'value 3' + propagate_at_launch: no + register: output + + - assert: + that: + - "output.tags | length == 1" + - output is changed + + - name: Re-Tag asg update propagate_at_launch + ec2_asg: + name: "{{ resource_prefix }}-asg-tag-test" + tags: + - tag_c: 'value 3' + propagate_at_launch: yes + register: output + + - assert: + that: + - "output.tags | length == 1" + - output is changed + + - name: Remove all tags + ec2_asg: + name: "{{ resource_prefix }}-asg-tag-test" + tags: [] + register: add_empty + + - name: Get asg info + ec2_asg_info: + name: "{{ resource_prefix }}-asg-tag-test" + register: info_result + # create a list of tag_keys from info result + - set_fact: + tag_keys: "{{ info_result.results[0].tags | map(attribute='key') | list }}" + + - assert: + that: + - add_empty is changed + - info_result.results[0].tags | length == 0 + - '"autoscaling:CreateOrUpdateTags" not in add_empty.resource_actions' + - '"autoscaling:DeleteTags" in add_empty.resource_actions' + + - name: Add 4 new tags - do not purge existing tags + ec2_asg: + name: "{{ resource_prefix }}-asg-tag-test" + tags: + - lowercase spaced: "hello cruel world" + propagate_at_launch: no + - Title Case: "Hello Cruel World" + propagate_at_launch: yes + - CamelCase: "SimpleCamelCase" + propagate_at_launch: yes + - snake_case: "simple_snake_case" + propagate_at_launch: no + purge_tags: false + register: add_result + + - name: Get asg info + ec2_asg_info: + name: "{{ resource_prefix }}-asg-tag-test" + register: info_result + # create a list of tag_keys from info result + - set_fact: + tag_keys: "{{ info_result.results[0].tags | map(attribute='key') | list }}" + + - assert: + that: + - add_result is changed + - info_result.results[0].tags | length == 4 + - '"lowercase spaced" in tag_keys' + - '"Title Case" in tag_keys' + - '"CamelCase" in tag_keys' + - '"snake_case" in tag_keys' + - '"autoscaling:CreateOrUpdateTags" in add_result.resource_actions' + + - name: Add 4 new tags - do not purge existing tags - idempotency + ec2_asg: + name: "{{ resource_prefix }}-asg-tag-test" + tags: + - lowercase spaced: "hello cruel world" + propagate_at_launch: no + - Title Case: "Hello Cruel World" + propagate_at_launch: yes + - CamelCase: "SimpleCamelCase" + propagate_at_launch: yes + - snake_case: "simple_snake_case" + propagate_at_launch: no + purge_tags: false + register: add_result + + - name: Get asg info + ec2_asg_info: + name: "{{ resource_prefix }}-asg-tag-test" + register: info_result + + - assert: + that: + - add_result is not changed + - info_result.results[0].tags | length == 4 + - '"autoscaling:CreateOrUpdateTags" not in add_result.resource_actions' + + - name: Add 2 new tags - purge existing tags + ec2_asg: + name: "{{ resource_prefix }}-asg-tag-test" + tags: + - tag_a: 'val_a' + propagate_at_launch: no + - tag_b: 'val_b' + propagate_at_launch: yes + register: add_purge_result + + - name: Get asg info + ec2_asg_info: + name: "{{ resource_prefix }}-asg-tag-test" + register: info_result + # create a list of tag_keys from info result + - set_fact: + tag_keys: "{{ info_result.results[0].tags | map(attribute='key') | list }}" + + - assert: + that: + - add_purge_result is changed + - info_result.results[0].tags | length == 2 + - '"tag_a" in tag_keys' + - '"tag_b" in tag_keys' + - '"lowercase spaced" not in tag_keys' + - '"Title Case" not in tag_keys' + - '"CamelCase" not in tag_keys' + - '"snake_case" not in tag_keys' + - '"autoscaling:CreateOrUpdateTags" in add_purge_result.resource_actions' + + - name: Re-tag ASG - modify values + ec2_asg: + name: "{{ resource_prefix }}-asg-tag-test" + tags: + - tag_a: 'new_val_a' + propagate_at_launch: no + - tag_b: 'new_val_b' + propagate_at_launch: yes + register: add_purge_result + + - name: Get asg info + ec2_asg_info: + name: "{{ resource_prefix }}-asg-tag-test" + register: info_result + # create a list of tag_keys and tag_values from info result + - set_fact: + tag_keys: "{{ info_result.results[0].tags | map(attribute='key') | list }}" + - set_fact: + tag_values: "{{ info_result.results[0].tags | map(attribute='value') | list }}" + + + - assert: + that: + - add_purge_result is changed + - info_result.results[0].tags | length == 2 + - '"tag_a" in tag_keys' + - '"tag_b" in tag_keys' + - '"new_val_a" in tag_values' + - '"new_val_b" in tag_values' + - '"lowercase spaced" not in tag_keys' + - '"Title Case" not in tag_keys' + - '"CamelCase" not in tag_keys' + - '"snake_case" not in tag_keys' + - '"autoscaling:CreateOrUpdateTags" in add_purge_result.resource_actions' + + - name: Add 2 more tags - do not purge existing tags + ec2_asg: + name: "{{ resource_prefix }}-asg-tag-test" + tags: + - lowercase spaced: "hello cruel world" + propagate_at_launch: no + - Title Case: "Hello Cruel World" + propagate_at_launch: yes + purge_tags: false + register: add_result + + - name: Get asg info + ec2_asg_info: + name: "{{ resource_prefix }}-asg-tag-test" + register: info_result + # create a list of tag_keys from info result + - set_fact: + tag_keys: "{{ info_result.results[0].tags | map(attribute='key') | list }}" + + - assert: + that: + - add_result is changed + - info_result.results[0].tags | length == 4 + - '"tag_a" in tag_keys' + - '"tag_b" in tag_keys' + - '"lowercase spaced" in tag_keys' + - '"Title Case" in tag_keys' + - '"autoscaling:CreateOrUpdateTags" in add_result.resource_actions' + + - name: Add empty tags with purge set to false to assert that existing tags are retained + ec2_asg: + name: "{{ resource_prefix }}-asg-tag-test" + tags: [] + purge_tags: false + register: add_empty + + - name: Get asg info + ec2_asg_info: + name: "{{ resource_prefix }}-asg-tag-test" + register: info_result + # create a list of tag_keys from info result + - set_fact: + tag_keys: "{{ info_result.results[0].tags | map(attribute='key') | list }}" + + - assert: + that: + - add_empty is not changed + - info_result.results[0].tags | length == 4 + - '"tag_a" in tag_keys' + - '"tag_b" in tag_keys' + - '"lowercase spaced" in tag_keys' + - '"Title Case" in tag_keys' + - '"autoscaling:CreateOrUpdateTags" not in add_empty.resource_actions' + + - name: Add empty tags with purge set to true to assert that existing tags are removed + ec2_asg: + name: "{{ resource_prefix }}-asg-tag-test" + tags: [] + register: add_empty + + - name: Get asg info + ec2_asg_info: + name: "{{ resource_prefix }}-asg-tag-test" + register: info_result + # create a list of tag_keys from info result + - set_fact: + tag_keys: "{{ info_result.results[0].tags | map(attribute='key') | list }}" + + - assert: + that: + - add_empty is changed + - info_result.results[0].tags | length == 0 + - '"tag_a" not in tag_keys' + - '"tag_b" not in tag_keys' + - '"lowercase spaced" not in tag_keys' + - '"Title Case" not in tag_keys' + - '"autoscaling:CreateOrUpdateTags" not in add_empty.resource_actions' + - '"autoscaling:DeleteTags" in add_empty.resource_actions' + + #---------------------------------------------------------------------- + + always: + + - name: kill asg created in this test + ec2_asg: + name: "{{ resource_prefix }}-asg-tag-test" + state: absent + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10 + + - name: remove launch config created in this test + ec2_lc: + name: "{{ resource_prefix }}-lc-tag-test" + state: absent + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10
AutoScaling Group tags module <!--- Verify first that your feature was not already discussed on GitHub --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY Add a new module `ec2_asg_tag` analogous to `ec2_tag` to manage tags on AutoScaling Groups. ##### ISSUE TYPE - Feature Idea ##### COMPONENT NAME `ec2_asg_tag` ##### ADDITIONAL INFORMATION Using `ec2_asg` to manage tags is difficult since you must [specify the entire list of tags to manage them](https://github.com/ansible-collections/community.aws/blob/9b60a2d5d50ff1d77e74cf79715ccebc4632757f/tests/integration/targets/ec2_asg/tasks/main.yml#L194-L248). This is cumbersome since you first need to use `ec2_asg_info` to query the current set of tags, munge the result to create a new list of tags that includes or excludes the tags you with to add/remove and call `ec2_asg` again. A more declarative approach would be to follow the pattern of `ec2_tag`, e.g.: <!--- Paste example playbooks or commands between quotes below --> ```yaml - name: Ensure tags are present on an ASG community.aws.ec2_asg_tag: resource: my-auto-scaling-group state: present tags: - environment: production propagate_at_launch: true - role: webserver propagate_at_launch: true - name: Ensure tag is absent on an ASG community.aws.ec2_asg_tag: resource: my-auto-scaling-group state: absent tags: - environment: development ``` The module would utilise underlying API calls to: * https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_DescribeTags.html * https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_CreateOrUpdateTags.html * https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_DeleteTags.html
Files identified in the description: None If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> Hi @tremble, how do you feel about this PR? @alinabuzachis, Generally I prefer the alternative option of adding a "purge" option to the ec2_asg module (defaulting to purge=True, but supporting purge=False for the behaviour @jsok is after). On the whole it's more consistent with our other modules. However, we do have ec2_tag and ecs_tag, so it's not entirely inconsistent. Consider me neither a +1 nor a -1.
2022-03-02T02:41:48
ansible-collections/community.aws
961
ansible-collections__community.aws-961
[ "959" ]
d649e372c993e65de2740e157f6e18c4d6f7201b
diff --git a/plugins/modules/iam_role.py b/plugins/modules/iam_role.py --- a/plugins/modules/iam_role.py +++ b/plugins/modules/iam_role.py @@ -571,10 +571,8 @@ def destroy_role(): # Before we try to delete the role we need to remove any # - attached instance profiles # - attached managed policies - # - permissions boundary remove_instance_profiles(role_params, role) update_managed_policies(role_params, role, [], True) - update_role_permissions_boundary(boundary_params, role) try: if not module.check_mode:
Deleting an IAM Role Should Not Fail if Permission Boundary Cannot Be Removed ### Summary I have a role with a permission boundary that disallows removing permission boundaries. This role is then able to create a new role, which inherits that permissions boundary. If I want to delete that role, the `iam_role` plugin fails due to the inability to delete the permission boundary. Deleting the permission boundary is not actually a prerequisite to deleting the role and there's nothing in AWS that requires removing permission boundaries from roles before deleting them. [This comment](https://github.com/ansible-collections/community.aws/blob/454f5eb5395f1372b125b5b09e731798a698124e/plugins/modules/iam_role.py#L571-L577) is not true when it comes to inherited permission boundaries. ### Issue Type Bug Report ### Component Name iam_role ### Ansible Version ```console (paste below) $ ansible --version ansible 2.10.8 config file = None configured module search path = [ "elided" ] ansible python module location = /usr/local/lib/python3.9/site-packages/ansible executable location = /usr/local/bin/ansible python version = 3.9.10 (main, Jan 15 2022, 11:48:00) [Clang 13.0.0 (clang-1300.0.29.3)] ``` ### Collection Versions ```console (paste below) $ ansible-galaxy collection list amazon.aws 1.4.1 community.aws 1.4.0 ``` ### AWS SDK versions ```console (paste below) $ pip show boto boto3 botocore Name: boto3 Version: 1.18.48 Summary: The AWS SDK for Python Home-page: https://github.com/boto/boto3 Author: Amazon Web Services Author-email: License: Apache License 2.0 Location: /usr/lib/python3.7/site-packages Requires: botocore, jmespath, s3transfer Required-by: --- Name: botocore Version: 1.21.48 Summary: Low-level, data-driven core of boto 3. Home-page: https://github.com/boto/botocore Author: Amazon Web Services Author-email: License: Apache License 2.0 Location: /usr/lib/python3.7/site-packages Requires: jmespath, python-dateutil, urllib3 Required-by: awscli, boto3, s3transfer ``` ### Configuration _No response_ ### OS / Environment _No response_ ### Steps to Reproduce <!--- Paste example playbooks or commands between quotes below --> ```yaml (paste below) - name: Create Manager Role community.aws.iam_role: aws_access_key: "{{ aws_access_key }}" aws_secret_key: "{{ aws_secret_key }}" security_token: "{{ aws_session_token }}" name: "manager" assume_role_policy_document: | { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "{{ aws_account_id }}" }, "Action": "sts:AssumeRole" } ] } boundary: | { "Version": "2012-10-17", "Statement": [ { "Sid": "NoBoundaryPolicyDelete", "Effect": "Deny", "Action": [ "iam:DeleteRolePermissionsBoundary" ], "Resource": "*" }, ] } create_instance_profile: false register: manager_role - name: Assume role community.aws.sts_assume_role: aws_access_key: "{{ aws_access_key }}" aws_secret_key: "{{ aws_secret_key }}" aws_security_token: "{{ aws_session_token }}" role_arn: "manager" role_session_name: "manager" register: _ansible_role - name: Update credentials set_fact: aws_access_key: "{{ _ansible_role.sts_creds.access_key }}" aws_secret_key: "{{ _ansible_role.sts_creds.secret_key }}" aws_session_token: "{{ _ansible_role.sts_creds.session_token }}" - name: Create test role # Inherits permission boundary from manager community.aws.iam_role: aws_access_key: "{{ aws_access_key }}" aws_secret_key: "{{ aws_secret_key }}" security_token: "{{ aws_session_token }}" name: "test" assume_role_policy_document: | { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "{{ manager_role.iam_role.arn }}" }, "Action": "sts:AssumeRole" } ] } - name: Delete test role # Fails because it cannot delete the inherited permission boundary community.aws.iam_role: aws_access_key: "{{ aws_access_key }}" aws_secret_key: "{{ aws_secret_key }}" security_token: "{{ aws_session_token }}" name: "test" state: absent ``` ### Expected Results I expect the be able to delete the role. ### Actual Results ```console (paste below) Unable to remove permission boundary for role test: An error occurred (AccessDenied) when calling the DeleteRolePermissionsBoundary operation: User: arn:aws:iam::<elided>:role/manager is not authorized to perform: iam:DeleteRolePermissionsBoundary on resource: role test with an explicit deny ``` ### Code of Conduct - [X] I agree to follow the Ansible Code of Conduct
Files identified in the description: * [`plugins/modules/iam_role.py`](https://github.com/['ansible-collections/amazon.aws', 'ansible-collections/community.aws', 'ansible-collections/community.vmware']/blob/main/plugins/modules/iam_role.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @jillr @markuman @s-hertel @tremble [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> I'm happy to submit a PR removing the offending lines of code. @phene Looking at the docs, you're probably correct that it's not necessary to remove the permissions boundary, it is however necessary to detach the managed policies and remove the inline policies (a weird quirk of roles, this isn't true for most AWS resources). If you can create the PR that would be the fastest way to get this added. Since we can't review and merge our own PRs, two maintainers need to get involved if a maintainer writes the PR, if you submit the PR it just takes one maintainer to approve and merge the PR. It looks like the integration tests already check that we can delete a role with a boundary policy attached: https://github.com/ansible-collections/community.aws/blob/main/tests/integration/targets/iam_role/tasks/boundary_policy.yml#L49-L82 so the only additional thing you'll need beyond the change is to add a changelog entry: https://docs.ansible.com/ansible/latest/community/development_process.html#changelogs-how-to
2022-03-03T01:23:53
ansible-collections/community.aws
963
ansible-collections__community.aws-963
[ "571" ]
d649e372c993e65de2740e157f6e18c4d6f7201b
diff --git a/plugins/modules/elb_application_lb.py b/plugins/modules/elb_application_lb.py --- a/plugins/modules/elb_application_lb.py +++ b/plugins/modules/elb_application_lb.py @@ -49,13 +49,38 @@ deletion_protection: description: - Indicates whether deletion protection for the ALB is enabled. - - Defaults to C(false). + - Defaults to C(False). type: bool http2: description: - Indicates whether to enable HTTP2 routing. - - Defaults to C(false). + - Defaults to C(True). type: bool + http_desync_mitigation_mode: + description: + - Determines how the load balancer handles requests that might pose a security risk to an application. + - Defaults to C('defensive') + type: str + choices: ['monitor', 'defensive', 'strictest'] + version_added: 3.2.0 + http_drop_invalid_header_fields: + description: + - Indicates whether HTTP headers with invalid header fields are removed by the load balancer C(True) or routed to targets C(False). + - Defaults to C(False). + type: bool + version_added: 3.2.0 + http_x_amzn_tls_version_and_cipher_suite: + description: + - Indicates whether the two headers are added to the client request before sending it to the target. + - Defaults to C(False). + type: bool + version_added: 3.2.0 + http_xff_client_port: + description: + - Indicates whether the X-Forwarded-For header should preserve the source port that the client used to connect to the load balancer. + - Defaults to C(False). + type: bool + version_added: 3.2.0 idle_timeout: description: - The number of seconds to wait before an idle connection is closed. @@ -183,6 +208,12 @@ - Sets the type of IP addresses used by the subnets of the specified Application Load Balancer. choices: [ 'ipv4', 'dualstack' ] type: str + waf_fail_open: + description: + - Indicates whether to allow a AWS WAF-enabled load balancer to route requests to targets if it is unable to forward the request to AWS WAF. + - Defaults to C(False). + type: bool + version_added: 3.2.0 extends_documentation_fragment: - amazon.aws.aws - amazon.aws.ec2 @@ -525,6 +556,13 @@ def create_or_update_alb(alb_obj): alb_obj.module.exit_json(changed=True, msg='Would have updated ALB if not in check mode.') alb_obj.modify_security_groups() + # ALB attributes + if not alb_obj.compare_elb_attributes(): + if alb_obj.module.check_mode: + alb_obj.module.exit_json(changed=True, msg='Would have updated ALB if not in check mode.') + alb_obj.update_elb_attributes() + alb_obj.modify_elb_attributes() + # Tags - only need to play with tags if tags parameter has been set to something if alb_obj.tags is not None: @@ -549,10 +587,6 @@ def create_or_update_alb(alb_obj): alb_obj.module.exit_json(changed=True, msg='Would have created ALB if not in check mode.') alb_obj.create_elb() - # ALB attributes - alb_obj.update_elb_attributes() - alb_obj.modify_elb_attributes() - # Listeners listeners_obj = ELBListeners(alb_obj.connection, alb_obj.module, alb_obj.elb['LoadBalancerArn']) listeners_to_add, listeners_to_modify, listeners_to_delete = listeners_obj.compare_listeners() @@ -683,6 +717,10 @@ def main(): access_logs_s3_prefix=dict(type='str'), deletion_protection=dict(type='bool'), http2=dict(type='bool'), + http_desync_mitigation_mode=dict(type='str', choices=['monitor', 'defensive', 'strictest']), + http_drop_invalid_header_fields=dict(type='bool'), + http_x_amzn_tls_version_and_cipher_suite=dict(type='bool'), + http_xff_client_port=dict(type='bool'), idle_timeout=dict(type='int'), listeners=dict(type='list', elements='dict', @@ -703,6 +741,7 @@ def main(): scheme=dict(default='internet-facing', choices=['internet-facing', 'internal']), state=dict(choices=['present', 'absent'], default='present'), tags=dict(type='dict'), + waf_fail_open=dict(type='bool'), wait_timeout=dict(type='int'), wait=dict(default=False, type='bool'), purge_rules=dict(default=True, type='bool'),
diff --git a/tests/integration/targets/elb_application_lb/tasks/main.yml b/tests/integration/targets/elb_application_lb/tasks/main.yml --- a/tests/integration/targets/elb_application_lb/tasks/main.yml +++ b/tests/integration/targets/elb_application_lb/tasks/main.yml @@ -241,6 +241,12 @@ - alb is changed - alb.ip_address_type == 'dualstack' - alb.listeners[0].rules | length == 1 + - alb.routing_http2_enabled | bool + - alb.routing_http_desync_mitigation_mode == 'defensive' + - not alb.routing_http_drop_invalid_header_fields_enabled | bool + - not alb.routing_http_x_amzn_tls_version_and_cipher_suite_enabled | bool + - not alb.routing_http_xff_client_port_enabled | bool + - not alb.waf_fail_open_enabled | bool - name: Create an ALB with ip address type (idempotence) - check_mode elb_application_lb: @@ -282,6 +288,132 @@ that: - alb is not changed - alb.ip_address_type == 'dualstack' + - alb.routing_http2_enabled | bool + - alb.routing_http_desync_mitigation_mode == 'defensive' + - not alb.routing_http_drop_invalid_header_fields_enabled | bool + - not alb.routing_http_x_amzn_tls_version_and_cipher_suite_enabled | bool + - not alb.routing_http_xff_client_port_enabled | bool + - not alb.waf_fail_open_enabled | bool + + # ------------------------------------------------------------------------------------------ + + - name: Update an ALB with different attributes - check_mode + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + ip_address_type: 'dualstack' + http2: no + http_desync_mitigation_mode: monitor + http_drop_invalid_header_fields: yes + http_x_amzn_tls_version_and_cipher_suite: yes + http_xff_client_port: yes + waf_fail_open: yes + register: alb + check_mode: yes + + - assert: + that: + - alb is changed + - alb.msg is match('Would have updated ALB if not in check mode.') + + - name: Update an ALB with different attributes + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + ip_address_type: 'dualstack' + http2: no + http_desync_mitigation_mode: monitor + http_drop_invalid_header_fields: yes + http_x_amzn_tls_version_and_cipher_suite: yes + http_xff_client_port: yes + waf_fail_open: yes + register: alb + + - assert: + that: + - alb is changed + - alb.ip_address_type == 'dualstack' + - not alb.routing_http2_enabled | bool + - alb.routing_http_desync_mitigation_mode == 'monitor' + - alb.routing_http_drop_invalid_header_fields_enabled | bool + - alb.routing_http_x_amzn_tls_version_and_cipher_suite_enabled | bool + - alb.routing_http_xff_client_port_enabled | bool + - alb.waf_fail_open_enabled | bool + + - name: Update an ALB with different attributes (idempotence) - check_mode + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + ip_address_type: 'dualstack' + http2: no + http_desync_mitigation_mode: monitor + http_drop_invalid_header_fields: yes + http_x_amzn_tls_version_and_cipher_suite: yes + http_xff_client_port: yes + waf_fail_open: yes + register: alb + check_mode: yes + + - assert: + that: + - alb is not changed + - alb.msg is match('IN CHECK MODE - no changes to make to ALB specified.') + + - name: Update an ALB with different attributes (idempotence) + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + ip_address_type: 'dualstack' + http2: no + http_desync_mitigation_mode: monitor + http_drop_invalid_header_fields: yes + http_x_amzn_tls_version_and_cipher_suite: yes + http_xff_client_port: yes + waf_fail_open: yes + register: alb + + - assert: + that: + - alb is not changed + - alb.ip_address_type == 'dualstack' + - not alb.routing_http2_enabled | bool + - alb.routing_http_desync_mitigation_mode == 'monitor' + - alb.routing_http_drop_invalid_header_fields_enabled | bool + - alb.routing_http_x_amzn_tls_version_and_cipher_suite_enabled | bool + - alb.routing_http_xff_client_port_enabled | bool + - alb.waf_fail_open_enabled | bool # ------------------------------------------------------------------------------------------ @@ -298,6 +430,12 @@ - Type: forward TargetGroupName: "{{ tg_name }}" ip_address_type: 'ipv4' + http2: no + http_desync_mitigation_mode: monitor + http_drop_invalid_header_fields: yes + http_x_amzn_tls_version_and_cipher_suite: yes + http_xff_client_port: yes + waf_fail_open: yes register: alb check_mode: yes @@ -319,12 +457,24 @@ - Type: forward TargetGroupName: "{{ tg_name }}" ip_address_type: 'ipv4' + http2: no + http_desync_mitigation_mode: monitor + http_drop_invalid_header_fields: yes + http_x_amzn_tls_version_and_cipher_suite: yes + http_xff_client_port: yes + waf_fail_open: yes register: alb - assert: that: - alb is changed - alb.ip_address_type == 'ipv4' + - not alb.routing_http2_enabled | bool + - alb.routing_http_desync_mitigation_mode == 'monitor' + - alb.routing_http_drop_invalid_header_fields_enabled | bool + - alb.routing_http_x_amzn_tls_version_and_cipher_suite_enabled | bool + - alb.routing_http_xff_client_port_enabled | bool + - alb.waf_fail_open_enabled | bool - name: Update an ALB with different ip address type (idempotence) - check_mode elb_application_lb: @@ -339,6 +489,12 @@ - Type: forward TargetGroupName: "{{ tg_name }}" ip_address_type: 'ipv4' + http2: no + http_desync_mitigation_mode: monitor + http_drop_invalid_header_fields: yes + http_x_amzn_tls_version_and_cipher_suite: yes + http_xff_client_port: yes + waf_fail_open: yes register: alb check_mode: yes @@ -360,12 +516,24 @@ - Type: forward TargetGroupName: "{{ tg_name }}" ip_address_type: 'ipv4' + http2: no + http_desync_mitigation_mode: monitor + http_drop_invalid_header_fields: yes + http_x_amzn_tls_version_and_cipher_suite: yes + http_xff_client_port: yes + waf_fail_open: yes register: alb - assert: that: - alb is not changed - alb.ip_address_type == 'ipv4' + - not alb.routing_http2_enabled | bool + - alb.routing_http_desync_mitigation_mode == 'monitor' + - alb.routing_http_drop_invalid_header_fields_enabled | bool + - alb.routing_http_x_amzn_tls_version_and_cipher_suite_enabled | bool + - alb.routing_http_xff_client_port_enabled | bool + - alb.waf_fail_open_enabled | bool # ------------------------------------------------------------------------------------------
Support "Drop invalid header fields" in elb_application_lb <!--- Verify first that your feature was not already discussed on GitHub --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY Add support for "drop invalid header fields" when manipulating an ALB. ##### ISSUE TYPE - Feature Idea ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> `elb_application_lb` ##### ADDITIONAL INFORMATION <!--- Describe how the feature would be used, why it is needed and what it would solve --> If you want to enable dropping invalid headers on your ALB you should: - create the ALB - by default, dropping invalid headers is disabled - edit the ALB settings on AWS UI and enable "Drop invalid header fields" This feature would solve the need to manually edit the ALB after its creation. <!--- Paste example playbooks or commands between quotes below --> ```yaml ``` <!--- HINT: You can also paste gist.github.com links for larger files -->
Hi @boutetnico, thank you for raising this. Would you be willing to implement this feature? If you need any help, please feel free to reach out to us on IRC #ansible-aws. Thank you. cc @jillr @s-hertel @tremble @wimnat [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> cc @markuman [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> I can work on adding this Also going to add support for the other routing options: - http_desync_mitigation_mode - http_drop_invalid_header_fields (this issue) - http_x_amzn_tls_version_and_cipher_suite - http_xff_client_port_enabled
2022-03-04T00:20:36
ansible-collections/community.aws
966
ansible-collections__community.aws-966
[ "891" ]
b920063bf8cf5f9c7b3459c03ee1e87e4e23555d
diff --git a/plugins/modules/elb_target_group.py b/plugins/modules/elb_target_group.py --- a/plugins/modules/elb_target_group.py +++ b/plugins/modules/elb_target_group.py @@ -76,13 +76,14 @@ type: str port: description: - - The port on which the targets receive traffic. This port is used unless you specify a port override when registering the target. Required if - I(state) is C(present). + - The port on which the targets receive traffic. This port is used unless you specify a port override when registering the target. + - Required when I(state) is C(present) and I(target_type) is C(instance), C(ip), or C(alb). required: false type: int protocol: description: - - The protocol to use for routing traffic to the targets. Required when I(state) is C(present). + - The protocol to use for routing traffic to the targets. + - Required when I(state) is C(present) and I(target_type) is C(instance), C(ip), or C(alb). required: false choices: [ 'http', 'https', 'tcp', 'tls', 'udp', 'tcp_udp', 'HTTP', 'HTTPS', 'TCP', 'TLS', 'UDP', 'TCP_UDP'] type: str @@ -141,15 +142,16 @@ target_type: description: - The type of target that you must specify when registering targets with this target group. The possible values are - C(instance) (targets are specified by instance ID), C(ip) (targets are specified by IP address) or C(lambda) (target is specified by ARN). - Note that you can't specify targets for a target group using more than one type. Target type lambda only accept one target. When more than + C(instance) (targets are specified by instance ID), C(ip) (targets are specified by IP address), C(lambda) (target is specified by ARN), + or C(alb) (target is specified by ARN). + Note that you can't specify targets for a target group using more than one type. Target types lambda and alb only accept one target. When more than one target is specified, only the first one is used. All additional targets are ignored. If the target type is ip, specify IP addresses from the subnets of the virtual private cloud (VPC) for the target group, the RFC 1918 range (10.0.0.0/8, 172.16.0.0/12, and 192.168.0.0/16), and the RFC 6598 range (100.64.0.0/10). You can't specify publicly routable IP addresses. - The default behavior is C(instance). required: false - choices: ['instance', 'ip', 'lambda'] + choices: ['instance', 'ip', 'lambda', 'alb'] type: str targets: description: @@ -165,7 +167,8 @@ type: int vpc_id: description: - - The identifier of the virtual private cloud (VPC). Required when I(state) is C(present). + - The identifier of the virtual private cloud (VPC). + - Required when I(state) is C(present) and I(target_type) is C(instance), C(ip), or C(alb). required: false type: str preserve_client_ip_enabled: @@ -891,7 +894,7 @@ def main(): state=dict(required=True, choices=['present', 'absent']), successful_response_codes=dict(), tags=dict(default={}, type='dict'), - target_type=dict(choices=['instance', 'ip', 'lambda']), + target_type=dict(choices=['instance', 'ip', 'lambda', 'alb']), targets=dict(type='list', elements='dict'), unhealthy_threshold_count=dict(type='int'), vpc_id=dict(), @@ -905,6 +908,7 @@ def main(): required_if=[ ['target_type', 'instance', ['protocol', 'port', 'vpc_id']], ['target_type', 'ip', ['protocol', 'port', 'vpc_id']], + ['target_type', 'alb', ['protocol', 'port', 'vpc_id']], ] )
diff --git a/tests/integration/targets/elb_target/tasks/alb_target.yml b/tests/integration/targets/elb_target/tasks/alb_target.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/elb_target/tasks/alb_target.yml @@ -0,0 +1,205 @@ +--- +- name: test elb_target_group with target_type = alb + block: + - name: set up testing VPC + ec2_vpc_net: + name: "{{ resource_prefix }}-vpc" + state: present + cidr_block: 20.0.0.0/16 + tags: + Name: "{{ resource_prefix }}-vpc" + Description: "Created by ansible-test" + register: vpc + + - name: set up testing internet gateway + ec2_vpc_igw: + vpc_id: "{{ vpc.vpc.id }}" + state: present + register: igw + + - name: set up testing subnet + ec2_vpc_subnet: + state: present + vpc_id: "{{ vpc.vpc.id }}" + cidr: 20.0.0.0/18 + az: "{{ aws_region }}a" + resource_tags: + Name: "{{ resource_prefix }}-subnet" + register: subnet_1 + + - name: set up testing subnet + ec2_vpc_subnet: + state: present + vpc_id: "{{ vpc.vpc.id }}" + cidr: 20.0.64.0/18 + az: "{{ aws_region }}b" + resource_tags: + Name: "{{ resource_prefix }}-subnet" + register: subnet_2 + + - name: create routing rules + ec2_vpc_route_table: + vpc_id: "{{ vpc.vpc.id }}" + tags: + created: "{{ resource_prefix }}-route" + routes: + - dest: 0.0.0.0/0 + gateway_id: "{{ igw.gateway_id }}" + subnets: + - "{{ subnet_1.subnet.id }}" + - "{{ subnet_2.subnet.id }}" + register: route_table + + - name: create testing security group + ec2_group: + name: "{{ resource_prefix }}-sg" + description: a security group for ansible tests + vpc_id: "{{ vpc.vpc.id }}" + rules: + - proto: tcp + from_port: 80 + to_port: 80 + cidr_ip: 0.0.0.0/0 + - proto: tcp + from_port: 22 + to_port: 22 + cidr_ip: 0.0.0.0/0 + register: sg + + - name: set up testing target group for NLB (type=alb) + elb_target_group: + name: "{{ elb_target_group_name }}" + target_type: alb + state: present + protocol: TCP + port: 80 + vpc_id: "{{ vpc.vpc.id }}" + register: elb_target_group + + - name: assert target group was created successfully + assert: + that: + - elb_target_group.changed + - elb_target_group.target_group_name == elb_target_group_name + - elb_target_group.target_type == 'alb' + - elb_target_group.vpc_id == vpc.vpc.id + - elb_target_group.port == 80 + - elb_target_group.protocol == 'TCP' + - elb_target_group.load_balancer_arns | length == 0 + + - name: create a network load balancer and attach to target group + elb_network_lb: + name: "{{ lb_name }}-nlb" + subnets: + - "{{ subnet_1.subnet.id }}" + - "{{ subnet_2.subnet.id }}" + listeners: + - Protocol: TCP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ elb_target_group_name }}" + state: present + register: nlb + + - name: assert NLB was created successfully and attached to target group + assert: + that: + - nlb is changed + - nlb.listeners | length == 1 + - nlb.listeners[0].default_actions[0].forward_config.target_groups[0].target_group_arn == elb_target_group.target_group_arn + + - name: get target group info + elb_target_group_info: + load_balancer_arn: "{{ nlb.load_balancer_arn }}" + register: tg_info + + - name: assert target group's target is nlb + assert: + that: + - tg_info.target_groups[0].target_group_name == elb_target_group_name + - tg_info.target_groups[0].target_type == 'alb' + - tg_info.target_groups[0].load_balancer_arns | length == 1 + - tg_info.target_groups[0].load_balancer_arns[0] == nlb.load_balancer_arn + + always: + - name: remove network load balancer + elb_network_lb: + name: "{{ lb_name }}-nlb" + state: absent + wait: true + wait_timeout: 600 + register: removed + retries: 10 + until: removed is not failed + ignore_errors: true + + - name: remove elb target group + elb_target_group: + name: "{{ elb_target_group_name }}" + target_type: alb + state: absent + protocol: HTTP + port: 80 + vpc_id: "{{ vpc.vpc.id }}" + ignore_errors: true + + - name: remove routing rules + ec2_vpc_route_table: + state: absent + lookup: id + route_table_id: "{{ route_table.route_table.id }}" + register: removed + retries: 5 + until: removed is not failed + ignore_errors: true + + - name: remove testing subnet + ec2_vpc_subnet: + state: absent + vpc_id: "{{ vpc.vpc.id }}" + cidr: 20.0.0.0/18 + az: "{{ aws_region }}a" + register: removed + retries: 10 + until: removed is not failed + ignore_errors: true + + - name: remove testing subnet + ec2_vpc_subnet: + state: absent + vpc_id: "{{ vpc.vpc.id }}" + cidr: 20.0.64.0/18 + az: "{{ aws_region }}b" + register: removed + retries: 10 + until: removed is not failed + ignore_errors: true + + - name: remove testing security group + ec2_group: + state: absent + name: "{{ resource_prefix }}-sg" + register: removed + retries: 10 + until: removed is not failed + ignore_errors: true + + - name: remove testing internet gateway + ec2_vpc_igw: + vpc_id: "{{ vpc.vpc.id }}" + state: absent + register: removed + retries: 2 + until: removed is not failed + ignore_errors: true + + - name: remove testing VPC + ec2_vpc_net: + name: "{{ resource_prefix }}-vpc" + cidr_block: 20.0.0.0/16 + state: absent + register: removed + retries: 2 + until: removed is not failed + ignore_errors: true \ No newline at end of file diff --git a/tests/integration/targets/elb_target/tasks/lambda_target.yml b/tests/integration/targets/elb_target/tasks/lambda_target.yml --- a/tests/integration/targets/elb_target/tasks/lambda_target.yml +++ b/tests/integration/targets/elb_target/tasks/lambda_target.yml @@ -91,7 +91,7 @@ targets: [] register: elb_target_group - - name: target is still the same, state must not be changed (idempotency) + - name: remove lambda target from target group assert: that: - elb_target_group.changed diff --git a/tests/integration/targets/elb_target/tasks/main.yml b/tests/integration/targets/elb_target/tasks/main.yml --- a/tests/integration/targets/elb_target/tasks/main.yml +++ b/tests/integration/targets/elb_target/tasks/main.yml @@ -12,3 +12,4 @@ block: - include_tasks: ec2_target.yml - include_tasks: lambda_target.yml + - include_tasks: alb_target.yml
elb_target_group: support target_type alb ### Summary Add support for `target_type: alb` Currently only `instance`, `ip`, and `lambda` are supported. ### Issue Type Feature Idea ### Component Name elb_target_group ### Additional Information <!--- Paste example playbooks or commands between quotes below --> ```yaml (paste below) ``` ### Code of Conduct - [X] I agree to follow the Ansible Code of Conduct
2022-03-05T01:13:26
ansible-collections/community.aws
970
ansible-collections__community.aws-970
[ "968" ]
b920063bf8cf5f9c7b3459c03ee1e87e4e23555d
diff --git a/plugins/modules/redshift_info.py b/plugins/modules/redshift_info.py --- a/plugins/modules/redshift_info.py +++ b/plugins/modules/redshift_info.py @@ -277,7 +277,7 @@ import re try: - from botocore.exception import BotoCoreError, ClientError + from botocore.exceptions import BotoCoreError, ClientError except ImportError: pass # caught by AnsibleAWSModule
Invalid import path for BotoCoreError in redshift_info module ### Summary In case of any AWS related error (like missing permissions) the module will throw a gigantic python stack trace with error summary as: ``` line 304, in find_clusters NameError: name 'BotoCoreError' is not defined ``` This is due to an invalid import path that is present in the module https://github.com/ansible-collections/community.aws/blob/main/plugins/modules/redshift_info.py#L280 Instead of `from botocore.exception` it should be `from botocore.exceptions`. Once that is done, ansible no longer hides the real error with the stack trace. ### Issue Type Bug Report ### Component Name redshift_info ### Ansible Version ```console (paste below) $ ansible --version ansible 2.10.8 config file = None configured module search path = ['/home/wojtek/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /usr/local/lib/python3.6/dist-packages/ansible executable location = /usr/local/bin/ansible python version = 3.6.9 (default, Jan 26 2021, 15:33:00) [GCC 8.4.0] ``` ### Collection Versions Non-relevant ### AWS SDK versions ```console (paste below) $ pip show boto boto3 botocore Name: boto Version: 2.49.0 Summary: Amazon Web Services Library Home-page: https://github.com/boto/boto/ Author: Mitch Garnaat Author-email: [email protected] License: MIT Location: /home/wojtek/.local/lib/python3.6/site-packages Requires: --- Name: boto3 Version: 1.20.54 Summary: The AWS SDK for Python Home-page: https://github.com/boto/boto3 Author: Amazon Web Services Author-email: None License: Apache License 2.0 Location: /home/wojtek/.local/lib/python3.6/site-packages Requires: jmespath, s3transfer, botocore --- Name: botocore Version: 1.23.54 Summary: Low-level, data-driven core of boto 3. Home-page: https://github.com/boto/botocore Author: Amazon Web Services Author-email: None License: Apache License 2.0 Location: /home/wojtek/.local/lib/python3.6/site-packages Requires: jmespath, urllib3, python-dateutil ``` ### Configuration ```console (paste below) $ ansible-config dump --only-changed ``` ### OS / Environment Ubuntu 20.04 ### Steps to Reproduce Run the module without DescribeClusters permission. ### Expected Results AWS API error on missing permissions is shown. ### Actual Results Python stack trace ending with ``` line 304, in find_clusters NameError: name 'BotoCoreError' is not defined ``` ### Code of Conduct - [X] I agree to follow the Ansible Code of Conduct
Files identified in the description: * [`plugins/modules/redshift_info.py`](https://github.com/['ansible-collections/amazon.aws', 'ansible-collections/community.aws', 'ansible-collections/community.vmware']/blob/main/plugins/modules/redshift_info.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @j-carl @jillr @markuman @s-hertel @tremble [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> @winglot Thank for your bringing this. Would you be willing to open a pull request that fixes this import error?
2022-03-07T18:36:13
ansible-collections/community.aws
971
ansible-collections__community.aws-971
[ "28" ]
b920063bf8cf5f9c7b3459c03ee1e87e4e23555d
diff --git a/plugins/modules/elb_application_lb.py b/plugins/modules/elb_application_lb.py --- a/plugins/modules/elb_application_lb.py +++ b/plugins/modules/elb_application_lb.py @@ -144,7 +144,7 @@ description: - A list of the names or IDs of the security groups to assign to the load balancer. - Required if I(state=present). - default: [] + - If C([]), the VPC's default security group will be used. type: list elements: str scheme: @@ -494,10 +494,16 @@ type: bool sample: false ''' +try: + import botocore +except ImportError: + pass # caught by AnsibleAWSModule from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule -from ansible_collections.amazon.aws.plugins.module_utils.ec2 import camel_dict_to_snake_dict +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import ansible_dict_to_boto3_filter_list +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AWSRetry from ansible_collections.amazon.aws.plugins.module_utils.ec2 import boto3_tag_list_to_ansible_dict +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import camel_dict_to_snake_dict from ansible_collections.amazon.aws.plugins.module_utils.ec2 import compare_aws_tags from ansible_collections.amazon.aws.plugins.module_utils.elbv2 import ( ApplicationLoadBalancer, @@ -509,6 +515,29 @@ from ansible_collections.amazon.aws.plugins.module_utils.elb_utils import get_elb_listener_rules [email protected]_backoff() +def describe_sgs_with_backoff(connection, **params): + paginator = connection.get_paginator('describe_security_groups') + return paginator.paginate(**params).build_full_result()['SecurityGroups'] + + +def find_default_sg(connection, module, vpc_id): + """ + Finds the default security group for the given VPC ID. + """ + filters = ansible_dict_to_boto3_filter_list({'vpc-id': vpc_id, 'group-name': 'default'}) + try: + sg = describe_sgs_with_backoff(connection, Filters=filters) + except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: + module.fail_json_aws(e, msg='No default security group found for VPC {0}'.format(vpc_id)) + if len(sg) == 1: + return sg[0]['GroupId'] + elif len(sg) == 0: + module.fail_json(msg='No default security group found for VPC {0}'.format(vpc_id)) + else: + module.fail_json(msg='Multiple security groups named "default" found for VPC {0}'.format(vpc_id)) + + def create_or_update_alb(alb_obj): """Create ALB or modify main attributes. json_exit here""" if alb_obj.elb: @@ -738,6 +767,11 @@ def main(): alb = ApplicationLoadBalancer(connection, connection_ec2, module) + # Update security group if default is specified + if alb.elb and module.params.get('security_groups') == []: + module.params['security_groups'] = [find_default_sg(connection_ec2, module, alb.elb['VpcId'])] + alb = ApplicationLoadBalancer(connection, connection_ec2, module) + if state == 'present': create_or_update_alb(alb) elif state == 'absent':
diff --git a/tests/integration/targets/elb_application_lb/tasks/main.yml b/tests/integration/targets/elb_application_lb/tasks/main.yml --- a/tests/integration/targets/elb_application_lb/tasks/main.yml +++ b/tests/integration/targets/elb_application_lb/tasks/main.yml @@ -25,6 +25,12 @@ set_fact: vpc_id: "{{ vpc.vpc.id }}" + - name: Get VPC's default security group + ec2_group_info: + filters: + vpc-id: "{{ vpc_id }}" + register: default_sg + - name: Create an internet gateway ec2_vpc_igw: vpc_id: '{{ vpc_id }}' @@ -200,7 +206,90 @@ # ------------------------------------------------------------------------------------------ - - name: Create an ALB with ip address type - check_mode + - name: Create an ALB with defaults - check_mode + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: [] + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + register: alb + check_mode: yes + + - assert: + that: + - alb is changed + - alb.msg is match('Would have created ALB if not in check mode.') + + - name: Create an ALB with defaults + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: [] + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + register: alb + + - assert: + that: + - alb is changed + - alb.listeners[0].rules | length == 1 + - alb.security_groups | length == 1 + - alb.security_groups[0] == default_sg.security_groups[0].group_id + + - name: Create an ALB with defaults (idempotence) - check_mode + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: [] + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + register: alb + check_mode: yes + + - assert: + that: + - alb is not changed + - alb.msg is match('IN CHECK MODE - no changes to make to ALB specified.') + + - name: Create an ALB with defaults (idempotence) + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: [] + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + register: alb + + - assert: + that: + - alb is not changed + - alb.listeners[0].rules | length == 1 + - alb.security_groups[0] == default_sg.security_groups[0].group_id + + # ------------------------------------------------------------------------------------------ + + - name: Update an ALB with ip address type - check_mode elb_application_lb: name: "{{ alb_name }}" subnets: "{{ public_subnets }}" @@ -219,9 +308,9 @@ - assert: that: - alb is changed - - alb.msg is match('Would have created ALB if not in check mode.') + - alb.msg is match('Would have updated ALB if not in check mode.') - - name: Create an ALB with ip address type + - name: Update an ALB with ip address type elb_application_lb: name: "{{ alb_name }}" subnets: "{{ public_subnets }}"
elb_application_lb with empty security groups list behaves inconsistently on create/update <!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> Resubmitted from https://github.com/ansible-collections/amazon.aws/issues/10 ##### SUMMARY <!--- Explain the problem briefly below --> `elb_application_lb` requires the `security_groups` option when `state=present` as explained in the docs (although it also says that the default is `[]` which seems useless since it won't accept the option being omitted). When creating a new ALB and supplying `security_groups: []` explicitly, the ALB is created successfully with the VPC default SG. Running the same task again will fail with the error that the `security_groups` option is missing, I'm not sure if this is reproducible outside of a VPC since I'm not sure there is such a thing as a default SG in that case. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> elb_application_lb ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> 2.9.6 ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> <!--- Paste example playbooks or commands between quotes below --> ```yaml - elb_application_lb: region: "us-east-1" name: "repro-delete" state: "present" subnets: "{{ my_subnets }}" listeners: - Protocol: HTTP Port: 80 DefaultActions: - Type: forward TargetGroupName: repro-group-us-east-1a scheme: internal security_groups: [] wait: yes register: alb loop: [1, 2] ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> ALB is created, then second run is `ok`. (an acceptable result might also be that the first run fails with an invalid option value, but that does preclude the possibility of using a "default" SG) ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> Second run fails. <!--- Paste verbatim command output between quotes --> ```paste below fatal: [localhost]: FAILED! => {"changed": false, "msg": "state is present but all of the following are missing: security_groups"} ```
Files identified in the description: * [`plugins/modules/elb_application_lb.py`](https://github.com/ansible-collections/community.aws/blob/main/plugins/modules/elb_application_lb.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @jillr @s-hertel @tremble @wimnat [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> @briantist Thank you for reporting this! We have recently this module to our CI so it should be easier to add a test case for this. > I'm not sure if this is reproducible outside of a VPC since I'm not sure there is such a thing as a default SG in that case. imo you can create ALB resources only **in** a VPC. the only way to solve this issue is imo to not allow an empty array as an input for `security_groups` parameter. otherwise and empty array must be treated as "use the VPCs default security group", which must be determined inside the code. I believe that "use the default VPC SG" is a desirable option in some/many use cases, so I wouldn't want to see that option disappear. It would be most useful if the module handled that case correctly, even if internally it means it has to retrieve the VPC default in order to verify its state. I can work on this @briantist @markuman. Expected behavior is treat empty array as "use the VPCs default security group" ? > I can work on this @briantist @markuman. Expected behavior is treat empty array as "use the VPCs default security group" ? @jatorcasso kind of yes, that's already what happens on first creation; the problem is that running it again will fail. So when the ALB already exists, the module needs to have a way to verify the current state, and that part is not working now. It may require reading the default SG from the VPC in order to verify. It might also be desirable to have "use the default VPC" as a separate option and then disallow the empty SG list, not sure... I might also suggest that no security group option supplied, when the ALB exists, might mean "don't check or change the state of SGs" but that is a behavioral change. If that's what happens on first creation, then that's what should happen after first creation as well imo to maintain idempotence. I'll work on that and add some integration tests to validate
2022-03-08T06:52:24
ansible-collections/community.aws
973
ansible-collections__community.aws-973
[ "135" ]
b920063bf8cf5f9c7b3459c03ee1e87e4e23555d
diff --git a/plugins/modules/ec2_asg_instance_refresh.py b/plugins/modules/ec2_asg_instance_refresh.py new file mode 100644 --- /dev/null +++ b/plugins/modules/ec2_asg_instance_refresh.py @@ -0,0 +1,267 @@ +#!/usr/bin/python +# Copyright: Ansible Project +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + +DOCUMENTATION = ''' +--- +module: ec2_asg_instance_refresh +version_added: 3.2.0 +short_description: Start or cancel an EC2 Auto Scaling Group (ASG) instance refresh in AWS +description: + - Start or cancel an EC2 Auto Scaling Group instance refresh in AWS. + - Can be used with M(community.aws.ec2_asg_instance_refresh_info) to track the subsequent progress. +author: "Dan Khersonsky (@danquixote)" +options: + state: + description: + - Desired state of the ASG. + type: str + required: true + choices: [ 'started', 'cancelled' ] + name: + description: + - The name of the auto scaling group you are searching for. + type: str + required: true + strategy: + description: + - The strategy to use for the instance refresh. The only valid value is C(Rolling). + - A rolling update is an update that is applied to all instances in an Auto Scaling group until all instances have been updated. + - A rolling update can fail due to failed health checks or if instances are on standby or are protected from scale in. + - If the rolling update process fails, any instances that were already replaced are not rolled back to their previous configuration. + type: str + default: 'Rolling' + preferences: + description: + - Set of preferences associated with the instance refresh request. + - If not provided, the default values are used. + - For I(min_healthy_percentage), the default value is C(90). + - For I(instance_warmup), the default is to use the value specified for the health check grace period for the Auto Scaling group. + - Can not be specified when I(state) is set to 'cancelled'. + required: false + suboptions: + min_healthy_percentage: + description: + - Total percent of capacity in ASG that must remain healthy during instance refresh to allow operation to continue. + - It is rounded up to the nearest integer. + type: int + default: 90 + instance_warmup: + description: + - The number of seconds until a newly launched instance is configured and ready to use. + - During this time, Amazon EC2 Auto Scaling does not immediately move on to the next replacement. + - The default is to use the value for the health check grace period defined for the group. + type: int + type: dict +extends_documentation_fragment: +- amazon.aws.aws +- amazon.aws.ec2 + +''' + +EXAMPLES = ''' +# Note: These examples do not set authentication details, see the AWS Guide for details. + +- name: Start a refresh + community.aws.ec2_asg_instance_refresh: + name: some-asg + state: started + +- name: Cancel a refresh + community.aws.ec2_asg_instance_refresh: + name: some-asg + state: cancelled + +- name: Start a refresh and pass preferences + community.aws.ec2_asg_instance_refresh: + name: some-asg + state: started + preferences: + min_healthy_percentage: 91 + instance_warmup: 60 + +''' + +RETURN = ''' +--- +instance_refresh_id: + description: instance refresh id + returned: success + type: str + sample: "08b91cf7-8fa6-48af-b6a6-d227f40f1b9b" +auto_scaling_group_name: + description: Name of autoscaling group + returned: success + type: str + sample: "public-webapp-production-1" +status: + description: + - The current state of the group when DeleteAutoScalingGroup is in progress. + - The following are the possible statuses + - Pending -- The request was created, but the operation has not started. + - InProgress -- The operation is in progress. + - Successful -- The operation completed successfully. + - Failed -- The operation failed to complete. You can troubleshoot using the status reason and the scaling activities. + - Cancelling -- + - An ongoing operation is being cancelled. + - Cancellation does not roll back any replacements that have already been completed, + - but it prevents new replacements from being started. + - Cancelled -- The operation is cancelled. + returned: success + type: str + sample: "Pending" +start_time: + description: The date and time this ASG was created, in ISO 8601 format. + returned: success + type: str + sample: "2015-11-25T00:05:36.309Z" +end_time: + description: The date and time this ASG was created, in ISO 8601 format. + returned: success + type: str + sample: "2015-11-25T00:05:36.309Z" +percentage_complete: + description: the % of completeness + returned: success + type: int + sample: 100 +instances_to_update: + description: num. of instance to update + returned: success + type: int + sample: 5 +''' + +try: + from botocore.exceptions import BotoCoreError, ClientError +except ImportError: + pass # caught by AnsibleAWSModule + + +from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AWSRetry +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import camel_dict_to_snake_dict +from ansible_collections.amazon.aws.plugins.module_utils.core import scrub_none_parameters +from ansible.module_utils.common.dict_transformations import snake_dict_to_camel_dict + + +def start_or_cancel_instance_refresh(conn, module): + """ + Args: + conn (boto3.AutoScaling.Client): Valid Boto3 ASG client. + module: AnsibleAWSModule object + + Returns: + { + "instance_refreshes": [ + { + 'auto_scaling_group_name': 'ansible-test-hermes-63642726-asg', + 'instance_refresh_id': '6507a3e5-4950-4503-8978-e9f2636efc09', + 'instances_to_update': 1, + 'percentage_complete': 0, + "preferences": { + "instance_warmup": 60, + "min_healthy_percentage": 90, + "skip_matching": false + }, + 'start_time': '2021-02-04T03:39:40+00:00', + 'status': 'Cancelling', + 'status_reason': 'Replacing instances before cancelling.', + } + ] + } + """ + + asg_state = module.params.get('state') + asg_name = module.params.get('name') + preferences = module.params.get('preferences') + + args = {} + args['AutoScalingGroupName'] = asg_name + if asg_state == 'started': + args['Strategy'] = module.params.get('strategy') + if preferences: + if asg_state == 'cancelled': + module.fail_json(msg='can not pass preferences dict when canceling a refresh') + _prefs = scrub_none_parameters(preferences) + args['Preferences'] = snake_dict_to_camel_dict(_prefs, capitalize_first=True) + cmd_invocations = { + 'cancelled': conn.cancel_instance_refresh, + 'started': conn.start_instance_refresh, + } + try: + if module.check_mode: + if asg_state == 'started': + ongoing_refresh = conn.describe_instance_refreshes(AutoScalingGroupName=asg_name).get('InstanceRefreshes', '[]') + if ongoing_refresh: + module.exit_json(changed=False, msg='In check_mode - Instance Refresh is already in progress, can not start new instance refresh.') + else: + module.exit_json(changed=True, msg='Would have started instance refresh if not in check mode.') + elif asg_state == 'cancelled': + ongoing_refresh = conn.describe_instance_refreshes(AutoScalingGroupName=asg_name).get('InstanceRefreshes', '[]')[0] + if ongoing_refresh.get('Status', '') in ['Cancelling', 'Cancelled']: + module.exit_json(changed=False, msg='In check_mode - Instance Refresh already cancelled or is pending cancellation.') + elif not ongoing_refresh: + module.exit_json(chaned=False, msg='In check_mode - No active referesh found, nothing to cancel.') + else: + module.exit_json(changed=True, msg='Would have cancelled instance refresh if not in check mode.') + result = cmd_invocations[asg_state](aws_retry=True, **args) + instance_refreshes = conn.describe_instance_refreshes(AutoScalingGroupName=asg_name, InstanceRefreshIds=[result['InstanceRefreshId']]) + result = dict( + instance_refreshes=camel_dict_to_snake_dict(instance_refreshes['InstanceRefreshes'][0]) + ) + return module.exit_json(**result) + except (BotoCoreError, ClientError) as e: + module.fail_json_aws( + e, + msg='Failed to {0} InstanceRefresh'.format( + asg_state.replace('ed', '') + ) + ) + + +def main(): + + argument_spec = dict( + state=dict( + type='str', + required=True, + choices=['started', 'cancelled'], + ), + name=dict(required=True), + strategy=dict( + type='str', + default='Rolling', + required=False + ), + preferences=dict( + type='dict', + required=False, + options=dict( + min_healthy_percentage=dict(type='int', default=90), + instance_warmup=dict(type='int'), + ) + ), + ) + + module = AnsibleAWSModule( + argument_spec=argument_spec, + supports_check_mode=True, + ) + autoscaling = module.client( + 'autoscaling', + retry_decorator=AWSRetry.jittered_backoff( + retries=10, + catch_extra_error_codes=['InstanceRefreshInProgress'] + ) + ) + + start_or_cancel_instance_refresh(autoscaling, module) + + +if __name__ == '__main__': + main() diff --git a/plugins/modules/ec2_asg_instance_refresh_info.py b/plugins/modules/ec2_asg_instance_refresh_info.py new file mode 100644 --- /dev/null +++ b/plugins/modules/ec2_asg_instance_refresh_info.py @@ -0,0 +1,219 @@ +#!/usr/bin/python +# Copyright: Ansible Project +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function + + +__metaclass__ = type + + +DOCUMENTATION = ''' +--- +module: ec2_asg_instance_refresh_info +version_added: 3.2.0 +short_description: Gather information about ec2 Auto Scaling Group (ASG) Instance Refreshes in AWS +description: + - Describes one or more instance refreshes. + - You can determine the status of a request by looking at the I(status) parameter. +author: "Dan Khersonsky (@danquixote)" +options: + name: + description: + - The name of the Auto Scaling group. + type: str + required: true + ids: + description: + - One or more instance refresh IDs. + type: list + elements: str + default: [] + next_token: + description: + - The token for the next set of items to return. (You received this token from a previous call.) + type: str + max_records: + description: + - The maximum number of items to return with this call. The default value is 50 and the maximum value is 100. + type: int + required: false +extends_documentation_fragment: +- amazon.aws.aws +- amazon.aws.ec2 + +''' + +EXAMPLES = ''' +# Note: These examples do not set authentication details, see the AWS Guide for details. + +- name: Find an refresh by ASG name + community.aws.ec2_asg_instance_refresh_info: + name: somename-asg + +- name: Find an refresh by ASG name and one or more refresh-IDs + community.aws.ec2_asg_instance_refresh_info: + name: somename-asg + ids: ['some-id-123'] + register: asgs + +- name: Find an refresh by ASG name and set max_records + community.aws.ec2_asg_instance_refresh_info: + name: somename-asg + max_records: 4 + register: asgs + +- name: Find an refresh by ASG name and NextToken, if received from a previous call + community.aws.ec2_asg_instance_refresh_info: + name: somename-asg + next_token: 'some-token-123' + register: asgs +''' + +RETURN = ''' +--- +instance_refresh_id: + description: instance refresh id + returned: success + type: str + sample: "08b91cf7-8fa6-48af-b6a6-d227f40f1b9b" +auto_scaling_group_name: + description: Name of autoscaling group + returned: success + type: str + sample: "public-webapp-production-1" +status: + description: + - The current state of the group when DeleteAutoScalingGroup is in progress. + - The following are the possible statuses + - Pending -- The request was created, but the operation has not started. + - InProgress -- The operation is in progress. + - Successful -- The operation completed successfully. + - Failed -- The operation failed to complete. You can troubleshoot using the status reason and the scaling activities. + - Cancelling -- + - An ongoing operation is being cancelled. + - Cancellation does not roll back any replacements that have already been completed, + - but it prevents new replacements from being started. + - Cancelled -- The operation is cancelled. + returned: success + type: str + sample: "Pending" +start_time: + description: The date and time this ASG was created, in ISO 8601 format. + returned: success + type: str + sample: "2015-11-25T00:05:36.309Z" +end_time: + description: The date and time this ASG was created, in ISO 8601 format. + returned: success + type: str + sample: "2015-11-25T00:05:36.309Z" +percentage_complete: + description: the % of completeness + returned: success + type: int + sample: 100 +instances_to_update: + description: num. of instance to update + returned: success + type: int + sample: 5 +''' + +try: + from botocore.exceptions import BotoCoreError, ClientError +except ImportError: + pass # caught by AnsibleAWSModule + +from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AWSRetry +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import camel_dict_to_snake_dict + + +def find_asg_instance_refreshes(conn, module): + """ + Args: + conn (boto3.AutoScaling.Client): Valid Boto3 ASG client. + module: AnsibleAWSModule object + + Returns: + { + "instance_refreshes": [ + { + 'auto_scaling_group_name': 'ansible-test-hermes-63642726-asg', + 'instance_refresh_id': '6507a3e5-4950-4503-8978-e9f2636efc09', + 'instances_to_update': 1, + 'percentage_complete': 0, + "preferences": { + "instance_warmup": 60, + "min_healthy_percentage": 90, + "skip_matching": false + }, + 'start_time': '2021-02-04T03:39:40+00:00', + 'status': 'Cancelled', + 'status_reason': 'Cancelled due to user request.', + } + ], + 'next_token': 'string' + } + """ + + asg_name = module.params.get('name') + asg_ids = module.params.get('ids') + asg_next_token = module.params.get('next_token') + asg_max_records = module.params.get('max_records') + + args = {} + args['AutoScalingGroupName'] = asg_name + if asg_ids: + args['InstanceRefreshIds'] = asg_ids + if asg_next_token: + args['NextToken'] = asg_next_token + if asg_max_records: + args['MaxRecords'] = asg_max_records + + try: + instance_refreshes_result = {} + response = conn.describe_instance_refreshes(**args) + if 'InstanceRefreshes' in response: + instance_refreshes_dict = dict( + instance_refreshes=response['InstanceRefreshes'], next_token=response.get('next_token', '')) + instance_refreshes_result = camel_dict_to_snake_dict( + instance_refreshes_dict) + + while 'NextToken' in response: + args['NextToken'] = response['NextToken'] + response = conn.describe_instance_refreshes(**args) + if 'InstanceRefreshes' in response: + instance_refreshes_dict = camel_dict_to_snake_dict(dict( + instance_refreshes=response['InstanceRefreshes'], next_token=response.get('next_token', ''))) + instance_refreshes_result.update(instance_refreshes_dict) + + return module.exit_json(**instance_refreshes_result) + except (BotoCoreError, ClientError) as e: + module.fail_json_aws(e, msg='Failed to describe InstanceRefreshes') + + +def main(): + + argument_spec = dict( + name=dict(required=True, type='str'), + ids=dict(required=False, default=[], elements='str', type='list'), + next_token=dict(required=False, default=None, type='str', no_log=True), + max_records=dict(required=False, type='int'), + ) + + module = AnsibleAWSModule( + argument_spec=argument_spec, + supports_check_mode=True, + ) + + autoscaling = module.client( + 'autoscaling', + retry_decorator=AWSRetry.jittered_backoff(retries=10) + ) + find_asg_instance_refreshes(autoscaling, module) + + +if __name__ == '__main__': + main()
diff --git a/tests/integration/targets/ec2_asg_instance_refresh/aliases b/tests/integration/targets/ec2_asg_instance_refresh/aliases new file mode 100644 --- /dev/null +++ b/tests/integration/targets/ec2_asg_instance_refresh/aliases @@ -0,0 +1,2 @@ +cloud/aws +ec2_asg_instance_refresh_info diff --git a/tests/integration/targets/ec2_asg_instance_refresh/defaults/main.yml b/tests/integration/targets/ec2_asg_instance_refresh/defaults/main.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/ec2_asg_instance_refresh/defaults/main.yml @@ -0,0 +1,5 @@ +--- +# defaults file for ec2_asg +vpc_seed: '{{ tiny_prefix }}' +ec2_ami_name: 'amzn2-ami-hvm-2.*-x86_64-gp2' +subnet_a_cidr: '10.{{ 256 | random(seed=vpc_seed) }}.32.0/24' diff --git a/tests/integration/targets/ec2_asg_instance_refresh/tasks/main.yml b/tests/integration/targets/ec2_asg_instance_refresh/tasks/main.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/ec2_asg_instance_refresh/tasks/main.yml @@ -0,0 +1,533 @@ +--- +- name: setup credentials and region + module_defaults: + group/aws: + aws_access_key: "{{ aws_access_key }}" + aws_secret_key: "{{ aws_secret_key }}" + security_token: "{{ security_token | default(omit) }}" + region: "{{ aws_region }}" + + collections: + - amazon.aws + + block: + + #NOTE: entire ASG setup is 'borrowed' from ec2_asg + - name: Find AMI to use + ec2_ami_info: + owners: 'amazon' + filters: + name: '{{ ec2_ami_name }}' + register: ec2_amis + - set_fact: + ec2_ami_image: '{{ ec2_amis.images[0].image_id }}' + + - name: load balancer name has to be less than 32 characters + set_fact: + load_balancer_name: "{{ item }}-lb" + loop: "{{ resource_prefix | regex_findall('.{8}$') }}" + + # Set up the testing dependencies: VPC, subnet, security group, and two launch configurations + - name: Create VPC for use in testing + ec2_vpc_net: + name: "{{ resource_prefix }}-vpc" + cidr_block: '{{ subnet_a_cidr }}' + tenancy: default + register: testing_vpc + + - name: Create internet gateway for use in testing + ec2_vpc_igw: + vpc_id: "{{ testing_vpc.vpc.id }}" + state: present + register: igw + + - name: Create subnet for use in testing + ec2_vpc_subnet: + state: present + vpc_id: "{{ testing_vpc.vpc.id }}" + cidr: '{{ subnet_a_cidr }}' + az: "{{ aws_region }}a" + resource_tags: + Name: "{{ resource_prefix }}-subnet" + register: testing_subnet + + - name: create routing rules + ec2_vpc_route_table: + vpc_id: "{{ testing_vpc.vpc.id }}" + tags: + created: "{{ resource_prefix }}-route" + routes: + - dest: 0.0.0.0/0 + gateway_id: "{{ igw.gateway_id }}" + subnets: + - "{{ testing_subnet.subnet.id }}" + + - name: create a security group with the vpc created in the ec2_setup + ec2_group: + name: "{{ resource_prefix }}-sg" + description: a security group for ansible tests + vpc_id: "{{ testing_vpc.vpc.id }}" + rules: + - proto: tcp + from_port: 22 + to_port: 22 + cidr_ip: 0.0.0.0/0 + - proto: tcp + from_port: 80 + to_port: 80 + cidr_ip: 0.0.0.0/0 + register: sg + + - name: ensure launch configs exist + ec2_lc: + name: "{{ item }}" + assign_public_ip: true + image_id: "{{ ec2_ami_image }}" + user_data: | + package_upgrade: true + package_update: true + packages: + - httpd + runcmd: + - "service httpd start" + security_groups: "{{ sg.group_id }}" + instance_type: t3.micro + loop: + - "{{ resource_prefix }}-lc" + - "{{ resource_prefix }}-lc-2" + + - name: launch asg and do not wait for instances to be deemed healthy (no ELB) + ec2_asg: + name: "{{ resource_prefix }}-asg" + launch_config_name: "{{ resource_prefix }}-lc" + desired_capacity: 1 + min_size: 1 + max_size: 1 + vpc_zone_identifier: "{{ testing_subnet.subnet.id }}" + wait_for_instances: no + state: present + register: output + + - assert: + that: + - "output.viable_instances == 0" + + # ============================================================ + + - name: test invalid cancelation - V1 - (pre-refresh) + ec2_asg_instance_refresh: + name: "{{ resource_prefix }}-asg" + state: "cancelled" + ignore_errors: yes + register: result + + - assert: + that: + - "'An error occurred (ActiveInstanceRefreshNotFound) when calling the CancelInstanceRefresh operation: No in progress or pending Instance Refresh found for Auto Scaling group {{ resource_prefix }}-asg' in result.msg" + + - name: test starting a refresh with a valid ASG name - check_mode + ec2_asg_instance_refresh: + name: "{{ resource_prefix }}-asg" + state: "started" + check_mode: true + register: output + + - assert: + that: + - output is not failed + - output is changed + - '"autoscaling:StartInstanceRefresh" not in output.resource_actions' + + - name: test starting a refresh with a valid ASG name + ec2_asg_instance_refresh: + name: "{{ resource_prefix }}-asg" + state: "started" + register: output + + - assert: + that: + - "'instance_refresh_id' in output.instance_refreshes" + + - name: test starting a refresh with a valid ASG name - Idempotent + ec2_asg_instance_refresh: + name: "{{ resource_prefix }}-asg" + state: "started" + ignore_errors: true + register: output + + - assert: + that: + - output is not changed + - '"Failed to start InstanceRefresh: An error occurred (InstanceRefreshInProgress) when calling the StartInstanceRefresh operation: An Instance Refresh is already in progress and blocks the execution of this Instance Refresh." in output.msg' + + - name: test starting a refresh with a valid ASG name - Idempotent (check_mode) + ec2_asg_instance_refresh: + name: "{{ resource_prefix }}-asg" + state: "started" + ignore_errors: true + check_mode: true + register: output + + - assert: + that: + - output is not changed + - output is not failed + - '"In check_mode - Instance Refresh is already in progress, can not start new instance refresh." in output.msg' + + - name: test starting a refresh with a nonexistent ASG name + ec2_asg_instance_refresh: + name: "nonexistentname-asg" + state: "started" + ignore_errors: yes + register: result + + - assert: + that: + - "'Failed to start InstanceRefresh: An error occurred (ValidationError) when calling the StartInstanceRefresh operation: AutoScalingGroup name not found' in result.msg" + + - name: test canceling a refresh with an ASG name - check_mode + ec2_asg_instance_refresh: + name: "{{ resource_prefix }}-asg" + state: "cancelled" + check_mode: true + register: output + + - assert: + that: + - output is not failed + - output is changed + - '"autoscaling:CancelInstanceRefresh" not in output.resource_actions' + + - name: test canceling a refresh with an ASG name + ec2_asg_instance_refresh: + name: "{{ resource_prefix }}-asg" + state: "cancelled" + register: output + + - assert: + that: + - "'instance_refresh_id' in output.instance_refreshes" + + - name: test canceling a refresh with a ASG name - Idempotent + ec2_asg_instance_refresh: + name: "{{ resource_prefix }}-asg" + state: "cancelled" + ignore_errors: yes + register: output + + - assert: + that: + - output is not changed + + - name: test cancelling a refresh with a valid ASG name - Idempotent (check_mode) + ec2_asg_instance_refresh: + name: "{{ resource_prefix }}-asg" + state: "cancelled" + ignore_errors: true + check_mode: true + register: output + + - assert: + that: + - output is not changed + - output is not failed + + - name: test starting a refresh with an ASG name and preferences dict + ec2_asg_instance_refresh: + name: "{{ resource_prefix }}-asg" + state: "started" + preferences: + min_healthy_percentage: 10 + instance_warmup: 10 + retries: 5 + register: output + until: output is not failed + + - assert: + that: + - "'instance_refresh_id' in output.instance_refreshes" + + - name: re-test canceling a refresh with an ASG name + ec2_asg_instance_refresh: + name: "{{ resource_prefix }}-asg" + state: "cancelled" + register: output + + - assert: + that: + - "'instance_refresh_id' in output.instance_refreshes" + + - name: test valid start - V1 - (with preferences missing instance_warmup) + ec2_asg_instance_refresh: + name: "{{ resource_prefix }}-asg" + state: "started" + preferences: + min_healthy_percentage: 10 + ignore_errors: yes + retries: 5 + register: output + until: output is not failed + + - assert: + that: + - "'instance_refresh_id' in output.instance_refreshes" + + - name: re-test canceling a refresh with an ASG name + ec2_asg_instance_refresh: + name: "{{ resource_prefix }}-asg" + state: "cancelled" + register: output + + - assert: + that: + - "'instance_refresh_id' in output.instance_refreshes" + + - name: test valid start - V2 - (with preferences missing min_healthy_percentage) + ec2_asg_instance_refresh: + name: "{{ resource_prefix }}-asg" + state: "started" + preferences: + instance_warmup: 10 + retries: 5 + register: output + until: output is not failed + ignore_errors: yes + + - assert: + that: + - "'instance_refresh_id' in output.instance_refreshes" + + - name: test invalid cancelation - V2 - (with preferences) + ec2_asg_instance_refresh: + name: "{{ resource_prefix }}-asg" + state: "cancelled" + preferences: + min_healthy_percentage: 10 + instance_warmup: 10 + ignore_errors: yes + register: result + + - assert: + that: + - "'can not pass preferences dict when canceling a refresh' in result.msg" + + # ============================================================ + + - name: run setup with refresh_and_cancel_three_times.yml + include_tasks: refresh_and_cancel_three_times.yml + loop: "{{ query('sequence', 'start=1 end=3') }}" + + - name: test getting info for an ASG name + ec2_asg_instance_refresh_info: + name: "{{ resource_prefix }}-asg" + region: "{{ aws_region }}" + ignore_errors: yes + register: output + + - assert: + that: + - output | community.general.json_query(inst_refresh_id_json_query) | unique | length == 7 + vars: + inst_refresh_id_json_query: instance_refreshes[].instance_refresh_id + + - name: test using fake refresh ID + ec2_asg_instance_refresh_info: + name: "{{ resource_prefix }}-asg" + ids: ['0e367f58-blabla-bla-bla-ca870dc5dbfe'] + ignore_errors: yes + register: output + + - assert: + that: + - "{{ output.instance_refreshes|length }} == 0" + + - name: test using a real refresh ID + ec2_asg_instance_refresh_info: + name: "{{ resource_prefix }}-asg" + ids: [ '{{ refreshout.instance_refreshes.instance_refresh_id }}' ] + ignore_errors: yes + register: output + + - assert: + that: + - "{{ output.instance_refreshes |length }} == 1" + + - name: test getting info for an ASG name which doesn't exist + ec2_asg_instance_refresh_info: + name: n0n3x1stentname27b + ignore_errors: yes + register: output + + - assert: + that: + - "'Failed to describe InstanceRefreshes: An error occurred (ValidationError) when calling the DescribeInstanceRefreshes operation: AutoScalingGroup name not found - AutoScalingGroup n0n3x1stentname27b not found' == output.msg" + + - name: assert that the correct number of records are returned + ec2_asg_instance_refresh_info: + name: "{{ resource_prefix }}-asg" + ignore_errors: yes + register: output + + - assert: + that: + - "{{ output.instance_refreshes|length }} == 7" + + - name: assert that valid message with fake-token is returned + ec2_asg_instance_refresh_info: + name: "{{ resource_prefix }}-asg" + next_token: "fake-token-123" + ignore_errors: yes + register: output + + - assert: + that: + - '"Failed to describe InstanceRefreshes: An error occurred (InvalidNextToken) when calling the DescribeInstanceRefreshes operation: The token ''********'' is invalid." == output.msg' + + - name: assert that max records=1 returns no more than one record + ec2_asg_instance_refresh_info: + name: "{{ resource_prefix }}-asg" + max_records: 1 + ignore_errors: yes + register: output + + - assert: + that: + - "{{ output.instance_refreshes|length }} < 2" + + - name: assert that valid message with real-token is returned + ec2_asg_instance_refresh_info: + name: "{{ resource_prefix }}-asg" + next_token: "{{ output.next_token }}" + ignore_errors: yes + register: output + + - assert: + that: + - "{{ output.instance_refreshes|length }} == 7" + + - name: test using both real nextToken and max_records=1 + ec2_asg_instance_refresh_info: + name: "{{ resource_prefix }}-asg" + max_records: 1 + next_token: "{{ output.next_token }}" + ignore_errors: yes + register: output + + - assert: + that: + - "{{ output.instance_refreshes|length }} == 1" + + always: + + - name: kill asg + ec2_asg: + name: "{{ resource_prefix }}-asg" + state: absent + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10 + # Remove the testing dependencies + + - name: remove the load balancer + ec2_elb_lb: + name: "{{ load_balancer_name }}" + state: absent + security_group_ids: + - "{{ sg.group_id }}" + subnets: "{{ testing_subnet.subnet.id }}" + wait: yes + connection_draining_timeout: 60 + listeners: + - protocol: http + load_balancer_port: 80 + instance_port: 80 + health_check: + ping_protocol: tcp + ping_port: 80 + ping_path: "/" + response_timeout: 5 + interval: 10 + unhealthy_threshold: 4 + healthy_threshold: 2 + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10 + + - name: remove launch configs + ec2_lc: + name: "{{ resource_prefix }}-lc" + state: absent + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10 + loop: + - "{{ resource_prefix }}-lc" + - "{{ resource_prefix }}-lc-2" + + - name: delete launch template + ec2_launch_template: + name: "{{ resource_prefix }}-lt" + state: absent + register: del_lt + retries: 10 + until: del_lt is not failed + ignore_errors: true + + - name: remove the security group + ec2_group: + name: "{{ resource_prefix }}-sg" + description: a security group for ansible tests + vpc_id: "{{ testing_vpc.vpc.id }}" + state: absent + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10 + + - name: remove routing rules + ec2_vpc_route_table: + state: absent + vpc_id: "{{ testing_vpc.vpc.id }}" + tags: + created: "{{ resource_prefix }}-route" + routes: + - dest: 0.0.0.0/0 + gateway_id: "{{ igw.gateway_id }}" + subnets: + - "{{ testing_subnet.subnet.id }}" + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10 + + - name: remove internet gateway + ec2_vpc_igw: + vpc_id: "{{ testing_vpc.vpc.id }}" + state: absent + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10 + + - name: remove the subnet + ec2_vpc_subnet: + state: absent + vpc_id: "{{ testing_vpc.vpc.id }}" + cidr: '{{ subnet_a_cidr }}' + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10 + + - name: remove the VPC + ec2_vpc_net: + name: "{{ resource_prefix }}-vpc" + cidr_block: '{{ subnet_a_cidr }}' + state: absent + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10 diff --git a/tests/integration/targets/ec2_asg_instance_refresh/tasks/refresh_and_cancel_three_times.yml b/tests/integration/targets/ec2_asg_instance_refresh/tasks/refresh_and_cancel_three_times.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/ec2_asg_instance_refresh/tasks/refresh_and_cancel_three_times.yml @@ -0,0 +1,29 @@ +--- + +- name: try to cancel pre-loop + ec2_asg_instance_refresh: + name: "{{ resource_prefix }}-asg" + state: "cancelled" + ignore_errors: yes + +- name: test starting a refresh with an ASG name + ec2_asg_instance_refresh: + name: "{{ resource_prefix }}-asg" + state: "started" + aws_access_key: "{{ aws_access_key }}" + aws_secret_key: "{{ aws_secret_key }}" + region: "{{ aws_region }}" + ignore_errors: no + retries: 10 + delay: 5 + register: refreshout + until: refreshout is not failed + +- name: test cancelling a refresh with an ASG name + ec2_asg_instance_refresh: + name: "{{ resource_prefix }}-asg" + state: "cancelled" + aws_access_key: "{{ aws_access_key }}" + aws_secret_key: "{{ aws_secret_key }}" + region: "{{ aws_region }}" + ignore_errors: yes diff --git a/tests/integration/targets/ec2_asg_instance_refresh/vars/main.yml b/tests/integration/targets/ec2_asg_instance_refresh/vars/main.yml new file mode 100644
Autoscaling instance refresh API support <!--- Verify first that your feature was not already discussed on GitHub --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Describe the new feature/improvement briefly below --> AWS recently introduced "Instance refresh" feature in ASG. Using it is preferred way to update launch configuration in ASG ##### ISSUE TYPE - Feature Idea ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> ec2_asg ##### ADDITIONAL INFORMATION <!--- Describe how the feature would be used, why it is needed and what it would solve --> Deploying ASG from the client depends on internet connectivity and is not transactional. In the middle of deployment of ASG it can fail leaving ASG in unpredicted state. Using AWS infrastructure will add more stability in deployment (and probably will make it faster) More about the feature: https://aws.amazon.com/blogs/compute/introducing-instance-refresh-for-ec2-auto-scaling/ Boto3 documentation: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/autoscaling.html#AutoScaling.Client.start_instance_refresh <!--- Paste example playbooks or commands between quotes below --> ```yaml - commutiny.aws.ec2_asg_instance_refresh: name: some-backend ``` <!--- HINT: You can also paste gist.github.com links for larger files -->
Files identified in the description: * [`plugins/modules/ec2_asg.py`](https://github.com/ansible-collections/community.aws/blob/main/plugins/modules/ec2_asg.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @garethr @jillr @s-hertel @tremble @wimnat [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify --->
2022-03-10T01:24:08
ansible-collections/community.aws
978
ansible-collections__community.aws-978
[ "891" ]
7738a1ff738c390e91c9e8589aef0e1de1f2829e
diff --git a/plugins/modules/elb_target_group.py b/plugins/modules/elb_target_group.py --- a/plugins/modules/elb_target_group.py +++ b/plugins/modules/elb_target_group.py @@ -76,13 +76,14 @@ type: str port: description: - - The port on which the targets receive traffic. This port is used unless you specify a port override when registering the target. Required if - I(state) is C(present). + - The port on which the targets receive traffic. This port is used unless you specify a port override when registering the target. + - Required when I(state) is C(present) and I(target_type) is C(instance), C(ip), or C(alb). required: false type: int protocol: description: - - The protocol to use for routing traffic to the targets. Required when I(state) is C(present). + - The protocol to use for routing traffic to the targets. + - Required when I(state) is C(present) and I(target_type) is C(instance), C(ip), or C(alb). required: false choices: [ 'http', 'https', 'tcp', 'tls', 'udp', 'tcp_udp', 'HTTP', 'HTTPS', 'TCP', 'TLS', 'UDP', 'TCP_UDP'] type: str @@ -141,15 +142,16 @@ target_type: description: - The type of target that you must specify when registering targets with this target group. The possible values are - C(instance) (targets are specified by instance ID), C(ip) (targets are specified by IP address) or C(lambda) (target is specified by ARN). - Note that you can't specify targets for a target group using more than one type. Target type lambda only accept one target. When more than + C(instance) (targets are specified by instance ID), C(ip) (targets are specified by IP address), C(lambda) (target is specified by ARN), + or C(alb) (target is specified by ARN). + Note that you can't specify targets for a target group using more than one type. Target types lambda and alb only accept one target. When more than one target is specified, only the first one is used. All additional targets are ignored. If the target type is ip, specify IP addresses from the subnets of the virtual private cloud (VPC) for the target group, the RFC 1918 range (10.0.0.0/8, 172.16.0.0/12, and 192.168.0.0/16), and the RFC 6598 range (100.64.0.0/10). You can't specify publicly routable IP addresses. - The default behavior is C(instance). required: false - choices: ['instance', 'ip', 'lambda'] + choices: ['instance', 'ip', 'lambda', 'alb'] type: str targets: description: @@ -165,7 +167,8 @@ type: int vpc_id: description: - - The identifier of the virtual private cloud (VPC). Required when I(state) is C(present). + - The identifier of the virtual private cloud (VPC). + - Required when I(state) is C(present) and I(target_type) is C(instance), C(ip), or C(alb). required: false type: str preserve_client_ip_enabled: @@ -891,7 +894,7 @@ def main(): state=dict(required=True, choices=['present', 'absent']), successful_response_codes=dict(), tags=dict(default={}, type='dict'), - target_type=dict(choices=['instance', 'ip', 'lambda']), + target_type=dict(choices=['instance', 'ip', 'lambda', 'alb']), targets=dict(type='list', elements='dict'), unhealthy_threshold_count=dict(type='int'), vpc_id=dict(), @@ -905,6 +908,7 @@ def main(): required_if=[ ['target_type', 'instance', ['protocol', 'port', 'vpc_id']], ['target_type', 'ip', ['protocol', 'port', 'vpc_id']], + ['target_type', 'alb', ['protocol', 'port', 'vpc_id']], ] )
diff --git a/tests/integration/targets/elb_target/tasks/alb_target.yml b/tests/integration/targets/elb_target/tasks/alb_target.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/elb_target/tasks/alb_target.yml @@ -0,0 +1,205 @@ +--- +- name: test elb_target_group with target_type = alb + block: + - name: set up testing VPC + ec2_vpc_net: + name: "{{ resource_prefix }}-vpc" + state: present + cidr_block: 20.0.0.0/16 + tags: + Name: "{{ resource_prefix }}-vpc" + Description: "Created by ansible-test" + register: vpc + + - name: set up testing internet gateway + ec2_vpc_igw: + vpc_id: "{{ vpc.vpc.id }}" + state: present + register: igw + + - name: set up testing subnet + ec2_vpc_subnet: + state: present + vpc_id: "{{ vpc.vpc.id }}" + cidr: 20.0.0.0/18 + az: "{{ aws_region }}a" + resource_tags: + Name: "{{ resource_prefix }}-subnet" + register: subnet_1 + + - name: set up testing subnet + ec2_vpc_subnet: + state: present + vpc_id: "{{ vpc.vpc.id }}" + cidr: 20.0.64.0/18 + az: "{{ aws_region }}b" + resource_tags: + Name: "{{ resource_prefix }}-subnet" + register: subnet_2 + + - name: create routing rules + ec2_vpc_route_table: + vpc_id: "{{ vpc.vpc.id }}" + tags: + created: "{{ resource_prefix }}-route" + routes: + - dest: 0.0.0.0/0 + gateway_id: "{{ igw.gateway_id }}" + subnets: + - "{{ subnet_1.subnet.id }}" + - "{{ subnet_2.subnet.id }}" + register: route_table + + - name: create testing security group + ec2_group: + name: "{{ resource_prefix }}-sg" + description: a security group for ansible tests + vpc_id: "{{ vpc.vpc.id }}" + rules: + - proto: tcp + from_port: 80 + to_port: 80 + cidr_ip: 0.0.0.0/0 + - proto: tcp + from_port: 22 + to_port: 22 + cidr_ip: 0.0.0.0/0 + register: sg + + - name: set up testing target group for NLB (type=alb) + elb_target_group: + name: "{{ elb_target_group_name }}" + target_type: alb + state: present + protocol: TCP + port: 80 + vpc_id: "{{ vpc.vpc.id }}" + register: elb_target_group + + - name: assert target group was created successfully + assert: + that: + - elb_target_group.changed + - elb_target_group.target_group_name == elb_target_group_name + - elb_target_group.target_type == 'alb' + - elb_target_group.vpc_id == vpc.vpc.id + - elb_target_group.port == 80 + - elb_target_group.protocol == 'TCP' + - elb_target_group.load_balancer_arns | length == 0 + + - name: create a network load balancer and attach to target group + elb_network_lb: + name: "{{ lb_name }}-nlb" + subnets: + - "{{ subnet_1.subnet.id }}" + - "{{ subnet_2.subnet.id }}" + listeners: + - Protocol: TCP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ elb_target_group_name }}" + state: present + register: nlb + + - name: assert NLB was created successfully and attached to target group + assert: + that: + - nlb is changed + - nlb.listeners | length == 1 + - nlb.listeners[0].default_actions[0].forward_config.target_groups[0].target_group_arn == elb_target_group.target_group_arn + + - name: get target group info + elb_target_group_info: + load_balancer_arn: "{{ nlb.load_balancer_arn }}" + register: tg_info + + - name: assert target group's target is nlb + assert: + that: + - tg_info.target_groups[0].target_group_name == elb_target_group_name + - tg_info.target_groups[0].target_type == 'alb' + - tg_info.target_groups[0].load_balancer_arns | length == 1 + - tg_info.target_groups[0].load_balancer_arns[0] == nlb.load_balancer_arn + + always: + - name: remove network load balancer + elb_network_lb: + name: "{{ lb_name }}-nlb" + state: absent + wait: true + wait_timeout: 600 + register: removed + retries: 10 + until: removed is not failed + ignore_errors: true + + - name: remove elb target group + elb_target_group: + name: "{{ elb_target_group_name }}" + target_type: alb + state: absent + protocol: HTTP + port: 80 + vpc_id: "{{ vpc.vpc.id }}" + ignore_errors: true + + - name: remove routing rules + ec2_vpc_route_table: + state: absent + lookup: id + route_table_id: "{{ route_table.route_table.id }}" + register: removed + retries: 5 + until: removed is not failed + ignore_errors: true + + - name: remove testing subnet + ec2_vpc_subnet: + state: absent + vpc_id: "{{ vpc.vpc.id }}" + cidr: 20.0.0.0/18 + az: "{{ aws_region }}a" + register: removed + retries: 10 + until: removed is not failed + ignore_errors: true + + - name: remove testing subnet + ec2_vpc_subnet: + state: absent + vpc_id: "{{ vpc.vpc.id }}" + cidr: 20.0.64.0/18 + az: "{{ aws_region }}b" + register: removed + retries: 10 + until: removed is not failed + ignore_errors: true + + - name: remove testing security group + ec2_group: + state: absent + name: "{{ resource_prefix }}-sg" + register: removed + retries: 10 + until: removed is not failed + ignore_errors: true + + - name: remove testing internet gateway + ec2_vpc_igw: + vpc_id: "{{ vpc.vpc.id }}" + state: absent + register: removed + retries: 2 + until: removed is not failed + ignore_errors: true + + - name: remove testing VPC + ec2_vpc_net: + name: "{{ resource_prefix }}-vpc" + cidr_block: 20.0.0.0/16 + state: absent + register: removed + retries: 2 + until: removed is not failed + ignore_errors: true \ No newline at end of file diff --git a/tests/integration/targets/elb_target/tasks/lambda_target.yml b/tests/integration/targets/elb_target/tasks/lambda_target.yml --- a/tests/integration/targets/elb_target/tasks/lambda_target.yml +++ b/tests/integration/targets/elb_target/tasks/lambda_target.yml @@ -91,7 +91,7 @@ targets: [] register: elb_target_group - - name: target is still the same, state must not be changed (idempotency) + - name: remove lambda target from target group assert: that: - elb_target_group.changed diff --git a/tests/integration/targets/elb_target/tasks/main.yml b/tests/integration/targets/elb_target/tasks/main.yml --- a/tests/integration/targets/elb_target/tasks/main.yml +++ b/tests/integration/targets/elb_target/tasks/main.yml @@ -12,3 +12,4 @@ block: - include_tasks: ec2_target.yml - include_tasks: lambda_target.yml + - include_tasks: alb_target.yml
elb_target_group: support target_type alb ### Summary Add support for `target_type: alb` Currently only `instance`, `ip`, and `lambda` are supported. ### Issue Type Feature Idea ### Component Name elb_target_group ### Additional Information <!--- Paste example playbooks or commands between quotes below --> ```yaml (paste below) ``` ### Code of Conduct - [X] I agree to follow the Ansible Code of Conduct
Added a PR for this cc @jillr @s-hertel @tremble [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify --->
2022-03-11T09:33:15
ansible-collections/community.aws
982
ansible-collections__community.aws-982
[ "481" ]
88dcf46598125da906d967c198a76227d9b9a5d4
diff --git a/plugins/modules/ec2_asg.py b/plugins/modules/ec2_asg.py --- a/plugins/modules/ec2_asg.py +++ b/plugins/modules/ec2_asg.py @@ -182,6 +182,21 @@ matching the current launch configuration. type: list elements: str + detach_instances: + description: + - Removes one or more instances from the specified AutoScalingGroup. + - If I(decrement_desired_capacity) flag is not set, new instance(s) are launched to replace the detached instance(s). + - If a Classic Load Balancer is attached to the AutoScalingGroup, the instances are also deregistered from the load balancer. + - If there are target groups attached to the AutoScalingGroup, the instances are also deregistered from the target groups. + type: list + elements: str + version_added: 3.2.0 + decrement_desired_capacity: + description: + - Indicates whether the AutoScalingGroup decrements the desired capacity value by the number of instances detached. + default: false + type: bool + version_added: 3.2.0 lc_check: description: - Check to make sure instances that are being replaced with I(replace_instances) do not already have the current I(launch_config). @@ -205,6 +220,13 @@ - When I(propagate_at_launch) is true the tags will be propagated to the Instances created. type: list elements: dict + purge_tags: + description: + - If C(true), existing tags will be purged from the resource to match exactly what is defined by I(tags) parameter. + - If the I(tags) parameter is not set then tags will not be modified. + default: true + type: bool + version_added: 3.2.0 health_check_period: description: - Length of time in seconds after a new EC2 instance comes into service that Auto Scaling starts checking its health. @@ -630,6 +652,7 @@ from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AWSRetry from ansible_collections.amazon.aws.plugins.module_utils.ec2 import snake_dict_to_camel_dict from ansible_collections.amazon.aws.plugins.module_utils.ec2 import camel_dict_to_snake_dict +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import ansible_dict_to_boto3_filter_list ASG_ATTRIBUTES = ('AvailabilityZones', 'DefaultCooldown', 'DesiredCapacity', 'HealthCheckGracePeriod', 'HealthCheckType', 'LaunchConfigurationName', @@ -756,6 +779,12 @@ def terminate_asg_instance(connection, instance_id, decrement_capacity): ShouldDecrementDesiredCapacity=decrement_capacity) [email protected]_backoff(**backoff_params) +def detach_asg_instances(connection, instance_ids, as_group_name, decrement_capacity): + connection.detach_instances(InstanceIds=instance_ids, AutoScalingGroupName=as_group_name, + ShouldDecrementDesiredCapacity=decrement_capacity) + + def enforce_required_arguments_for_create(): ''' As many arguments are not required for autoscale group deletion they cannot be mandatory arguments for the module, so we enforce @@ -1076,6 +1105,7 @@ def create_autoscaling_group(connection): desired_capacity = module.params.get('desired_capacity') vpc_zone_identifier = module.params.get('vpc_zone_identifier') set_tags = module.params.get('tags') + purge_tags = module.params.get('purge_tags') health_check_period = module.params.get('health_check_period') health_check_type = module.params.get('health_check_type') default_cooldown = module.params.get('default_cooldown') @@ -1184,9 +1214,12 @@ def create_autoscaling_group(connection): changed = True # process tag changes + have_tags = as_group.get('Tags') + want_tags = asg_tags + if purge_tags and not want_tags and have_tags: + connection.delete_tags(Tags=list(have_tags)) + if len(set_tags) > 0: - have_tags = as_group.get('Tags') - want_tags = asg_tags if have_tags: have_tags.sort(key=lambda x: x["Key"]) if want_tags: @@ -1197,9 +1230,11 @@ def create_autoscaling_group(connection): for dead_tag in set(have_tag_keyvals).difference(want_tag_keyvals): changed = True - dead_tags.append(dict(ResourceId=as_group['AutoScalingGroupName'], - ResourceType='auto-scaling-group', Key=dead_tag)) + if purge_tags: + dead_tags.append(dict( + ResourceId=as_group['AutoScalingGroupName'], ResourceType='auto-scaling-group', Key=dead_tag)) have_tags = [have_tag for have_tag in have_tags if have_tag['Key'] != dead_tag] + if dead_tags: connection.delete_tags(Tags=dead_tags) @@ -1523,6 +1558,40 @@ def replace(connection): return changed, asg_properties +def detach(connection): + group_name = module.params.get('name') + detach_instances = module.params.get('detach_instances') + as_group = describe_autoscaling_groups(connection, group_name)[0] + decrement_desired_capacity = module.params.get('decrement_desired_capacity') + min_size = module.params.get('min_size') + props = get_properties(as_group) + instances = props['instances'] + + # check if provided instance exists in asg, create list of instances to detach which exist in asg + instances_to_detach = [] + for instance_id in detach_instances: + if instance_id in instances: + instances_to_detach.append(instance_id) + + # check if setting decrement_desired_capacity will make desired_capacity smaller + # than the currently set minimum size in ASG configuration + if decrement_desired_capacity: + decremented_desired_capacity = len(instances) - len(instances_to_detach) + if min_size and min_size > decremented_desired_capacity: + module.fail_json( + msg="Detaching instance(s) with 'decrement_desired_capacity' flag set reduces number of instances to {0}\ + which is below current min_size {1}, please update AutoScalingGroup Sizes properly.".format(decremented_desired_capacity, min_size)) + + if instances_to_detach: + try: + detach_asg_instances(connection, instances_to_detach, group_name, decrement_desired_capacity) + except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: + module.fail_json_aws(e, msg="Failed to detach instances from AutoScaling Group") + + asg_properties = get_properties(as_group) + return True, asg_properties + + def get_instances_by_launch_config(props, lc_check, initial_instances): new_instances = [] old_instances = [] @@ -1776,11 +1845,14 @@ def main(): replace_batch_size=dict(type='int', default=1), replace_all_instances=dict(type='bool', default=False), replace_instances=dict(type='list', default=[], elements='str'), + detach_instances=dict(type='list', default=[], elements='str'), + decrement_desired_capacity=dict(type='bool', default=False), lc_check=dict(type='bool', default=True), lt_check=dict(type='bool', default=True), wait_timeout=dict(type='int', default=300), state=dict(default='present', choices=['present', 'absent']), tags=dict(type='list', default=[], elements='dict'), + purge_tags=dict(type='bool', default=True), health_check_period=dict(type='int', default=300), health_check_type=dict(default='EC2', choices=['EC2', 'ELB']), default_cooldown=dict(type='int', default=300), @@ -1821,16 +1893,18 @@ def main(): argument_spec=argument_spec, mutually_exclusive=[ ['replace_all_instances', 'replace_instances'], - ['launch_config_name', 'launch_template'] + ['replace_all_instances', 'detach_instances'], + ['launch_config_name', 'launch_template'], ] ) state = module.params.get('state') replace_instances = module.params.get('replace_instances') replace_all_instances = module.params.get('replace_all_instances') + detach_instances = module.params.get('detach_instances') connection = module.client('autoscaling') - changed = create_changed = replace_changed = False + changed = create_changed = replace_changed = detach_changed = False exists = asg_exists(connection) if state == 'present': @@ -1847,7 +1921,15 @@ def main(): ): replace_changed, asg_properties = replace(connection) - if create_changed or replace_changed: + # Only detach instances if asg existed at start of call + if ( + exists + and (detach_instances) + and (module.params.get('launch_config_name') or module.params.get('launch_template')) + ): + detach_changed, asg_properties = detach(connection) + + if create_changed or replace_changed or detach_changed: changed = True module.exit_json(changed=changed, **asg_properties)
diff --git a/tests/integration/targets/ec2_asg/tasks/instance_detach.yml b/tests/integration/targets/ec2_asg/tasks/instance_detach.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/ec2_asg/tasks/instance_detach.yml @@ -0,0 +1,208 @@ +- name: Running instance detach tests + block: + #---------------------------------------------------------------------- + - name: create a launch configuration + ec2_lc: + name: "{{ resource_prefix }}-lc-detach-test" + image_id: "{{ ec2_ami_image }}" + region: "{{ aws_region }}" + instance_type: t2.micro + assign_public_ip: yes + register: create_lc + + - name: ensure that lc is created + assert: + that: + - create_lc is changed + - create_lc.failed is false + - '"autoscaling:CreateLaunchConfiguration" in create_lc.resource_actions' + + #---------------------------------------------------------------------- + - name: create a AutoScalingGroup to be used for instance_detach test + ec2_asg: + name: "{{ resource_prefix }}-asg-detach-test" + launch_config_name: "{{ resource_prefix }}-lc-detach-test" + health_check_period: 60 + health_check_type: ELB + replace_all_instances: yes + min_size: 3 + max_size: 6 + desired_capacity: 3 + region: "{{ aws_region }}" + register: create_asg + + - name: ensure that AutoScalingGroup is created + assert: + that: + - create_asg is changed + - create_asg.failed is false + - create_asg.instances | length == 3 + - create_asg.desired_capacity == 3 + - create_asg.in_service_instances == 3 + - '"autoscaling:CreateAutoScalingGroup" in create_asg.resource_actions' + + - name: gather info about asg, get instance ids + ec2_asg_info: + name: "{{ resource_prefix }}-asg-detach-test" + register: asg_info + - set_fact: + init_instance_1: "{{ asg_info.results[0].instances[0].instance_id }}" + init_instance_2: "{{ asg_info.results[0].instances[1].instance_id }}" + init_instance_3: "{{ asg_info.results[0].instances[2].instance_id }}" + + - name: Gather information about recently detached instances + amazon.aws.ec2_instance_info: + instance_ids: + - "{{ init_instance_1 }}" + - "{{ init_instance_2 }}" + - "{{ init_instance_3 }}" + register: instances_info + + # assert that there are 3 instances running in the AutoScalingGroup + - assert: + that: + - asg_info.results[0].instances | length == 3 + - "'{{ instances_info.instances[0].state.name }}' == 'running'" + - "'{{ instances_info.instances[1].state.name }}' == 'running'" + - "'{{ instances_info.instances[2].state.name }}' == 'running'" + + #---------------------------------------------------------------------- + + - name: detach 2 instance from the asg and replace with other instances + ec2_asg: + name: "{{ resource_prefix }}-asg-detach-test" + launch_config_name: "{{ resource_prefix }}-lc-detach-test" + health_check_period: 60 + health_check_type: ELB + min_size: 3 + max_size: 3 + desired_capacity: 3 + region: "{{ aws_region }}" + detach_instances: + - '{{ init_instance_1 }}' + - '{{ init_instance_2 }}' + + # pause to allow completion of instance replacement + - name: Pause for 30 seconds + pause: + seconds: 30 + + # gather info about asg and get instance ids + - ec2_asg_info: + name: "{{ resource_prefix }}-asg-detach-test" + register: asg_info_replaced + - set_fact: + instance_replace_1: "{{ asg_info_replaced.results[0].instances[0].instance_id }}" + instance_replace_2: "{{ asg_info_replaced.results[0].instances[1].instance_id }}" + instance_replace_3: "{{ asg_info_replaced.results[0].instances[2].instance_id }}" + + # create a list of instance currently attached to asg + - set_fact: + asg_instance_detach_replace: "{{ asg_info_replaced.results[0].instances | map(attribute='instance_id') | list }}" + + - name: Gather information about recently detached instances + amazon.aws.ec2_instance_info: + instance_ids: + - "{{ init_instance_1 }}" + - "{{ init_instance_2 }}" + register: detached_instances_info + + # assert that + # there are 3 still instances in the AutoScalingGroup + # two specified instances are detached and still running independently(not terminated) + - assert: + that: + - asg_info_replaced.results[0].desired_capacity == 3 + - asg_info_replaced.results[0].instances | length == 3 + - "'{{ init_instance_1 }}' not in {{ asg_instance_detach_replace }}" + - "'{{ init_instance_2 }}' not in {{ asg_instance_detach_replace }}" + - "'{{ detached_instances_info.instances[0].state.name }}' == 'running'" + - "'{{ detached_instances_info.instances[1].state.name }}' == 'running'" + + #---------------------------------------------------------------------- + + # detach 2 instances from the asg and reduce the desired capacity from 3 to 1 + - name: detach 2 instance from the asg and reduce the desired capacity from 3 to 1 + ec2_asg: + name: "{{ resource_prefix }}-asg-detach-test" + launch_config_name: "{{ resource_prefix }}-lc-detach-test" + health_check_period: 60 + health_check_type: ELB + min_size: 1 + max_size: 5 + desired_capacity: 3 + region: "{{ aws_region }}" + decrement_desired_capacity: true + detach_instances: + - '{{ instance_replace_1 }}' + - '{{ instance_replace_2 }}' + + - name: Pause for 30 seconds to allow completion of above task + pause: + seconds: 30 + + # gather information about asg and get instance id + - ec2_asg_info: + name: "{{ resource_prefix }}-asg-detach-test" + register: asg_info_decrement + - set_fact: + instance_detach_decrement: "{{ asg_info_decrement.results[0].instances[0].instance_id }}" + # create a list of instance ids from info result and set variable value to instance ID + - set_fact: + asg_instance_detach_decrement: "{{ asg_info_decrement.results[0].instances | map(attribute='instance_id') | list }}" + + - name: Gather information about recently detached instances + amazon.aws.ec2_instance_info: + instance_ids: + - "{{ instance_replace_1 }}" + - "{{ instance_replace_2 }}" + register: detached_instances_info + + # assert that + # detached instances are not replaced and there is only 1 instance in the AutoScalingGroup + # desired capacity is reduced to 1 + # detached instances are not terminated + - assert: + that: + - asg_info_decrement.results[0].instances | length == 1 + - asg_info_decrement.results[0].desired_capacity == 1 + - "'{{ instance_replace_1 }}' not in {{ asg_instance_detach_decrement }}" + - "'{{ instance_replace_2 }}' not in {{ asg_instance_detach_decrement }}" + - "'{{ detached_instances_info.instances[0].state.name }}' == 'running'" + - "'{{ detached_instances_info.instances[1].state.name }}' == 'running'" + - "'{{ instance_replace_3 }}' == '{{ instance_detach_decrement }}'" + + #---------------------------------------------------------------------- + + always: + + - name: terminate any instances created during this test + amazon.aws.ec2_instance: + instance_ids: + - "{{ item }}" + state: absent + loop: + - "{{ init_instance_1 }}" + - "{{ init_instance_2 }}" + - "{{ init_instance_3 }}" + - "{{ instance_replace_1 }}" + - "{{ instance_replace_2 }}" + - "{{ instance_replace_3 }}" + + - name: kill asg created in this test + ec2_asg: + name: "{{ resource_prefix }}-asg-detach-test" + state: absent + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10 + + - name: remove launch config created in this test + ec2_lc: + name: "{{ resource_prefix }}-lc-detach-test" + state: absent + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10 diff --git a/tests/integration/targets/ec2_asg/tasks/main.yml b/tests/integration/targets/ec2_asg/tasks/main.yml --- a/tests/integration/targets/ec2_asg/tasks/main.yml +++ b/tests/integration/targets/ec2_asg/tasks/main.yml @@ -30,7 +30,6 @@ aws_secret_key: "{{ aws_secret_key }}" security_token: "{{ security_token | default(omit) }}" region: "{{ aws_region }}" - collections: - amazon.aws @@ -106,6 +105,10 @@ cidr_ip: 0.0.0.0/0 register: sg + - include_tasks: tag_operations.yml + + - include_tasks: instance_detach.yml + - name: ensure launch configs exist ec2_lc: name: "{{ item }}" @@ -143,62 +146,6 @@ that: - "output.viable_instances == 1" - - name: Tag asg - ec2_asg: - name: "{{ resource_prefix }}-asg" - tags: - - tag_a: 'value 1' - propagate_at_launch: no - - tag_b: 'value 2' - propagate_at_launch: yes - register: output - - - assert: - that: - - "output.tags | length == 2" - - output is changed - - - name: Re-Tag asg (different order) - ec2_asg: - name: "{{ resource_prefix }}-asg" - tags: - - tag_b: 'value 2' - propagate_at_launch: yes - - tag_a: 'value 1' - propagate_at_launch: no - register: output - - - assert: - that: - - "output.tags | length == 2" - - output is not changed - - - name: Re-Tag asg new tags - ec2_asg: - name: "{{ resource_prefix }}-asg" - tags: - - tag_c: 'value 3' - propagate_at_launch: no - register: output - - - assert: - that: - - "output.tags | length == 1" - - output is changed - - - name: Re-Tag asg update propagate_at_launch - ec2_asg: - name: "{{ resource_prefix }}-asg" - tags: - - tag_c: 'value 3' - propagate_at_launch: yes - register: output - - - assert: - that: - - "output.tags | length == 1" - - output is changed - - name: Enable metrics collection ec2_asg: name: "{{ resource_prefix }}-asg" diff --git a/tests/integration/targets/ec2_asg/tasks/tag_operations.yml b/tests/integration/targets/ec2_asg/tasks/tag_operations.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/ec2_asg/tasks/tag_operations.yml @@ -0,0 +1,352 @@ +- name: Running AutoScalingGroup Tag operations test + block: + #---------------------------------------------------------------------- + - name: create a launch configuration + ec2_lc: + name: "{{ resource_prefix }}-lc-tag-test" + image_id: "{{ ec2_ami_image }}" + region: "{{ aws_region }}" + instance_type: t2.micro + assign_public_ip: yes + register: create_lc + + - name: ensure that lc is created + assert: + that: + - create_lc is changed + - create_lc.failed is false + - '"autoscaling:CreateLaunchConfiguration" in create_lc.resource_actions' + + #---------------------------------------------------------------------- + - name: create a AutoScalingGroup to be used for tag_operations test + ec2_asg: + name: "{{ resource_prefix }}-asg-tag-test" + launch_config_name: "{{ resource_prefix }}-lc-tag-test" + health_check_period: 60 + health_check_type: ELB + replace_all_instances: yes + min_size: 1 + max_size: 1 + desired_capacity: 1 + region: "{{ aws_region }}" + register: create_asg + + - name: ensure that AutoScalingGroup is created + assert: + that: + - create_asg is changed + - create_asg.failed is false + - '"autoscaling:CreateAutoScalingGroup" in create_asg.resource_actions' + + #---------------------------------------------------------------------- + + - name: Get asg info + ec2_asg_info: + name: "{{ resource_prefix }}-asg-tag-test" + register: info_result + + - assert: + that: + - info_result.results[0].tags | length == 0 + + - name: Tag asg + ec2_asg: + name: "{{ resource_prefix }}-asg-tag-test" + tags: + - tag_a: 'value 1' + propagate_at_launch: no + - tag_b: 'value 2' + propagate_at_launch: yes + register: output + + - assert: + that: + - "output.tags | length == 2" + - output is changed + + - name: Re-Tag asg (different order) + ec2_asg: + name: "{{ resource_prefix }}-asg-tag-test" + tags: + - tag_b: 'value 2' + propagate_at_launch: yes + - tag_a: 'value 1' + propagate_at_launch: no + register: output + + - assert: + that: + - "output.tags | length == 2" + - output is not changed + + - name: Re-Tag asg new tags + ec2_asg: + name: "{{ resource_prefix }}-asg-tag-test" + tags: + - tag_c: 'value 3' + propagate_at_launch: no + register: output + + - assert: + that: + - "output.tags | length == 1" + - output is changed + + - name: Re-Tag asg update propagate_at_launch + ec2_asg: + name: "{{ resource_prefix }}-asg-tag-test" + tags: + - tag_c: 'value 3' + propagate_at_launch: yes + register: output + + - assert: + that: + - "output.tags | length == 1" + - output is changed + + - name: Remove all tags + ec2_asg: + name: "{{ resource_prefix }}-asg-tag-test" + tags: [] + register: add_empty + + - name: Get asg info + ec2_asg_info: + name: "{{ resource_prefix }}-asg-tag-test" + register: info_result + # create a list of tag_keys from info result + - set_fact: + tag_keys: "{{ info_result.results[0].tags | map(attribute='key') | list }}" + + - assert: + that: + - add_empty is changed + - info_result.results[0].tags | length == 0 + - '"autoscaling:CreateOrUpdateTags" not in add_empty.resource_actions' + - '"autoscaling:DeleteTags" in add_empty.resource_actions' + + - name: Add 4 new tags - do not purge existing tags + ec2_asg: + name: "{{ resource_prefix }}-asg-tag-test" + tags: + - lowercase spaced: "hello cruel world" + propagate_at_launch: no + - Title Case: "Hello Cruel World" + propagate_at_launch: yes + - CamelCase: "SimpleCamelCase" + propagate_at_launch: yes + - snake_case: "simple_snake_case" + propagate_at_launch: no + purge_tags: false + register: add_result + + - name: Get asg info + ec2_asg_info: + name: "{{ resource_prefix }}-asg-tag-test" + register: info_result + # create a list of tag_keys from info result + - set_fact: + tag_keys: "{{ info_result.results[0].tags | map(attribute='key') | list }}" + + - assert: + that: + - add_result is changed + - info_result.results[0].tags | length == 4 + - '"lowercase spaced" in tag_keys' + - '"Title Case" in tag_keys' + - '"CamelCase" in tag_keys' + - '"snake_case" in tag_keys' + - '"autoscaling:CreateOrUpdateTags" in add_result.resource_actions' + + - name: Add 4 new tags - do not purge existing tags - idempotency + ec2_asg: + name: "{{ resource_prefix }}-asg-tag-test" + tags: + - lowercase spaced: "hello cruel world" + propagate_at_launch: no + - Title Case: "Hello Cruel World" + propagate_at_launch: yes + - CamelCase: "SimpleCamelCase" + propagate_at_launch: yes + - snake_case: "simple_snake_case" + propagate_at_launch: no + purge_tags: false + register: add_result + + - name: Get asg info + ec2_asg_info: + name: "{{ resource_prefix }}-asg-tag-test" + register: info_result + + - assert: + that: + - add_result is not changed + - info_result.results[0].tags | length == 4 + - '"autoscaling:CreateOrUpdateTags" not in add_result.resource_actions' + + - name: Add 2 new tags - purge existing tags + ec2_asg: + name: "{{ resource_prefix }}-asg-tag-test" + tags: + - tag_a: 'val_a' + propagate_at_launch: no + - tag_b: 'val_b' + propagate_at_launch: yes + register: add_purge_result + + - name: Get asg info + ec2_asg_info: + name: "{{ resource_prefix }}-asg-tag-test" + register: info_result + # create a list of tag_keys from info result + - set_fact: + tag_keys: "{{ info_result.results[0].tags | map(attribute='key') | list }}" + + - assert: + that: + - add_purge_result is changed + - info_result.results[0].tags | length == 2 + - '"tag_a" in tag_keys' + - '"tag_b" in tag_keys' + - '"lowercase spaced" not in tag_keys' + - '"Title Case" not in tag_keys' + - '"CamelCase" not in tag_keys' + - '"snake_case" not in tag_keys' + - '"autoscaling:CreateOrUpdateTags" in add_purge_result.resource_actions' + + - name: Re-tag ASG - modify values + ec2_asg: + name: "{{ resource_prefix }}-asg-tag-test" + tags: + - tag_a: 'new_val_a' + propagate_at_launch: no + - tag_b: 'new_val_b' + propagate_at_launch: yes + register: add_purge_result + + - name: Get asg info + ec2_asg_info: + name: "{{ resource_prefix }}-asg-tag-test" + register: info_result + # create a list of tag_keys and tag_values from info result + - set_fact: + tag_keys: "{{ info_result.results[0].tags | map(attribute='key') | list }}" + - set_fact: + tag_values: "{{ info_result.results[0].tags | map(attribute='value') | list }}" + + + - assert: + that: + - add_purge_result is changed + - info_result.results[0].tags | length == 2 + - '"tag_a" in tag_keys' + - '"tag_b" in tag_keys' + - '"new_val_a" in tag_values' + - '"new_val_b" in tag_values' + - '"lowercase spaced" not in tag_keys' + - '"Title Case" not in tag_keys' + - '"CamelCase" not in tag_keys' + - '"snake_case" not in tag_keys' + - '"autoscaling:CreateOrUpdateTags" in add_purge_result.resource_actions' + + - name: Add 2 more tags - do not purge existing tags + ec2_asg: + name: "{{ resource_prefix }}-asg-tag-test" + tags: + - lowercase spaced: "hello cruel world" + propagate_at_launch: no + - Title Case: "Hello Cruel World" + propagate_at_launch: yes + purge_tags: false + register: add_result + + - name: Get asg info + ec2_asg_info: + name: "{{ resource_prefix }}-asg-tag-test" + register: info_result + # create a list of tag_keys from info result + - set_fact: + tag_keys: "{{ info_result.results[0].tags | map(attribute='key') | list }}" + + - assert: + that: + - add_result is changed + - info_result.results[0].tags | length == 4 + - '"tag_a" in tag_keys' + - '"tag_b" in tag_keys' + - '"lowercase spaced" in tag_keys' + - '"Title Case" in tag_keys' + - '"autoscaling:CreateOrUpdateTags" in add_result.resource_actions' + + - name: Add empty tags with purge set to false to assert that existing tags are retained + ec2_asg: + name: "{{ resource_prefix }}-asg-tag-test" + tags: [] + purge_tags: false + register: add_empty + + - name: Get asg info + ec2_asg_info: + name: "{{ resource_prefix }}-asg-tag-test" + register: info_result + # create a list of tag_keys from info result + - set_fact: + tag_keys: "{{ info_result.results[0].tags | map(attribute='key') | list }}" + + - assert: + that: + - add_empty is not changed + - info_result.results[0].tags | length == 4 + - '"tag_a" in tag_keys' + - '"tag_b" in tag_keys' + - '"lowercase spaced" in tag_keys' + - '"Title Case" in tag_keys' + - '"autoscaling:CreateOrUpdateTags" not in add_empty.resource_actions' + + - name: Add empty tags with purge set to true to assert that existing tags are removed + ec2_asg: + name: "{{ resource_prefix }}-asg-tag-test" + tags: [] + register: add_empty + + - name: Get asg info + ec2_asg_info: + name: "{{ resource_prefix }}-asg-tag-test" + register: info_result + # create a list of tag_keys from info result + - set_fact: + tag_keys: "{{ info_result.results[0].tags | map(attribute='key') | list }}" + + - assert: + that: + - add_empty is changed + - info_result.results[0].tags | length == 0 + - '"tag_a" not in tag_keys' + - '"tag_b" not in tag_keys' + - '"lowercase spaced" not in tag_keys' + - '"Title Case" not in tag_keys' + - '"autoscaling:CreateOrUpdateTags" not in add_empty.resource_actions' + - '"autoscaling:DeleteTags" in add_empty.resource_actions' + + #---------------------------------------------------------------------- + + always: + + - name: kill asg created in this test + ec2_asg: + name: "{{ resource_prefix }}-asg-tag-test" + state: absent + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10 + + - name: remove launch config created in this test + ec2_lc: + name: "{{ resource_prefix }}-lc-tag-test" + state: absent + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10
AutoScaling Group tags module <!--- Verify first that your feature was not already discussed on GitHub --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY Add a new module `ec2_asg_tag` analogous to `ec2_tag` to manage tags on AutoScaling Groups. ##### ISSUE TYPE - Feature Idea ##### COMPONENT NAME `ec2_asg_tag` ##### ADDITIONAL INFORMATION Using `ec2_asg` to manage tags is difficult since you must [specify the entire list of tags to manage them](https://github.com/ansible-collections/community.aws/blob/9b60a2d5d50ff1d77e74cf79715ccebc4632757f/tests/integration/targets/ec2_asg/tasks/main.yml#L194-L248). This is cumbersome since you first need to use `ec2_asg_info` to query the current set of tags, munge the result to create a new list of tags that includes or excludes the tags you with to add/remove and call `ec2_asg` again. A more declarative approach would be to follow the pattern of `ec2_tag`, e.g.: <!--- Paste example playbooks or commands between quotes below --> ```yaml - name: Ensure tags are present on an ASG community.aws.ec2_asg_tag: resource: my-auto-scaling-group state: present tags: - environment: production propagate_at_launch: true - role: webserver propagate_at_launch: true - name: Ensure tag is absent on an ASG community.aws.ec2_asg_tag: resource: my-auto-scaling-group state: absent tags: - environment: development ``` The module would utilise underlying API calls to: * https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_DescribeTags.html * https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_CreateOrUpdateTags.html * https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_DeleteTags.html
Files identified in the description: None If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> Hi @tremble, how do you feel about this PR? @alinabuzachis, Generally I prefer the alternative option of adding a "purge" option to the ec2_asg module (defaulting to purge=True, but supporting purge=False for the behaviour @jsok is after). On the whole it's more consistent with our other modules. However, we do have ec2_tag and ecs_tag, so it's not entirely inconsistent. Consider me neither a +1 nor a -1.
2022-03-11T18:24:20
ansible-collections/community.aws
989
ansible-collections__community.aws-989
[ "968" ]
a2dda5b5f45d22d45848cc8d2cc8f2c0219677b9
diff --git a/plugins/modules/redshift_info.py b/plugins/modules/redshift_info.py --- a/plugins/modules/redshift_info.py +++ b/plugins/modules/redshift_info.py @@ -278,7 +278,7 @@ import re try: - from botocore.exception import BotoCoreError, ClientError + from botocore.exceptions import BotoCoreError, ClientError except ImportError: pass # caught by AnsibleAWSModule
Invalid import path for BotoCoreError in redshift_info module ### Summary In case of any AWS related error (like missing permissions) the module will throw a gigantic python stack trace with error summary as: ``` line 304, in find_clusters NameError: name 'BotoCoreError' is not defined ``` This is due to an invalid import path that is present in the module https://github.com/ansible-collections/community.aws/blob/main/plugins/modules/redshift_info.py#L280 Instead of `from botocore.exception` it should be `from botocore.exceptions`. Once that is done, ansible no longer hides the real error with the stack trace. ### Issue Type Bug Report ### Component Name redshift_info ### Ansible Version ```console (paste below) $ ansible --version ansible 2.10.8 config file = None configured module search path = ['/home/wojtek/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /usr/local/lib/python3.6/dist-packages/ansible executable location = /usr/local/bin/ansible python version = 3.6.9 (default, Jan 26 2021, 15:33:00) [GCC 8.4.0] ``` ### Collection Versions Non-relevant ### AWS SDK versions ```console (paste below) $ pip show boto boto3 botocore Name: boto Version: 2.49.0 Summary: Amazon Web Services Library Home-page: https://github.com/boto/boto/ Author: Mitch Garnaat Author-email: [email protected] License: MIT Location: /home/wojtek/.local/lib/python3.6/site-packages Requires: --- Name: boto3 Version: 1.20.54 Summary: The AWS SDK for Python Home-page: https://github.com/boto/boto3 Author: Amazon Web Services Author-email: None License: Apache License 2.0 Location: /home/wojtek/.local/lib/python3.6/site-packages Requires: jmespath, s3transfer, botocore --- Name: botocore Version: 1.23.54 Summary: Low-level, data-driven core of boto 3. Home-page: https://github.com/boto/botocore Author: Amazon Web Services Author-email: None License: Apache License 2.0 Location: /home/wojtek/.local/lib/python3.6/site-packages Requires: jmespath, urllib3, python-dateutil ``` ### Configuration ```console (paste below) $ ansible-config dump --only-changed ``` ### OS / Environment Ubuntu 20.04 ### Steps to Reproduce Run the module without DescribeClusters permission. ### Expected Results AWS API error on missing permissions is shown. ### Actual Results Python stack trace ending with ``` line 304, in find_clusters NameError: name 'BotoCoreError' is not defined ``` ### Code of Conduct - [X] I agree to follow the Ansible Code of Conduct
Files identified in the description: * [`plugins/modules/redshift_info.py`](https://github.com/['ansible-collections/amazon.aws', 'ansible-collections/community.aws', 'ansible-collections/community.vmware']/blob/main/plugins/modules/redshift_info.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @j-carl @jillr @markuman @s-hertel @tremble [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> @winglot Thank for your bringing this. Would you be willing to open a pull request that fixes this import error? @alinabuzachis Sure, the PR is ready.
2022-03-14T20:08:45
ansible-collections/community.aws
990
ansible-collections__community.aws-990
[ "968" ]
6770f9f382c3511ba680f6f0c93850670a6735b0
diff --git a/plugins/modules/redshift_info.py b/plugins/modules/redshift_info.py --- a/plugins/modules/redshift_info.py +++ b/plugins/modules/redshift_info.py @@ -277,7 +277,7 @@ import re try: - from botocore.exception import BotoCoreError, ClientError + from botocore.exceptions import BotoCoreError, ClientError except ImportError: pass # caught by AnsibleAWSModule
Invalid import path for BotoCoreError in redshift_info module ### Summary In case of any AWS related error (like missing permissions) the module will throw a gigantic python stack trace with error summary as: ``` line 304, in find_clusters NameError: name 'BotoCoreError' is not defined ``` This is due to an invalid import path that is present in the module https://github.com/ansible-collections/community.aws/blob/main/plugins/modules/redshift_info.py#L280 Instead of `from botocore.exception` it should be `from botocore.exceptions`. Once that is done, ansible no longer hides the real error with the stack trace. ### Issue Type Bug Report ### Component Name redshift_info ### Ansible Version ```console (paste below) $ ansible --version ansible 2.10.8 config file = None configured module search path = ['/home/wojtek/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /usr/local/lib/python3.6/dist-packages/ansible executable location = /usr/local/bin/ansible python version = 3.6.9 (default, Jan 26 2021, 15:33:00) [GCC 8.4.0] ``` ### Collection Versions Non-relevant ### AWS SDK versions ```console (paste below) $ pip show boto boto3 botocore Name: boto Version: 2.49.0 Summary: Amazon Web Services Library Home-page: https://github.com/boto/boto/ Author: Mitch Garnaat Author-email: [email protected] License: MIT Location: /home/wojtek/.local/lib/python3.6/site-packages Requires: --- Name: boto3 Version: 1.20.54 Summary: The AWS SDK for Python Home-page: https://github.com/boto/boto3 Author: Amazon Web Services Author-email: None License: Apache License 2.0 Location: /home/wojtek/.local/lib/python3.6/site-packages Requires: jmespath, s3transfer, botocore --- Name: botocore Version: 1.23.54 Summary: Low-level, data-driven core of boto 3. Home-page: https://github.com/boto/botocore Author: Amazon Web Services Author-email: None License: Apache License 2.0 Location: /home/wojtek/.local/lib/python3.6/site-packages Requires: jmespath, urllib3, python-dateutil ``` ### Configuration ```console (paste below) $ ansible-config dump --only-changed ``` ### OS / Environment Ubuntu 20.04 ### Steps to Reproduce Run the module without DescribeClusters permission. ### Expected Results AWS API error on missing permissions is shown. ### Actual Results Python stack trace ending with ``` line 304, in find_clusters NameError: name 'BotoCoreError' is not defined ``` ### Code of Conduct - [X] I agree to follow the Ansible Code of Conduct
Files identified in the description: * [`plugins/modules/redshift_info.py`](https://github.com/['ansible-collections/amazon.aws', 'ansible-collections/community.aws', 'ansible-collections/community.vmware']/blob/main/plugins/modules/redshift_info.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @j-carl @jillr @markuman @s-hertel @tremble [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> @winglot Thank for your bringing this. Would you be willing to open a pull request that fixes this import error? @alinabuzachis Sure, the PR is ready.
2022-03-14T20:08:53
ansible-collections/community.aws
999
ansible-collections__community.aws-999
[ "959" ]
869b956fcd4214ec5a5fb13d42f651355022b799
diff --git a/plugins/modules/iam_role.py b/plugins/modules/iam_role.py --- a/plugins/modules/iam_role.py +++ b/plugins/modules/iam_role.py @@ -571,10 +571,8 @@ def destroy_role(): # Before we try to delete the role we need to remove any # - attached instance profiles # - attached managed policies - # - permissions boundary remove_instance_profiles(role_params, role) update_managed_policies(role_params, role, [], True) - update_role_permissions_boundary(boundary_params, role) try: if not module.check_mode:
Deleting an IAM Role Should Not Fail if Permission Boundary Cannot Be Removed ### Summary I have a role with a permission boundary that disallows removing permission boundaries. This role is then able to create a new role, which inherits that permissions boundary. If I want to delete that role, the `iam_role` plugin fails due to the inability to delete the permission boundary. Deleting the permission boundary is not actually a prerequisite to deleting the role and there's nothing in AWS that requires removing permission boundaries from roles before deleting them. [This comment](https://github.com/ansible-collections/community.aws/blob/454f5eb5395f1372b125b5b09e731798a698124e/plugins/modules/iam_role.py#L571-L577) is not true when it comes to inherited permission boundaries. ### Issue Type Bug Report ### Component Name iam_role ### Ansible Version ```console (paste below) $ ansible --version ansible 2.10.8 config file = None configured module search path = [ "elided" ] ansible python module location = /usr/local/lib/python3.9/site-packages/ansible executable location = /usr/local/bin/ansible python version = 3.9.10 (main, Jan 15 2022, 11:48:00) [Clang 13.0.0 (clang-1300.0.29.3)] ``` ### Collection Versions ```console (paste below) $ ansible-galaxy collection list amazon.aws 1.4.1 community.aws 1.4.0 ``` ### AWS SDK versions ```console (paste below) $ pip show boto boto3 botocore Name: boto3 Version: 1.18.48 Summary: The AWS SDK for Python Home-page: https://github.com/boto/boto3 Author: Amazon Web Services Author-email: License: Apache License 2.0 Location: /usr/lib/python3.7/site-packages Requires: botocore, jmespath, s3transfer Required-by: --- Name: botocore Version: 1.21.48 Summary: Low-level, data-driven core of boto 3. Home-page: https://github.com/boto/botocore Author: Amazon Web Services Author-email: License: Apache License 2.0 Location: /usr/lib/python3.7/site-packages Requires: jmespath, python-dateutil, urllib3 Required-by: awscli, boto3, s3transfer ``` ### Configuration _No response_ ### OS / Environment _No response_ ### Steps to Reproduce <!--- Paste example playbooks or commands between quotes below --> ```yaml (paste below) - name: Create Manager Role community.aws.iam_role: aws_access_key: "{{ aws_access_key }}" aws_secret_key: "{{ aws_secret_key }}" security_token: "{{ aws_session_token }}" name: "manager" assume_role_policy_document: | { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "{{ aws_account_id }}" }, "Action": "sts:AssumeRole" } ] } boundary: | { "Version": "2012-10-17", "Statement": [ { "Sid": "NoBoundaryPolicyDelete", "Effect": "Deny", "Action": [ "iam:DeleteRolePermissionsBoundary" ], "Resource": "*" }, ] } create_instance_profile: false register: manager_role - name: Assume role community.aws.sts_assume_role: aws_access_key: "{{ aws_access_key }}" aws_secret_key: "{{ aws_secret_key }}" aws_security_token: "{{ aws_session_token }}" role_arn: "manager" role_session_name: "manager" register: _ansible_role - name: Update credentials set_fact: aws_access_key: "{{ _ansible_role.sts_creds.access_key }}" aws_secret_key: "{{ _ansible_role.sts_creds.secret_key }}" aws_session_token: "{{ _ansible_role.sts_creds.session_token }}" - name: Create test role # Inherits permission boundary from manager community.aws.iam_role: aws_access_key: "{{ aws_access_key }}" aws_secret_key: "{{ aws_secret_key }}" security_token: "{{ aws_session_token }}" name: "test" assume_role_policy_document: | { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "{{ manager_role.iam_role.arn }}" }, "Action": "sts:AssumeRole" } ] } - name: Delete test role # Fails because it cannot delete the inherited permission boundary community.aws.iam_role: aws_access_key: "{{ aws_access_key }}" aws_secret_key: "{{ aws_secret_key }}" security_token: "{{ aws_session_token }}" name: "test" state: absent ``` ### Expected Results I expect the be able to delete the role. ### Actual Results ```console (paste below) Unable to remove permission boundary for role test: An error occurred (AccessDenied) when calling the DeleteRolePermissionsBoundary operation: User: arn:aws:iam::<elided>:role/manager is not authorized to perform: iam:DeleteRolePermissionsBoundary on resource: role test with an explicit deny ``` ### Code of Conduct - [X] I agree to follow the Ansible Code of Conduct
Files identified in the description: * [`plugins/modules/iam_role.py`](https://github.com/['ansible-collections/amazon.aws', 'ansible-collections/community.aws', 'ansible-collections/community.vmware']/blob/main/plugins/modules/iam_role.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @jillr @markuman @s-hertel @tremble [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> I'm happy to submit a PR removing the offending lines of code. @phene Looking at the docs, you're probably correct that it's not necessary to remove the permissions boundary, it is however necessary to detach the managed policies and remove the inline policies (a weird quirk of roles, this isn't true for most AWS resources). If you can create the PR that would be the fastest way to get this added. Since we can't review and merge our own PRs, two maintainers need to get involved if a maintainer writes the PR, if you submit the PR it just takes one maintainer to approve and merge the PR. It looks like the integration tests already check that we can delete a role with a boundary policy attached: https://github.com/ansible-collections/community.aws/blob/main/tests/integration/targets/iam_role/tasks/boundary_policy.yml#L49-L82 so the only additional thing you'll need beyond the change is to add a changelog entry: https://docs.ansible.com/ansible/latest/community/development_process.html#changelogs-how-to @tremble PR submitted.
2022-03-16T08:59:45
ansible-collections/community.aws
1,000
ansible-collections__community.aws-1000
[ "959" ]
4d5eead2f467297118bb31437f72b5f2b055c690
diff --git a/plugins/modules/iam_role.py b/plugins/modules/iam_role.py --- a/plugins/modules/iam_role.py +++ b/plugins/modules/iam_role.py @@ -571,10 +571,8 @@ def destroy_role(): # Before we try to delete the role we need to remove any # - attached instance profiles # - attached managed policies - # - permissions boundary remove_instance_profiles(role_params, role) update_managed_policies(role_params, role, [], True) - update_role_permissions_boundary(boundary_params, role) try: if not module.check_mode:
Deleting an IAM Role Should Not Fail if Permission Boundary Cannot Be Removed ### Summary I have a role with a permission boundary that disallows removing permission boundaries. This role is then able to create a new role, which inherits that permissions boundary. If I want to delete that role, the `iam_role` plugin fails due to the inability to delete the permission boundary. Deleting the permission boundary is not actually a prerequisite to deleting the role and there's nothing in AWS that requires removing permission boundaries from roles before deleting them. [This comment](https://github.com/ansible-collections/community.aws/blob/454f5eb5395f1372b125b5b09e731798a698124e/plugins/modules/iam_role.py#L571-L577) is not true when it comes to inherited permission boundaries. ### Issue Type Bug Report ### Component Name iam_role ### Ansible Version ```console (paste below) $ ansible --version ansible 2.10.8 config file = None configured module search path = [ "elided" ] ansible python module location = /usr/local/lib/python3.9/site-packages/ansible executable location = /usr/local/bin/ansible python version = 3.9.10 (main, Jan 15 2022, 11:48:00) [Clang 13.0.0 (clang-1300.0.29.3)] ``` ### Collection Versions ```console (paste below) $ ansible-galaxy collection list amazon.aws 1.4.1 community.aws 1.4.0 ``` ### AWS SDK versions ```console (paste below) $ pip show boto boto3 botocore Name: boto3 Version: 1.18.48 Summary: The AWS SDK for Python Home-page: https://github.com/boto/boto3 Author: Amazon Web Services Author-email: License: Apache License 2.0 Location: /usr/lib/python3.7/site-packages Requires: botocore, jmespath, s3transfer Required-by: --- Name: botocore Version: 1.21.48 Summary: Low-level, data-driven core of boto 3. Home-page: https://github.com/boto/botocore Author: Amazon Web Services Author-email: License: Apache License 2.0 Location: /usr/lib/python3.7/site-packages Requires: jmespath, python-dateutil, urllib3 Required-by: awscli, boto3, s3transfer ``` ### Configuration _No response_ ### OS / Environment _No response_ ### Steps to Reproduce <!--- Paste example playbooks or commands between quotes below --> ```yaml (paste below) - name: Create Manager Role community.aws.iam_role: aws_access_key: "{{ aws_access_key }}" aws_secret_key: "{{ aws_secret_key }}" security_token: "{{ aws_session_token }}" name: "manager" assume_role_policy_document: | { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "{{ aws_account_id }}" }, "Action": "sts:AssumeRole" } ] } boundary: | { "Version": "2012-10-17", "Statement": [ { "Sid": "NoBoundaryPolicyDelete", "Effect": "Deny", "Action": [ "iam:DeleteRolePermissionsBoundary" ], "Resource": "*" }, ] } create_instance_profile: false register: manager_role - name: Assume role community.aws.sts_assume_role: aws_access_key: "{{ aws_access_key }}" aws_secret_key: "{{ aws_secret_key }}" aws_security_token: "{{ aws_session_token }}" role_arn: "manager" role_session_name: "manager" register: _ansible_role - name: Update credentials set_fact: aws_access_key: "{{ _ansible_role.sts_creds.access_key }}" aws_secret_key: "{{ _ansible_role.sts_creds.secret_key }}" aws_session_token: "{{ _ansible_role.sts_creds.session_token }}" - name: Create test role # Inherits permission boundary from manager community.aws.iam_role: aws_access_key: "{{ aws_access_key }}" aws_secret_key: "{{ aws_secret_key }}" security_token: "{{ aws_session_token }}" name: "test" assume_role_policy_document: | { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "{{ manager_role.iam_role.arn }}" }, "Action": "sts:AssumeRole" } ] } - name: Delete test role # Fails because it cannot delete the inherited permission boundary community.aws.iam_role: aws_access_key: "{{ aws_access_key }}" aws_secret_key: "{{ aws_secret_key }}" security_token: "{{ aws_session_token }}" name: "test" state: absent ``` ### Expected Results I expect the be able to delete the role. ### Actual Results ```console (paste below) Unable to remove permission boundary for role test: An error occurred (AccessDenied) when calling the DeleteRolePermissionsBoundary operation: User: arn:aws:iam::<elided>:role/manager is not authorized to perform: iam:DeleteRolePermissionsBoundary on resource: role test with an explicit deny ``` ### Code of Conduct - [X] I agree to follow the Ansible Code of Conduct
Files identified in the description: * [`plugins/modules/iam_role.py`](https://github.com/['ansible-collections/amazon.aws', 'ansible-collections/community.aws', 'ansible-collections/community.vmware']/blob/main/plugins/modules/iam_role.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @jillr @markuman @s-hertel @tremble [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> I'm happy to submit a PR removing the offending lines of code. @phene Looking at the docs, you're probably correct that it's not necessary to remove the permissions boundary, it is however necessary to detach the managed policies and remove the inline policies (a weird quirk of roles, this isn't true for most AWS resources). If you can create the PR that would be the fastest way to get this added. Since we can't review and merge our own PRs, two maintainers need to get involved if a maintainer writes the PR, if you submit the PR it just takes one maintainer to approve and merge the PR. It looks like the integration tests already check that we can delete a role with a boundary policy attached: https://github.com/ansible-collections/community.aws/blob/main/tests/integration/targets/iam_role/tasks/boundary_policy.yml#L49-L82 so the only additional thing you'll need beyond the change is to add a changelog entry: https://docs.ansible.com/ansible/latest/community/development_process.html#changelogs-how-to @tremble PR submitted.
2022-03-16T08:59:53
ansible-collections/community.aws
1,002
ansible-collections__community.aws-1002
[ "1013" ]
3661b1ca39b36b46afbb0669db3c755deab496cb
diff --git a/plugins/modules/rds_instance.py b/plugins/modules/rds_instance.py --- a/plugins/modules/rds_instance.py +++ b/plugins/modules/rds_instance.py @@ -205,6 +205,23 @@ description: - Set to true to conduct the reboot through a MultiAZ failover. type: bool + iam_roles: + description: + - List of Amazon Web Services Identity and Access Management (IAM) roles to associate with DB instance. + type: list + elements: dict + suboptions: + feature_name: + description: + - The name of the feature associated with the IAM role. + type: str + required: yes + role_arn: + description: + - The ARN of the IAM role to associate with the DB instance. + type: str + required: yes + version_added: 3.3.0 iops: description: - The Provisioned IOPS (I/O operations per second) value. Is only set when using I(storage_type) is set to io1. @@ -316,6 +333,12 @@ a publicly resolvable DNS name, which resolves to a public IP address. A value of false specifies an internal instance with a DNS name that resolves to a private IP address. type: bool + purge_iam_roles: + description: + - Set to C(True) to remove any IAM roles that aren't specified in the task and are associated with the instance. + type: bool + default: False + version_added: 3.3.0 restore_time: description: - If using I(creation_source=instance) this indicates the UTC date and time to restore from the source instance. @@ -462,7 +485,49 @@ vpc_security_group_ids: - sg-0be17ba10c9286b0b purge_security_groups: false - register: result + register: result + +# Add IAM role to db instance +- name: Create IAM policy + community.aws.iam_managed_policy: + policy_name: "my-policy" + policy: "{{ lookup('file','files/policy.json') }}" + state: present + register: iam_policy + +- name: Create IAM role + community.aws.iam_role: + assume_role_policy_document: "{{ lookup('file','files/assume_policy.json') }}" + name: "my-role" + state: present + managed_policy: "{{ iam_policy.policy.arn }}" + register: iam_role + +- name: Create DB instance with added IAM role + community.aws.rds_instance: + id: "my-instance-id" + state: present + engine: postgres + engine_version: 14.2 + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: db.m6g.large + allocated_storage: "{{ allocated_storage }}" + iam_roles: + - role_arn: "{{ iam_role.arn }}" + feature_name: 's3Export' + +- name: Remove IAM role from DB instance + community.aws.rds_instance: + id: "my-instance-id" + state: present + engine: postgres + engine_version: 14.2 + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: db.m6g.large + allocated_storage: "{{ allocated_storage }}" + purge_iam_roles: yes ''' RETURN = r''' @@ -780,16 +845,23 @@ from ansible_collections.amazon.aws.plugins.module_utils.core import get_boto3_client_method_parameters from ansible_collections.amazon.aws.plugins.module_utils.ec2 import ansible_dict_to_boto3_tag_list from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AWSRetry +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import boto3_tag_list_to_ansible_dict from ansible_collections.amazon.aws.plugins.module_utils.rds import arg_spec_to_rds_params from ansible_collections.amazon.aws.plugins.module_utils.rds import call_method +from ansible_collections.amazon.aws.plugins.module_utils.rds import compare_iam_roles from ansible_collections.amazon.aws.plugins.module_utils.rds import ensure_tags from ansible_collections.amazon.aws.plugins.module_utils.rds import get_final_identifier from ansible_collections.amazon.aws.plugins.module_utils.rds import get_rds_method_attribute from ansible_collections.amazon.aws.plugins.module_utils.rds import get_tags +from ansible_collections.amazon.aws.plugins.module_utils.rds import update_iam_roles + valid_engines = ['aurora', 'aurora-mysql', 'aurora-postgresql', 'mariadb', 'mysql', 'oracle-ee', 'oracle-ee-cdb', 'oracle-se2', 'oracle-se2-cdb', 'postgres', 'sqlserver-ee', 'sqlserver-se', 'sqlserver-ex', 'sqlserver-web'] +valid_engines_iam_roles = ['aurora-postgresql', 'oracle-ee', 'oracle-ee-cdb', 'oracle-se2', 'oracle-se2-cdb', + 'postgres', 'sqlserver-ee', 'sqlserver-se', 'sqlserver-ex', 'sqlserver-web'] + def get_rds_method_attribute_name(instance, state, creation_source, read_replica): method_name = None @@ -945,23 +1017,21 @@ def get_current_attributes_with_inconsistent_keys(instance): options['DBSecurityGroups'] = [sg['DBSecurityGroupName'] for sg in instance['DBSecurityGroups'] if sg['Status'] in ['adding', 'active']] options['VpcSecurityGroupIds'] = [sg['VpcSecurityGroupId'] for sg in instance['VpcSecurityGroups'] if sg['Status'] in ['adding', 'active']] options['DBParameterGroupName'] = [parameter_group['DBParameterGroupName'] for parameter_group in instance['DBParameterGroups']] - options['AllowMajorVersionUpgrade'] = None options['EnableIAMDatabaseAuthentication'] = instance['IAMDatabaseAuthenticationEnabled'] # PerformanceInsightsEnabled is not returned on older RDS instances it seems options['EnablePerformanceInsights'] = instance.get('PerformanceInsightsEnabled', False) - options['MasterUserPassword'] = None options['NewDBInstanceIdentifier'] = instance['DBInstanceIdentifier'] + # Neither of these are returned via describe_db_instances, so if either is specified during a check_mode run, changed=True + options['AllowMajorVersionUpgrade'] = None + options['MasterUserPassword'] = None + return options def get_changing_options_with_inconsistent_keys(modify_params, instance, purge_cloudwatch_logs, purge_security_groups): changing_params = {} current_options = get_current_attributes_with_inconsistent_keys(instance) - - if current_options.get("MaxAllocatedStorage") is None: - current_options["MaxAllocatedStorage"] = None - for option in current_options: current_option = current_options[option] desired_option = modify_params.pop(option, None) @@ -982,9 +1052,14 @@ def get_changing_options_with_inconsistent_keys(modify_params, instance, purge_c if desired_option in current_option: continue - if current_option == desired_option: + # Current option and desired option are the same - continue loop + if option != 'ProcessorFeatures' and current_option == desired_option: + continue + + if option == 'ProcessorFeatures' and current_option == boto3_tag_list_to_ansible_dict(desired_option, 'Name', 'Value'): continue + # Current option and desired option are different - add to changing_params list if option == 'ProcessorFeatures' and desired_option == []: changing_params['UseDefaultProcessorFeatures'] = True elif option == 'CloudwatchLogsExportConfiguration': @@ -1074,13 +1149,48 @@ def update_instance(client, module, instance, instance_id): def promote_replication_instance(client, module, instance, read_replica): changed = False if read_replica is False: - changed = bool(instance.get('ReadReplicaSourceDBInstanceIdentifier') or instance.get('StatusInfos')) - if changed: - try: - call_method(client, module, method_name='promote_read_replica', parameters={'DBInstanceIdentifier': instance['DBInstanceIdentifier']}) - changed = True - except is_boto3_error_message('DB Instance is not a read replica'): - pass + # 'StatusInfos' only exists when the instance is a read replica + # See https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-db-instances.html + if bool(instance.get('StatusInfos')): + try: + result, changed = call_method(client, module, method_name='promote_read_replica', + parameters={'DBInstanceIdentifier': instance['DBInstanceIdentifier']}) + except is_boto3_error_message('DB Instance is not a read replica'): + pass + return changed + + +def ensure_iam_roles(client, module, instance_id): + ''' + Ensure specified IAM roles are associated with DB instance + + Parameters: + client: RDS client + module: AWSModule + instance_id: DB's instance ID + + Returns: + changed (bool): True if changes were successfully made to DB instance's IAM roles; False if not + ''' + instance = camel_dict_to_snake_dict(get_instance(client, module, instance_id), ignore_list=['Tags', 'ProcessorFeatures']) + + # Ensure engine type supports associating IAM roles + engine = instance.get('engine') + if engine not in valid_engines_iam_roles: + module.fail_json(msg='DB engine {0} is not valid for adding IAM roles. Valid engines are {1}'.format(engine, valid_engines_iam_roles)) + + changed = False + purge_iam_roles = module.params.get('purge_iam_roles') + target_roles = module.params.get('iam_roles') if module.params.get('iam_roles') else [] + existing_roles = instance.get('associated_roles', []) + roles_to_add, roles_to_remove = compare_iam_roles(existing_roles, target_roles, purge_iam_roles) + if bool(roles_to_add or roles_to_remove): + changed = True + # Don't update on check_mode + if module.check_mode: + module.exit_json(changed=changed, **instance) + else: + update_iam_roles(client, module, instance_id, roles_to_add, roles_to_remove) return changed @@ -1121,6 +1231,7 @@ def main(): creation_source=dict(choices=['snapshot', 's3', 'instance']), force_update_password=dict(type='bool', default=False, no_log=False), purge_cloudwatch_logs_exports=dict(type='bool', default=True), + purge_iam_roles=dict(type='bool', default=False), purge_tags=dict(type='bool', default=True), read_replica=dict(type='bool'), wait=dict(type='bool', default=True), @@ -1154,6 +1265,7 @@ def main(): engine_version=dict(), final_db_snapshot_identifier=dict(aliases=['final_snapshot_identifier']), force_failover=dict(type='bool'), + iam_roles=dict(type='list', elements='dict'), iops=dict(type='int'), kms_key_id=dict(), license_model=dict(), @@ -1230,6 +1342,13 @@ def main(): if module.params['preferred_maintenance_window']: module.params['preferred_maintenance_window'] = module.params['preferred_maintenance_window'].lower() + # Throw warning regarding case when allow_major_version_upgrade is specified in check_mode + # describe_rds_instance never returns this value, so on check_mode, it will always return changed=True + # In non-check mode runs, changed will return the correct value, so no need to warn there. + # see: amazon.aws.module_util.rds.handle_errors. + if module.params.get('allow_major_version_upgrade') and module.check_mode: + module.warn('allow_major_version_upgrade is not returned when describing db instances, so changed will always be `True` on check mode runs.') + client = module.client('rds') changed = False state = module.params['state'] @@ -1239,17 +1358,30 @@ def main(): method_name = get_rds_method_attribute_name(instance, state, module.params['creation_source'], module.params['read_replica']) if method_name: + + # Exit on create/delete if check_mode + if module.check_mode and method_name in ['create_db_instance', 'delete_db_instance']: + module.exit_json(changed=True, **camel_dict_to_snake_dict(instance, ignore_list=['Tags', 'ProcessorFeatures'])) + raw_parameters = arg_spec_to_rds_params(dict((k, module.params[k]) for k in module.params if k in parameter_options)) - parameters = get_parameters(client, module, raw_parameters, method_name) + parameters_to_modify = get_parameters(client, module, raw_parameters, method_name) - if parameters: - result, changed = call_method(client, module, method_name, parameters) + if parameters_to_modify: + # Exit on check_mode when parameters to modify + if module.check_mode: + module.exit_json(changed=True, **camel_dict_to_snake_dict(instance, ignore_list=['Tags', 'ProcessorFeatures'])) + result, changed = call_method(client, module, method_name, parameters_to_modify) instance_id = get_final_identifier(method_name, module) - # Check tagging/promoting/rebooting/starting/stopping instance - if state != 'absent' and (not module.check_mode or instance): - changed |= update_instance(client, module, instance, instance_id) + if state != 'absent': + # Check tagging/promoting/rebooting/starting/stopping instance + if not module.check_mode or instance: + changed |= update_instance(client, module, instance, instance_id) + + # Check IAM roles + if module.params.get('iam_roles') or module.params.get('purge_iam_roles'): + changed |= ensure_iam_roles(client, module, instance_id) if changed: instance = get_instance(client, module, instance_id)
diff --git a/tests/integration/targets/rds_instance/inventory b/tests/integration/targets/rds_instance/inventory --- a/tests/integration/targets/rds_instance/inventory +++ b/tests/integration/targets/rds_instance/inventory @@ -15,6 +15,9 @@ tagging replica upgrade +# TODO: uncomment after adding iam:CreatePolicy and iam:DeletePolicy +# iam_roles + # TODO: uncomment after adding rds_cluster module # aurora diff --git a/tests/integration/targets/rds_instance/roles/rds_instance/defaults/main.yml b/tests/integration/targets/rds_instance/roles/rds_instance/defaults/main.yml --- a/tests/integration/targets/rds_instance/roles/rds_instance/defaults/main.yml +++ b/tests/integration/targets/rds_instance/roles/rds_instance/defaults/main.yml @@ -29,3 +29,7 @@ modified_processor_features: # For mariadb tests mariadb_engine_version: 10.3.31 mariadb_engine_version_2: 10.4.21 + +# For iam roles tests +postgres_db_instance_class: db.m6g.large # smallest psql instance +postgres_db_engine_version: 14.2 diff --git a/tests/integration/targets/rds_instance/roles/rds_instance/files/s3_integration_policy.json b/tests/integration/targets/rds_instance/roles/rds_instance/files/s3_integration_policy.json new file mode 100644 --- /dev/null +++ b/tests/integration/targets/rds_instance/roles/rds_instance/files/s3_integration_policy.json @@ -0,0 +1,16 @@ +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "", + "Effect": "Allow", + "Action": [ + "s3:PutObject", + "s3:GetObject", + "s3:ListBucket", + "rds:*" + ], + "Resource": "*" + } + ] +} diff --git a/tests/integration/targets/rds_instance/roles/rds_instance/files/s3_integration_trust_policy.json b/tests/integration/targets/rds_instance/roles/rds_instance/files/s3_integration_trust_policy.json new file mode 100644 --- /dev/null +++ b/tests/integration/targets/rds_instance/roles/rds_instance/files/s3_integration_trust_policy.json @@ -0,0 +1,13 @@ +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "", + "Effect": "Allow", + "Principal": { + "Service": "rds.amazonaws.com" + }, + "Action": "sts:AssumeRole" + } + ] +} diff --git a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_complex.yml b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_complex.yml --- a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_complex.yml +++ b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_complex.yml @@ -41,11 +41,59 @@ - result.changed - "result.db_instance_identifier == '{{ instance_id }}'" + - name: Add IAM roles to mariab (should fail - iam roles not supported for mariadb) + rds_instance: + id: "{{ instance_id }}" + state: present + engine: mariadb + engine_version: "{{ mariadb_engine_version }}" + allow_major_version_upgrade: true + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ db_instance_class }}" + allocated_storage: "{{ io1_allocated_storage }}" + storage_type: "{{ storage_type }}" + iops: "{{ iops }}" + iam_roles: + - role_arn: 'my_role' + feature_name: 'my_feature' + register: result + ignore_errors: True + + - assert: + that: + - result.failed + - '"is not valid for adding IAM roles" in result.msg' + # TODO: test modifying db_subnet_group_name, db_security_groups, db_parameter_group_name, option_group_name, # monitoring_role_arn, monitoring_interval, domain, domain_iam_role_name, cloudwatch_logs_export_configuration # Test multiple modifications including enabling enhanced monitoring + - name: Modify several attributes - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + allocated_storage: "{{ io1_modified_allocated_storage }}" + storage_type: "{{ storage_type }}" + db_instance_class: "{{ modified_db_instance_class }}" + backup_retention_period: 2 + preferred_backup_window: "05:00-06:00" + preferred_maintenance_window: "{{ preferred_maintenance_window }}" + auto_minor_version_upgrade: false + monitoring_interval: "{{ monitoring_interval }}" + monitoring_role_arn: "{{ enhanced_monitoring_role.arn }}" + iops: "{{ iops }}" + port: 1150 + max_allocated_storage: 150 + apply_immediately: True + register: result + check_mode: yes + + - assert: + that: + - result.changed + - name: Modify several attributes rds_instance: id: "{{ instance_id }}" @@ -74,6 +122,32 @@ - '"db_instance_class" in result.pending_modified_values or result.db_instance_class == modified_db_instance_class' - '"monitoring_interval" in result.pending_modified_values or result.monitoring_interval == monitoring_interval' + - name: Idempotence modifying several pending attributes - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + allocated_storage: "{{ io1_modified_allocated_storage }}" + storage_type: "{{ storage_type }}" + db_instance_class: "{{ modified_db_instance_class }}" + backup_retention_period: 2 + preferred_backup_window: "05:00-06:00" + preferred_maintenance_window: "{{ preferred_maintenance_window }}" + auto_minor_version_upgrade: false + monitoring_interval: "{{ monitoring_interval }}" + monitoring_role_arn: "{{ enhanced_monitoring_role.arn }}" + iops: "{{ iops }}" + port: 1150 + max_allocated_storage: 150 + register: result + retries: 30 + delay: 10 + until: result is not failed + check_mode: yes + + - assert: + that: + - not result.changed + - name: Idempotence modifying several pending attributes rds_instance: id: "{{ instance_id }}" diff --git a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_iam_roles.yml b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_iam_roles.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_iam_roles.yml @@ -0,0 +1,400 @@ +--- +- block: + - name: Ensure the resource doesn't exist + rds_instance: + id: "{{ instance_id }}" + state: absent + skip_final_snapshot: True + register: result + + - assert: + that: + - not result.changed + ignore_errors: yes + + - name: Create s3 integration policy + iam_managed_policy: + policy_name: "{{ instance_id }}-s3-policy" + policy: "{{ lookup('file','files/s3_integration_policy.json') }}" + state: present + register: s3_integration_policy + + - name: Create an s3 integration role + iam_role: + assume_role_policy_document: "{{ lookup('file','files/s3_integration_trust_policy.json') }}" + name: "{{ instance_id }}-s3-role-1" + state: present + managed_policy: "{{ s3_integration_policy.policy.arn }}" + register: s3_integration_role_1 + + - name: Create an s3 integration role + iam_role: + assume_role_policy_document: "{{ lookup('file','files/s3_integration_trust_policy.json') }}" + name: "{{ instance_id }}-s3-role-2" + state: present + managed_policy: "{{ s3_integration_policy.policy.arn }}" + register: s3_integration_role_2 + + - name: Create an s3 integration role + iam_role: + assume_role_policy_document: "{{ lookup('file','files/s3_integration_trust_policy.json') }}" + name: "{{ instance_id }}-s3-role-3" + state: present + managed_policy: "{{ s3_integration_policy.policy.arn }}" + register: s3_integration_role_3 + + # ------------------------------------------------------------------------------------------ + + - name: Create DB instance with IAM roles - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + engine: postgres + engine_version: "{{ postgres_db_engine_version }}" + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ postgres_db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + allow_major_version_upgrade: yes + iam_roles: + - role_arn: "{{ s3_integration_role_1.arn }}" + feature_name: 's3Export' + - role_arn: "{{ s3_integration_role_2.arn }}" + feature_name: 'Lambda' + - role_arn: "{{ s3_integration_role_3.arn }}" + feature_name: 's3Import' + register: result + check_mode: yes + + - assert: + that: + - result.changed + + - name: Create DB instance with IAM roles + rds_instance: + id: "{{ instance_id }}" + state: present + engine: postgres + engine_version: "{{ postgres_db_engine_version }}" + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ postgres_db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + allow_major_version_upgrade: yes + iam_roles: + - role_arn: "{{ s3_integration_role_1.arn }}" + feature_name: 's3Export' + - role_arn: "{{ s3_integration_role_2.arn }}" + feature_name: 'Lambda' + - role_arn: "{{ s3_integration_role_3.arn }}" + feature_name: 's3Import' + register: result + + - assert: + that: + - result.changed + - "result.db_instance_identifier == '{{ instance_id }}'" + - result.associated_roles | length == 3 + - "{{ 's3Export' in result.associated_roles | map(attribute='feature_name') }}" + - "{{ 'Lambda' in result.associated_roles | map(attribute='feature_name') }}" + - "{{ 's3Import' in result.associated_roles | map(attribute='feature_name') }}" + + - name: Create DB instance with IAM roles (idempotence) - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + engine: postgres + engine_version: "{{ postgres_db_engine_version }}" + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ postgres_db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + iam_roles: + - role_arn: "{{ s3_integration_role_1.arn }}" + feature_name: 's3Export' + - role_arn: "{{ s3_integration_role_2.arn }}" + feature_name: 'Lambda' + - role_arn: "{{ s3_integration_role_3.arn }}" + feature_name: 's3Import' + register: result + check_mode: yes + + - assert: + that: + - not result.changed + + - name: Create DB instance with IAM roles (idempotence) + rds_instance: + id: "{{ instance_id }}" + state: present + engine: postgres + engine_version: "{{ postgres_db_engine_version }}" + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ postgres_db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + iam_roles: + - role_arn: "{{ s3_integration_role_1.arn }}" + feature_name: 's3Export' + - role_arn: "{{ s3_integration_role_2.arn }}" + feature_name: 'Lambda' + - role_arn: "{{ s3_integration_role_3.arn }}" + feature_name: 's3Import' + register: result + + - assert: + that: + - not result.changed + - "result.db_instance_identifier == '{{ instance_id }}'" + - result.associated_roles | length == 3 + - "{{ 's3Export' in result.associated_roles | map(attribute='feature_name') }}" + - "{{ 'Lambda' in result.associated_roles | map(attribute='feature_name') }}" + - "{{ 's3Import' in result.associated_roles | map(attribute='feature_name') }}" + + - name: Create DB instance with IAM roles (idempotence) - purge roles + rds_instance: + id: "{{ instance_id }}" + state: present + engine: postgres + engine_version: "{{ postgres_db_engine_version }}" + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ postgres_db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + iam_roles: + - role_arn: "{{ s3_integration_role_1.arn }}" + feature_name: 's3Export' + - role_arn: "{{ s3_integration_role_2.arn }}" + feature_name: 'Lambda' + - role_arn: "{{ s3_integration_role_3.arn }}" + feature_name: 's3Import' + purge_iam_roles: yes + register: result + + - assert: + that: + - not result.changed + - "result.db_instance_identifier == '{{ instance_id }}'" + - result.associated_roles | length == 3 + - "{{ 's3Export' in result.associated_roles | map(attribute='feature_name') }}" + - "{{ 'Lambda' in result.associated_roles | map(attribute='feature_name') }}" + - "{{ 's3Import' in result.associated_roles | map(attribute='feature_name') }}" + + # ------------------------------------------------------------------------------------------ + + - name: Remove s3Import IAM role from db instance - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + iam_roles: + - role_arn: "{{ s3_integration_role_1.arn }}" + feature_name: 's3Export' + - role_arn: "{{ s3_integration_role_2.arn }}" + feature_name: 'Lambda' + purge_iam_roles: yes + register: result + check_mode: yes + + - assert: + that: + - result.changed + + - name: Remove s3Import IAM role from db instance + rds_instance: + id: "{{ instance_id }}" + state: present + iam_roles: + - role_arn: "{{ s3_integration_role_1.arn }}" + feature_name: 's3Export' + - role_arn: "{{ s3_integration_role_2.arn }}" + feature_name: 'Lambda' + purge_iam_roles: yes + register: result + + - assert: + that: + - result.changed + - "result.db_instance_identifier == '{{ instance_id }}'" + - result.associated_roles | length == 2 + - "{{ 's3Export' in result.associated_roles | map(attribute='feature_name') }}" + - "{{ 'Lambda' in result.associated_roles | map(attribute='feature_name') }}" + - "{{ 's3Import' not in result.associated_roles | map(attribute='feature_name') }}" + + - name: Remove s3Import IAM role from db instance (idempotence) - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + iam_roles: + - role_arn: "{{ s3_integration_role_1.arn }}" + feature_name: 's3Export' + - role_arn: "{{ s3_integration_role_2.arn }}" + feature_name: 'Lambda' + purge_iam_roles: yes + register: result + check_mode: yes + + - assert: + that: + - not result.changed + + - name: Remove s3Import IAM role from db instance (idempotence) + rds_instance: + id: "{{ instance_id }}" + state: present + iam_roles: + - role_arn: "{{ s3_integration_role_1.arn }}" + feature_name: 's3Export' + - role_arn: "{{ s3_integration_role_2.arn }}" + feature_name: 'Lambda' + purge_iam_roles: yes + register: result + + - assert: + that: + - not result.changed + - "result.db_instance_identifier == '{{ instance_id }}'" + - result.associated_roles | length == 2 + - "{{ 's3Export' in result.associated_roles | map(attribute='feature_name') }}" + - "{{ 'Lambda' in result.associated_roles | map(attribute='feature_name') }}" + - "{{ 's3Import' not in result.associated_roles | map(attribute='feature_name') }}" + + # ------------------------------------------------------------------------------------------ + + - name: Remove IAM roles from db instance - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + purge_iam_roles: yes + register: result + check_mode: yes + + - assert: + that: + - result.changed + + - name: Remove IAM roles from db instance + rds_instance: + id: "{{ instance_id }}" + state: present + purge_iam_roles: yes + register: result + + - assert: + that: + - result.changed + - "result.db_instance_identifier == '{{ instance_id }}'" + - result.associated_roles | length == 0 + + - name: Remove IAM roles from db instance (idempotence) - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + purge_iam_roles: yes + register: result + check_mode: yes + + - assert: + that: + - not result.changed + + - name: Remove IAM roles from db instance (idempotence) + rds_instance: + id: "{{ instance_id }}" + state: present + purge_iam_roles: yes + register: result + + - assert: + that: + - not result.changed + - "result.db_instance_identifier == '{{ instance_id }}'" + - result.associated_roles | length == 0 + + # ------------------------------------------------------------------------------------------ + + - name: Add IAM role to existing db instance - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + iam_roles: + - role_arn: "{{ s3_integration_role_1.arn }}" + feature_name: 's3Export' + register: result + check_mode: yes + + - assert: + that: + - result.changed + + - name: Add IAM role to existing db instance + rds_instance: + id: "{{ instance_id }}" + state: present + iam_roles: + - role_arn: "{{ s3_integration_role_1.arn }}" + feature_name: 's3Export' + register: result + + - assert: + that: + - result.changed + - "result.db_instance_identifier == '{{ instance_id }}'" + - result.associated_roles | length == 1 + - "{{ 's3Export' in result.associated_roles | map(attribute='feature_name') }}" + + - name: Add IAM role to existing db instance (idempotence) - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + iam_roles: + - role_arn: "{{ s3_integration_role_1.arn }}" + feature_name: 's3Export' + register: result + check_mode: yes + + - assert: + that: + - not result.changed + + - name: Add IAM role to existing db instance (idempotence) + rds_instance: + id: "{{ instance_id }}" + state: present + + iam_roles: + - role_arn: "{{ s3_integration_role_1.arn }}" + feature_name: 's3Export' + register: result + + - assert: + that: + - not result.changed + - "result.db_instance_identifier == '{{ instance_id }}'" + - result.associated_roles | length == 1 + - "{{ 's3Export' in result.associated_roles | map(attribute='feature_name') }}" + + always: + - name: Delete IAM policy + iam_managed_policy: + policy_name: "{{ instance_id }}-s3-policy" + state: absent + ignore_errors: yes + + - name: Delete IAM roles + iam_role: + name: "{{ item.role_name }}" + assume_role_policy_document: "{{ lookup('file','files/s3_integration_trust_policy.json') }}" + state: absent + ignore_errors: yes + with_items: + - "{{ s3_integration_role_1 }}" + - "{{ s3_integration_role_2 }}" + - "{{ s3_integration_role_3 }}" + + - name: Delete the instance + rds_instance: + id: "{{ instance_id }}" + state: absent + skip_final_snapshot: True + wait: false + ignore_errors: yes diff --git a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_modify.yml b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_modify.yml --- a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_modify.yml +++ b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_modify.yml @@ -39,6 +39,20 @@ - result.changed - "result.db_instance_identifier == '{{ instance_id }}'" + - name: Modify the instance name without immediate application - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + new_id: "{{ modified_instance_id }}" + password: "{{ password }}" + apply_immediately: False + register: result + check_mode: yes + + - assert: + that: + - result.changed + - name: Modify the instance name without immediate application rds_instance: id: "{{ instance_id }}" @@ -53,6 +67,19 @@ - result.changed - 'result.db_instance_identifier == "{{ instance_id }}"' + - name: Immediately apply the pending update - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + new_id: "{{ modified_instance_id }}" + apply_immediately: True + register: result + check_mode: yes + + - assert: + that: + - result.changed + - name: Immediately apply the pending update rds_instance: id: "{{ instance_id }}" diff --git a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_processor.yml b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_processor.yml --- a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_processor.yml +++ b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_processor.yml @@ -30,7 +30,7 @@ that: - result.changed - - name: Check mode - modify the processor features + - name: Modify the processor features - check_mode rds_instance: id: "{{ instance_id }}" state: present @@ -69,6 +69,45 @@ - 'result.pending_modified_values.processor_features.coreCount == "{{ modified_processor_features.coreCount }}"' - 'result.pending_modified_values.processor_features.threadsPerCore == "{{ modified_processor_features.threadsPerCore }}"' + - name: Modify the processor features (idempotence) - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + engine: oracle-ee + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ oracle_ee_db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + storage_encrypted: True + processor_features: "{{ modified_processor_features }}" + apply_immediately: true + register: result + check_mode: True + + - assert: + that: + - not result.changed + + - name: Modify the processor features (idempotence) + rds_instance: + id: "{{ instance_id }}" + state: present + engine: oracle-ee + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ oracle_ee_db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + storage_encrypted: True + processor_features: "{{ modified_processor_features }}" + apply_immediately: true + register: result + + - assert: + that: + - not result.changed + - 'result.pending_modified_values.processor_features.coreCount == "{{ modified_processor_features.coreCount }}"' + - 'result.pending_modified_values.processor_features.threadsPerCore == "{{ modified_processor_features.threadsPerCore }}"' + always: - name: Delete the DB instance diff --git a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_replica.yml b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_replica.yml --- a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_replica.yml +++ b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_replica.yml @@ -40,6 +40,31 @@ - source_db.changed - "source_db.db_instance_identifier == '{{ instance_id }}'" + # ------------------------------------------------------------------------------------------ + + - name: Create a read replica in a different region - check_mode + rds_instance: + id: "{{ instance_id }}-replica" + state: present + source_db_instance_identifier: "{{ instance_id }}" + engine: mysql + username: "{{ username }}" + password: "{{ password }}" + read_replica: True + db_instance_class: "{{ db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + region: "{{ region_dest }}" + tags: + Name: "{{ instance_id }}" + Created_by: Ansible rds_instance tests + wait: yes + register: result + check_mode: yes + + - assert: + that: + - result.changed + - name: Create a read replica in a different region rds_instance: id: "{{ instance_id }}-replica" @@ -66,6 +91,27 @@ - "result.tags.Name == '{{ instance_id }}'" - "result.tags.Created_by == 'Ansible rds_instance tests'" + - name: Test idempotence with a read replica - check_mode + rds_instance: + id: "{{ instance_id }}-replica" + state: present + source_db_instance_identifier: "{{ instance_id }}" + engine: mysql + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + region: "{{ region_dest }}" + tags: + Name: "{{ instance_id }}" + Created_by: Ansible rds_instance tests + register: result + check_mode: yes + + - assert: + that: + - not result.changed + - name: Test idempotence with a read replica rds_instance: id: "{{ instance_id }}-replica" @@ -82,10 +128,9 @@ Created_by: Ansible rds_instance tests register: result - ## XXX Bug - # - assert: - # that: - # - not result.changed + - assert: + that: + - not result.changed - name: Test idempotence with read_replica=True rds_instance: @@ -104,6 +149,25 @@ Created_by: Ansible rds_instance tests register: result + - assert: + that: + - not result.changed + + # ------------------------------------------------------------------------------------------ + + - name: Promote the read replica - check_mode + rds_instance: + id: "{{ instance_id }}-replica" + state: present + read_replica: False + region: "{{ region_dest }}" + register: result + check_mode: yes + + - assert: + that: + - result.changed + - name: Promote the read replica rds_instance: id: "{{ instance_id }}-replica" @@ -116,6 +180,19 @@ that: - result.changed + - name: Test idempotence - check_mode + rds_instance: + id: "{{ instance_id }}-replica" + state: present + read_replica: False + region: "{{ region_dest }}" + register: result + check_mode: yes + + - assert: + that: + - not result.changed + - name: Test idempotence rds_instance: id: "{{ instance_id }}-replica" @@ -124,10 +201,9 @@ region: "{{ region_dest }}" register: result - ## XXX Bug - #- assert: - # that: - # - not result.changed + - assert: + that: + - not result.changed always: diff --git a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_restore.yml b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_restore.yml --- a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_restore.yml +++ b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_restore.yml @@ -31,6 +31,25 @@ - source_db.changed - "source_db.db_instance_identifier == '{{ instance_id }}-s'" + - name: Create a point in time DB instance - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + source_db_instance_identifier: "{{ instance_id }}-s" + creation_source: instance + engine: mysql + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + use_latest_restorable_time: True + register: result + check_mode: yes + + - assert: + that: + result.changed + - name: Create a point in time DB instance rds_instance: id: "{{ instance_id }}" @@ -45,7 +64,30 @@ use_latest_restorable_time: True register: result - - name: Test idempotence with a point in time replica + - assert: + that: + result.changed + + - name: Create a point in time DB instance (idempotence) - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + source_db_instance_identifier: "{{ instance_id }}-s" + creation_source: instance + engine: mysql + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + restore_time: "{{ result.latest_restorable_time }}" + register: result + check_mode: yes + + - assert: + that: + - not result.changed + + - name: Create a point in time DB instance (idempotence) rds_instance: id: "{{ instance_id }}" state: present diff --git a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_sgroups.yml b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_sgroups.yml --- a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_sgroups.yml +++ b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_sgroups.yml @@ -40,8 +40,6 @@ - "{{ resource_prefix }}-sg-2" - "{{ resource_prefix }}-sg-3" - - debug: var=sgs_result - - name: Ensure the resource doesn't exist rds_instance: id: "{{ instance_id }}" @@ -54,6 +52,27 @@ - not result.changed ignore_errors: yes + # ------------------------------------------------------------------------------------------ + + - name: Create a DB instance in the VPC with two security groups - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + engine: mariadb + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + vpc_security_group_ids: + - "{{ sgs_result.results.0.group_id }}" + - "{{ sgs_result.results.1.group_id }}" + register: result + check_mode: yes + + - assert: + that: + - result.changed + - name: Create a DB instance in the VPC with two security groups rds_instance: id: "{{ instance_id }}" @@ -74,7 +93,48 @@ - "result.db_instance_identifier == '{{ instance_id }}'" - "result.vpc_security_groups | selectattr('status', 'in', ['active', 'adding']) | list | length == 2" - - name: Add a new security group without purge (check_mode) + - name: Create a DB instance in the VPC with two security groups (idempotence) - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + engine: mariadb + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + vpc_security_group_ids: + - "{{ sgs_result.results.0.group_id }}" + - "{{ sgs_result.results.1.group_id }}" + register: result + check_mode: yes + + - assert: + that: + - not result.changed + + - name: Create a DB instance in the VPC with two security groups (idempotence) + rds_instance: + id: "{{ instance_id }}" + state: present + engine: mariadb + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + vpc_security_group_ids: + - "{{ sgs_result.results.0.group_id }}" + - "{{ sgs_result.results.1.group_id }}" + register: result + + - assert: + that: + - not result.changed + - "result.db_instance_identifier == '{{ instance_id }}'" + - "result.vpc_security_groups | selectattr('status', 'in', ['active', 'adding']) | list | length == 2" + + # ------------------------------------------------------------------------------------------ + + - name: Add a new security group without purge - check_mode rds_instance: id: "{{ instance_id }}" state: present @@ -106,7 +166,23 @@ - "result.db_instance_identifier == '{{ instance_id }}'" - "result.vpc_security_groups | selectattr('status', 'in', ['active', 'adding']) | list | length == 3" - - name: Add a new security group without purge (test idempotence) + - name: Add a new security group without purge (idempotence) - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + vpc_security_group_ids: + - "{{ sgs_result.results.2.group_id }}" + apply_immediately: true + purge_security_groups: false + register: result + check_mode: yes + + - assert: + that: + - not result.changed + - "result.db_instance_identifier == '{{ instance_id }}'" + + - name: Add a new security group without purge (idempotence) rds_instance: id: "{{ instance_id }}" state: present @@ -120,6 +196,23 @@ that: - not result.changed - "result.db_instance_identifier == '{{ instance_id }}'" + - "result.vpc_security_groups | selectattr('status', 'in', ['active', 'adding']) | list | length == 3" + + # ------------------------------------------------------------------------------------------ + + - name: Add a security group with purge - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + vpc_security_group_ids: + - "{{ sgs_result.results.2.group_id }}" + apply_immediately: true + register: result + check_mode: yes + + - assert: + that: + - result.changed - name: Add a security group with purge rds_instance: @@ -137,6 +230,35 @@ - "result.vpc_security_groups | selectattr('status', 'in', ['active', 'adding']) | list | length == 1" - "result.vpc_security_groups | selectattr('status', 'equalto', 'removing') | list | length == 2" + - name: Add a security group with purge (idempotence) - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + vpc_security_group_ids: + - "{{ sgs_result.results.2.group_id }}" + apply_immediately: true + register: result + check_mode: yes + + - assert: + that: + - not result.changed + + - name: Add a security group with purge (idempotence) + rds_instance: + id: "{{ instance_id }}" + state: present + vpc_security_group_ids: + - "{{ sgs_result.results.2.group_id }}" + apply_immediately: true + register: result + + - assert: + that: + - not result.changed + - "result.db_instance_identifier == '{{ instance_id }}'" + - "result.vpc_security_groups | selectattr('status', 'in', ['active', 'adding']) | list | length == 1" + always: - name: Ensure the resource doesn't exist diff --git a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_states.yml b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_states.yml --- a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_states.yml +++ b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_states.yml @@ -12,6 +12,28 @@ - not result.changed ignore_errors: yes + + # ------------------------------------------------------------------------------------------ + + - name: Create a mariadb instance - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + engine: mariadb + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + tags: + Name: "{{ instance_id }}" + Created_by: Ansible rds_instance tests + register: result + check_mode: yes + + - assert: + that: + - result.changed + - name: Create a mariadb instance rds_instance: id: "{{ instance_id }}" @@ -34,8 +56,51 @@ - "result.tags.Name == '{{ instance_id }}'" - "result.tags.Created_by == 'Ansible rds_instance tests'" + - name: Create a mariadb instance (idempotence) - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + engine: mariadb + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + tags: + Name: "{{ instance_id }}" + Created_by: Ansible rds_instance tests + register: result + check_mode: yes + + - assert: + that: + - not result.changed + + - name: Create a mariadb instance (idempotence) + rds_instance: + id: "{{ instance_id }}" + state: present + engine: mariadb + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + tags: + Name: "{{ instance_id }}" + Created_by: Ansible rds_instance tests + register: result + + - assert: + that: + - not result.changed + - "result.db_instance_identifier == '{{ instance_id }}'" + - "result.tags | length == 2" + - "result.tags.Name == '{{ instance_id }}'" + - "result.tags.Created_by == 'Ansible rds_instance tests'" + + # ------------------------------------------------------------------------------------------ # Test stopping / rebooting instances - - name: Check mode - reboot a stopped instance + + - name: Reboot a stopped instance - check_mode rds_instance: id: "{{ instance_id }}" state: rebooted @@ -56,7 +121,9 @@ that: - result.changed - - name: Check Mode - stop the instance + # ------------------------------------------------------------------------------------------ + + - name: Stop the instance - check_mode rds_instance: id: "{{ instance_id }}" state: stopped @@ -77,7 +144,7 @@ that: - result.changed - - name: Check Mode - idempotence + - name: Stop the instance (idempotence) - check_mode rds_instance: id: "{{ instance_id }}" state: stopped @@ -88,7 +155,7 @@ that: - not result.changed - - name: Idempotence + - name: Stop the instance (idempotence) rds_instance: id: "{{ instance_id }}" state: stopped @@ -98,7 +165,9 @@ that: - not result.changed - - name: Check Mode - start the instance + # ------------------------------------------------------------------------------------------ + + - name: Start the instance - check_mode rds_instance: id: "{{ instance_id }}" state: started @@ -119,6 +188,93 @@ that: - result.changed + - name: Start the instance (idempotence) - check_mode + rds_instance: + id: "{{ instance_id }}" + state: started + register: result + check_mode: yes + + - assert: + that: + - not result.changed + + - name: Start the instance (idempotence) + rds_instance: + id: "{{ instance_id }}" + state: started + register: result + + - assert: + that: + - not result.changed + + # ------------------------------------------------------------------------------------------ + + - name: Ensure instance exists prior to deleting + rds_instance_info: + db_instance_identifier: '{{ instance_id }}' + register: db_info + + - assert: + that: + - db_info.instances | length == 1 + + - name: Delete the instance - check_mode + rds_instance: + id: "{{ instance_id }}" + state: absent + skip_final_snapshot: True + register: result + check_mode: yes + + - assert: + that: + - result.changed + + - name: Delete the instance + rds_instance: + id: "{{ instance_id }}" + state: absent + skip_final_snapshot: True + register: result + + - assert: + that: + - result.changed + + - name: Ensure instance was deleted + rds_instance_info: + db_instance_identifier: '{{ instance_id }}' + register: db_info + + - assert: + that: + - db_info.instances | length == 0 + + - name: Delete the instance (idempotence) - check_mode + rds_instance: + id: "{{ instance_id }}" + state: absent + skip_final_snapshot: True + register: result + check_mode: yes + + - assert: + that: + - not result.changed + + - name: Delete the instance (idempotence) + rds_instance: + id: "{{ instance_id }}" + state: absent + skip_final_snapshot: True + register: result + + - assert: + that: + - not result.changed + always: - name: Remove DB instance rds_instance: diff --git a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_tagging.yml b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_tagging.yml --- a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_tagging.yml +++ b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_tagging.yml @@ -56,6 +56,22 @@ - result.kms_key_id - result.storage_encrypted == true + - name: Test impotency omitting tags - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + engine: mariadb + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + register: result + check_mode: yes + + - assert: + that: + - not result.changed + - name: Test impotency omitting tags rds_instance: id: "{{ instance_id }}" @@ -103,6 +119,21 @@ - not result.changed - "result.tags | length == 2" + - name: Add a tag and remove a tag - check_mode + rds_instance: + db_instance_identifier: "{{ instance_id }}" + state: present + tags: + Name: "{{ instance_id }}-new" + Created_by: Ansible rds_instance tests + purge_tags: True + register: result + check_mode: yes + + - assert: + that: + - result.changed + - name: Add a tag and remove a tag rds_instance: db_instance_identifier: "{{ instance_id }}" @@ -119,6 +150,37 @@ - "result.tags | length == 2" - "result.tags.Name == '{{ instance_id }}-new'" + - name: Add a tag and remove a tag (idempotence) - check_mode + rds_instance: + db_instance_identifier: "{{ instance_id }}" + state: present + tags: + Name: "{{ instance_id }}-new" + Created_by: Ansible rds_instance tests + purge_tags: True + register: result + check_mode: yes + + - assert: + that: + - not result.changed + + - name: Add a tag and remove a tag (idempotence) + rds_instance: + db_instance_identifier: "{{ instance_id }}" + state: present + tags: + Name: "{{ instance_id }}-new" + Created_by: Ansible rds_instance tests + purge_tags: True + register: result + + - assert: + that: + - not result.changed + - "result.tags | length == 2" + - "result.tags.Name == '{{ instance_id }}-new'" + # Test final snapshot on deletion - name: Delete the DB instance rds_instance: diff --git a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_upgrade.yml b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_upgrade.yml --- a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_upgrade.yml +++ b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_upgrade.yml @@ -32,7 +32,26 @@ # Test upgrade of DB instance - - name: Uprade a mariadb instance + - name: Upgrade a mariadb instance - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + engine: mariadb + engine_version: "{{ mariadb_engine_version_2 }}" + allow_major_version_upgrade: true + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + apply_immediately: True + register: result + check_mode: yes + + - assert: + that: + - result.changed + + - name: Upgrade a mariadb instance rds_instance: id: "{{ instance_id }}" state: present @@ -51,7 +70,30 @@ - result.changed - '"engine_version" in result.pending_modified_values or result.engine_version == mariadb_engine_version_2' - - name: Idempotence uprading a mariadb instance + - name: Idempotence upgrading a mariadb instance - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + engine: mariadb + engine_version: "{{ mariadb_engine_version_2 }}" + allow_major_version_upgrade: true + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + register: result + retries: 30 + delay: 10 + until: result is not failed + check_mode: yes + + ### Specifying allow_major_version_upgrade with check_mode will always result in changed=True + ### since it's not returned in describe_db_instances api call + # - assert: + # that: + # - not result.changed + + - name: Idempotence upgrading a mariadb instance rds_instance: id: "{{ instance_id }}" state: present
rds_instance - Broken check_mode and idempotence ### Summary When adding integration tests for adding iam_roles support for rds_instance, I noticed check_mode tests fail on idempotence checks, as well as some other checks like adding sgs on check_mode, etc. ### Issue Type Bug Report ### Component Name rds_instance ### Ansible Version ```console (paste below) $ ansible --version ``` ### Collection Versions ```console (paste below) $ ansible-galaxy collection list ``` ### AWS SDK versions ```console (paste below) $ pip show boto boto3 botocore ``` ### Configuration ```console (paste below) $ ansible-config dump --only-changed ``` ### OS / Environment _No response_ ### Steps to Reproduce <!--- Paste example playbooks or commands between quotes below --> ```yaml (paste below) - name: Create DB instance with IAM roles (idempotence) - check_mode rds_instance: id: "{{ instance_id }}" state: present engine: postgres engine_version: "{{ postgres_db_engine_version }}" username: "{{ username }}" password: "{{ password }}" db_instance_class: "{{ postgres_db_instance_class }}" allocated_storage: "{{ allocated_storage }}" allow_major_version_upgrade: yes iam_roles: - role_arn: "{{ s3_integration_role_1.arn }}" feature_name: 's3Export' - role_arn: "{{ s3_integration_role_2.arn }}" feature_name: 'Lambda' - role_arn: "{{ s3_integration_role_3.arn }}" feature_name: 's3Import' register: result check_mode: yes - assert: that: - not result.changed ``` ### Expected Results expected check_mode to not modify anything and return the correct `changed` ### Actual Results in idempotence tests, check_mode returned `changed = True`. When adding sg on check_mode, the sgs were actually added. ### Code of Conduct - [X] I agree to follow the Ansible Code of Conduct
2022-03-17T02:46:11
ansible-collections/community.aws
1,014
ansible-collections__community.aws-1014
[ "135" ]
00a26e9561f931054ec2d1a994cab32097433e73
diff --git a/plugins/modules/ec2_asg_instance_refresh.py b/plugins/modules/ec2_asg_instance_refresh.py new file mode 100644 --- /dev/null +++ b/plugins/modules/ec2_asg_instance_refresh.py @@ -0,0 +1,267 @@ +#!/usr/bin/python +# Copyright: Ansible Project +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + +DOCUMENTATION = ''' +--- +module: ec2_asg_instance_refresh +version_added: 3.2.0 +short_description: Start or cancel an EC2 Auto Scaling Group (ASG) instance refresh in AWS +description: + - Start or cancel an EC2 Auto Scaling Group instance refresh in AWS. + - Can be used with M(community.aws.ec2_asg_instance_refresh_info) to track the subsequent progress. +author: "Dan Khersonsky (@danquixote)" +options: + state: + description: + - Desired state of the ASG. + type: str + required: true + choices: [ 'started', 'cancelled' ] + name: + description: + - The name of the auto scaling group you are searching for. + type: str + required: true + strategy: + description: + - The strategy to use for the instance refresh. The only valid value is C(Rolling). + - A rolling update is an update that is applied to all instances in an Auto Scaling group until all instances have been updated. + - A rolling update can fail due to failed health checks or if instances are on standby or are protected from scale in. + - If the rolling update process fails, any instances that were already replaced are not rolled back to their previous configuration. + type: str + default: 'Rolling' + preferences: + description: + - Set of preferences associated with the instance refresh request. + - If not provided, the default values are used. + - For I(min_healthy_percentage), the default value is C(90). + - For I(instance_warmup), the default is to use the value specified for the health check grace period for the Auto Scaling group. + - Can not be specified when I(state) is set to 'cancelled'. + required: false + suboptions: + min_healthy_percentage: + description: + - Total percent of capacity in ASG that must remain healthy during instance refresh to allow operation to continue. + - It is rounded up to the nearest integer. + type: int + default: 90 + instance_warmup: + description: + - The number of seconds until a newly launched instance is configured and ready to use. + - During this time, Amazon EC2 Auto Scaling does not immediately move on to the next replacement. + - The default is to use the value for the health check grace period defined for the group. + type: int + type: dict +extends_documentation_fragment: +- amazon.aws.aws +- amazon.aws.ec2 + +''' + +EXAMPLES = ''' +# Note: These examples do not set authentication details, see the AWS Guide for details. + +- name: Start a refresh + community.aws.ec2_asg_instance_refresh: + name: some-asg + state: started + +- name: Cancel a refresh + community.aws.ec2_asg_instance_refresh: + name: some-asg + state: cancelled + +- name: Start a refresh and pass preferences + community.aws.ec2_asg_instance_refresh: + name: some-asg + state: started + preferences: + min_healthy_percentage: 91 + instance_warmup: 60 + +''' + +RETURN = ''' +--- +instance_refresh_id: + description: instance refresh id + returned: success + type: str + sample: "08b91cf7-8fa6-48af-b6a6-d227f40f1b9b" +auto_scaling_group_name: + description: Name of autoscaling group + returned: success + type: str + sample: "public-webapp-production-1" +status: + description: + - The current state of the group when DeleteAutoScalingGroup is in progress. + - The following are the possible statuses + - Pending -- The request was created, but the operation has not started. + - InProgress -- The operation is in progress. + - Successful -- The operation completed successfully. + - Failed -- The operation failed to complete. You can troubleshoot using the status reason and the scaling activities. + - Cancelling -- + - An ongoing operation is being cancelled. + - Cancellation does not roll back any replacements that have already been completed, + - but it prevents new replacements from being started. + - Cancelled -- The operation is cancelled. + returned: success + type: str + sample: "Pending" +start_time: + description: The date and time this ASG was created, in ISO 8601 format. + returned: success + type: str + sample: "2015-11-25T00:05:36.309Z" +end_time: + description: The date and time this ASG was created, in ISO 8601 format. + returned: success + type: str + sample: "2015-11-25T00:05:36.309Z" +percentage_complete: + description: the % of completeness + returned: success + type: int + sample: 100 +instances_to_update: + description: num. of instance to update + returned: success + type: int + sample: 5 +''' + +try: + from botocore.exceptions import BotoCoreError, ClientError +except ImportError: + pass # caught by AnsibleAWSModule + + +from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AWSRetry +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import camel_dict_to_snake_dict +from ansible_collections.amazon.aws.plugins.module_utils.core import scrub_none_parameters +from ansible.module_utils.common.dict_transformations import snake_dict_to_camel_dict + + +def start_or_cancel_instance_refresh(conn, module): + """ + Args: + conn (boto3.AutoScaling.Client): Valid Boto3 ASG client. + module: AnsibleAWSModule object + + Returns: + { + "instance_refreshes": [ + { + 'auto_scaling_group_name': 'ansible-test-hermes-63642726-asg', + 'instance_refresh_id': '6507a3e5-4950-4503-8978-e9f2636efc09', + 'instances_to_update': 1, + 'percentage_complete': 0, + "preferences": { + "instance_warmup": 60, + "min_healthy_percentage": 90, + "skip_matching": false + }, + 'start_time': '2021-02-04T03:39:40+00:00', + 'status': 'Cancelling', + 'status_reason': 'Replacing instances before cancelling.', + } + ] + } + """ + + asg_state = module.params.get('state') + asg_name = module.params.get('name') + preferences = module.params.get('preferences') + + args = {} + args['AutoScalingGroupName'] = asg_name + if asg_state == 'started': + args['Strategy'] = module.params.get('strategy') + if preferences: + if asg_state == 'cancelled': + module.fail_json(msg='can not pass preferences dict when canceling a refresh') + _prefs = scrub_none_parameters(preferences) + args['Preferences'] = snake_dict_to_camel_dict(_prefs, capitalize_first=True) + cmd_invocations = { + 'cancelled': conn.cancel_instance_refresh, + 'started': conn.start_instance_refresh, + } + try: + if module.check_mode: + if asg_state == 'started': + ongoing_refresh = conn.describe_instance_refreshes(AutoScalingGroupName=asg_name).get('InstanceRefreshes', '[]') + if ongoing_refresh: + module.exit_json(changed=False, msg='In check_mode - Instance Refresh is already in progress, can not start new instance refresh.') + else: + module.exit_json(changed=True, msg='Would have started instance refresh if not in check mode.') + elif asg_state == 'cancelled': + ongoing_refresh = conn.describe_instance_refreshes(AutoScalingGroupName=asg_name).get('InstanceRefreshes', '[]')[0] + if ongoing_refresh.get('Status', '') in ['Cancelling', 'Cancelled']: + module.exit_json(changed=False, msg='In check_mode - Instance Refresh already cancelled or is pending cancellation.') + elif not ongoing_refresh: + module.exit_json(chaned=False, msg='In check_mode - No active referesh found, nothing to cancel.') + else: + module.exit_json(changed=True, msg='Would have cancelled instance refresh if not in check mode.') + result = cmd_invocations[asg_state](aws_retry=True, **args) + instance_refreshes = conn.describe_instance_refreshes(AutoScalingGroupName=asg_name, InstanceRefreshIds=[result['InstanceRefreshId']]) + result = dict( + instance_refreshes=camel_dict_to_snake_dict(instance_refreshes['InstanceRefreshes'][0]) + ) + return module.exit_json(**result) + except (BotoCoreError, ClientError) as e: + module.fail_json_aws( + e, + msg='Failed to {0} InstanceRefresh'.format( + asg_state.replace('ed', '') + ) + ) + + +def main(): + + argument_spec = dict( + state=dict( + type='str', + required=True, + choices=['started', 'cancelled'], + ), + name=dict(required=True), + strategy=dict( + type='str', + default='Rolling', + required=False + ), + preferences=dict( + type='dict', + required=False, + options=dict( + min_healthy_percentage=dict(type='int', default=90), + instance_warmup=dict(type='int'), + ) + ), + ) + + module = AnsibleAWSModule( + argument_spec=argument_spec, + supports_check_mode=True, + ) + autoscaling = module.client( + 'autoscaling', + retry_decorator=AWSRetry.jittered_backoff( + retries=10, + catch_extra_error_codes=['InstanceRefreshInProgress'] + ) + ) + + start_or_cancel_instance_refresh(autoscaling, module) + + +if __name__ == '__main__': + main() diff --git a/plugins/modules/ec2_asg_instance_refresh_info.py b/plugins/modules/ec2_asg_instance_refresh_info.py new file mode 100644 --- /dev/null +++ b/plugins/modules/ec2_asg_instance_refresh_info.py @@ -0,0 +1,219 @@ +#!/usr/bin/python +# Copyright: Ansible Project +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function + + +__metaclass__ = type + + +DOCUMENTATION = ''' +--- +module: ec2_asg_instance_refresh_info +version_added: 3.2.0 +short_description: Gather information about ec2 Auto Scaling Group (ASG) Instance Refreshes in AWS +description: + - Describes one or more instance refreshes. + - You can determine the status of a request by looking at the I(status) parameter. +author: "Dan Khersonsky (@danquixote)" +options: + name: + description: + - The name of the Auto Scaling group. + type: str + required: true + ids: + description: + - One or more instance refresh IDs. + type: list + elements: str + default: [] + next_token: + description: + - The token for the next set of items to return. (You received this token from a previous call.) + type: str + max_records: + description: + - The maximum number of items to return with this call. The default value is 50 and the maximum value is 100. + type: int + required: false +extends_documentation_fragment: +- amazon.aws.aws +- amazon.aws.ec2 + +''' + +EXAMPLES = ''' +# Note: These examples do not set authentication details, see the AWS Guide for details. + +- name: Find an refresh by ASG name + community.aws.ec2_asg_instance_refresh_info: + name: somename-asg + +- name: Find an refresh by ASG name and one or more refresh-IDs + community.aws.ec2_asg_instance_refresh_info: + name: somename-asg + ids: ['some-id-123'] + register: asgs + +- name: Find an refresh by ASG name and set max_records + community.aws.ec2_asg_instance_refresh_info: + name: somename-asg + max_records: 4 + register: asgs + +- name: Find an refresh by ASG name and NextToken, if received from a previous call + community.aws.ec2_asg_instance_refresh_info: + name: somename-asg + next_token: 'some-token-123' + register: asgs +''' + +RETURN = ''' +--- +instance_refresh_id: + description: instance refresh id + returned: success + type: str + sample: "08b91cf7-8fa6-48af-b6a6-d227f40f1b9b" +auto_scaling_group_name: + description: Name of autoscaling group + returned: success + type: str + sample: "public-webapp-production-1" +status: + description: + - The current state of the group when DeleteAutoScalingGroup is in progress. + - The following are the possible statuses + - Pending -- The request was created, but the operation has not started. + - InProgress -- The operation is in progress. + - Successful -- The operation completed successfully. + - Failed -- The operation failed to complete. You can troubleshoot using the status reason and the scaling activities. + - Cancelling -- + - An ongoing operation is being cancelled. + - Cancellation does not roll back any replacements that have already been completed, + - but it prevents new replacements from being started. + - Cancelled -- The operation is cancelled. + returned: success + type: str + sample: "Pending" +start_time: + description: The date and time this ASG was created, in ISO 8601 format. + returned: success + type: str + sample: "2015-11-25T00:05:36.309Z" +end_time: + description: The date and time this ASG was created, in ISO 8601 format. + returned: success + type: str + sample: "2015-11-25T00:05:36.309Z" +percentage_complete: + description: the % of completeness + returned: success + type: int + sample: 100 +instances_to_update: + description: num. of instance to update + returned: success + type: int + sample: 5 +''' + +try: + from botocore.exceptions import BotoCoreError, ClientError +except ImportError: + pass # caught by AnsibleAWSModule + +from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AWSRetry +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import camel_dict_to_snake_dict + + +def find_asg_instance_refreshes(conn, module): + """ + Args: + conn (boto3.AutoScaling.Client): Valid Boto3 ASG client. + module: AnsibleAWSModule object + + Returns: + { + "instance_refreshes": [ + { + 'auto_scaling_group_name': 'ansible-test-hermes-63642726-asg', + 'instance_refresh_id': '6507a3e5-4950-4503-8978-e9f2636efc09', + 'instances_to_update': 1, + 'percentage_complete': 0, + "preferences": { + "instance_warmup": 60, + "min_healthy_percentage": 90, + "skip_matching": false + }, + 'start_time': '2021-02-04T03:39:40+00:00', + 'status': 'Cancelled', + 'status_reason': 'Cancelled due to user request.', + } + ], + 'next_token': 'string' + } + """ + + asg_name = module.params.get('name') + asg_ids = module.params.get('ids') + asg_next_token = module.params.get('next_token') + asg_max_records = module.params.get('max_records') + + args = {} + args['AutoScalingGroupName'] = asg_name + if asg_ids: + args['InstanceRefreshIds'] = asg_ids + if asg_next_token: + args['NextToken'] = asg_next_token + if asg_max_records: + args['MaxRecords'] = asg_max_records + + try: + instance_refreshes_result = {} + response = conn.describe_instance_refreshes(**args) + if 'InstanceRefreshes' in response: + instance_refreshes_dict = dict( + instance_refreshes=response['InstanceRefreshes'], next_token=response.get('next_token', '')) + instance_refreshes_result = camel_dict_to_snake_dict( + instance_refreshes_dict) + + while 'NextToken' in response: + args['NextToken'] = response['NextToken'] + response = conn.describe_instance_refreshes(**args) + if 'InstanceRefreshes' in response: + instance_refreshes_dict = camel_dict_to_snake_dict(dict( + instance_refreshes=response['InstanceRefreshes'], next_token=response.get('next_token', ''))) + instance_refreshes_result.update(instance_refreshes_dict) + + return module.exit_json(**instance_refreshes_result) + except (BotoCoreError, ClientError) as e: + module.fail_json_aws(e, msg='Failed to describe InstanceRefreshes') + + +def main(): + + argument_spec = dict( + name=dict(required=True, type='str'), + ids=dict(required=False, default=[], elements='str', type='list'), + next_token=dict(required=False, default=None, type='str', no_log=True), + max_records=dict(required=False, type='int'), + ) + + module = AnsibleAWSModule( + argument_spec=argument_spec, + supports_check_mode=True, + ) + + autoscaling = module.client( + 'autoscaling', + retry_decorator=AWSRetry.jittered_backoff(retries=10) + ) + find_asg_instance_refreshes(autoscaling, module) + + +if __name__ == '__main__': + main()
diff --git a/tests/integration/targets/ec2_asg_instance_refresh/aliases b/tests/integration/targets/ec2_asg_instance_refresh/aliases new file mode 100644 --- /dev/null +++ b/tests/integration/targets/ec2_asg_instance_refresh/aliases @@ -0,0 +1,2 @@ +cloud/aws +ec2_asg_instance_refresh_info diff --git a/tests/integration/targets/ec2_asg_instance_refresh/defaults/main.yml b/tests/integration/targets/ec2_asg_instance_refresh/defaults/main.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/ec2_asg_instance_refresh/defaults/main.yml @@ -0,0 +1,5 @@ +--- +# defaults file for ec2_asg +vpc_seed: '{{ tiny_prefix }}' +ec2_ami_name: 'amzn2-ami-hvm-2.*-x86_64-gp2' +subnet_a_cidr: '10.{{ 256 | random(seed=vpc_seed) }}.32.0/24' diff --git a/tests/integration/targets/ec2_asg_instance_refresh/tasks/main.yml b/tests/integration/targets/ec2_asg_instance_refresh/tasks/main.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/ec2_asg_instance_refresh/tasks/main.yml @@ -0,0 +1,533 @@ +--- +- name: setup credentials and region + module_defaults: + group/aws: + aws_access_key: "{{ aws_access_key }}" + aws_secret_key: "{{ aws_secret_key }}" + security_token: "{{ security_token | default(omit) }}" + region: "{{ aws_region }}" + + collections: + - amazon.aws + + block: + + #NOTE: entire ASG setup is 'borrowed' from ec2_asg + - name: Find AMI to use + ec2_ami_info: + owners: 'amazon' + filters: + name: '{{ ec2_ami_name }}' + register: ec2_amis + - set_fact: + ec2_ami_image: '{{ ec2_amis.images[0].image_id }}' + + - name: load balancer name has to be less than 32 characters + set_fact: + load_balancer_name: "{{ item }}-lb" + loop: "{{ resource_prefix | regex_findall('.{8}$') }}" + + # Set up the testing dependencies: VPC, subnet, security group, and two launch configurations + - name: Create VPC for use in testing + ec2_vpc_net: + name: "{{ resource_prefix }}-vpc" + cidr_block: '{{ subnet_a_cidr }}' + tenancy: default + register: testing_vpc + + - name: Create internet gateway for use in testing + ec2_vpc_igw: + vpc_id: "{{ testing_vpc.vpc.id }}" + state: present + register: igw + + - name: Create subnet for use in testing + ec2_vpc_subnet: + state: present + vpc_id: "{{ testing_vpc.vpc.id }}" + cidr: '{{ subnet_a_cidr }}' + az: "{{ aws_region }}a" + resource_tags: + Name: "{{ resource_prefix }}-subnet" + register: testing_subnet + + - name: create routing rules + ec2_vpc_route_table: + vpc_id: "{{ testing_vpc.vpc.id }}" + tags: + created: "{{ resource_prefix }}-route" + routes: + - dest: 0.0.0.0/0 + gateway_id: "{{ igw.gateway_id }}" + subnets: + - "{{ testing_subnet.subnet.id }}" + + - name: create a security group with the vpc created in the ec2_setup + ec2_group: + name: "{{ resource_prefix }}-sg" + description: a security group for ansible tests + vpc_id: "{{ testing_vpc.vpc.id }}" + rules: + - proto: tcp + from_port: 22 + to_port: 22 + cidr_ip: 0.0.0.0/0 + - proto: tcp + from_port: 80 + to_port: 80 + cidr_ip: 0.0.0.0/0 + register: sg + + - name: ensure launch configs exist + ec2_lc: + name: "{{ item }}" + assign_public_ip: true + image_id: "{{ ec2_ami_image }}" + user_data: | + package_upgrade: true + package_update: true + packages: + - httpd + runcmd: + - "service httpd start" + security_groups: "{{ sg.group_id }}" + instance_type: t3.micro + loop: + - "{{ resource_prefix }}-lc" + - "{{ resource_prefix }}-lc-2" + + - name: launch asg and do not wait for instances to be deemed healthy (no ELB) + ec2_asg: + name: "{{ resource_prefix }}-asg" + launch_config_name: "{{ resource_prefix }}-lc" + desired_capacity: 1 + min_size: 1 + max_size: 1 + vpc_zone_identifier: "{{ testing_subnet.subnet.id }}" + wait_for_instances: no + state: present + register: output + + - assert: + that: + - "output.viable_instances == 0" + + # ============================================================ + + - name: test invalid cancelation - V1 - (pre-refresh) + ec2_asg_instance_refresh: + name: "{{ resource_prefix }}-asg" + state: "cancelled" + ignore_errors: yes + register: result + + - assert: + that: + - "'An error occurred (ActiveInstanceRefreshNotFound) when calling the CancelInstanceRefresh operation: No in progress or pending Instance Refresh found for Auto Scaling group {{ resource_prefix }}-asg' in result.msg" + + - name: test starting a refresh with a valid ASG name - check_mode + ec2_asg_instance_refresh: + name: "{{ resource_prefix }}-asg" + state: "started" + check_mode: true + register: output + + - assert: + that: + - output is not failed + - output is changed + - '"autoscaling:StartInstanceRefresh" not in output.resource_actions' + + - name: test starting a refresh with a valid ASG name + ec2_asg_instance_refresh: + name: "{{ resource_prefix }}-asg" + state: "started" + register: output + + - assert: + that: + - "'instance_refresh_id' in output.instance_refreshes" + + - name: test starting a refresh with a valid ASG name - Idempotent + ec2_asg_instance_refresh: + name: "{{ resource_prefix }}-asg" + state: "started" + ignore_errors: true + register: output + + - assert: + that: + - output is not changed + - '"Failed to start InstanceRefresh: An error occurred (InstanceRefreshInProgress) when calling the StartInstanceRefresh operation: An Instance Refresh is already in progress and blocks the execution of this Instance Refresh." in output.msg' + + - name: test starting a refresh with a valid ASG name - Idempotent (check_mode) + ec2_asg_instance_refresh: + name: "{{ resource_prefix }}-asg" + state: "started" + ignore_errors: true + check_mode: true + register: output + + - assert: + that: + - output is not changed + - output is not failed + - '"In check_mode - Instance Refresh is already in progress, can not start new instance refresh." in output.msg' + + - name: test starting a refresh with a nonexistent ASG name + ec2_asg_instance_refresh: + name: "nonexistentname-asg" + state: "started" + ignore_errors: yes + register: result + + - assert: + that: + - "'Failed to start InstanceRefresh: An error occurred (ValidationError) when calling the StartInstanceRefresh operation: AutoScalingGroup name not found' in result.msg" + + - name: test canceling a refresh with an ASG name - check_mode + ec2_asg_instance_refresh: + name: "{{ resource_prefix }}-asg" + state: "cancelled" + check_mode: true + register: output + + - assert: + that: + - output is not failed + - output is changed + - '"autoscaling:CancelInstanceRefresh" not in output.resource_actions' + + - name: test canceling a refresh with an ASG name + ec2_asg_instance_refresh: + name: "{{ resource_prefix }}-asg" + state: "cancelled" + register: output + + - assert: + that: + - "'instance_refresh_id' in output.instance_refreshes" + + - name: test canceling a refresh with a ASG name - Idempotent + ec2_asg_instance_refresh: + name: "{{ resource_prefix }}-asg" + state: "cancelled" + ignore_errors: yes + register: output + + - assert: + that: + - output is not changed + + - name: test cancelling a refresh with a valid ASG name - Idempotent (check_mode) + ec2_asg_instance_refresh: + name: "{{ resource_prefix }}-asg" + state: "cancelled" + ignore_errors: true + check_mode: true + register: output + + - assert: + that: + - output is not changed + - output is not failed + + - name: test starting a refresh with an ASG name and preferences dict + ec2_asg_instance_refresh: + name: "{{ resource_prefix }}-asg" + state: "started" + preferences: + min_healthy_percentage: 10 + instance_warmup: 10 + retries: 5 + register: output + until: output is not failed + + - assert: + that: + - "'instance_refresh_id' in output.instance_refreshes" + + - name: re-test canceling a refresh with an ASG name + ec2_asg_instance_refresh: + name: "{{ resource_prefix }}-asg" + state: "cancelled" + register: output + + - assert: + that: + - "'instance_refresh_id' in output.instance_refreshes" + + - name: test valid start - V1 - (with preferences missing instance_warmup) + ec2_asg_instance_refresh: + name: "{{ resource_prefix }}-asg" + state: "started" + preferences: + min_healthy_percentage: 10 + ignore_errors: yes + retries: 5 + register: output + until: output is not failed + + - assert: + that: + - "'instance_refresh_id' in output.instance_refreshes" + + - name: re-test canceling a refresh with an ASG name + ec2_asg_instance_refresh: + name: "{{ resource_prefix }}-asg" + state: "cancelled" + register: output + + - assert: + that: + - "'instance_refresh_id' in output.instance_refreshes" + + - name: test valid start - V2 - (with preferences missing min_healthy_percentage) + ec2_asg_instance_refresh: + name: "{{ resource_prefix }}-asg" + state: "started" + preferences: + instance_warmup: 10 + retries: 5 + register: output + until: output is not failed + ignore_errors: yes + + - assert: + that: + - "'instance_refresh_id' in output.instance_refreshes" + + - name: test invalid cancelation - V2 - (with preferences) + ec2_asg_instance_refresh: + name: "{{ resource_prefix }}-asg" + state: "cancelled" + preferences: + min_healthy_percentage: 10 + instance_warmup: 10 + ignore_errors: yes + register: result + + - assert: + that: + - "'can not pass preferences dict when canceling a refresh' in result.msg" + + # ============================================================ + + - name: run setup with refresh_and_cancel_three_times.yml + include_tasks: refresh_and_cancel_three_times.yml + loop: "{{ query('sequence', 'start=1 end=3') }}" + + - name: test getting info for an ASG name + ec2_asg_instance_refresh_info: + name: "{{ resource_prefix }}-asg" + region: "{{ aws_region }}" + ignore_errors: yes + register: output + + - assert: + that: + - output | community.general.json_query(inst_refresh_id_json_query) | unique | length == 7 + vars: + inst_refresh_id_json_query: instance_refreshes[].instance_refresh_id + + - name: test using fake refresh ID + ec2_asg_instance_refresh_info: + name: "{{ resource_prefix }}-asg" + ids: ['0e367f58-blabla-bla-bla-ca870dc5dbfe'] + ignore_errors: yes + register: output + + - assert: + that: + - "{{ output.instance_refreshes|length }} == 0" + + - name: test using a real refresh ID + ec2_asg_instance_refresh_info: + name: "{{ resource_prefix }}-asg" + ids: [ '{{ refreshout.instance_refreshes.instance_refresh_id }}' ] + ignore_errors: yes + register: output + + - assert: + that: + - "{{ output.instance_refreshes |length }} == 1" + + - name: test getting info for an ASG name which doesn't exist + ec2_asg_instance_refresh_info: + name: n0n3x1stentname27b + ignore_errors: yes + register: output + + - assert: + that: + - "'Failed to describe InstanceRefreshes: An error occurred (ValidationError) when calling the DescribeInstanceRefreshes operation: AutoScalingGroup name not found - AutoScalingGroup n0n3x1stentname27b not found' == output.msg" + + - name: assert that the correct number of records are returned + ec2_asg_instance_refresh_info: + name: "{{ resource_prefix }}-asg" + ignore_errors: yes + register: output + + - assert: + that: + - "{{ output.instance_refreshes|length }} == 7" + + - name: assert that valid message with fake-token is returned + ec2_asg_instance_refresh_info: + name: "{{ resource_prefix }}-asg" + next_token: "fake-token-123" + ignore_errors: yes + register: output + + - assert: + that: + - '"Failed to describe InstanceRefreshes: An error occurred (InvalidNextToken) when calling the DescribeInstanceRefreshes operation: The token ''********'' is invalid." == output.msg' + + - name: assert that max records=1 returns no more than one record + ec2_asg_instance_refresh_info: + name: "{{ resource_prefix }}-asg" + max_records: 1 + ignore_errors: yes + register: output + + - assert: + that: + - "{{ output.instance_refreshes|length }} < 2" + + - name: assert that valid message with real-token is returned + ec2_asg_instance_refresh_info: + name: "{{ resource_prefix }}-asg" + next_token: "{{ output.next_token }}" + ignore_errors: yes + register: output + + - assert: + that: + - "{{ output.instance_refreshes|length }} == 7" + + - name: test using both real nextToken and max_records=1 + ec2_asg_instance_refresh_info: + name: "{{ resource_prefix }}-asg" + max_records: 1 + next_token: "{{ output.next_token }}" + ignore_errors: yes + register: output + + - assert: + that: + - "{{ output.instance_refreshes|length }} == 1" + + always: + + - name: kill asg + ec2_asg: + name: "{{ resource_prefix }}-asg" + state: absent + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10 + # Remove the testing dependencies + + - name: remove the load balancer + ec2_elb_lb: + name: "{{ load_balancer_name }}" + state: absent + security_group_ids: + - "{{ sg.group_id }}" + subnets: "{{ testing_subnet.subnet.id }}" + wait: yes + connection_draining_timeout: 60 + listeners: + - protocol: http + load_balancer_port: 80 + instance_port: 80 + health_check: + ping_protocol: tcp + ping_port: 80 + ping_path: "/" + response_timeout: 5 + interval: 10 + unhealthy_threshold: 4 + healthy_threshold: 2 + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10 + + - name: remove launch configs + ec2_lc: + name: "{{ resource_prefix }}-lc" + state: absent + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10 + loop: + - "{{ resource_prefix }}-lc" + - "{{ resource_prefix }}-lc-2" + + - name: delete launch template + ec2_launch_template: + name: "{{ resource_prefix }}-lt" + state: absent + register: del_lt + retries: 10 + until: del_lt is not failed + ignore_errors: true + + - name: remove the security group + ec2_group: + name: "{{ resource_prefix }}-sg" + description: a security group for ansible tests + vpc_id: "{{ testing_vpc.vpc.id }}" + state: absent + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10 + + - name: remove routing rules + ec2_vpc_route_table: + state: absent + vpc_id: "{{ testing_vpc.vpc.id }}" + tags: + created: "{{ resource_prefix }}-route" + routes: + - dest: 0.0.0.0/0 + gateway_id: "{{ igw.gateway_id }}" + subnets: + - "{{ testing_subnet.subnet.id }}" + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10 + + - name: remove internet gateway + ec2_vpc_igw: + vpc_id: "{{ testing_vpc.vpc.id }}" + state: absent + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10 + + - name: remove the subnet + ec2_vpc_subnet: + state: absent + vpc_id: "{{ testing_vpc.vpc.id }}" + cidr: '{{ subnet_a_cidr }}' + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10 + + - name: remove the VPC + ec2_vpc_net: + name: "{{ resource_prefix }}-vpc" + cidr_block: '{{ subnet_a_cidr }}' + state: absent + register: removed + until: removed is not failed + ignore_errors: yes + retries: 10 diff --git a/tests/integration/targets/ec2_asg_instance_refresh/tasks/refresh_and_cancel_three_times.yml b/tests/integration/targets/ec2_asg_instance_refresh/tasks/refresh_and_cancel_three_times.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/ec2_asg_instance_refresh/tasks/refresh_and_cancel_three_times.yml @@ -0,0 +1,29 @@ +--- + +- name: try to cancel pre-loop + ec2_asg_instance_refresh: + name: "{{ resource_prefix }}-asg" + state: "cancelled" + ignore_errors: yes + +- name: test starting a refresh with an ASG name + ec2_asg_instance_refresh: + name: "{{ resource_prefix }}-asg" + state: "started" + aws_access_key: "{{ aws_access_key }}" + aws_secret_key: "{{ aws_secret_key }}" + region: "{{ aws_region }}" + ignore_errors: no + retries: 10 + delay: 5 + register: refreshout + until: refreshout is not failed + +- name: test cancelling a refresh with an ASG name + ec2_asg_instance_refresh: + name: "{{ resource_prefix }}-asg" + state: "cancelled" + aws_access_key: "{{ aws_access_key }}" + aws_secret_key: "{{ aws_secret_key }}" + region: "{{ aws_region }}" + ignore_errors: yes diff --git a/tests/integration/targets/ec2_asg_instance_refresh/vars/main.yml b/tests/integration/targets/ec2_asg_instance_refresh/vars/main.yml new file mode 100644
Autoscaling instance refresh API support <!--- Verify first that your feature was not already discussed on GitHub --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Describe the new feature/improvement briefly below --> AWS recently introduced "Instance refresh" feature in ASG. Using it is preferred way to update launch configuration in ASG ##### ISSUE TYPE - Feature Idea ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> ec2_asg ##### ADDITIONAL INFORMATION <!--- Describe how the feature would be used, why it is needed and what it would solve --> Deploying ASG from the client depends on internet connectivity and is not transactional. In the middle of deployment of ASG it can fail leaving ASG in unpredicted state. Using AWS infrastructure will add more stability in deployment (and probably will make it faster) More about the feature: https://aws.amazon.com/blogs/compute/introducing-instance-refresh-for-ec2-auto-scaling/ Boto3 documentation: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/autoscaling.html#AutoScaling.Client.start_instance_refresh <!--- Paste example playbooks or commands between quotes below --> ```yaml - commutiny.aws.ec2_asg_instance_refresh: name: some-backend ``` <!--- HINT: You can also paste gist.github.com links for larger files -->
Files identified in the description: * [`plugins/modules/ec2_asg.py`](https://github.com/ansible-collections/community.aws/blob/main/plugins/modules/ec2_asg.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @garethr @jillr @s-hertel @tremble @wimnat [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> Hello @goneri et al. I've submitted a PR here: https://github.com/ansible-collections/community.aws/pull/425 cc @markuman [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify --->
2022-03-24T16:54:10
ansible-collections/community.aws
1,021
ansible-collections__community.aws-1021
[ "601" ]
94c7ca80f5396f138800bbcc08171d09f35ed7a8
diff --git a/plugins/modules/sns_topic_info.py b/plugins/modules/sns_topic_info.py new file mode 100644 --- /dev/null +++ b/plugins/modules/sns_topic_info.py @@ -0,0 +1,167 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# Copyright: Ansible Project +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + +DOCUMENTATION = r''' +module: sns_topic_info +short_description: sns_topic_info module +version_added: 3.2.0 +description: +- The M(community.aws.sns_topic_info) module allows to get all AWS SNS topics or properties of a specific AWS SNS topic. +author: +- "Alina Buzachis (@alinabuzachis)" +options: + topic_arn: + description: The ARN of the AWS SNS topic for which you wish to find subscriptions or list attributes. + required: false + type: str +extends_documentation_fragment: +- amazon.aws.aws +- amazon.aws.ec2 +''' + +EXAMPLES = r''' +- name: list all the topics + community.aws.sns_topic_info: + register: sns_topic_list + +- name: get info on specific topic + community.aws.sns_topic_info: + topic_arn: "{{ sns_arn }}" + register: sns_topic_info +''' + +RETURN = r''' +result: + description: + - The result contaning the details of one or all AWS SNS topics. + returned: success + type: list + contains: + sns_arn: + description: The ARN of the topic. + type: str + returned: always + sample: "arn:aws:sns:us-east-2:111111111111:my_topic_name" + sns_topic: + description: Dict of sns topic details. + type: complex + returned: always + contains: + delivery_policy: + description: Delivery policy for the SNS topic. + returned: when topic is owned by this AWS account + type: str + sample: > + {"http":{"defaultHealthyRetryPolicy":{"minDelayTarget":20,"maxDelayTarget":20,"numRetries":3,"numMaxDelayRetries":0, + "numNoDelayRetries":0,"numMinDelayRetries":0,"backoffFunction":"linear"},"disableSubscriptionOverrides":false}} + display_name: + description: Display name for SNS topic. + returned: when topic is owned by this AWS account + type: str + sample: My topic name + owner: + description: AWS account that owns the topic. + returned: when topic is owned by this AWS account + type: str + sample: '111111111111' + policy: + description: Policy for the SNS topic. + returned: when topic is owned by this AWS account + type: str + sample: > + {"Version":"2012-10-17","Id":"SomePolicyId","Statement":[{"Sid":"ANewSid","Effect":"Allow","Principal":{"AWS":"arn:aws:iam::111111111111:root"}, + "Action":"sns:Subscribe","Resource":"arn:aws:sns:us-east-2:111111111111:ansible-test-dummy-topic","Condition":{"StringEquals":{"sns:Protocol":"email"}}}]} + subscriptions: + description: List of subscribers to the topic in this AWS account. + returned: always + type: list + sample: [] + subscriptions_added: + description: List of subscribers added in this run. + returned: always + type: list + sample: [] + subscriptions_confirmed: + description: Count of confirmed subscriptions. + returned: when topic is owned by this AWS account + type: str + sample: '0' + subscriptions_deleted: + description: Count of deleted subscriptions. + returned: when topic is owned by this AWS account + type: str + sample: '0' + subscriptions_existing: + description: List of existing subscriptions. + returned: always + type: list + sample: [] + subscriptions_new: + description: List of new subscriptions. + returned: always + type: list + sample: [] + subscriptions_pending: + description: Count of pending subscriptions. + returned: when topic is owned by this AWS account + type: str + sample: '0' + subscriptions_purge: + description: Whether or not purge_subscriptions was set. + returned: always + type: bool + sample: true + topic_arn: + description: ARN of the SNS topic (equivalent to sns_arn). + returned: when topic is owned by this AWS account + type: str + sample: arn:aws:sns:us-east-2:111111111111:ansible-test-dummy-topic + topic_type: + description: The type of topic. + type: str + sample: "standard" +''' + + +try: + import botocore +except ImportError: + pass # handled by AnsibleAWSModule + +from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AWSRetry +from ansible_collections.community.aws.plugins.module_utils.sns import list_topics +from ansible_collections.community.aws.plugins.module_utils.sns import get_info + + +def main(): + argument_spec = dict( + topic_arn=dict(type='str', required=False), + ) + + module = AnsibleAWSModule(argument_spec=argument_spec, + supports_check_mode=True) + + topic_arn = module.params.get('topic_arn') + + try: + connection = module.client('sns', retry_decorator=AWSRetry.jittered_backoff()) + except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: + module.fail_json_aws(e, msg='Failed to connect to AWS.') + + if topic_arn: + results = dict(sns_arn=topic_arn, sns_topic=get_info(connection, module, topic_arn)) + else: + results = list_topics(connection, module) + + module.exit_json(result=results) + + +if __name__ == '__main__': + main()
diff --git a/tests/integration/targets/sns_topic/aliases b/tests/integration/targets/sns_topic/aliases --- a/tests/integration/targets/sns_topic/aliases +++ b/tests/integration/targets/sns_topic/aliases @@ -1 +1,3 @@ cloud/aws + +sns_topic_info diff --git a/tests/integration/targets/sns_topic/tasks/main.yml b/tests/integration/targets/sns_topic/tasks/main.yml --- a/tests/integration/targets/sns_topic/tasks/main.yml +++ b/tests/integration/targets/sns_topic/tasks/main.yml @@ -4,8 +4,7 @@ aws_access_key: '{{ aws_access_key }}' security_token: '{{ security_token|default(omit) }}' region: '{{ aws_region }}' - collections: - - community.general + block: - name: create minimal lambda role (needed for subscription test further down) @@ -22,6 +21,25 @@ seconds: 10 when: iam_role is changed + - name: list all the topics (check_mode) + sns_topic_info: + check_mode: true + register: sns_topic_list + + - name: assert success + assert: + that: + - sns_topic_list is successful + + - name: list all the topics + sns_topic_info: + register: sns_topic_list + + - name: assert success + assert: + that: + - sns_topic_list is successful + - name: create standard SNS topic sns_topic: name: '{{ sns_topic_topic_name }}' @@ -37,6 +55,41 @@ set_fact: sns_arn: '{{ sns_topic_create.sns_arn }}' + - name: get info on specific topic (check_mode) + sns_topic_info: + topic_arn: "{{ sns_arn }}" + check_mode: true + register: sns_topic_info + + - name: assert success + assert: + that: + - sns_topic_info is successful + - "'result' in sns_topic_info" + - sns_topic_info.result["sns_arn"] == "{{ sns_arn }}" + - "'sns_topic' in sns_topic_info.result" + - "'display_name' in sns_topic_info.result['sns_topic']" + - sns_topic_info.result["sns_topic"]["display_name"] == "My topic name" + - "'owner' in sns_topic_info.result['sns_topic']" + - "'policy' in sns_topic_info.result['sns_topic']" + + - name: get info on specific topic + sns_topic_info: + topic_arn: "{{ sns_arn }}" + register: sns_topic_info + + - name: assert success + assert: + that: + - sns_topic_info is successful + - "'result' in sns_topic_info" + - sns_topic_info.result["sns_arn"] == "{{ sns_arn }}" + - "'sns_topic' in sns_topic_info.result" + - "'display_name' in sns_topic_info.result['sns_topic']" + - sns_topic_info.result["sns_topic"]["display_name"] == "My topic name" + - "'owner' in sns_topic_info.result['sns_topic']" + - "'policy' in sns_topic_info.result['sns_topic']" + - name: create topic again (expect changed=False) sns_topic: name: '{{ sns_topic_topic_name }}'
community.aws.sns_topic_info module missing ##### SUMMARY community.aws.sns_topic_info module missing ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME community.aws.sns_topic exists, however the equivelent _info module is not yet developed. The _info module would be useful to detect the current state of sns_topics. ##### ANSIBLE VERSION ``` $ ansible --version ansible 2.10.8 config file = /home/nobody/src/mobile-ansible-core/ansible.cfg configured module search path = ['/home/nobody/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /home/nobody/.cache/venv/mobile-ansible-core-3.8/lib/python3.8/site-packages/ansible executable location = /home/nobody/.cache/venv/mobile-ansible-core-3.8/bin/ansible python version = 3.8.2 (default, Jan 1 1970, 00:00:01) [GCC 7.5.0] ``` and using ``` - name: community.aws version: 1.5.0 ```
Files identified in the description: * [`plugins/modules/sns_topic.py`](https://github.com/['ansible-collections/amazon.aws', 'ansible-collections/community.aws', 'ansible-collections/community.vmware']/blob/main/plugins/modules/sns_topic.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> @divansantana: Greetings! Thanks for taking the time to open this issue. In order for the community to handle your issue effectively, we need a bit more information. Here are the items we could not find in your description: - ansible version Please set the description of this issue with this template: https://raw.githubusercontent.com/ansible/ansible/devel/.github/ISSUE_TEMPLATE/bug_report.md [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: issue_missing_data ---> cc @jillr @joelthompson @nand0p @s-hertel @tremble @wimnat [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> cc @markuman [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify --->
2022-03-28T10:01:49
ansible-collections/community.aws
1,025
ansible-collections__community.aws-1025
[ "28" ]
3a88e2a7106517ae3196ae95e65e61e0d0b9e398
diff --git a/plugins/modules/elb_application_lb.py b/plugins/modules/elb_application_lb.py --- a/plugins/modules/elb_application_lb.py +++ b/plugins/modules/elb_application_lb.py @@ -48,21 +48,46 @@ type: str deletion_protection: description: - - Indicates whether deletion protection for the ELB is enabled. - - Defaults to C(false). + - Indicates whether deletion protection for the ALB is enabled. + - Defaults to C(False). type: bool http2: description: - Indicates whether to enable HTTP2 routing. - - Defaults to C(false). + - Defaults to C(True). type: bool + http_desync_mitigation_mode: + description: + - Determines how the load balancer handles requests that might pose a security risk to an application. + - Defaults to C('defensive') + type: str + choices: ['monitor', 'defensive', 'strictest'] + version_added: 3.2.0 + http_drop_invalid_header_fields: + description: + - Indicates whether HTTP headers with invalid header fields are removed by the load balancer C(True) or routed to targets C(False). + - Defaults to C(False). + type: bool + version_added: 3.2.0 + http_x_amzn_tls_version_and_cipher_suite: + description: + - Indicates whether the two headers are added to the client request before sending it to the target. + - Defaults to C(False). + type: bool + version_added: 3.2.0 + http_xff_client_port: + description: + - Indicates whether the X-Forwarded-For header should preserve the source port that the client used to connect to the load balancer. + - Defaults to C(False). + type: bool + version_added: 3.2.0 idle_timeout: description: - The number of seconds to wait before an idle connection is closed. type: int listeners: description: - - A list of dicts containing listeners to attach to the ELB. See examples for detail of the dict required. Note that listener keys + - A list of dicts containing listeners to attach to the ALB. See examples for detail of the dict required. Note that listener keys are CamelCased. type: list elements: dict @@ -123,7 +148,7 @@ type: str purge_listeners: description: - - If C(yes), existing listeners will be purged from the ELB to match exactly what is defined by I(listeners) parameter. + - If C(yes), existing listeners will be purged from the ALB to match exactly what is defined by I(listeners) parameter. - If the I(listeners) parameter is not set then listeners will not be modified. default: yes type: bool @@ -144,12 +169,12 @@ description: - A list of the names or IDs of the security groups to assign to the load balancer. - Required if I(state=present). - default: [] + - If C([]), the VPC's default security group will be used. type: list elements: str scheme: description: - - Internet-facing or internal load balancer. An ELB scheme can not be modified after creation. + - Internet-facing or internal load balancer. An ALB scheme can not be modified after creation. default: internet-facing choices: [ 'internet-facing', 'internal' ] type: str @@ -183,6 +208,12 @@ - Sets the type of IP addresses used by the subnets of the specified Application Load Balancer. choices: [ 'ipv4', 'dualstack' ] type: str + waf_fail_open: + description: + - Indicates whether to allow a AWS WAF-enabled load balancer to route requests to targets if it is unable to forward the request to AWS WAF. + - Defaults to C(False). + type: bool + version_added: 3.2.0 extends_documentation_fragment: - amazon.aws.aws - amazon.aws.ec2 @@ -195,9 +226,9 @@ EXAMPLES = r''' # Note: These examples do not set authentication details, see the AWS Guide for details. -# Create an ELB and attach a listener +# Create an ALB and attach a listener - community.aws.elb_application_lb: - name: myelb + name: myalb security_groups: - sg-12345678 - my-sec-group @@ -216,12 +247,12 @@ TargetGroupName: # Required. The name of the target group state: present -# Create an ELB and attach a listener with logging enabled +# Create an ALB and attach a listener with logging enabled - community.aws.elb_application_lb: access_logs_enabled: yes access_logs_s3_bucket: mybucket access_logs_s3_prefix: "logs" - name: myelb + name: myalb security_groups: - sg-12345678 - my-sec-group @@ -303,9 +334,9 @@ Type: forward state: present -# Remove an ELB +# Remove an ALB - community.aws.elb_application_lb: - name: myelb + name: myalb state: absent ''' @@ -315,27 +346,32 @@ description: The name of the S3 bucket for the access logs. returned: when state is present type: str - sample: mys3bucket + sample: "mys3bucket" access_logs_s3_enabled: description: Indicates whether access logs stored in Amazon S3 are enabled. returned: when state is present - type: str + type: bool sample: true access_logs_s3_prefix: description: The prefix for the location in the S3 bucket. returned: when state is present type: str - sample: my/logs + sample: "my/logs" availability_zones: description: The Availability Zones for the load balancer. returned: when state is present type: list - sample: "[{'subnet_id': 'subnet-aabbccddff', 'zone_name': 'ap-southeast-2a'}]" + sample: [{ "load_balancer_addresses": [], "subnet_id": "subnet-aabbccddff", "zone_name": "ap-southeast-2a" }] canonical_hosted_zone_id: description: The ID of the Amazon Route 53 hosted zone associated with the load balancer. returned: when state is present type: str - sample: ABCDEF12345678 + sample: "ABCDEF12345678" +changed: + description: Whether an ALB was created/updated/deleted + returned: always + type: bool + sample: true created_time: description: The date and time the load balancer was created. returned: when state is present @@ -344,23 +380,23 @@ deletion_protection_enabled: description: Indicates whether deletion protection is enabled. returned: when state is present - type: str + type: bool sample: true dns_name: description: The public DNS name of the load balancer. returned: when state is present type: str - sample: internal-my-elb-123456789.ap-southeast-2.elb.amazonaws.com + sample: "internal-my-elb-123456789.ap-southeast-2.elb.amazonaws.com" idle_timeout_timeout_seconds: description: The idle timeout value, in seconds. returned: when state is present type: int sample: 60 ip_address_type: - description: The type of IP addresses used by the subnets for the load balancer. + description: The type of IP addresses used by the subnets for the load balancer. returned: when state is present type: str - sample: ipv4 + sample: "ipv4" listeners: description: Information about the listeners. returned: when state is present @@ -385,7 +421,7 @@ description: The protocol for connections from clients to the load balancer. returned: when state is present type: str - sample: HTTPS + sample: "HTTPS" certificates: description: The SSL server certificate. returned: when state is present @@ -420,22 +456,42 @@ description: The Amazon Resource Name (ARN) of the load balancer. returned: when state is present type: str - sample: arn:aws:elasticloadbalancing:ap-southeast-2:0123456789:loadbalancer/app/my-elb/001122334455 + sample: "arn:aws:elasticloadbalancing:ap-southeast-2:0123456789:loadbalancer/app/my-alb/001122334455" load_balancer_name: description: The name of the load balancer. returned: when state is present type: str - sample: my-elb + sample: "my-alb" routing_http2_enabled: description: Indicates whether HTTP/2 is enabled. returned: when state is present - type: str + type: bool sample: true +routing_http_desync_mitigation_mode: + description: Determines how the load balancer handles requests that might pose a security risk to an application. + returned: when state is present + type: str + sample: "defensive" +routing_http_drop_invalid_header_fields_enabled: + description: Indicates whether HTTP headers with invalid header fields are removed by the load balancer (true) or routed to targets (false). + returned: when state is present + type: bool + sample: false +routing_http_x_amzn_tls_version_and_cipher_suite_enabled: + description: Indicates whether the two headers are added to the client request before sending it to the target. + returned: when state is present + type: bool + sample: false +routing_http_xff_client_port_enabled: + description: Indicates whether the X-Forwarded-For header should preserve the source port that the client used to connect to the load balancer. + returned: when state is present + type: bool + sample: false scheme: description: Internet-facing or internal load balancer. returned: when state is present type: str - sample: internal + sample: "internal" security_groups: description: The IDs of the security groups for the load balancer. returned: when state is present @@ -445,29 +501,41 @@ description: The state of the load balancer. returned: when state is present type: dict - sample: "{'code': 'active'}" + sample: {'code': 'active'} tags: description: The tags attached to the load balancer. returned: when state is present type: dict - sample: "{ + sample: { 'Tag': 'Example' - }" + } type: description: The type of load balancer. returned: when state is present type: str - sample: application + sample: "application" vpc_id: description: The ID of the VPC for the load balancer. returned: when state is present type: str - sample: vpc-0011223344 + sample: "vpc-0011223344" +waf_fail_open_enabled: + description: Indicates whether to allow a AWS WAF-enabled load balancer to route requests to targets if it is unable to forward the request to AWS WAF. + returned: when state is present + type: bool + sample: false ''' +try: + import botocore +except ImportError: + pass # caught by AnsibleAWSModule from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule -from ansible_collections.amazon.aws.plugins.module_utils.ec2 import camel_dict_to_snake_dict, boto3_tag_list_to_ansible_dict, compare_aws_tags - +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import ansible_dict_to_boto3_filter_list +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AWSRetry +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import boto3_tag_list_to_ansible_dict +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import camel_dict_to_snake_dict +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import compare_aws_tags from ansible_collections.amazon.aws.plugins.module_utils.elbv2 import ( ApplicationLoadBalancer, ELBListener, @@ -478,134 +546,196 @@ from ansible_collections.amazon.aws.plugins.module_utils.elb_utils import get_elb_listener_rules -def create_or_update_elb(elb_obj): - """Create ELB or modify main attributes. json_exit here""" - if elb_obj.elb: - # ELB exists so check subnets, security groups and tags match what has been passed [email protected]_backoff() +def describe_sgs_with_backoff(connection, **params): + paginator = connection.get_paginator('describe_security_groups') + return paginator.paginate(**params).build_full_result()['SecurityGroups'] + + +def find_default_sg(connection, module, vpc_id): + """ + Finds the default security group for the given VPC ID. + """ + filters = ansible_dict_to_boto3_filter_list({'vpc-id': vpc_id, 'group-name': 'default'}) + try: + sg = describe_sgs_with_backoff(connection, Filters=filters) + except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: + module.fail_json_aws(e, msg='No default security group found for VPC {0}'.format(vpc_id)) + if len(sg) == 1: + return sg[0]['GroupId'] + elif len(sg) == 0: + module.fail_json(msg='No default security group found for VPC {0}'.format(vpc_id)) + else: + module.fail_json(msg='Multiple security groups named "default" found for VPC {0}'.format(vpc_id)) + +def create_or_update_alb(alb_obj): + """Create ALB or modify main attributes. json_exit here""" + if alb_obj.elb: + # ALB exists so check subnets, security groups and tags match what has been passed # Subnets - if not elb_obj.compare_subnets(): - elb_obj.modify_subnets() + if not alb_obj.compare_subnets(): + if alb_obj.module.check_mode: + alb_obj.module.exit_json(changed=True, msg='Would have updated ALB if not in check mode.') + alb_obj.modify_subnets() # Security Groups - if not elb_obj.compare_security_groups(): - elb_obj.modify_security_groups() + if not alb_obj.compare_security_groups(): + if alb_obj.module.check_mode: + alb_obj.module.exit_json(changed=True, msg='Would have updated ALB if not in check mode.') + alb_obj.modify_security_groups() + + # ALB attributes + if not alb_obj.compare_elb_attributes(): + if alb_obj.module.check_mode: + alb_obj.module.exit_json(changed=True, msg='Would have updated ALB if not in check mode.') + alb_obj.update_elb_attributes() + alb_obj.modify_elb_attributes() # Tags - only need to play with tags if tags parameter has been set to something - if elb_obj.tags is not None: + if alb_obj.tags is not None: + + tags_need_modify, tags_to_delete = compare_aws_tags(boto3_tag_list_to_ansible_dict(alb_obj.elb['tags']), + boto3_tag_list_to_ansible_dict(alb_obj.tags), alb_obj.purge_tags) + + # Exit on check_mode + if alb_obj.module.check_mode and (tags_need_modify or tags_to_delete): + alb_obj.module.exit_json(changed=True, msg='Would have updated ALB if not in check mode.') # Delete necessary tags - tags_need_modify, tags_to_delete = compare_aws_tags(boto3_tag_list_to_ansible_dict(elb_obj.elb['tags']), - boto3_tag_list_to_ansible_dict(elb_obj.tags), elb_obj.purge_tags) if tags_to_delete: - elb_obj.delete_tags(tags_to_delete) + alb_obj.delete_tags(tags_to_delete) # Add/update tags if tags_need_modify: - elb_obj.modify_tags() + alb_obj.modify_tags() else: # Create load balancer - elb_obj.create_elb() - - # ELB attributes - elb_obj.update_elb_attributes() - elb_obj.modify_elb_attributes() + if alb_obj.module.check_mode: + alb_obj.module.exit_json(changed=True, msg='Would have created ALB if not in check mode.') + alb_obj.create_elb() # Listeners - listeners_obj = ELBListeners(elb_obj.connection, elb_obj.module, elb_obj.elb['LoadBalancerArn']) - + listeners_obj = ELBListeners(alb_obj.connection, alb_obj.module, alb_obj.elb['LoadBalancerArn']) listeners_to_add, listeners_to_modify, listeners_to_delete = listeners_obj.compare_listeners() + # Exit on check_mode + if alb_obj.module.check_mode and (listeners_to_add or listeners_to_modify or listeners_to_delete): + alb_obj.module.exit_json(changed=True, msg='Would have updated ALB if not in check mode.') + # Delete listeners for listener_to_delete in listeners_to_delete: - listener_obj = ELBListener(elb_obj.connection, elb_obj.module, listener_to_delete, elb_obj.elb['LoadBalancerArn']) + listener_obj = ELBListener(alb_obj.connection, alb_obj.module, listener_to_delete, alb_obj.elb['LoadBalancerArn']) listener_obj.delete() listeners_obj.changed = True # Add listeners for listener_to_add in listeners_to_add: - listener_obj = ELBListener(elb_obj.connection, elb_obj.module, listener_to_add, elb_obj.elb['LoadBalancerArn']) + listener_obj = ELBListener(alb_obj.connection, alb_obj.module, listener_to_add, alb_obj.elb['LoadBalancerArn']) listener_obj.add() listeners_obj.changed = True # Modify listeners for listener_to_modify in listeners_to_modify: - listener_obj = ELBListener(elb_obj.connection, elb_obj.module, listener_to_modify, elb_obj.elb['LoadBalancerArn']) + listener_obj = ELBListener(alb_obj.connection, alb_obj.module, listener_to_modify, alb_obj.elb['LoadBalancerArn']) listener_obj.modify() listeners_obj.changed = True - # If listeners changed, mark ELB as changed + # If listeners changed, mark ALB as changed if listeners_obj.changed: - elb_obj.changed = True + alb_obj.changed = True # Rules of each listener for listener in listeners_obj.listeners: if 'Rules' in listener: - rules_obj = ELBListenerRules(elb_obj.connection, elb_obj.module, elb_obj.elb['LoadBalancerArn'], listener['Rules'], listener['Port']) - + rules_obj = ELBListenerRules(alb_obj.connection, alb_obj.module, alb_obj.elb['LoadBalancerArn'], listener['Rules'], listener['Port']) rules_to_add, rules_to_modify, rules_to_delete = rules_obj.compare_rules() + # Exit on check_mode + if alb_obj.module.check_mode and (rules_to_add or rules_to_modify or rules_to_delete): + alb_obj.module.exit_json(changed=True, msg='Would have updated ALB if not in check mode.') + # Delete rules - if elb_obj.module.params['purge_rules']: + if alb_obj.module.params['purge_rules']: for rule in rules_to_delete: - rule_obj = ELBListenerRule(elb_obj.connection, elb_obj.module, {'RuleArn': rule}, rules_obj.listener_arn) + rule_obj = ELBListenerRule(alb_obj.connection, alb_obj.module, {'RuleArn': rule}, rules_obj.listener_arn) rule_obj.delete() - elb_obj.changed = True + alb_obj.changed = True # Add rules for rule in rules_to_add: - rule_obj = ELBListenerRule(elb_obj.connection, elb_obj.module, rule, rules_obj.listener_arn) + rule_obj = ELBListenerRule(alb_obj.connection, alb_obj.module, rule, rules_obj.listener_arn) rule_obj.create() - elb_obj.changed = True + alb_obj.changed = True # Modify rules for rule in rules_to_modify: - rule_obj = ELBListenerRule(elb_obj.connection, elb_obj.module, rule, rules_obj.listener_arn) + rule_obj = ELBListenerRule(alb_obj.connection, alb_obj.module, rule, rules_obj.listener_arn) rule_obj.modify() - elb_obj.changed = True + alb_obj.changed = True + + # Update ALB ip address type only if option has been provided + if alb_obj.module.params.get('ip_address_type') and alb_obj.elb_ip_addr_type != alb_obj.module.params.get('ip_address_type'): + # Exit on check_mode + if alb_obj.module.check_mode: + alb_obj.module.exit_json(changed=True, msg='Would have updated ALB if not in check mode.') + + alb_obj.modify_ip_address_type(alb_obj.module.params.get('ip_address_type')) - # Update ELB ip address type only if option has been provided - if elb_obj.module.params.get('ip_address_type') is not None: - elb_obj.modify_ip_address_type(elb_obj.module.params.get('ip_address_type')) - # Get the ELB again - elb_obj.update() + # Exit on check_mode - no changes + if alb_obj.module.check_mode: + alb_obj.module.exit_json(changed=False, msg='IN CHECK MODE - no changes to make to ALB specified.') - # Get the ELB listeners again + # Get the ALB again + alb_obj.update() + + # Get the ALB listeners again listeners_obj.update() - # Update the ELB attributes - elb_obj.update_elb_attributes() + # Update the ALB attributes + alb_obj.update_elb_attributes() # Convert to snake_case and merge in everything we want to return to the user - snaked_elb = camel_dict_to_snake_dict(elb_obj.elb) - snaked_elb.update(camel_dict_to_snake_dict(elb_obj.elb_attributes)) - snaked_elb['listeners'] = [] + snaked_alb = camel_dict_to_snake_dict(alb_obj.elb) + snaked_alb.update(camel_dict_to_snake_dict(alb_obj.elb_attributes)) + snaked_alb['listeners'] = [] for listener in listeners_obj.current_listeners: # For each listener, get listener rules - listener['rules'] = get_elb_listener_rules(elb_obj.connection, elb_obj.module, listener['ListenerArn']) - snaked_elb['listeners'].append(camel_dict_to_snake_dict(listener)) + listener['rules'] = get_elb_listener_rules(alb_obj.connection, alb_obj.module, listener['ListenerArn']) + snaked_alb['listeners'].append(camel_dict_to_snake_dict(listener)) # Change tags to ansible friendly dict - snaked_elb['tags'] = boto3_tag_list_to_ansible_dict(snaked_elb['tags']) + snaked_alb['tags'] = boto3_tag_list_to_ansible_dict(snaked_alb['tags']) # ip address type - snaked_elb['ip_address_type'] = elb_obj.get_elb_ip_address_type() + snaked_alb['ip_address_type'] = alb_obj.get_elb_ip_address_type() + + alb_obj.module.exit_json(changed=alb_obj.changed, **snaked_alb) + - elb_obj.module.exit_json(changed=elb_obj.changed, **snaked_elb) +def delete_alb(alb_obj): + if alb_obj.elb: -def delete_elb(elb_obj): + # Exit on check_mode + if alb_obj.module.check_mode: + alb_obj.module.exit_json(changed=True, msg='Would have deleted ALB if not in check mode.') - if elb_obj.elb: - listeners_obj = ELBListeners(elb_obj.connection, elb_obj.module, elb_obj.elb['LoadBalancerArn']) + listeners_obj = ELBListeners(alb_obj.connection, alb_obj.module, alb_obj.elb['LoadBalancerArn']) for listener_to_delete in [i['ListenerArn'] for i in listeners_obj.current_listeners]: - listener_obj = ELBListener(elb_obj.connection, elb_obj.module, listener_to_delete, elb_obj.elb['LoadBalancerArn']) + listener_obj = ELBListener(alb_obj.connection, alb_obj.module, listener_to_delete, alb_obj.elb['LoadBalancerArn']) listener_obj.delete() - elb_obj.delete() + alb_obj.delete() - elb_obj.module.exit_json(changed=elb_obj.changed) + else: + + # Exit on check_mode - no changes + if alb_obj.module.check_mode: + alb_obj.module.exit_json(changed=False, msg='IN CHECK MODE - ALB already absent.') + + alb_obj.module.exit_json(changed=alb_obj.changed) def main(): @@ -616,6 +746,10 @@ def main(): access_logs_s3_prefix=dict(type='str'), deletion_protection=dict(type='bool'), http2=dict(type='bool'), + http_desync_mitigation_mode=dict(type='str', choices=['monitor', 'defensive', 'strictest']), + http_drop_invalid_header_fields=dict(type='bool'), + http_x_amzn_tls_version_and_cipher_suite=dict(type='bool'), + http_xff_client_port=dict(type='bool'), idle_timeout=dict(type='int'), listeners=dict(type='list', elements='dict', @@ -636,6 +770,7 @@ def main(): scheme=dict(default='internet-facing', choices=['internet-facing', 'internal']), state=dict(choices=['present', 'absent'], default='present'), tags=dict(type='dict'), + waf_fail_open=dict(type='bool'), wait_timeout=dict(type='int'), wait=dict(default=False, type='bool'), purge_rules=dict(default=True, type='bool'), @@ -648,7 +783,8 @@ def main(): ], required_together=[ ['access_logs_enabled', 'access_logs_s3_bucket'] - ] + ], + supports_check_mode=True, ) # Quick check of listeners parameters @@ -668,12 +804,17 @@ def main(): state = module.params.get("state") - elb = ApplicationLoadBalancer(connection, connection_ec2, module) + alb = ApplicationLoadBalancer(connection, connection_ec2, module) + + # Update security group if default is specified + if alb.elb and module.params.get('security_groups') == []: + module.params['security_groups'] = [find_default_sg(connection_ec2, module, alb.elb['VpcId'])] + alb = ApplicationLoadBalancer(connection, connection_ec2, module) if state == 'present': - create_or_update_elb(elb) - else: - delete_elb(elb) + create_or_update_alb(alb) + elif state == 'absent': + delete_alb(alb) if __name__ == '__main__': diff --git a/plugins/modules/elb_application_lb_info.py b/plugins/modules/elb_application_lb_info.py --- a/plugins/modules/elb_application_lb_info.py +++ b/plugins/modules/elb_application_lb_info.py @@ -10,9 +10,9 @@ --- module: elb_application_lb_info version_added: 1.0.0 -short_description: Gather information about application ELBs in AWS +short_description: Gather information about Application Load Balancers in AWS description: - - Gather information about application ELBs in AWS + - Gather information about Application Load Balancers in AWS author: Rob White (@wimnat) options: load_balancer_arns: @@ -37,19 +37,19 @@ EXAMPLES = r''' # Note: These examples do not set authentication details, see the AWS Guide for details. -- name: Gather information about all target groups +- name: Gather information about all ALBs community.aws.elb_application_lb_info: -- name: Gather information about the target group attached to a particular ELB +- name: Gather information about a particular ALB given its ARN community.aws.elb_application_lb_info: load_balancer_arns: - - "arn:aws:elasticloadbalancing:ap-southeast-2:001122334455:loadbalancer/app/my-elb/aabbccddeeff" + - "arn:aws:elasticloadbalancing:ap-southeast-2:001122334455:loadbalancer/app/my-alb/aabbccddeeff" -- name: Gather information about a target groups named 'tg1' and 'tg2' +- name: Gather information about ALBs named 'alb1' and 'alb2' community.aws.elb_application_lb_info: names: - - elb1 - - elb2 + - alb1 + - alb2 - name: Gather information about specific ALB community.aws.elb_application_lb_info: @@ -69,55 +69,119 @@ access_logs_s3_bucket: description: The name of the S3 bucket for the access logs. type: str - sample: mys3bucket + sample: "mys3bucket" access_logs_s3_enabled: description: Indicates whether access logs stored in Amazon S3 are enabled. - type: str + type: bool sample: true access_logs_s3_prefix: description: The prefix for the location in the S3 bucket. type: str - sample: /my/logs + sample: "my/logs" availability_zones: description: The Availability Zones for the load balancer. type: list - sample: "[{'subnet_id': 'subnet-aabbccddff', 'zone_name': 'ap-southeast-2a'}]" + sample: [{ "load_balancer_addresses": [], "subnet_id": "subnet-aabbccddff", "zone_name": "ap-southeast-2a" }] canonical_hosted_zone_id: description: The ID of the Amazon Route 53 hosted zone associated with the load balancer. type: str - sample: ABCDEF12345678 + sample: "ABCDEF12345678" created_time: description: The date and time the load balancer was created. type: str sample: "2015-02-12T02:14:02+00:00" deletion_protection_enabled: description: Indicates whether deletion protection is enabled. - type: str + type: bool sample: true dns_name: description: The public DNS name of the load balancer. type: str - sample: internal-my-elb-123456789.ap-southeast-2.elb.amazonaws.com + sample: "internal-my-alb-123456789.ap-southeast-2.elb.amazonaws.com" idle_timeout_timeout_seconds: description: The idle timeout value, in seconds. - type: str + type: int sample: 60 ip_address_type: - description: The type of IP addresses used by the subnets for the load balancer. + description: The type of IP addresses used by the subnets for the load balancer. type: str - sample: ipv4 + sample: "ipv4" + listeners: + description: Information about the listeners. + type: complex + contains: + listener_arn: + description: The Amazon Resource Name (ARN) of the listener. + type: str + sample: "" + load_balancer_arn: + description: The Amazon Resource Name (ARN) of the load balancer. + type: str + sample: "" + port: + description: The port on which the load balancer is listening. + type: int + sample: 80 + protocol: + description: The protocol for connections from clients to the load balancer. + type: str + sample: "HTTPS" + certificates: + description: The SSL server certificate. + type: complex + contains: + certificate_arn: + description: The Amazon Resource Name (ARN) of the certificate. + type: str + sample: "" + ssl_policy: + description: The security policy that defines which ciphers and protocols are supported. + type: str + sample: "" + default_actions: + description: The default actions for the listener. + type: str + contains: + type: + description: The type of action. + type: str + sample: "" + target_group_arn: + description: The Amazon Resource Name (ARN) of the target group. + type: str + sample: "" load_balancer_arn: description: The Amazon Resource Name (ARN) of the load balancer. type: str - sample: arn:aws:elasticloadbalancing:ap-southeast-2:0123456789:loadbalancer/app/my-elb/001122334455 + sample: "arn:aws:elasticloadbalancing:ap-southeast-2:0123456789:loadbalancer/app/my-alb/001122334455" load_balancer_name: description: The name of the load balancer. type: str - sample: my-elb + sample: "my-alb" + routing_http2_enabled: + description: Indicates whether HTTP/2 is enabled. + type: bool + sample: true + routing_http_desync_mitigation_mode: + description: Determines how the load balancer handles requests that might pose a security risk to an application. + type: str + sample: "defensive" + routing_http_drop_invalid_header_fields_enabled: + description: Indicates whether HTTP headers with invalid header fields are removed by the load balancer (true) or routed to targets (false). + type: bool + sample: false + routing_http_x_amzn_tls_version_and_cipher_suite_enabled: + description: Indicates whether the two headers are added to the client request before sending it to the target. + type: bool + sample: false + routing_http_xff_client_port_enabled: + description: Indicates whether the X-Forwarded-For header should preserve the source port that the client used to connect to the load balancer. + type: bool + sample: false scheme: description: Internet-facing or internal load balancer. type: str - sample: internal + sample: "internal" security_groups: description: The IDs of the security groups for the load balancer. type: list @@ -125,21 +189,26 @@ state: description: The state of the load balancer. type: dict - sample: "{'code': 'active'}" + sample: {'code': 'active'} tags: description: The tags attached to the load balancer. type: dict - sample: "{ + sample: { 'Tag': 'Example' - }" + } type: description: The type of load balancer. type: str - sample: application + sample: "application" vpc_id: description: The ID of the VPC for the load balancer. type: str - sample: vpc-0011223344 + sample: "vpc-0011223344" + waf_fail_open_enabled: + description: Indicates whether to allow a AWS WAF-enabled load balancer to route requests to targets + if it is unable to forward the request to AWS WAF. + type: bool + sample: false ''' try: @@ -160,12 +229,12 @@ def get_paginator(connection, **kwargs): return paginator.paginate(**kwargs).build_full_result() -def get_elb_listeners(connection, module, elb_arn): +def get_alb_listeners(connection, module, alb_arn): try: - return connection.describe_listeners(LoadBalancerArn=elb_arn)['Listeners'] + return connection.describe_listeners(LoadBalancerArn=alb_arn)['Listeners'] except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: - module.fail_json_aws(e, msg="Failed to describe elb listeners") + module.fail_json_aws(e, msg="Failed to describe alb listeners") def get_listener_rules(connection, module, listener_arn): @@ -223,17 +292,17 @@ def list_load_balancers(connection, module): module.fail_json_aws(e, msg="Failed to list load balancers") for load_balancer in load_balancers['LoadBalancers']: - # Get the attributes for each elb + # Get the attributes for each alb load_balancer.update(get_load_balancer_attributes(connection, module, load_balancer['LoadBalancerArn'])) - # Get the listeners for each elb - load_balancer['listeners'] = get_elb_listeners(connection, module, load_balancer['LoadBalancerArn']) + # Get the listeners for each alb + load_balancer['listeners'] = get_alb_listeners(connection, module, load_balancer['LoadBalancerArn']) # For each listener, get listener rules for listener in load_balancer['listeners']: listener['rules'] = get_listener_rules(connection, module, listener['ListenerArn']) - # Get ELB ip address type + # Get ALB ip address type load_balancer['IpAddressType'] = get_load_balancer_ipaddresstype(connection, module, load_balancer['LoadBalancerArn']) # Turn the boto3 result in to ansible_friendly_snaked_names
diff --git a/tests/integration/targets/elb_application_lb/aliases b/tests/integration/targets/elb_application_lb/aliases --- a/tests/integration/targets/elb_application_lb/aliases +++ b/tests/integration/targets/elb_application_lb/aliases @@ -1,2 +1,3 @@ cloud/aws slow +elb_application_lb_info \ No newline at end of file diff --git a/tests/integration/targets/elb_application_lb/defaults/main.yml b/tests/integration/targets/elb_application_lb/defaults/main.yml --- a/tests/integration/targets/elb_application_lb/defaults/main.yml +++ b/tests/integration/targets/elb_application_lb/defaults/main.yml @@ -1,4 +1,14 @@ --- +# defaults file for elb_application_lb + resource_short: "{{ '%0.8x'%((16**8) | random(seed=resource_prefix)) }}" alb_name: "alb-test-{{ resource_short }}" tg_name: "alb-test-{{ resource_short }}" + +vpc_cidr: '10.{{ 256 | random(seed=resource_prefix) }}.0.0/16' + +private_subnet_cidr_1: '10.{{ 256 | random(seed=resource_prefix) }}.1.0/24' +private_subnet_cidr_2: '10.{{ 256 | random(seed=resource_prefix) }}.2.0/24' + +public_subnet_cidr_1: '10.{{ 256 | random(seed=resource_prefix) }}.3.0/24' +public_subnet_cidr_2: '10.{{ 256 | random(seed=resource_prefix) }}.4.0/24' \ No newline at end of file diff --git a/tests/integration/targets/elb_application_lb/tasks/full_test.yml b/tests/integration/targets/elb_application_lb/tasks/full_test.yml deleted file mode 100644 --- a/tests/integration/targets/elb_application_lb/tasks/full_test.yml +++ /dev/null @@ -1,186 +0,0 @@ -- name: elb_application_lb full_test - block: - # Setup - - name: create VPC - ec2_vpc_net: - cidr_block: 10.228.228.0/22 - name: '{{ resource_prefix }}_vpc' - state: present - ipv6_cidr: true - register: vpc - - name: create internet gateway - ec2_vpc_igw: - vpc_id: '{{ vpc.vpc.id }}' - state: present - tags: - Name: '{{ resource_prefix }}' - register: igw - - name: create private subnet - ec2_vpc_subnet: - cidr: '{{ item.cidr }}' - az: '{{ aws_region}}{{ item.az }}' - vpc_id: '{{ vpc.vpc.id }}' - state: present - tags: - Public: '{{ item.public|string }}' - Name: '{{ item.public|ternary(''public'', ''private'') }}-{{ item.az }}' - with_items: - - cidr: 10.228.230.0/24 - az: a - public: 'False' - - cidr: 10.228.231.0/24 - az: b - public: 'False' - - - name: create public subnets with ipv6 - ec2_vpc_subnet: - cidr: '{{ item.cidr }}' - az: '{{ aws_region}}{{ item.az }}' - vpc_id: '{{ vpc.vpc.id }}' - state: present - ipv6_cidr: '{{ item.vpc_ipv6_cidr }}' - tags: - Public: '{{ item.public|string }}' - Name: '{{ item.public|ternary(''public'', ''private'') }}-{{ item.az }}' - with_items: - - cidr: 10.228.228.0/24 - az: a - public: 'True' - vpc_ipv6_cidr: "{{ vpc.vpc.ipv6_cidr_block_association_set[0].ipv6_cidr_block | replace('0::/56','0::/64') }}" - - cidr: 10.228.229.0/24 - az: b - public: 'True' - vpc_ipv6_cidr: "{{ vpc.vpc.ipv6_cidr_block_association_set[0].ipv6_cidr_block | replace('0::/56','1::/64') }}" - - - ec2_vpc_subnet_info: - filters: - vpc-id: '{{ vpc.vpc.id }}' - register: vpc_subnets - - name: create list of subnet ids - set_fact: - alb_subnets: '{{ vpc_subnets|community.general.json_query(''subnets[?tags.Public == `True`].id'') }}' - private_subnets: '{{ vpc_subnets|community.general.json_query(''subnets[?tags.Public != `True`].id'') }}' - - name: create a route table - ec2_vpc_route_table: - vpc_id: '{{ vpc.vpc.id }}' - tags: - Name: igw-route - Created: '{{ resource_prefix }}' - subnets: '{{ alb_subnets + private_subnets }}' - routes: - - dest: 0.0.0.0/0 - gateway_id: '{{ igw.gateway_id }}' - register: route_table - - ec2_group: - name: '{{ resource_prefix }}' - description: security group for Ansible ALB integration tests - state: present - vpc_id: '{{ vpc.vpc.id }}' - rules: - - proto: tcp - from_port: 1 - to_port: 65535 - cidr_ip: 0.0.0.0/0 - register: sec_group - - name: create a target group for testing - elb_target_group: - name: '{{ tg_name }}' - protocol: http - port: 80 - vpc_id: '{{ vpc.vpc.id }}' - state: present - register: tg - - # Run main tests - - include_tasks: test_alb_bad_listener_options.yml - - include_tasks: test_alb_ip_address_type_options.yml - - include_tasks: test_alb_tags.yml - - include_tasks: test_creating_alb.yml - - include_tasks: test_alb_with_asg.yml - - include_tasks: test_modifying_alb_listeners.yml - - include_tasks: test_deleting_alb.yml - - include_tasks: test_multiple_actions.yml - - always: - # Cleanup - - name: destroy ALB - elb_application_lb: - name: '{{ alb_name }}' - state: absent - wait: true - wait_timeout: 600 - ignore_errors: true - - - name: destroy target group if it was created - elb_target_group: - name: '{{ tg_name }}' - protocol: http - port: 80 - vpc_id: '{{ vpc.vpc.id }}' - state: absent - wait: true - wait_timeout: 600 - register: remove_tg - retries: 5 - delay: 3 - until: remove_tg is success - when: tg is defined - ignore_errors: true - - name: destroy sec group - ec2_group: - name: '{{ sec_group.group_name }}' - description: security group for Ansible ALB integration tests - state: absent - vpc_id: '{{ vpc.vpc.id }}' - register: remove_sg - retries: 10 - delay: 5 - until: remove_sg is success - ignore_errors: true - - name: remove route table - ec2_vpc_route_table: - vpc_id: '{{ vpc.vpc.id }}' - route_table_id: '{{ route_table.route_table.route_table_id }}' - lookup: id - state: absent - register: remove_rt - retries: 10 - delay: 5 - until: remove_rt is success - ignore_errors: true - - name: destroy subnets - ec2_vpc_subnet: - cidr: '{{ item.cidr }}' - vpc_id: '{{ vpc.vpc.id }}' - state: absent - register: remove_subnet - retries: 10 - delay: 5 - until: remove_subnet is success - with_items: - - cidr: 10.228.228.0/24 - - cidr: 10.228.229.0/24 - - cidr: 10.228.230.0/24 - - cidr: 10.228.231.0/24 - ignore_errors: true - - name: destroy internet gateway - ec2_vpc_igw: - vpc_id: '{{ vpc.vpc.id }}' - tags: - Name: '{{ resource_prefix }}' - state: absent - register: remove_igw - retries: 10 - delay: 5 - until: remove_igw is success - ignore_errors: true - - name: destroy VPC - ec2_vpc_net: - cidr_block: 10.228.228.0/22 - name: '{{ resource_prefix }}_vpc' - state: absent - register: remove_vpc - retries: 10 - delay: 5 - until: remove_vpc is success - ignore_errors: true diff --git a/tests/integration/targets/elb_application_lb/tasks/main.yml b/tests/integration/targets/elb_application_lb/tasks/main.yml --- a/tests/integration/targets/elb_application_lb/tasks/main.yml +++ b/tests/integration/targets/elb_application_lb/tasks/main.yml @@ -1,12 +1,1429 @@ - name: 'elb_application_lb integration tests' collections: - amazon.aws + module_defaults: group/aws: - aws_access_key: '{{ aws_access_key }}' - aws_secret_key: '{{ aws_secret_key }}' - security_token: '{{ security_token | default(omit) }}' - region: '{{ aws_region }}' + aws_access_key: "{{ aws_access_key }}" + aws_secret_key: "{{ aws_secret_key }}" + security_token: "{{ security_token | default(omit) }}" + region: "{{ aws_region }}" + block: + - name: Create a test VPC + ec2_vpc_net: + cidr_block: "{{ vpc_cidr }}" + name: '{{ resource_prefix }}_vpc' + state: present + ipv6_cidr: true + tags: + Name: elb_application_lb testing + ResourcePrefix: "{{ resource_prefix }}" + register: vpc + + - name: 'Set fact: VPC ID' + set_fact: + vpc_id: "{{ vpc.vpc.id }}" + + - name: Get VPC's default security group + ec2_group_info: + filters: + vpc-id: "{{ vpc_id }}" + register: default_sg + + - name: Create an internet gateway + ec2_vpc_igw: + vpc_id: '{{ vpc_id }}' + state: present + tags: + Name: '{{ resource_prefix }}' + register: igw + + - name: Create private subnets + ec2_vpc_subnet: + cidr: '{{ item.cidr }}' + az: '{{ aws_region }}{{ item.az }}' + vpc_id: '{{ vpc_id }}' + state: present + tags: + Public: 'False' + Name: 'private-{{ item.az }}' + with_items: + - cidr: "{{ private_subnet_cidr_1 }}" + az: a + - cidr: "{{ private_subnet_cidr_2 }}" + az: b + register: private_subnets + + - name: Create public subnets with ipv6 + ec2_vpc_subnet: + cidr: '{{ item.cidr }}' + az: '{{ aws_region }}{{ item.az }}' + vpc_id: '{{ vpc_id }}' + state: present + ipv6_cidr: '{{ item.vpc_ipv6_cidr }}' + tags: + Public: 'True' + Name: 'public-{{ item.az }}' + with_items: + - cidr: "{{ public_subnet_cidr_1 }}" + az: a + vpc_ipv6_cidr: "{{ vpc.vpc.ipv6_cidr_block_association_set[0].ipv6_cidr_block | replace('0::/56','0::/64') }}" + - cidr: "{{ public_subnet_cidr_2 }}" + az: b + vpc_ipv6_cidr: "{{ vpc.vpc.ipv6_cidr_block_association_set[0].ipv6_cidr_block | replace('0::/56','1::/64') }}" + register: public_subnets + + - name: Create list of subnet ids + set_fact: + public_subnets: "{{ public_subnets.results | map(attribute='subnet') | map(attribute='id') }}" + private_subnets: "{{ private_subnets.results | map(attribute='subnet') | map(attribute='id') }}" + + - name: Create a route table + ec2_vpc_route_table: + vpc_id: '{{ vpc_id }}' + tags: + Name: igw-route + Created: '{{ resource_prefix }}' + subnets: '{{ public_subnets + private_subnets }}' + routes: + - dest: 0.0.0.0/0 + gateway_id: '{{ igw.gateway_id }}' + register: route_table + + - name: Create a security group for Ansible ALB integration tests + ec2_group: + name: '{{ resource_prefix }}' + description: security group for Ansible ALB integration tests + state: present + vpc_id: '{{ vpc_id }}' + rules: + - proto: tcp + from_port: 1 + to_port: 65535 + cidr_ip: 0.0.0.0/0 + register: sec_group + + - name: Create another security group for Ansible ALB integration tests + ec2_group: + name: '{{ resource_prefix }}-2' + description: security group for Ansible ALB integration tests + state: present + vpc_id: '{{ vpc_id }}' + rules: + - proto: tcp + from_port: 1 + to_port: 65535 + cidr_ip: 0.0.0.0/0 + register: sec_group2 + + - name: Create a target group for testing + elb_target_group: + name: '{{ tg_name }}' + protocol: http + port: 80 + vpc_id: '{{ vpc_id }}' + state: present + register: tg + + # ---------------- elb_application_lb tests --------------------------------------------------- + + - name: Create an ALB (invalid - SslPolicy is required when Protocol == HTTPS) + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + listeners: + - Protocol: HTTPS + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + ignore_errors: yes + register: alb + + - assert: + that: + - alb is failed + - alb.msg is match("'SslPolicy' is a required listener dict key when Protocol = HTTPS") + + - name: Create an ALB (invalid - didn't provide required listener options) + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + listeners: + - Port: 80 + ignore_errors: yes + register: alb + + - assert: + that: + - alb is failed + - alb.msg is match("missing required arguments:\ DefaultActions, Protocol found in listeners") + + - name: Create an ALB (invalid - invalid listener option type) + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + listeners: + - Protocol: HTTP + Port: "bad type" + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + ignore_errors: yes + register: alb + + - assert: + that: + - alb is failed + - "'unable to convert to int' in alb.msg" + + - name: Create an ALB (invalid - invalid ip address type) + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + ip_address_type: "ip_addr_v4_v6" + ignore_errors: yes + register: alb + + - assert: + that: + - alb is failed + + # ------------------------------------------------------------------------------------------ + + - name: Create an ALB with defaults - check_mode + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: [] + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + register: alb + check_mode: yes + + - assert: + that: + - alb is changed + - alb.msg is match('Would have created ALB if not in check mode.') + + - name: Create an ALB with defaults + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: [] + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + register: alb + + - assert: + that: + - alb is changed + - alb.listeners[0].rules | length == 1 + - alb.security_groups | length == 1 + - alb.security_groups[0] == default_sg.security_groups[0].group_id + + - name: Create an ALB with defaults (idempotence) - check_mode + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: [] + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + register: alb + check_mode: yes + + - assert: + that: + - alb is not changed + - alb.msg is match('IN CHECK MODE - no changes to make to ALB specified.') + + - name: Create an ALB with defaults (idempotence) + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: [] + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + register: alb + + - assert: + that: + - alb is not changed + - alb.listeners[0].rules | length == 1 + - alb.security_groups[0] == default_sg.security_groups[0].group_id + + # ------------------------------------------------------------------------------------------ + + - name: Update an ALB with ip address type - check_mode + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + ip_address_type: 'dualstack' + register: alb + check_mode: yes + + - assert: + that: + - alb is changed + - alb.msg is match('Would have updated ALB if not in check mode.') + + - name: Update an ALB with ip address type + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + ip_address_type: 'dualstack' + register: alb + + - assert: + that: + - alb is changed + - alb.ip_address_type == 'dualstack' + - alb.listeners[0].rules | length == 1 + - alb.routing_http2_enabled | bool + - alb.routing_http_desync_mitigation_mode == 'defensive' + - not alb.routing_http_drop_invalid_header_fields_enabled | bool + - not alb.routing_http_x_amzn_tls_version_and_cipher_suite_enabled | bool + - not alb.routing_http_xff_client_port_enabled | bool + - not alb.waf_fail_open_enabled | bool + + - name: Create an ALB with ip address type (idempotence) - check_mode + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + ip_address_type: 'dualstack' + register: alb + check_mode: yes + + - assert: + that: + - alb is not changed + - alb.msg is match('IN CHECK MODE - no changes to make to ALB specified.') + + - name: Create an ALB with ip address type (idempotence) + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + ip_address_type: 'dualstack' + register: alb + + - assert: + that: + - alb is not changed + - alb.ip_address_type == 'dualstack' + - alb.routing_http2_enabled | bool + - alb.routing_http_desync_mitigation_mode == 'defensive' + - not alb.routing_http_drop_invalid_header_fields_enabled | bool + - not alb.routing_http_x_amzn_tls_version_and_cipher_suite_enabled | bool + - not alb.routing_http_xff_client_port_enabled | bool + - not alb.waf_fail_open_enabled | bool + + # ------------------------------------------------------------------------------------------ + + - name: Update an ALB with different attributes - check_mode + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + ip_address_type: 'dualstack' + http2: no + http_desync_mitigation_mode: monitor + http_drop_invalid_header_fields: yes + http_x_amzn_tls_version_and_cipher_suite: yes + http_xff_client_port: yes + waf_fail_open: yes + register: alb + check_mode: yes + + - assert: + that: + - alb is changed + - alb.msg is match('Would have updated ALB if not in check mode.') + + - name: Update an ALB with different attributes + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + ip_address_type: 'dualstack' + http2: no + http_desync_mitigation_mode: monitor + http_drop_invalid_header_fields: yes + http_x_amzn_tls_version_and_cipher_suite: yes + http_xff_client_port: yes + waf_fail_open: yes + register: alb + + - assert: + that: + - alb is changed + - alb.ip_address_type == 'dualstack' + - not alb.routing_http2_enabled | bool + - alb.routing_http_desync_mitigation_mode == 'monitor' + - alb.routing_http_drop_invalid_header_fields_enabled | bool + - alb.routing_http_x_amzn_tls_version_and_cipher_suite_enabled | bool + - alb.routing_http_xff_client_port_enabled | bool + - alb.waf_fail_open_enabled | bool + + - name: Update an ALB with different attributes (idempotence) - check_mode + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + ip_address_type: 'dualstack' + http2: no + http_desync_mitigation_mode: monitor + http_drop_invalid_header_fields: yes + http_x_amzn_tls_version_and_cipher_suite: yes + http_xff_client_port: yes + waf_fail_open: yes + register: alb + check_mode: yes + + - assert: + that: + - alb is not changed + - alb.msg is match('IN CHECK MODE - no changes to make to ALB specified.') + + - name: Update an ALB with different attributes (idempotence) + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + ip_address_type: 'dualstack' + http2: no + http_desync_mitigation_mode: monitor + http_drop_invalid_header_fields: yes + http_x_amzn_tls_version_and_cipher_suite: yes + http_xff_client_port: yes + waf_fail_open: yes + register: alb + + - assert: + that: + - alb is not changed + - alb.ip_address_type == 'dualstack' + - not alb.routing_http2_enabled | bool + - alb.routing_http_desync_mitigation_mode == 'monitor' + - alb.routing_http_drop_invalid_header_fields_enabled | bool + - alb.routing_http_x_amzn_tls_version_and_cipher_suite_enabled | bool + - alb.routing_http_xff_client_port_enabled | bool + - alb.waf_fail_open_enabled | bool + + # ------------------------------------------------------------------------------------------ + + - name: Update an ALB with different ip address type - check_mode + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + ip_address_type: 'ipv4' + http2: no + http_desync_mitigation_mode: monitor + http_drop_invalid_header_fields: yes + http_x_amzn_tls_version_and_cipher_suite: yes + http_xff_client_port: yes + waf_fail_open: yes + register: alb + check_mode: yes + + - assert: + that: + - alb is changed + - alb.msg is match('Would have updated ALB if not in check mode.') + + - name: Update an ALB with different ip address type + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + ip_address_type: 'ipv4' + http2: no + http_desync_mitigation_mode: monitor + http_drop_invalid_header_fields: yes + http_x_amzn_tls_version_and_cipher_suite: yes + http_xff_client_port: yes + waf_fail_open: yes + register: alb + + - assert: + that: + - alb is changed + - alb.ip_address_type == 'ipv4' + - not alb.routing_http2_enabled | bool + - alb.routing_http_desync_mitigation_mode == 'monitor' + - alb.routing_http_drop_invalid_header_fields_enabled | bool + - alb.routing_http_x_amzn_tls_version_and_cipher_suite_enabled | bool + - alb.routing_http_xff_client_port_enabled | bool + - alb.waf_fail_open_enabled | bool + + - name: Update an ALB with different ip address type (idempotence) - check_mode + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + ip_address_type: 'ipv4' + http2: no + http_desync_mitigation_mode: monitor + http_drop_invalid_header_fields: yes + http_x_amzn_tls_version_and_cipher_suite: yes + http_xff_client_port: yes + waf_fail_open: yes + register: alb + check_mode: yes + + - assert: + that: + - alb is not changed + - alb.msg is match('IN CHECK MODE - no changes to make to ALB specified.') + + - name: Update an ALB with different ip address type (idempotence) + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + ip_address_type: 'ipv4' + http2: no + http_desync_mitigation_mode: monitor + http_drop_invalid_header_fields: yes + http_x_amzn_tls_version_and_cipher_suite: yes + http_xff_client_port: yes + waf_fail_open: yes + register: alb + + - assert: + that: + - alb is not changed + - alb.ip_address_type == 'ipv4' + - not alb.routing_http2_enabled | bool + - alb.routing_http_desync_mitigation_mode == 'monitor' + - alb.routing_http_drop_invalid_header_fields_enabled | bool + - alb.routing_http_x_amzn_tls_version_and_cipher_suite_enabled | bool + - alb.routing_http_xff_client_port_enabled | bool + - alb.waf_fail_open_enabled | bool + + # ------------------------------------------------------------------------------------------ + + - name: Update an ALB with different listener by adding rule - check_mode + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + Rules: + - Conditions: + - Field: path-pattern + Values: + - '/test' + Priority: '1' + Actions: + - TargetGroupName: "{{ tg_name }}" + Type: forward + register: alb + check_mode: yes + + - assert: + that: + - alb is changed + - alb.msg is match('Would have updated ALB if not in check mode.') + + - name: Update an ALB with different listener by adding rule + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + Rules: + - Conditions: + - Field: path-pattern + Values: + - '/test' + Priority: '1' + Actions: + - TargetGroupName: "{{ tg_name }}" + Type: forward + register: alb + + - assert: + that: + - alb is changed + - alb.listeners[0].rules | length == 2 + - "'1' in {{ alb.listeners[0].rules | map(attribute='priority') }}" + + - name: Update an ALB with different listener by adding rule (idempotence) - check_mode + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + Rules: + - Conditions: + - Field: path-pattern + Values: + - '/test' + Priority: '1' + Actions: + - TargetGroupName: "{{ tg_name }}" + Type: forward + register: alb + check_mode: yes + + - assert: + that: + - alb is not changed + - alb.msg is match('IN CHECK MODE - no changes to make to ALB specified.') + + - name: Update an ALB with different listener by adding rule (idempotence) + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + Rules: + - Conditions: + - Field: path-pattern + Values: + - '/test' + Priority: '1' + Actions: + - TargetGroupName: "{{ tg_name }}" + Type: forward + register: alb + + - assert: + that: + - alb is not changed + - alb.listeners[0].rules | length == 2 + - "'1' in {{ alb.listeners[0].rules | map(attribute='priority') }}" + + # ------------------------------------------------------------------------------------------ + + - name: Update an ALB with different listener by modifying rule - check_mode + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + Rules: + - Conditions: + - Field: path-pattern + Values: + - '/test' + Priority: '2' + Actions: + - TargetGroupName: "{{ tg_name }}" + Type: forward + register: alb + check_mode: yes + + - assert: + that: + - alb is changed + - alb.msg is match('Would have updated ALB if not in check mode.') + + - name: Update an ALB with different listener by modifying rule + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + Rules: + - Conditions: + - Field: path-pattern + Values: + - '/test' + Priority: '2' + Actions: + - TargetGroupName: "{{ tg_name }}" + Type: forward + register: alb + + - assert: + that: + - alb is changed + - alb.listeners[0].rules | length == 2 + - "'2' in {{ alb.listeners[0].rules | map(attribute='priority') }}" + + - name: Update an ALB with different listener by modifying rule (idempotence) - check_mode + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + Rules: + - Conditions: + - Field: path-pattern + Values: + - '/test' + Priority: '2' + Actions: + - TargetGroupName: "{{ tg_name }}" + Type: forward + register: alb + check_mode: yes + + - assert: + that: + - alb is not changed + - alb.msg is match('IN CHECK MODE - no changes to make to ALB specified.') + + - name: Update an ALB with different listener by modifying rule (idempotence) + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + Rules: + - Conditions: + - Field: path-pattern + Values: + - '/test' + Priority: '2' + Actions: + - TargetGroupName: "{{ tg_name }}" + Type: forward + register: alb + + - assert: + that: + - alb is not changed + - alb.listeners[0].rules | length == 2 + - "'2' in {{ alb.listeners[0].rules | map(attribute='priority') }}" + + # ------------------------------------------------------------------------------------------ + + - name: Update an ALB with different listener by deleting rule - check_mode + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + Rules: [] + register: alb + check_mode: yes + + - assert: + that: + - alb is changed + - alb.msg is match('Would have updated ALB if not in check mode.') + + - name: Update an ALB with different listener by deleting rule + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + Rules: [] + register: alb + + - assert: + that: + - alb is changed + - alb.listeners[0].rules | length == 1 + - "'2' not in {{ alb.listeners[0].rules | map(attribute='priority') }}" + + - name: Update an ALB with different listener by deleting rule (idempotence) - check_mode + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + Rules: [] + register: alb + check_mode: yes + + - assert: + that: + - alb is not changed + - alb.msg is match('IN CHECK MODE - no changes to make to ALB specified.') + + - name: Update an ALB with different listener by deleting rule (idempotence) + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + listeners: + - Protocol: HTTP + Port: 80 + DefaultActions: + - Type: forward + TargetGroupName: "{{ tg_name }}" + Rules: [] + register: alb + + - assert: + that: + - alb is not changed + - alb.listeners[0].rules | length == 1 + - "'2' not in {{ alb.listeners[0].rules | map(attribute='priority') }}" + + # ------------------------------------------------------------------------------------------ + + - name: Update an ALB by deleting listener - check_mode + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + listeners: [] + register: alb + check_mode: yes + + - assert: + that: + - alb is changed + - alb.msg is match('Would have updated ALB if not in check mode.') + + - name: Update an ALB by deleting listener + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + listeners: [] + register: alb + + - assert: + that: + - alb is changed + - not alb.listeners + + - name: Update an ALB by deleting listener (idempotence) - check_mode + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + listeners: [] + register: alb + check_mode: yes + + - assert: + that: + - alb is not changed + - alb.msg is match('IN CHECK MODE - no changes to make to ALB specified.') + + - name: Update an ALB by deleting listener (idempotence) + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + listeners: [] + register: alb + + - assert: + that: + - alb is not changed + - not alb.listeners + + # ------------------------------------------------------------------------------------------ + + - name: Update an ALB by adding tags - check_mode + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + tags: + created_by: "ALB test {{ resource_prefix }}" + register: alb + check_mode: yes + + - assert: + that: + - alb is changed + - alb.msg is match('Would have updated ALB if not in check mode.') + + - name: Update an ALB by adding tags + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + tags: + created_by: "ALB test {{ resource_prefix }}" + register: alb + + - assert: + that: + - alb is changed + - 'alb.tags == {"created_by": "ALB test {{ resource_prefix }}"}' + + - name: Update an ALB by adding tags (idempotence) - check_mode + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + tags: + created_by: "ALB test {{ resource_prefix }}" + register: alb + check_mode: yes + + - assert: + that: + - alb is not changed + - alb.msg is match('IN CHECK MODE - no changes to make to ALB specified.') + + - name: Update an ALB by adding tags (idempotence) + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + tags: + created_by: "ALB test {{ resource_prefix }}" + register: alb + + - assert: + that: + - alb is not changed + - 'alb.tags == {"created_by": "ALB test {{ resource_prefix }}"}' + + # ------------------------------------------------------------------------------------------ + + - name: Update an ALB by modifying tags - check_mode + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + tags: + created_by: "ALB test {{ resource_prefix }}-2" + register: alb + check_mode: yes + + - assert: + that: + - alb is changed + - alb.msg is match('Would have updated ALB if not in check mode.') + + - name: Update an ALB by modifying tags + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + tags: + created_by: "ALB test {{ resource_prefix }}-2" + register: alb + + - assert: + that: + - alb is changed + - 'alb.tags == {"created_by": "ALB test {{ resource_prefix }}-2"}' + + - name: Update an ALB by modifying tags (idempotence) - check_mode + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + tags: + created_by: "ALB test {{ resource_prefix }}-2" + register: alb + check_mode: yes + + - assert: + that: + - alb is not changed + - alb.msg is match('IN CHECK MODE - no changes to make to ALB specified.') + + - name: Update an ALB by modifying tags (idempotence) + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + tags: + created_by: "ALB test {{ resource_prefix }}-2" + register: alb + + - assert: + that: + - alb is not changed + - 'alb.tags == {"created_by": "ALB test {{ resource_prefix }}-2"}' + + # ------------------------------------------------------------------------------------------ + + - name: Update an ALB by removing tags - check_mode + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + tags: {} + register: alb + check_mode: yes + + - assert: + that: + - alb is changed + - alb.msg is match('Would have updated ALB if not in check mode.') + + - name: Update an ALB by removing tags + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + tags: {} + register: alb + + - assert: + that: + - alb is changed + - not alb.tags + + - name: Update an ALB by removing tags (idempotence) - check_mode + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + tags: {} + register: alb + check_mode: yes + + - assert: + that: + - alb is not changed + - alb.msg is match('IN CHECK MODE - no changes to make to ALB specified.') + + - name: Update an ALB by removing tags (idempotence) + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group.group_id }}" + state: present + tags: {} + register: alb + + - assert: + that: + - alb is not changed + - not alb.tags + + # ------------------------------------------------------------------------------------------ + + - name: Update an ALB by changing security group - check_mode + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group2.group_id }}" + state: present + register: alb + check_mode: yes + + - assert: + that: + - alb is changed + - alb.msg is match('Would have updated ALB if not in check mode.') + + - name: Update an ALB by changing security group + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group2.group_id }}" + state: present + register: alb + + - assert: + that: + - alb is changed + - alb.security_groups[0] == sec_group2.group_id + + - name: Update an ALB by changing security group (idempotence) - check_mode + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group2.group_id }}" + state: present + register: alb + check_mode: yes + + - assert: + that: + - alb is not changed + - alb.msg is match('IN CHECK MODE - no changes to make to ALB specified.') + + - name: Update an ALB by changing security group (idempotence) + elb_application_lb: + name: "{{ alb_name }}" + subnets: "{{ public_subnets }}" + security_groups: "{{ sec_group2.group_id }}" + state: present + register: alb + + - assert: + that: + - alb is not changed + - alb.security_groups[0] == sec_group2.group_id + + # ------------------------------------------------------------------------------------------ + + - name: Ensure elb_application_lb_info supports check_mode + elb_application_lb_info: + register: alb_info + check_mode: yes + + - assert: + that: + - alb_info.load_balancers | length > 0 + + - name: Get ALB application info using no args + elb_application_lb_info: + register: alb_info + + - assert: + that: + - alb_info.load_balancers | length > 0 + + - name: Get ALB application info using load balancer arn + elb_application_lb_info: + load_balancer_arns: + - "{{ alb.load_balancer_arn }}" + register: alb_info + + - assert: + that: + - alb_info.load_balancers[0].security_groups[0] == sec_group2.group_id + + - name: Get ALB application info using load balancer name + elb_application_lb_info: + names: + - "{{ alb.load_balancer_name }}" + register: alb_info + + - assert: + that: + - alb_info.load_balancers[0].security_groups[0] == sec_group2.group_id + + # ------------------------------------------------------------------------------------------ + + - name: Delete an ALB - check_mode + elb_application_lb: + name: "{{ alb_name }}" + state: absent + register: alb + check_mode: yes + + - assert: + that: + - alb is changed + - alb.msg is match('Would have deleted ALB if not in check mode.') + + - name: Delete an ALB + elb_application_lb: + name: "{{ alb_name }}" + state: absent + register: alb + + - assert: + that: + - alb is changed + + - name: Delete an ALB (idempotence) - check_mode + elb_application_lb: + name: "{{ alb_name }}" + state: absent + register: alb + check_mode: yes + + - assert: + that: + - alb is not changed + - alb.msg is match('IN CHECK MODE - ALB already absent.') + + - name: Delete an ALB (idempotence) + elb_application_lb: + name: "{{ alb_name }}" + state: absent + register: alb + + - assert: + that: + - alb is not changed + + # ----- Cleanup ------------------------------------------------------------------------------ + + always: + - name: Destroy ALB + elb_application_lb: + name: '{{ alb_name }}' + state: absent + wait: true + wait_timeout: 600 + ignore_errors: true + + - name: Destroy target group if it was created + elb_target_group: + name: '{{ tg_name }}' + protocol: http + port: 80 + vpc_id: '{{ vpc_id }}' + state: absent + wait: true + wait_timeout: 600 + register: remove_tg + retries: 5 + delay: 3 + until: remove_tg is success + when: tg is defined + ignore_errors: true + + - name: Destroy sec groups + ec2_group: + name: "{{ item }}" + description: security group for Ansible ALB integration tests + state: absent + vpc_id: '{{ vpc_id }}' + register: remove_sg + retries: 10 + delay: 5 + until: remove_sg is success + ignore_errors: true + with_items: + - "{{ resource_prefix }}" + - "{{ resource_prefix }}-2" + + - name: Destroy route table + ec2_vpc_route_table: + vpc_id: '{{ vpc_id }}' + route_table_id: '{{ route_table.route_table.route_table_id }}' + lookup: id + state: absent + register: remove_rt + retries: 10 + delay: 5 + until: remove_rt is success + ignore_errors: true + + - name: Destroy subnets + ec2_vpc_subnet: + cidr: "{{ item }}" + vpc_id: "{{ vpc_id }}" + state: absent + register: remove_subnet + retries: 10 + delay: 5 + until: remove_subnet is success + with_items: + - "{{ private_subnet_cidr_1 }}" + - "{{ private_subnet_cidr_2 }}" + - "{{ public_subnet_cidr_1 }}" + - "{{ public_subnet_cidr_2 }}" + ignore_errors: true + + - name: Destroy internet gateway + ec2_vpc_igw: + vpc_id: '{{ vpc_id }}' + tags: + Name: '{{ resource_prefix }}' + state: absent + register: remove_igw + retries: 10 + delay: 5 + until: remove_igw is success + ignore_errors: true - - include_tasks: full_test.yml + - name: Destroy VPC + ec2_vpc_net: + cidr_block: "{{ vpc_cidr }}" + name: "{{ resource_prefix }}_vpc" + state: absent + register: remove_vpc + retries: 10 + delay: 5 + until: remove_vpc is success + ignore_errors: true diff --git a/tests/integration/targets/elb_application_lb/tasks/test_alb_bad_listener_options.yml b/tests/integration/targets/elb_application_lb/tasks/test_alb_bad_listener_options.yml deleted file mode 100644 --- a/tests/integration/targets/elb_application_lb/tasks/test_alb_bad_listener_options.yml +++ /dev/null @@ -1,68 +0,0 @@ -- block: - - - name: test creating an ALB with invalid listener options - elb_application_lb: - name: "{{ alb_name }}" - subnets: "{{ alb_subnets }}" - security_groups: "{{ sec_group.group_id }}" - state: present - listeners: - - Protocol: HTTPS - Port: 80 - DefaultActions: - - Type: forward - TargetGroupName: "{{ tg_name }}" - ignore_errors: yes - register: alb - - - assert: - that: - - alb is failed - - - name: test creating an ALB without providing required listener options - elb_application_lb: - name: "{{ alb_name }}" - subnets: "{{ alb_subnets }}" - security_groups: "{{ sec_group.group_id }}" - state: present - listeners: - - Port: 80 - ignore_errors: yes - register: alb - - - assert: - that: - - alb is failed - - '"missing required arguments" in alb.msg' - - '"Protocol" in alb.msg' - - '"DefaultActions" in alb.msg' - - - name: test creating an ALB providing an invalid listener option type - elb_application_lb: - name: "{{ alb_name }}" - subnets: "{{ alb_subnets }}" - security_groups: "{{ sec_group.group_id }}" - state: present - listeners: - - Protocol: HTTP - Port: "bad type" - DefaultActions: - - Type: forward - TargetGroupName: "{{ tg_name }}" - ignore_errors: yes - register: alb - - - assert: - that: - - alb is failed - - "'unable to convert to int' in alb.msg" - - always: - # Cleanup - - name: destroy ALB if created - elb_application_lb: - name: '{{ alb_name }}' - state: absent - wait: true - wait_timeout: 600 - ignore_errors: true diff --git a/tests/integration/targets/elb_application_lb/tasks/test_alb_ip_address_type_options.yml b/tests/integration/targets/elb_application_lb/tasks/test_alb_ip_address_type_options.yml deleted file mode 100644 --- a/tests/integration/targets/elb_application_lb/tasks/test_alb_ip_address_type_options.yml +++ /dev/null @@ -1,93 +0,0 @@ -- block: - - name: set elb name for ipv6 - set_fact: - elb_name_ipv6: "{{ alb_name ~ 'ipv6' }}" - - - name: test creating an ELB with invalid ip address type - elb_application_lb: - name: "{{ elb_name_ipv6 }}" - subnets: "{{ alb_subnets }}" - security_groups: "{{ sec_group.group_id }}" - state: present - listeners: - - Protocol: HTTP - Port: 80 - DefaultActions: - - Type: forward - TargetGroupName: "{{ tg_name }}" - ip_address_type: "ip_addr_v4_v6" - ignore_errors: yes - register: elb - - - assert: - that: - - elb is failed - - - name: test creating an ELB with dualstack ip adress type - elb_application_lb: - name: "{{ elb_name_ipv6 }}" - subnets: "{{ alb_subnets }}" - security_groups: "{{ sec_group.group_id }}" - state: present - listeners: - - Protocol: HTTP - Port: 80 - DefaultActions: - - Type: forward - TargetGroupName: "{{ tg_name }}" - ip_address_type: "dualstack" - register: elb - - - assert: - that: - - elb.ip_address_type == "dualstack" - - - name: test updating an ELB with ipv4 adress type - elb_application_lb: - name: "{{ elb_name_ipv6 }}" - subnets: "{{ alb_subnets }}" - security_groups: "{{ sec_group.group_id }}" - state: present - listeners: - - Protocol: HTTP - Port: 80 - DefaultActions: - - Type: forward - TargetGroupName: "{{ tg_name }}" - ip_address_type: "ipv4" - register: elb - - - assert: - that: - - elb.changed - - elb.ip_address_type == "ipv4" - - - name: test idempotence updating an ELB with ipv4 adress type - elb_application_lb: - name: "{{ elb_name_ipv6 }}" - subnets: "{{ alb_subnets }}" - security_groups: "{{ sec_group.group_id }}" - state: present - listeners: - - Protocol: HTTP - Port: 80 - DefaultActions: - - Type: forward - TargetGroupName: "{{ tg_name }}" - ip_address_type: "ipv4" - register: elb - - - assert: - that: - - not elb.changed - - elb.ip_address_type == "ipv4" - - always: - # Cleanup - - name: destroy ALB if created - elb_application_lb: - name: '{{ elb_name_ipv6 }}' - state: absent - wait: true - wait_timeout: 600 - ignore_errors: true diff --git a/tests/integration/targets/elb_application_lb/tasks/test_alb_tags.yml b/tests/integration/targets/elb_application_lb/tasks/test_alb_tags.yml deleted file mode 100644 --- a/tests/integration/targets/elb_application_lb/tasks/test_alb_tags.yml +++ /dev/null @@ -1,78 +0,0 @@ -- block: - - - name: create ALB with no listeners - elb_application_lb: - name: "{{ alb_name }}" - subnets: "{{ alb_subnets }}" - security_groups: "{{ sec_group.group_id }}" - state: present - register: alb - - - assert: - that: - - alb.changed - - - name: re-create ALB with no listeners - elb_application_lb: - name: "{{ alb_name }}" - subnets: "{{ alb_subnets }}" - security_groups: "{{ sec_group.group_id }}" - state: present - register: alb - - - assert: - that: - - not alb.changed - - - name: add tags to ALB - elb_application_lb: - name: "{{ alb_name }}" - subnets: "{{ alb_subnets }}" - security_groups: "{{ sec_group.group_id }}" - state: present - tags: - created_by: "ALB test {{ resource_prefix }}" - register: alb - - - assert: - that: - - alb.changed - - 'alb.tags == {"created_by": "ALB test {{ resource_prefix }}"}' - - - name: remove tags from ALB - elb_application_lb: - name: "{{ alb_name }}" - subnets: "{{ alb_subnets }}" - security_groups: "{{ sec_group.group_id }}" - state: present - tags: {} - register: alb - - - assert: - that: - - alb.changed - - not alb.tags - - - name: test idempotence - elb_application_lb: - name: "{{ alb_name }}" - subnets: "{{ alb_subnets }}" - security_groups: "{{ sec_group.group_id }}" - state: present - tags: {} - register: alb - - - assert: - that: - - not alb.changed - - not alb.tags - - - name: destroy ALB with no listeners - elb_application_lb: - name: "{{ alb_name }}" - state: absent - register: alb - - - assert: - that: - - alb.changed diff --git a/tests/integration/targets/elb_application_lb/tasks/test_alb_with_asg.yml b/tests/integration/targets/elb_application_lb/tasks/test_alb_with_asg.yml deleted file mode 100644 --- a/tests/integration/targets/elb_application_lb/tasks/test_alb_with_asg.yml +++ /dev/null @@ -1,73 +0,0 @@ -- block: - - - ec2_ami_info: - filters: - architecture: x86_64 - virtualization-type: hvm - root-device-type: ebs - name: "amzn-ami-hvm*" - owner-alias: "amazon" - register: amis - - - set_fact: - latest_amazon_linux: "{{ amis.images | sort(attribute='creation_date') | last }}" - - - ec2_asg: - state: absent - name: "{{ resource_prefix }}-webservers" - wait_timeout: 900 - - - ec2_lc: - name: "{{ resource_prefix }}-web-lcfg" - state: absent - - - name: Create launch config for testing - ec2_lc: - name: "{{ resource_prefix }}-web-lcfg" - assign_public_ip: true - image_id: "{{ latest_amazon_linux.image_id }}" - security_groups: "{{ sec_group.group_id }}" - instance_type: t2.medium - user_data: | - #!/bin/bash - set -x - yum update -y --nogpgcheck - yum install -y --nogpgcheck httpd - echo "Hello Ansiblings!" >> /var/www/html/index.html - service httpd start - volumes: - - device_name: /dev/xvda - volume_size: 10 - volume_type: gp2 - delete_on_termination: true - - - name: Create autoscaling group for app server fleet - ec2_asg: - name: "{{ resource_prefix }}-webservers" - vpc_zone_identifier: "{{ alb_subnets }}" - launch_config_name: "{{ resource_prefix }}-web-lcfg" - termination_policies: - - OldestLaunchConfiguration - - Default - health_check_period: 600 - health_check_type: EC2 - replace_all_instances: true - min_size: 0 - max_size: 2 - desired_capacity: 1 - wait_for_instances: true - target_group_arns: - - "{{ tg.target_group_arn }}" - - always: - - - ec2_asg: - state: absent - name: "{{ resource_prefix }}-webservers" - wait_timeout: 900 - ignore_errors: yes - - - ec2_lc: - name: "{{ resource_prefix }}-web-lcfg" - state: absent - ignore_errors: yes diff --git a/tests/integration/targets/elb_application_lb/tasks/test_creating_alb.yml b/tests/integration/targets/elb_application_lb/tasks/test_creating_alb.yml deleted file mode 100644 --- a/tests/integration/targets/elb_application_lb/tasks/test_creating_alb.yml +++ /dev/null @@ -1,41 +0,0 @@ -- block: - - - name: create ALB with a listener - elb_application_lb: - name: "{{ alb_name }}" - subnets: "{{ alb_subnets }}" - security_groups: "{{ sec_group.group_id }}" - state: present - listeners: - - Protocol: HTTP - Port: 80 - DefaultActions: - - Type: forward - TargetGroupName: "{{ tg_name }}" - register: alb - - - assert: - that: - - alb.changed - - alb.listeners|length == 1 - - alb.listeners[0].rules|length == 1 - - - name: test idempotence creating ALB with a listener - elb_application_lb: - name: "{{ alb_name }}" - subnets: "{{ alb_subnets }}" - security_groups: "{{ sec_group.group_id }}" - state: present - listeners: - - Protocol: HTTP - Port: 80 - DefaultActions: - - Type: forward - TargetGroupName: "{{ tg_name }}" - register: alb - - - assert: - that: - - not alb.changed - - alb.listeners|length == 1 - - alb.listeners[0].rules|length == 1 diff --git a/tests/integration/targets/elb_application_lb/tasks/test_deleting_alb.yml b/tests/integration/targets/elb_application_lb/tasks/test_deleting_alb.yml deleted file mode 100644 --- a/tests/integration/targets/elb_application_lb/tasks/test_deleting_alb.yml +++ /dev/null @@ -1,37 +0,0 @@ -- block: - - - name: destroy ALB with listener - elb_application_lb: - name: "{{ alb_name }}" - subnets: "{{ alb_subnets }}" - security_groups: "{{ sec_group.group_id }}" - state: absent - listeners: - - Protocol: HTTP - Port: 80 - DefaultActions: - - Type: forward - TargetGroupName: "{{ tg_name }}" - wait: yes - wait_timeout: 300 - register: alb - - - name: test idempotence - elb_application_lb: - name: "{{ alb_name }}" - subnets: "{{ alb_subnets }}" - security_groups: "{{ sec_group.group_id }}" - state: absent - listeners: - - Protocol: HTTP - Port: 80 - DefaultActions: - - Type: forward - TargetGroupName: "{{ tg_name }}" - wait: yes - wait_timeout: 300 - register: alb - - - assert: - that: - - not alb.changed diff --git a/tests/integration/targets/elb_application_lb/tasks/test_modifying_alb_listeners.yml b/tests/integration/targets/elb_application_lb/tasks/test_modifying_alb_listeners.yml deleted file mode 100644 --- a/tests/integration/targets/elb_application_lb/tasks/test_modifying_alb_listeners.yml +++ /dev/null @@ -1,222 +0,0 @@ -- block: - - - name: add a rule to the listener - elb_application_lb: - name: "{{ alb_name }}" - subnets: "{{ alb_subnets }}" - security_groups: "{{ sec_group.group_id }}" - state: present - listeners: - - Protocol: HTTP - Port: 80 - DefaultActions: - - Type: forward - TargetGroupName: "{{ tg_name }}" - Rules: - - Conditions: - - Field: path-pattern - Values: - - '/test' - Priority: '1' - Actions: - - TargetGroupName: "{{ tg_name }}" - Type: forward - register: alb - - - assert: - that: - - alb.changed - - alb.listeners[0].rules|length == 2 - - - name: test replacing the rule with one with the same priority - elb_application_lb: - name: "{{ alb_name }}" - subnets: "{{ alb_subnets }}" - security_groups: "{{ sec_group.group_id }}" - state: present - purge_listeners: true - listeners: - - Protocol: HTTP - Port: 80 - DefaultActions: - - Type: forward - TargetGroupName: "{{ tg_name }}" - Rules: - - Conditions: - - Field: path-pattern - Values: - - '/new' - Priority: '1' - Actions: - - TargetGroupName: "{{ tg_name }}" - Type: forward - register: alb - - - assert: - that: - - alb.changed - - alb.listeners[0].rules|length == 2 - - - name: test the rule will not be removed without purge_listeners - elb_application_lb: - name: "{{ alb_name }}" - subnets: "{{ alb_subnets }}" - security_groups: "{{ sec_group.group_id }}" - state: present - listeners: - - Protocol: HTTP - Port: 80 - DefaultActions: - - Type: forward - TargetGroupName: "{{ tg_name }}" - register: alb - - - assert: - that: - - not alb.changed - - alb.listeners[0].rules|length == 2 - - - name: test a rule can be added and other rules will not be removed when purge_rules is no. - elb_application_lb: - name: "{{ alb_name }}" - subnets: "{{ alb_subnets }}" - security_groups: "{{ sec_group.group_id }}" - state: present - purge_rules: no - listeners: - - Protocol: HTTP - Port: 80 - DefaultActions: - - Type: forward - TargetGroupName: "{{ tg_name }}" - Rules: - - Conditions: - - Field: path-pattern - Values: - - '/new' - Priority: '2' - Actions: - - TargetGroupName: "{{ tg_name }}" - Type: forward - register: alb - - - assert: - that: - - alb.changed - - alb.listeners[0].rules|length == 3 - - - name: add a rule that uses the host header condition to the listener - elb_application_lb: - name: "{{ alb_name }}" - subnets: "{{ alb_subnets }}" - security_groups: "{{ sec_group.group_id }}" - state: present - purge_rules: no - listeners: - - Protocol: HTTP - Port: 80 - DefaultActions: - - Type: forward - TargetGroupName: "{{ tg_name }}" - Rules: - - Conditions: - - Field: host-header - Values: - - 'local.mydomain.com' - Priority: '3' - Actions: - - TargetGroupName: "{{ tg_name }}" - Type: forward - register: alb - - - assert: - that: - - alb.changed - - alb.listeners[0].rules|length == 4 - # - '{{ alb|community.general.json_query("listeners[].rules[].conditions[].host_header_config.values[]")|length == 1 }}' - - - name: test replacing the rule that uses the host header condition with multiple host header conditions - elb_application_lb: - name: "{{ alb_name }}" - subnets: "{{ alb_subnets }}" - security_groups: "{{ sec_group.group_id }}" - purge_rules: no - state: present - listeners: - - Protocol: HTTP - Port: 80 - DefaultActions: - - Type: forward - TargetGroupName: "{{ tg_name }}" - Rules: - - Conditions: - - Field: host-header - Values: - - 'local.mydomain.com' - - 'alternate.mydomain.com' - Priority: '3' - Actions: - - TargetGroupName: "{{ tg_name }}" - Type: forward - register: alb - - - assert: - that: - - alb.changed - - alb.listeners[0].rules|length == 4 - #- '{{ alb|community.general.json_query("listeners[].rules[].conditions[].host_header_config.values[]")|length == 2 }}' - - - name: remove the rule - elb_application_lb: - name: "{{ alb_name }}" - subnets: "{{ alb_subnets }}" - security_groups: "{{ sec_group.group_id }}" - state: present - purge_listeners: true - listeners: - - Protocol: HTTP - Port: 80 - DefaultActions: - - Type: forward - TargetGroupName: "{{ tg_name }}" - Rules: [] - register: alb - - - assert: - that: - - alb.changed - - alb.listeners[0].rules|length == 1 - - - name: remove listener from ALB - elb_application_lb: - name: "{{ alb_name }}" - subnets: "{{ alb_subnets }}" - security_groups: "{{ sec_group.group_id }}" - state: present - listeners: [] - register: alb - - - assert: - that: - - alb.changed - - not alb.listeners - - - name: add the listener to the ALB - elb_application_lb: - name: "{{ alb_name }}" - subnets: "{{ alb_subnets }}" - security_groups: "{{ sec_group.group_id }}" - state: present - listeners: - - Protocol: HTTP - Port: 80 - DefaultActions: - - Type: forward - TargetGroupName: "{{ tg_name }}" - register: alb - - - assert: - that: - - alb.changed - - alb.listeners|length == 1 - - alb.availability_zones|length == 2 diff --git a/tests/integration/targets/elb_application_lb/tasks/test_multiple_actions.yml b/tests/integration/targets/elb_application_lb/tasks/test_multiple_actions.yml deleted file mode 100644 --- a/tests/integration/targets/elb_application_lb/tasks/test_multiple_actions.yml +++ /dev/null @@ -1,447 +0,0 @@ -- block: - - - name: register dummy OIDC config - set_fact: - AuthenticateOidcActionConfig: - AuthorizationEndpoint: "https://www.example.com/auth" - ClientId: "eeeeeeeeeeeeeeeeeeeeeeeeee" - ClientSecret: "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee" - Issuer: "https://www.example.com/issuer" - OnUnauthenticatedRequest: "authenticate" - Scope: "openid" - SessionCookieName: "AWSELBAuthSessionCookie" - SessionTimeout: 604800 - TokenEndpoint: "https://www.example.com/token" - UserInfoEndpoint: "https://www.example.com/userinfo" - UseExistingClientSecret: true - - - name: register fixed response action - set_fact: - FixedResponseActionConfig: - ContentType: "text/plain" - MessageBody: "This is the page you're looking for" - StatusCode: "200" - - - name: register redirect action - set_fact: - RedirectActionConfig: - Host: "#{host}" - Path: "/example/redir" # or /#{path} - Port: "#{port}" - Protocol: "#{protocol}" - Query: "#{query}" - StatusCode: "HTTP_302" # or HTTP_301 - - - name: delete existing ALB to avoid target group association issues - elb_application_lb: - name: "{{ alb_name }}" - state: absent - wait: yes - wait_timeout: 600 - - - name: cleanup tg to avoid target group association issues - elb_target_group: - name: "{{ tg_name }}" - protocol: http - port: 80 - vpc_id: "{{ vpc.vpc.id }}" - state: absent - wait: yes - wait_timeout: 600 - register: cleanup_tg - retries: 5 - delay: 3 - until: cleanup_tg is success - - - name: recreate a target group - elb_target_group: - name: "{{ tg_name }}" - protocol: http - port: 80 - vpc_id: "{{ vpc.vpc.id }}" - state: present - register: tg - - - name: create ALB with redirect DefaultAction - elb_application_lb: - name: "{{ alb_name }}" - subnets: "{{ alb_subnets }}" - security_groups: "{{ sec_group.group_id }}" - state: present - listeners: - - Protocol: HTTP - Port: 80 - DefaultActions: - - Type: redirect - RedirectConfig: "{{ RedirectActionConfig }}" - register: alb - - - assert: - that: - - alb.changed - - alb.listeners|length == 1 - - alb.listeners[0].rules[0].actions|length == 1 - - alb.listeners[0].rules[0].actions[0].type == "redirect" - - - name: test idempotence with redirect DefaultAction - elb_application_lb: - name: "{{ alb_name }}" - subnets: "{{ alb_subnets }}" - security_groups: "{{ sec_group.group_id }}" - state: present - listeners: - - Protocol: HTTP - Port: 80 - DefaultActions: - - Type: redirect - RedirectConfig: "{{ RedirectActionConfig }}" - register: alb - - - assert: - that: - - not alb.changed - - alb.listeners|length == 1 - - alb.listeners[0].rules[0].actions|length == 1 - - alb.listeners[0].rules[0].actions[0].type == "redirect" - - - name: update ALB with fixed-response DefaultAction - elb_application_lb: - name: "{{ alb_name }}" - subnets: "{{ alb_subnets }}" - security_groups: "{{ sec_group.group_id }}" - state: present - listeners: - - Protocol: HTTP - Port: 80 - DefaultActions: - - Type: fixed-response - FixedResponseConfig: "{{ FixedResponseActionConfig }}" - register: alb - - - assert: - that: - - alb.changed - - alb.listeners|length == 1 - - alb.listeners[0].rules[0].actions|length == 1 - - alb.listeners[0].rules[0].actions[0].type == "fixed-response" - - - name: test idempotence with fixed-response DefaultAction - elb_application_lb: - name: "{{ alb_name }}" - subnets: "{{ alb_subnets }}" - security_groups: "{{ sec_group.group_id }}" - state: present - listeners: - - Protocol: HTTP - Port: 80 - DefaultActions: - - Type: fixed-response - FixedResponseConfig: "{{ FixedResponseActionConfig }}" - register: alb - - - assert: - that: - - not alb.changed - - alb.listeners|length == 1 - - alb.listeners[0].rules[0].actions|length == 1 - - alb.listeners[0].rules[0].actions[0].type == "fixed-response" - - - name: test multiple non-default rules - elb_application_lb: - name: "{{ alb_name }}" - subnets: "{{ alb_subnets }}" - security_groups: "{{ sec_group.group_id }}" - state: present - listeners: - - Protocol: HTTP - Port: 80 - DefaultActions: - - Type: fixed-response - FixedResponseConfig: "{{ FixedResponseActionConfig }}" - Rules: - - Conditions: - - Field: http-header - HttpHeaderConfig: - HttpHeaderName: 'User-Agent' - Values: ['*Trident/7:0*rv:*'] - - Field: http-header - HttpHeaderConfig: - HttpHeaderName: 'X-Something' - Values: ['foobar'] - Priority: '1' - Actions: - - Type: fixed-response - FixedResponseConfig: - StatusCode: "200" - ContentType: "text/html" - MessageBody: "<b>Hello World!</b>" - - Conditions: - - Field: path-pattern - Values: - - "/forward-path/*" - Priority: 2 - Actions: - - Type: forward - TargetGroupName: "{{ tg_name }}" - - Conditions: - - Field: path-pattern - Values: - - "/redirect-path/*" - Priority: 3 - Actions: - - Type: redirect - RedirectConfig: "{{ RedirectActionConfig }}" - - Conditions: - - Field: path-pattern - Values: - - "/fixed-response-path/" - Priority: 4 - Actions: - - Type: fixed-response - FixedResponseConfig: "{{ FixedResponseActionConfig }}" - register: alb - - - assert: - that: - - alb.changed - - alb.listeners|length == 1 - - alb.listeners[0].rules|length == 5 ## defaultactions is included as a rule - - alb.listeners[0].rules[0].actions|length == 1 - - alb.listeners[0].rules[0].actions[0].type == "fixed-response" - - alb.listeners[0].rules[1].actions|length == 1 - - alb.listeners[0].rules[1].actions[0].type == "forward" - - alb.listeners[0].rules[2].actions|length == 1 - - alb.listeners[0].rules[2].actions[0].type == "redirect" - - alb.listeners[0].rules[3].actions|length == 1 - - alb.listeners[0].rules[3].actions[0].type == "fixed-response" - - - name: test idempotence multiple non-default rules - elb_application_lb: - name: "{{ alb_name }}" - subnets: "{{ alb_subnets }}" - security_groups: "{{ sec_group.group_id }}" - state: present - listeners: - - Protocol: HTTP - Port: 80 - DefaultActions: - - Type: fixed-response - FixedResponseConfig: "{{ FixedResponseActionConfig }}" - Rules: - - Conditions: - - Field: http-header - HttpHeaderConfig: - HttpHeaderName: 'User-Agent' - Values: ['*Trident/7:0*rv:*'] - - Field: http-header - HttpHeaderConfig: - HttpHeaderName: 'X-Something' - Values: ['foobar'] - Priority: '1' - Actions: - - Type: fixed-response - FixedResponseConfig: - StatusCode: "200" - ContentType: "text/html" - MessageBody: "<b>Hello World!</b>" - - Conditions: - - Field: path-pattern - Values: - - "/forward-path/*" - Priority: 2 - Actions: - - Type: forward - TargetGroupName: "{{ tg_name }}" - - Conditions: - - Field: path-pattern - Values: - - "/redirect-path/*" - Priority: 3 - Actions: - - Type: redirect - RedirectConfig: "{{ RedirectActionConfig }}" - - Conditions: - - Field: path-pattern - Values: - - "/fixed-response-path/" - Priority: 4 - Actions: - - Type: fixed-response - FixedResponseConfig: "{{ FixedResponseActionConfig }}" - register: alb - - - assert: - that: - - not alb.changed - - alb.listeners|length == 1 - - alb.listeners[0].rules|length == 5 ## defaultactions is included as a rule - - alb.listeners[0].rules[0].actions|length == 1 - - alb.listeners[0].rules[0].actions[0].type == "fixed-response" - - alb.listeners[0].rules[1].actions|length == 1 - - alb.listeners[0].rules[1].actions[0].type == "forward" - - alb.listeners[0].rules[2].actions|length == 1 - - alb.listeners[0].rules[2].actions[0].type == "redirect" - - alb.listeners[0].rules[3].actions|length == 1 - - alb.listeners[0].rules[3].actions[0].type == "fixed-response" - - -# - name: test creating ALB with a default listener with multiple actions -# elb_application_lb: -# name: "{{ alb_name }}" -# subnets: "{{ alb_subnets }}" -# security_groups: "{{ sec_group.group_id }}" -# state: present -# listeners: -# - Protocol: HTTP -# Port: 80 -# DefaultActions: -# - Type: forward -# TargetGroupName: "{{ tg_name }}" -# Order: 2 -# - Type: authenticate-oidc -# AuthenticateOidcConfig: "{{ AuthenticateOidcActionConfig }}" -# Order: 1 -# register: alb -# -# - assert: -# that: -# - alb.listeners|length == 1 -# - alb.listeners[0].rules[0].actions|length == 2 -# -# - name: test changing order of actions -# elb_application_lb: -# name: "{{ alb_name }}" -# subnets: "{{ alb_subnets }}" -# security_groups: "{{ sec_group.group_id }}" -# state: present -# listeners: -# - Protocol: HTTP -# Port: 80 -# DefaultActions: -# - Type: authenticate-oidc -# AuthenticateOidcConfig: "{{ AuthenticateOidcActionConfig }}" -# Order: 1 -# - Type: forward -# TargetGroupName: "{{ tg_name }}" -# Order: 2 -# register: alb -# -# - assert: -# that: -# - not alb.changed -# - alb.listeners|length == 1 -# - alb.listeners[0].rules[0].actions|length == 2 -# -# - name: test non-default rule with multiple actions -# elb_application_lb: -# name: "{{ alb_name }}" -# subnets: "{{ alb_subnets }}" -# security_groups: "{{ sec_group.group_id }}" -# state: present -# listeners: -# - Protocol: HTTP -# Port: 80 -# DefaultActions: -# - Type: authenticate-oidc -# AuthenticateOidcConfig: "{{ AuthenticateOidcActionConfig }}" -# Order: 1 -# - Type: forward -# TargetGroupName: "{{ tg_name }}" -# Order: 2 -# Rules: -# - Conditions: -# - Field: path-pattern -# Values: -# - "*" -# Priority: 1 -# Actions: -# - Type: forward -# TargetGroupName: "{{ tg_name }}" -# Order: 2 -# - Type: authenticate-oidc -# AuthenticateOidcConfig: "{{ AuthenticateOidcActionConfig }}" -# Order: 1 -# register: alb -# -# - assert: -# that: -# - alb.changed -# - alb.listeners|length == 1 -# - alb.listeners[0].rules[0].actions|length == 2 -# - alb.listeners[0].rules[1].actions|length == 2 -# -# - name: test idempotency non-default rule with multiple actions -# elb_application_lb: -# name: "{{ alb_name }}" -# subnets: "{{ alb_subnets }}" -# security_groups: "{{ sec_group.group_id }}" -# state: present -# listeners: -# - Protocol: HTTP -# Port: 80 -# DefaultActions: -# - Type: authenticate-oidc -# AuthenticateOidcConfig: "{{ AuthenticateOidcActionConfig }}" -# Order: 1 -# - Type: forward -# TargetGroupName: "{{ tg_name }}" -# Order: 2 -# Rules: -# - Conditions: -# - Field: path-pattern -# Values: -# - "*" -# Priority: 1 -# Actions: -# - Type: forward -# TargetGroupName: "{{ tg_name }}" -# Order: 2 -# - Type: authenticate-oidc -# AuthenticateOidcConfig: "{{ AuthenticateOidcActionConfig }}" -# Order: 1 -# register: alb -# -# - assert: -# that: -# - not alb.changed -# - alb.listeners|length == 1 -# - alb.listeners[0].rules[0].actions|length == 2 -# - alb.listeners[0].rules[1].actions|length == 2 -# -# - name: test non-default rule action order change -# elb_application_lb: -# name: "{{ alb_name }}" -# subnets: "{{ alb_subnets }}" -# security_groups: "{{ sec_group.group_id }}" -# state: present -# listeners: -# - Protocol: HTTP -# Port: 80 -# DefaultActions: -# - Type: authenticate-oidc -# AuthenticateOidcConfig: "{{ AuthenticateOidcActionConfig }}" -# Order: 1 -# - Type: forward -# TargetGroupName: "{{ tg_name }}" -# Order: 2 -# Rules: -# - Conditions: -# - Field: path-pattern -# Values: -# - "*" -# Priority: 1 -# Actions: -# - Type: authenticate-oidc -# AuthenticateOidcConfig: "{{ AuthenticateOidcActionConfig }}" -# Order: 1 -# - Type: forward -# TargetGroupName: "{{ tg_name }}" -# Order: 2 -# register: alb -# -# - assert: -# that: -# - not alb.changed -# - alb.listeners|length == 1 -# - alb.listeners[0].rules[0].actions|length == 2 -# - alb.listeners[0].rules[1].actions|length == 2 diff --git a/tests/integration/targets/elb_application_lb_info/aliases b/tests/integration/targets/elb_application_lb_info/aliases deleted file mode 100644 --- a/tests/integration/targets/elb_application_lb_info/aliases +++ /dev/null @@ -1 +0,0 @@ -cloud/aws diff --git a/tests/integration/targets/elb_application_lb_info/defaults/main.yml b/tests/integration/targets/elb_application_lb_info/defaults/main.yml deleted file mode 100644 --- a/tests/integration/targets/elb_application_lb_info/defaults/main.yml +++ /dev/null @@ -1,4 +0,0 @@ ---- -resource_short: "{{ '%0.8x'%((16**8) | random(seed=resource_prefix)) }}" -alb_name: "alb-test-{{ resource_short }}" -tg_name: "alb-test-{{ resource_short }}" diff --git a/tests/integration/targets/elb_application_lb_info/meta/main.yml b/tests/integration/targets/elb_application_lb_info/meta/main.yml deleted file mode 100644 --- a/tests/integration/targets/elb_application_lb_info/meta/main.yml +++ /dev/null @@ -1,2 +0,0 @@ -dependencies: - - setup_remote_tmp_dir diff --git a/tests/integration/targets/elb_application_lb_info/tasks/full_test.yml b/tests/integration/targets/elb_application_lb_info/tasks/full_test.yml deleted file mode 100644 --- a/tests/integration/targets/elb_application_lb_info/tasks/full_test.yml +++ /dev/null @@ -1,11 +0,0 @@ -- name: elb_application_lb full_test - block: - # setup - - include_tasks: setup.yml - - # Run main tests - - include_tasks: test_elb_application_lb_info.yml - - always: - # Cleanup - - include_tasks: teardown.yml diff --git a/tests/integration/targets/elb_application_lb_info/tasks/main.yml b/tests/integration/targets/elb_application_lb_info/tasks/main.yml deleted file mode 100644 --- a/tests/integration/targets/elb_application_lb_info/tasks/main.yml +++ /dev/null @@ -1,11 +0,0 @@ -- name: 'elb_application_lb_info integration tests' - collections: - - amazon.aws - module_defaults: - group/aws: - aws_access_key: '{{ aws_access_key }}' - aws_secret_key: '{{ aws_secret_key }}' - security_token: '{{ security_token | default(omit) }}' - region: '{{ aws_region }}' - block: - - include_tasks: full_test.yml diff --git a/tests/integration/targets/elb_application_lb_info/tasks/setup.yml b/tests/integration/targets/elb_application_lb_info/tasks/setup.yml deleted file mode 100644 --- a/tests/integration/targets/elb_application_lb_info/tasks/setup.yml +++ /dev/null @@ -1,84 +0,0 @@ -- name: elb_application_lb_info setup - block: - - name: create VPC - ec2_vpc_net: - cidr_block: 10.228.228.0/22 - name: '{{ resource_prefix }}_vpc' - state: present - register: vpc - - - name: create internet gateway - ec2_vpc_igw: - vpc_id: '{{ vpc.vpc.id }}' - state: present - tags: - Name: '{{ resource_prefix }}' - register: igw - - - name: create public subnet - ec2_vpc_subnet: - cidr: '{{ item.cidr }}' - az: '{{ aws_region}}{{ item.az }}' - vpc_id: '{{ vpc.vpc.id }}' - state: present - tags: - Public: '{{ item.public|string }}' - Name: '{{ item.public|ternary(''public'', ''private'') }}-{{ item.az }}' - with_items: - - cidr: 10.228.228.0/24 - az: a - public: 'True' - - cidr: 10.228.229.0/24 - az: b - public: 'True' - - cidr: 10.228.230.0/24 - az: a - public: 'False' - - cidr: 10.228.231.0/24 - az: b - public: 'False' - register: subnets - - - ec2_vpc_subnet_info: - filters: - vpc-id: '{{ vpc.vpc.id }}' - register: vpc_subnets - - - name: create list of subnet ids - set_fact: - alb_subnets: "{{ ( vpc_subnets.subnets | selectattr('tags.Public', 'equalto', 'True') | map(attribute='id') | list ) }}" - private_subnets: "{{ ( vpc_subnets.subnets | rejectattr('tags.Public', 'equalto', 'True') | map(attribute='id') | list ) }}" - - - name: create a route table - ec2_vpc_route_table: - vpc_id: '{{ vpc.vpc.id }}' - tags: - Name: igw-route - Created: '{{ resource_prefix }}' - subnets: '{{ alb_subnets + private_subnets }}' - routes: - - dest: 0.0.0.0/0 - gateway_id: '{{ igw.gateway_id }}' - register: route_table - - - ec2_group: - name: '{{ resource_prefix }}' - description: security group for Ansible ALB integration tests - state: present - vpc_id: '{{ vpc.vpc.id }}' - rules: - - proto: tcp - from_port: 1 - to_port: 65535 - cidr_ip: 0.0.0.0/0 - register: sec_group - - - name: create a target group for testing - elb_target_group: - name: '{{ tg_name }}' - protocol: http - port: 80 - vpc_id: '{{ vpc.vpc.id }}' - state: present - register: tg - diff --git a/tests/integration/targets/elb_application_lb_info/tasks/teardown.yml b/tests/integration/targets/elb_application_lb_info/tasks/teardown.yml deleted file mode 100644 --- a/tests/integration/targets/elb_application_lb_info/tasks/teardown.yml +++ /dev/null @@ -1,83 +0,0 @@ -- name: elb_application_lb_info teardown - block: - - name: destroy ALB - elb_application_lb: - name: '{{ alb_name }}' - state: absent - wait: true - wait_timeout: 600 - ignore_errors: true - - - name: destroy target group if it was created - elb_target_group: - name: '{{ tg_name }}' - protocol: http - port: 80 - vpc_id: '{{ vpc.vpc.id }}' - state: absent - wait: true - wait_timeout: 600 - register: remove_tg - retries: 5 - delay: 3 - until: remove_tg is success - when: tg is defined - ignore_errors: true - - name: destroy sec group - ec2_group: - name: '{{ sec_group.group_name }}' - description: security group for Ansible ALB integration tests - state: absent - vpc_id: '{{ vpc.vpc.id }}' - register: remove_sg - retries: 10 - delay: 5 - until: remove_sg is success - ignore_errors: true - - name: remove route table - ec2_vpc_route_table: - vpc_id: '{{ vpc.vpc.id }}' - route_table_id: '{{ route_table.route_table.route_table_id }}' - lookup: id - state: absent - register: remove_rt - retries: 10 - delay: 5 - until: remove_rt is success - ignore_errors: true - - name: destroy subnets - ec2_vpc_subnet: - cidr: '{{ item.cidr }}' - vpc_id: '{{ vpc.vpc.id }}' - state: absent - register: remove_subnet - retries: 10 - delay: 5 - until: remove_subnet is success - with_items: - - cidr: 10.228.228.0/24 - - cidr: 10.228.229.0/24 - - cidr: 10.228.230.0/24 - - cidr: 10.228.231.0/24 - ignore_errors: true - - name: destroy internet gateway - ec2_vpc_igw: - vpc_id: '{{ vpc.vpc.id }}' - tags: - Name: '{{ resource_prefix }}' - state: absent - register: remove_igw - retries: 10 - delay: 5 - until: remove_igw is success - ignore_errors: true - - name: destroy VPC - ec2_vpc_net: - cidr_block: 10.228.228.0/22 - name: '{{ resource_prefix }}_vpc' - state: absent - register: remove_vpc - retries: 10 - delay: 5 - until: remove_vpc is success - ignore_errors: true diff --git a/tests/integration/targets/elb_application_lb_info/tasks/test_elb_application_lb_info.yml b/tests/integration/targets/elb_application_lb_info/tasks/test_elb_application_lb_info.yml deleted file mode 100644 --- a/tests/integration/targets/elb_application_lb_info/tasks/test_elb_application_lb_info.yml +++ /dev/null @@ -1,41 +0,0 @@ -- block: - - - name: create ALB with a listener - elb_application_lb: - name: "{{ alb_name }}" - subnets: "{{ alb_subnets }}" - security_groups: "{{ sec_group.group_id }}" - state: present - listeners: - - Protocol: HTTP - Port: 80 - DefaultActions: - - Type: forward - TargetGroupName: "{{ tg_name }}" - register: alb - - - assert: - that: - - alb.changed - - alb.listeners|length == 1 - - alb.listeners[0].rules|length == 1 - - - name: ELB applicaiton info using load balancer arn - elb_application_lb_info: - load_balancer_arns: - - "{{ alb.load_balancer_arn }}" - register: elb_app_lb_info - - - assert: - that: - - elb_app_lb_info.load_balancers[0].ip_address_type == 'ipv4' - - - name: ELB applicaiton info using load balancer name - elb_application_lb_info: - names: - - "{{ alb.load_balancer_name }}" - register: elb_app_lb_info - - - assert: - that: - - elb_app_lb_info.load_balancers[0].ip_address_type == 'ipv4'
elb_application_lb with empty security groups list behaves inconsistently on create/update <!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> Resubmitted from https://github.com/ansible-collections/amazon.aws/issues/10 ##### SUMMARY <!--- Explain the problem briefly below --> `elb_application_lb` requires the `security_groups` option when `state=present` as explained in the docs (although it also says that the default is `[]` which seems useless since it won't accept the option being omitted). When creating a new ALB and supplying `security_groups: []` explicitly, the ALB is created successfully with the VPC default SG. Running the same task again will fail with the error that the `security_groups` option is missing, I'm not sure if this is reproducible outside of a VPC since I'm not sure there is such a thing as a default SG in that case. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> elb_application_lb ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> 2.9.6 ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> <!--- Paste example playbooks or commands between quotes below --> ```yaml - elb_application_lb: region: "us-east-1" name: "repro-delete" state: "present" subnets: "{{ my_subnets }}" listeners: - Protocol: HTTP Port: 80 DefaultActions: - Type: forward TargetGroupName: repro-group-us-east-1a scheme: internal security_groups: [] wait: yes register: alb loop: [1, 2] ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> ALB is created, then second run is `ok`. (an acceptable result might also be that the first run fails with an invalid option value, but that does preclude the possibility of using a "default" SG) ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> Second run fails. <!--- Paste verbatim command output between quotes --> ```paste below fatal: [localhost]: FAILED! => {"changed": false, "msg": "state is present but all of the following are missing: security_groups"} ```
Files identified in the description: * [`plugins/modules/elb_application_lb.py`](https://github.com/ansible-collections/community.aws/blob/main/plugins/modules/elb_application_lb.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @jillr @s-hertel @tremble @wimnat [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> @briantist Thank you for reporting this! We have recently this module to our CI so it should be easier to add a test case for this. > I'm not sure if this is reproducible outside of a VPC since I'm not sure there is such a thing as a default SG in that case. imo you can create ALB resources only **in** a VPC. the only way to solve this issue is imo to not allow an empty array as an input for `security_groups` parameter. otherwise and empty array must be treated as "use the VPCs default security group", which must be determined inside the code. I believe that "use the default VPC SG" is a desirable option in some/many use cases, so I wouldn't want to see that option disappear. It would be most useful if the module handled that case correctly, even if internally it means it has to retrieve the VPC default in order to verify its state.
2022-03-28T16:35:33
ansible-collections/community.aws
1,050
ansible-collections__community.aws-1050
[ "849", "191" ]
3500c6ba0b107afe659de40437f0acff53af70c4
diff --git a/plugins/modules/rds_cluster.py b/plugins/modules/rds_cluster.py new file mode 100644 --- /dev/null +++ b/plugins/modules/rds_cluster.py @@ -0,0 +1,1026 @@ +#!/usr/bin/python +# Copyright (c) 2022 Ansible Project +# Copyright (c) 2022 Alina Buzachis (@alinabuzachis) +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + +DOCUMENTATION = r''' +--- +module: rds_cluster +version_added: "3.2.0" +short_description: rds_cluster module +description: + - Create, modify, and delete RDS clusters. +extends_documentation_fragment: +- amazon.aws.aws +- amazon.aws.ec2 +author: + - Sloane Hertel (@s-hertel) + - Alina Buzachis (@alinabuzachis) +options: + # General module options + state: + description: Whether the snapshot should exist or not. + choices: ['present', 'absent'] + default: 'present' + type: str + creation_source: + description: Which source to use if creating from a template (an existing cluster, S3 bucket, or snapshot). + choices: ['snapshot', 's3', 'cluster'] + type: str + force_update_password: + description: + - Set to C(true) to update your cluster password with I(master_user_password). + - Since comparing passwords to determine if it needs to be updated is not possible this is set to C(false) by default to allow idempotence. + type: bool + default: false + promote: + description: Set to C(true) to promote a read replica cluster. + type: bool + default: false + purge_cloudwatch_logs_exports: + description: + - Whether or not to disable Cloudwatch logs enabled for the DB cluster that are not provided in I(enable_cloudwatch_logs_exports). + Set I(enable_cloudwatch_logs_exports) to an empty list to disable all. + type: bool + default: true + purge_tags: + description: + - Whether or not to remove tags assigned to the DB cluster if not specified in the playbook. To remove all tags + set I(tags) to an empty dictionary in conjunction with this. + type: bool + default: true + purge_security_groups: + description: + - Set to C(false) to retain any enabled security groups that aren't specified in the task and are associated with the cluster. + - Can be applied to I(vpc_security_group_ids) + type: bool + default: true + wait: + description: Whether to wait for the cluster to be available or deleted. + type: bool + default: true + # Options that have a corresponding boto3 parameter + apply_immediately: + description: + - A value that specifies whether modifying a cluster with I(new_db_cluster_identifier) and I(master_user_password) + should be applied as soon as possible, regardless of the I(preferred_maintenance_window) setting. If C(false), changes + are applied during the next maintenance window. + type: bool + default: false + availability_zones: + description: + - A list of EC2 Availability Zones that instances in the DB cluster can be created in. + May be used when creating a cluster or when restoring from S3 or a snapshot. + aliases: + - zones + - az + type: list + elements: str + backtrack_to: + description: + - The timestamp of the time to backtrack the DB cluster to in ISO 8601 format, such as "2017-07-08T18:00Z". + type: str + backtrack_window: + description: + - The target backtrack window, in seconds. To disable backtracking, set this value to C(0). + - If specified, this value must be set to a number from C(0) to C(259,200) (72 hours). + default: 0 + type: int + backup_retention_period: + description: + - The number of days for which automated backups are retained (must be within C(1) to C(35)). + May be used when creating a new cluster, when restoring from S3, or when modifying a cluster. + type: int + default: 1 + character_set_name: + description: + - The character set to associate with the DB cluster. + type: str + database_name: + description: + - The name for your database. If a name is not provided Amazon RDS will not create a database. + aliases: + - db_name + type: str + db_cluster_identifier: + description: + - The DB cluster (lowercase) identifier. The identifier must contain from 1 to 63 letters, numbers, or + hyphens and the first character must be a letter and may not end in a hyphen or contain consecutive hyphens. + aliases: + - cluster_id + - id + - cluster_name + type: str + required: true + db_cluster_parameter_group_name: + description: + - The name of the DB cluster parameter group to associate with this DB cluster. + If this argument is omitted when creating a cluster, the default DB cluster parameter group for the specified DB engine and version is used. + type: str + db_subnet_group_name: + description: + - A DB subnet group to associate with this DB cluster if not using the default. + type: str + enable_cloudwatch_logs_exports: + description: + - A list of log types that need to be enabled for exporting to CloudWatch Logs. + - Engine aurora-mysql supports C(audit), C(error), C(general) and C(slowquery). + - Engine aurora-postgresql supports C(postgresql). + type: list + elements: str + deletion_protection: + description: + - A value that indicates whether the DB cluster has deletion protection enabled. + The database can't be deleted when deletion protection is enabled. + By default, deletion protection is disabled. + type: bool + global_cluster_identifier: + description: + - The global cluster ID of an Aurora cluster that becomes the primary cluster in the new global database cluster. + type: str + enable_http_endpoint: + description: + - A value that indicates whether to enable the HTTP endpoint for an Aurora Serverless DB cluster. + By default, the HTTP endpoint is disabled. + type: bool + copy_tags_to_snapshot: + description: + - Indicates whether to copy all tags from the DB cluster to snapshots of the DB cluster. + The default is not to copy them. + type: bool + domain: + description: + - The Active Directory directory ID to create the DB cluster in. + type: str + domain_iam_role_name: + description: + - Specify the name of the IAM role to be used when making API calls to the Directory Service. + type: str + enable_global_write_forwarding: + description: + - A value that indicates whether to enable this DB cluster to forward write operations to the primary cluster of an Aurora global database. + By default, write operations are not allowed on Aurora DB clusters that are secondary clusters in an Aurora global database. + - This value can be only set on Aurora DB clusters that are members of an Aurora global database. + type: bool + enable_iam_database_authentication: + description: + - Enable mapping of AWS Identity and Access Management (IAM) accounts to database accounts. + If this option is omitted when creating the cluster, Amazon RDS sets this to C(false). + type: bool + engine: + description: + - The name of the database engine to be used for this DB cluster. This is required to create a cluster. + choices: + - aurora + - aurora-mysql + - aurora-postgresql + type: str + engine_version: + description: + - The version number of the database engine to use. + - For Aurora MySQL that could be C(5.6.10a), C(5.7.12). + - Aurora PostgreSQL example, C(9.6.3). + type: str + final_snapshot_identifier: + description: + - The DB cluster snapshot identifier of the new DB cluster snapshot created when I(skip_final_snapshot=false). + type: str + force_backtrack: + description: + - A boolean to indicate if the DB cluster should be forced to backtrack when binary logging is enabled. + Otherwise, an error occurs when binary logging is enabled. + type: bool + kms_key_id: + description: + - The AWS KMS key identifier (the ARN, unless you are creating a cluster in the same account that owns the + KMS key, in which case the KMS key alias may be used). + - If I(replication_source_identifier) specifies an encrypted source Amazon RDS will use the key used toe encrypt the source. + - If I(storage_encrypted=true) and and I(replication_source_identifier) is not provided, the default encryption key is used. + type: str + master_user_password: + description: + - An 8-41 character password for the master database user. + - The password can contain any printable ASCII character except "/", """, or "@". + - To modify the password use I(force_password_update). Use I(apply immediately) to change + the password immediately, otherwise it is updated during the next maintenance window. + aliases: + - password + type: str + master_username: + description: + - The name of the master user for the DB cluster. Must be 1-16 letters or numbers and begin with a letter. + aliases: + - username + type: str + new_db_cluster_identifier: + description: + - The new DB cluster (lowercase) identifier for the DB cluster when renaming a DB cluster. + - The identifier must contain from 1 to 63 letters, numbers, or hyphens and the first character must be a + letter and may not end in a hyphen or contain consecutive hyphens. + - Use I(apply_immediately) to rename immediately, otherwise it is updated during the next maintenance window. + aliases: + - new_cluster_id + - new_id + - new_cluster_name + type: str + option_group_name: + description: + - The option group to associate with the DB cluster. + type: str + port: + description: + - The port number on which the instances in the DB cluster accept connections. If not specified, Amazon RDS + defaults this to C(3306) if the I(engine) is C(aurora) and c(5432) if the I(engine) is C(aurora-postgresql). + type: int + preferred_backup_window: + description: + - The daily time range (in UTC) of at least 30 minutes, during which automated backups are created if automated backups are + enabled using I(backup_retention_period). The option must be in the format of "hh24:mi-hh24:mi" and not conflict with + I(preferred_maintenance_window). + aliases: + - backup_window + type: str + preferred_maintenance_window: + description: + - The weekly time range (in UTC) of at least 30 minutes, during which system maintenance can occur. The option must + be in the format "ddd:hh24:mi-ddd:hh24:mi" where ddd is one of Mon, Tue, Wed, Thu, Fri, Sat, Sun. + aliases: + - maintenance_window + type: str + replication_source_identifier: + description: + - The Amazon Resource Name (ARN) of the source DB instance or DB cluster if this DB cluster is created as a Read Replica. + aliases: + - replication_src_id + type: str + restore_to_time: + description: + - The UTC date and time to restore the DB cluster to. Must be in the format "2015-03-07T23:45:00Z". + - If this is not provided while restoring a cluster, I(use_latest_restorable_time) must be. + May not be specified if I(restore_type) is copy-on-write. + type: str + restore_type: + description: + - The type of restore to be performed. If not provided, Amazon RDS uses full-copy. + choices: + - full-copy + - copy-on-write + type: str + role_arn: + description: + - The Amazon Resource Name (ARN) of the IAM role to associate with the Aurora DB cluster, for example + "arn:aws:iam::123456789012:role/AuroraAccessRole" + type: str + s3_bucket_name: + description: + - The name of the Amazon S3 bucket that contains the data used to create the Amazon Aurora DB cluster. + type: str + s3_ingestion_role_arn: + description: + - The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that authorizes Amazon RDS to access + the Amazon S3 bucket on your behalf. + type: str + s3_prefix: + description: + - The prefix for all of the file names that contain the data used to create the Amazon Aurora DB cluster. + - If you do not specify a SourceS3Prefix value, then the Amazon Aurora DB cluster is created by using all of the files in the Amazon S3 bucket. + type: str + skip_final_snapshot: + description: + - Whether a final DB cluster snapshot is created before the DB cluster is deleted. + - If this is C(false), I(final_snapshot_identifier) must be provided. + type: bool + default: false + snapshot_identifier: + description: + - The identifier for the DB snapshot or DB cluster snapshot to restore from. + - You can use either the name or the ARN to specify a DB cluster snapshot. However, you can use only the ARN to specify a DB snapshot. + type: str + source_db_cluster_identifier: + description: + - The identifier of the source DB cluster from which to restore. + type: str + source_engine: + description: + - The identifier for the database engine that was backed up to create the files stored in the Amazon S3 bucket. + choices: + - mysql + type: str + source_engine_version: + description: + - The version of the database that the backup files were created from. + type: str + source_region: + description: + - The ID of the region that contains the source for the DB cluster. + type: str + storage_encrypted: + description: + - Whether the DB cluster is encrypted. + type: bool + tags: + description: + - A dictionary of key value pairs to assign the DB cluster. + type: dict + use_earliest_time_on_point_in_time_unavailable: + description: + - If I(backtrack_to) is set to a timestamp earlier than the earliest backtrack time, this value backtracks the DB cluster to + the earliest possible backtrack time. Otherwise, an error occurs. + type: bool + use_latest_restorable_time: + description: + - Whether to restore the DB cluster to the latest restorable backup time. Only one of I(use_latest_restorable_time) + and I(restore_to_time) may be provided. + type: bool + vpc_security_group_ids: + description: + - A list of EC2 VPC security groups to associate with the DB cluster. + type: list + elements: str +''' + +EXAMPLES = r''' +# Note: These examples do not set authentication details, see the AWS Guide for details. +- name: Create minimal aurora cluster in default VPC and default subnet group + community.aws.rds_cluster: + cluster_id: "{{ cluster_id }}" + engine: "aurora" + password: "{{ password }}" + username: "{{ username }}" + +- name: Add a new security group without purge + community.aws.rds_cluster: + id: "{{ cluster_id }}" + state: present + vpc_security_group_ids: + - sg-0be17ba10c9286b0b + purge_security_groups: false + +- name: Modify password + community.aws.rds_cluster: + id: "{{ cluster_id }}" + state: present + password: "{{ new_password }}" + force_update_password: true + apply_immediately: true + +- name: Rename the cluster + community.aws.rds_cluster: + engine: aurora + password: "{{ password }}" + username: "{{ username }}" + cluster_id: "cluster-{{ resource_prefix }}" + new_cluster_id: "cluster-{{ resource_prefix }}-renamed" + apply_immediately: true + +- name: Delete aurora cluster without creating a final snapshot + community.aws.rds_cluster: + engine: aurora + password: "{{ password }}" + username: "{{ username }}" + cluster_id: "{{ cluster_id }}" + skip_final_snapshot: True + tags: + Name: "cluster-{{ resource_prefix }}" + Created_By: "Ansible_rds_cluster_integration_test" + state: absent + +- name: Restore cluster from source snapshot + community.aws.rds_cluster: + engine: aurora + password: "{{ password }}" + username: "{{ username }}" + cluster_id: "cluster-{{ resource_prefix }}-restored" + snapshot_identifier: "cluster-{{ resource_prefix }}-snapshot" +''' + +RETURN = r''' +activity_stream_status: + description: The status of the database activity stream. + returned: always + type: str + sample: stopped +allocated_storage: + description: + - The allocated storage size in gigabytes. Since aurora storage size is not fixed this is + always 1 for aurora database engines. + returned: always + type: int + sample: 1 +associated_roles: + description: + - A list of dictionaries of the AWS Identity and Access Management (IAM) roles that are associated + with the DB cluster. Each dictionary contains the role_arn and the status of the role. + returned: always + type: list + sample: [] +availability_zones: + description: The list of availability zones that instances in the DB cluster can be created in. + returned: always + type: list + sample: + - us-east-1c + - us-east-1a + - us-east-1e +backup_retention_period: + description: The number of days for which automatic DB snapshots are retained. + returned: always + type: int + sample: 1 +changed: + description: If the RDS cluster has changed. + returned: always + type: bool + sample: true +cluster_create_time: + description: The time in UTC when the DB cluster was created. + returned: always + type: str + sample: '2018-06-29T14:08:58.491000+00:00' +copy_tags_to_snapshot: + description: + - Specifies whether tags are copied from the DB cluster to snapshots of the DB cluster. + returned: always + type: bool + sample: false +cross_account_clone: + description: + - Specifies whether the DB cluster is a clone of a DB cluster owned by a different Amazon Web Services account. + returned: always + type: bool + sample: false +db_cluster_arn: + description: The Amazon Resource Name (ARN) for the DB cluster. + returned: always + type: str + sample: arn:aws:rds:us-east-1:123456789012:cluster:rds-cluster-demo +db_cluster_identifier: + description: The lowercase user-supplied DB cluster identifier. + returned: always + type: str + sample: rds-cluster-demo +db_cluster_members: + description: + - A list of dictionaries containing information about the instances in the cluster. + Each dictionary contains the db_instance_identifier, is_cluster_writer (bool), + db_cluster_parameter_group_status, and promotion_tier (int). + returned: always + type: list + sample: [] +db_cluster_parameter_group: + description: The parameter group associated with the DB cluster. + returned: always + type: str + sample: default.aurora5.6 +db_cluster_resource_id: + description: The AWS Region-unique, immutable identifier for the DB cluster. + returned: always + type: str + sample: cluster-D2MEQDN3BQNXDF74K6DQJTHASU +db_subnet_group: + description: The name of the subnet group associated with the DB Cluster. + returned: always + type: str + sample: default +deletion_protection: + description: + - Indicates if the DB cluster has deletion protection enabled. + The database can't be deleted when deletion protection is enabled. + returned: always + type: bool + sample: false +domain_memberships: + description: + - The Active Directory Domain membership records associated with the DB cluster. + returned: always + type: list + sample: [] +earliest_restorable_time: + description: The earliest time to which a database can be restored with point-in-time restore. + returned: always + type: str + sample: '2018-06-29T14:09:34.797000+00:00' +endpoint: + description: The connection endpoint for the primary instance of the DB cluster. + returned: always + type: str + sample: rds-cluster-demo.cluster-cvlrtwiennww.us-east-1.rds.amazonaws.com +engine: + description: The database engine of the DB cluster. + returned: always + type: str + sample: aurora +engine_mode: + description: The DB engine mode of the DB cluster. + returned: always + type: str + sample: provisioned +engine_version: + description: The database engine version. + returned: always + type: str + sample: 5.6.10a +hosted_zone_id: + description: The ID that Amazon Route 53 assigns when you create a hosted zone. + returned: always + type: str + sample: Z2R2ITUGPM61AM +http_endpoint_enabled: + description: + - A value that indicates whether the HTTP endpoint for an Aurora Serverless DB cluster is enabled. + returned: always + type: bool + sample: false +iam_database_authentication_enabled: + description: Whether IAM accounts may be mapped to database accounts. + returned: always + type: bool + sample: false +latest_restorable_time: + description: The latest time to which a database can be restored with point-in-time restore. + returned: always + type: str + sample: '2018-06-29T14:09:34.797000+00:00' +master_username: + description: The master username for the DB cluster. + returned: always + type: str + sample: username +multi_az: + description: Whether the DB cluster has instances in multiple availability zones. + returned: always + type: bool + sample: false +port: + description: The port that the database engine is listening on. + returned: always + type: int + sample: 3306 +preferred_backup_window: + description: The UTC weekly time range during which system maintenance can occur. + returned: always + type: str + sample: 10:18-10:48 +preferred_maintenance_window: + description: The UTC weekly time range during which system maintenance can occur. + returned: always + type: str + sample: tue:03:23-tue:03:53 +read_replica_identifiers: + description: A list of read replica ID strings associated with the DB cluster. + returned: always + type: list + sample: [] +reader_endpoint: + description: The reader endpoint for the DB cluster. + returned: always + type: str + sample: rds-cluster-demo.cluster-ro-cvlrtwiennww.us-east-1.rds.amazonaws.com +status: + description: The status of the DB cluster. + returned: always + type: str + sample: available +storage_encrypted: + description: Whether the DB cluster is storage encrypted. + returned: always + type: bool + sample: false +tag_list: + description: A list of tags consisting of key-value pairs. + returned: always + type: list + elements: dict + sample: [ + { + "key": "Created_By", + "value": "Ansible_rds_cluster_integration_test" + } + ] +tags: + description: A dictionary of key value pairs. + returned: always + type: dict + sample: { + "Name": "rds-cluster-demo" + } +vpc_security_groups: + description: A list of the DB cluster's security groups and their status. + returned: always + type: complex + contains: + status: + description: Status of the security group. + returned: always + type: str + sample: active + vpc_security_group_id: + description: Security group of the cluster. + returned: always + type: str + sample: sg-12345678 +''' + + +try: + import botocore +except ImportError: + pass # caught by AnsibleAWSModule + +from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict + +from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule +from ansible_collections.amazon.aws.plugins.module_utils.core import is_boto3_error_code +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AWSRetry +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import ansible_dict_to_boto3_tag_list +from ansible_collections.amazon.aws.plugins.module_utils.rds import wait_for_cluster_status +from ansible_collections.amazon.aws.plugins.module_utils.rds import arg_spec_to_rds_params +from ansible_collections.amazon.aws.plugins.module_utils.rds import get_tags +from ansible_collections.amazon.aws.plugins.module_utils.rds import ensure_tags +from ansible_collections.amazon.aws.plugins.module_utils.rds import call_method + + [email protected]_backoff(retries=10) +def _describe_db_clusters(**params): + try: + paginator = client.get_paginator('describe_db_clusters') + return paginator.paginate(**params).build_full_result()['DBClusters'][0] + except is_boto3_error_code('DBClusterNotFoundFault'): + return {} + + +def get_add_role_options(params_dict, cluster): + current_role_arns = [role['RoleArn'] for role in cluster.get('AssociatedRoles', [])] + role = params_dict['RoleArn'] + if role is not None and role not in current_role_arns: + return {'RoleArn': role, 'DBClusterIdentifier': params_dict['DBClusterIdentifier']} + return {} + + +def get_backtrack_options(params_dict): + options = ['BacktrackTo', 'DBClusterIdentifier', 'UseEarliestTimeOnPointInTimeUnavailable'] + if params_dict['BacktrackTo'] is not None: + options = dict((k, params_dict[k]) for k in options if params_dict[k] is not None) + if 'ForceBacktrack' in params_dict: + options['Force'] = params_dict['ForceBacktrack'] + return options + return {} + + +def get_create_options(params_dict): + options = [ + 'AvailabilityZones', 'BacktrackWindow', 'BackupRetentionPeriod', 'PreferredBackupWindow', + 'CharacterSetName', 'DBClusterIdentifier', 'DBClusterParameterGroupName', 'DBSubnetGroupName', + 'DatabaseName', 'EnableCloudwatchLogsExports', 'EnableIAMDatabaseAuthentication', 'KmsKeyId', + 'Engine', 'EngineVersion', 'PreferredMaintenanceWindow', 'MasterUserPassword', 'MasterUsername', + 'OptionGroupName', 'Port', 'ReplicationSourceIdentifier', 'SourceRegion', 'StorageEncrypted', + 'Tags', 'VpcSecurityGroupIds', 'EngineMode', 'ScalingConfiguration', 'DeletionProtection', + 'EnableHttpEndpoint', 'CopyTagsToSnapshot', 'Domain', 'DomainIAMRoleName', + 'EnableGlobalWriteForwarding', + ] + + return dict((k, v) for k, v in params_dict.items() if k in options and v is not None) + + +def get_modify_options(params_dict, force_update_password): + options = [ + 'ApplyImmediately', 'BacktrackWindow', 'BackupRetentionPeriod', 'PreferredBackupWindow', + 'DBClusterIdentifier', 'DBClusterParameterGroupName', 'EnableIAMDatabaseAuthentication', + 'EngineVersion', 'PreferredMaintenanceWindow', 'MasterUserPassword', 'NewDBClusterIdentifier', + 'OptionGroupName', 'Port', 'VpcSecurityGroupIds', 'EnableIAMDatabaseAuthentication', + 'CloudwatchLogsExportConfiguration', 'DeletionProtection', 'EnableHttpEndpoint', + 'CopyTagsToSnapshot', 'EnableGlobalWriteForwarding', 'Domain', 'DomainIAMRoleName', + ] + modify_options = dict((k, v) for k, v in params_dict.items() if k in options and v is not None) + if not force_update_password: + modify_options.pop('MasterUserPassword', None) + return modify_options + + +def get_delete_options(params_dict): + options = ['DBClusterIdentifier', 'FinalSnapshotIdentifier', 'SkipFinalSnapshot'] + return dict((k, params_dict[k]) for k in options if params_dict[k] is not None) + + +def get_restore_s3_options(params_dict): + options = [ + 'AvailabilityZones', 'BacktrackWindow', 'BackupRetentionPeriod', 'CharacterSetName', + 'DBClusterIdentifier', 'DBClusterParameterGroupName', 'DBSubnetGroupName', 'DatabaseName', + 'EnableCloudwatchLogsExports', 'EnableIAMDatabaseAuthentication', 'Engine', 'EngineVersion', + 'KmsKeyId', 'MasterUserPassword', 'MasterUsername', 'OptionGroupName', 'Port', + 'PreferredBackupWindow', 'PreferredMaintenanceWindow', 'S3BucketName', 'S3IngestionRoleArn', + 'S3Prefix', 'SourceEngine', 'SourceEngineVersion', 'StorageEncrypted', 'Tags', + 'VpcSecurityGroupIds', 'DeletionProtection', 'EnableHttpEndpoint', 'CopyTagsToSnapshot', + 'Domain', 'DomainIAMRoleName', + ] + + return dict((k, v) for k, v in params_dict.items() if k in options and v is not None) + + +def get_restore_snapshot_options(params_dict): + options = [ + 'AvailabilityZones', 'BacktrackWindow', 'DBClusterIdentifier', 'DBSubnetGroupName', + 'DatabaseName', 'EnableCloudwatchLogsExports', 'EnableIAMDatabaseAuthentication', + 'Engine', 'EngineVersion', 'KmsKeyId', 'OptionGroupName', 'Port', 'SnapshotIdentifier', + 'Tags', 'VpcSecurityGroupIds', 'DBClusterParameterGroupName', 'DeletionProtection', + 'CopyTagsToSnapshot', 'Domain', 'DomainIAMRoleName', + ] + return dict((k, v) for k, v in params_dict.items() if k in options and v is not None) + + +def get_restore_cluster_options(params_dict): + options = [ + 'BacktrackWindow', 'DBClusterIdentifier', 'DBSubnetGroupName', 'EnableCloudwatchLogsExports', + 'EnableIAMDatabaseAuthentication', 'KmsKeyId', 'OptionGroupName', 'Port', 'RestoreToTime', + 'RestoreType', 'SourceDBClusterIdentifier', 'Tags', 'UseLatestRestorableTime', + 'VpcSecurityGroupIds', 'DeletionProtection', 'CopyTagsToSnapshot', 'Domain', + 'DomainIAMRoleName', + ] + return dict((k, v) for k, v in params_dict.items() if k in options and v is not None) + + +def get_rds_method_attribute_name(cluster): + state = module.params['state'] + creation_source = module.params['creation_source'] + method_name = None + method_options_name = None + + if state == 'absent': + if cluster and cluster['Status'] not in ['deleting', 'deleted']: + method_name = 'delete_db_cluster' + method_options_name = 'get_delete_options' + else: + if cluster: + method_name = 'modify_db_cluster' + method_options_name = 'get_modify_options' + elif creation_source == 'snapshot': + method_name = 'restore_db_cluster_from_db_snapshot' + method_options_name = 'get_restore_snapshot_options' + elif creation_source == 's3': + method_name = 'restore_db_cluster_from_s3' + method_options_name = 'get_restore_s3_options' + elif creation_source == 'cluster': + method_name = 'restore_db_cluster_to_point_in_time' + method_options_name = 'get_restore_cluster_options' + else: + method_name = 'create_db_cluster' + method_options_name = 'get_create_options' + + return method_name, method_options_name + + +def add_role(params): + if not module.check_mode: + try: + client.add_role_to_db_cluster(**params) + except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: + module.fail_json_aws(e, msg=f"Unable to add role {params['RoleArn']} to cluster {params['DBClusterIdentifier']}") + wait_for_cluster_status(client, module, params['DBClusterIdentifier'], 'cluster_available') + + +def backtrack_cluster(params): + if not module.check_mode: + try: + client.backtrack_db_cluster(**params) + except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: + module.fail_json_aws(e, msg=F"Unable to backtrack cluster {params['DBClusterIdentifier']}") + wait_for_cluster_status(client, module, params['DBClusterIdentifier'], 'cluster_available') + + +def get_cluster(db_cluster_id): + try: + return _describe_db_clusters(DBClusterIdentifier=db_cluster_id) + except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: + module.fail_json_aws(e, msg="Failed to describe DB clusters") + + +def changing_cluster_options(modify_params, current_cluster): + changing_params = {} + apply_immediately = modify_params.pop('ApplyImmediately') + db_cluster_id = modify_params.pop('DBClusterIdentifier') + + enable_cloudwatch_logs_export = modify_params.pop('EnableCloudwatchLogsExports', None) + if enable_cloudwatch_logs_export is not None: + desired_cloudwatch_logs_configuration = {'EnableLogTypes': [], 'DisableLogTypes': []} + provided_cloudwatch_logs = set(enable_cloudwatch_logs_export) + current_cloudwatch_logs_export = set(current_cluster['EnabledCloudwatchLogsExports']) + + desired_cloudwatch_logs_configuration['EnableLogTypes'] = list(provided_cloudwatch_logs.difference(current_cloudwatch_logs_export)) + if module.params['purge_cloudwatch_logs_exports']: + desired_cloudwatch_logs_configuration['DisableLogTypes'] = list(current_cloudwatch_logs_export.difference(provided_cloudwatch_logs)) + changing_params['CloudwatchLogsExportConfiguration'] = desired_cloudwatch_logs_configuration + + password = modify_params.pop('MasterUserPassword', None) + if password: + changing_params['MasterUserPassword'] = password + + new_cluster_id = modify_params.pop('NewDBClusterIdentifier', None) + if new_cluster_id and new_cluster_id != current_cluster['DBClusterIdentifier']: + changing_params['NewDBClusterIdentifier'] = new_cluster_id + + option_group = modify_params.pop('OptionGroupName', None) + if ( + option_group and option_group not in [g['DBClusterOptionGroupName'] for g in current_cluster['DBClusterOptionGroupMemberships']] + ): + changing_params['OptionGroupName'] = option_group + + vpc_sgs = modify_params.pop('VpcSecurityGroupIds', None) + if vpc_sgs: + desired_vpc_sgs = [] + provided_vpc_sgs = set(vpc_sgs) + current_vpc_sgs = set([sg['VpcSecurityGroupId'] for sg in current_cluster['VpcSecurityGroups']]) + if module.params['purge_security_groups']: + desired_vpc_sgs = vpc_sgs + else: + if provided_vpc_sgs - current_vpc_sgs: + desired_vpc_sgs = list(provided_vpc_sgs | current_vpc_sgs) + + if desired_vpc_sgs: + changing_params['VpcSecurityGroupIds'] = desired_vpc_sgs + + for param in modify_params: + if modify_params[param] != current_cluster[param]: + changing_params[param] = modify_params[param] + + if changing_params: + changing_params['DBClusterIdentifier'] = db_cluster_id + if apply_immediately is not None: + changing_params['ApplyImmediately'] = apply_immediately + + return changing_params + + +def ensure_present(cluster, parameters, method_name, method_options_name): + changed = False + + if not cluster: + if parameters.get('Tags') is not None: + parameters['Tags'] = ansible_dict_to_boto3_tag_list(parameters['Tags']) + call_method(client, module, method_name, eval(method_options_name)(parameters)) + changed = True + else: + if get_backtrack_options(parameters): + backtrack_cluster(client, module, get_backtrack_options(parameters)) + changed = True + else: + modifiable_options = eval(method_options_name)(parameters, + force_update_password=module.params['force_update_password']) + modify_options = changing_cluster_options(modifiable_options, cluster) + if modify_options: + call_method(client, module, method_name, modify_options) + changed = True + if module.params['tags'] is not None: + existing_tags = get_tags(client, module, cluster['DBClusterArn']) + changed |= ensure_tags(client, module, cluster['DBClusterArn'], existing_tags, module.params['tags'], + module.params['purge_tags']) + + add_role_params = get_add_role_options(parameters, cluster) + if add_role_params: + add_role(client, module, add_role_params) + changed = True + + if module.params['promote'] and cluster.get('ReplicationSourceIdentifier'): + call_method(client, module, 'promote_read_replica_db_cluster', parameters={'DBClusterIdentifier': module.params['db_cluster_identifier']}) + changed = True + + return changed + + +def main(): + global module + global client + + arg_spec = dict( + state=dict(choices=['present', 'absent'], default='present'), + creation_source=dict(type='str', choices=['snapshot', 's3', 'cluster']), + force_update_password=dict(type='bool', default=False), + promote=dict(type='bool', default=False), + purge_cloudwatch_logs_exports=dict(type='bool', default=True), + purge_tags=dict(type='bool', default=True), + wait=dict(type='bool', default=True), + purge_security_groups=dict(type='bool', default=True), + ) + + parameter_options = dict( + apply_immediately=dict(type='bool', default=False), + availability_zones=dict(type='list', elements='str', aliases=['zones', 'az']), + backtrack_to=dict(), + backtrack_window=dict(type='int'), + backup_retention_period=dict(type='int', default=1), + character_set_name=dict(), + database_name=dict(aliases=['db_name']), + db_cluster_identifier=dict(required=True, aliases=['cluster_id', 'id', 'cluster_name']), + db_cluster_parameter_group_name=dict(), + db_subnet_group_name=dict(), + enable_cloudwatch_logs_exports=dict(type='list', elements='str'), + deletion_protection=dict(type='bool'), + global_cluster_identifier=dict(), + enable_http_endpoint=dict(type='bool'), + copy_tags_to_snapshot=dict(type='bool'), + domain=dict(), + domain_iam_role_name=dict(), + enable_global_write_forwarding=dict(type='bool'), + enable_iam_database_authentication=dict(type='bool'), + engine=dict(choices=["aurora", "aurora-mysql", "aurora-postgresql"]), + engine_version=dict(), + final_snapshot_identifier=dict(), + force_backtrack=dict(type='bool'), + kms_key_id=dict(), + master_user_password=dict(aliases=['password'], no_log=True), + master_username=dict(aliases=['username']), + new_db_cluster_identifier=dict(aliases=['new_cluster_id', 'new_id', 'new_cluster_name']), + option_group_name=dict(), + port=dict(type='int'), + preferred_backup_window=dict(aliases=['backup_window']), + preferred_maintenance_window=dict(aliases=['maintenance_window']), + replication_source_identifier=dict(aliases=['replication_src_id']), + restore_to_time=dict(), + restore_type=dict(choices=['full-copy', 'copy-on-write']), + role_arn=dict(), + s3_bucket_name=dict(), + s3_ingestion_role_arn=dict(), + s3_prefix=dict(), + skip_final_snapshot=dict(type='bool', default=False), + snapshot_identifier=dict(), + source_db_cluster_identifier=dict(), + source_engine=dict(choices=['mysql']), + source_engine_version=dict(), + source_region=dict(), + storage_encrypted=dict(type='bool'), + tags=dict(type='dict'), + use_earliest_time_on_point_in_time_unavailable=dict(type='bool'), + use_latest_restorable_time=dict(type='bool'), + vpc_security_group_ids=dict(type='list', elements='str'), + ) + arg_spec.update(parameter_options) + + module = AnsibleAWSModule( + argument_spec=arg_spec, + required_if=[ + ('creation_source', 'snapshot', ('snapshot_identifier', 'engine')), + ('creation_source', 's3', ( + 's3_bucket_name', 'engine', 'master_username', 'master_user_password', + 'source_engine', 'source_engine_version', 's3_ingestion_role_arn')), + ], + mutually_exclusive=[ + ('s3_bucket_name', 'source_db_cluster_identifier', 'snapshot_identifier'), + ('use_latest_restorable_time', 'restore_to_time'), + ], + supports_check_mode=True + ) + + retry_decorator = AWSRetry.jittered_backoff(retries=10) + + try: + client = module.client('rds', retry_decorator=retry_decorator) + except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: + module.fail_json_aws(e, msg='Failed to connect to AWS.') + + module.params['db_cluster_identifier'] = module.params['db_cluster_identifier'].lower() + cluster = get_cluster(module.params['db_cluster_identifier']) + + if module.params['new_db_cluster_identifier']: + module.params['new_db_cluster_identifier'] = module.params['new_db_cluster_identifier'].lower() + + if get_cluster(module.params['new_db_cluster_identifier']): + module.fail_json(f"A new cluster ID {module.params['new_db_cluster_identifier']} was provided but it already exists") + if not cluster: + module.fail_json(f"A new cluster ID {module.params['new_db_cluster_identifier']} was provided but the cluster to be renamed does not exist") + + if ( + module.params['state'] == 'absent' and module.params['skip_final_snapshot'] is False and + module.params['final_snapshot_identifier'] is None + ): + module.fail_json(msg='skip_final_snapshot is False but all of the following are missing: final_snapshot_identifier') + + parameters = arg_spec_to_rds_params(dict((k, module.params[k]) for k in module.params if k in parameter_options)) + + changed = False + method_name, method_options_name = get_rds_method_attribute_name(cluster) + + if method_name: + if method_name == 'delete_db_cluster': + call_method(client, module, method_name, eval(method_options_name)(parameters)) + changed = True + else: + changed |= ensure_present(cluster, parameters, method_name, method_options_name) + + if not module.check_mode and module.params['new_db_cluster_identifier'] and module.params['apply_immediately']: + cluster_id = module.params['new_db_cluster_identifier'] + else: + cluster_id = module.params['db_cluster_identifier'] + + result = camel_dict_to_snake_dict(get_cluster(cluster_id)) + + if result: + result['tags'] = get_tags(client, module, result['db_cluster_arn']) + + module.exit_json(changed=changed, **result) + + +if __name__ == '__main__': + main() diff --git a/plugins/modules/rds_cluster_info.py b/plugins/modules/rds_cluster_info.py new file mode 100644 --- /dev/null +++ b/plugins/modules/rds_cluster_info.py @@ -0,0 +1,307 @@ +#!/usr/bin/python +# Copyright (c) 2022 Ansible Project +# Copyright (c) 2022 Alina Buzachis (@alinabuzachis) +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + +DOCUMENTATION = r''' +module: rds_cluster_info +version_added: 3.2.0 +short_description: Obtain information about one or more RDS clusters +description: + - Obtain information about one or more RDS clusters. +options: + db_cluster_identifier: + description: + - The user-supplied DB cluster identifier. + - If this parameter is specified, information from only the specific DB cluster is returned. + aliases: + - cluster_id + - id + - cluster_name + type: str + filters: + description: + - A filter that specifies one or more DB clusters to describe. + See U(https://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_DescribeDBClusters.html). + type: dict +author: + - Alina Buzachis (@alinabuzachis) +extends_documentation_fragment: +- amazon.aws.aws +- amazon.aws.ec2 + +''' + +EXAMPLES = r''' +- name: Get info of all existing DB clusters + community.aws.rds_cluster_info: + register: _result_cluster_info + +- name: Get info on a specific DB cluster + community.aws.rds_cluster_info: + cluster_id: "{{ cluster_id }}" + register: _result_cluster_info + +- name: Get info all DB clusters with specific engine + community.aws.rds_cluster_info: + engine: "aurora" + register: _result_cluster_info +''' + +RETURN = r''' +clusters: + description: List of RDS clusters. + returned: always + type: list + contains: + activity_stream_status: + description: The status of the database activity stream. + type: str + sample: stopped + allocated_storage: + description: + - The allocated storage size in gigabytes. Since aurora storage size is not fixed this is + always 1 for aurora database engines. + type: int + sample: 1 + associated_roles: + description: + - A list of dictionaries of the AWS Identity and Access Management (IAM) roles that are associated + with the DB cluster. Each dictionary contains the role_arn and the status of the role. + type: list + sample: [] + availability_zones: + description: The list of availability zones that instances in the DB cluster can be created in. + type: list + sample: + - us-east-1c + - us-east-1a + - us-east-1e + backup_retention_period: + description: The number of days for which automatic DB snapshots are retained. + type: int + sample: 1 + cluster_create_time: + description: The time in UTC when the DB cluster was created. + type: str + sample: '2018-06-29T14:08:58.491000+00:00' + copy_tags_to_snapshot: + description: + - Specifies whether tags are copied from the DB cluster to snapshots of the DB cluster. + type: bool + sample: false + cross_account_clone: + description: + - Specifies whether the DB cluster is a clone of a DB cluster owned by a different Amazon Web Services account. + type: bool + sample: false + db_cluster_arn: + description: The Amazon Resource Name (ARN) for the DB cluster. + type: str + sample: arn:aws:rds:us-east-1:123456789012:cluster:rds-cluster-demo + db_cluster_identifier: + description: The lowercase user-supplied DB cluster identifier. + type: str + sample: rds-cluster-demo + db_cluster_members: + description: + - A list of dictionaries containing information about the instances in the cluster. + Each dictionary contains the I(db_instance_identifier), I(is_cluster_writer) (bool), + I(db_cluster_parameter_group_status), and I(promotion_tier) (int). + type: list + sample: [] + db_cluster_parameter_group: + description: The parameter group associated with the DB cluster. + type: str + sample: default.aurora5.6 + db_cluster_resource_id: + description: The AWS Region-unique, immutable identifier for the DB cluster. + type: str + sample: cluster-D2MEQDN3BQNXDF74K6DQJTHASU + db_subnet_group: + description: The name of the subnet group associated with the DB Cluster. + type: str + sample: default + deletion_protection: + description: + - Indicates if the DB cluster has deletion protection enabled. + The database can't be deleted when deletion protection is enabled. + type: bool + sample: false + domain_memberships: + description: + - The Active Directory Domain membership records associated with the DB cluster. + type: list + sample: [] + earliest_restorable_time: + description: The earliest time to which a database can be restored with point-in-time restore. + type: str + sample: '2018-06-29T14:09:34.797000+00:00' + endpoint: + description: The connection endpoint for the primary instance of the DB cluster. + type: str + sample: rds-cluster-demo.cluster-cvlrtwiennww.us-east-1.rds.amazonaws.com + engine: + description: The database engine of the DB cluster. + type: str + sample: aurora + engine_mode: + description: The DB engine mode of the DB cluster. + type: str + sample: provisioned + engine_version: + description: The database engine version. + type: str + sample: 5.6.10a + hosted_zone_id: + description: The ID that Amazon Route 53 assigns when you create a hosted zone. + type: str + sample: Z2R2ITUGPM61AM + http_endpoint_enabled: + description: + - A value that indicates whether the HTTP endpoint for an Aurora Serverless DB cluster is enabled. + type: bool + sample: false + iam_database_authentication_enabled: + description: Whether IAM accounts may be mapped to database accounts. + type: bool + sample: false + latest_restorable_time: + description: The latest time to which a database can be restored with point-in-time restore. + type: str + sample: '2018-06-29T14:09:34.797000+00:00' + master_username: + description: The master username for the DB cluster. + type: str + sample: username + multi_az: + description: Whether the DB cluster has instances in multiple availability zones. + type: bool + sample: false + port: + description: The port that the database engine is listening on. + type: int + sample: 3306 + preferred_backup_window: + description: The UTC weekly time range during which system maintenance can occur. + type: str + sample: 10:18-10:48 + preferred_maintenance_window: + description: The UTC weekly time range during which system maintenance can occur. + type: str + sample: tue:03:23-tue:03:53 + read_replica_identifiers: + description: A list of read replica ID strings associated with the DB cluster. + type: list + sample: [] + reader_endpoint: + description: The reader endpoint for the DB cluster. + type: str + sample: rds-cluster-demo.cluster-ro-cvlrtwiennww.us-east-1.rds.amazonaws.com + status: + description: The status of the DB cluster. + type: str + sample: available + storage_encrypted: + description: Whether the DB cluster is storage encrypted. + type: bool + sample: false + tag_list: + description: A list of tags consisting of key-value pairs. + type: list + elements: dict + sample: [ + { + "key": "Created_By", + "value": "Ansible_rds_cluster_integration_test" + } + ] + tags: + description: A dictionary of key value pairs. + type: dict + sample: { + "Name": "rds-cluster-demo" + } + vpc_security_groups: + description: A list of the DB cluster's security groups and their status. + type: complex + contains: + status: + description: Status of the security group. + type: str + sample: active + vpc_security_group_id: + description: Security group of the cluster. + type: str + sample: sg-12345678 +''' + + +try: + import botocore +except ImportError: + pass # handled by AnsibleAWSModule + +from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule +from ansible_collections.amazon.aws.plugins.module_utils.core import is_boto3_error_code +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import ansible_dict_to_boto3_filter_list +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AWSRetry +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import camel_dict_to_snake_dict +from ansible_collections.amazon.aws.plugins.module_utils.rds import get_tags + + [email protected]_backoff(retries=10) +def _describe_db_clusters(client, **params): + try: + paginator = client.get_paginator('describe_db_clusters') + return paginator.paginate(**params).build_full_result()['DBClusters'] + except is_boto3_error_code('DBClusterNotFoundFault'): + return [] + + +def cluster_info(client, module): + cluster_id = module.params.get('db_cluster_identifier') + filters = module.params.get('filters') + + params = dict() + if cluster_id: + params['DBClusterIdentifier'] = cluster_id + if filters: + params['Filters'] = ansible_dict_to_boto3_filter_list(filters) + + try: + result = _describe_db_clusters(client, **params) + except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: + module.fail_json_aws(e, "Couldn't get RDS cluster information.") + + for cluster in result: + cluster['Tags'] = get_tags(client, module, cluster['DBClusterArn']) + + return dict(changed=False, clusters=[camel_dict_to_snake_dict(cluster, ignore_list=['Tags']) for cluster in result]) + + +def main(): + argument_spec = dict( + db_cluster_identifier=dict(aliases=['cluster_id', 'id', 'cluster_name']), + filters=dict(type='dict'), + ) + + module = AnsibleAWSModule( + argument_spec=argument_spec, + supports_check_mode=True, + ) + + try: + client = module.client('rds', retry_decorator=AWSRetry.jittered_backoff(retries=10)) + except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: + module.fail_json_aws(e, msg='Failed to connect to AWS.') + + module.exit_json(**cluster_info(client, module)) + + +if __name__ == '__main__': + main()
diff --git a/tests/integration/targets/rds_cluster/aliases b/tests/integration/targets/rds_cluster/aliases new file mode 100644 --- /dev/null +++ b/tests/integration/targets/rds_cluster/aliases @@ -0,0 +1,3 @@ +cloud/aws + +rds_cluster_info diff --git a/tests/integration/targets/rds_cluster/inventory b/tests/integration/targets/rds_cluster/inventory new file mode 100644 --- /dev/null +++ b/tests/integration/targets/rds_cluster/inventory @@ -0,0 +1,23 @@ +[tests] +# basic rds_cluster cretion tests +create + +# restore cluster tests +restore + +# TODO: Cannot be tested in the CI because: +# An error occurred (InvalidParameterValue) when calling the CreateDBCluster operation: Replication from cluster in same region is not supported +# promote + +# security groups db tests +create_sgs + +# basic modify operations applied on the rds cluster +modify + +# tag rds cluster test +tag + +[all:vars] +ansible_connection=local +ansible_python_interpreter="{{ ansible_playbook_python }}" diff --git a/tests/integration/targets/rds_cluster/main.yml b/tests/integration/targets/rds_cluster/main.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/rds_cluster/main.yml @@ -0,0 +1,11 @@ +--- +# Beware: most of our tests here are run in parallel. +# To add new tests you'll need to add a new host to the inventory and a matching +# '{{ inventory_hostname }}'.yml file in roles/rds_cluster/tasks/ + +- hosts: all + gather_facts: no + strategy: free + serial: 6 + roles: + - rds_cluster diff --git a/tests/integration/targets/rds_cluster/roles/rds_cluster/defaults/main.yml b/tests/integration/targets/rds_cluster/roles/rds_cluster/defaults/main.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/rds_cluster/roles/rds_cluster/defaults/main.yml @@ -0,0 +1,36 @@ +--- +# defaults file for rds_cluster + +# Create cluster +cluster_id: "ansible-test-{{ inventory_hostname | replace('_','-') }}{{ tiny_prefix }}" +username: 'testrdsusername' +password: 'test-rds_password' +engine: 'aurora' +port: 3306 +tags_create: + Name: 'ansible-test-cluster-{{ tiny_prefix }}' + Created_By: "Ansible_rds_cluster_integration_test" + +# Modify cluster +new_cluster_id: 'ansible-test-cluster-{{ tiny_prefix }}-new' +new_port: 1155 +new_password: 'test-rds_password-new' + +# Tag cluster +tags_patch: + Name: "{{ tiny_prefix }}-new" + Created_by: Ansible rds_cluster integration tests + +# Create cluster in a VPC +vpc_name: 'ansible-test-vpc-{{ tiny_prefix }}' +vpc_cidr: '10.{{ 256 | random(seed=tiny_prefix) }}.0.0/16' +subnets: + - {'cidr': '10.{{ 256 | random(seed=tiny_prefix) }}.1.0/24', 'zone': '{{ aws_region }}a'} + - {'cidr': '10.{{ 256 | random(seed=tiny_prefix) }}.2.0/24', 'zone': '{{ aws_region }}b'} + - {'cidr': '10.{{ 256 | random(seed=tiny_prefix) }}.3.0/24', 'zone': '{{ aws_region }}c'} + - {'cidr': '10.{{ 256 | random(seed=tiny_prefix) }}.4.0/24', 'zone': '{{ aws_region }}d'} + +security_groups: + - '{{ tiny_prefix }}-sg-1' + - '{{ tiny_prefix }}-sg-2' + - '{{ tiny_prefix }}-sg-3' diff --git a/tests/integration/targets/rds_cluster/roles/rds_cluster/meta/main.yml b/tests/integration/targets/rds_cluster/roles/rds_cluster/meta/main.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/rds_cluster/roles/rds_cluster/meta/main.yml @@ -0,0 +1 @@ +--- \ No newline at end of file diff --git a/tests/integration/targets/rds_cluster/roles/rds_cluster/tasks/main.yml b/tests/integration/targets/rds_cluster/roles/rds_cluster/tasks/main.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/rds_cluster/roles/rds_cluster/tasks/main.yml @@ -0,0 +1,15 @@ +--- +- name: 'rds_cluster integration tests' + module_defaults: + group/aws: + region: "{{ aws_region }}" + aws_access_key: "{{ aws_access_key }}" + aws_secret_key: "{{ aws_secret_key }}" + security_token: "{{ security_token | default(omit) }}" + + collections: + - community.aws + - amazon.aws + + block: + - include: './test_{{ inventory_hostname }}.yml' diff --git a/tests/integration/targets/rds_cluster/roles/rds_cluster/tasks/test_create.yml b/tests/integration/targets/rds_cluster/roles/rds_cluster/tasks/test_create.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/rds_cluster/roles/rds_cluster/tasks/test_create.yml @@ -0,0 +1,122 @@ +--- +- block: + - name: Ensure the resource doesn't exist + rds_cluster: + id: "{{ cluster_id }}" + state: absent + engine: "{{ engine}}" + username: "{{ username }}" + password: "{{ password }}" + skip_final_snapshot: True + register: _result_delete_db_cluster + + - assert: + that: + - not _result_delete_db_cluster.changed + ignore_errors: yes + + - name: Get info of all existing clusters + rds_cluster_info: + register: _result_cluster_info + + - assert: + that: + - _result_cluster_info is successful + + - name: Create minimal aurora cluster in default VPC and default subnet group (CHECK MODE) + rds_cluster: + engine: "{{ engine }}" + username: "{{ username }}" + password: "{{ password }}" + cluster_id: "{{ cluster_id }}" + tags: "{{ tags_create }}" + register: _result_create_db_cluster + check_mode: true + + - assert: + that: + - _result_create_db_cluster.changed + + - name: Create minimal aurora cluster in default VPC and default subnet group + rds_cluster: + engine: "{{ engine }}" + username: "{{ username }}" + password: "{{ password }}" + cluster_id: "{{ cluster_id }}" + tags: "{{ tags_create }}" + register: _result_create_db_cluster + + - assert: + that: + - _result_create_db_cluster.changed + - "'allocated_storage' in _result_create_db_cluster" + - _result_create_db_cluster.allocated_storage == 1 + - "'cluster_create_time' in _result_create_db_cluster" + - _result_create_db_cluster.copy_tags_to_snapshot == false + - "'db_cluster_arn' in _result_create_db_cluster" + - "'db_cluster_identifier' in _result_create_db_cluster" + - _result_create_db_cluster.db_cluster_identifier == "{{ cluster_id }}" + - "'db_cluster_parameter_group' in _result_create_db_cluster" + - "'db_cluster_resource_id' in _result_create_db_cluster" + - "'endpoint' in _result_create_db_cluster" + - "'engine' in _result_create_db_cluster" + - _result_create_db_cluster.engine == "{{ engine }}" + - "'engine_mode' in _result_create_db_cluster" + - _result_create_db_cluster.engine_mode == "provisioned" + - "'engine_version' in _result_create_db_cluster" + - "'master_username' in _result_create_db_cluster" + - _result_create_db_cluster.master_username == "{{ username }}" + - "'port' in _result_create_db_cluster" + - "_result_create_db_cluster.port == {{ port }}" + - "'status' in _result_create_db_cluster" + - _result_create_db_cluster.status == 'available' + - _result_create_db_cluster.storage_encrypted == false + - "'tags' in _result_create_db_cluster" + - _result_create_db_cluster.tags | length == 2 + - _result_create_db_cluster.tags["Created_By"] == "{{ tags_create["Created_By"]}}" + - _result_create_db_cluster.tags["Name"] == "{{ tags_create["Name"]}}" + - "'vpc_security_groups' in _result_create_db_cluster" + + - name: Get info of the existing cluster + rds_cluster_info: + cluster_id: "{{ cluster_id }}" + register: result_cluster_info + + - assert: + that: + - result_cluster_info is successful + + - name: Create minimal aurora cluster in default VPC and default subnet group - idempotence (CHECK MODE) + rds_cluster: + engine: "{{ engine }}" + username: "{{ username }}" + password: "{{ password }}" + cluster_id: "{{ cluster_id }}" + tags: "{{ tags_create }}" + register: _result_create_db_cluster + check_mode: true + + - assert: + that: + - not _result_create_db_cluster.changed + + - name: Create minimal aurora cluster in default VPC and default subnet group - idempotence + rds_cluster: + engine: "{{ engine }}" + username: "{{ username }}" + password: "{{ password }}" + cluster_id: "{{ cluster_id }}" + tags: "{{ tags_create }}" + register: _result_create_db_cluster + + - assert: + that: + - not _result_create_db_cluster.changed + + always: + - name: Delete DB cluster without creating a final snapshot + rds_cluster: + state: absent + cluster_id: "{{ cluster_id }}" + skip_final_snapshot: True + ignore_errors: true diff --git a/tests/integration/targets/rds_cluster/roles/rds_cluster/tasks/test_create_sgs.yml b/tests/integration/targets/rds_cluster/roles/rds_cluster/tasks/test_create_sgs.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/rds_cluster/roles/rds_cluster/tasks/test_create_sgs.yml @@ -0,0 +1,206 @@ +--- +- block: + - name: Ensure the resource doesn't exist + rds_cluster: + id: "{{ cluster_id }}" + state: absent + engine: "{{ engine}}" + username: "{{ username }}" + password: "{{ password }}" + skip_final_snapshot: True + register: _result_delete_db_cluster + + - assert: + that: + - not _result_delete_db_cluster.changed + ignore_errors: yes + + - name: Create a VPC + ec2_vpc_net: + name: "{{ vpc_name }}" + state: present + cidr_block: "{{ vpc_cidr }}" + tags: + Name: "{{ vpc_name }}" + Description: "Created by rds_cluster integration tests" + register: _result_create_vpc + + - name: Create subnets + ec2_vpc_subnet: + cidr: "{{ item.cidr }}" + az: "{{ item.zone }}" + vpc_id: "{{ _result_create_vpc.vpc.id }}" + tags: + Name: "{{ resource_prefix }}-subnet" + Description: "created by rds_cluster integration tests" + state: present + register: _result_create_subnet + loop: "{{ subnets }}" + + - name: Create security groups + ec2_group: + name: "{{ item }}" + description: "Created by rds_cluster integration tests" + state: present + register: _result_create_sg + loop: "{{ security_groups }}" + + - name: Create an RDS cluster in the VPC with two security groups + rds_cluster: + id: "{{ cluster_id }}" + engine: "{{ engine }}" + username: "{{ username }}" + password: "{{ password }}" + vpc_security_group_ids: + - "{{ _result_create_sg.results.0.group_id }}" + - "{{ _result_create_sg.results.1.group_id }}" + register: _result_create_db_cluster + + - assert: + that: + - _result_create_db_cluster.changed + - "'allocated_storage' in _result_create_db_cluster" + - _result_create_db_cluster.allocated_storage == 1 + - "'cluster_create_time' in _result_create_db_cluster" + - _result_create_db_cluster.copy_tags_to_snapshot == false + - "'db_cluster_arn' in _result_create_db_cluster" + - "'db_cluster_identifier' in _result_create_db_cluster" + - _result_create_db_cluster.db_cluster_identifier == "{{ cluster_id }}" + - "'db_cluster_parameter_group' in _result_create_db_cluster" + - "'db_cluster_resource_id' in _result_create_db_cluster" + - "'endpoint' in _result_create_db_cluster" + - "'engine' in _result_create_db_cluster" + - _result_create_db_cluster.engine == "{{ engine }}" + - "'engine_mode' in _result_create_db_cluster" + - _result_create_db_cluster.engine_mode == "provisioned" + - "'engine_version' in _result_create_db_cluster" + - "'master_username' in _result_create_db_cluster" + - _result_create_db_cluster.master_username == "{{ username }}" + - "'port' in _result_create_db_cluster" + - "_result_create_db_cluster.port == {{ port }}" + - "'status' in _result_create_db_cluster" + - _result_create_db_cluster.status == 'available' + - _result_create_db_cluster.storage_encrypted == false + - "'tags' in _result_create_db_cluster" + - "'vpc_security_groups' in _result_create_db_cluster" + - "_result_create_db_cluster.vpc_security_groups | selectattr('status', 'in', ['active', 'adding']) | list | length == 2" + + - name: Add a new security group without purge (check_mode) + rds_cluster: + id: "{{ cluster_id }}" + state: present + vpc_security_group_ids: + - "{{ _result_create_sg.results.2.group_id }}" + apply_immediately: true + purge_security_groups: false + check_mode: true + register: _result_create_db_cluster + + - assert: + that: + - _result_create_db_cluster.changed + + - name: Add a new security group without purge + rds_cluster: + id: "{{ cluster_id }}" + state: present + vpc_security_group_ids: + - "{{ _result_create_sg.results.2.group_id }}" + apply_immediately: true + purge_security_groups: false + register: _result_create_db_cluster + + - assert: + that: + - _result_create_db_cluster.changed + - "'allocated_storage' in _result_create_db_cluster" + - _result_create_db_cluster.allocated_storage == 1 + - "'cluster_create_time' in _result_create_db_cluster" + - _result_create_db_cluster.copy_tags_to_snapshot == false + - "'db_cluster_arn' in _result_create_db_cluster" + - "'db_cluster_identifier' in _result_create_db_cluster" + - _result_create_db_cluster.db_cluster_identifier == "{{ cluster_id }}" + - "'db_cluster_parameter_group' in _result_create_db_cluster" + - "'db_cluster_resource_id' in _result_create_db_cluster" + - "'endpoint' in _result_create_db_cluster" + - "'engine' in _result_create_db_cluster" + - _result_create_db_cluster.engine == "{{ engine }}" + - "'engine_mode' in _result_create_db_cluster" + - _result_create_db_cluster.engine_mode == "provisioned" + - "'engine_version' in _result_create_db_cluster" + - "'master_username' in _result_create_db_cluster" + - _result_create_db_cluster.master_username == "{{ username }}" + - "'port' in _result_create_db_cluster" + - "_result_create_db_cluster.port == {{ port }}" + - "'status' in _result_create_db_cluster" + - _result_create_db_cluster.status == 'available' + - _result_create_db_cluster.storage_encrypted == false + - "'tags' in _result_create_db_cluster" + - "'vpc_security_groups' in _result_create_db_cluster" + - "_result_create_db_cluster.vpc_security_groups | selectattr('status', 'in', ['active', 'adding']) | list | length == 3" + + - name: Add a new security group without purge (test idempotence) + rds_cluster: + id: "{{ cluster_id }}" + state: present + vpc_security_group_ids: + - "{{ _result_create_sg.results.2.group_id }}" + apply_immediately: true + purge_security_groups: false + register: _result_create_db_cluster + + - assert: + that: + - not _result_create_db_cluster.changed + + - name: Add a security group with purge + rds_cluster: + id: "{{ cluster_id }}" + state: present + vpc_security_group_ids: + - "{{ _result_create_sg .results.2.group_id }}" + apply_immediately: true + register: _result_create_db_cluster + + - assert: + that: + - _result_create_db_cluster.changed + - "_result_create_db_cluster.db_cluster_identifier == '{{ cluster_id }}'" + - "_result_create_db_cluster.vpc_security_groups | selectattr('status', 'in', ['active', 'adding']) | list | length == 1" + + always: + - name: Delete DB cluster without creating a final snapshot + rds_cluster: + state: absent + cluster_id: "{{ cluster_id }}" + skip_final_snapshot: True + ignore_errors: true + + - name: Remove security groups + ec2_group: + name: "{{ item }}" + description: "created by rds_cluster integration tests" + state: absent + loop: "{{ security_groups }}" + + - name: Remove subnets + ec2_vpc_subnet: + cidr: "{{ item.cidr }}" + az: "{{ item.zone }}" + vpc_id: "{{ _result_create_vpc.vpc.id }}" + tags: + Name: "{{ resource_prefix }}-subnet" + Description: "Created by rds_cluster integration tests" + state: absent + ignore_errors: yes + loop: "{{ subnets }}" + + - name: Delete VPC + ec2_vpc_net: + name: "{{ vpc_name }}" + state: absent + cidr_block: "{{ vpc_cidr }}" + tags: + Name: "{{ vpc_name }}" + Description: "Created by rds_cluster integration tests" + ignore_errors: yes diff --git a/tests/integration/targets/rds_cluster/roles/rds_cluster/tasks/test_modify.yml b/tests/integration/targets/rds_cluster/roles/rds_cluster/tasks/test_modify.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/rds_cluster/roles/rds_cluster/tasks/test_modify.yml @@ -0,0 +1,197 @@ +--- +- block: + - name: Ensure the resource doesn't exist + rds_cluster: + id: "{{ cluster_id }}" + state: absent + engine: "{{ engine}}" + username: "{{ username }}" + password: "{{ password }}" + skip_final_snapshot: True + register: _result_delete_db_cluster + + - assert: + that: + - not _result_delete_db_cluster.changed + ignore_errors: yes + + - name: Create a DB cluster + rds_cluster: + id: "{{ cluster_id }}" + state: present + engine: "{{ engine}}" + username: "{{ username }}" + password: "{{ password }}" + register: _result_create_source_db_cluster + + - assert: + that: + - _result_create_source_db_cluster.changed + - _result_create_source_db_cluster.changed + - "'allocated_storage' in _result_create_source_db_cluster" + - _result_create_source_db_cluster.allocated_storage == 1 + - "'cluster_create_time' in _result_create_source_db_cluster" + - _result_create_source_db_cluster.copy_tags_to_snapshot == false + - "'db_cluster_arn' in _result_create_source_db_cluster" + - "_result_create_source_db_cluster.db_cluster_identifier == '{{ cluster_id }}'" + - "'db_cluster_parameter_group' in _result_create_source_db_cluster" + - "'db_cluster_resource_id' in _result_create_source_db_cluster" + - "'endpoint' in _result_create_source_db_cluster" + - "'engine' in _result_create_source_db_cluster" + - _result_create_source_db_cluster.engine == "{{ engine }}" + - "'engine_mode' in _result_create_source_db_cluster" + - _result_create_source_db_cluster.engine_mode == "provisioned" + - "'engine_version' in _result_create_source_db_cluster" + - "'master_username' in _result_create_source_db_cluster" + - _result_create_source_db_cluster.master_username == "{{ username }}" + - "'port' in _result_create_source_db_cluster" + - "_result_create_source_db_cluster.port == {{ port }}" + - "'status' in _result_create_source_db_cluster" + - _result_create_source_db_cluster.status == "available" + - "'tags' in _result_create_source_db_cluster" + - "'vpc_security_groups' in _result_create_source_db_cluster" + + - name: Modify DB cluster password + rds_cluster: + id: "{{ cluster_id }}" + state: present + password: "{{ new_password }}" + force_update_password: True + apply_immediately: True + register: _result_modify_password + + - assert: + that: + - _result_modify_password.changed + - "'allocated_storage' in _result_modify_password" + - _result_modify_password.allocated_storage == 1 + - "'cluster_create_time' in _result_modify_password" + - _result_modify_password.copy_tags_to_snapshot == false + - "'db_cluster_arn' in _result_modify_password" + - "_result_modify_password.db_cluster_identifier == '{{ cluster_id }}'" + - "'db_cluster_parameter_group' in _result_modify_password" + - "'db_cluster_resource_id' in _result_modify_password" + - "'endpoint' in _result_modify_password" + - "'engine' in _result_modify_password" + - _result_modify_password.engine == "{{ engine }}" + - "'engine_mode' in _result_modify_password" + - _result_modify_password.engine_mode == "provisioned" + - "'engine_version' in _result_modify_password" + - "'master_username' in _result_modify_password" + - _result_modify_password.master_username == "{{ username }}" + - "'port' in _result_create_source_db_cluster" + - "_result_modify_password.port == {{ port }}" + - "'status' in _result_modify_password" + - _result_modify_password.status == "available" + - "'tags' in _result_modify_password" + - "'vpc_security_groups' in _result_modify_password" + + - name: Modify DB cluster port + rds_cluster: + id: "{{ cluster_id }}" + state: present + port: "{{ new_port }}" + register: _result_modify_port + + - assert: + that: + - _result_modify_port.changed + - "'allocated_storage' in _result_modify_port" + - _result_modify_port.allocated_storage == 1 + - "'cluster_create_time' in _result_modify_port" + - _result_modify_port.copy_tags_to_snapshot == false + - "'db_cluster_arn' in _result_modify_port" + - "_result_modify_port.db_cluster_identifier == '{{ cluster_id }}'" + - "'db_cluster_parameter_group' in _result_modify_port" + - "'db_cluster_resource_id' in _result_modify_port" + - "'endpoint' in _result_modify_port" + - "'engine' in _result_modify_port" + - _result_modify_port.engine == "{{ engine }}" + - "'engine_mode' in _result_modify_port" + - _result_modify_port.engine_mode == "provisioned" + - "'engine_version' in _result_modify_port" + - "'master_username' in _result_modify_port" + - _result_modify_port.master_username == "{{ username }}" + - "'port' in _result_modify_port" + - "_result_modify_port.port == {{ new_port }}" + - "'status' in _result_modify_port" + - _result_modify_port.status == "available" + - "'tags' in _result_modify_port" + - "'vpc_security_groups' in _result_modify_port" + + - name: Modify DB cluster identifier + rds_cluster: + id: "{{ cluster_id }}" + state: present + purge_tags: False + new_cluster_id: "{{ new_cluster_id }}" + apply_immediately: True + register: _result_modify_id + + - assert: + that: + - _result_modify_id.changed + - "'allocated_storage' in _result_modify_id" + - _result_modify_id.allocated_storage == 1 + - "'cluster_create_time' in _result_modify_id" + - _result_modify_id.copy_tags_to_snapshot == false + - "'db_cluster_arn' in _result_modify_id" + - "_result_modify_id.db_cluster_identifier == '{{ new_cluster_id }}'" + - "'db_cluster_parameter_group' in _result_modify_id" + - "'db_cluster_resource_id' in _result_modify_id" + - "'endpoint' in _result_modify_id" + - "'engine' in _result_modify_id" + - _result_modify_id.engine == "{{ engine }}" + - "'engine_mode' in _result_modify_id" + - _result_modify_id.engine_mode == "provisioned" + - "'engine_version' in _result_modify_id" + - "'master_username' in _result_modify_id" + - _result_modify_id.master_username == "{{ username }}" + - "'port' in _result_modify_id" + - "_result_modify_id.port == {{ new_port }}" + - "'status' in _result_modify_id" + - _result_modify_id.status == "available" + - "'tags' in _result_modify_id" + - "'vpc_security_groups' in _result_modify_id" + + - name: Delete DB cluster without creating a final snapshot (CHECK MODE) + rds_cluster: + state: absent + cluster_id: "{{ new_cluster_id }}" + skip_final_snapshot: True + register: _result_delete_cluster + check_mode: true + + - assert: + that: + - _result_delete_cluster.changed + + - name: Delete DB cluster without creating a final snapshot + rds_cluster: + state: absent + cluster_id: "{{ new_cluster_id }}" + skip_final_snapshot: True + register: _result_delete_cluster + + - assert: + that: + - _result_delete_cluster.changed + + - name: Delete DB cluster without creating a final snapshot (idempotence) + rds_cluster: + state: absent + cluster_id: "{{ new_cluster_id }}" + skip_final_snapshot: True + register: _result_delete_cluster + + - assert: + that: + - not _result_delete_cluster.changed + + always: + - name: Delete DB cluster without creating a final snapshot + rds_cluster: + state: absent + cluster_id: "{{ cluster_id }}" + skip_final_snapshot: True + ignore_errors: true diff --git a/tests/integration/targets/rds_cluster/roles/rds_cluster/tasks/test_promote.yml b/tests/integration/targets/rds_cluster/roles/rds_cluster/tasks/test_promote.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/rds_cluster/roles/rds_cluster/tasks/test_promote.yml @@ -0,0 +1,186 @@ +--- +- block: + - name: Ensure the resource doesn't exist + rds_cluster: + id: "{{ cluster_id }}" + state: absent + engine: "{{ engine}}" + username: "{{ username }}" + password: "{{ password }}" + skip_final_snapshot: True + register: _result_delete_db_cluster + + - assert: + that: + - not _result_delete_db_cluster.changed + ignore_errors: yes + + - name: Set the two regions for the source DB and the read replica + set_fact: + region_src: "{{ aws_region }}" + region_dest: "{{ aws_region }}" + + - name: Create a source DB cluster + rds_cluster: + cluster_id: "{{ cluster_id }}" + state: present + engine: "{{ engine}}" + username: "{{ username }}" + password: "{{ password }}" + region: "{{ region_src }}" + tags: + Name: "{{ cluster_id }}" + Created_by: Ansible rds_cluster tests + register: _result_create_src_db_cluster + + - assert: + that: + - _result_create_src_db_cluster.changed + - "'allocated_storage' in _result_create_src_db_cluster" + - _result_create_src_db_cluster.allocated_storage == 1 + - "'cluster_create_time' in _result_create_src_db_cluster" + - _result_create_src_db_cluster.copy_tags_to_snapshot == false + - "'db_cluster_arn' in _result_create_src_db_cluster" + - "_result_create_src_db_cluster.db_cluster_identifier == '{{ cluster_id }}'" + - "'db_cluster_parameter_group' in _result_create_src_db_cluster" + - "'db_cluster_resource_id' in _result_create_src_db_cluster" + - "'endpoint' in _result_create_src_db_cluster" + - "'engine' in _result_create_src_db_cluster" + - _result_create_src_db_cluster.engine == "{{ engine }}" + - "'engine_mode' in _result_create_src_db_cluster" + - _result_create_src_db_cluster.engine_mode == "provisioned" + - "'engine_version' in _result_create_src_db_cluster" + - "'master_username' in _result_create_src_db_cluster" + - _result_create_src_db_cluster.master_username == "{{ username }}" + - "'port' in _result_create_src_db_cluster" + - "_result_create_src_db_cluster.port == {{ port }}" + - "'status' in _result_create_src_db_cluster" + - _result_create_src_db_cluster.status == "available" + - "'tags' in _result_create_src_db_cluster" + - "_result_create_src_db_cluster.tags | length == 2" + - "_result_create_src_db_cluster.tags.Name == '{{ cluster_id }}'" + - "_result_create_src_db_cluster.tags.Created_by == 'Ansible rds_cluster tests'" + - "'vpc_security_groups' in _result_create_src_db_cluster" + + - name: Get info on DB cluster + rds_cluster_info: + db_cluster_identifier: "{{ cluster_id }}" + register: _result_cluster_info + + - assert: + that: + - _result_cluster_info is successful + + - name: Set the ARN of the source DB cluster + set_fact: + src_db_cluster_arn: "{{ _result_cluster_info.clusters[0].db_cluster_arn}}" + + - name: Create a DB cluster read replica in a different region + rds_cluster: + id: "{{ cluster_id }}-replica" + state: present + replication_source_identifier: "{{ src_db_cluster_arn }}" + engine: "{{ engine}}" + region: "{{ region_dest }}" + tags: + Name: "{{ cluster_id }}" + Created_by: Ansible rds_cluster tests + wait: yes + register: _result_create_replica_db_cluster + + - assert: + that: + - _result_create_replica_db_cluster.changed + - "'allocated_storage' in _result_create_replica_db_cluster" + - _result_create_replica_db_cluster.allocated_storage == 1 + - "'cluster_create_time' in _result_create_replica_db_cluster" + - _result_create_replica_db_cluster.copy_tags_to_snapshot == false + - "'db_cluster_arn' in _result_create_replica_db_cluster" + - "_result_create_replica_db_cluster.db_cluster_identifier == '{{ cluster_id }}'" + - "'db_cluster_parameter_group' in _result_create_replica_db_cluster" + - "'db_cluster_resource_id' in _result_create_replica_db_cluster" + - "'endpoint' in _result_create_replica_db_cluster" + - "'engine' in _result_create_replica_db_cluster" + - _result_create_replica_db_cluster.engine == "{{ engine }}" + - "'engine_mode' in _result_create_replica_db_cluster" + - _result_create_replica_db_cluster.engine_mode == "provisioned" + - "'engine_version' in _result_create_replica_db_cluster" + - "'master_username' in _result_create_replica_db_cluster" + - _result_create_replica_db_cluster.master_username == "{{ username }}" + - "'port' in _result_create_replica_db_cluster" + - "_result_create_replica_db_cluster.port == {{ port }}" + - "'status' in _result_create_replica_db_cluster" + - _result_create_replica_db_cluster.status == "available" + - "'tags' in _result_create_replica_db_cluster" + - "_result_create_replica_db_cluster.tags | length == 2" + - "_result_create_replica_db_cluster.tags.Name == '{{ cluster_id }}'" + - "_result_create_replica_db_cluster.tags.Created_by == 'Ansible rds_cluster tests'" + - "'vpc_security_groups' in _result_create_replica_db_cluster" + + - name: Test idempotence with a DB cluster read replica + rds_cluster: + id: "{{ cluster_id }}-replica" + state: present + replication_source_identifier: "{{ src_db_cluster_arn }}" + engine: "{{ engine}}" + region: "{{ region_dest }}" + tags: + Name: "{{ cluster_id }}" + Created_by: Ansible rds_cluster tests + register: _result_create_replica_db_cluster + + - assert: + that: + - not _result_create_replica_db_cluster.changed + + - name: Get info of existing DB cluster + rds_cluster_info: + db_cluster_identifier: "{{ cluster_id }}-replica" + region: "{{ region_dest }}" + register: _result_cluster_info + + - assert: + that: + - _result_cluster_info is successful + # - _result_cluster_info.clusters | length == 0 + + - name: Promote the DB cluster read replica + rds_cluster: + cluster_id: "{{ cluster_id }}-replica" + state: present + promote: True + region: "{{ region_dest }}" + register: _result_promote_replica_db_cluster + + - assert: + that: + - _result_promote_replica_db_cluster.changed + + - name: Promote the DB cluster read replica (idempotence) + rds_cluster: + cluster_id: "{{ cluster_id }}-replica" + state: present + promote: True + region: "{{ region_dest }}" + register: _result_promote_replica_db_cluster + + - assert: + that: + - not _result_promote_replica_db_cluster.changed + + always: + - name: Remove the DB cluster + rds_cluster: + id: "{{ cluster_id }}" + state: absent + skip_final_snapshot: True + region: "{{ region_src }}" + ignore_errors: yes + + - name: Remove the DB cluster read replica + rds_cluster: + id: "{{ cluster_id }}-replica" + state: absent + skip_final_snapshot: True + region: "{{ region_dest }}" + ignore_errors: yes diff --git a/tests/integration/targets/rds_cluster/roles/rds_cluster/tasks/test_restore.yml b/tests/integration/targets/rds_cluster/roles/rds_cluster/tasks/test_restore.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/rds_cluster/roles/rds_cluster/tasks/test_restore.yml @@ -0,0 +1,185 @@ +--- +- block: + - name: Ensure the resource doesn't exist + rds_cluster: + id: "{{ cluster_id }}" + state: absent + engine: "{{ engine}}" + username: "{{ username }}" + password: "{{ password }}" + skip_final_snapshot: True + register: _result_delete_db_cluster + + - assert: + that: + - not _result_delete_db_cluster.changed + ignore_errors: yes + + - name: Create a source DB cluster + rds_cluster: + id: "{{ cluster_id }}" + state: present + engine: "{{ engine}}" + backup_retention_period: 1 + username: "{{ username }}" + password: "{{ password }}" + register: _result_create_source_db_cluster + + - assert: + that: + - _result_create_source_db_cluster.changed + - "'allocated_storage' in _result_create_source_db_cluster" + - _result_create_source_db_cluster.allocated_storage == 1 + - "'cluster_create_time' in _result_create_source_db_cluster" + - _result_create_source_db_cluster.copy_tags_to_snapshot == false + - "'db_cluster_arn' in _result_create_source_db_cluster" + - "'db_cluster_identifier' in _result_create_source_db_cluster" + - _result_create_source_db_cluster.db_cluster_identifier == "{{ cluster_id }}" + - "'db_cluster_parameter_group' in _result_create_source_db_cluster" + - "'db_cluster_resource_id' in _result_create_source_db_cluster" + - "'endpoint' in _result_create_source_db_cluster" + - "'engine' in _result_create_source_db_cluster" + - _result_create_source_db_cluster.engine == "{{ engine }}" + - "'engine_mode' in _result_create_source_db_cluster" + - _result_create_source_db_cluster.engine_mode == "provisioned" + - "'engine_version' in _result_create_source_db_cluster" + - "'master_username' in _result_create_source_db_cluster" + - _result_create_source_db_cluster.master_username == "{{ username }}" + - "'port' in _result_create_source_db_cluster" + - "_result_create_source_db_cluster.port == {{ port }}" + - "'status' in _result_create_source_db_cluster" + - _result_create_source_db_cluster.status == 'available' + - _result_create_source_db_cluster.storage_encrypted == false + - "'tags' in _result_create_source_db_cluster" + - "'vpc_security_groups' in _result_create_source_db_cluster" + + - name: Create a point in time DB cluster + rds_cluster: + state: present + id: "{{ cluster_id }}-point-in-time" + source_db_cluster_identifier: "{{ cluster_id }}" + creation_source: "cluster" + engine: "{{ engine}}" + username: "{{ username }}" + password: "{{ password }}" + use_latest_restorable_time: true + tags: + Name: "{{ cluster_id }}" + Created_by: Ansible rds_cluster tests + register: _result_restored_db_cluster + + - assert: + that: + - _result_restored_db_cluster.changed + - "'allocated_storage' in _result_restored_db_cluster" + - _result_restored_db_cluster.allocated_storage == 1 + - "'cluster_create_time' in _result_restored_db_cluster" + - _result_restored_db_cluster.copy_tags_to_snapshot == false + - "'db_cluster_arn' in _result_restored_db_cluster" + - "_result_restored_db_cluster.db_cluster_identifier == '{{ cluster_id }}-point-in-time'" + - "'db_cluster_parameter_group' in _result_restored_db_cluster" + - "'db_cluster_resource_id' in _result_restored_db_cluster" + - "'endpoint' in _result_restored_db_cluster" + - "'engine' in _result_restored_db_cluster" + - _result_restored_db_cluster.engine == "{{ engine }}" + - "'engine_mode' in _result_restored_db_cluster" + - _result_restored_db_cluster.engine_mode == "provisioned" + - "'engine_version' in _result_restored_db_cluster" + - "'master_username' in _result_restored_db_cluster" + - _result_restored_db_cluster.master_username == "{{ username }}" + - "'port' in _result_restored_db_cluster" + - "_result_restored_db_cluster.port == {{ port }}" + - "'status' in _result_restored_db_cluster" + - _result_restored_db_cluster.status == "available" + - "'tags' in _result_restored_db_cluster" + - "_result_restored_db_cluster.tags | length == 2" + - "_result_restored_db_cluster.tags.Name == '{{ cluster_id }}'" + - "_result_restored_db_cluster.tags.Created_by == 'Ansible rds_cluster tests'" + - "'vpc_security_groups' in _result_restored_db_cluster" + + - name: Create a point in time DB cluster (idempotence) + rds_cluster: + state: present + id: "{{ cluster_id }}-point-in-time" + source_db_cluster_identifier: "{{ cluster_id }}" + creation_source: "cluster" + engine: "{{ engine}}" + username: "{{ username }}" + password: "{{ password }}" + restore_to_time: "{{ _result_restored_db_cluster.latest_restorable_time }}" + tags: + Name: "{{ cluster_id }}" + Created_by: Ansible rds_cluster tests + register: _result_restored_db_cluster + + - assert: + that: + - not _result_restored_db_cluster.changed + + # TODO: Requires rds_cluster_snapshot module + # - name: Take a snapshot of the DB cluster + # rds_cluster_snapshot: + # state: present + # db_cluster_identifier: "{{ cluster_id }}" + # db_snapshot_identifier: "{{ cluster_id }}-snapshot" + # register: _result_cluster_snapshot + + # - assert: + # that: + # - _result_cluster_snapshot.changed + + # - name: Restore DB cluster from source (snapshot) + # rds_cluster: + # creation_source: 'snapshot' + # engine: "{{ engine }}" + # cluster_id: "cluster-{{ resource_prefix }}-restored-snapshot" + # snapshot_identifier: "cluster-{{ resource_prefix }}-snapshot" + # register: _result_restored_db_cluster + + # - assert: + # that: + # - _result_restored_db_cluster.changed + # - "'allocated_storage' in _result_restored_db_cluster" + # - _result_restored_db_cluster.allocated_storage == 1 + # - "'cluster_create_time' in _result_restored_db_cluster" + # - _result_restored_db_cluster.copy_tags_to_snapshot == false + # - "'db_cluster_arn' in _result_restored_db_cluster" + # - "_result_restored_db_cluster.db_cluster_identifier == '{{ cluster_id }}-restored-snapshot'" + # - "'db_cluster_parameter_group' in _result_restored_db_cluster" + # - "'db_cluster_resource_id' in _result_restored_db_cluster" + # - "'endpoint' in _result_restored_db_cluster" + # - "'engine' in _result_restored_db_cluster" + # - _result_restored_db_cluster.engine == "{{ engine }}" + # - "'engine_mode' in _result_restored_db_cluster" + # - _result_restored_db_cluster.engine_mode == "provisioned" + # - "'engine_version' in _result_restored_db_cluster" + # - "'master_username' in _result_restored_db_cluster" + # - _result_restored_db_cluster.master_username == "{{ username }}" + # - "'port' in _result_restored_db_cluster" + # - "_result_restored_db_cluster.port == {{ port }}" + # - "'status' in _result_restored_db_cluster" + # - _result_restored_db_cluster.status == "available" + # - "'tags' in _result_restored_db_cluster" + # - "_result_restored_db_cluster.tags | length == 2" + # - "_result_restored_db_cluster.tags.Name == '{{ cluster_id }}'" + # - "_result_restored_db_cluster.tags.Created_by == 'Ansible rds_cluster tests'" + # - "'vpc_security_groups' in _result_restored_db_cluster" + + # TODO: export a snapshot to an S3 bucket and restore cluster from it + # Requires rds_export_task module + + always: + # - name: Delete the snapshot + # rds_cluster: + # snapshot_identifier: "{{ cluster_id }}-snapshot" + # register: _result_delete_snapshot + + - name: Delete DB cluster without creating a final snapshot + rds_cluster: + state: absent + cluster_id: "{{ item }}" + skip_final_snapshot: True + ignore_errors: true + loop: + - "{{ cluster_id }}" + - "{{ cluster_id }}-point-in-time" diff --git a/tests/integration/targets/rds_cluster/roles/rds_cluster/tasks/test_tag.yml b/tests/integration/targets/rds_cluster/roles/rds_cluster/tasks/test_tag.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/rds_cluster/roles/rds_cluster/tasks/test_tag.yml @@ -0,0 +1,291 @@ +--- +- block: + - name: Ensure the resource doesn't exist + rds_cluster: + id: "{{ cluster_id }}" + state: absent + engine: "{{ engine}}" + username: "{{ username }}" + password: "{{ password }}" + skip_final_snapshot: True + register: _result_delete_db_cluster + + - assert: + that: + - not _result_delete_db_cluster.changed + ignore_errors: yes + + - name: Create a DB cluster + rds_cluster: + engine: "{{ engine }}" + username: "{{ username }}" + password: "{{ password }}" + cluster_id: "{{ cluster_id }}" + tags: "{{ tags_create }}" + register: _result_create_db_cluster + + - assert: + that: + - _result_create_db_cluster.changed + - "'allocated_storage' in _result_create_db_cluster" + - _result_create_db_cluster.allocated_storage == 1 + - "'cluster_create_time' in _result_create_db_cluster" + - _result_create_db_cluster.copy_tags_to_snapshot == false + - "'db_cluster_arn' in _result_create_db_cluster" + - "'db_cluster_identifier' in _result_create_db_cluster" + - _result_create_db_cluster.db_cluster_identifier == "{{ cluster_id }}" + - "'db_cluster_parameter_group' in _result_create_db_cluster" + - "'db_cluster_resource_id' in _result_create_db_cluster" + - "'endpoint' in _result_create_db_cluster" + - "'engine' in _result_create_db_cluster" + - _result_create_db_cluster.engine == "{{ engine }}" + - "'engine_mode' in _result_create_db_cluster" + - _result_create_db_cluster.engine_mode == "provisioned" + - "'engine_version' in _result_create_db_cluster" + - "'master_username' in _result_create_db_cluster" + - _result_create_db_cluster.master_username == "{{ username }}" + - "'port' in _result_create_db_cluster" + - "_result_create_db_cluster.port == {{ port }}" + - "'status' in _result_create_db_cluster" + - _result_create_db_cluster.status == 'available' + - _result_create_db_cluster.storage_encrypted == false + - "'tags' in _result_create_db_cluster" + - _result_create_db_cluster.tags | length == 2 + - _result_create_db_cluster.tags["Created_By"] == "{{ tags_create["Created_By"] }}" + - _result_create_db_cluster.tags["Name"] == "{{ tags_create["Name"]}}" + - "'vpc_security_groups' in _result_create_db_cluster" + + - name: Test tags are not purged if purge_tags is False + rds_cluster: + engine: "{{ engine }}" + username: "{{ username }}" + password: "{{ new_password }}" + cluster_id: "{{ cluster_id }}" + tags: {} + purge_tags: False + register: _result_tag_db_cluster + + - assert: + that: + - not _result_tag_db_cluster.changed + - "'allocated_storage' in _result_tag_db_cluster" + - _result_tag_db_cluster.allocated_storage == 1 + - "'cluster_create_time' in _result_tag_db_cluster" + - _result_tag_db_cluster.copy_tags_to_snapshot == false + - "'db_cluster_arn' in _result_tag_db_cluster" + - "'db_cluster_identifier' in _result_tag_db_cluster" + - _result_tag_db_cluster.db_cluster_identifier == "{{ cluster_id }}" + - "'db_cluster_parameter_group' in _result_tag_db_cluster" + - "'db_cluster_resource_id' in _result_tag_db_cluster" + - "'endpoint' in _result_tag_db_cluster" + - "'engine' in _result_tag_db_cluster" + - _result_tag_db_cluster.engine == "{{ engine }}" + - "'engine_mode' in _result_tag_db_cluster" + - _result_tag_db_cluster.engine_mode == "provisioned" + - "'engine_version' in _result_tag_db_cluster" + - "'master_username' in _result_tag_db_cluster" + - _result_tag_db_cluster.master_username == "{{ username }}" + - "'port' in _result_tag_db_cluster" + - "_result_tag_db_cluster.port == {{ port }}" + - "'status' in _result_tag_db_cluster" + - _result_tag_db_cluster.status == 'available' + - _result_tag_db_cluster.storage_encrypted == false + - "'tags' in _result_tag_db_cluster" + - _result_tag_db_cluster.tags | length == 2 + - _result_tag_db_cluster.tags["Created_By"] == "{{ tags_create["Created_By"] }}" + - _result_tag_db_cluster.tags["Name"] == "{{ tags_create["Name"] }}" + - "'vpc_security_groups' in _result_tag_db_cluster" + + - name: Add a tag and remove a tag (purge_tags is True) + rds_cluster: + cluster_id: "{{ cluster_id }}" + state: present + tags: "{{ tags_patch }}" + register: _result_tag_db_cluster + + - assert: + that: + - _result_tag_db_cluster.changed + - "'allocated_storage' in _result_tag_db_cluster" + - _result_tag_db_cluster.allocated_storage == 1 + - "'cluster_create_time' in _result_tag_db_cluster" + - _result_tag_db_cluster.copy_tags_to_snapshot == false + - "'db_cluster_arn' in _result_tag_db_cluster" + - "'db_cluster_identifier' in _result_tag_db_cluster" + - _result_tag_db_cluster.db_cluster_identifier == "{{ cluster_id }}" + - "'db_cluster_parameter_group' in _result_tag_db_cluster" + - "'db_cluster_resource_id' in _result_tag_db_cluster" + - "'endpoint' in _result_tag_db_cluster" + - "'engine' in _result_tag_db_cluster" + - _result_tag_db_cluster.engine == "{{ engine }}" + - "'engine_mode' in _result_tag_db_cluster" + - _result_tag_db_cluster.engine_mode == "provisioned" + - "'engine_version' in _result_tag_db_cluster" + - "'master_username' in _result_tag_db_cluster" + - _result_tag_db_cluster.master_username == "{{ username }}" + - "'port' in _result_tag_db_cluster" + - "_result_tag_db_cluster.port == {{ port }}" + - "'status' in _result_tag_db_cluster" + - _result_tag_db_cluster.status == 'available' + - _result_tag_db_cluster.storage_encrypted == false + - "'tags' in _result_tag_db_cluster" + - _result_tag_db_cluster.tags | length == 2 + - _result_tag_db_cluster.tags["Name"] == "{{ tags_patch['Name'] }}" + - "'vpc_security_groups' in _result_tag_db_cluster" + + - name: Purge a tag from the cluster (CHECK MODE) + rds_cluster: + engine: "{{ engine }}" + username: "{{ username }}" + password: "{{ password }}" + cluster_id: "{{ cluster_id }}" + tags: + Created_By: "Ansible_rds_cluster_integration_test" + register: _result_tag_db_cluster + check_mode: true + + - assert: + that: + - _result_tag_db_cluster.changed + + - name: Purge a tag from the cluster + rds_cluster: + engine: "{{ engine }}" + username: "{{ username }}" + password: "{{ password }}" + cluster_id: "{{ cluster_id }}" + tags: + Created_By: "Ansible_rds_cluster_integration_test" + register: _result_tag_db_cluster + + - assert: + that: + - _result_tag_db_cluster.changed + - "'allocated_storage' in _result_tag_db_cluster" + - _result_tag_db_cluster.allocated_storage == 1 + - "'cluster_create_time' in _result_tag_db_cluster" + - _result_tag_db_cluster.copy_tags_to_snapshot == false + - "'db_cluster_arn' in _result_tag_db_cluster" + - "'db_cluster_identifier' in _result_tag_db_cluster" + - _result_tag_db_cluster.db_cluster_identifier == "{{ cluster_id }}" + - "'db_cluster_parameter_group' in _result_tag_db_cluster" + - "'db_cluster_resource_id' in _result_tag_db_cluster" + - "'endpoint' in _result_tag_db_cluster" + - "'engine' in _result_tag_db_cluster" + - _result_tag_db_cluster.engine == "{{ engine }}" + - "'engine_mode' in _result_tag_db_cluster" + - _result_tag_db_cluster.engine_mode == "provisioned" + - "'engine_version' in _result_tag_db_cluster" + - "'master_username' in _result_tag_db_cluster" + - _result_tag_db_cluster.master_username == "{{ username }}" + - "'port' in _result_tag_db_cluster" + - "_result_tag_db_cluster.port == {{ port }}" + - "'status' in _result_tag_db_cluster" + - _result_tag_db_cluster.status == 'available' + - _result_tag_db_cluster.storage_encrypted == false + - "'tags' in _result_tag_db_cluster" + - _result_tag_db_cluster.tags | length == 1 + - _result_tag_db_cluster.tags["Created_By"] == "Ansible_rds_cluster_integration_test" + - "'vpc_security_groups' in _result_tag_db_cluster" + + - name: Add a tag to the cluster (CHECK MODE) + rds_cluster: + engine: "{{ engine }}" + username: "{{ username }}" + password: "{{ password }}" + cluster_id: "{{ cluster_id }}" + tags: + Name: "cluster-{{ resource_prefix }}" + Created_By: "Ansible_rds_cluster_integration_test" + register: _result_tag_db_cluster + check_mode: true + + - assert: + that: + - _result_tag_db_cluster.changed + + - name: Add a tag to the cluster + rds_cluster: + engine: "{{ engine }}" + username: "{{ username }}" + password: "{{ password }}" + cluster_id: "{{ cluster_id }}" + tags: "{{ tags_create }}" + register: _result_tag_db_cluster + + - assert: + that: + - _result_tag_db_cluster.changed + - "'allocated_storage' in _result_tag_db_cluster" + - _result_tag_db_cluster.allocated_storage == 1 + - "'cluster_create_time' in _result_tag_db_cluster" + - _result_tag_db_cluster.copy_tags_to_snapshot == false + - "'db_cluster_arn' in _result_tag_db_cluster" + - "'db_cluster_identifier' in _result_tag_db_cluster" + - _result_tag_db_cluster.db_cluster_identifier == "{{ cluster_id }}" + - "'db_cluster_parameter_group' in _result_tag_db_cluster" + - "'db_cluster_resource_id' in _result_tag_db_cluster" + - "'endpoint' in _result_tag_db_cluster" + - "'engine' in _result_tag_db_cluster" + - _result_tag_db_cluster.engine == "{{ engine }}" + - "'engine_mode' in _result_tag_db_cluster" + - _result_tag_db_cluster.engine_mode == "provisioned" + - "'engine_version' in _result_tag_db_cluster" + - "'master_username' in _result_tag_db_cluster" + - _result_tag_db_cluster.master_username == "{{ username }}" + - "'port' in _result_tag_db_cluster" + - "_result_tag_db_cluster.port == {{ port }}" + - "'status' in _result_tag_db_cluster" + - _result_tag_db_cluster.status == 'available' + - _result_tag_db_cluster.storage_encrypted == false + - "'tags' in _result_tag_db_cluster" + - _result_tag_db_cluster.tags | length == 2 + - _result_tag_db_cluster.tags["Created_By"] == "{{ tags_create["Created_By"]}}" + - _result_tag_db_cluster.tags["Name"] == "{{ tags_create["Name"]}}" + - "'vpc_security_groups' in _result_tag_db_cluster" + + - name: Remove all tags + rds_cluster: + engine: "{{ engine }}" + username: "{{ username }}" + password: "{{ password }}" + cluster_id: "{{ cluster_id }}" + tags: {} + register: _result_tag_db_cluster + + - assert: + that: + - _result_tag_db_cluster.changed + - "'allocated_storage' in _result_tag_db_cluster" + - _result_tag_db_cluster.allocated_storage == 1 + - "'cluster_create_time' in _result_tag_db_cluster" + - _result_tag_db_cluster.copy_tags_to_snapshot == false + - "'db_cluster_arn' in _result_tag_db_cluster" + - "'db_cluster_identifier' in _result_tag_db_cluster" + - _result_tag_db_cluster.db_cluster_identifier == "{{ cluster_id }}" + - "'db_cluster_parameter_group' in _result_tag_db_cluster" + - "'db_cluster_resource_id' in _result_tag_db_cluster" + - "'endpoint' in _result_tag_db_cluster" + - "'engine' in _result_tag_db_cluster" + - _result_tag_db_cluster.engine == "{{ engine }}" + - "'engine_mode' in _result_tag_db_cluster" + - _result_tag_db_cluster.engine_mode == "provisioned" + - "'engine_version' in _result_tag_db_cluster" + - "'master_username' in _result_tag_db_cluster" + - _result_tag_db_cluster.master_username == "{{ username }}" + - "'port' in _result_tag_db_cluster" + - "_result_tag_db_cluster.port == {{ port }}" + - "'status' in _result_tag_db_cluster" + - _result_tag_db_cluster.status == 'available' + - _result_tag_db_cluster.storage_encrypted == false + - "'tags' in _result_tag_db_cluster" + - _result_tag_db_cluster.tags | length == 0 + - "'vpc_security_groups' in _result_tag_db_cluster" + + always: + - name: Delete DB cluster without creating a final snapshot + rds_cluster: + state: absent + cluster_id: "{{ cluster_id }}" + skip_final_snapshot: True + ignore_errors: true diff --git a/tests/integration/targets/rds_cluster/roles/rds_cluster/vars/main.yml b/tests/integration/targets/rds_cluster/roles/rds_cluster/vars/main.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/rds_cluster/roles/rds_cluster/vars/main.yml @@ -0,0 +1 @@ +--- diff --git a/tests/integration/targets/rds_cluster/runme.sh b/tests/integration/targets/rds_cluster/runme.sh new file mode 100755 --- /dev/null +++ b/tests/integration/targets/rds_cluster/runme.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +# +# Beware: most of our tests here are run in parallel. +# To add new tests you'll need to add a new host to the inventory and a matching +# '{{ inventory_hostname }}'.yml file in roles/rds_cluster/tasks/ + + +set -eux + +export ANSIBLE_ROLES_PATH=../ + +ansible-playbook main.yml -i inventory "$@"
Use community.aws.rds_instance module to create Aurora cluster ### Summary I am trying to create an Aurora DB/Cluster from new. I am not clear from the documentation how to do this. The documentation refers to: "see rds_cluster to manage it" - what does this mean as I do not see any modules for rds_cluster? Would appreciate your support Thank you Tony ### Issue Type Documentation Report ### Component Name community.aws.rds_instance ### Ansible Version ```console (paste below) $ ansible --version ``` ### Collection Versions ```console (paste below) $ ansible-galaxy collection list ``` ### Configuration ```console (paste below) $ ansible-config dump --only-changed ``` ### OS / Environment _No response_ ### Additional Information _No response_ ### Code of Conduct - [X] I agree to follow the Ansible Code of Conduct Support AWS RDS serverless <!--- Verify first that your feature was not already discussed on GitHub --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Describe the new feature/improvement briefly below --> Ported from https://github.com/ansible/ansible/issues/45811 Support AWS RDS serverless ##### ISSUE TYPE - Feature Idea ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> rds ##### ADDITIONAL INFORMATION <!--- Describe how the feature would be used, why it is needed and what it would solve --> This would allow the management of Aurora serverless instances https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora-serverless.html
Hm, that's a typo in the example section, because there is no `rds_cluster` module. Basically you also use `rds_instance` to create a rds "cluster". But "cluster" is here a buzzword. Because you always create a primary node. always. It does not matter if the engine is mariadb, mysql or aurora. After the primary node is deployed. you can attach read replicas to it. ```yml - name: add reader nodes. rds_instance: engine: aurora-mysql db_instance_identifier: "{{ extra_node_name }}" instance_type: "{{ extra_node_type }}" cluster_id: "{{ cluster }}" region: "{{ region }}" ``` The question is, what else do you want to "manage"? You can force a failover also with `rds_instance`. A snapshot is targeting with `rds_instance_snapshot`. TIL: https://github.com/ansible-collections/community.aws/pull/687 `rds_cluster` is currently in development. Files identified in the description: * [`plugins/modules/rds.py`](https://github.com/ansible-collections/community.aws/blob/main/plugins/modules/rds.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @jillr @s-hertel @tremble @willthames @wimnat [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify --->
2022-04-05T23:02:53
ansible-collections/community.aws
1,055
ansible-collections__community.aws-1055
[ "1013" ]
6f0f283705bb17957b01b31587ff2b7da6d4685f
diff --git a/plugins/modules/rds_instance.py b/plugins/modules/rds_instance.py --- a/plugins/modules/rds_instance.py +++ b/plugins/modules/rds_instance.py @@ -205,6 +205,23 @@ description: - Set to true to conduct the reboot through a MultiAZ failover. type: bool + iam_roles: + description: + - List of Amazon Web Services Identity and Access Management (IAM) roles to associate with DB instance. + type: list + elements: dict + suboptions: + feature_name: + description: + - The name of the feature associated with the IAM role. + type: str + required: yes + role_arn: + description: + - The ARN of the IAM role to associate with the DB instance. + type: str + required: yes + version_added: 3.3.0 iops: description: - The Provisioned IOPS (I/O operations per second) value. Is only set when using I(storage_type) is set to io1. @@ -316,6 +333,12 @@ a publicly resolvable DNS name, which resolves to a public IP address. A value of false specifies an internal instance with a DNS name that resolves to a private IP address. type: bool + purge_iam_roles: + description: + - Set to C(True) to remove any IAM roles that aren't specified in the task and are associated with the instance. + type: bool + default: False + version_added: 3.3.0 restore_time: description: - If using I(creation_source=instance) this indicates the UTC date and time to restore from the source instance. @@ -462,7 +485,49 @@ vpc_security_group_ids: - sg-0be17ba10c9286b0b purge_security_groups: false - register: result + register: result + +# Add IAM role to db instance +- name: Create IAM policy + community.aws.iam_managed_policy: + policy_name: "my-policy" + policy: "{{ lookup('file','files/policy.json') }}" + state: present + register: iam_policy + +- name: Create IAM role + community.aws.iam_role: + assume_role_policy_document: "{{ lookup('file','files/assume_policy.json') }}" + name: "my-role" + state: present + managed_policy: "{{ iam_policy.policy.arn }}" + register: iam_role + +- name: Create DB instance with added IAM role + community.aws.rds_instance: + id: "my-instance-id" + state: present + engine: postgres + engine_version: 14.2 + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: db.m6g.large + allocated_storage: "{{ allocated_storage }}" + iam_roles: + - role_arn: "{{ iam_role.arn }}" + feature_name: 's3Export' + +- name: Remove IAM role from DB instance + community.aws.rds_instance: + id: "my-instance-id" + state: present + engine: postgres + engine_version: 14.2 + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: db.m6g.large + allocated_storage: "{{ allocated_storage }}" + purge_iam_roles: yes ''' RETURN = r''' @@ -780,16 +845,23 @@ from ansible_collections.amazon.aws.plugins.module_utils.core import get_boto3_client_method_parameters from ansible_collections.amazon.aws.plugins.module_utils.ec2 import ansible_dict_to_boto3_tag_list from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AWSRetry +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import boto3_tag_list_to_ansible_dict from ansible_collections.amazon.aws.plugins.module_utils.rds import arg_spec_to_rds_params from ansible_collections.amazon.aws.plugins.module_utils.rds import call_method +from ansible_collections.amazon.aws.plugins.module_utils.rds import compare_iam_roles from ansible_collections.amazon.aws.plugins.module_utils.rds import ensure_tags from ansible_collections.amazon.aws.plugins.module_utils.rds import get_final_identifier from ansible_collections.amazon.aws.plugins.module_utils.rds import get_rds_method_attribute from ansible_collections.amazon.aws.plugins.module_utils.rds import get_tags +from ansible_collections.amazon.aws.plugins.module_utils.rds import update_iam_roles + valid_engines = ['aurora', 'aurora-mysql', 'aurora-postgresql', 'mariadb', 'mysql', 'oracle-ee', 'oracle-ee-cdb', 'oracle-se2', 'oracle-se2-cdb', 'postgres', 'sqlserver-ee', 'sqlserver-se', 'sqlserver-ex', 'sqlserver-web'] +valid_engines_iam_roles = ['aurora-postgresql', 'oracle-ee', 'oracle-ee-cdb', 'oracle-se2', 'oracle-se2-cdb', + 'postgres', 'sqlserver-ee', 'sqlserver-se', 'sqlserver-ex', 'sqlserver-web'] + def get_rds_method_attribute_name(instance, state, creation_source, read_replica): method_name = None @@ -945,23 +1017,21 @@ def get_current_attributes_with_inconsistent_keys(instance): options['DBSecurityGroups'] = [sg['DBSecurityGroupName'] for sg in instance['DBSecurityGroups'] if sg['Status'] in ['adding', 'active']] options['VpcSecurityGroupIds'] = [sg['VpcSecurityGroupId'] for sg in instance['VpcSecurityGroups'] if sg['Status'] in ['adding', 'active']] options['DBParameterGroupName'] = [parameter_group['DBParameterGroupName'] for parameter_group in instance['DBParameterGroups']] - options['AllowMajorVersionUpgrade'] = None options['EnableIAMDatabaseAuthentication'] = instance['IAMDatabaseAuthenticationEnabled'] # PerformanceInsightsEnabled is not returned on older RDS instances it seems options['EnablePerformanceInsights'] = instance.get('PerformanceInsightsEnabled', False) - options['MasterUserPassword'] = None options['NewDBInstanceIdentifier'] = instance['DBInstanceIdentifier'] + # Neither of these are returned via describe_db_instances, so if either is specified during a check_mode run, changed=True + options['AllowMajorVersionUpgrade'] = None + options['MasterUserPassword'] = None + return options def get_changing_options_with_inconsistent_keys(modify_params, instance, purge_cloudwatch_logs, purge_security_groups): changing_params = {} current_options = get_current_attributes_with_inconsistent_keys(instance) - - if current_options.get("MaxAllocatedStorage") is None: - current_options["MaxAllocatedStorage"] = None - for option in current_options: current_option = current_options[option] desired_option = modify_params.pop(option, None) @@ -982,9 +1052,14 @@ def get_changing_options_with_inconsistent_keys(modify_params, instance, purge_c if desired_option in current_option: continue - if current_option == desired_option: + # Current option and desired option are the same - continue loop + if option != 'ProcessorFeatures' and current_option == desired_option: + continue + + if option == 'ProcessorFeatures' and current_option == boto3_tag_list_to_ansible_dict(desired_option, 'Name', 'Value'): continue + # Current option and desired option are different - add to changing_params list if option == 'ProcessorFeatures' and desired_option == []: changing_params['UseDefaultProcessorFeatures'] = True elif option == 'CloudwatchLogsExportConfiguration': @@ -1074,13 +1149,48 @@ def update_instance(client, module, instance, instance_id): def promote_replication_instance(client, module, instance, read_replica): changed = False if read_replica is False: - changed = bool(instance.get('ReadReplicaSourceDBInstanceIdentifier') or instance.get('StatusInfos')) - if changed: - try: - call_method(client, module, method_name='promote_read_replica', parameters={'DBInstanceIdentifier': instance['DBInstanceIdentifier']}) - changed = True - except is_boto3_error_message('DB Instance is not a read replica'): - pass + # 'StatusInfos' only exists when the instance is a read replica + # See https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-db-instances.html + if bool(instance.get('StatusInfos')): + try: + result, changed = call_method(client, module, method_name='promote_read_replica', + parameters={'DBInstanceIdentifier': instance['DBInstanceIdentifier']}) + except is_boto3_error_message('DB Instance is not a read replica'): + pass + return changed + + +def ensure_iam_roles(client, module, instance_id): + ''' + Ensure specified IAM roles are associated with DB instance + + Parameters: + client: RDS client + module: AWSModule + instance_id: DB's instance ID + + Returns: + changed (bool): True if changes were successfully made to DB instance's IAM roles; False if not + ''' + instance = camel_dict_to_snake_dict(get_instance(client, module, instance_id), ignore_list=['Tags', 'ProcessorFeatures']) + + # Ensure engine type supports associating IAM roles + engine = instance.get('engine') + if engine not in valid_engines_iam_roles: + module.fail_json(msg='DB engine {0} is not valid for adding IAM roles. Valid engines are {1}'.format(engine, valid_engines_iam_roles)) + + changed = False + purge_iam_roles = module.params.get('purge_iam_roles') + target_roles = module.params.get('iam_roles') if module.params.get('iam_roles') else [] + existing_roles = instance.get('associated_roles', []) + roles_to_add, roles_to_remove = compare_iam_roles(existing_roles, target_roles, purge_iam_roles) + if bool(roles_to_add or roles_to_remove): + changed = True + # Don't update on check_mode + if module.check_mode: + module.exit_json(changed=changed, **instance) + else: + update_iam_roles(client, module, instance_id, roles_to_add, roles_to_remove) return changed @@ -1121,6 +1231,7 @@ def main(): creation_source=dict(choices=['snapshot', 's3', 'instance']), force_update_password=dict(type='bool', default=False, no_log=False), purge_cloudwatch_logs_exports=dict(type='bool', default=True), + purge_iam_roles=dict(type='bool', default=False), purge_tags=dict(type='bool', default=True), read_replica=dict(type='bool'), wait=dict(type='bool', default=True), @@ -1154,6 +1265,7 @@ def main(): engine_version=dict(), final_db_snapshot_identifier=dict(aliases=['final_snapshot_identifier']), force_failover=dict(type='bool'), + iam_roles=dict(type='list', elements='dict'), iops=dict(type='int'), kms_key_id=dict(), license_model=dict(), @@ -1230,6 +1342,13 @@ def main(): if module.params['preferred_maintenance_window']: module.params['preferred_maintenance_window'] = module.params['preferred_maintenance_window'].lower() + # Throw warning regarding case when allow_major_version_upgrade is specified in check_mode + # describe_rds_instance never returns this value, so on check_mode, it will always return changed=True + # In non-check mode runs, changed will return the correct value, so no need to warn there. + # see: amazon.aws.module_util.rds.handle_errors. + if module.params.get('allow_major_version_upgrade') and module.check_mode: + module.warn('allow_major_version_upgrade is not returned when describing db instances, so changed will always be `True` on check mode runs.') + client = module.client('rds') changed = False state = module.params['state'] @@ -1239,17 +1358,30 @@ def main(): method_name = get_rds_method_attribute_name(instance, state, module.params['creation_source'], module.params['read_replica']) if method_name: + + # Exit on create/delete if check_mode + if module.check_mode and method_name in ['create_db_instance', 'delete_db_instance']: + module.exit_json(changed=True, **camel_dict_to_snake_dict(instance, ignore_list=['Tags', 'ProcessorFeatures'])) + raw_parameters = arg_spec_to_rds_params(dict((k, module.params[k]) for k in module.params if k in parameter_options)) - parameters = get_parameters(client, module, raw_parameters, method_name) + parameters_to_modify = get_parameters(client, module, raw_parameters, method_name) - if parameters: - result, changed = call_method(client, module, method_name, parameters) + if parameters_to_modify: + # Exit on check_mode when parameters to modify + if module.check_mode: + module.exit_json(changed=True, **camel_dict_to_snake_dict(instance, ignore_list=['Tags', 'ProcessorFeatures'])) + result, changed = call_method(client, module, method_name, parameters_to_modify) instance_id = get_final_identifier(method_name, module) - # Check tagging/promoting/rebooting/starting/stopping instance - if state != 'absent' and (not module.check_mode or instance): - changed |= update_instance(client, module, instance, instance_id) + if state != 'absent': + # Check tagging/promoting/rebooting/starting/stopping instance + if not module.check_mode or instance: + changed |= update_instance(client, module, instance, instance_id) + + # Check IAM roles + if module.params.get('iam_roles') or module.params.get('purge_iam_roles'): + changed |= ensure_iam_roles(client, module, instance_id) if changed: instance = get_instance(client, module, instance_id)
diff --git a/tests/integration/targets/rds_instance/inventory b/tests/integration/targets/rds_instance/inventory --- a/tests/integration/targets/rds_instance/inventory +++ b/tests/integration/targets/rds_instance/inventory @@ -15,6 +15,9 @@ tagging replica upgrade +# TODO: uncomment after adding iam:CreatePolicy and iam:DeletePolicy +# iam_roles + # TODO: uncomment after adding rds_cluster module # aurora diff --git a/tests/integration/targets/rds_instance/roles/rds_instance/defaults/main.yml b/tests/integration/targets/rds_instance/roles/rds_instance/defaults/main.yml --- a/tests/integration/targets/rds_instance/roles/rds_instance/defaults/main.yml +++ b/tests/integration/targets/rds_instance/roles/rds_instance/defaults/main.yml @@ -29,3 +29,7 @@ modified_processor_features: # For mariadb tests mariadb_engine_version: 10.3.31 mariadb_engine_version_2: 10.4.21 + +# For iam roles tests +postgres_db_instance_class: db.m6g.large # smallest psql instance +postgres_db_engine_version: 14.2 diff --git a/tests/integration/targets/rds_instance/roles/rds_instance/files/s3_integration_policy.json b/tests/integration/targets/rds_instance/roles/rds_instance/files/s3_integration_policy.json new file mode 100644 --- /dev/null +++ b/tests/integration/targets/rds_instance/roles/rds_instance/files/s3_integration_policy.json @@ -0,0 +1,16 @@ +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "", + "Effect": "Allow", + "Action": [ + "s3:PutObject", + "s3:GetObject", + "s3:ListBucket", + "rds:*" + ], + "Resource": "*" + } + ] +} diff --git a/tests/integration/targets/rds_instance/roles/rds_instance/files/s3_integration_trust_policy.json b/tests/integration/targets/rds_instance/roles/rds_instance/files/s3_integration_trust_policy.json new file mode 100644 --- /dev/null +++ b/tests/integration/targets/rds_instance/roles/rds_instance/files/s3_integration_trust_policy.json @@ -0,0 +1,13 @@ +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "", + "Effect": "Allow", + "Principal": { + "Service": "rds.amazonaws.com" + }, + "Action": "sts:AssumeRole" + } + ] +} diff --git a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_complex.yml b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_complex.yml --- a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_complex.yml +++ b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_complex.yml @@ -41,11 +41,59 @@ - result.changed - "result.db_instance_identifier == '{{ instance_id }}'" + - name: Add IAM roles to mariab (should fail - iam roles not supported for mariadb) + rds_instance: + id: "{{ instance_id }}" + state: present + engine: mariadb + engine_version: "{{ mariadb_engine_version }}" + allow_major_version_upgrade: true + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ db_instance_class }}" + allocated_storage: "{{ io1_allocated_storage }}" + storage_type: "{{ storage_type }}" + iops: "{{ iops }}" + iam_roles: + - role_arn: 'my_role' + feature_name: 'my_feature' + register: result + ignore_errors: True + + - assert: + that: + - result.failed + - '"is not valid for adding IAM roles" in result.msg' + # TODO: test modifying db_subnet_group_name, db_security_groups, db_parameter_group_name, option_group_name, # monitoring_role_arn, monitoring_interval, domain, domain_iam_role_name, cloudwatch_logs_export_configuration # Test multiple modifications including enabling enhanced monitoring + - name: Modify several attributes - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + allocated_storage: "{{ io1_modified_allocated_storage }}" + storage_type: "{{ storage_type }}" + db_instance_class: "{{ modified_db_instance_class }}" + backup_retention_period: 2 + preferred_backup_window: "05:00-06:00" + preferred_maintenance_window: "{{ preferred_maintenance_window }}" + auto_minor_version_upgrade: false + monitoring_interval: "{{ monitoring_interval }}" + monitoring_role_arn: "{{ enhanced_monitoring_role.arn }}" + iops: "{{ iops }}" + port: 1150 + max_allocated_storage: 150 + apply_immediately: True + register: result + check_mode: yes + + - assert: + that: + - result.changed + - name: Modify several attributes rds_instance: id: "{{ instance_id }}" @@ -74,6 +122,32 @@ - '"db_instance_class" in result.pending_modified_values or result.db_instance_class == modified_db_instance_class' - '"monitoring_interval" in result.pending_modified_values or result.monitoring_interval == monitoring_interval' + - name: Idempotence modifying several pending attributes - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + allocated_storage: "{{ io1_modified_allocated_storage }}" + storage_type: "{{ storage_type }}" + db_instance_class: "{{ modified_db_instance_class }}" + backup_retention_period: 2 + preferred_backup_window: "05:00-06:00" + preferred_maintenance_window: "{{ preferred_maintenance_window }}" + auto_minor_version_upgrade: false + monitoring_interval: "{{ monitoring_interval }}" + monitoring_role_arn: "{{ enhanced_monitoring_role.arn }}" + iops: "{{ iops }}" + port: 1150 + max_allocated_storage: 150 + register: result + retries: 30 + delay: 10 + until: result is not failed + check_mode: yes + + - assert: + that: + - not result.changed + - name: Idempotence modifying several pending attributes rds_instance: id: "{{ instance_id }}" diff --git a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_iam_roles.yml b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_iam_roles.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_iam_roles.yml @@ -0,0 +1,400 @@ +--- +- block: + - name: Ensure the resource doesn't exist + rds_instance: + id: "{{ instance_id }}" + state: absent + skip_final_snapshot: True + register: result + + - assert: + that: + - not result.changed + ignore_errors: yes + + - name: Create s3 integration policy + iam_managed_policy: + policy_name: "{{ instance_id }}-s3-policy" + policy: "{{ lookup('file','files/s3_integration_policy.json') }}" + state: present + register: s3_integration_policy + + - name: Create an s3 integration role + iam_role: + assume_role_policy_document: "{{ lookup('file','files/s3_integration_trust_policy.json') }}" + name: "{{ instance_id }}-s3-role-1" + state: present + managed_policy: "{{ s3_integration_policy.policy.arn }}" + register: s3_integration_role_1 + + - name: Create an s3 integration role + iam_role: + assume_role_policy_document: "{{ lookup('file','files/s3_integration_trust_policy.json') }}" + name: "{{ instance_id }}-s3-role-2" + state: present + managed_policy: "{{ s3_integration_policy.policy.arn }}" + register: s3_integration_role_2 + + - name: Create an s3 integration role + iam_role: + assume_role_policy_document: "{{ lookup('file','files/s3_integration_trust_policy.json') }}" + name: "{{ instance_id }}-s3-role-3" + state: present + managed_policy: "{{ s3_integration_policy.policy.arn }}" + register: s3_integration_role_3 + + # ------------------------------------------------------------------------------------------ + + - name: Create DB instance with IAM roles - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + engine: postgres + engine_version: "{{ postgres_db_engine_version }}" + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ postgres_db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + allow_major_version_upgrade: yes + iam_roles: + - role_arn: "{{ s3_integration_role_1.arn }}" + feature_name: 's3Export' + - role_arn: "{{ s3_integration_role_2.arn }}" + feature_name: 'Lambda' + - role_arn: "{{ s3_integration_role_3.arn }}" + feature_name: 's3Import' + register: result + check_mode: yes + + - assert: + that: + - result.changed + + - name: Create DB instance with IAM roles + rds_instance: + id: "{{ instance_id }}" + state: present + engine: postgres + engine_version: "{{ postgres_db_engine_version }}" + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ postgres_db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + allow_major_version_upgrade: yes + iam_roles: + - role_arn: "{{ s3_integration_role_1.arn }}" + feature_name: 's3Export' + - role_arn: "{{ s3_integration_role_2.arn }}" + feature_name: 'Lambda' + - role_arn: "{{ s3_integration_role_3.arn }}" + feature_name: 's3Import' + register: result + + - assert: + that: + - result.changed + - "result.db_instance_identifier == '{{ instance_id }}'" + - result.associated_roles | length == 3 + - "{{ 's3Export' in result.associated_roles | map(attribute='feature_name') }}" + - "{{ 'Lambda' in result.associated_roles | map(attribute='feature_name') }}" + - "{{ 's3Import' in result.associated_roles | map(attribute='feature_name') }}" + + - name: Create DB instance with IAM roles (idempotence) - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + engine: postgres + engine_version: "{{ postgres_db_engine_version }}" + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ postgres_db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + iam_roles: + - role_arn: "{{ s3_integration_role_1.arn }}" + feature_name: 's3Export' + - role_arn: "{{ s3_integration_role_2.arn }}" + feature_name: 'Lambda' + - role_arn: "{{ s3_integration_role_3.arn }}" + feature_name: 's3Import' + register: result + check_mode: yes + + - assert: + that: + - not result.changed + + - name: Create DB instance with IAM roles (idempotence) + rds_instance: + id: "{{ instance_id }}" + state: present + engine: postgres + engine_version: "{{ postgres_db_engine_version }}" + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ postgres_db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + iam_roles: + - role_arn: "{{ s3_integration_role_1.arn }}" + feature_name: 's3Export' + - role_arn: "{{ s3_integration_role_2.arn }}" + feature_name: 'Lambda' + - role_arn: "{{ s3_integration_role_3.arn }}" + feature_name: 's3Import' + register: result + + - assert: + that: + - not result.changed + - "result.db_instance_identifier == '{{ instance_id }}'" + - result.associated_roles | length == 3 + - "{{ 's3Export' in result.associated_roles | map(attribute='feature_name') }}" + - "{{ 'Lambda' in result.associated_roles | map(attribute='feature_name') }}" + - "{{ 's3Import' in result.associated_roles | map(attribute='feature_name') }}" + + - name: Create DB instance with IAM roles (idempotence) - purge roles + rds_instance: + id: "{{ instance_id }}" + state: present + engine: postgres + engine_version: "{{ postgres_db_engine_version }}" + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ postgres_db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + iam_roles: + - role_arn: "{{ s3_integration_role_1.arn }}" + feature_name: 's3Export' + - role_arn: "{{ s3_integration_role_2.arn }}" + feature_name: 'Lambda' + - role_arn: "{{ s3_integration_role_3.arn }}" + feature_name: 's3Import' + purge_iam_roles: yes + register: result + + - assert: + that: + - not result.changed + - "result.db_instance_identifier == '{{ instance_id }}'" + - result.associated_roles | length == 3 + - "{{ 's3Export' in result.associated_roles | map(attribute='feature_name') }}" + - "{{ 'Lambda' in result.associated_roles | map(attribute='feature_name') }}" + - "{{ 's3Import' in result.associated_roles | map(attribute='feature_name') }}" + + # ------------------------------------------------------------------------------------------ + + - name: Remove s3Import IAM role from db instance - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + iam_roles: + - role_arn: "{{ s3_integration_role_1.arn }}" + feature_name: 's3Export' + - role_arn: "{{ s3_integration_role_2.arn }}" + feature_name: 'Lambda' + purge_iam_roles: yes + register: result + check_mode: yes + + - assert: + that: + - result.changed + + - name: Remove s3Import IAM role from db instance + rds_instance: + id: "{{ instance_id }}" + state: present + iam_roles: + - role_arn: "{{ s3_integration_role_1.arn }}" + feature_name: 's3Export' + - role_arn: "{{ s3_integration_role_2.arn }}" + feature_name: 'Lambda' + purge_iam_roles: yes + register: result + + - assert: + that: + - result.changed + - "result.db_instance_identifier == '{{ instance_id }}'" + - result.associated_roles | length == 2 + - "{{ 's3Export' in result.associated_roles | map(attribute='feature_name') }}" + - "{{ 'Lambda' in result.associated_roles | map(attribute='feature_name') }}" + - "{{ 's3Import' not in result.associated_roles | map(attribute='feature_name') }}" + + - name: Remove s3Import IAM role from db instance (idempotence) - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + iam_roles: + - role_arn: "{{ s3_integration_role_1.arn }}" + feature_name: 's3Export' + - role_arn: "{{ s3_integration_role_2.arn }}" + feature_name: 'Lambda' + purge_iam_roles: yes + register: result + check_mode: yes + + - assert: + that: + - not result.changed + + - name: Remove s3Import IAM role from db instance (idempotence) + rds_instance: + id: "{{ instance_id }}" + state: present + iam_roles: + - role_arn: "{{ s3_integration_role_1.arn }}" + feature_name: 's3Export' + - role_arn: "{{ s3_integration_role_2.arn }}" + feature_name: 'Lambda' + purge_iam_roles: yes + register: result + + - assert: + that: + - not result.changed + - "result.db_instance_identifier == '{{ instance_id }}'" + - result.associated_roles | length == 2 + - "{{ 's3Export' in result.associated_roles | map(attribute='feature_name') }}" + - "{{ 'Lambda' in result.associated_roles | map(attribute='feature_name') }}" + - "{{ 's3Import' not in result.associated_roles | map(attribute='feature_name') }}" + + # ------------------------------------------------------------------------------------------ + + - name: Remove IAM roles from db instance - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + purge_iam_roles: yes + register: result + check_mode: yes + + - assert: + that: + - result.changed + + - name: Remove IAM roles from db instance + rds_instance: + id: "{{ instance_id }}" + state: present + purge_iam_roles: yes + register: result + + - assert: + that: + - result.changed + - "result.db_instance_identifier == '{{ instance_id }}'" + - result.associated_roles | length == 0 + + - name: Remove IAM roles from db instance (idempotence) - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + purge_iam_roles: yes + register: result + check_mode: yes + + - assert: + that: + - not result.changed + + - name: Remove IAM roles from db instance (idempotence) + rds_instance: + id: "{{ instance_id }}" + state: present + purge_iam_roles: yes + register: result + + - assert: + that: + - not result.changed + - "result.db_instance_identifier == '{{ instance_id }}'" + - result.associated_roles | length == 0 + + # ------------------------------------------------------------------------------------------ + + - name: Add IAM role to existing db instance - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + iam_roles: + - role_arn: "{{ s3_integration_role_1.arn }}" + feature_name: 's3Export' + register: result + check_mode: yes + + - assert: + that: + - result.changed + + - name: Add IAM role to existing db instance + rds_instance: + id: "{{ instance_id }}" + state: present + iam_roles: + - role_arn: "{{ s3_integration_role_1.arn }}" + feature_name: 's3Export' + register: result + + - assert: + that: + - result.changed + - "result.db_instance_identifier == '{{ instance_id }}'" + - result.associated_roles | length == 1 + - "{{ 's3Export' in result.associated_roles | map(attribute='feature_name') }}" + + - name: Add IAM role to existing db instance (idempotence) - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + iam_roles: + - role_arn: "{{ s3_integration_role_1.arn }}" + feature_name: 's3Export' + register: result + check_mode: yes + + - assert: + that: + - not result.changed + + - name: Add IAM role to existing db instance (idempotence) + rds_instance: + id: "{{ instance_id }}" + state: present + + iam_roles: + - role_arn: "{{ s3_integration_role_1.arn }}" + feature_name: 's3Export' + register: result + + - assert: + that: + - not result.changed + - "result.db_instance_identifier == '{{ instance_id }}'" + - result.associated_roles | length == 1 + - "{{ 's3Export' in result.associated_roles | map(attribute='feature_name') }}" + + always: + - name: Delete IAM policy + iam_managed_policy: + policy_name: "{{ instance_id }}-s3-policy" + state: absent + ignore_errors: yes + + - name: Delete IAM roles + iam_role: + name: "{{ item.role_name }}" + assume_role_policy_document: "{{ lookup('file','files/s3_integration_trust_policy.json') }}" + state: absent + ignore_errors: yes + with_items: + - "{{ s3_integration_role_1 }}" + - "{{ s3_integration_role_2 }}" + - "{{ s3_integration_role_3 }}" + + - name: Delete the instance + rds_instance: + id: "{{ instance_id }}" + state: absent + skip_final_snapshot: True + wait: false + ignore_errors: yes diff --git a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_modify.yml b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_modify.yml --- a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_modify.yml +++ b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_modify.yml @@ -39,6 +39,20 @@ - result.changed - "result.db_instance_identifier == '{{ instance_id }}'" + - name: Modify the instance name without immediate application - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + new_id: "{{ modified_instance_id }}" + password: "{{ password }}" + apply_immediately: False + register: result + check_mode: yes + + - assert: + that: + - result.changed + - name: Modify the instance name without immediate application rds_instance: id: "{{ instance_id }}" @@ -53,6 +67,19 @@ - result.changed - 'result.db_instance_identifier == "{{ instance_id }}"' + - name: Immediately apply the pending update - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + new_id: "{{ modified_instance_id }}" + apply_immediately: True + register: result + check_mode: yes + + - assert: + that: + - result.changed + - name: Immediately apply the pending update rds_instance: id: "{{ instance_id }}" diff --git a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_processor.yml b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_processor.yml --- a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_processor.yml +++ b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_processor.yml @@ -30,7 +30,7 @@ that: - result.changed - - name: Check mode - modify the processor features + - name: Modify the processor features - check_mode rds_instance: id: "{{ instance_id }}" state: present @@ -69,6 +69,45 @@ - 'result.pending_modified_values.processor_features.coreCount == "{{ modified_processor_features.coreCount }}"' - 'result.pending_modified_values.processor_features.threadsPerCore == "{{ modified_processor_features.threadsPerCore }}"' + - name: Modify the processor features (idempotence) - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + engine: oracle-ee + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ oracle_ee_db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + storage_encrypted: True + processor_features: "{{ modified_processor_features }}" + apply_immediately: true + register: result + check_mode: True + + - assert: + that: + - not result.changed + + - name: Modify the processor features (idempotence) + rds_instance: + id: "{{ instance_id }}" + state: present + engine: oracle-ee + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ oracle_ee_db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + storage_encrypted: True + processor_features: "{{ modified_processor_features }}" + apply_immediately: true + register: result + + - assert: + that: + - not result.changed + - 'result.pending_modified_values.processor_features.coreCount == "{{ modified_processor_features.coreCount }}"' + - 'result.pending_modified_values.processor_features.threadsPerCore == "{{ modified_processor_features.threadsPerCore }}"' + always: - name: Delete the DB instance diff --git a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_replica.yml b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_replica.yml --- a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_replica.yml +++ b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_replica.yml @@ -40,6 +40,31 @@ - source_db.changed - "source_db.db_instance_identifier == '{{ instance_id }}'" + # ------------------------------------------------------------------------------------------ + + - name: Create a read replica in a different region - check_mode + rds_instance: + id: "{{ instance_id }}-replica" + state: present + source_db_instance_identifier: "{{ instance_id }}" + engine: mysql + username: "{{ username }}" + password: "{{ password }}" + read_replica: True + db_instance_class: "{{ db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + region: "{{ region_dest }}" + tags: + Name: "{{ instance_id }}" + Created_by: Ansible rds_instance tests + wait: yes + register: result + check_mode: yes + + - assert: + that: + - result.changed + - name: Create a read replica in a different region rds_instance: id: "{{ instance_id }}-replica" @@ -66,6 +91,27 @@ - "result.tags.Name == '{{ instance_id }}'" - "result.tags.Created_by == 'Ansible rds_instance tests'" + - name: Test idempotence with a read replica - check_mode + rds_instance: + id: "{{ instance_id }}-replica" + state: present + source_db_instance_identifier: "{{ instance_id }}" + engine: mysql + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + region: "{{ region_dest }}" + tags: + Name: "{{ instance_id }}" + Created_by: Ansible rds_instance tests + register: result + check_mode: yes + + - assert: + that: + - not result.changed + - name: Test idempotence with a read replica rds_instance: id: "{{ instance_id }}-replica" @@ -82,10 +128,9 @@ Created_by: Ansible rds_instance tests register: result - ## XXX Bug - # - assert: - # that: - # - not result.changed + - assert: + that: + - not result.changed - name: Test idempotence with read_replica=True rds_instance: @@ -104,6 +149,25 @@ Created_by: Ansible rds_instance tests register: result + - assert: + that: + - not result.changed + + # ------------------------------------------------------------------------------------------ + + - name: Promote the read replica - check_mode + rds_instance: + id: "{{ instance_id }}-replica" + state: present + read_replica: False + region: "{{ region_dest }}" + register: result + check_mode: yes + + - assert: + that: + - result.changed + - name: Promote the read replica rds_instance: id: "{{ instance_id }}-replica" @@ -116,6 +180,19 @@ that: - result.changed + - name: Test idempotence - check_mode + rds_instance: + id: "{{ instance_id }}-replica" + state: present + read_replica: False + region: "{{ region_dest }}" + register: result + check_mode: yes + + - assert: + that: + - not result.changed + - name: Test idempotence rds_instance: id: "{{ instance_id }}-replica" @@ -124,10 +201,9 @@ region: "{{ region_dest }}" register: result - ## XXX Bug - #- assert: - # that: - # - not result.changed + - assert: + that: + - not result.changed always: diff --git a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_restore.yml b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_restore.yml --- a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_restore.yml +++ b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_restore.yml @@ -31,6 +31,25 @@ - source_db.changed - "source_db.db_instance_identifier == '{{ instance_id }}-s'" + - name: Create a point in time DB instance - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + source_db_instance_identifier: "{{ instance_id }}-s" + creation_source: instance + engine: mysql + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + use_latest_restorable_time: True + register: result + check_mode: yes + + - assert: + that: + result.changed + - name: Create a point in time DB instance rds_instance: id: "{{ instance_id }}" @@ -45,7 +64,30 @@ use_latest_restorable_time: True register: result - - name: Test idempotence with a point in time replica + - assert: + that: + result.changed + + - name: Create a point in time DB instance (idempotence) - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + source_db_instance_identifier: "{{ instance_id }}-s" + creation_source: instance + engine: mysql + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + restore_time: "{{ result.latest_restorable_time }}" + register: result + check_mode: yes + + - assert: + that: + - not result.changed + + - name: Create a point in time DB instance (idempotence) rds_instance: id: "{{ instance_id }}" state: present diff --git a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_sgroups.yml b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_sgroups.yml --- a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_sgroups.yml +++ b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_sgroups.yml @@ -40,8 +40,6 @@ - "{{ resource_prefix }}-sg-2" - "{{ resource_prefix }}-sg-3" - - debug: var=sgs_result - - name: Ensure the resource doesn't exist rds_instance: id: "{{ instance_id }}" @@ -54,6 +52,27 @@ - not result.changed ignore_errors: yes + # ------------------------------------------------------------------------------------------ + + - name: Create a DB instance in the VPC with two security groups - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + engine: mariadb + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + vpc_security_group_ids: + - "{{ sgs_result.results.0.group_id }}" + - "{{ sgs_result.results.1.group_id }}" + register: result + check_mode: yes + + - assert: + that: + - result.changed + - name: Create a DB instance in the VPC with two security groups rds_instance: id: "{{ instance_id }}" @@ -74,7 +93,48 @@ - "result.db_instance_identifier == '{{ instance_id }}'" - "result.vpc_security_groups | selectattr('status', 'in', ['active', 'adding']) | list | length == 2" - - name: Add a new security group without purge (check_mode) + - name: Create a DB instance in the VPC with two security groups (idempotence) - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + engine: mariadb + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + vpc_security_group_ids: + - "{{ sgs_result.results.0.group_id }}" + - "{{ sgs_result.results.1.group_id }}" + register: result + check_mode: yes + + - assert: + that: + - not result.changed + + - name: Create a DB instance in the VPC with two security groups (idempotence) + rds_instance: + id: "{{ instance_id }}" + state: present + engine: mariadb + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + vpc_security_group_ids: + - "{{ sgs_result.results.0.group_id }}" + - "{{ sgs_result.results.1.group_id }}" + register: result + + - assert: + that: + - not result.changed + - "result.db_instance_identifier == '{{ instance_id }}'" + - "result.vpc_security_groups | selectattr('status', 'in', ['active', 'adding']) | list | length == 2" + + # ------------------------------------------------------------------------------------------ + + - name: Add a new security group without purge - check_mode rds_instance: id: "{{ instance_id }}" state: present @@ -106,7 +166,23 @@ - "result.db_instance_identifier == '{{ instance_id }}'" - "result.vpc_security_groups | selectattr('status', 'in', ['active', 'adding']) | list | length == 3" - - name: Add a new security group without purge (test idempotence) + - name: Add a new security group without purge (idempotence) - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + vpc_security_group_ids: + - "{{ sgs_result.results.2.group_id }}" + apply_immediately: true + purge_security_groups: false + register: result + check_mode: yes + + - assert: + that: + - not result.changed + - "result.db_instance_identifier == '{{ instance_id }}'" + + - name: Add a new security group without purge (idempotence) rds_instance: id: "{{ instance_id }}" state: present @@ -120,6 +196,23 @@ that: - not result.changed - "result.db_instance_identifier == '{{ instance_id }}'" + - "result.vpc_security_groups | selectattr('status', 'in', ['active', 'adding']) | list | length == 3" + + # ------------------------------------------------------------------------------------------ + + - name: Add a security group with purge - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + vpc_security_group_ids: + - "{{ sgs_result.results.2.group_id }}" + apply_immediately: true + register: result + check_mode: yes + + - assert: + that: + - result.changed - name: Add a security group with purge rds_instance: @@ -137,6 +230,35 @@ - "result.vpc_security_groups | selectattr('status', 'in', ['active', 'adding']) | list | length == 1" - "result.vpc_security_groups | selectattr('status', 'equalto', 'removing') | list | length == 2" + - name: Add a security group with purge (idempotence) - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + vpc_security_group_ids: + - "{{ sgs_result.results.2.group_id }}" + apply_immediately: true + register: result + check_mode: yes + + - assert: + that: + - not result.changed + + - name: Add a security group with purge (idempotence) + rds_instance: + id: "{{ instance_id }}" + state: present + vpc_security_group_ids: + - "{{ sgs_result.results.2.group_id }}" + apply_immediately: true + register: result + + - assert: + that: + - not result.changed + - "result.db_instance_identifier == '{{ instance_id }}'" + - "result.vpc_security_groups | selectattr('status', 'in', ['active', 'adding']) | list | length == 1" + always: - name: Ensure the resource doesn't exist diff --git a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_states.yml b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_states.yml --- a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_states.yml +++ b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_states.yml @@ -12,6 +12,28 @@ - not result.changed ignore_errors: yes + + # ------------------------------------------------------------------------------------------ + + - name: Create a mariadb instance - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + engine: mariadb + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + tags: + Name: "{{ instance_id }}" + Created_by: Ansible rds_instance tests + register: result + check_mode: yes + + - assert: + that: + - result.changed + - name: Create a mariadb instance rds_instance: id: "{{ instance_id }}" @@ -34,8 +56,51 @@ - "result.tags.Name == '{{ instance_id }}'" - "result.tags.Created_by == 'Ansible rds_instance tests'" + - name: Create a mariadb instance (idempotence) - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + engine: mariadb + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + tags: + Name: "{{ instance_id }}" + Created_by: Ansible rds_instance tests + register: result + check_mode: yes + + - assert: + that: + - not result.changed + + - name: Create a mariadb instance (idempotence) + rds_instance: + id: "{{ instance_id }}" + state: present + engine: mariadb + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + tags: + Name: "{{ instance_id }}" + Created_by: Ansible rds_instance tests + register: result + + - assert: + that: + - not result.changed + - "result.db_instance_identifier == '{{ instance_id }}'" + - "result.tags | length == 2" + - "result.tags.Name == '{{ instance_id }}'" + - "result.tags.Created_by == 'Ansible rds_instance tests'" + + # ------------------------------------------------------------------------------------------ # Test stopping / rebooting instances - - name: Check mode - reboot a stopped instance + + - name: Reboot a stopped instance - check_mode rds_instance: id: "{{ instance_id }}" state: rebooted @@ -56,7 +121,9 @@ that: - result.changed - - name: Check Mode - stop the instance + # ------------------------------------------------------------------------------------------ + + - name: Stop the instance - check_mode rds_instance: id: "{{ instance_id }}" state: stopped @@ -77,7 +144,7 @@ that: - result.changed - - name: Check Mode - idempotence + - name: Stop the instance (idempotence) - check_mode rds_instance: id: "{{ instance_id }}" state: stopped @@ -88,7 +155,7 @@ that: - not result.changed - - name: Idempotence + - name: Stop the instance (idempotence) rds_instance: id: "{{ instance_id }}" state: stopped @@ -98,7 +165,9 @@ that: - not result.changed - - name: Check Mode - start the instance + # ------------------------------------------------------------------------------------------ + + - name: Start the instance - check_mode rds_instance: id: "{{ instance_id }}" state: started @@ -119,6 +188,93 @@ that: - result.changed + - name: Start the instance (idempotence) - check_mode + rds_instance: + id: "{{ instance_id }}" + state: started + register: result + check_mode: yes + + - assert: + that: + - not result.changed + + - name: Start the instance (idempotence) + rds_instance: + id: "{{ instance_id }}" + state: started + register: result + + - assert: + that: + - not result.changed + + # ------------------------------------------------------------------------------------------ + + - name: Ensure instance exists prior to deleting + rds_instance_info: + db_instance_identifier: '{{ instance_id }}' + register: db_info + + - assert: + that: + - db_info.instances | length == 1 + + - name: Delete the instance - check_mode + rds_instance: + id: "{{ instance_id }}" + state: absent + skip_final_snapshot: True + register: result + check_mode: yes + + - assert: + that: + - result.changed + + - name: Delete the instance + rds_instance: + id: "{{ instance_id }}" + state: absent + skip_final_snapshot: True + register: result + + - assert: + that: + - result.changed + + - name: Ensure instance was deleted + rds_instance_info: + db_instance_identifier: '{{ instance_id }}' + register: db_info + + - assert: + that: + - db_info.instances | length == 0 + + - name: Delete the instance (idempotence) - check_mode + rds_instance: + id: "{{ instance_id }}" + state: absent + skip_final_snapshot: True + register: result + check_mode: yes + + - assert: + that: + - not result.changed + + - name: Delete the instance (idempotence) + rds_instance: + id: "{{ instance_id }}" + state: absent + skip_final_snapshot: True + register: result + + - assert: + that: + - not result.changed + always: - name: Remove DB instance rds_instance: diff --git a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_tagging.yml b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_tagging.yml --- a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_tagging.yml +++ b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_tagging.yml @@ -56,6 +56,22 @@ - result.kms_key_id - result.storage_encrypted == true + - name: Test impotency omitting tags - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + engine: mariadb + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + register: result + check_mode: yes + + - assert: + that: + - not result.changed + - name: Test impotency omitting tags rds_instance: id: "{{ instance_id }}" @@ -103,6 +119,21 @@ - not result.changed - "result.tags | length == 2" + - name: Add a tag and remove a tag - check_mode + rds_instance: + db_instance_identifier: "{{ instance_id }}" + state: present + tags: + Name: "{{ instance_id }}-new" + Created_by: Ansible rds_instance tests + purge_tags: True + register: result + check_mode: yes + + - assert: + that: + - result.changed + - name: Add a tag and remove a tag rds_instance: db_instance_identifier: "{{ instance_id }}" @@ -119,6 +150,37 @@ - "result.tags | length == 2" - "result.tags.Name == '{{ instance_id }}-new'" + - name: Add a tag and remove a tag (idempotence) - check_mode + rds_instance: + db_instance_identifier: "{{ instance_id }}" + state: present + tags: + Name: "{{ instance_id }}-new" + Created_by: Ansible rds_instance tests + purge_tags: True + register: result + check_mode: yes + + - assert: + that: + - not result.changed + + - name: Add a tag and remove a tag (idempotence) + rds_instance: + db_instance_identifier: "{{ instance_id }}" + state: present + tags: + Name: "{{ instance_id }}-new" + Created_by: Ansible rds_instance tests + purge_tags: True + register: result + + - assert: + that: + - not result.changed + - "result.tags | length == 2" + - "result.tags.Name == '{{ instance_id }}-new'" + # Test final snapshot on deletion - name: Delete the DB instance rds_instance: diff --git a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_upgrade.yml b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_upgrade.yml --- a/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_upgrade.yml +++ b/tests/integration/targets/rds_instance/roles/rds_instance/tasks/test_upgrade.yml @@ -32,7 +32,26 @@ # Test upgrade of DB instance - - name: Uprade a mariadb instance + - name: Upgrade a mariadb instance - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + engine: mariadb + engine_version: "{{ mariadb_engine_version_2 }}" + allow_major_version_upgrade: true + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + apply_immediately: True + register: result + check_mode: yes + + - assert: + that: + - result.changed + + - name: Upgrade a mariadb instance rds_instance: id: "{{ instance_id }}" state: present @@ -51,7 +70,30 @@ - result.changed - '"engine_version" in result.pending_modified_values or result.engine_version == mariadb_engine_version_2' - - name: Idempotence uprading a mariadb instance + - name: Idempotence upgrading a mariadb instance - check_mode + rds_instance: + id: "{{ instance_id }}" + state: present + engine: mariadb + engine_version: "{{ mariadb_engine_version_2 }}" + allow_major_version_upgrade: true + username: "{{ username }}" + password: "{{ password }}" + db_instance_class: "{{ db_instance_class }}" + allocated_storage: "{{ allocated_storage }}" + register: result + retries: 30 + delay: 10 + until: result is not failed + check_mode: yes + + ### Specifying allow_major_version_upgrade with check_mode will always result in changed=True + ### since it's not returned in describe_db_instances api call + # - assert: + # that: + # - not result.changed + + - name: Idempotence upgrading a mariadb instance rds_instance: id: "{{ instance_id }}" state: present
rds_instance - Broken check_mode and idempotence ### Summary When adding integration tests for adding iam_roles support for rds_instance, I noticed check_mode tests fail on idempotence checks, as well as some other checks like adding sgs on check_mode, etc. ### Issue Type Bug Report ### Component Name rds_instance ### Ansible Version ```console (paste below) $ ansible --version ``` ### Collection Versions ```console (paste below) $ ansible-galaxy collection list ``` ### AWS SDK versions ```console (paste below) $ pip show boto boto3 botocore ``` ### Configuration ```console (paste below) $ ansible-config dump --only-changed ``` ### OS / Environment _No response_ ### Steps to Reproduce <!--- Paste example playbooks or commands between quotes below --> ```yaml (paste below) - name: Create DB instance with IAM roles (idempotence) - check_mode rds_instance: id: "{{ instance_id }}" state: present engine: postgres engine_version: "{{ postgres_db_engine_version }}" username: "{{ username }}" password: "{{ password }}" db_instance_class: "{{ postgres_db_instance_class }}" allocated_storage: "{{ allocated_storage }}" allow_major_version_upgrade: yes iam_roles: - role_arn: "{{ s3_integration_role_1.arn }}" feature_name: 's3Export' - role_arn: "{{ s3_integration_role_2.arn }}" feature_name: 'Lambda' - role_arn: "{{ s3_integration_role_3.arn }}" feature_name: 's3Import' register: result check_mode: yes - assert: that: - not result.changed ``` ### Expected Results expected check_mode to not modify anything and return the correct `changed` ### Actual Results in idempotence tests, check_mode returned `changed = True`. When adding sg on check_mode, the sgs were actually added. ### Code of Conduct - [X] I agree to follow the Ansible Code of Conduct
Files identified in the description: * [`plugins/modules/rds_instance.py`](https://github.com/['ansible-collections/amazon.aws', 'ansible-collections/community.aws', 'ansible-collections/community.vmware']/blob/main/plugins/modules/rds_instance.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @jillr @markuman @s-hertel @tremble [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> @markuman @alinabuzachis I found the issue to be with the `allow_major_version_upgrade` parameter. I now see that it's never returned by `describe_db_instance`, so I guess idempotency wont hold in this case. same with the `master_user_password` it seems.
2022-04-12T04:53:45
ansible-collections/community.aws
1,078
ansible-collections__community.aws-1078
[ "210" ]
872f6e31ee822d09e62f2e24357a68e0387fa4e9
diff --git a/plugins/modules/rds_instance_snapshot.py b/plugins/modules/rds_instance_snapshot.py --- a/plugins/modules/rds_instance_snapshot.py +++ b/plugins/modules/rds_instance_snapshot.py @@ -32,15 +32,37 @@ type: str db_instance_identifier: description: - - Database instance identifier. Required when state is present. + - Database instance identifier. Required when creating a snapshot. aliases: - instance_id type: str + source_db_snapshot_identifier: + description: + - The identifier of the source DB snapshot. + - Required when copying a snapshot. + - If the source snapshot is in the same AWS region as the copy, specify the snapshot's identifier. + - If the source snapshot is in a different AWS region as the copy, specify the snapshot's ARN. + aliases: + - source_id + - source_snapshot_id + type: str + version_added: 3.3.0 + source_region: + description: + - The region that contains the snapshot to be copied. + type: str + version_added: 3.3.0 + copy_tags: + description: + - Whether to copy all tags from I(source_db_snapshot_identifier) to I(db_instance_identifier). + type: bool + default: False + version_added: 3.3.0 wait: description: - Whether or not to wait for snapshot creation or deletion. type: bool - default: 'no' + default: False wait_timeout: description: - how long before wait gives up, in seconds. @@ -52,13 +74,14 @@ type: dict purge_tags: description: - - whether to remove tags not present in the C(tags) parameter. + - whether to remove tags not present in the I(tags) parameter. default: True type: bool author: - "Will Thames (@willthames)" - "Michael De La Rue (@mikedlr)" - "Alina Buzachis (@alinabuzachis)" + - "Joseph Torcasso (@jatorcasso)" extends_documentation_fragment: - amazon.aws.aws - amazon.aws.ec2 @@ -70,6 +93,15 @@ community.aws.rds_instance_snapshot: db_instance_identifier: new-database db_snapshot_identifier: new-database-snapshot + register: snapshot + +- name: Copy snapshot from a different region and copy its tags + community.aws.rds_instance_snapshot: + id: new-database-snapshot-copy + region: us-east-1 + source_id: "{{ snapshot.db_snapshot_arn }}" + source_region: us-east-2 + copy_tags: yes - name: Delete snapshot community.aws.rds_instance_snapshot: @@ -163,6 +195,12 @@ returned: always type: list sample: [] +source_db_snapshot_identifier: + description: The DB snapshot ARN that the DB snapshot was copied from. + returned: when snapshot is a copy + type: str + sample: arn:aws:rds:us-west-2:123456789012:snapshot:ansible-test-16638696-test-snapshot-source + version_added: 3.3.0 snapshot_create_time: description: Creation time of the snapshot. returned: always @@ -202,31 +240,41 @@ # import module snippets from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule +from ansible_collections.amazon.aws.plugins.module_utils.core import get_boto3_client_method_parameters from ansible_collections.amazon.aws.plugins.module_utils.core import is_boto3_error_code +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import ansible_dict_to_boto3_tag_list from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AWSRetry from ansible_collections.amazon.aws.plugins.module_utils.ec2 import camel_dict_to_snake_dict -from ansible_collections.amazon.aws.plugins.module_utils.ec2 import ansible_dict_to_boto3_tag_list -from ansible_collections.amazon.aws.plugins.module_utils.rds import get_tags -from ansible_collections.amazon.aws.plugins.module_utils.rds import ensure_tags +from ansible_collections.amazon.aws.plugins.module_utils.rds import arg_spec_to_rds_params from ansible_collections.amazon.aws.plugins.module_utils.rds import call_method +from ansible_collections.amazon.aws.plugins.module_utils.rds import ensure_tags +from ansible_collections.amazon.aws.plugins.module_utils.rds import get_rds_method_attribute +from ansible_collections.amazon.aws.plugins.module_utils.rds import get_tags def get_snapshot(snapshot_id): try: - response = client.describe_db_snapshots(DBSnapshotIdentifier=snapshot_id) - except is_boto3_error_code("DBSnapshotNotFoundFault"): - return None - except is_boto3_error_code("DBSnapshotNotFound"): # pylint: disable=duplicate-except - return None + snapshot = client.describe_db_snapshots(DBSnapshotIdentifier=snapshot_id)['DBSnapshots'][0] + snapshot['Tags'] = get_tags(client, module, snapshot['DBSnapshotArn']) + except is_boto3_error_code("DBSnapshotNotFound"): + return {} except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: # pylint: disable=duplicate-except module.fail_json_aws(e, msg="Couldn't get snapshot {0}".format(snapshot_id)) - return response['DBSnapshots'][0] + return snapshot -def fetch_tags(snapshot): - snapshot["Tags"] = get_tags(client, module, snapshot["DBSnapshotArn"]) +def get_parameters(parameters, method_name): + if method_name == 'copy_db_snapshot': + parameters['TargetDBSnapshotIdentifier'] = module.params['db_snapshot_identifier'] - return camel_dict_to_snake_dict(snapshot, ignore_list=["Tags"]) + required_options = get_boto3_client_method_parameters(client, method_name, required=True) + if any(parameters.get(k) is None for k in required_options): + module.fail_json(msg='To {0} requires the parameters: {1}'.format( + get_rds_method_attribute(method_name, module).operation_description, required_options)) + options = get_boto3_client_method_parameters(client, method_name) + parameters = dict((k, v) for k, v in parameters.items() if k in options and v is not None) + + return parameters def ensure_snapshot_absent(): @@ -236,40 +284,68 @@ def ensure_snapshot_absent(): snapshot = get_snapshot(snapshot_name) if not snapshot: - return dict(changed=changed) + module.exit_json(changed=changed) elif snapshot and snapshot["Status"] != "deleting": snapshot, changed = call_method(client, module, "delete_db_snapshot", params) - return dict(changed=changed) + module.exit_json(changed=changed) -def ensure_snapshot_present(): - db_instance_identifier = module.params.get('db_instance_identifier') +def ensure_snapshot_present(params): + source_id = module.params.get('source_db_snapshot_identifier') snapshot_name = module.params.get('db_snapshot_identifier') changed = False snapshot = get_snapshot(snapshot_name) + + # Copy snapshot + if source_id: + changed |= copy_snapshot(params) + + # Create snapshot + elif not snapshot: + changed |= create_snapshot(params) + + # Snapshot exists and we're not creating a copy - modify exising snapshot + else: + changed |= modify_snapshot() + + snapshot = get_snapshot(snapshot_name) + module.exit_json(changed=changed, **camel_dict_to_snake_dict(snapshot, ignore_list=['Tags'])) + + +def create_snapshot(params): + method_params = get_parameters(params, 'create_db_snapshot') + if method_params.get('Tags'): + method_params['Tags'] = ansible_dict_to_boto3_tag_list(method_params['Tags']) + snapshot, changed = call_method(client, module, 'create_db_snapshot', method_params) + + return changed + + +def copy_snapshot(params): + changed = False + snapshot_id = module.params.get('db_snapshot_identifier') + snapshot = get_snapshot(snapshot_id) + if not snapshot: - params = { - "DBSnapshotIdentifier": snapshot_name, - "DBInstanceIdentifier": db_instance_identifier - } - if module.params.get("tags"): - params['Tags'] = ansible_dict_to_boto3_tag_list(module.params.get("tags")) - _result, changed = call_method(client, module, "create_db_snapshot", params) + method_params = get_parameters(params, 'copy_db_snapshot') + if method_params.get('Tags'): + method_params['Tags'] = ansible_dict_to_boto3_tag_list(method_params['Tags']) + result, changed = call_method(client, module, 'copy_db_snapshot', method_params) - if module.check_mode: - return dict(changed=changed) + return changed - return dict(changed=changed, **fetch_tags(get_snapshot(snapshot_name))) - existing_tags = get_tags(client, module, snapshot["DBSnapshotArn"]) - changed |= ensure_tags(client, module, snapshot["DBSnapshotArn"], existing_tags, - module.params["tags"], module.params["purge_tags"]) +def modify_snapshot(): + # TODO - add other modifications aside from purely tags + changed = False + snapshot_id = module.params.get('db_snapshot_identifier') + snapshot = get_snapshot(snapshot_id) - if module.check_mode: - return dict(changed=changed) + if module.params.get('tags'): + changed |= ensure_tags(client, module, snapshot['DBSnapshotArn'], snapshot['Tags'], module.params['tags'], module.params['purge_tags']) - return dict(changed=changed, **fetch_tags(get_snapshot(snapshot_name))) + return changed def main(): @@ -280,16 +356,18 @@ def main(): state=dict(choices=['present', 'absent'], default='present'), db_snapshot_identifier=dict(aliases=['id', 'snapshot_id'], required=True), db_instance_identifier=dict(aliases=['instance_id']), + source_db_snapshot_identifier=dict(aliases=['source_id', 'source_snapshot_id']), wait=dict(type='bool', default=False), wait_timeout=dict(type='int', default=300), tags=dict(type='dict'), purge_tags=dict(type='bool', default=True), + copy_tags=dict(type='bool', default=False), + source_region=dict(type='str'), ) module = AnsibleAWSModule( argument_spec=argument_spec, - required_if=[['state', 'present', ['db_instance_identifier']]], - supports_check_mode=True, + supports_check_mode=True ) retry_decorator = AWSRetry.jittered_backoff(retries=10) @@ -298,12 +376,13 @@ def main(): except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: module.fail_json_aws(e, msg="Failed to connect to AWS.") - if module.params['state'] == 'absent': - ret_dict = ensure_snapshot_absent() - else: - ret_dict = ensure_snapshot_present() + state = module.params.get("state") + if state == 'absent': + ensure_snapshot_absent() - module.exit_json(**ret_dict) + elif state == 'present': + params = arg_spec_to_rds_params(dict((k, module.params[k]) for k in module.params if k in argument_spec)) + ensure_snapshot_present(params) if __name__ == '__main__':
diff --git a/tests/integration/targets/rds_instance_snapshot/defaults/main.yml b/tests/integration/targets/rds_instance_snapshot/defaults/main.yml --- a/tests/integration/targets/rds_instance_snapshot/defaults/main.yml +++ b/tests/integration/targets/rds_instance_snapshot/defaults/main.yml @@ -2,13 +2,13 @@ # defaults file for rds_instance_snapshot # Create RDS instance -instance_id: 'ansible-test-instance-{{ resource_prefix }}' +instance_id: '{{ resource_prefix }}-instance' username: 'testrdsusername' -password: 'test-rds_password' +password: "{{ lookup('password', '/dev/null') }}" db_instance_class: db.t3.micro allocated_storage: 10 engine: 'mariadb' mariadb_engine_version: 10.3.31 # Create snapshot -snapshot_id: 'ansible-test-instance-snapshot-{{ resource_prefix }}' +snapshot_id: '{{ instance_id }}-snapshot' diff --git a/tests/integration/targets/rds_instance_snapshot/tasks/main.yml b/tests/integration/targets/rds_instance_snapshot/tasks/main.yml --- a/tests/integration/targets/rds_instance_snapshot/tasks/main.yml +++ b/tests/integration/targets/rds_instance_snapshot/tasks/main.yml @@ -27,12 +27,12 @@ that: - _result_create_instance.changed - _result_create_instance.db_instance_identifier == "{{ instance_id }}" - + - name: Get all RDS snapshots for the existing instance rds_snapshot_info: db_instance_identifier: "{{ instance_id }}" register: _result_instance_snapshot_info - + - assert: that: - _result_instance_snapshot_info is successful @@ -49,7 +49,7 @@ - assert: that: - _result_instance_snapshot.changed - + - name: Take a snapshot of the existing RDS instance rds_instance_snapshot: state: present @@ -89,18 +89,70 @@ - _result_instance_snapshot.storage_type == "gp2" - "'tags' in _result_instance_snapshot" - "'vpc_id' in _result_instance_snapshot" - + + - name: Take a snapshot of the existing RDS instance (CHECK_MODE - IDEMPOTENCE) + rds_instance_snapshot: + state: present + db_instance_identifier: "{{ instance_id }}" + db_snapshot_identifier: "{{ snapshot_id }}" + check_mode: yes + register: _result_instance_snapshot + + - assert: + that: + - not _result_instance_snapshot.changed + + - name: Take a snapshot of the existing RDS instance (IDEMPOTENCE) + rds_instance_snapshot: + state: present + db_instance_identifier: "{{ instance_id }}" + db_snapshot_identifier: "{{ snapshot_id }}" + wait: true + register: _result_instance_snapshot + + - assert: + that: + - not _result_instance_snapshot.changed + - "'availability_zone' in _result_instance_snapshot" + - "'instance_create_time' in _result_instance_snapshot" + - "'db_instance_identifier' in _result_instance_snapshot" + - _result_instance_snapshot.db_instance_identifier == "{{ instance_id }}" + - "'db_snapshot_identifier' in _result_instance_snapshot" + - _result_instance_snapshot.db_snapshot_identifier == "{{ snapshot_id }}" + - "'db_snapshot_arn' in _result_instance_snapshot" + - "'dbi_resource_id' in _result_instance_snapshot" + - "'encrypted' in _result_instance_snapshot" + - "'engine' in _result_instance_snapshot" + - _result_instance_snapshot.engine == "{{ engine }}" + - "'engine_version' in _result_instance_snapshot" + - _result_instance_snapshot.engine_version == "{{ mariadb_engine_version }}" + - "'iam_database_authentication_enabled' in _result_instance_snapshot" + - "'license_model' in _result_instance_snapshot" + - "'master_username' in _result_instance_snapshot" + - _result_instance_snapshot.master_username == "{{ username }}" + - "'snapshot_create_time' in _result_instance_snapshot" + - "'snapshot_type' in _result_instance_snapshot" + - "'status' in _result_instance_snapshot" + - _result_instance_snapshot.status == "available" + - "'snapshot_type' in _result_instance_snapshot" + - _result_instance_snapshot.snapshot_type == "manual" + - "'status' in _result_instance_snapshot" + - "'storage_type' in _result_instance_snapshot" + - _result_instance_snapshot.storage_type == "gp2" + - "'tags' in _result_instance_snapshot" + - "'vpc_id' in _result_instance_snapshot" + - name: Get information about the existing DB snapshot rds_snapshot_info: db_snapshot_identifier: "{{ snapshot_id }}" register: _result_instance_snapshot_info - + - assert: that: - _result_instance_snapshot_info is successful - _result_instance_snapshot_info.snapshots[0].db_instance_identifier == "{{ instance_id }}" - _result_instance_snapshot_info.snapshots[0].db_snapshot_identifier == "{{ snapshot_id }}" - + - name: Take another snapshot of the existing RDS instance rds_instance_snapshot: state: present @@ -140,38 +192,59 @@ - _result_instance_snapshot.storage_type == "gp2" - "'tags' in _result_instance_snapshot" - "'vpc_id' in _result_instance_snapshot" - + - name: Get all snapshots for the existing RDS instance rds_snapshot_info: db_instance_identifier: "{{ instance_id }}" register: _result_instance_snapshot_info - + - assert: that: - _result_instance_snapshot_info is successful #- _result_instance_snapshot_info.cluster_snapshots | length == 3 - + - name: Delete existing DB instance snapshot (CHECK_MODE) rds_instance_snapshot: state: absent db_snapshot_identifier: "{{ snapshot_id }}-b" register: _result_delete_snapshot check_mode: yes - + - assert: that: - _result_delete_snapshot.changed - + - name: Delete the existing DB instance snapshot rds_instance_snapshot: state: absent db_snapshot_identifier: "{{ snapshot_id }}-b" register: _result_delete_snapshot - + - assert: that: - _result_delete_snapshot.changed - + + - name: Delete existing DB instance snapshot (CHECK_MODE - IDEMPOTENCE) + rds_instance_snapshot: + state: absent + db_snapshot_identifier: "{{ snapshot_id }}-b" + register: _result_delete_snapshot + check_mode: yes + + - assert: + that: + - not _result_delete_snapshot.changed + + - name: Delete the existing DB instance snapshot (IDEMPOTENCE) + rds_instance_snapshot: + state: absent + db_snapshot_identifier: "{{ snapshot_id }}-b" + register: _result_delete_snapshot + + - assert: + that: + - not _result_delete_snapshot.changed + - name: Take another snapshot of the existing RDS instance and assign tags rds_instance_snapshot: state: present @@ -217,7 +290,7 @@ - _result_instance_snapshot.tags["tag_one"] == "{{ snapshot_id }}-b One" - _result_instance_snapshot.tags["Tag Two"] == "two {{ snapshot_id }}-b" - "'vpc_id' in _result_instance_snapshot" - + - name: Attempt to take another snapshot of the existing RDS instance and assign tags (idempotence) rds_instance_snapshot: state: present @@ -232,7 +305,7 @@ - assert: that: - not _result_instance_snapshot.changed - + - name: Take another snapshot of the existing RDS instance and update tags rds_instance_snapshot: state: present @@ -277,7 +350,7 @@ - _result_instance_snapshot.tags["tag_three"] == "{{ snapshot_id }}-b Three" - _result_instance_snapshot.tags["Tag Two"] == "two {{ snapshot_id }}-b" - "'vpc_id' in _result_instance_snapshot" - + - name: Take another snapshot of the existing RDS instance and update tags without purge rds_instance_snapshot: state: present @@ -323,7 +396,7 @@ - _result_instance_snapshot.tags["Tag Two"] == "two {{ snapshot_id }}-b" - _result_instance_snapshot.tags["tag_three"] == "{{ snapshot_id }}-b Three" - "'vpc_id' in _result_instance_snapshot" - + - name: Take another snapshot of the existing RDS instance and do not specify any tag to ensure previous tags are not removed rds_instance_snapshot: state: present @@ -334,25 +407,99 @@ - assert: that: - not _result_instance_snapshot.changed - - always: + + # ------------------------------------------------------------------------------------------ + # Test copying a snapshot + ### Note - copying a snapshot from a different region is supported, but not in CI runs, + ### because the aws-terminator only terminates resources in one region. + + - set_fact: + _snapshot_arn: "{{ _result_instance_snapshot.db_snapshot_arn }}" + + - name: Copy a snapshot (check mode) + rds_instance_snapshot: + id: "{{ snapshot_id }}-copy" + source_id: "{{ snapshot_id }}-b" + copy_tags: yes + wait: true + register: _result_instance_snapshot + check_mode: yes + + - assert: + that: + - _result_instance_snapshot.changed + + - name: Copy a snapshot + rds_instance_snapshot: + id: "{{ snapshot_id }}-copy" + source_id: "{{ snapshot_id }}-b" + copy_tags: yes + wait: true + register: _result_instance_snapshot + + - assert: + that: + - _result_instance_snapshot.changed + - _result_instance_snapshot.db_instance_identifier == "{{ instance_id }}" + - _result_instance_snapshot.source_db_snapshot_identifier == "{{ _snapshot_arn }}" + - _result_instance_snapshot.db_snapshot_identifier == "{{ snapshot_id }}-copy" + - "'tags' in _result_instance_snapshot" + - _result_instance_snapshot.tags | length == 3 + - _result_instance_snapshot.tags["tag_one"] == "{{ snapshot_id }}-b One" + - _result_instance_snapshot.tags["Tag Two"] == "two {{ snapshot_id }}-b" + - _result_instance_snapshot.tags["tag_three"] == "{{ snapshot_id }}-b Three" + + - name: Copy a snapshot (idempotence - check mode) + rds_instance_snapshot: + id: "{{ snapshot_id }}-copy" + source_id: "{{ snapshot_id }}-b" + copy_tags: yes + wait: true + register: _result_instance_snapshot + check_mode: yes + + - assert: + that: + - not _result_instance_snapshot.changed + + - name: Copy a snapshot (idempotence) + rds_instance_snapshot: + id: "{{ snapshot_id }}-copy" + source_id: "{{ snapshot_id }}-b" + copy_tags: yes + wait: true + register: _result_instance_snapshot + + - assert: + that: + - not _result_instance_snapshot.changed + - _result_instance_snapshot.db_instance_identifier == "{{ instance_id }}" + - _result_instance_snapshot.source_db_snapshot_identifier == "{{ _snapshot_arn }}" + - _result_instance_snapshot.db_snapshot_identifier == "{{ snapshot_id }}-copy" + - "'tags' in _result_instance_snapshot" + - _result_instance_snapshot.tags | length == 3 + - _result_instance_snapshot.tags["tag_one"] == "{{ snapshot_id }}-b One" + - _result_instance_snapshot.tags["Tag Two"] == "two {{ snapshot_id }}-b" + - _result_instance_snapshot.tags["tag_three"] == "{{ snapshot_id }}-b Three" + + always: - name: Delete the existing DB instance snapshots rds_instance_snapshot: state: absent db_snapshot_identifier: "{{ item }}" + wait: false register: _result_delete_snapshot ignore_errors: true loop: - "{{ snapshot_id }}" - "{{ snapshot_id }}-b" + - "{{ snapshot_id }}-copy" - name: Delete the existing RDS instance without creating a final snapshot rds_instance: state: absent - instance_id: "{{ item }}" + instance_id: "{{ instance_id }}" skip_final_snapshot: True + wait: false register: _result_delete_instance ignore_errors: true - loop: - - "{{ instance_id }}" - - "{{ instance_id }}-b"
Extend rds module to allow copying of rds snaphots cross region <!--- Verify first that your feature was not already discussed on GitHub --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Describe the new feature/improvement briefly below --> Extend to allow module to copy an rds snapshot to another region. ##### ISSUE TYPE - Feature Idea ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> rds_instance rds ##### ADDITIONAL INFORMATION <!--- Describe how the feature would be used, why it is needed and what it would solve --> During automated backups of databases, copy rds snapshot to different region for backup redundancy and ensure availability of rds instance. <!--- Paste example playbooks or commands between quotes below --> ```yaml ``` <!--- HINT: You can also paste gist.github.com links for larger files -->
Files identified in the description: * [`plugins/modules/rds.py`](https://github.com/ansible-collections/community.aws/blob/main/plugins/modules/rds.py) * [`plugins/modules/rds_instance.py`](https://github.com/ansible-collections/community.aws/blob/main/plugins/modules/rds_instance.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @jillr @s-hertel @tremble @willthames @wimnat [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> Files identified in the description: * [`plugins/modules/rds_instance.py`](https://github.com/['ansible-collections/amazon.aws', 'ansible-collections/community.aws', 'ansible-collections/community.vmware']/blob/main/plugins/modules/rds_instance.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @markuman [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> @markuman @alinabuzachis I would assume this functionality should be added to `rds_instance_snapshot` ? > @markuman @alinabuzachis I would assume this functionality should be added to `rds_instance_snapshot` ? Sounds good to me.
2022-04-19T20:50:58
ansible-collections/community.aws
1,085
ansible-collections__community.aws-1085
[ "1084" ]
4f989bdd5578373f97ce31008f50a15c825af5ef
diff --git a/plugins/modules/s3_lifecycle.py b/plugins/modules/s3_lifecycle.py --- a/plugins/modules/s3_lifecycle.py +++ b/plugins/modules/s3_lifecycle.py @@ -485,15 +485,23 @@ def create_lifecycle_rule(client, module): _changed = changed _retries = 10 - while wait and _changed and _retries: + _not_changed_cnt = 6 + while wait and _changed and _retries and _not_changed_cnt: # We've seen examples where get_bucket_lifecycle_configuration returns - # the updated rules, then the old rules, then the updated rules again, + # the updated rules, then the old rules, then the updated rules again and + # again couple of times. + # Thus try to read the rule few times in a row to check if it has changed. time.sleep(5) _retries -= 1 new_rules = fetch_rules(client, module, name) (_changed, lifecycle_configuration) = compare_and_update_configuration(client, module, new_rules, new_rule) + if not _changed: + _not_changed_cnt -= 1 + _changed = True + else: + _not_changed_cnt = 6 new_rules = fetch_rules(client, module, name) @@ -531,13 +539,21 @@ def destroy_lifecycle_rule(client, module): _changed = changed _retries = 10 - while wait and _changed and _retries: + _not_changed_cnt = 6 + while wait and _changed and _retries and _not_changed_cnt: # We've seen examples where get_bucket_lifecycle_configuration returns - # the updated rules, then the old rules, then the updated rules again, + # the updated rules, then the old rules, then the updated rules again and + # again couple of times. + # Thus try to read the rule few times in a row to check if it has changed. time.sleep(5) _retries -= 1 new_rules = fetch_rules(client, module, name) (_changed, lifecycle_configuration) = compare_and_remove_rule(new_rules, rule_id, prefix) + if not _changed: + _not_changed_cnt -= 1 + _changed = True + else: + _not_changed_cnt = 6 new_rules = fetch_rules(client, module, name)
diff --git a/tests/integration/targets/s3_lifecycle/tasks/main.yml b/tests/integration/targets/s3_lifecycle/tasks/main.yml --- a/tests/integration/targets/s3_lifecycle/tasks/main.yml +++ b/tests/integration/targets/s3_lifecycle/tasks/main.yml @@ -24,6 +24,42 @@ - output.changed - output.name == bucket_name - not output.requester_pays + # ============================================================ + - name: Create a number of policies and check if all of them are created + community.aws.s3_lifecycle: + name: "{{ bucket_name }}" + rule_id: "{{ item }}" + expiration_days: 10 + prefix: "{{ item }}" + status: enabled + state: present + wait: yes + register: output + loop: + - rule_1 + - rule_2 + - rule_3 + - assert: + that: + - (output.results | last).rules | length == 3 + # ============================================================ + - name: Remove previously created policies and check if all of them are removed + community.aws.s3_lifecycle: + name: "{{ bucket_name }}" + rule_id: "{{ item }}" + expiration_days: 10 + prefix: "{{ item }}" + status: enabled + state: absent + wait: yes + register: output + loop: + - rule_1 + - rule_2 + - rule_3 + - assert: + that: + - (output.results | last).rules | length == 0 # ============================================================ - name: Create a lifecycle policy s3_lifecycle:
s3_lifecycle - occasionally fails to add/remove all rules from playbook ### Summary Sometimes not all rules from playbook are added or removed. It occurs even if 'wait' parameter is set to 'yes'. It was observed that shortly (~30s) after setting the rules with the plugin. get-bucket-lifecycle returns alternatively new and old rules in a random manner. Similar issue has been reported in boto3 library. https://github.com/boto/boto3/issues/2491 ### Issue Type Bug Report ### Component Name s3_lifecycle ### Ansible Version ```console (paste below) $ ansible --version ansible [core 2.12.4] config file = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/ansible.cfg configured module search path = ['/home/rubin/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/lib/python3.8/site-packages/ansible ansible collection location = /home/rubin/.ansible/collections:/usr/share/ansible/collections executable location = ./env/bin/ansible python version = 3.8.10 (default, Mar 15 2022, 12:22:08) [GCC 9.4.0] jinja version = 3.1.1 libyaml = True ``` ### Collection Versions ```console (paste below) $ ansible-galaxy collection list Collection Version ----------------------------- ------- amazon.aws 2.2.0 ansible.netcommon 2.6.1 ansible.posix 1.3.0 ansible.utils 2.5.2 ansible.windows 1.9.0 arista.eos 3.1.0 awx.awx 19.4.0 azure.azcollection 1.12.0 check_point.mgmt 2.3.0 chocolatey.chocolatey 1.2.0 cisco.aci 2.2.0 cisco.asa 2.1.0 cisco.intersight 1.0.18 cisco.ios 2.8.1 cisco.iosxr 2.9.0 cisco.ise 1.2.1 cisco.meraki 2.6.1 cisco.mso 1.4.0 cisco.nso 1.0.3 cisco.nxos 2.9.1 cisco.ucs 1.8.0 cloud.common 2.1.0 cloudscale_ch.cloud 2.2.1 community.aws 2.4.0 community.azure 1.1.0 community.ciscosmb 1.0.4 community.crypto 2.2.4 community.digitalocean 1.16.0 community.dns 2.0.9 community.docker 2.3.0 community.fortios 1.0.0 community.general 4.7.0 community.google 1.0.0 community.grafana 1.3.3 community.hashi_vault 2.4.0 community.hrobot 1.2.3 community.kubernetes 2.0.1 community.kubevirt 1.0.0 community.libvirt 1.0.2 community.mongodb 1.3.3 community.mysql 2.3.5 community.network 3.1.0 community.okd 2.1.0 community.postgresql 1.7.1 community.proxysql 1.3.1 community.rabbitmq 1.1.0 community.routeros 2.0.0 community.sap 1.0.0 community.skydive 1.0.0 community.sops 1.2.1 community.vmware 1.18.0 community.windows 1.9.0 community.zabbix 1.5.1 containers.podman 1.9.3 cyberark.conjur 1.1.0 cyberark.pas 1.0.13 dellemc.enterprise_sonic 1.1.0 dellemc.openmanage 4.4.0 dellemc.os10 1.1.1 dellemc.os6 1.0.7 dellemc.os9 1.0.4 f5networks.f5_modules 1.15.0 fortinet.fortimanager 2.1.4 fortinet.fortios 2.1.4 frr.frr 1.0.3 gluster.gluster 1.0.2 google.cloud 1.0.2 hetzner.hcloud 1.6.0 hpe.nimble 1.1.4 ibm.qradar 1.0.3 infinidat.infinibox 1.3.3 infoblox.nios_modules 1.2.1 inspur.sm 1.3.0 junipernetworks.junos 2.10.0 kubernetes.core 2.3.0 mellanox.onyx 1.0.0 netapp.aws 21.7.0 netapp.azure 21.10.0 netapp.cloudmanager 21.15.0 netapp.elementsw 21.7.0 netapp.ontap 21.17.3 netapp.storagegrid 21.10.0 netapp.um_info 21.8.0 netapp_eseries.santricity 1.3.0 netbox.netbox 3.6.0 ngine_io.cloudstack 2.2.3 ngine_io.exoscale 1.0.0 ngine_io.vultr 1.1.1 openstack.cloud 1.7.2 openvswitch.openvswitch 2.1.0 ovirt.ovirt 1.6.6 purestorage.flasharray 1.12.1 purestorage.flashblade 1.9.0 sensu.sensu_go 1.13.0 servicenow.servicenow 1.0.6 splunk.es 1.0.2 t_systems_mms.icinga_director 1.28.0 theforeman.foreman 2.2.0 vyos.vyos 2.8.0 wti.remote 1.0.3 ``` ### AWS SDK versions ```console (paste below) $ pip show boto boto3 botocore WARNING: Package(s) not found: boto Name: boto3 Version: 1.21.39 Summary: The AWS SDK for Python Home-page: https://github.com/boto/boto3 Author: Amazon Web Services Author-email: License: Apache License 2.0 Location: /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/lib/python3.8/site-packages Requires: botocore, jmespath, s3transfer Required-by: --- Name: botocore Version: 1.24.39 Summary: Low-level, data-driven core of boto 3. Home-page: https://github.com/boto/botocore Author: Amazon Web Services Author-email: License: Apache License 2.0 Location: /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/lib/python3.8/site-packages Requires: jmespath, python-dateutil, urllib3 Required-by: boto3, s3transfer ``` ### Configuration ```console (paste below) $ ansible-config dump --only-changed ANSIBLE_PIPELINING(/work/ansible/ansible.cfg) = True DEFAULT_HOST_LIST(/work/ansible/ansible.cfg) = ['/work/ansible/hosts'] DEFAULT_LOG_PATH(/work/ansible/ansible.cfg) = /work/ansible/tmp/ansible.log INTERPRETER_PYTHON(/work/ansible/ansible.cfg) = auto ``` ### OS / Environment Ubuntu 20.04.3 Python 3.8.10 ### Steps to Reproduce <!--- Paste example playbooks or commands between quotes below --> 1. Create playbook file to create/remove 3 lifecycle rules ```console (paste below) $ cat << EOF >> lifecycle_wait_issue.yml --- - hosts: local gather_facts: False vars: bucket: bucket_name state: present tasks: - name: "exemplary cleanup rule" community.aws.s3_lifecycle: name: "{{ bucket }}" rule_id: cleanup_rule_1 noncurrent_version_expiration_days: 1 prefix: "" status: enabled state: "{{ state }}" wait: yes - name: "{{ bucket }} - exemplary loop rule" community.aws.s3_lifecycle: name: "{{ bucket }}" rule_id: "{{ item.rule_id }}" expiration_days: 14 prefix: "{{ item.prefix }}" status: enabled state: "{{ state }}" wait: yes loop: - { rule_id: loop_rule_id_1, prefix: prefix_1 } - { rule_id: loop_rule_id_2, prefix: prefix_2 } EOF ``` 2. Run below script NOTE! Below steps assume there are no other lifecycle rules in the bucket. ```bash BUCKET=<set-your-bucket-here> reproduced=false step=1 #set -x while [ $step -le 10 ] ; do echo "[$step/10] Adding rules..." # Add 3 rules according to the playbook ansible-playbook -vv lifecycle_wait_issue.yml -e "bucket=$BUCKET" -e "state=present" rules=$(aws s3api get-bucket-lifecycle --bucket $BUCKET --query 'Rules[*][ID]' --output text) cnt=$(echo "$rules" | wc -l) # 3 rules are expected if [ $cnt != 3 ] ; then echo "issue reproduced, 3 rules expected, $cnt rules found:" echo "$rules" reproduced=true break fi echo "[$step/10] Removing rules..." # Remove all rules ansible-playbook -vv lifecycle_wait_issue.yml -e "bucket=$BUCKET" -e "state=absent" # expected error: The lifecycle configuration does not exist rules=$(aws s3api get-bucket-lifecycle --bucket $BUCKET --query 'Rules[*][ID]' --output text) if [ $? -ne 254 ] ; then cnt=$(echo "$rules" | wc -l) echo "issue reproduced, 0 rules expected, $cnt rules found:" echo "$rules" reproduced=true break fi step=$(( step + 1)) done if ! $reproduced ; then echo 'issue not reproduced' fi ``` ### Expected Results Script prints: ```console issue not reproduced ``` which means it was able to successfully: - add 3 rules - remove 3 added rules in 10 consecutive steps. ### Actual Results Script prints: ```console (paste below) issue reproduced, ... ``` Example 1: ```console [1/10] Adding rules... ansible-playbook [core 2.12.4] config file = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/ansible.cfg configured module search path = ['/home/rubin/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/lib/python3.8/site-packages/ansible ansible collection location = /home/rubin/.ansible/collections:/usr/share/ansible/collections executable location = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/bin/ansible-playbook python version = 3.8.10 (default, Mar 15 2022, 12:22:08) [GCC 9.4.0] jinja version = 3.1.1 libyaml = True Using /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/ansible.cfg as config file Skipping callback 'default', as we already have a stdout callback. Skipping callback 'minimal', as we already have a stdout callback. Skipping callback 'oneline', as we already have a stdout callback. PLAYBOOK: lifecycle_wait_issue.yml ********************************************************************************************************************************************************************************* 1 plays in lifecycle_wait_issue.yml PLAY [local] ******************************************************************************************************************************************************************************************************* META: ran handlers TASK [exemplary cleanup rule] ************************************************************************************************************************************************************************************** task path: /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/lifecycle_wait_issue.yml:10 changed: [localhost] => {"_config": {"Rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}]}, "_retries": 9, "ansible_facts": {"discovered_interpreter_python": "/usr/bin/python3"}, "changed": true, "new_rule": {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}, "old_rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}], "rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}]} TASK [lgi-onemw-staging-dawn-base - exemplary loop rule] *********************************************************************************************************************************************************** task path: /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/lifecycle_wait_issue.yml:20 ok: [localhost] => (item={'rule_id': 'loop_rule_id_1', 'prefix': 'prefix_1'}) => {"_config": {"Rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}]}, "_retries": 10, "ansible_loop_var": "item", "changed": false, "item": {"prefix": "prefix_1", "rule_id": "loop_rule_id_1"}, "new_rule": {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, "old_rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}], "rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}]} ok: [localhost] => (item={'rule_id': 'loop_rule_id_2', 'prefix': 'prefix_2'}) => {"_config": {"Rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}]}, "_retries": 10, "ansible_loop_var": "item", "changed": false, "item": {"prefix": "prefix_2", "rule_id": "loop_rule_id_2"}, "new_rule": {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, "old_rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}], "rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}]} META: ran handlers META: ran handlers PLAY RECAP ********************************************************************************************************************************************************************************************************* localhost : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 [1/10] Removing rules... ansible-playbook [core 2.12.4] config file = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/ansible.cfg configured module search path = ['/home/rubin/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/lib/python3.8/site-packages/ansible ansible collection location = /home/rubin/.ansible/collections:/usr/share/ansible/collections executable location = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/bin/ansible-playbook python version = 3.8.10 (default, Mar 15 2022, 12:22:08) [GCC 9.4.0] jinja version = 3.1.1 libyaml = True Using /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/ansible.cfg as config file Skipping callback 'default', as we already have a stdout callback. Skipping callback 'minimal', as we already have a stdout callback. Skipping callback 'oneline', as we already have a stdout callback. PLAYBOOK: lifecycle_wait_issue.yml ********************************************************************************************************************************************************************************* 1 plays in lifecycle_wait_issue.yml PLAY [local] ******************************************************************************************************************************************************************************************************* META: ran handlers TASK [exemplary cleanup rule] ************************************************************************************************************************************************************************************** task path: /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/lifecycle_wait_issue.yml:10 changed: [localhost] => {"_retries": 9, "ansible_facts": {"discovered_interpreter_python": "/usr/bin/python3"}, "changed": true, "old_rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}], "rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}]} TASK [lgi-onemw-staging-dawn-base - exemplary loop rule] *********************************************************************************************************************************************************** task path: /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/lifecycle_wait_issue.yml:20 changed: [localhost] => (item={'rule_id': 'loop_rule_id_1', 'prefix': 'prefix_1'}) => {"_retries": 9, "ansible_loop_var": "item", "changed": true, "item": {"prefix": "prefix_1", "rule_id": "loop_rule_id_1"}, "old_rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}], "rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}]} changed: [localhost] => (item={'rule_id': 'loop_rule_id_2', 'prefix': 'prefix_2'}) => {"_retries": 8, "ansible_loop_var": "item", "changed": true, "item": {"prefix": "prefix_2", "rule_id": "loop_rule_id_2"}, "old_rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}], "rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}]} META: ran handlers META: ran handlers PLAY RECAP ********************************************************************************************************************************************************************************************************* localhost : ok=2 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 An error occurred (NoSuchLifecycleConfiguration) when calling the GetBucketLifecycle operation: The lifecycle configuration does not exist [2/10] Adding rules... ansible-playbook [core 2.12.4] config file = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/ansible.cfg configured module search path = ['/home/rubin/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/lib/python3.8/site-packages/ansible ansible collection location = /home/rubin/.ansible/collections:/usr/share/ansible/collections executable location = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/bin/ansible-playbook python version = 3.8.10 (default, Mar 15 2022, 12:22:08) [GCC 9.4.0] jinja version = 3.1.1 libyaml = True Using /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/ansible.cfg as config file Skipping callback 'default', as we already have a stdout callback. Skipping callback 'minimal', as we already have a stdout callback. Skipping callback 'oneline', as we already have a stdout callback. PLAYBOOK: lifecycle_wait_issue.yml ******************************************************************************************************************************************************************************************************************************************************** 1 plays in lifecycle_wait_issue.yml PLAY [local] ****************************************************************************************************************************************************************************************************************************************************************************** META: ran handlers TASK [exemplary cleanup rule] ************************************************************************************************************************************************************************************************************************************************************* task path: /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/lifecycle_wait_issue.yml:10 changed: [localhost] => {"_config": {"Rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}]}, "_retries": 8, "ansible_facts": {"discovered_interpreter_python": "/usr/bin/python3"}, "changed": true, "new_rule": {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}, "old_rules": [], "rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}]} TASK [lgi-onemw-staging-dawn-base - exemplary loop rule] ********************************************************************************************************************************************************************************************************************************** task path: /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/lifecycle_wait_issue.yml:20 changed: [localhost] => (item={'rule_id': 'loop_rule_id_1', 'prefix': 'prefix_1'}) => {"_config": {"Rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}]}, "_retries": 9, "ansible_loop_var": "item", "changed": true, "item": {"prefix": "prefix_1", "rule_id": "loop_rule_id_1"}, "new_rule": {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, "old_rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}], "rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}]} changed: [localhost] => (item={'rule_id': 'loop_rule_id_2', 'prefix': 'prefix_2'}) => {"_config": {"Rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}]}, "_retries": 9, "ansible_loop_var": "item", "changed": true, "item": {"prefix": "prefix_2", "rule_id": "loop_rule_id_2"}, "new_rule": {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, "old_rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}], "rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}]} META: ran handlers META: ran handlers PLAY RECAP ******************************************************************************************************************************************************************************************************************************************************************************** localhost : ok=2 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 [2/10] Removing rules... ansible-playbook [core 2.12.4] config file = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/ansible.cfg configured module search path = ['/home/rubin/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/lib/python3.8/site-packages/ansible ansible collection location = /home/rubin/.ansible/collections:/usr/share/ansible/collections executable location = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/bin/ansible-playbook python version = 3.8.10 (default, Mar 15 2022, 12:22:08) [GCC 9.4.0] jinja version = 3.1.1 libyaml = True Using /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/ansible.cfg as config file Skipping callback 'default', as we already have a stdout callback. Skipping callback 'minimal', as we already have a stdout callback. Skipping callback 'oneline', as we already have a stdout callback. PLAYBOOK: lifecycle_wait_issue.yml ******************************************************************************************************************************************************************************************************************************************************** 1 plays in lifecycle_wait_issue.yml PLAY [local] ****************************************************************************************************************************************************************************************************************************************************************************** META: ran handlers TASK [exemplary cleanup rule] ************************************************************************************************************************************************************************************************************************************************************* task path: /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/lifecycle_wait_issue.yml:10 changed: [localhost] => {"_retries": 9, "ansible_facts": {"discovered_interpreter_python": "/usr/bin/python3"}, "changed": true, "old_rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}], "rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}]} TASK [lgi-onemw-staging-dawn-base - exemplary loop rule] ********************************************************************************************************************************************************************************************************************************** task path: /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/lifecycle_wait_issue.yml:20 changed: [localhost] => (item={'rule_id': 'loop_rule_id_1', 'prefix': 'prefix_1'}) => {"_retries": 8, "ansible_loop_var": "item", "changed": true, "item": {"prefix": "prefix_1", "rule_id": "loop_rule_id_1"}, "old_rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}], "rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}]} changed: [localhost] => (item={'rule_id': 'loop_rule_id_2', 'prefix': 'prefix_2'}) => {"_retries": 9, "ansible_loop_var": "item", "changed": true, "item": {"prefix": "prefix_2", "rule_id": "loop_rule_id_2"}, "old_rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}], "rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}]} META: ran handlers META: ran handlers PLAY RECAP ******************************************************************************************************************************************************************************************************************************************************************************** localhost : ok=2 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 issue reproduced, 0 rules expected, 2 rules found: cleanup_rule_1 loop_rule_id_2 ``` Example 2: ```console [1/10] Adding rules... ansible-playbook [core 2.12.4] config file = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/ansible.cfg configured module search path = ['/home/rubin/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/lib/python3.8/site-packages/ansible ansible collection location = /home/rubin/.ansible/collections:/usr/share/ansible/collections executable location = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/bin/ansible-playbook python version = 3.8.10 (default, Mar 15 2022, 12:22:08) [GCC 9.4.0] jinja version = 3.1.1 libyaml = True Using /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/ansible.cfg as config file Skipping callback 'default', as we already have a stdout callback. Skipping callback 'minimal', as we already have a stdout callback. Skipping callback 'oneline', as we already have a stdout callback. PLAYBOOK: lifecycle_wait_issue.yml ********************************************************************************************************************************************************************************* 1 plays in lifecycle_wait_issue.yml PLAY [local] ******************************************************************************************************************************************************************************************************* META: ran handlers TASK [exemplary cleanup rule] ************************************************************************************************************************************************************************************** task path: /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/lifecycle_wait_issue.yml:10 changed: [localhost] => {"_config": {"Rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}]}, "_retries": 8, "ansible_facts": {"discovered_interpreter_python": "/usr/bin/python3"}, "changed": true, "new_rule": {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}, "old_rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}], "rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}]} TASK [lgi-onemw-staging-dawn-base - exemplary loop rule] *********************************************************************************************************************************************************** task path: /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/lifecycle_wait_issue.yml:20 changed: [localhost] => (item={'rule_id': 'loop_rule_id_1', 'prefix': 'prefix_1'}) => {"_config": {"Rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}]}, "_retries": 9, "ansible_loop_var": "item", "changed": true, "item": {"prefix": "prefix_1", "rule_id": "loop_rule_id_1"}, "new_rule": {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, "old_rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}], "rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}]} ok: [localhost] => (item={'rule_id': 'loop_rule_id_2', 'prefix': 'prefix_2'}) => {"_config": {"Rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}]}, "_retries": 10, "ansible_loop_var": "item", "changed": false, "item": {"prefix": "prefix_2", "rule_id": "loop_rule_id_2"}, "new_rule": {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, "old_rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}], "rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}]} META: ran handlers META: ran handlers PLAY RECAP ********************************************************************************************************************************************************************************************************* localhost : ok=2 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 issue reproduced, 3 rules expected, 2 rules found: loop_rule_id_2 loop_rule_id_1 ``` It cannot reliably add or remove rules from playbook. ### Code of Conduct - [X] I agree to follow the Ansible Code of Conduct
Files identified in the description: * [`plugins/modules/s3_lifecycle.py`](https://github.com/['ansible-collections/amazon.aws', 'ansible-collections/community.aws', 'ansible-collections/community.vmware']/blob/main/plugins/modules/s3_lifecycle.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @jillr @markuman @s-hertel @tremble [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify --->
2022-04-20T13:51:06
ansible-collections/community.aws
1,105
ansible-collections__community.aws-1105
[ "922" ]
c5363d56dc761e6a8b53be7d0ebd243af20adec7
diff --git a/plugins/modules/rds_instance.py b/plugins/modules/rds_instance.py --- a/plugins/modules/rds_instance.py +++ b/plugins/modules/rds_instance.py @@ -160,6 +160,13 @@ aliases: - subnet_group type: str + deletion_protection: + description: + - A value that indicates whether the DB instance has deletion protection enabled. + The database can't be deleted when deletion protection is enabled. + By default, deletion protection is disabled. + type: bool + version_added: 3.3.0 domain: description: - The Active Directory Domain to restore the instance in. @@ -666,6 +673,12 @@ returned: always type: str sample: db-UHV3QRNWX4KB6GALCIGRML6QFA +deletion_protection: + description: C(True) if the DB instance has deletion protection enabled, C(False) if not. + returned: always + type: bool + sample: False + version_added: 3.3.0 domain_memberships: description: The Active Directory Domain membership records associated with the DB instance. returned: always @@ -1256,6 +1269,7 @@ def main(): db_security_groups=dict(type='list', elements='str'), db_snapshot_identifier=dict(), db_subnet_group_name=dict(aliases=['subnet_group']), + deletion_protection=dict(type='bool'), domain=dict(), domain_iam_role_name=dict(), enable_cloudwatch_logs_exports=dict(type='list', aliases=['cloudwatch_log_exports'], elements='str'), diff --git a/plugins/modules/rds_instance_info.py b/plugins/modules/rds_instance_info.py --- a/plugins/modules/rds_instance_info.py +++ b/plugins/modules/rds_instance_info.py @@ -188,6 +188,12 @@ returned: always type: str sample: db-AAAAAAAAAAAAAAAAAAAAAAAAAA + deletion_protection: + description: C(True) if the DB instance has deletion protection enabled, C(False) if not. + returned: always + type: bool + sample: False + version_added: 3.3.0 domain_memberships: description: List of domain memberships returned: always
rds_instance: modify delete protection ### Summary I am trying to modify an RDS instance that has delete protection on it, preventing deletion. I would like the ability to modify this via ansible directly ``` for rds in $(aws rds describe-db-instances | jq -r '.DBInstances.[].DBInstanceIdentifier'); do aws rds modify-db-instance --no-deletion-protection --db-instance-identifier "${rds}" done ``` ### Issue Type Feature Idea ### Component Name rds_instance ### Additional Information <!--- Paste example playbooks or commands between quotes below --> ```yaml (paste below) - name: Get all RDS instances community.aws.rds_instance_info: region: "{{ region }}" aws_access_key: "{{ aws_access_key_id }}" aws_secret_key: "{{ aws_secret_access_key }}" register: __rds_instances - name: Remove delete protection from any DB instances community.aws.rds_instance: id: "{{ item.db_instance_identifier }}" deletion_protection: false loop: __rds_instances.instances - name: Remove any DB instance without a final snapshot community.aws.rds_instance: id: "{{ item.db_instance_identifier }}" state: absent skip_final_snapshot: true loop: __rds_instances.instances ``` ### Code of Conduct - [X] I agree to follow the Ansible Code of Conduct
2022-04-28T23:54:59
ansible-collections/community.aws
1,108
ansible-collections__community.aws-1108
[ "1111" ]
da4b50108e22dc46d9762e23b013a850de130950
diff --git a/plugins/modules/execute_lambda.py b/plugins/modules/execute_lambda.py --- a/plugins/modules/execute_lambda.py +++ b/plugins/modules/execute_lambda.py @@ -260,8 +260,10 @@ def main(): def wait_for_lambda(client, module, name): try: - waiter = client.get_waiter('function_active') - waiter.wait(FunctionName=name) + client_active_waiter = client.get_waiter('function_active') + client_updated_waiter = client.get_waiter('function_updated') + client_active_waiter.wait(FunctionName=name) + client_updated_waiter.wait(FunctionName=name) except botocore.exceptions.WaiterError as e: module.fail_json_aws(e, msg='Timeout while waiting on lambda to be Active') except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: diff --git a/plugins/modules/lambda.py b/plugins/modules/lambda.py --- a/plugins/modules/lambda.py +++ b/plugins/modules/lambda.py @@ -107,6 +107,11 @@ description: - Tag dict to apply to the function. type: dict + kms_key_arn: + description: + - The KMS key ARN used to encrypt the function's environment variables. + type: str + version_added: 3.3.0 author: - 'Steyn Huizinga (@steynovich)' extends_documentation_fragment: @@ -350,6 +355,7 @@ def main(): vpc_security_group_ids=dict(type='list', elements='str'), environment_variables=dict(type='dict'), dead_letter_arn=dict(), + kms_key_arn=dict(type='str', no_log=False), tracing_mode=dict(choices=['Active', 'PassThrough']), tags=dict(type='dict'), ) @@ -387,6 +393,7 @@ def main(): dead_letter_arn = module.params.get('dead_letter_arn') tracing_mode = module.params.get('tracing_mode') tags = module.params.get('tags') + kms_key_arn = module.params.get('kms_key_arn') check_mode = module.check_mode changed = False @@ -442,6 +449,8 @@ def main(): func_kwargs.update({'DeadLetterConfig': {'TargetArn': dead_letter_arn}}) if tracing_mode and (current_config.get('TracingConfig', {}).get('Mode', 'PassThrough') != tracing_mode): func_kwargs.update({'TracingConfig': {'Mode': tracing_mode}}) + if kms_key_arn: + func_kwargs.update({'KMSKeyArn': kms_key_arn}) # If VPC configuration is desired if vpc_subnet_ids: @@ -573,17 +582,23 @@ def main(): if tracing_mode: func_kwargs.update({'TracingConfig': {'Mode': tracing_mode}}) + if kms_key_arn: + func_kwargs.update({'KMSKeyArn': kms_key_arn}) + # If VPC configuration is given if vpc_subnet_ids: func_kwargs.update({'VpcConfig': {'SubnetIds': vpc_subnet_ids, 'SecurityGroupIds': vpc_security_group_ids}}) + # Function would have been created if not check mode + if check_mode: + module.exit_json(changed=True) + # Finally try to create function current_version = None try: - if not check_mode: - response = client.create_function(aws_retry=True, **func_kwargs) - current_version = response['Version'] + response = client.create_function(aws_retry=True, **func_kwargs) + current_version = response['Version'] changed = True except (BotoCoreError, ClientError) as e: module.fail_json_aws(e, msg="Trying to create function")
diff --git a/tests/integration/targets/lambda/tasks/main.yml b/tests/integration/targets/lambda/tasks/main.yml --- a/tests/integration/targets/lambda/tasks/main.yml +++ b/tests/integration/targets/lambda/tasks/main.yml @@ -93,6 +93,19 @@ - '"parameters are required together" in result.msg' # Prepare minimal Lambda + - name: test state=present - upload the lambda (check mode) + lambda: + name: '{{ lambda_function_name }}' + runtime: python3.6 + handler: mini_lambda.handler + role: '{{ lambda_role_name }}' + zip_file: '{{ zip_res.dest }}' + register: result + check_mode: yes + - name: assert lambda upload succeeded + assert: + that: + - result.changed - name: test state=present - upload the lambda lambda: @@ -105,7 +118,7 @@ - name: assert lambda upload succeeded assert: that: - - result is not failed + - result.changed - result.configuration.tracing_config.mode == "PassThrough" # Test basic operation of Uploaded lambda @@ -122,6 +135,25 @@ - result.result.output.message == "hello Mr Ansible Tests" # Test updating Lambda + - name: test lambda config updates (check mode) + lambda: + name: '{{lambda_function_name}}' + runtime: nodejs14.x + tracing_mode: Active + handler: mini_lambda.handler + role: '{{ lambda_role_name }}' + tags: + CamelCase: 'ACamelCaseValue' + snake_case: 'a_snake_case_value' + 'Spaced key': 'A value with spaces' + register: update_result + check_mode: yes + - name: assert that update succeeded + assert: + that: + - update_result is not failed + - update_result.changed == True + - name: test lambda config updates lambda: name: '{{lambda_function_name}}' @@ -142,6 +174,25 @@ - update_result.configuration.runtime == 'nodejs14.x' - update_result.configuration.tracing_config.mode == 'Active' + - name: test no changes are made with the same parameters repeated (check mode) + lambda: + name: '{{lambda_function_name}}' + runtime: nodejs14.x + tracing_mode: Active + handler: mini_lambda.handler + role: '{{ lambda_role_name }}' + tags: + CamelCase: 'ACamelCaseValue' + snake_case: 'a_snake_case_value' + 'Spaced key': 'A value with spaces' + register: update_result + check_mode: yes + - name: assert that update succeeded + assert: + that: + - update_result is not failed + - update_result.changed == False + - name: test no changes are made with the same parameters repeated lambda: name: '{{lambda_function_name}}' @@ -184,6 +235,7 @@ name: '{{ lambda_function_name }}' query: all register: lambda_infos_all + check_mode: yes - name: lambda_info | Assert successfull retrieval of all information assert: that: @@ -278,6 +330,23 @@ - result is not failed - result.changed == False + - name: test putting an environment variable changes lambda (check mode) + lambda: + name: '{{lambda_function_name}}' + runtime: python3.6 + handler: mini_lambda.handler + role: '{{ lambda_role_name }}' + zip_file: '{{zip_res.dest}}' + environment_variables: + EXTRA_MESSAGE: I think you are great!! + register: result + check_mode: yes + - name: assert lambda upload succeeded + assert: + that: + - result is not failed + - result.changed == True + - name: test putting an environment variable changes lambda lambda: name: '{{lambda_function_name}}' @@ -293,6 +362,8 @@ that: - result is not failed - result.changed == True + - result.configuration.environment.variables.extra_message == "I think you are great!!" + - name: test lambda works execute_lambda: name: '{{lambda_function_name}}' @@ -306,6 +377,19 @@ - result.result.output.message == "hello Mr Ansible Tests. I think you are great!!" # Deletion behavious + - name: test state=absent (expect changed=True) (check mode) + lambda: + name: '{{lambda_function_name}}' + state: absent + register: result + check_mode: yes + + - name: assert state=absent + assert: + that: + - result is not failed + - result is changed + - name: test state=absent (expect changed=True) lambda: name: '{{lambda_function_name}}' @@ -318,6 +402,19 @@ - result is not failed - result is changed + - name: test state=absent (expect changed=False) when already deleted (check mode) + lambda: + name: '{{lambda_function_name}}' + state: absent + register: result + check_mode: yes + + - name: assert state=absent + assert: + that: + - result is not failed + - result is not changed + - name: test state=absent (expect changed=False) when already deleted lambda: name: '{{lambda_function_name}}'
Add support for lambda KMSKeyArn ### Summary Please add support to set KMSKeyArn when creating and updating lambda functions. https://docs.aws.amazon.com/lambda/latest/dg/API_CreateFunction.html#SSS-CreateFunction-request-KMSKeyArn https://docs.aws.amazon.com/lambda/latest/dg/API_UpdateFunctionCode.html#SSS-UpdateFunctionCode-response-KMSKeyArn ### Issue Type Feature Idea ### Component Name lambda ### Additional Information _No response_ ### Code of Conduct - [X] I agree to follow the Ansible Code of Conduct
2022-05-02T13:28:35
ansible-collections/community.aws
1,117
ansible-collections__community.aws-1117
[ "89" ]
872f6e31ee822d09e62f2e24357a68e0387fa4e9
diff --git a/plugins/modules/route53.py b/plugins/modules/route53.py --- a/plugins/modules/route53.py +++ b/plugins/modules/route53.py @@ -108,6 +108,30 @@ latency-based routing - Mutually exclusive with I(weight) and I(failover). type: str + geo_location: + description: + - Allows to control how Amazon Route 53 responds to DNS queries based on the geographic origin of the query. + - Two geolocation resource record sets that specify same geographic location cannot be created. + - Non-geolocation resource record sets that have the same values for the Name and Type elements as geolocation + resource record sets cannot be created. + suboptions: + continent_code: + description: + - The two-letter code for the continent. + - Specifying I(continent_code) with either I(country_code) or I(subdivision_code) returns an InvalidInput error. + type: str + country_code: + description: + - The two-letter code for a country. + - Amazon Route 53 uses the two-letter country codes that are specified in ISO standard 3166-1 alpha-2 . + type: str + subdivision_code: + description: + - The two-letter code for a state of the United States. + - To specify I(subdivision_code), I(country_code) must be set to C(US). + type: str + type: dict + version_added: 3.3.0 health_check: description: - Health check to associate with this record @@ -166,6 +190,12 @@ returned: always type: str sample: PRIMARY + geo_location: + description: geograpic location based on which Route53 resonds to DNS queries. + returned: when configured + type: dict + sample: { continent_code: "NA", country_code: "US", subdivision_code: "CA" } + version_added: 3.3.0 health_check: description: health_check associated with this record. returned: always @@ -350,6 +380,29 @@ - 0 issue "ca.example.net" - 0 issuewild ";" - 0 iodef "mailto:[email protected]" +- name: Create a record with geo_location - country_code + community.aws.route53: + state: present + zone: '{{ zone_one }}' + record: 'geo-test.{{ zone_one }}' + identifier: "geohost@www" + type: A + value: 1.1.1.1 + ttl: 30 + geo_location: + country_code: US +- name: Create a record with geo_location - subdivision code + community.aws.route53: + state: present + zone: '{{ zone_one }}' + record: 'geo-test.{{ zone_one }}' + identifier: "geohost@www" + type: A + value: 1.1.1.1 + ttl: 30 + geo_location: + country_code: US + subdivision_code: TX ''' from operator import itemgetter @@ -495,6 +548,12 @@ def main(): identifier=dict(type='str'), weight=dict(type='int'), region=dict(type='str'), + geo_location=dict(type='dict', + options=dict( + continent_code=dict(type="str"), + country_code=dict(type="str"), + subdivision_code=dict(type="str")), + required=False), health_check=dict(type='str'), failover=dict(type='str', choices=['PRIMARY', 'SECONDARY']), vpc_id=dict(type='str'), @@ -518,11 +577,12 @@ def main(): ('failover', 'region', 'weight'), ('alias', 'ttl'), ], - # failover, region and weight require identifier + # failover, region, weight and geo_location require identifier required_by=dict( failover=('identifier',), region=('identifier',), weight=('identifier',), + geo_location=('identifier'), ), ) @@ -557,6 +617,7 @@ def main(): vpc_id_in = module.params.get('vpc_id') wait_in = module.params.get('wait') wait_timeout_in = module.params.get('wait_timeout') + geo_location = module.params.get('geo_location') if zone_in[-1:] != '.': zone_in += "." @@ -567,8 +628,8 @@ def main(): if command_in == 'create' or command_in == 'delete': if alias_in and len(value_in) != 1: module.fail_json(msg="parameter 'value' must contain a single dns name for alias records") - if (weight_in is None and region_in is None and failover_in is None) and identifier_in is not None: - module.fail_json(msg="You have specified identifier which makes sense only if you specify one of: weight, region or failover.") + if not any([weight_in, region_in, failover_in, geo_location]) and identifier_in is not None: + module.fail_json(msg="You have specified identifier which makes sense only if you specify one of: weight, region, geo_location or failover.") retry_decorator = AWSRetry.jittered_backoff( retries=MAX_AWS_RETRIES, @@ -604,6 +665,30 @@ def main(): 'HealthCheckId': health_check_in, 'SetIdentifier': identifier_in, }) + + if geo_location: + continent_code = geo_location.get('continent_code') + country_code = geo_location.get('country_code') + subdivision_code = geo_location.get('subdivision_code') + + if continent_code and (country_code or subdivision_code): + module.fail_json(changed=False, msg='While using geo_location, continent_code is mutually exclusive with country_code and subdivision_code.') + + if not any([continent_code, country_code, subdivision_code]): + module.fail_json(changed=False, msg='To use geo_location please specify either continent_code, country_code, or subdivision_code.') + + if geo_location.get('subdivision_code') and geo_location.get('country_code').lower() != 'us': + module.fail_json(changed=False, msg='To use subdivision_code, you must specify country_code as US.') + + # Build geo_location suboptions specification + resource_record_set['GeoLocation'] = {} + if continent_code: + resource_record_set['GeoLocation']['ContinentCode'] = continent_code + if country_code: + resource_record_set['GeoLocation']['CountryCode'] = country_code + if subdivision_code: + resource_record_set['GeoLocation']['SubdivisionCode'] = subdivision_code + if command_in == 'delete' and aws_record is not None: resource_record_set['TTL'] = aws_record.get('TTL') if not resource_record_set['ResourceRecords']:
diff --git a/tests/integration/targets/route53/tasks/main.yml b/tests/integration/targets/route53/tasks/main.yml --- a/tests/integration/targets/route53/tasks/main.yml +++ b/tests/integration/targets/route53/tasks/main.yml @@ -635,7 +635,314 @@ - weighted_record is not failed - weighted_record is not changed +#Test Geo Location - Continent Code + - name: Create a record with geo_location - continent_code (check_mode) + route53: + state: present + zone: '{{ zone_one }}' + record: 'geo-test-1.{{ zone_one }}' + identifier: "geohost1@www" + type: A + value: 127.0.0.1 + ttl: 30 + geo_location: + continent_code: NA + check_mode: true + register: create_geo_continent_check_mode + - assert: + that: + - create_geo_continent_check_mode is changed + - create_geo_continent_check_mode is not failed + - '"route53:ChangeResourceRecordSets" not in create_geo_continent_check_mode.resource_actions' + + - name: Create a record with geo_location - continent_code + route53: + state: present + zone: '{{ zone_one }}' + record: 'geo-test-1.{{ zone_one }}' + identifier: "geohost1@www" + type: A + value: 127.0.0.1 + ttl: 30 + geo_location: + continent_code: NA + register: create_geo_continent + # Get resulting A record and geo_location parameters are applied + - name: 'get Route53 A record information' + route53_info: + type: A + query: record_sets + hosted_zone_id: '{{ z1.zone_id }}' + start_record_name: 'geo-test-1.{{ zone_one }}' + max_items: 1 + register: result + + - assert: + that: + - create_geo_continent is changed + - create_geo_continent is not failed + - '"route53:ChangeResourceRecordSets" in create_geo_continent.resource_actions' + - result.ResourceRecordSets[0].GeoLocation.ContinentCode == "NA" + + - name: Create a record with geo_location - continent_code (idempotency) + route53: + state: present + zone: '{{ zone_one }}' + record: 'geo-test-1.{{ zone_one }}' + identifier: "geohost1@www" + type: A + value: 127.0.0.1 + ttl: 30 + geo_location: + continent_code: NA + register: create_geo_continent_idem + - assert: + that: + - create_geo_continent_idem is not changed + - create_geo_continent_idem is not failed + - '"route53:ChangeResourceRecordSets" not in create_geo_continent_idem.resource_actions' + + - name: Create a record with geo_location - continent_code (idempotency - check_mode) + route53: + state: present + zone: '{{ zone_one }}' + record: 'geo-test-1.{{ zone_one }}' + identifier: "geohost1@www" + type: A + value: 127.0.0.1 + ttl: 30 + geo_location: + continent_code: NA + check_mode: true + register: create_geo_continent_idem_check + + - assert: + that: + - create_geo_continent_idem_check is not changed + - create_geo_continent_idem_check is not failed + - '"route53:ChangeResourceRecordSets" not in create_geo_continent_idem_check.resource_actions' + +#Test Geo Location - Country Code + - name: Create a record with geo_location - country_code (check_mode) + route53: + state: present + zone: '{{ zone_one }}' + record: 'geo-test-2.{{ zone_one }}' + identifier: "geohost2@www" + type: A + value: 127.0.0.1 + ttl: 30 + geo_location: + country_code: US + check_mode: true + register: create_geo_country_check_mode + - assert: + that: + - create_geo_country_check_mode is changed + - create_geo_country_check_mode is not failed + - '"route53:ChangeResourceRecordSets" not in create_geo_country_check_mode.resource_actions' + + - name: Create a record with geo_location - country_code + route53: + state: present + zone: '{{ zone_one }}' + record: 'geo-test-2.{{ zone_one }}' + identifier: "geohost2@www" + type: A + value: 127.0.0.1 + ttl: 30 + geo_location: + country_code: US + register: create_geo_country + # Get resulting A record and geo_location parameters are applied + - name: 'get Route53 A record information' + route53_info: + type: A + query: record_sets + hosted_zone_id: '{{ z1.zone_id }}' + start_record_name: 'geo-test-2.{{ zone_one }}' + max_items: 1 + register: result + - assert: + that: + - create_geo_country is changed + - create_geo_country is not failed + - '"route53:ChangeResourceRecordSets" in create_geo_country.resource_actions' + - result.ResourceRecordSets[0].GeoLocation.CountryCode == "US" + + - name: Create a record with geo_location - country_code (idempotency) + route53: + state: present + zone: '{{ zone_one }}' + record: 'geo-test-2.{{ zone_one }}' + identifier: "geohost2@www" + type: A + value: 127.0.0.1 + ttl: 30 + geo_location: + country_code: US + register: create_geo_country_idem + - assert: + that: + - create_geo_country_idem is not changed + - create_geo_country_idem is not failed + - '"route53:ChangeResourceRecordSets" not in create_geo_country_idem.resource_actions' + + - name: Create a record with geo_location - country_code (idempotency - check_mode) + route53: + state: present + zone: '{{ zone_one }}' + record: 'geo-test-2.{{ zone_one }}' + identifier: "geohost2@www" + type: A + value: 127.0.0.1 + ttl: 30 + geo_location: + country_code: US + check_mode: true + register: create_geo_country_idem_check + + - assert: + that: + - create_geo_country_idem_check is not changed + - create_geo_country_idem_check is not failed + - '"route53:ChangeResourceRecordSets" not in create_geo_country_idem_check.resource_actions' + +#Test Geo Location - Subdivision Code + - name: Create a record with geo_location - subdivision_code (check_mode) + route53: + state: present + zone: '{{ zone_one }}' + record: 'geo-test-3.{{ zone_one }}' + identifier: "geohost3@www" + type: A + value: 127.0.0.1 + ttl: 30 + geo_location: + country_code: US + subdivision_code: TX + check_mode: true + register: create_geo_subdivision_check_mode + - assert: + that: + - create_geo_subdivision_check_mode is changed + - create_geo_subdivision_check_mode is not failed + - '"route53:ChangeResourceRecordSets" not in create_geo_subdivision_check_mode.resource_actions' + + - name: Create a record with geo_location - subdivision_code + route53: + state: present + zone: '{{ zone_one }}' + record: 'geo-test-3.{{ zone_one }}' + identifier: "geohost3@www" + type: A + value: 127.0.0.1 + ttl: 30 + geo_location: + country_code: US + subdivision_code: TX + register: create_geo_subdivision + # Get resulting A record and geo_location parameters are applied + - name: 'get Route53 A record information' + route53_info: + type: A + query: record_sets + hosted_zone_id: '{{ z1.zone_id }}' + start_record_name: 'geo-test-3.{{ zone_one }}' + max_items: 1 + register: result + - assert: + that: + - create_geo_subdivision is changed + - create_geo_subdivision is not failed + - '"route53:ChangeResourceRecordSets" in create_geo_subdivision.resource_actions' + - result.ResourceRecordSets[0].GeoLocation.CountryCode == "US" + - result.ResourceRecordSets[0].GeoLocation.SubdivisionCode == "TX" + + - name: Create a record with geo_location - subdivision_code (idempotency) + route53: + state: present + zone: '{{ zone_one }}' + record: 'geo-test-3.{{ zone_one }}' + identifier: "geohost3@www" + type: A + value: 127.0.0.1 + ttl: 30 + geo_location: + country_code: US + subdivision_code: TX + register: create_geo_subdivision_idem + - assert: + that: + - create_geo_subdivision_idem is not changed + - create_geo_subdivision_idem is not failed + - '"route53:ChangeResourceRecordSets" not in create_geo_subdivision_idem.resource_actions' + + - name: Create a record with geo_location - subdivision_code (idempotency - check_mode) + route53: + state: present + zone: '{{ zone_one }}' + record: 'geo-test-3.{{ zone_one }}' + identifier: "geohost3@www" + type: A + value: 127.0.0.1 + ttl: 30 + geo_location: + country_code: US + subdivision_code: TX + check_mode: true + register: create_geo_subdivision_idem_check + + - assert: + that: + - create_geo_subdivision_idem_check is not changed + - create_geo_subdivision_idem_check is not failed + - '"route53:ChangeResourceRecordSets" not in create_geo_subdivision_idem_check.resource_actions' + +#Cleanup------------------------------------------------------ + always: + + - name: delete a record with geo_location - continent_code + route53: + state: absent + zone: '{{ zone_one }}' + record: 'geo-test-1.{{ zone_one }}' + identifier: "geohost1@www" + type: A + value: 127.0.0.1 + ttl: 30 + geo_location: + continent_code: NA + ignore_errors: true + + - name: delete a record with geo_location - country_code + route53: + state: absent + zone: '{{ zone_one }}' + record: 'geo-test-2.{{ zone_one }}' + identifier: "geohost2@www" + type: A + value: 127.0.0.1 + ttl: 30 + geo_location: + country_code: US + ignore_errors: true + + - name: delete a record with geo_location - subdivision_code + route53: + state: absent + zone: '{{ zone_one }}' + record: 'geo-test-3.{{ zone_one }}' + identifier: "geohost3@www" + type: A + value: 127.0.0.1 + ttl: 30 + geo_location: + country_code: US + subdivision_code: TX + ignore_errors: true + - route53_info: query: record_sets hosted_zone_id: '{{ z1.zone_id }}' @@ -737,7 +1044,7 @@ state: absent zone: '{{ zone_one }}' register: delete_one - ignore_errors: yes + ignore_errors: true retries: 10 until: delete_one is not failed @@ -746,7 +1053,7 @@ state: absent zone: '{{ zone_two }}' register: delete_two - ignore_errors: yes + ignore_errors: True retries: 10 until: delete_two is not failed
Add route53 GeoLocation support <!--- Verify first that your feature was not already discussed on GitHub --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Describe the new feature/improvement briefly below --> Moving [issue](https://github.com/ansible/ansible/issues/24834) from Ansible repository. Add route53 GeoLocation support ##### ISSUE TYPE - Feature Idea Add change_resource_record_sets method to support route53 GeoLocation. This functionality is available in [salt](https://docs.saltstack.com/en/develop/ref/states/all/salt.states.boto3_route53.html) ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> Either update/upgrade route53 module, or create a new module to support adding/changing recourd sets. ##### ADDITIONAL INFORMATION <!--- Describe how the feature would be used, why it is needed and what it would solve --> <!--- Paste example playbooks or commands between quotes below --> ```yaml ``` <!--- HINT: You can also paste gist.github.com links for larger files -->
Files identified in the description: * [`plugins/modules/route53.py`](https://github.com/ansible-collections/community.aws/blob/main/plugins/modules/route53.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @jillr @jimbydamonk @s-hertel @tremble @wimnat [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> cc @markuman [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify --->
2022-05-04T22:48:58
ansible-collections/community.aws
1,128
ansible-collections__community.aws-1128
[ "1111" ]
6032b66677cd5ac5cb821673b928df8839c17254
diff --git a/plugins/modules/execute_lambda.py b/plugins/modules/execute_lambda.py --- a/plugins/modules/execute_lambda.py +++ b/plugins/modules/execute_lambda.py @@ -260,8 +260,10 @@ def main(): def wait_for_lambda(client, module, name): try: - waiter = client.get_waiter('function_active') - waiter.wait(FunctionName=name) + client_active_waiter = client.get_waiter('function_active') + client_updated_waiter = client.get_waiter('function_updated') + client_active_waiter.wait(FunctionName=name) + client_updated_waiter.wait(FunctionName=name) except botocore.exceptions.WaiterError as e: module.fail_json_aws(e, msg='Timeout while waiting on lambda to be Active') except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: diff --git a/plugins/modules/lambda.py b/plugins/modules/lambda.py --- a/plugins/modules/lambda.py +++ b/plugins/modules/lambda.py @@ -107,6 +107,11 @@ description: - Tag dict to apply to the function. type: dict + kms_key_arn: + description: + - The KMS key ARN used to encrypt the function's environment variables. + type: str + version_added: 3.3.0 author: - 'Steyn Huizinga (@steynovich)' extends_documentation_fragment: @@ -350,6 +355,7 @@ def main(): vpc_security_group_ids=dict(type='list', elements='str'), environment_variables=dict(type='dict'), dead_letter_arn=dict(), + kms_key_arn=dict(type='str', no_log=False), tracing_mode=dict(choices=['Active', 'PassThrough']), tags=dict(type='dict'), ) @@ -387,6 +393,7 @@ def main(): dead_letter_arn = module.params.get('dead_letter_arn') tracing_mode = module.params.get('tracing_mode') tags = module.params.get('tags') + kms_key_arn = module.params.get('kms_key_arn') check_mode = module.check_mode changed = False @@ -442,6 +449,8 @@ def main(): func_kwargs.update({'DeadLetterConfig': {'TargetArn': dead_letter_arn}}) if tracing_mode and (current_config.get('TracingConfig', {}).get('Mode', 'PassThrough') != tracing_mode): func_kwargs.update({'TracingConfig': {'Mode': tracing_mode}}) + if kms_key_arn: + func_kwargs.update({'KMSKeyArn': kms_key_arn}) # If VPC configuration is desired if vpc_subnet_ids: @@ -573,17 +582,23 @@ def main(): if tracing_mode: func_kwargs.update({'TracingConfig': {'Mode': tracing_mode}}) + if kms_key_arn: + func_kwargs.update({'KMSKeyArn': kms_key_arn}) + # If VPC configuration is given if vpc_subnet_ids: func_kwargs.update({'VpcConfig': {'SubnetIds': vpc_subnet_ids, 'SecurityGroupIds': vpc_security_group_ids}}) + # Function would have been created if not check mode + if check_mode: + module.exit_json(changed=True) + # Finally try to create function current_version = None try: - if not check_mode: - response = client.create_function(aws_retry=True, **func_kwargs) - current_version = response['Version'] + response = client.create_function(aws_retry=True, **func_kwargs) + current_version = response['Version'] changed = True except (BotoCoreError, ClientError) as e: module.fail_json_aws(e, msg="Trying to create function")
diff --git a/tests/integration/targets/lambda/tasks/main.yml b/tests/integration/targets/lambda/tasks/main.yml --- a/tests/integration/targets/lambda/tasks/main.yml +++ b/tests/integration/targets/lambda/tasks/main.yml @@ -93,6 +93,19 @@ - '"parameters are required together" in result.msg' # Prepare minimal Lambda + - name: test state=present - upload the lambda (check mode) + lambda: + name: '{{ lambda_function_name }}' + runtime: python3.6 + handler: mini_lambda.handler + role: '{{ lambda_role_name }}' + zip_file: '{{ zip_res.dest }}' + register: result + check_mode: yes + - name: assert lambda upload succeeded + assert: + that: + - result.changed - name: test state=present - upload the lambda lambda: @@ -105,7 +118,7 @@ - name: assert lambda upload succeeded assert: that: - - result is not failed + - result.changed - result.configuration.tracing_config.mode == "PassThrough" # Test basic operation of Uploaded lambda @@ -122,6 +135,25 @@ - result.result.output.message == "hello Mr Ansible Tests" # Test updating Lambda + - name: test lambda config updates (check mode) + lambda: + name: '{{lambda_function_name}}' + runtime: nodejs14.x + tracing_mode: Active + handler: mini_lambda.handler + role: '{{ lambda_role_name }}' + tags: + CamelCase: 'ACamelCaseValue' + snake_case: 'a_snake_case_value' + 'Spaced key': 'A value with spaces' + register: update_result + check_mode: yes + - name: assert that update succeeded + assert: + that: + - update_result is not failed + - update_result.changed == True + - name: test lambda config updates lambda: name: '{{lambda_function_name}}' @@ -142,6 +174,25 @@ - update_result.configuration.runtime == 'nodejs14.x' - update_result.configuration.tracing_config.mode == 'Active' + - name: test no changes are made with the same parameters repeated (check mode) + lambda: + name: '{{lambda_function_name}}' + runtime: nodejs14.x + tracing_mode: Active + handler: mini_lambda.handler + role: '{{ lambda_role_name }}' + tags: + CamelCase: 'ACamelCaseValue' + snake_case: 'a_snake_case_value' + 'Spaced key': 'A value with spaces' + register: update_result + check_mode: yes + - name: assert that update succeeded + assert: + that: + - update_result is not failed + - update_result.changed == False + - name: test no changes are made with the same parameters repeated lambda: name: '{{lambda_function_name}}' @@ -184,6 +235,7 @@ name: '{{ lambda_function_name }}' query: all register: lambda_infos_all + check_mode: yes - name: lambda_info | Assert successfull retrieval of all information assert: that: @@ -278,6 +330,23 @@ - result is not failed - result.changed == False + - name: test putting an environment variable changes lambda (check mode) + lambda: + name: '{{lambda_function_name}}' + runtime: python3.6 + handler: mini_lambda.handler + role: '{{ lambda_role_name }}' + zip_file: '{{zip_res.dest}}' + environment_variables: + EXTRA_MESSAGE: I think you are great!! + register: result + check_mode: yes + - name: assert lambda upload succeeded + assert: + that: + - result is not failed + - result.changed == True + - name: test putting an environment variable changes lambda lambda: name: '{{lambda_function_name}}' @@ -293,6 +362,8 @@ that: - result is not failed - result.changed == True + - result.configuration.environment.variables.extra_message == "I think you are great!!" + - name: test lambda works execute_lambda: name: '{{lambda_function_name}}' @@ -306,6 +377,19 @@ - result.result.output.message == "hello Mr Ansible Tests. I think you are great!!" # Deletion behavious + - name: test state=absent (expect changed=True) (check mode) + lambda: + name: '{{lambda_function_name}}' + state: absent + register: result + check_mode: yes + + - name: assert state=absent + assert: + that: + - result is not failed + - result is changed + - name: test state=absent (expect changed=True) lambda: name: '{{lambda_function_name}}' @@ -318,6 +402,19 @@ - result is not failed - result is changed + - name: test state=absent (expect changed=False) when already deleted (check mode) + lambda: + name: '{{lambda_function_name}}' + state: absent + register: result + check_mode: yes + + - name: assert state=absent + assert: + that: + - result is not failed + - result is not changed + - name: test state=absent (expect changed=False) when already deleted lambda: name: '{{lambda_function_name}}'
Add support for lambda KMSKeyArn ### Summary Please add support to set KMSKeyArn when creating and updating lambda functions. https://docs.aws.amazon.com/lambda/latest/dg/API_CreateFunction.html#SSS-CreateFunction-request-KMSKeyArn https://docs.aws.amazon.com/lambda/latest/dg/API_UpdateFunctionCode.html#SSS-UpdateFunctionCode-response-KMSKeyArn ### Issue Type Feature Idea ### Component Name lambda ### Additional Information _No response_ ### Code of Conduct - [X] I agree to follow the Ansible Code of Conduct
Files identified in the description: * [`plugins/modules/lambda.py`](https://github.com/['ansible-collections/amazon.aws', 'ansible-collections/community.aws', 'ansible-collections/community.vmware']/blob/main/plugins/modules/lambda.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @jillr @markuman @s-hertel @steynovich @tremble [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> @sethernet thanks for this request - added it as part of https://github.com/ansible-collections/community.aws/pull/1108. Let me know if that works!
2022-05-06T12:52:42
ansible-collections/community.aws
1,131
ansible-collections__community.aws-1131
[ "1084" ]
2277f5cf9ed8243c6a13903ef109fc0b88f76626
diff --git a/plugins/modules/s3_lifecycle.py b/plugins/modules/s3_lifecycle.py --- a/plugins/modules/s3_lifecycle.py +++ b/plugins/modules/s3_lifecycle.py @@ -485,15 +485,23 @@ def create_lifecycle_rule(client, module): _changed = changed _retries = 10 - while wait and _changed and _retries: + _not_changed_cnt = 6 + while wait and _changed and _retries and _not_changed_cnt: # We've seen examples where get_bucket_lifecycle_configuration returns - # the updated rules, then the old rules, then the updated rules again, + # the updated rules, then the old rules, then the updated rules again and + # again couple of times. + # Thus try to read the rule few times in a row to check if it has changed. time.sleep(5) _retries -= 1 new_rules = fetch_rules(client, module, name) (_changed, lifecycle_configuration) = compare_and_update_configuration(client, module, new_rules, new_rule) + if not _changed: + _not_changed_cnt -= 1 + _changed = True + else: + _not_changed_cnt = 6 new_rules = fetch_rules(client, module, name) @@ -531,13 +539,21 @@ def destroy_lifecycle_rule(client, module): _changed = changed _retries = 10 - while wait and _changed and _retries: + _not_changed_cnt = 6 + while wait and _changed and _retries and _not_changed_cnt: # We've seen examples where get_bucket_lifecycle_configuration returns - # the updated rules, then the old rules, then the updated rules again, + # the updated rules, then the old rules, then the updated rules again and + # again couple of times. + # Thus try to read the rule few times in a row to check if it has changed. time.sleep(5) _retries -= 1 new_rules = fetch_rules(client, module, name) (_changed, lifecycle_configuration) = compare_and_remove_rule(new_rules, rule_id, prefix) + if not _changed: + _not_changed_cnt -= 1 + _changed = True + else: + _not_changed_cnt = 6 new_rules = fetch_rules(client, module, name)
diff --git a/tests/integration/targets/s3_lifecycle/tasks/main.yml b/tests/integration/targets/s3_lifecycle/tasks/main.yml --- a/tests/integration/targets/s3_lifecycle/tasks/main.yml +++ b/tests/integration/targets/s3_lifecycle/tasks/main.yml @@ -24,6 +24,42 @@ - output.changed - output.name == bucket_name - not output.requester_pays + # ============================================================ + - name: Create a number of policies and check if all of them are created + community.aws.s3_lifecycle: + name: "{{ bucket_name }}" + rule_id: "{{ item }}" + expiration_days: 10 + prefix: "{{ item }}" + status: enabled + state: present + wait: yes + register: output + loop: + - rule_1 + - rule_2 + - rule_3 + - assert: + that: + - (output.results | last).rules | length == 3 + # ============================================================ + - name: Remove previously created policies and check if all of them are removed + community.aws.s3_lifecycle: + name: "{{ bucket_name }}" + rule_id: "{{ item }}" + expiration_days: 10 + prefix: "{{ item }}" + status: enabled + state: absent + wait: yes + register: output + loop: + - rule_1 + - rule_2 + - rule_3 + - assert: + that: + - (output.results | last).rules | length == 0 # ============================================================ - name: Create a lifecycle policy s3_lifecycle:
s3_lifecycle - occasionally fails to add/remove all rules from playbook ### Summary Sometimes not all rules from playbook are added or removed. It occurs even if 'wait' parameter is set to 'yes'. It was observed that shortly (~30s) after setting the rules with the plugin. get-bucket-lifecycle returns alternatively new and old rules in a random manner. Similar issue has been reported in boto3 library. https://github.com/boto/boto3/issues/2491 ### Issue Type Bug Report ### Component Name s3_lifecycle ### Ansible Version ```console (paste below) $ ansible --version ansible [core 2.12.4] config file = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/ansible.cfg configured module search path = ['/home/rubin/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/lib/python3.8/site-packages/ansible ansible collection location = /home/rubin/.ansible/collections:/usr/share/ansible/collections executable location = ./env/bin/ansible python version = 3.8.10 (default, Mar 15 2022, 12:22:08) [GCC 9.4.0] jinja version = 3.1.1 libyaml = True ``` ### Collection Versions ```console (paste below) $ ansible-galaxy collection list Collection Version ----------------------------- ------- amazon.aws 2.2.0 ansible.netcommon 2.6.1 ansible.posix 1.3.0 ansible.utils 2.5.2 ansible.windows 1.9.0 arista.eos 3.1.0 awx.awx 19.4.0 azure.azcollection 1.12.0 check_point.mgmt 2.3.0 chocolatey.chocolatey 1.2.0 cisco.aci 2.2.0 cisco.asa 2.1.0 cisco.intersight 1.0.18 cisco.ios 2.8.1 cisco.iosxr 2.9.0 cisco.ise 1.2.1 cisco.meraki 2.6.1 cisco.mso 1.4.0 cisco.nso 1.0.3 cisco.nxos 2.9.1 cisco.ucs 1.8.0 cloud.common 2.1.0 cloudscale_ch.cloud 2.2.1 community.aws 2.4.0 community.azure 1.1.0 community.ciscosmb 1.0.4 community.crypto 2.2.4 community.digitalocean 1.16.0 community.dns 2.0.9 community.docker 2.3.0 community.fortios 1.0.0 community.general 4.7.0 community.google 1.0.0 community.grafana 1.3.3 community.hashi_vault 2.4.0 community.hrobot 1.2.3 community.kubernetes 2.0.1 community.kubevirt 1.0.0 community.libvirt 1.0.2 community.mongodb 1.3.3 community.mysql 2.3.5 community.network 3.1.0 community.okd 2.1.0 community.postgresql 1.7.1 community.proxysql 1.3.1 community.rabbitmq 1.1.0 community.routeros 2.0.0 community.sap 1.0.0 community.skydive 1.0.0 community.sops 1.2.1 community.vmware 1.18.0 community.windows 1.9.0 community.zabbix 1.5.1 containers.podman 1.9.3 cyberark.conjur 1.1.0 cyberark.pas 1.0.13 dellemc.enterprise_sonic 1.1.0 dellemc.openmanage 4.4.0 dellemc.os10 1.1.1 dellemc.os6 1.0.7 dellemc.os9 1.0.4 f5networks.f5_modules 1.15.0 fortinet.fortimanager 2.1.4 fortinet.fortios 2.1.4 frr.frr 1.0.3 gluster.gluster 1.0.2 google.cloud 1.0.2 hetzner.hcloud 1.6.0 hpe.nimble 1.1.4 ibm.qradar 1.0.3 infinidat.infinibox 1.3.3 infoblox.nios_modules 1.2.1 inspur.sm 1.3.0 junipernetworks.junos 2.10.0 kubernetes.core 2.3.0 mellanox.onyx 1.0.0 netapp.aws 21.7.0 netapp.azure 21.10.0 netapp.cloudmanager 21.15.0 netapp.elementsw 21.7.0 netapp.ontap 21.17.3 netapp.storagegrid 21.10.0 netapp.um_info 21.8.0 netapp_eseries.santricity 1.3.0 netbox.netbox 3.6.0 ngine_io.cloudstack 2.2.3 ngine_io.exoscale 1.0.0 ngine_io.vultr 1.1.1 openstack.cloud 1.7.2 openvswitch.openvswitch 2.1.0 ovirt.ovirt 1.6.6 purestorage.flasharray 1.12.1 purestorage.flashblade 1.9.0 sensu.sensu_go 1.13.0 servicenow.servicenow 1.0.6 splunk.es 1.0.2 t_systems_mms.icinga_director 1.28.0 theforeman.foreman 2.2.0 vyos.vyos 2.8.0 wti.remote 1.0.3 ``` ### AWS SDK versions ```console (paste below) $ pip show boto boto3 botocore WARNING: Package(s) not found: boto Name: boto3 Version: 1.21.39 Summary: The AWS SDK for Python Home-page: https://github.com/boto/boto3 Author: Amazon Web Services Author-email: License: Apache License 2.0 Location: /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/lib/python3.8/site-packages Requires: botocore, jmespath, s3transfer Required-by: --- Name: botocore Version: 1.24.39 Summary: Low-level, data-driven core of boto 3. Home-page: https://github.com/boto/botocore Author: Amazon Web Services Author-email: License: Apache License 2.0 Location: /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/lib/python3.8/site-packages Requires: jmespath, python-dateutil, urllib3 Required-by: boto3, s3transfer ``` ### Configuration ```console (paste below) $ ansible-config dump --only-changed ANSIBLE_PIPELINING(/work/ansible/ansible.cfg) = True DEFAULT_HOST_LIST(/work/ansible/ansible.cfg) = ['/work/ansible/hosts'] DEFAULT_LOG_PATH(/work/ansible/ansible.cfg) = /work/ansible/tmp/ansible.log INTERPRETER_PYTHON(/work/ansible/ansible.cfg) = auto ``` ### OS / Environment Ubuntu 20.04.3 Python 3.8.10 ### Steps to Reproduce <!--- Paste example playbooks or commands between quotes below --> 1. Create playbook file to create/remove 3 lifecycle rules ```console (paste below) $ cat << EOF >> lifecycle_wait_issue.yml --- - hosts: local gather_facts: False vars: bucket: bucket_name state: present tasks: - name: "exemplary cleanup rule" community.aws.s3_lifecycle: name: "{{ bucket }}" rule_id: cleanup_rule_1 noncurrent_version_expiration_days: 1 prefix: "" status: enabled state: "{{ state }}" wait: yes - name: "{{ bucket }} - exemplary loop rule" community.aws.s3_lifecycle: name: "{{ bucket }}" rule_id: "{{ item.rule_id }}" expiration_days: 14 prefix: "{{ item.prefix }}" status: enabled state: "{{ state }}" wait: yes loop: - { rule_id: loop_rule_id_1, prefix: prefix_1 } - { rule_id: loop_rule_id_2, prefix: prefix_2 } EOF ``` 2. Run below script NOTE! Below steps assume there are no other lifecycle rules in the bucket. ```bash BUCKET=<set-your-bucket-here> reproduced=false step=1 #set -x while [ $step -le 10 ] ; do echo "[$step/10] Adding rules..." # Add 3 rules according to the playbook ansible-playbook -vv lifecycle_wait_issue.yml -e "bucket=$BUCKET" -e "state=present" rules=$(aws s3api get-bucket-lifecycle --bucket $BUCKET --query 'Rules[*][ID]' --output text) cnt=$(echo "$rules" | wc -l) # 3 rules are expected if [ $cnt != 3 ] ; then echo "issue reproduced, 3 rules expected, $cnt rules found:" echo "$rules" reproduced=true break fi echo "[$step/10] Removing rules..." # Remove all rules ansible-playbook -vv lifecycle_wait_issue.yml -e "bucket=$BUCKET" -e "state=absent" # expected error: The lifecycle configuration does not exist rules=$(aws s3api get-bucket-lifecycle --bucket $BUCKET --query 'Rules[*][ID]' --output text) if [ $? -ne 254 ] ; then cnt=$(echo "$rules" | wc -l) echo "issue reproduced, 0 rules expected, $cnt rules found:" echo "$rules" reproduced=true break fi step=$(( step + 1)) done if ! $reproduced ; then echo 'issue not reproduced' fi ``` ### Expected Results Script prints: ```console issue not reproduced ``` which means it was able to successfully: - add 3 rules - remove 3 added rules in 10 consecutive steps. ### Actual Results Script prints: ```console (paste below) issue reproduced, ... ``` Example 1: ```console [1/10] Adding rules... ansible-playbook [core 2.12.4] config file = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/ansible.cfg configured module search path = ['/home/rubin/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/lib/python3.8/site-packages/ansible ansible collection location = /home/rubin/.ansible/collections:/usr/share/ansible/collections executable location = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/bin/ansible-playbook python version = 3.8.10 (default, Mar 15 2022, 12:22:08) [GCC 9.4.0] jinja version = 3.1.1 libyaml = True Using /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/ansible.cfg as config file Skipping callback 'default', as we already have a stdout callback. Skipping callback 'minimal', as we already have a stdout callback. Skipping callback 'oneline', as we already have a stdout callback. PLAYBOOK: lifecycle_wait_issue.yml ********************************************************************************************************************************************************************************* 1 plays in lifecycle_wait_issue.yml PLAY [local] ******************************************************************************************************************************************************************************************************* META: ran handlers TASK [exemplary cleanup rule] ************************************************************************************************************************************************************************************** task path: /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/lifecycle_wait_issue.yml:10 changed: [localhost] => {"_config": {"Rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}]}, "_retries": 9, "ansible_facts": {"discovered_interpreter_python": "/usr/bin/python3"}, "changed": true, "new_rule": {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}, "old_rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}], "rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}]} TASK [lgi-onemw-staging-dawn-base - exemplary loop rule] *********************************************************************************************************************************************************** task path: /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/lifecycle_wait_issue.yml:20 ok: [localhost] => (item={'rule_id': 'loop_rule_id_1', 'prefix': 'prefix_1'}) => {"_config": {"Rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}]}, "_retries": 10, "ansible_loop_var": "item", "changed": false, "item": {"prefix": "prefix_1", "rule_id": "loop_rule_id_1"}, "new_rule": {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, "old_rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}], "rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}]} ok: [localhost] => (item={'rule_id': 'loop_rule_id_2', 'prefix': 'prefix_2'}) => {"_config": {"Rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}]}, "_retries": 10, "ansible_loop_var": "item", "changed": false, "item": {"prefix": "prefix_2", "rule_id": "loop_rule_id_2"}, "new_rule": {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, "old_rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}], "rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}]} META: ran handlers META: ran handlers PLAY RECAP ********************************************************************************************************************************************************************************************************* localhost : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 [1/10] Removing rules... ansible-playbook [core 2.12.4] config file = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/ansible.cfg configured module search path = ['/home/rubin/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/lib/python3.8/site-packages/ansible ansible collection location = /home/rubin/.ansible/collections:/usr/share/ansible/collections executable location = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/bin/ansible-playbook python version = 3.8.10 (default, Mar 15 2022, 12:22:08) [GCC 9.4.0] jinja version = 3.1.1 libyaml = True Using /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/ansible.cfg as config file Skipping callback 'default', as we already have a stdout callback. Skipping callback 'minimal', as we already have a stdout callback. Skipping callback 'oneline', as we already have a stdout callback. PLAYBOOK: lifecycle_wait_issue.yml ********************************************************************************************************************************************************************************* 1 plays in lifecycle_wait_issue.yml PLAY [local] ******************************************************************************************************************************************************************************************************* META: ran handlers TASK [exemplary cleanup rule] ************************************************************************************************************************************************************************************** task path: /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/lifecycle_wait_issue.yml:10 changed: [localhost] => {"_retries": 9, "ansible_facts": {"discovered_interpreter_python": "/usr/bin/python3"}, "changed": true, "old_rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}], "rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}]} TASK [lgi-onemw-staging-dawn-base - exemplary loop rule] *********************************************************************************************************************************************************** task path: /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/lifecycle_wait_issue.yml:20 changed: [localhost] => (item={'rule_id': 'loop_rule_id_1', 'prefix': 'prefix_1'}) => {"_retries": 9, "ansible_loop_var": "item", "changed": true, "item": {"prefix": "prefix_1", "rule_id": "loop_rule_id_1"}, "old_rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}], "rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}]} changed: [localhost] => (item={'rule_id': 'loop_rule_id_2', 'prefix': 'prefix_2'}) => {"_retries": 8, "ansible_loop_var": "item", "changed": true, "item": {"prefix": "prefix_2", "rule_id": "loop_rule_id_2"}, "old_rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}], "rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}]} META: ran handlers META: ran handlers PLAY RECAP ********************************************************************************************************************************************************************************************************* localhost : ok=2 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 An error occurred (NoSuchLifecycleConfiguration) when calling the GetBucketLifecycle operation: The lifecycle configuration does not exist [2/10] Adding rules... ansible-playbook [core 2.12.4] config file = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/ansible.cfg configured module search path = ['/home/rubin/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/lib/python3.8/site-packages/ansible ansible collection location = /home/rubin/.ansible/collections:/usr/share/ansible/collections executable location = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/bin/ansible-playbook python version = 3.8.10 (default, Mar 15 2022, 12:22:08) [GCC 9.4.0] jinja version = 3.1.1 libyaml = True Using /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/ansible.cfg as config file Skipping callback 'default', as we already have a stdout callback. Skipping callback 'minimal', as we already have a stdout callback. Skipping callback 'oneline', as we already have a stdout callback. PLAYBOOK: lifecycle_wait_issue.yml ******************************************************************************************************************************************************************************************************************************************************** 1 plays in lifecycle_wait_issue.yml PLAY [local] ****************************************************************************************************************************************************************************************************************************************************************************** META: ran handlers TASK [exemplary cleanup rule] ************************************************************************************************************************************************************************************************************************************************************* task path: /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/lifecycle_wait_issue.yml:10 changed: [localhost] => {"_config": {"Rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}]}, "_retries": 8, "ansible_facts": {"discovered_interpreter_python": "/usr/bin/python3"}, "changed": true, "new_rule": {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}, "old_rules": [], "rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}]} TASK [lgi-onemw-staging-dawn-base - exemplary loop rule] ********************************************************************************************************************************************************************************************************************************** task path: /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/lifecycle_wait_issue.yml:20 changed: [localhost] => (item={'rule_id': 'loop_rule_id_1', 'prefix': 'prefix_1'}) => {"_config": {"Rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}]}, "_retries": 9, "ansible_loop_var": "item", "changed": true, "item": {"prefix": "prefix_1", "rule_id": "loop_rule_id_1"}, "new_rule": {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, "old_rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}], "rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}]} changed: [localhost] => (item={'rule_id': 'loop_rule_id_2', 'prefix': 'prefix_2'}) => {"_config": {"Rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}]}, "_retries": 9, "ansible_loop_var": "item", "changed": true, "item": {"prefix": "prefix_2", "rule_id": "loop_rule_id_2"}, "new_rule": {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, "old_rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}], "rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}]} META: ran handlers META: ran handlers PLAY RECAP ******************************************************************************************************************************************************************************************************************************************************************************** localhost : ok=2 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 [2/10] Removing rules... ansible-playbook [core 2.12.4] config file = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/ansible.cfg configured module search path = ['/home/rubin/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/lib/python3.8/site-packages/ansible ansible collection location = /home/rubin/.ansible/collections:/usr/share/ansible/collections executable location = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/bin/ansible-playbook python version = 3.8.10 (default, Mar 15 2022, 12:22:08) [GCC 9.4.0] jinja version = 3.1.1 libyaml = True Using /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/ansible.cfg as config file Skipping callback 'default', as we already have a stdout callback. Skipping callback 'minimal', as we already have a stdout callback. Skipping callback 'oneline', as we already have a stdout callback. PLAYBOOK: lifecycle_wait_issue.yml ******************************************************************************************************************************************************************************************************************************************************** 1 plays in lifecycle_wait_issue.yml PLAY [local] ****************************************************************************************************************************************************************************************************************************************************************************** META: ran handlers TASK [exemplary cleanup rule] ************************************************************************************************************************************************************************************************************************************************************* task path: /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/lifecycle_wait_issue.yml:10 changed: [localhost] => {"_retries": 9, "ansible_facts": {"discovered_interpreter_python": "/usr/bin/python3"}, "changed": true, "old_rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}], "rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}]} TASK [lgi-onemw-staging-dawn-base - exemplary loop rule] ********************************************************************************************************************************************************************************************************************************** task path: /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/lifecycle_wait_issue.yml:20 changed: [localhost] => (item={'rule_id': 'loop_rule_id_1', 'prefix': 'prefix_1'}) => {"_retries": 8, "ansible_loop_var": "item", "changed": true, "item": {"prefix": "prefix_1", "rule_id": "loop_rule_id_1"}, "old_rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}], "rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}]} changed: [localhost] => (item={'rule_id': 'loop_rule_id_2', 'prefix': 'prefix_2'}) => {"_retries": 9, "ansible_loop_var": "item", "changed": true, "item": {"prefix": "prefix_2", "rule_id": "loop_rule_id_2"}, "old_rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}], "rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}]} META: ran handlers META: ran handlers PLAY RECAP ******************************************************************************************************************************************************************************************************************************************************************************** localhost : ok=2 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 issue reproduced, 0 rules expected, 2 rules found: cleanup_rule_1 loop_rule_id_2 ``` Example 2: ```console [1/10] Adding rules... ansible-playbook [core 2.12.4] config file = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/ansible.cfg configured module search path = ['/home/rubin/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/lib/python3.8/site-packages/ansible ansible collection location = /home/rubin/.ansible/collections:/usr/share/ansible/collections executable location = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/bin/ansible-playbook python version = 3.8.10 (default, Mar 15 2022, 12:22:08) [GCC 9.4.0] jinja version = 3.1.1 libyaml = True Using /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/ansible.cfg as config file Skipping callback 'default', as we already have a stdout callback. Skipping callback 'minimal', as we already have a stdout callback. Skipping callback 'oneline', as we already have a stdout callback. PLAYBOOK: lifecycle_wait_issue.yml ********************************************************************************************************************************************************************************* 1 plays in lifecycle_wait_issue.yml PLAY [local] ******************************************************************************************************************************************************************************************************* META: ran handlers TASK [exemplary cleanup rule] ************************************************************************************************************************************************************************************** task path: /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/lifecycle_wait_issue.yml:10 changed: [localhost] => {"_config": {"Rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}]}, "_retries": 8, "ansible_facts": {"discovered_interpreter_python": "/usr/bin/python3"}, "changed": true, "new_rule": {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}, "old_rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}], "rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}]} TASK [lgi-onemw-staging-dawn-base - exemplary loop rule] *********************************************************************************************************************************************************** task path: /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/lifecycle_wait_issue.yml:20 changed: [localhost] => (item={'rule_id': 'loop_rule_id_1', 'prefix': 'prefix_1'}) => {"_config": {"Rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}]}, "_retries": 9, "ansible_loop_var": "item", "changed": true, "item": {"prefix": "prefix_1", "rule_id": "loop_rule_id_1"}, "new_rule": {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, "old_rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}], "rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}]} ok: [localhost] => (item={'rule_id': 'loop_rule_id_2', 'prefix': 'prefix_2'}) => {"_config": {"Rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}]}, "_retries": 10, "ansible_loop_var": "item", "changed": false, "item": {"prefix": "prefix_2", "rule_id": "loop_rule_id_2"}, "new_rule": {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, "old_rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}], "rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}]} META: ran handlers META: ran handlers PLAY RECAP ********************************************************************************************************************************************************************************************************* localhost : ok=2 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 issue reproduced, 3 rules expected, 2 rules found: loop_rule_id_2 loop_rule_id_1 ``` It cannot reliably add or remove rules from playbook. ### Code of Conduct - [X] I agree to follow the Ansible Code of Conduct
Files identified in the description: * [`plugins/modules/s3_lifecycle.py`](https://github.com/['ansible-collections/amazon.aws', 'ansible-collections/community.aws', 'ansible-collections/community.vmware']/blob/main/plugins/modules/s3_lifecycle.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @jillr @markuman @s-hertel @tremble [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify --->
2022-05-06T21:36:37
ansible-collections/community.aws
1,132
ansible-collections__community.aws-1132
[ "1084" ]
4bf05cad35f4e70ffe715a96af236ec80e1e79a2
diff --git a/plugins/modules/s3_lifecycle.py b/plugins/modules/s3_lifecycle.py --- a/plugins/modules/s3_lifecycle.py +++ b/plugins/modules/s3_lifecycle.py @@ -485,15 +485,23 @@ def create_lifecycle_rule(client, module): _changed = changed _retries = 10 - while wait and _changed and _retries: + _not_changed_cnt = 6 + while wait and _changed and _retries and _not_changed_cnt: # We've seen examples where get_bucket_lifecycle_configuration returns - # the updated rules, then the old rules, then the updated rules again, + # the updated rules, then the old rules, then the updated rules again and + # again couple of times. + # Thus try to read the rule few times in a row to check if it has changed. time.sleep(5) _retries -= 1 new_rules = fetch_rules(client, module, name) (_changed, lifecycle_configuration) = compare_and_update_configuration(client, module, new_rules, new_rule) + if not _changed: + _not_changed_cnt -= 1 + _changed = True + else: + _not_changed_cnt = 6 new_rules = fetch_rules(client, module, name) @@ -531,13 +539,21 @@ def destroy_lifecycle_rule(client, module): _changed = changed _retries = 10 - while wait and _changed and _retries: + _not_changed_cnt = 6 + while wait and _changed and _retries and _not_changed_cnt: # We've seen examples where get_bucket_lifecycle_configuration returns - # the updated rules, then the old rules, then the updated rules again, + # the updated rules, then the old rules, then the updated rules again and + # again couple of times. + # Thus try to read the rule few times in a row to check if it has changed. time.sleep(5) _retries -= 1 new_rules = fetch_rules(client, module, name) (_changed, lifecycle_configuration) = compare_and_remove_rule(new_rules, rule_id, prefix) + if not _changed: + _not_changed_cnt -= 1 + _changed = True + else: + _not_changed_cnt = 6 new_rules = fetch_rules(client, module, name)
diff --git a/tests/integration/targets/s3_lifecycle/tasks/main.yml b/tests/integration/targets/s3_lifecycle/tasks/main.yml --- a/tests/integration/targets/s3_lifecycle/tasks/main.yml +++ b/tests/integration/targets/s3_lifecycle/tasks/main.yml @@ -24,6 +24,42 @@ - output.changed - output.name == bucket_name - not output.requester_pays + # ============================================================ + - name: Create a number of policies and check if all of them are created + community.aws.s3_lifecycle: + name: "{{ bucket_name }}" + rule_id: "{{ item }}" + expiration_days: 10 + prefix: "{{ item }}" + status: enabled + state: present + wait: yes + register: output + loop: + - rule_1 + - rule_2 + - rule_3 + - assert: + that: + - (output.results | last).rules | length == 3 + # ============================================================ + - name: Remove previously created policies and check if all of them are removed + community.aws.s3_lifecycle: + name: "{{ bucket_name }}" + rule_id: "{{ item }}" + expiration_days: 10 + prefix: "{{ item }}" + status: enabled + state: absent + wait: yes + register: output + loop: + - rule_1 + - rule_2 + - rule_3 + - assert: + that: + - (output.results | last).rules | length == 0 # ============================================================ - name: Create a lifecycle policy s3_lifecycle:
s3_lifecycle - occasionally fails to add/remove all rules from playbook ### Summary Sometimes not all rules from playbook are added or removed. It occurs even if 'wait' parameter is set to 'yes'. It was observed that shortly (~30s) after setting the rules with the plugin. get-bucket-lifecycle returns alternatively new and old rules in a random manner. Similar issue has been reported in boto3 library. https://github.com/boto/boto3/issues/2491 ### Issue Type Bug Report ### Component Name s3_lifecycle ### Ansible Version ```console (paste below) $ ansible --version ansible [core 2.12.4] config file = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/ansible.cfg configured module search path = ['/home/rubin/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/lib/python3.8/site-packages/ansible ansible collection location = /home/rubin/.ansible/collections:/usr/share/ansible/collections executable location = ./env/bin/ansible python version = 3.8.10 (default, Mar 15 2022, 12:22:08) [GCC 9.4.0] jinja version = 3.1.1 libyaml = True ``` ### Collection Versions ```console (paste below) $ ansible-galaxy collection list Collection Version ----------------------------- ------- amazon.aws 2.2.0 ansible.netcommon 2.6.1 ansible.posix 1.3.0 ansible.utils 2.5.2 ansible.windows 1.9.0 arista.eos 3.1.0 awx.awx 19.4.0 azure.azcollection 1.12.0 check_point.mgmt 2.3.0 chocolatey.chocolatey 1.2.0 cisco.aci 2.2.0 cisco.asa 2.1.0 cisco.intersight 1.0.18 cisco.ios 2.8.1 cisco.iosxr 2.9.0 cisco.ise 1.2.1 cisco.meraki 2.6.1 cisco.mso 1.4.0 cisco.nso 1.0.3 cisco.nxos 2.9.1 cisco.ucs 1.8.0 cloud.common 2.1.0 cloudscale_ch.cloud 2.2.1 community.aws 2.4.0 community.azure 1.1.0 community.ciscosmb 1.0.4 community.crypto 2.2.4 community.digitalocean 1.16.0 community.dns 2.0.9 community.docker 2.3.0 community.fortios 1.0.0 community.general 4.7.0 community.google 1.0.0 community.grafana 1.3.3 community.hashi_vault 2.4.0 community.hrobot 1.2.3 community.kubernetes 2.0.1 community.kubevirt 1.0.0 community.libvirt 1.0.2 community.mongodb 1.3.3 community.mysql 2.3.5 community.network 3.1.0 community.okd 2.1.0 community.postgresql 1.7.1 community.proxysql 1.3.1 community.rabbitmq 1.1.0 community.routeros 2.0.0 community.sap 1.0.0 community.skydive 1.0.0 community.sops 1.2.1 community.vmware 1.18.0 community.windows 1.9.0 community.zabbix 1.5.1 containers.podman 1.9.3 cyberark.conjur 1.1.0 cyberark.pas 1.0.13 dellemc.enterprise_sonic 1.1.0 dellemc.openmanage 4.4.0 dellemc.os10 1.1.1 dellemc.os6 1.0.7 dellemc.os9 1.0.4 f5networks.f5_modules 1.15.0 fortinet.fortimanager 2.1.4 fortinet.fortios 2.1.4 frr.frr 1.0.3 gluster.gluster 1.0.2 google.cloud 1.0.2 hetzner.hcloud 1.6.0 hpe.nimble 1.1.4 ibm.qradar 1.0.3 infinidat.infinibox 1.3.3 infoblox.nios_modules 1.2.1 inspur.sm 1.3.0 junipernetworks.junos 2.10.0 kubernetes.core 2.3.0 mellanox.onyx 1.0.0 netapp.aws 21.7.0 netapp.azure 21.10.0 netapp.cloudmanager 21.15.0 netapp.elementsw 21.7.0 netapp.ontap 21.17.3 netapp.storagegrid 21.10.0 netapp.um_info 21.8.0 netapp_eseries.santricity 1.3.0 netbox.netbox 3.6.0 ngine_io.cloudstack 2.2.3 ngine_io.exoscale 1.0.0 ngine_io.vultr 1.1.1 openstack.cloud 1.7.2 openvswitch.openvswitch 2.1.0 ovirt.ovirt 1.6.6 purestorage.flasharray 1.12.1 purestorage.flashblade 1.9.0 sensu.sensu_go 1.13.0 servicenow.servicenow 1.0.6 splunk.es 1.0.2 t_systems_mms.icinga_director 1.28.0 theforeman.foreman 2.2.0 vyos.vyos 2.8.0 wti.remote 1.0.3 ``` ### AWS SDK versions ```console (paste below) $ pip show boto boto3 botocore WARNING: Package(s) not found: boto Name: boto3 Version: 1.21.39 Summary: The AWS SDK for Python Home-page: https://github.com/boto/boto3 Author: Amazon Web Services Author-email: License: Apache License 2.0 Location: /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/lib/python3.8/site-packages Requires: botocore, jmespath, s3transfer Required-by: --- Name: botocore Version: 1.24.39 Summary: Low-level, data-driven core of boto 3. Home-page: https://github.com/boto/botocore Author: Amazon Web Services Author-email: License: Apache License 2.0 Location: /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/lib/python3.8/site-packages Requires: jmespath, python-dateutil, urllib3 Required-by: boto3, s3transfer ``` ### Configuration ```console (paste below) $ ansible-config dump --only-changed ANSIBLE_PIPELINING(/work/ansible/ansible.cfg) = True DEFAULT_HOST_LIST(/work/ansible/ansible.cfg) = ['/work/ansible/hosts'] DEFAULT_LOG_PATH(/work/ansible/ansible.cfg) = /work/ansible/tmp/ansible.log INTERPRETER_PYTHON(/work/ansible/ansible.cfg) = auto ``` ### OS / Environment Ubuntu 20.04.3 Python 3.8.10 ### Steps to Reproduce <!--- Paste example playbooks or commands between quotes below --> 1. Create playbook file to create/remove 3 lifecycle rules ```console (paste below) $ cat << EOF >> lifecycle_wait_issue.yml --- - hosts: local gather_facts: False vars: bucket: bucket_name state: present tasks: - name: "exemplary cleanup rule" community.aws.s3_lifecycle: name: "{{ bucket }}" rule_id: cleanup_rule_1 noncurrent_version_expiration_days: 1 prefix: "" status: enabled state: "{{ state }}" wait: yes - name: "{{ bucket }} - exemplary loop rule" community.aws.s3_lifecycle: name: "{{ bucket }}" rule_id: "{{ item.rule_id }}" expiration_days: 14 prefix: "{{ item.prefix }}" status: enabled state: "{{ state }}" wait: yes loop: - { rule_id: loop_rule_id_1, prefix: prefix_1 } - { rule_id: loop_rule_id_2, prefix: prefix_2 } EOF ``` 2. Run below script NOTE! Below steps assume there are no other lifecycle rules in the bucket. ```bash BUCKET=<set-your-bucket-here> reproduced=false step=1 #set -x while [ $step -le 10 ] ; do echo "[$step/10] Adding rules..." # Add 3 rules according to the playbook ansible-playbook -vv lifecycle_wait_issue.yml -e "bucket=$BUCKET" -e "state=present" rules=$(aws s3api get-bucket-lifecycle --bucket $BUCKET --query 'Rules[*][ID]' --output text) cnt=$(echo "$rules" | wc -l) # 3 rules are expected if [ $cnt != 3 ] ; then echo "issue reproduced, 3 rules expected, $cnt rules found:" echo "$rules" reproduced=true break fi echo "[$step/10] Removing rules..." # Remove all rules ansible-playbook -vv lifecycle_wait_issue.yml -e "bucket=$BUCKET" -e "state=absent" # expected error: The lifecycle configuration does not exist rules=$(aws s3api get-bucket-lifecycle --bucket $BUCKET --query 'Rules[*][ID]' --output text) if [ $? -ne 254 ] ; then cnt=$(echo "$rules" | wc -l) echo "issue reproduced, 0 rules expected, $cnt rules found:" echo "$rules" reproduced=true break fi step=$(( step + 1)) done if ! $reproduced ; then echo 'issue not reproduced' fi ``` ### Expected Results Script prints: ```console issue not reproduced ``` which means it was able to successfully: - add 3 rules - remove 3 added rules in 10 consecutive steps. ### Actual Results Script prints: ```console (paste below) issue reproduced, ... ``` Example 1: ```console [1/10] Adding rules... ansible-playbook [core 2.12.4] config file = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/ansible.cfg configured module search path = ['/home/rubin/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/lib/python3.8/site-packages/ansible ansible collection location = /home/rubin/.ansible/collections:/usr/share/ansible/collections executable location = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/bin/ansible-playbook python version = 3.8.10 (default, Mar 15 2022, 12:22:08) [GCC 9.4.0] jinja version = 3.1.1 libyaml = True Using /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/ansible.cfg as config file Skipping callback 'default', as we already have a stdout callback. Skipping callback 'minimal', as we already have a stdout callback. Skipping callback 'oneline', as we already have a stdout callback. PLAYBOOK: lifecycle_wait_issue.yml ********************************************************************************************************************************************************************************* 1 plays in lifecycle_wait_issue.yml PLAY [local] ******************************************************************************************************************************************************************************************************* META: ran handlers TASK [exemplary cleanup rule] ************************************************************************************************************************************************************************************** task path: /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/lifecycle_wait_issue.yml:10 changed: [localhost] => {"_config": {"Rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}]}, "_retries": 9, "ansible_facts": {"discovered_interpreter_python": "/usr/bin/python3"}, "changed": true, "new_rule": {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}, "old_rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}], "rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}]} TASK [lgi-onemw-staging-dawn-base - exemplary loop rule] *********************************************************************************************************************************************************** task path: /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/lifecycle_wait_issue.yml:20 ok: [localhost] => (item={'rule_id': 'loop_rule_id_1', 'prefix': 'prefix_1'}) => {"_config": {"Rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}]}, "_retries": 10, "ansible_loop_var": "item", "changed": false, "item": {"prefix": "prefix_1", "rule_id": "loop_rule_id_1"}, "new_rule": {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, "old_rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}], "rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}]} ok: [localhost] => (item={'rule_id': 'loop_rule_id_2', 'prefix': 'prefix_2'}) => {"_config": {"Rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}]}, "_retries": 10, "ansible_loop_var": "item", "changed": false, "item": {"prefix": "prefix_2", "rule_id": "loop_rule_id_2"}, "new_rule": {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, "old_rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}], "rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}]} META: ran handlers META: ran handlers PLAY RECAP ********************************************************************************************************************************************************************************************************* localhost : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 [1/10] Removing rules... ansible-playbook [core 2.12.4] config file = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/ansible.cfg configured module search path = ['/home/rubin/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/lib/python3.8/site-packages/ansible ansible collection location = /home/rubin/.ansible/collections:/usr/share/ansible/collections executable location = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/bin/ansible-playbook python version = 3.8.10 (default, Mar 15 2022, 12:22:08) [GCC 9.4.0] jinja version = 3.1.1 libyaml = True Using /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/ansible.cfg as config file Skipping callback 'default', as we already have a stdout callback. Skipping callback 'minimal', as we already have a stdout callback. Skipping callback 'oneline', as we already have a stdout callback. PLAYBOOK: lifecycle_wait_issue.yml ********************************************************************************************************************************************************************************* 1 plays in lifecycle_wait_issue.yml PLAY [local] ******************************************************************************************************************************************************************************************************* META: ran handlers TASK [exemplary cleanup rule] ************************************************************************************************************************************************************************************** task path: /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/lifecycle_wait_issue.yml:10 changed: [localhost] => {"_retries": 9, "ansible_facts": {"discovered_interpreter_python": "/usr/bin/python3"}, "changed": true, "old_rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}], "rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}]} TASK [lgi-onemw-staging-dawn-base - exemplary loop rule] *********************************************************************************************************************************************************** task path: /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/lifecycle_wait_issue.yml:20 changed: [localhost] => (item={'rule_id': 'loop_rule_id_1', 'prefix': 'prefix_1'}) => {"_retries": 9, "ansible_loop_var": "item", "changed": true, "item": {"prefix": "prefix_1", "rule_id": "loop_rule_id_1"}, "old_rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}], "rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}]} changed: [localhost] => (item={'rule_id': 'loop_rule_id_2', 'prefix': 'prefix_2'}) => {"_retries": 8, "ansible_loop_var": "item", "changed": true, "item": {"prefix": "prefix_2", "rule_id": "loop_rule_id_2"}, "old_rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}], "rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}]} META: ran handlers META: ran handlers PLAY RECAP ********************************************************************************************************************************************************************************************************* localhost : ok=2 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 An error occurred (NoSuchLifecycleConfiguration) when calling the GetBucketLifecycle operation: The lifecycle configuration does not exist [2/10] Adding rules... ansible-playbook [core 2.12.4] config file = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/ansible.cfg configured module search path = ['/home/rubin/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/lib/python3.8/site-packages/ansible ansible collection location = /home/rubin/.ansible/collections:/usr/share/ansible/collections executable location = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/bin/ansible-playbook python version = 3.8.10 (default, Mar 15 2022, 12:22:08) [GCC 9.4.0] jinja version = 3.1.1 libyaml = True Using /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/ansible.cfg as config file Skipping callback 'default', as we already have a stdout callback. Skipping callback 'minimal', as we already have a stdout callback. Skipping callback 'oneline', as we already have a stdout callback. PLAYBOOK: lifecycle_wait_issue.yml ******************************************************************************************************************************************************************************************************************************************************** 1 plays in lifecycle_wait_issue.yml PLAY [local] ****************************************************************************************************************************************************************************************************************************************************************************** META: ran handlers TASK [exemplary cleanup rule] ************************************************************************************************************************************************************************************************************************************************************* task path: /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/lifecycle_wait_issue.yml:10 changed: [localhost] => {"_config": {"Rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}]}, "_retries": 8, "ansible_facts": {"discovered_interpreter_python": "/usr/bin/python3"}, "changed": true, "new_rule": {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}, "old_rules": [], "rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}]} TASK [lgi-onemw-staging-dawn-base - exemplary loop rule] ********************************************************************************************************************************************************************************************************************************** task path: /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/lifecycle_wait_issue.yml:20 changed: [localhost] => (item={'rule_id': 'loop_rule_id_1', 'prefix': 'prefix_1'}) => {"_config": {"Rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}]}, "_retries": 9, "ansible_loop_var": "item", "changed": true, "item": {"prefix": "prefix_1", "rule_id": "loop_rule_id_1"}, "new_rule": {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, "old_rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}], "rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}]} changed: [localhost] => (item={'rule_id': 'loop_rule_id_2', 'prefix': 'prefix_2'}) => {"_config": {"Rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}]}, "_retries": 9, "ansible_loop_var": "item", "changed": true, "item": {"prefix": "prefix_2", "rule_id": "loop_rule_id_2"}, "new_rule": {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, "old_rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}], "rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}]} META: ran handlers META: ran handlers PLAY RECAP ******************************************************************************************************************************************************************************************************************************************************************************** localhost : ok=2 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 [2/10] Removing rules... ansible-playbook [core 2.12.4] config file = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/ansible.cfg configured module search path = ['/home/rubin/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/lib/python3.8/site-packages/ansible ansible collection location = /home/rubin/.ansible/collections:/usr/share/ansible/collections executable location = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/bin/ansible-playbook python version = 3.8.10 (default, Mar 15 2022, 12:22:08) [GCC 9.4.0] jinja version = 3.1.1 libyaml = True Using /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/ansible.cfg as config file Skipping callback 'default', as we already have a stdout callback. Skipping callback 'minimal', as we already have a stdout callback. Skipping callback 'oneline', as we already have a stdout callback. PLAYBOOK: lifecycle_wait_issue.yml ******************************************************************************************************************************************************************************************************************************************************** 1 plays in lifecycle_wait_issue.yml PLAY [local] ****************************************************************************************************************************************************************************************************************************************************************************** META: ran handlers TASK [exemplary cleanup rule] ************************************************************************************************************************************************************************************************************************************************************* task path: /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/lifecycle_wait_issue.yml:10 changed: [localhost] => {"_retries": 9, "ansible_facts": {"discovered_interpreter_python": "/usr/bin/python3"}, "changed": true, "old_rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}], "rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}]} TASK [lgi-onemw-staging-dawn-base - exemplary loop rule] ********************************************************************************************************************************************************************************************************************************** task path: /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/lifecycle_wait_issue.yml:20 changed: [localhost] => (item={'rule_id': 'loop_rule_id_1', 'prefix': 'prefix_1'}) => {"_retries": 8, "ansible_loop_var": "item", "changed": true, "item": {"prefix": "prefix_1", "rule_id": "loop_rule_id_1"}, "old_rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}], "rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}]} changed: [localhost] => (item={'rule_id': 'loop_rule_id_2', 'prefix': 'prefix_2'}) => {"_retries": 9, "ansible_loop_var": "item", "changed": true, "item": {"prefix": "prefix_2", "rule_id": "loop_rule_id_2"}, "old_rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}], "rules": [{"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}]} META: ran handlers META: ran handlers PLAY RECAP ******************************************************************************************************************************************************************************************************************************************************************************** localhost : ok=2 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 issue reproduced, 0 rules expected, 2 rules found: cleanup_rule_1 loop_rule_id_2 ``` Example 2: ```console [1/10] Adding rules... ansible-playbook [core 2.12.4] config file = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/ansible.cfg configured module search path = ['/home/rubin/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/lib/python3.8/site-packages/ansible ansible collection location = /home/rubin/.ansible/collections:/usr/share/ansible/collections executable location = /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/env/bin/ansible-playbook python version = 3.8.10 (default, Mar 15 2022, 12:22:08) [GCC 9.4.0] jinja version = 3.1.1 libyaml = True Using /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/ansible.cfg as config file Skipping callback 'default', as we already have a stdout callback. Skipping callback 'minimal', as we already have a stdout callback. Skipping callback 'oneline', as we already have a stdout callback. PLAYBOOK: lifecycle_wait_issue.yml ********************************************************************************************************************************************************************************* 1 plays in lifecycle_wait_issue.yml PLAY [local] ******************************************************************************************************************************************************************************************************* META: ran handlers TASK [exemplary cleanup rule] ************************************************************************************************************************************************************************************** task path: /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/lifecycle_wait_issue.yml:10 changed: [localhost] => {"_config": {"Rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}]}, "_retries": 8, "ansible_facts": {"discovered_interpreter_python": "/usr/bin/python3"}, "changed": true, "new_rule": {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}, "old_rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}], "rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Filter": {"Prefix": ""}, "ID": "cleanup_rule_1", "NoncurrentVersionExpiration": {"NoncurrentDays": 1}, "Status": "Enabled"}]} TASK [lgi-onemw-staging-dawn-base - exemplary loop rule] *********************************************************************************************************************************************************** task path: /work/infra/jenkins/onemw-tools/onemw-infrastructure/ansible/lifecycle_wait_issue.yml:20 changed: [localhost] => (item={'rule_id': 'loop_rule_id_1', 'prefix': 'prefix_1'}) => {"_config": {"Rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}]}, "_retries": 9, "ansible_loop_var": "item", "changed": true, "item": {"prefix": "prefix_1", "rule_id": "loop_rule_id_1"}, "new_rule": {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}, "old_rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}], "rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}]} ok: [localhost] => (item={'rule_id': 'loop_rule_id_2', 'prefix': 'prefix_2'}) => {"_config": {"Rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}]}, "_retries": 10, "ansible_loop_var": "item", "changed": false, "item": {"prefix": "prefix_2", "rule_id": "loop_rule_id_2"}, "new_rule": {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, "old_rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}], "rules": [{"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_2"}, "ID": "loop_rule_id_2", "Status": "Enabled"}, {"Expiration": {"Days": 14}, "Filter": {"Prefix": "prefix_1"}, "ID": "loop_rule_id_1", "Status": "Enabled"}]} META: ran handlers META: ran handlers PLAY RECAP ********************************************************************************************************************************************************************************************************* localhost : ok=2 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 issue reproduced, 3 rules expected, 2 rules found: loop_rule_id_2 loop_rule_id_1 ``` It cannot reliably add or remove rules from playbook. ### Code of Conduct - [X] I agree to follow the Ansible Code of Conduct
Files identified in the description: * [`plugins/modules/s3_lifecycle.py`](https://github.com/['ansible-collections/amazon.aws', 'ansible-collections/community.aws', 'ansible-collections/community.vmware']/blob/main/plugins/modules/s3_lifecycle.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @jillr @markuman @s-hertel @tremble [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify --->
2022-05-06T21:36:46
ansible-collections/community.aws
1,138
ansible-collections__community.aws-1138
[ "922" ]
b993c7a66d2dc3dc98c049bf219d5da4ff8bfbb8
diff --git a/plugins/modules/rds_instance.py b/plugins/modules/rds_instance.py --- a/plugins/modules/rds_instance.py +++ b/plugins/modules/rds_instance.py @@ -160,6 +160,13 @@ aliases: - subnet_group type: str + deletion_protection: + description: + - A value that indicates whether the DB instance has deletion protection enabled. + The database can't be deleted when deletion protection is enabled. + By default, deletion protection is disabled. + type: bool + version_added: 3.3.0 domain: description: - The Active Directory Domain to restore the instance in. @@ -666,6 +673,12 @@ returned: always type: str sample: db-UHV3QRNWX4KB6GALCIGRML6QFA +deletion_protection: + description: C(True) if the DB instance has deletion protection enabled, C(False) if not. + returned: always + type: bool + sample: False + version_added: 3.3.0 domain_memberships: description: The Active Directory Domain membership records associated with the DB instance. returned: always @@ -1256,6 +1269,7 @@ def main(): db_security_groups=dict(type='list', elements='str'), db_snapshot_identifier=dict(), db_subnet_group_name=dict(aliases=['subnet_group']), + deletion_protection=dict(type='bool'), domain=dict(), domain_iam_role_name=dict(), enable_cloudwatch_logs_exports=dict(type='list', aliases=['cloudwatch_log_exports'], elements='str'), diff --git a/plugins/modules/rds_instance_info.py b/plugins/modules/rds_instance_info.py --- a/plugins/modules/rds_instance_info.py +++ b/plugins/modules/rds_instance_info.py @@ -188,6 +188,12 @@ returned: always type: str sample: db-AAAAAAAAAAAAAAAAAAAAAAAAAA + deletion_protection: + description: C(True) if the DB instance has deletion protection enabled, C(False) if not. + returned: always + type: bool + sample: False + version_added: 3.3.0 domain_memberships: description: List of domain memberships returned: always
rds_instance: modify delete protection ### Summary I am trying to modify an RDS instance that has delete protection on it, preventing deletion. I would like the ability to modify this via ansible directly ``` for rds in $(aws rds describe-db-instances | jq -r '.DBInstances.[].DBInstanceIdentifier'); do aws rds modify-db-instance --no-deletion-protection --db-instance-identifier "${rds}" done ``` ### Issue Type Feature Idea ### Component Name rds_instance ### Additional Information <!--- Paste example playbooks or commands between quotes below --> ```yaml (paste below) - name: Get all RDS instances community.aws.rds_instance_info: region: "{{ region }}" aws_access_key: "{{ aws_access_key_id }}" aws_secret_key: "{{ aws_secret_access_key }}" register: __rds_instances - name: Remove delete protection from any DB instances community.aws.rds_instance: id: "{{ item.db_instance_identifier }}" deletion_protection: false loop: __rds_instances.instances - name: Remove any DB instance without a final snapshot community.aws.rds_instance: id: "{{ item.db_instance_identifier }}" state: absent skip_final_snapshot: true loop: __rds_instances.instances ``` ### Code of Conduct - [X] I agree to follow the Ansible Code of Conduct
Hi @jbpratt! Thanks for requesting this. I went ahead and opened a PR for this since I was already working on this module. In the future, feel free to open a PR yourself and ask any questions that you may have. cc @jillr @markuman @rrey @s-hertel @tremble [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify --->
2022-05-09T14:41:29
ansible-collections/community.aws
1,143
ansible-collections__community.aws-1143
[ "88" ]
ba08f904c4b06b87d03578e2dd8152d04b7d2515
diff --git a/plugins/modules/route53_health_check.py b/plugins/modules/route53_health_check.py --- a/plugins/modules/route53_health_check.py +++ b/plugins/modules/route53_health_check.py @@ -44,7 +44,7 @@ description: - The type of health check that you want to create, which indicates how Amazon Route 53 determines whether an endpoint is healthy. - required: true + - Once health_check is created, type can not be changed. choices: [ 'HTTP', 'HTTPS', 'HTTP_STR_MATCH', 'HTTPS_STR_MATCH', 'TCP' ] type: str resource_path: @@ -86,6 +86,28 @@ - Will default to C(3) if not specified on creation. choices: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] type: int + health_check_name: + description: + - Name of the Health Check. + - Used together with I(use_unique_names) to set/make use of I(health_check_name) as a unique identifier. + type: str + required: False + aliases: ['name'] + version_added: 4.1.0 + use_unique_names: + description: + - Used together with I(health_check_name) to set/make use of I(health_check_name) as a unique identifier. + type: bool + required: False + version_added: 4.1.0 + health_check_id: + description: + - ID of the health check to be update or deleted. + - If provided, a health check can be updated or deleted based on the ID as unique identifier. + type: str + required: False + aliases: ['id'] + version_added: 4.1.0 author: - "zimbatm (@zimbatm)" notes: @@ -120,10 +142,35 @@ weight: 100 health_check: "{{ my_health_check.health_check.id }}" +- name: create a simple health check with health_check_name as unique identifier + community.aws.route53_health_check: + state: present + health_check_name: ansible + fqdn: ansible.com + port: 443 + type: HTTPS + use_unique_names: true + - name: Delete health-check community.aws.route53_health_check: state: absent fqdn: host1.example.com + +- name: Update Health check by ID - update ip_address + community.aws.route53_health_check: + id: 12345678-abcd-abcd-abcd-0fxxxxxxxxxx + ip_address: 1.2.3.4 + +- name: Update Health check by ID - update port + community.aws.route53_health_check: + id: 12345678-abcd-abcd-abcd-0fxxxxxxxxxx + ip_address: 8080 + +- name: Delete Health check by ID + community.aws.route53_health_check: + state: absent + id: 12345678-abcd-abcd-abcd-0fxxxxxxxxxx + ''' RETURN = r''' @@ -249,7 +296,6 @@ def find_health_check(ip_addr, fqdn, hc_type, request_interval, port): # Additionally, we can't properly wrap the paginator, so retrying means # starting from scratch with a paginator results = _list_health_checks() - while True: for check in results.get('HealthChecks'): config = check.get('HealthCheckConfig') @@ -268,6 +314,20 @@ def find_health_check(ip_addr, fqdn, hc_type, request_interval, port): return None +def get_existing_checks_with_name(): + results = _list_health_checks() + health_checks_with_name = {} + while True: + for check in results.get('HealthChecks'): + if 'Name' in describe_health_check(check['Id'])['tags']: + check_name = describe_health_check(check['Id'])['tags']['Name'] + health_checks_with_name[check_name] = check + if results.get('IsTruncated', False): + results = _list_health_checks(Marker=results.get('NextMarker')) + else: + return health_checks_with_name + + def delete_health_check(check_id): if not check_id: return False, None @@ -348,10 +408,14 @@ def create_health_check(ip_addr_in, fqdn_in, type_in, request_interval_in, port_ def update_health_check(existing_check): - # In theory it's also possible to update the IPAddress, Port and - # FullyQualifiedDomainName, however, because we use these in lieu of a - # 'Name' to uniquely identify the health check this isn't currently - # supported. If we accepted an ID it would be possible to modify them. + # It's possible to update following parameters + # - ResourcePath + # - SearchString + # - FailureThreshold + # - Disabled + # - IPAddress + # - Port + # - FullyQualifiedDomainName changes = dict() existing_config = existing_check.get('HealthCheckConfig') @@ -372,10 +436,23 @@ def update_health_check(existing_check): if disabled is not None and disabled != existing_config.get('Disabled'): changes['Disabled'] = module.params.get('disabled') + # If updating based on Health Check ID or health_check_name, we can update + if module.params.get('health_check_id') or module.params.get('use_unique_names'): + ip_address = module.params.get('ip_address', None) + if ip_address is not None and ip_address != existing_config.get('IPAddress'): + changes['IPAddress'] = module.params.get('ip_address') + + port = module.params.get('port', None) + if port is not None and port != existing_config.get('Port'): + changes['Port'] = module.params.get('port') + + fqdn = module.params.get('fqdn', None) + if fqdn is not None and fqdn != existing_config.get('FullyQualifiedDomainName'): + changes['FullyQualifiedDomainName'] = module.params.get('fqdn') + # No changes... if not changes: return False, None - if module.check_mode: return True, 'update' @@ -419,7 +496,7 @@ def main(): disabled=dict(type='bool'), ip_address=dict(), port=dict(type='int'), - type=dict(required=True, choices=['HTTP', 'HTTPS', 'HTTP_STR_MATCH', 'HTTPS_STR_MATCH', 'TCP']), + type=dict(choices=['HTTP', 'HTTPS', 'HTTP_STR_MATCH', 'HTTPS_STR_MATCH', 'TCP']), resource_path=dict(), fqdn=dict(), string_match=dict(), @@ -427,16 +504,27 @@ def main(): failure_threshold=dict(type='int', choices=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), tags=dict(type='dict', aliases=['resource_tags']), purge_tags=dict(type='bool'), + health_check_id=dict(type='str', aliases=['id'], required=False), + health_check_name=dict(type='str', aliases=['name'], required=False), + use_unique_names=dict(type='bool', required=False), ) args_one_of = [ - ['ip_address', 'fqdn'], + ['ip_address', 'fqdn', 'health_check_id'], ] args_if = [ ['type', 'TCP', ('port',)], ] + args_required_together = [ + ['use_unique_names', 'health_check_name'], + ] + + args_mutually_exclusive = [ + ['health_check_id', 'health_check_name'] + ] + global module global client @@ -444,6 +532,8 @@ def main(): argument_spec=argument_spec, required_one_of=args_one_of, required_if=args_if, + required_together=args_required_together, + mutually_exclusive=args_mutually_exclusive, supports_check_mode=True, ) @@ -455,6 +545,9 @@ def main(): version='5.0.0', collection_name='community.aws') module.params['purge_tags'] = False + if not module.params.get('health_check_id') and not module.params.get('type'): + module.fail_json(msg="parameter 'type' is required if not updating or deleting health check by ID.") + state_in = module.params.get('state') ip_addr_in = module.params.get('ip_address') port_in = module.params.get('port') @@ -464,6 +557,8 @@ def main(): string_match_in = module.params.get('string_match') request_interval_in = module.params.get('request_interval') failure_threshold_in = module.params.get('failure_threshold') + health_check_name = module.params.get('health_check_name') + tags = module.params.get('tags') # Default port if port_in is None: @@ -484,22 +579,66 @@ def main(): action = None check_id = None - existing_check = find_health_check(ip_addr_in, fqdn_in, type_in, request_interval_in, port_in) - - if existing_check: - check_id = existing_check.get('Id') - + if module.params.get('use_unique_names') or module.params.get('health_check_id'): + module.deprecate( + 'The health_check_name is currently non required parameter.' + ' This behavior will change and health_check_name ' + ' will change to required=True and use_unique_names will change to default=True in release 6.0.0.', + version='6.0.0', collection_name='community.aws') + + # If update or delete Health Check based on ID + update_delete_by_id = False + if module.params.get('health_check_id'): + update_delete_by_id = True + id_to_update_delete = module.params.get('health_check_id') + try: + existing_check = client.get_health_check(HealthCheckId=id_to_update_delete)['HealthCheck'] + except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: + module.exit_json(changed=False, msg='The specified health check with ID: {0} does not exist'.format(id_to_update_delete)) + else: + existing_check = find_health_check(ip_addr_in, fqdn_in, type_in, request_interval_in, port_in) + if existing_check: + check_id = existing_check.get('Id') + + # Delete Health Check if state_in == 'absent': - changed, action = delete_health_check(check_id) + if update_delete_by_id: + changed, action = delete_health_check(id_to_update_delete) + else: + changed, action = delete_health_check(check_id) check_id = None + + # Create Health Check elif state_in == 'present': - if existing_check is None: + if existing_check is None and not module.params.get('use_unique_names') and not update_delete_by_id: changed, action, check_id = create_health_check(ip_addr_in, fqdn_in, type_in, request_interval_in, port_in) + + # Update Health Check else: - changed, action = update_health_check(existing_check) + # If health_check_name is a unique identifier + if module.params.get('use_unique_names'): + existing_checks_with_name = get_existing_checks_with_name() + # update the health_check if another health check with same name exists + if health_check_name in existing_checks_with_name: + changed, action = update_health_check(existing_checks_with_name[health_check_name]) + else: + # create a new health_check if another health check with same name does not exists + changed, action, check_id = create_health_check(ip_addr_in, fqdn_in, type_in, request_interval_in, port_in) + # Add tag to add name to health check + if check_id: + if not tags: + tags = {} + tags['Name'] = health_check_name + + else: + if update_delete_by_id: + changed, action = update_health_check(existing_check) + else: + changed, action = update_health_check(existing_check) + if check_id: changed |= manage_tags(module, client, 'healthcheck', check_id, - module.params.get('tags'), module.params.get('purge_tags')) + tags, module.params.get('purge_tags')) health_check = describe_health_check(id=check_id) health_check['action'] = action
diff --git a/tests/integration/targets/route53_health_check/defaults/main.yml b/tests/integration/targets/route53_health_check/defaults/main.yml --- a/tests/integration/targets/route53_health_check/defaults/main.yml +++ b/tests/integration/targets/route53_health_check/defaults/main.yml @@ -11,6 +11,7 @@ #ip_address: We allocate an EIP due to route53 restrictions fqdn: '{{ tiny_prefix }}.route53-health.ansible.test' +fqdn_1: '{{ tiny_prefix }}-1.route53-health.ansible.test' port: 8080 type: 'TCP' request_interval: 30 @@ -27,7 +28,9 @@ failure_threshold_updated: 1 # for string_match we need an _STR_MATCH type type_https_match: 'HTTPS_STR_MATCH' type_http_match: 'HTTP_STR_MATCH' +type_http: 'HTTP' resource_path: '/health.php' +resource_path_1: '/new-health.php' resource_path_updated: '/healthz' string_match: 'Hello' string_match_updated: 'Hello World' diff --git a/tests/integration/targets/route53_health_check/tasks/create_multiple_health_checks.yml b/tests/integration/targets/route53_health_check/tasks/create_multiple_health_checks.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/route53_health_check/tasks/create_multiple_health_checks.yml @@ -0,0 +1,134 @@ +--- +- block: + - name: 'Create multiple HTTP health checks with different resource_path - check_mode' + route53_health_check: + state: present + name: '{{ tiny_prefix }}-{{ item }}-test-hc-delete-if-found' + ip_address: '{{ ip_address }}' + port: '{{ port }}' + type: '{{ type_http }}' + resource_path: '{{ item }}' + use_unique_names: true + register: create_check + check_mode: true + with_items: + - '{{ resource_path }}' + - '{{ resource_path_1 }}' + + - name: 'Check result - Create a HTTP health check - check_mode' + assert: + that: + - create_check is not failed + - create_check is changed + - '"route53:CreateHealthCheck" not in create_check.results[0].resource_actions' + - '"route53:CreateHealthCheck" not in create_check.results[1].resource_actions' + + - name: 'Create multiple HTTP health checks with different resource_path' + route53_health_check: + state: present + name: '{{ tiny_prefix }}-{{ item }}-test-hc-delete-if-found' + ip_address: '{{ ip_address }}' + port: '{{ port }}' + type: '{{ type_http }}' + resource_path: '{{ item }}' + use_unique_names: true + register: create_result + with_items: + - '{{ resource_path }}' + - '{{ resource_path_1 }}' + + - name: Get ID's for health_checks created in above task + set_fact: + health_check_1_id: "{{ create_result.results[0].health_check.id }}" + health_check_2_id: "{{ create_result.results[1].health_check.id }}" + + - name: Get health_check 1 info + community.aws.route53_info: + query: health_check + health_check_id: "{{ health_check_1_id }}" + health_check_method: details + register: health_check_1_info + + - name: Get health_check 2 info + community.aws.route53_info: + query: health_check + health_check_id: "{{ health_check_2_id }}" + health_check_method: details + register: health_check_2_info + + - name: 'Check result - Create multiple HTTP health check' + assert: + that: + - create_result is not failed + - create_result is changed + - '"route53:UpdateHealthCheck" not in create_result.results[0].resource_actions' + - '"route53:UpdateHealthCheck" not in create_result.results[1].resource_actions' + - health_check_1_id != health_check_2_id + - health_check_1_info.HealthCheck.HealthCheckConfig.ResourcePath == '{{ resource_path }}' + - health_check_2_info.HealthCheck.HealthCheckConfig.ResourcePath == '{{ resource_path_1 }}' + + - name: 'Create multiple HTTP health checks with different resource_path - idempotency - check_mode' + route53_health_check: + state: present + name: '{{ tiny_prefix }}-{{ item }}-test-hc-delete-if-found' + ip_address: '{{ ip_address }}' + port: '{{ port }}' + type: '{{ type_http }}' + resource_path: '{{ item }}' + use_unique_names: true + register: create_idem_check + check_mode: true + with_items: + - '{{ resource_path }}' + - '{{ resource_path_1 }}' + + - name: 'Check result - Create multiple HTTP health check - idempotency - check_mode' + assert: + that: + - create_idem_check is not failed + - create_idem_check is not changed + - '"route53:CreateHealthCheck" not in create_idem_check.results[0].resource_actions' + - '"route53:CreateHealthCheck" not in create_idem_check.results[1].resource_actions' + - '"route53:UpdateHealthCheck" not in create_idem_check.results[0].resource_actions' + - '"route53:UpdateHealthCheck" not in create_idem_check.results[1].resource_actions' + + - name: 'Create multiple HTTP health checks with different resource_path - idempotency' + route53_health_check: + state: present + name: '{{ tiny_prefix }}-{{ item }}-test-hc-delete-if-found' + ip_address: '{{ ip_address }}' + port: '{{ port }}' + type: '{{ type_http }}' + resource_path: '{{ item }}' + use_unique_names: true + register: create_idem + check_mode: true + with_items: + - '{{ resource_path }}' + - '{{ resource_path_1 }}' + + - name: 'Check result - Create multiple HTTP health check - idempotency - check_mode' + assert: + that: + - create_idem is not failed + - create_idem is not changed + - '"route53:CreateHealthCheck" not in create_idem.results[0].resource_actions' + - '"route53:CreateHealthCheck" not in create_idem.results[1].resource_actions' + - '"route53:UpdateHealthCheck" not in create_idem.results[0].resource_actions' + - '"route53:UpdateHealthCheck" not in create_idem.results[1].resource_actions' + + always: + # Cleanup starts here + - name: 'Delete multiple HTTP health checks with different resource_path' + route53_health_check: + state: absent + name: '{{ tiny_prefix }}-{{ item }}-test-hc-delete-if-found' + ip_address: '{{ ip_address }}' + port: '{{ port }}' + type: '{{ type_http }}' + resource_path: '{{ item }}' + use_unique_names: true + register: delete_result + with_items: + - '{{ resource_path }}' + - '{{ resource_path_1 }}' diff --git a/tests/integration/targets/route53_health_check/tasks/main.yml b/tests/integration/targets/route53_health_check/tasks/main.yml --- a/tests/integration/targets/route53_health_check/tasks/main.yml +++ b/tests/integration/targets/route53_health_check/tasks/main.yml @@ -32,6 +32,12 @@ - set_fact: ip_address: '{{ eip.public_ip }}' + - name: Run tests for creating multiple health checks with name as unique identifier + include_tasks: create_multiple_health_checks.yml + + - name: Run tests for update and delete health check by ID + include_tasks: update_delete_by_id.yml + # Minimum possible definition - name: 'Create a TCP health check - check_mode' route53_health_check: diff --git a/tests/integration/targets/route53_health_check/tasks/update_delete_by_id.yml b/tests/integration/targets/route53_health_check/tasks/update_delete_by_id.yml new file mode 100644 --- /dev/null +++ b/tests/integration/targets/route53_health_check/tasks/update_delete_by_id.yml @@ -0,0 +1,303 @@ +--- +- block: + - name: 'Create HTTP health check for use in this test' + route53_health_check: + state: present + name: '{{ tiny_prefix }}-test-update-delete-by-id' + ip_address: '{{ ip_address }}' + port: '{{ port }}' + type: '{{ type_http }}' + resource_path: '{{ resource_path }}' + fqdn: '{{ fqdn }}' + use_unique_names: true + register: create_result + + - name: 'Check result - Create HTTP health check' + assert: + that: + - create_result is not failed + - create_result is changed + - '"route53:CreateHealthCheck" in create_result.resource_actions' + + - name: Get ID for health_checks created in above task + set_fact: + health_check_id: "{{ create_result.health_check.id }}" + + - name: Get health_check info + community.aws.route53_info: + query: health_check + health_check_id: "{{ health_check_id }}" + health_check_method: details + register: health_check_info + + # Update Health Check by ID Tests + - name: 'Update Health Check by ID - Update Port - check_mode' + route53_health_check: + id: "{{ health_check_id }}" + port: 8888 + register: update_result + check_mode: true + + - name: 'Check result - Update Health Check Port - check_mode' + assert: + that: + - update_result is not failed + - update_result is changed + - '"route53:UpdateHealthCheck" not in update_result.resource_actions' + + - name: 'Update Health Check by ID - Update Port' + route53_health_check: + id: "{{ health_check_id }}" + port: 8888 + register: update_result + + - name: Get health_check info + community.aws.route53_info: + query: health_check + health_check_id: "{{ health_check_id }}" + health_check_method: details + register: health_check_info + + - name: 'Check result - Update Health Check Port' + assert: + that: + - update_result is not failed + - update_result is changed + - health_check_info.HealthCheck.HealthCheckConfig.Port == 8888 + + + - name: 'Update Health Check by ID - Update Port - idempotency - check_mode' + route53_health_check: + id: "{{ health_check_id }}" + port: 8888 + register: update_result + check_mode: true + + - name: 'Check result - Update Health Check Port - idempotency - check_mode' + assert: + that: + - update_result is not failed + - update_result is not changed + - '"route53:UpdateHealthCheck" not in update_result.resource_actions' + + - name: 'Update Health Check by ID - Update Port - idempotency' + route53_health_check: + id: "{{ health_check_id }}" + port: 8888 + register: update_result + + - name: 'Check result - Update Health Check Port - idempotency' + assert: + that: + - update_result is not failed + - update_result is not changed + - '"route53:UpdateHealthCheck" not in update_result.resource_actions' + + ## + - name: 'Update Health Check by ID - Update IP address and FQDN - check_mode' + route53_health_check: + id: "{{ health_check_id }}" + ip_address: 1.2.3.4 + fqdn: '{{ fqdn_1 }}' + register: update_result + check_mode: true + + - name: 'Check result - Update Health Check IP address and FQDN - check_mode' + assert: + that: + - update_result is not failed + - update_result is changed + - '"route53:UpdateHealthCheck" not in update_result.resource_actions' + + - name: 'Update Health Check by ID - Update IP address and FQDN' + route53_health_check: + id: "{{ health_check_id }}" + ip_address: 1.2.3.4 + fqdn: '{{ fqdn_1 }}' + register: update_result + + - name: Get health_check info + community.aws.route53_info: + query: health_check + health_check_id: "{{ health_check_id }}" + health_check_method: details + register: health_check_info + + - name: 'Check result - Update Health Check IP address and FQDN' + assert: + that: + - update_result is not failed + - update_result is changed + - health_check_info.HealthCheck.HealthCheckConfig.IPAddress == '1.2.3.4' + - health_check_info.HealthCheck.HealthCheckConfig.FullyQualifiedDomainName == "{{ fqdn_1 }}" + + + - name: 'Update Health Check by ID - Update IP address and FQDN - idempotency - check_mode' + route53_health_check: + id: "{{ health_check_id }}" + ip_address: 1.2.3.4 + fqdn: '{{ fqdn_1 }}' + register: update_result + check_mode: true + + - name: 'Check result - Update Health Check IP address and FQDN - idempotency - check_mode' + assert: + that: + - update_result is not failed + - update_result is not changed + - '"route53:UpdateHealthCheck" not in update_result.resource_actions' + + - name: 'Update Health Check by ID - Update IP address and FQDN - idempotency' + route53_health_check: + id: "{{ health_check_id }}" + ip_address: 1.2.3.4 + fqdn: '{{ fqdn_1 }}' + register: update_result + + - name: 'Check result - Update Health Check IP address and FQDN - idempotency' + assert: + that: + - update_result is not failed + - update_result is not changed + - '"route53:UpdateHealthCheck" not in update_result.resource_actions' + + # Update Health Check (Port) by name + + - name: 'Update Health Check by name - Update Port - check_mode' + route53_health_check: + state: present + port: 8080 + type: '{{ type_http }}' + fqdn: '{{ fqdn }}' + health_check_name: '{{ tiny_prefix }}-test-update-delete-by-id' + use_unique_names: true + register: update_result + check_mode: true + + - name: 'Check result - Update Health Check Port - check_mode' + assert: + that: + - update_result is not failed + - update_result is changed + - '"route53:UpdateHealthCheck" not in update_result.resource_actions' + + - name: 'Update Health Check by name - Update Port' + route53_health_check: + state: present + port: 8080 + type: '{{ type_http }}' + fqdn: '{{ fqdn }}' + health_check_name: '{{ tiny_prefix }}-test-update-delete-by-id' + use_unique_names: true + register: update_result + + - name: Get health_check info + community.aws.route53_info: + query: health_check + health_check_id: "{{ health_check_id }}" + health_check_method: details + register: health_check_info + + - name: 'Check result - Update Health Check Port' + assert: + that: + - update_result is not failed + - update_result is changed + - health_check_info.HealthCheck.HealthCheckConfig.Port == 8080 + + - name: 'Update Health Check by name - Update Port - idempotency - check_mode' + route53_health_check: + state: present + port: 8080 + type: '{{ type_http }}' + fqdn: '{{ fqdn }}' + health_check_name: '{{ tiny_prefix }}-test-update-delete-by-id' + use_unique_names: true + register: update_result + check_mode: true + + - name: 'Check result - Update Health Check Port - idempotency - check_mode' + assert: + that: + - update_result is not failed + - update_result is not changed + - '"route53:UpdateHealthCheck" not in update_result.resource_actions' + + - name: 'Update Health Check by name - Update Port - idempotency' + route53_health_check: + state: present + port: 8080 + type: '{{ type_http }}' + fqdn: '{{ fqdn }}' + health_check_name: '{{ tiny_prefix }}-test-update-delete-by-id' + use_unique_names: true + register: update_result + + - name: 'Check result - Update Health Check Port - idempotency' + assert: + that: + - update_result is not failed + - update_result is not changed + - '"route53:UpdateHealthCheck" not in update_result.resource_actions' + + # Delete Health Check by ID Tests + - name: Delete Health check by ID - check_mode + route53_health_check: + state: absent + id: "{{ health_check_id }}" + register: delete_result + check_mode: true + + - name: 'Check result - Delete Health Check by ID -check_mode' + assert: + that: + - delete_result is not failed + - delete_result is changed + - '"route53:DeleteHealthCheck" not in delete_result.resource_actions' + + - name: Delete Health check by ID + route53_health_check: + state: absent + id: "{{ health_check_id }}" + register: delete_result + + - name: 'Check result - Delete Health Check by ID' + assert: + that: + - delete_result is not failed + - delete_result is changed + - '"route53:DeleteHealthCheck" in delete_result.resource_actions' + + - name: Delete Health check by ID - idempotency - check_mode + route53_health_check: + state: absent + id: "{{ health_check_id }}" + register: delete_result + check_mode: true + + - name: 'Check result - Delete Health Check by ID -idempotency -check_mode' + assert: + that: + - delete_result is not failed + - delete_result is not changed + - '"route53:DeleteHealthCheck" not in delete_result.resource_actions' + + - name: Delete Health check by ID - idempotency + route53_health_check: + state: absent + id: "{{ health_check_id }}" + register: delete_result + + - name: 'Check result - Delete Health Check by ID -idempotency' + assert: + that: + - delete_result is not failed + - delete_result is not changed + - '"route53:DeleteHealthCheck" not in delete_result.resource_actions' + + # cleanup + always: + - name: Delete Health check by ID + route53_health_check: + state: absent + id: "{{ health_check_id }}"
route53_health_check resource_path uniqueness ignored <!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> Moving [issue](https://github.com/ansible/ansible/issues/23110) from ansible repository to community.aws collections. Tried to create multiple route53 healthchecks to the same server but different resource paths using with_items . Instead of creating one health check for each resource path, only the first is created. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.2.2.0 ``` ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> <!--- Paste example playbooks or commands between quotes below --> ```yaml - name: set up route53 health checks connection: local become: false route53_health_check: failure_threshold: 3 ip_address: '{{ ip_address }}' port: 80 request_interval: 30 resource_path: '{{ item }}' state: present type: HTTP register: result with_items: - /some_status1 - /other_status2 ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> 2 health checks created result contains health_check.ids for each health check ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> 1 health check created result contains two items, both having the same health_check.id <!--- Paste verbatim command output between quotes --> ```paste below ```
Files identified in the description: None If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner --->
2022-05-10T16:54:50
ansible-collections/community.aws
1,144
ansible-collections__community.aws-1144
[ "89" ]
0c3dcffd0118b80a9c803fdacc0c865080542b92
diff --git a/plugins/modules/route53.py b/plugins/modules/route53.py --- a/plugins/modules/route53.py +++ b/plugins/modules/route53.py @@ -108,6 +108,30 @@ latency-based routing - Mutually exclusive with I(weight) and I(failover). type: str + geo_location: + description: + - Allows to control how Amazon Route 53 responds to DNS queries based on the geographic origin of the query. + - Two geolocation resource record sets that specify same geographic location cannot be created. + - Non-geolocation resource record sets that have the same values for the Name and Type elements as geolocation + resource record sets cannot be created. + suboptions: + continent_code: + description: + - The two-letter code for the continent. + - Specifying I(continent_code) with either I(country_code) or I(subdivision_code) returns an InvalidInput error. + type: str + country_code: + description: + - The two-letter code for a country. + - Amazon Route 53 uses the two-letter country codes that are specified in ISO standard 3166-1 alpha-2 . + type: str + subdivision_code: + description: + - The two-letter code for a state of the United States. + - To specify I(subdivision_code), I(country_code) must be set to C(US). + type: str + type: dict + version_added: 3.3.0 health_check: description: - Health check to associate with this record @@ -166,6 +190,12 @@ returned: always type: str sample: PRIMARY + geo_location: + description: geograpic location based on which Route53 resonds to DNS queries. + returned: when configured + type: dict + sample: { continent_code: "NA", country_code: "US", subdivision_code: "CA" } + version_added: 3.3.0 health_check: description: health_check associated with this record. returned: always @@ -350,6 +380,29 @@ - 0 issue "ca.example.net" - 0 issuewild ";" - 0 iodef "mailto:[email protected]" +- name: Create a record with geo_location - country_code + community.aws.route53: + state: present + zone: '{{ zone_one }}' + record: 'geo-test.{{ zone_one }}' + identifier: "geohost@www" + type: A + value: 1.1.1.1 + ttl: 30 + geo_location: + country_code: US +- name: Create a record with geo_location - subdivision code + community.aws.route53: + state: present + zone: '{{ zone_one }}' + record: 'geo-test.{{ zone_one }}' + identifier: "geohost@www" + type: A + value: 1.1.1.1 + ttl: 30 + geo_location: + country_code: US + subdivision_code: TX ''' from operator import itemgetter @@ -495,6 +548,12 @@ def main(): identifier=dict(type='str'), weight=dict(type='int'), region=dict(type='str'), + geo_location=dict(type='dict', + options=dict( + continent_code=dict(type="str"), + country_code=dict(type="str"), + subdivision_code=dict(type="str")), + required=False), health_check=dict(type='str'), failover=dict(type='str', choices=['PRIMARY', 'SECONDARY']), vpc_id=dict(type='str'), @@ -518,11 +577,12 @@ def main(): ('failover', 'region', 'weight'), ('alias', 'ttl'), ], - # failover, region and weight require identifier + # failover, region, weight and geo_location require identifier required_by=dict( failover=('identifier',), region=('identifier',), weight=('identifier',), + geo_location=('identifier'), ), ) @@ -557,6 +617,7 @@ def main(): vpc_id_in = module.params.get('vpc_id') wait_in = module.params.get('wait') wait_timeout_in = module.params.get('wait_timeout') + geo_location = module.params.get('geo_location') if zone_in[-1:] != '.': zone_in += "." @@ -567,8 +628,8 @@ def main(): if command_in == 'create' or command_in == 'delete': if alias_in and len(value_in) != 1: module.fail_json(msg="parameter 'value' must contain a single dns name for alias records") - if (weight_in is None and region_in is None and failover_in is None) and identifier_in is not None: - module.fail_json(msg="You have specified identifier which makes sense only if you specify one of: weight, region or failover.") + if not any([weight_in, region_in, failover_in, geo_location]) and identifier_in is not None: + module.fail_json(msg="You have specified identifier which makes sense only if you specify one of: weight, region, geo_location or failover.") retry_decorator = AWSRetry.jittered_backoff( retries=MAX_AWS_RETRIES, @@ -604,6 +665,30 @@ def main(): 'HealthCheckId': health_check_in, 'SetIdentifier': identifier_in, }) + + if geo_location: + continent_code = geo_location.get('continent_code') + country_code = geo_location.get('country_code') + subdivision_code = geo_location.get('subdivision_code') + + if continent_code and (country_code or subdivision_code): + module.fail_json(changed=False, msg='While using geo_location, continent_code is mutually exclusive with country_code and subdivision_code.') + + if not any([continent_code, country_code, subdivision_code]): + module.fail_json(changed=False, msg='To use geo_location please specify either continent_code, country_code, or subdivision_code.') + + if geo_location.get('subdivision_code') and geo_location.get('country_code').lower() != 'us': + module.fail_json(changed=False, msg='To use subdivision_code, you must specify country_code as US.') + + # Build geo_location suboptions specification + resource_record_set['GeoLocation'] = {} + if continent_code: + resource_record_set['GeoLocation']['ContinentCode'] = continent_code + if country_code: + resource_record_set['GeoLocation']['CountryCode'] = country_code + if subdivision_code: + resource_record_set['GeoLocation']['SubdivisionCode'] = subdivision_code + if command_in == 'delete' and aws_record is not None: resource_record_set['TTL'] = aws_record.get('TTL') if not resource_record_set['ResourceRecords']:
diff --git a/tests/integration/targets/route53/tasks/main.yml b/tests/integration/targets/route53/tasks/main.yml --- a/tests/integration/targets/route53/tasks/main.yml +++ b/tests/integration/targets/route53/tasks/main.yml @@ -635,7 +635,314 @@ - weighted_record is not failed - weighted_record is not changed +#Test Geo Location - Continent Code + - name: Create a record with geo_location - continent_code (check_mode) + route53: + state: present + zone: '{{ zone_one }}' + record: 'geo-test-1.{{ zone_one }}' + identifier: "geohost1@www" + type: A + value: 127.0.0.1 + ttl: 30 + geo_location: + continent_code: NA + check_mode: true + register: create_geo_continent_check_mode + - assert: + that: + - create_geo_continent_check_mode is changed + - create_geo_continent_check_mode is not failed + - '"route53:ChangeResourceRecordSets" not in create_geo_continent_check_mode.resource_actions' + + - name: Create a record with geo_location - continent_code + route53: + state: present + zone: '{{ zone_one }}' + record: 'geo-test-1.{{ zone_one }}' + identifier: "geohost1@www" + type: A + value: 127.0.0.1 + ttl: 30 + geo_location: + continent_code: NA + register: create_geo_continent + # Get resulting A record and geo_location parameters are applied + - name: 'get Route53 A record information' + route53_info: + type: A + query: record_sets + hosted_zone_id: '{{ z1.zone_id }}' + start_record_name: 'geo-test-1.{{ zone_one }}' + max_items: 1 + register: result + + - assert: + that: + - create_geo_continent is changed + - create_geo_continent is not failed + - '"route53:ChangeResourceRecordSets" in create_geo_continent.resource_actions' + - result.ResourceRecordSets[0].GeoLocation.ContinentCode == "NA" + + - name: Create a record with geo_location - continent_code (idempotency) + route53: + state: present + zone: '{{ zone_one }}' + record: 'geo-test-1.{{ zone_one }}' + identifier: "geohost1@www" + type: A + value: 127.0.0.1 + ttl: 30 + geo_location: + continent_code: NA + register: create_geo_continent_idem + - assert: + that: + - create_geo_continent_idem is not changed + - create_geo_continent_idem is not failed + - '"route53:ChangeResourceRecordSets" not in create_geo_continent_idem.resource_actions' + + - name: Create a record with geo_location - continent_code (idempotency - check_mode) + route53: + state: present + zone: '{{ zone_one }}' + record: 'geo-test-1.{{ zone_one }}' + identifier: "geohost1@www" + type: A + value: 127.0.0.1 + ttl: 30 + geo_location: + continent_code: NA + check_mode: true + register: create_geo_continent_idem_check + + - assert: + that: + - create_geo_continent_idem_check is not changed + - create_geo_continent_idem_check is not failed + - '"route53:ChangeResourceRecordSets" not in create_geo_continent_idem_check.resource_actions' + +#Test Geo Location - Country Code + - name: Create a record with geo_location - country_code (check_mode) + route53: + state: present + zone: '{{ zone_one }}' + record: 'geo-test-2.{{ zone_one }}' + identifier: "geohost2@www" + type: A + value: 127.0.0.1 + ttl: 30 + geo_location: + country_code: US + check_mode: true + register: create_geo_country_check_mode + - assert: + that: + - create_geo_country_check_mode is changed + - create_geo_country_check_mode is not failed + - '"route53:ChangeResourceRecordSets" not in create_geo_country_check_mode.resource_actions' + + - name: Create a record with geo_location - country_code + route53: + state: present + zone: '{{ zone_one }}' + record: 'geo-test-2.{{ zone_one }}' + identifier: "geohost2@www" + type: A + value: 127.0.0.1 + ttl: 30 + geo_location: + country_code: US + register: create_geo_country + # Get resulting A record and geo_location parameters are applied + - name: 'get Route53 A record information' + route53_info: + type: A + query: record_sets + hosted_zone_id: '{{ z1.zone_id }}' + start_record_name: 'geo-test-2.{{ zone_one }}' + max_items: 1 + register: result + - assert: + that: + - create_geo_country is changed + - create_geo_country is not failed + - '"route53:ChangeResourceRecordSets" in create_geo_country.resource_actions' + - result.ResourceRecordSets[0].GeoLocation.CountryCode == "US" + + - name: Create a record with geo_location - country_code (idempotency) + route53: + state: present + zone: '{{ zone_one }}' + record: 'geo-test-2.{{ zone_one }}' + identifier: "geohost2@www" + type: A + value: 127.0.0.1 + ttl: 30 + geo_location: + country_code: US + register: create_geo_country_idem + - assert: + that: + - create_geo_country_idem is not changed + - create_geo_country_idem is not failed + - '"route53:ChangeResourceRecordSets" not in create_geo_country_idem.resource_actions' + + - name: Create a record with geo_location - country_code (idempotency - check_mode) + route53: + state: present + zone: '{{ zone_one }}' + record: 'geo-test-2.{{ zone_one }}' + identifier: "geohost2@www" + type: A + value: 127.0.0.1 + ttl: 30 + geo_location: + country_code: US + check_mode: true + register: create_geo_country_idem_check + + - assert: + that: + - create_geo_country_idem_check is not changed + - create_geo_country_idem_check is not failed + - '"route53:ChangeResourceRecordSets" not in create_geo_country_idem_check.resource_actions' + +#Test Geo Location - Subdivision Code + - name: Create a record with geo_location - subdivision_code (check_mode) + route53: + state: present + zone: '{{ zone_one }}' + record: 'geo-test-3.{{ zone_one }}' + identifier: "geohost3@www" + type: A + value: 127.0.0.1 + ttl: 30 + geo_location: + country_code: US + subdivision_code: TX + check_mode: true + register: create_geo_subdivision_check_mode + - assert: + that: + - create_geo_subdivision_check_mode is changed + - create_geo_subdivision_check_mode is not failed + - '"route53:ChangeResourceRecordSets" not in create_geo_subdivision_check_mode.resource_actions' + + - name: Create a record with geo_location - subdivision_code + route53: + state: present + zone: '{{ zone_one }}' + record: 'geo-test-3.{{ zone_one }}' + identifier: "geohost3@www" + type: A + value: 127.0.0.1 + ttl: 30 + geo_location: + country_code: US + subdivision_code: TX + register: create_geo_subdivision + # Get resulting A record and geo_location parameters are applied + - name: 'get Route53 A record information' + route53_info: + type: A + query: record_sets + hosted_zone_id: '{{ z1.zone_id }}' + start_record_name: 'geo-test-3.{{ zone_one }}' + max_items: 1 + register: result + - assert: + that: + - create_geo_subdivision is changed + - create_geo_subdivision is not failed + - '"route53:ChangeResourceRecordSets" in create_geo_subdivision.resource_actions' + - result.ResourceRecordSets[0].GeoLocation.CountryCode == "US" + - result.ResourceRecordSets[0].GeoLocation.SubdivisionCode == "TX" + + - name: Create a record with geo_location - subdivision_code (idempotency) + route53: + state: present + zone: '{{ zone_one }}' + record: 'geo-test-3.{{ zone_one }}' + identifier: "geohost3@www" + type: A + value: 127.0.0.1 + ttl: 30 + geo_location: + country_code: US + subdivision_code: TX + register: create_geo_subdivision_idem + - assert: + that: + - create_geo_subdivision_idem is not changed + - create_geo_subdivision_idem is not failed + - '"route53:ChangeResourceRecordSets" not in create_geo_subdivision_idem.resource_actions' + + - name: Create a record with geo_location - subdivision_code (idempotency - check_mode) + route53: + state: present + zone: '{{ zone_one }}' + record: 'geo-test-3.{{ zone_one }}' + identifier: "geohost3@www" + type: A + value: 127.0.0.1 + ttl: 30 + geo_location: + country_code: US + subdivision_code: TX + check_mode: true + register: create_geo_subdivision_idem_check + + - assert: + that: + - create_geo_subdivision_idem_check is not changed + - create_geo_subdivision_idem_check is not failed + - '"route53:ChangeResourceRecordSets" not in create_geo_subdivision_idem_check.resource_actions' + +#Cleanup------------------------------------------------------ + always: + + - name: delete a record with geo_location - continent_code + route53: + state: absent + zone: '{{ zone_one }}' + record: 'geo-test-1.{{ zone_one }}' + identifier: "geohost1@www" + type: A + value: 127.0.0.1 + ttl: 30 + geo_location: + continent_code: NA + ignore_errors: true + + - name: delete a record with geo_location - country_code + route53: + state: absent + zone: '{{ zone_one }}' + record: 'geo-test-2.{{ zone_one }}' + identifier: "geohost2@www" + type: A + value: 127.0.0.1 + ttl: 30 + geo_location: + country_code: US + ignore_errors: true + + - name: delete a record with geo_location - subdivision_code + route53: + state: absent + zone: '{{ zone_one }}' + record: 'geo-test-3.{{ zone_one }}' + identifier: "geohost3@www" + type: A + value: 127.0.0.1 + ttl: 30 + geo_location: + country_code: US + subdivision_code: TX + ignore_errors: true + - route53_info: query: record_sets hosted_zone_id: '{{ z1.zone_id }}' @@ -737,7 +1044,7 @@ state: absent zone: '{{ zone_one }}' register: delete_one - ignore_errors: yes + ignore_errors: true retries: 10 until: delete_one is not failed @@ -746,7 +1053,7 @@ state: absent zone: '{{ zone_two }}' register: delete_two - ignore_errors: yes + ignore_errors: True retries: 10 until: delete_two is not failed
Add route53 GeoLocation support <!--- Verify first that your feature was not already discussed on GitHub --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Describe the new feature/improvement briefly below --> Moving [issue](https://github.com/ansible/ansible/issues/24834) from Ansible repository. Add route53 GeoLocation support ##### ISSUE TYPE - Feature Idea Add change_resource_record_sets method to support route53 GeoLocation. This functionality is available in [salt](https://docs.saltstack.com/en/develop/ref/states/all/salt.states.boto3_route53.html) ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> Either update/upgrade route53 module, or create a new module to support adding/changing recourd sets. ##### ADDITIONAL INFORMATION <!--- Describe how the feature would be used, why it is needed and what it would solve --> <!--- Paste example playbooks or commands between quotes below --> ```yaml ``` <!--- HINT: You can also paste gist.github.com links for larger files -->
Files identified in the description: * [`plugins/modules/route53.py`](https://github.com/ansible-collections/community.aws/blob/main/plugins/modules/route53.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @jillr @jimbydamonk @s-hertel @tremble @wimnat [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> cc @markuman [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify --->
2022-05-10T20:22:35
ansible-collections/community.aws
1,152
ansible-collections__community.aws-1152
[ "1151" ]
3347cb04867e3cfe545a2d2570ae5daf539e8441
diff --git a/plugins/modules/lambda_info.py b/plugins/modules/lambda_info.py --- a/plugins/modules/lambda_info.py +++ b/plugins/modules/lambda_info.py @@ -13,16 +13,17 @@ short_description: Gathers AWS Lambda function details description: - Gathers various details related to Lambda functions, including aliases, versions and event source mappings. - - Use module M(community.aws.lambda) to manage the lambda function itself, M(community.aws.lambda_alias) to manage function aliases and - M(community.aws.lambda_event) to manage lambda event source mappings. + - Use module M(community.aws.lambda) to manage the lambda function itself, M(community.aws.lambda_alias) to manage function aliases, + M(community.aws.lambda_event) to manage lambda event source mappings, and M(community.aws.lambda_policy) to manage policy statements. options: query: description: - - Specifies the resource type for which to gather information. Leave blank to retrieve all information. + - Specifies the resource type for which to gather information. + - Defaults to C(all) when I(function_name) is specified. + - Defaults to C(config) when I(function_name) is NOT specified. choices: [ "aliases", "all", "config", "mappings", "policy", "versions", "tags" ] - default: "all" type: str function_name: description: @@ -48,17 +49,20 @@ query: all function_name: myFunction register: my_function_details + # List all versions of a function - name: List function versions community.aws.lambda_info: query: versions function_name: myFunction register: my_function_versions -# List all lambda function versions -- name: List all function + +# List all info for all functions +- name: List all functions community.aws.lambda_info: query: all register: output + - name: show Lambda information ansible.builtin.debug: msg: "{{ output['function'] }}" @@ -120,108 +124,118 @@ def fix_return(node): return node_value -def alias_details(client, module): +def alias_details(client, module, function_name): """ Returns list of aliases for a specified function. :param client: AWS API client reference (boto3) :param module: Ansible module reference + :param function_name (str): Name of Lambda function to query :return dict: """ lambda_info = dict() - function_name = module.params.get('function_name') - if function_name: - try: - lambda_info.update(aliases=_paginate(client, 'list_aliases', FunctionName=function_name)['Aliases']) - except is_boto3_error_code('ResourceNotFoundException'): - lambda_info.update(aliases=[]) - except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: # pylint: disable=duplicate-except - module.fail_json_aws(e, msg="Trying to get aliases") - else: - module.fail_json(msg='Parameter function_name required for query=aliases.') + try: + lambda_info.update(aliases=_paginate(client, 'list_aliases', FunctionName=function_name)['Aliases']) + except is_boto3_error_code('ResourceNotFoundException'): + lambda_info.update(aliases=[]) + except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: # pylint: disable=duplicate-except + module.fail_json_aws(e, msg="Trying to get aliases") - return {function_name: camel_dict_to_snake_dict(lambda_info)} + return camel_dict_to_snake_dict(lambda_info) -def all_details(client, module): +def list_lambdas(client, module): """ - Returns all lambda related facts. + Returns queried facts for a specified function (or all functions). :param client: AWS API client reference (boto3) :param module: Ansible module reference :return dict: """ - lambda_info = dict() - function_name = module.params.get('function_name') if function_name: - lambda_info[function_name] = {} - lambda_info[function_name].update(config_details(client, module)[function_name]) - lambda_info[function_name].update(alias_details(client, module)[function_name]) - lambda_info[function_name].update(policy_details(client, module)[function_name]) - lambda_info[function_name].update(version_details(client, module)[function_name]) - lambda_info[function_name].update(mapping_details(client, module)[function_name]) - lambda_info[function_name].update(tags_details(client, module)[function_name]) + # Function name is specified - retrieve info on that function + function_names = [function_name] + else: - lambda_info.update(config_details(client, module)) + # Function name is not specified - retrieve all function names + all_function_info = _paginate(client, 'list_functions')['Functions'] + function_names = [function_info['FunctionName'] for function_info in all_function_info] + + query = module.params['query'] + lambdas = dict() + + for function_name in function_names: + lambdas[function_name] = {} - return lambda_info + if query == 'all': + lambdas[function_name].update(config_details(client, module, function_name)) + lambdas[function_name].update(alias_details(client, module, function_name)) + lambdas[function_name].update(policy_details(client, module, function_name)) + lambdas[function_name].update(version_details(client, module, function_name)) + lambdas[function_name].update(mapping_details(client, module, function_name)) + lambdas[function_name].update(tags_details(client, module, function_name)) + elif query == 'config': + lambdas[function_name].update(config_details(client, module, function_name)) -def config_details(client, module): + elif query == 'aliases': + lambdas[function_name].update(alias_details(client, module, function_name)) + + elif query == 'policy': + lambdas[function_name].update(policy_details(client, module, function_name)) + + elif query == 'versions': + lambdas[function_name].update(version_details(client, module, function_name)) + + elif query == 'mappings': + lambdas[function_name].update(mapping_details(client, module, function_name)) + + elif query == 'tags': + lambdas[function_name].update(tags_details(client, module, function_name)) + + return lambdas + + +def config_details(client, module, function_name): """ - Returns configuration details for one or all lambda functions. + Returns configuration details for a lambda function. :param client: AWS API client reference (boto3) :param module: Ansible module reference + :param function_name (str): Name of Lambda function to query :return dict: """ lambda_info = dict() - function_name = module.params.get('function_name') - if function_name: - try: - lambda_info.update(client.get_function_configuration(aws_retry=True, FunctionName=function_name)) - except is_boto3_error_code('ResourceNotFoundException'): - lambda_info.update(function={}) - except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: # pylint: disable=duplicate-except - module.fail_json_aws(e, msg="Trying to get {0} configuration".format(function_name)) - else: - try: - lambda_info.update(function_list=_paginate(client, 'list_functions')['Functions']) - except is_boto3_error_code('ResourceNotFoundException'): - lambda_info.update(function_list=[]) - except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: # pylint: disable=duplicate-except - module.fail_json_aws(e, msg="Trying to get function list") - - functions = dict() - for func in lambda_info.pop('function_list', []): - func['tags'] = client.get_function(FunctionName=func['FunctionName']).get('Tags', {}) - functions[func['FunctionName']] = camel_dict_to_snake_dict(func) - return functions + try: + lambda_info.update(client.get_function_configuration(aws_retry=True, FunctionName=function_name)) + except is_boto3_error_code('ResourceNotFoundException'): + lambda_info.update(function={}) + except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: # pylint: disable=duplicate-except + module.fail_json_aws(e, msg="Trying to get {0} configuration".format(function_name)) - return {function_name: camel_dict_to_snake_dict(lambda_info)} + return camel_dict_to_snake_dict(lambda_info) -def mapping_details(client, module): +def mapping_details(client, module, function_name): """ Returns all lambda event source mappings. :param client: AWS API client reference (boto3) :param module: Ansible module reference + :param function_name (str): Name of Lambda function to query :return dict: """ lambda_info = dict() params = dict() - function_name = module.params.get('function_name') - if function_name: - params['FunctionName'] = module.params.get('function_name') + params['FunctionName'] = function_name if module.params.get('event_source_arn'): params['EventSourceArn'] = module.params.get('event_source_arn') @@ -233,86 +247,74 @@ def mapping_details(client, module): except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: # pylint: disable=duplicate-except module.fail_json_aws(e, msg="Trying to get source event mappings") - if function_name: - return {function_name: camel_dict_to_snake_dict(lambda_info)} - return camel_dict_to_snake_dict(lambda_info) -def policy_details(client, module): +def policy_details(client, module, function_name): """ Returns policy attached to a lambda function. :param client: AWS API client reference (boto3) :param module: Ansible module reference + :param function_name (str): Name of Lambda function to query :return dict: """ lambda_info = dict() - function_name = module.params.get('function_name') - if function_name: - try: - # get_policy returns a JSON string so must convert to dict before reassigning to its key - lambda_info.update(policy=json.loads(client.get_policy(aws_retry=True, FunctionName=function_name)['Policy'])) - except is_boto3_error_code('ResourceNotFoundException'): - lambda_info.update(policy={}) - except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: # pylint: disable=duplicate-except - module.fail_json_aws(e, msg="Trying to get {0} policy".format(function_name)) - else: - module.fail_json(msg='Parameter function_name required for query=policy.') + try: + # get_policy returns a JSON string so must convert to dict before reassigning to its key + lambda_info.update(policy=json.loads(client.get_policy(aws_retry=True, FunctionName=function_name)['Policy'])) + except is_boto3_error_code('ResourceNotFoundException'): + lambda_info.update(policy={}) + except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: # pylint: disable=duplicate-except + module.fail_json_aws(e, msg="Trying to get {0} policy".format(function_name)) - return {function_name: camel_dict_to_snake_dict(lambda_info)} + return camel_dict_to_snake_dict(lambda_info) -def version_details(client, module): +def version_details(client, module, function_name): """ Returns all lambda function versions. :param client: AWS API client reference (boto3) :param module: Ansible module reference + :param function_name (str): Name of Lambda function to query :return dict: """ lambda_info = dict() - function_name = module.params.get('function_name') - if function_name: - try: - lambda_info.update(versions=_paginate(client, 'list_versions_by_function', FunctionName=function_name)['Versions']) - except is_boto3_error_code('ResourceNotFoundException'): - lambda_info.update(versions=[]) - except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: # pylint: disable=duplicate-except - module.fail_json_aws(e, msg="Trying to get {0} versions".format(function_name)) - else: - module.fail_json(msg='Parameter function_name required for query=versions.') + try: + lambda_info.update(versions=_paginate(client, 'list_versions_by_function', FunctionName=function_name)['Versions']) + except is_boto3_error_code('ResourceNotFoundException'): + lambda_info.update(versions=[]) + except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: # pylint: disable=duplicate-except + module.fail_json_aws(e, msg="Trying to get {0} versions".format(function_name)) - return {function_name: camel_dict_to_snake_dict(lambda_info)} + return camel_dict_to_snake_dict(lambda_info) -def tags_details(client, module): +def tags_details(client, module, function_name): """ - Returns tag details for one or all lambda functions. + Returns tag details for a lambda function. :param client: AWS API client reference (boto3) :param module: Ansible module reference + :param function_name (str): Name of Lambda function to query :return dict: """ lambda_info = dict() - function_name = module.params.get('function_name') - if function_name: - try: - lambda_info.update(tags=client.get_function(aws_retry=True, FunctionName=function_name).get('Tags', {})) - except is_boto3_error_code('ResourceNotFoundException'): - lambda_info.update(function={}) - except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: # pylint: disable=duplicate-except - module.fail_json_aws(e, msg="Trying to get {0} tags".format(function_name)) - else: - module.fail_json(msg='Parameter function_name required for query=tags.') + try: + lambda_info.update(tags=client.get_function(aws_retry=True, FunctionName=function_name).get('Tags', {})) + except is_boto3_error_code('ResourceNotFoundException'): + lambda_info.update(function={}) + except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: # pylint: disable=duplicate-except + module.fail_json_aws(e, msg="Trying to get {0} tags".format(function_name)) - return {function_name: camel_dict_to_snake_dict(lambda_info)} + return camel_dict_to_snake_dict(lambda_info) def main(): @@ -323,7 +325,7 @@ def main(): """ argument_spec = dict( function_name=dict(required=False, default=None, aliases=['function', 'name']), - query=dict(required=False, choices=['aliases', 'all', 'config', 'mappings', 'policy', 'versions', 'tags'], default='all'), + query=dict(required=False, choices=['aliases', 'all', 'config', 'mappings', 'policy', 'versions', 'tags'], default=None), event_source_arn=dict(required=False, default=None), ) @@ -344,20 +346,18 @@ def main(): if len(function_name) > 64: module.fail_json(msg='Function name "{0}" exceeds 64 character limit'.format(function_name)) - client = module.client('lambda', retry_decorator=AWSRetry.jittered_backoff()) + # create default values for query if not specified. + # if function name exists, query should default to 'all'. + # if function name does not exist, query should default to 'config' to limit the runtime when listing all lambdas. + if not module.params.get('query'): + if function_name: + module.params['query'] = 'all' + else: + module.params['query'] = 'config' - invocations = dict( - aliases='alias_details', - all='all_details', - config='config_details', - mappings='mapping_details', - policy='policy_details', - versions='version_details', - tags='tags_details', - ) + client = module.client('lambda', retry_decorator=AWSRetry.jittered_backoff()) - this_module_function = globals()[invocations[module.params['query']]] - all_facts = fix_return(this_module_function(client, module)) + all_facts = fix_return(list_lambdas(client, module)) results = dict(function=all_facts, changed=False)
diff --git a/tests/integration/targets/lambda/tasks/main.yml b/tests/integration/targets/lambda/tasks/main.yml --- a/tests/integration/targets/lambda/tasks/main.yml +++ b/tests/integration/targets/lambda/tasks/main.yml @@ -252,10 +252,9 @@ - result.configuration.runtime == 'python3.6' - result.configuration.tracing_config.mode == 'PassThrough' - # Query the Lambda - - name: lambda_info | Gather all infos for given lambda function + # Test lambda_info + - name: lambda_info | Gather all infos for all lambda functions lambda_info: - name: '{{ lambda_function_name }}' query: all register: lambda_infos_all check_mode: yes @@ -263,17 +262,54 @@ assert: that: - lambda_infos_all is not failed + - lambda_infos_all.function | length > 0 - lambda_infos_all.function[lambda_function_name].function_name == lambda_function_name - lambda_infos_all.function[lambda_function_name].runtime == "python3.6" + - lambda_infos_all.function[lambda_function_name].description == "" + - lambda_infos_all.function[lambda_function_name].function_arn is defined + - lambda_infos_all.function[lambda_function_name].handler == "mini_lambda.handler" - lambda_infos_all.function[lambda_function_name].versions is defined - lambda_infos_all.function[lambda_function_name].aliases is defined - lambda_infos_all.function[lambda_function_name].policy is defined - lambda_infos_all.function[lambda_function_name].mappings is defined - - lambda_infos_all.function[lambda_function_name].description == "" - - lambda_infos_all.function[lambda_function_name].function_arn is defined - - lambda_infos_all.function[lambda_function_name].handler == "mini_lambda.handler" - lambda_infos_all.function[lambda_function_name].tags is defined + - name: lambda_info | Ensure default query value is 'config' when function name omitted + lambda_info: + register: lambda_infos_query_config + check_mode: yes + - name: lambda_info | Assert successfull retrieval of all information + assert: + that: + - lambda_infos_query_config is not failed + - lambda_infos_query_config.function | length > 0 + - lambda_infos_query_config.function[lambda_function_name].function_name == lambda_function_name + - lambda_infos_query_config.function[lambda_function_name].runtime == "python3.6" + - lambda_infos_query_config.function[lambda_function_name].description == "" + - lambda_infos_query_config.function[lambda_function_name].function_arn is defined + - lambda_infos_query_config.function[lambda_function_name].handler == "mini_lambda.handler" + - lambda_infos_query_config.function[lambda_function_name].versions is not defined + - lambda_infos_query_config.function[lambda_function_name].aliases is not defined + - lambda_infos_query_config.function[lambda_function_name].policy is not defined + - lambda_infos_query_config.function[lambda_function_name].mappings is not defined + - lambda_infos_query_config.function[lambda_function_name].tags is not defined + + - name: lambda_info | Ensure default query value is 'all' when function name specified + lambda_info: + name: '{{ lambda_function_name }}' + register: lambda_infos_query_all + - name: lambda_info | Assert successfull retrieval of all information + assert: + that: + - lambda_infos_query_all is not failed + - lambda_infos_query_all.function | length == 1 + - lambda_infos_query_all.function[lambda_function_name].versions|length > 0 + - lambda_infos_query_all.function[lambda_function_name].function_name is defined + - lambda_infos_query_all.function[lambda_function_name].policy is defined + - lambda_infos_query_all.function[lambda_function_name].aliases is defined + - lambda_infos_query_all.function[lambda_function_name].mappings is defined + - lambda_infos_query_all.function[lambda_function_name].tags is defined + - name: lambda_info | Gather version infos for given lambda function lambda_info: name: '{{ lambda_function_name }}' @@ -283,8 +319,13 @@ assert: that: - lambda_infos_versions is not failed + - lambda_infos_versions.function | length == 1 - lambda_infos_versions.function[lambda_function_name].versions|length > 0 - lambda_infos_versions.function[lambda_function_name].function_name is undefined + - lambda_infos_versions.function[lambda_function_name].policy is undefined + - lambda_infos_versions.function[lambda_function_name].aliases is undefined + - lambda_infos_versions.function[lambda_function_name].mappings is undefined + - lambda_infos_versions.function[lambda_function_name].tags is undefined - name: lambda_info | Gather config infos for given lambda function lambda_info: @@ -295,9 +336,14 @@ assert: that: - lambda_infos_config is not failed + - lambda_infos_config.function | length == 1 - lambda_infos_config.function[lambda_function_name].function_name == lambda_function_name - lambda_infos_config.function[lambda_function_name].description is defined - lambda_infos_config.function[lambda_function_name].versions is undefined + - lambda_infos_config.function[lambda_function_name].policy is undefined + - lambda_infos_config.function[lambda_function_name].aliases is undefined + - lambda_infos_config.function[lambda_function_name].mappings is undefined + - lambda_infos_config.function[lambda_function_name].tags is undefined - name: lambda_info | Gather policy infos for given lambda function lambda_info: @@ -308,8 +354,13 @@ assert: that: - lambda_infos_policy is not failed + - lambda_infos_policy.function | length == 1 - lambda_infos_policy.function[lambda_function_name].policy is defined - lambda_infos_policy.function[lambda_function_name].versions is undefined + - lambda_infos_policy.function[lambda_function_name].function_name is undefined + - lambda_infos_policy.function[lambda_function_name].aliases is undefined + - lambda_infos_policy.function[lambda_function_name].mappings is undefined + - lambda_infos_policy.function[lambda_function_name].tags is undefined - name: lambda_info | Gather aliases infos for given lambda function lambda_info: @@ -320,7 +371,13 @@ assert: that: - lambda_infos_aliases is not failed + - lambda_infos_aliases.function | length == 1 - lambda_infos_aliases.function[lambda_function_name].aliases is defined + - lambda_infos_aliases.function[lambda_function_name].versions is undefined + - lambda_infos_aliases.function[lambda_function_name].function_name is undefined + - lambda_infos_aliases.function[lambda_function_name].policy is undefined + - lambda_infos_aliases.function[lambda_function_name].mappings is undefined + - lambda_infos_aliases.function[lambda_function_name].tags is undefined - name: lambda_info | Gather mappings infos for given lambda function lambda_info: @@ -331,7 +388,13 @@ assert: that: - lambda_infos_mappings is not failed + - lambda_infos_mappings.function | length == 1 - lambda_infos_mappings.function[lambda_function_name].mappings is defined + - lambda_infos_mappings.function[lambda_function_name].versions is undefined + - lambda_infos_mappings.function[lambda_function_name].function_name is undefined + - lambda_infos_mappings.function[lambda_function_name].aliases is undefined + - lambda_infos_mappings.function[lambda_function_name].policy is undefined + - lambda_infos_mappings.function[lambda_function_name].tags is undefined # More Lambda update tests - name: test state=present with all nullable variables explicitly set to null @@ -523,11 +586,19 @@ - result is not failed always: - - name: ensure function is absent at end of test + + - name: ensure functions are absent at end of test lambda: - name: '{{lambda_function_name}}' + name: "{{ item }}" state: absent ignore_errors: true + with_items: + - "{{ lambda_function_name }}" + - "{{ lambda_function_name }}_1" + - "{{ lambda_function_name }}_2" + - "{{ lambda_function_name }}_3" + - "{{ lambda_function_name }}_4" + - name: ensure role has been removed at end of test iam_role: name: '{{ lambda_role_name }}'
lambda_info - only queries config info when function_name is omitted ### Summary When trying to retrieve info on all lambda functions (by omitting `function_name`), module acts as if `query = config` ### Issue Type Bug Report ### Component Name lambda_info ### Ansible Version ```console (paste below) $ ansible --version ``` ### Collection Versions ```console (paste below) $ ansible-galaxy collection list ``` ### AWS SDK versions ```console (paste below) $ pip show boto boto3 botocore ``` ### Configuration ```console (paste below) $ ansible-config dump --only-changed ``` ### OS / Environment _No response_ ### Steps to Reproduce <!--- Paste example playbooks or commands between quotes below --> ```yaml (paste below) # Query the Lambda - name: lambda_info | Gather all infos for all lambda functions lambda_info: register: lambda_infos_all check_mode: yes - name: lambda_info | Assert successfull retrieval of all information assert: that: - lambda_infos_all | length > 0 - lambda_infos_all is not failed - lambda_infos_all.function[lambda_function_name].function_name == lambda_function_name - lambda_infos_all.function[lambda_function_name].runtime == "python3.6" - lambda_infos_all.function[lambda_function_name].versions is defined - lambda_infos_all.function[lambda_function_name].aliases is defined - lambda_infos_all.function[lambda_function_name].policy is defined - lambda_infos_all.function[lambda_function_name].mappings is defined - lambda_infos_all.function[lambda_function_name].description == "" - lambda_infos_all.function[lambda_function_name].function_arn is defined - lambda_infos_all.function[lambda_function_name].handler == "mini_lambda.handler" - lambda_infos_all.function[lambda_function_name].tags is defined ``` ### Expected Results ```yaml (paste below) "function": { "70f9dc46f894": { "aliases": [], "code_sha256": "LC/DkOB9wKYLWMSMqYoGPw8yyXUVHcDcdShg/MUKyYM=", "code_size": 854, "description": "", "function_arn": "arn:aws:lambda:us-east-1:721066863947:function:70f9dc46f894", "function_name": "70f9dc46f894", "handler": "mini_lambda.handler", "last_modified": "2022-05-19T19:46:15.375+0000", "mappings": [], "memory_size": 128, "package_type": "Zip", "policy": {}, "response_metadata": { "http_headers": { "connection": "keep-alive", "content-length": "986", "content-type": "application/json", "date": "Thu, 19 May 2022 19:46:18 GMT", "x-amzn-requestid": "0b50adea-e1ed-4f25-975f-f0eec9478282" }, "http_status_code": 200, "request_id": "0b50adea-e1ed-4f25-975f-f0eec9478282", "retry_attempts": 0 }, "revision_id": "20bbfe78-8589-46ca-8fb3-6ff089ea7bab", "role": "arn:aws:iam::721066863947:role/ansible-test-70f9dc46f894-lambda", "runtime": "python3.6", "state": "Pending", "state_reason": "The function is being created.", "state_reason_code": "Creating", "tags": {}, "timeout": 3, "tracing_config": { "mode": "PassThrough" }, "version": "$LATEST", "versions": [ { "code_sha256": "LC/DkOB9wKYLWMSMqYoGPw8yyXUVHcDcdShg/MUKyYM=", "code_size": 854, "description": "", "function_arn": "arn:aws:lambda:us-east-1:721066863947:function:70f9dc46f894:$LATEST", "function_name": "70f9dc46f894", "handler": "mini_lambda.handler", "last_modified": "2022-05-19T19:46:15.375+0000", "memory_size": 128, "package_type": "Zip", "revision_id": "20bbfe78-8589-46ca-8fb3-6ff089ea7bab", "role": "arn:aws:iam::721066863947:role/ansible-test-70f9dc46f894-lambda", "runtime": "python3.6", "timeout": 3, "tracing_config": { "mode": "PassThrough" }, "version": "$LATEST" }, { "code_sha256": "LC/DkOB9wKYLWMSMqYoGPw8yyXUVHcDcdShg/MUKyYM=", "code_size": 854, "description": "", "function_arn": "arn:aws:lambda:us-east-1:721066863947:function:70f9dc46f894:1", "function_name": "70f9dc46f894", "handler": "mini_lambda.handler", "last_modified": "2022-05-19T19:46:15.375+0000", "memory_size": 128, "package_type": "Zip", "revision_id": "23d33d24-983b-47e2-92cd-142bc18b1833", "role": "arn:aws:iam::721066863947:role/ansible-test-70f9dc46f894-lambda", "runtime": "python3.6", "timeout": 3, "tracing_config": { "mode": "PassThrough" }, "version": "1" } ] } ``` ### Actual Results ```yaml (paste below) "function": { "7a603343767f": { "code_sha256": "HcAK+Oux100a8L18ww1SdRC1NgwU4CTn0RHIj65dHO4=", "code_size": 854, "description": "", "function_arn": "arn:aws:lambda:us-east-1:721066863947:function:7a603343767f", "function_name": "7a603343767f", "handler": "mini_lambda.handler", "last_modified": "2022-05-19T19:59:25.000+0000", "memory_size": 128, "package_type": "Zip", "revision_id": "d1d89e30-797d-453f-92ae-efc1f6ab7c34", "role": "arn:aws:iam::721066863947:role/ansible-test-7a603343767f-lambda", "runtime": "python3.6", "tags": { "camel_case": "ACamelCaseValue", "snake_case": "a_snake_case_value", "spaced key": "A value with spaces" }, "timeout": 3, "tracing_config": { "mode": "PassThrough" }, "version": "$LATEST" } ``` ### Code of Conduct - [X] I agree to follow the Ansible Code of Conduct
Files identified in the description: * [`plugins/modules/lambda_info.py`](https://github.com/['ansible-collections/amazon.aws', 'ansible-collections/community.aws', 'ansible-collections/community.vmware']/blob/main/plugins/modules/lambda_info.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @jillr @markuman @pjodouin @s-hertel @tremble [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify --->
2022-05-19T22:20:35
ansible-collections/community.aws
1,156
ansible-collections__community.aws-1156
[ "210" ]
236f5204419957a9e4d624177cbda591193e23ce
diff --git a/plugins/modules/rds_instance_snapshot.py b/plugins/modules/rds_instance_snapshot.py --- a/plugins/modules/rds_instance_snapshot.py +++ b/plugins/modules/rds_instance_snapshot.py @@ -32,15 +32,37 @@ type: str db_instance_identifier: description: - - Database instance identifier. Required when state is present. + - Database instance identifier. Required when creating a snapshot. aliases: - instance_id type: str + source_db_snapshot_identifier: + description: + - The identifier of the source DB snapshot. + - Required when copying a snapshot. + - If the source snapshot is in the same AWS region as the copy, specify the snapshot's identifier. + - If the source snapshot is in a different AWS region as the copy, specify the snapshot's ARN. + aliases: + - source_id + - source_snapshot_id + type: str + version_added: 3.3.0 + source_region: + description: + - The region that contains the snapshot to be copied. + type: str + version_added: 3.3.0 + copy_tags: + description: + - Whether to copy all tags from I(source_db_snapshot_identifier) to I(db_instance_identifier). + type: bool + default: False + version_added: 3.3.0 wait: description: - Whether or not to wait for snapshot creation or deletion. type: bool - default: 'no' + default: False wait_timeout: description: - how long before wait gives up, in seconds. @@ -52,13 +74,14 @@ type: dict purge_tags: description: - - whether to remove tags not present in the C(tags) parameter. + - whether to remove tags not present in the I(tags) parameter. default: True type: bool author: - "Will Thames (@willthames)" - "Michael De La Rue (@mikedlr)" - "Alina Buzachis (@alinabuzachis)" + - "Joseph Torcasso (@jatorcasso)" extends_documentation_fragment: - amazon.aws.aws - amazon.aws.ec2 @@ -70,6 +93,15 @@ community.aws.rds_instance_snapshot: db_instance_identifier: new-database db_snapshot_identifier: new-database-snapshot + register: snapshot + +- name: Copy snapshot from a different region and copy its tags + community.aws.rds_instance_snapshot: + id: new-database-snapshot-copy + region: us-east-1 + source_id: "{{ snapshot.db_snapshot_arn }}" + source_region: us-east-2 + copy_tags: yes - name: Delete snapshot community.aws.rds_instance_snapshot: @@ -163,6 +195,12 @@ returned: always type: list sample: [] +source_db_snapshot_identifier: + description: The DB snapshot ARN that the DB snapshot was copied from. + returned: when snapshot is a copy + type: str + sample: arn:aws:rds:us-west-2:123456789012:snapshot:ansible-test-16638696-test-snapshot-source + version_added: 3.3.0 snapshot_create_time: description: Creation time of the snapshot. returned: always @@ -202,31 +240,41 @@ # import module snippets from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule +from ansible_collections.amazon.aws.plugins.module_utils.core import get_boto3_client_method_parameters from ansible_collections.amazon.aws.plugins.module_utils.core import is_boto3_error_code +from ansible_collections.amazon.aws.plugins.module_utils.ec2 import ansible_dict_to_boto3_tag_list from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AWSRetry from ansible_collections.amazon.aws.plugins.module_utils.ec2 import camel_dict_to_snake_dict -from ansible_collections.amazon.aws.plugins.module_utils.ec2 import ansible_dict_to_boto3_tag_list -from ansible_collections.amazon.aws.plugins.module_utils.rds import get_tags -from ansible_collections.amazon.aws.plugins.module_utils.rds import ensure_tags +from ansible_collections.amazon.aws.plugins.module_utils.rds import arg_spec_to_rds_params from ansible_collections.amazon.aws.plugins.module_utils.rds import call_method +from ansible_collections.amazon.aws.plugins.module_utils.rds import ensure_tags +from ansible_collections.amazon.aws.plugins.module_utils.rds import get_rds_method_attribute +from ansible_collections.amazon.aws.plugins.module_utils.rds import get_tags def get_snapshot(snapshot_id): try: - response = client.describe_db_snapshots(DBSnapshotIdentifier=snapshot_id) - except is_boto3_error_code("DBSnapshotNotFoundFault"): - return None - except is_boto3_error_code("DBSnapshotNotFound"): # pylint: disable=duplicate-except - return None + snapshot = client.describe_db_snapshots(DBSnapshotIdentifier=snapshot_id)['DBSnapshots'][0] + snapshot['Tags'] = get_tags(client, module, snapshot['DBSnapshotArn']) + except is_boto3_error_code("DBSnapshotNotFound"): + return {} except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: # pylint: disable=duplicate-except module.fail_json_aws(e, msg="Couldn't get snapshot {0}".format(snapshot_id)) - return response['DBSnapshots'][0] + return snapshot -def fetch_tags(snapshot): - snapshot["Tags"] = get_tags(client, module, snapshot["DBSnapshotArn"]) +def get_parameters(parameters, method_name): + if method_name == 'copy_db_snapshot': + parameters['TargetDBSnapshotIdentifier'] = module.params['db_snapshot_identifier'] - return camel_dict_to_snake_dict(snapshot, ignore_list=["Tags"]) + required_options = get_boto3_client_method_parameters(client, method_name, required=True) + if any(parameters.get(k) is None for k in required_options): + module.fail_json(msg='To {0} requires the parameters: {1}'.format( + get_rds_method_attribute(method_name, module).operation_description, required_options)) + options = get_boto3_client_method_parameters(client, method_name) + parameters = dict((k, v) for k, v in parameters.items() if k in options and v is not None) + + return parameters def ensure_snapshot_absent(): @@ -236,40 +284,68 @@ def ensure_snapshot_absent(): snapshot = get_snapshot(snapshot_name) if not snapshot: - return dict(changed=changed) + module.exit_json(changed=changed) elif snapshot and snapshot["Status"] != "deleting": snapshot, changed = call_method(client, module, "delete_db_snapshot", params) - return dict(changed=changed) + module.exit_json(changed=changed) -def ensure_snapshot_present(): - db_instance_identifier = module.params.get('db_instance_identifier') +def ensure_snapshot_present(params): + source_id = module.params.get('source_db_snapshot_identifier') snapshot_name = module.params.get('db_snapshot_identifier') changed = False snapshot = get_snapshot(snapshot_name) + + # Copy snapshot + if source_id: + changed |= copy_snapshot(params) + + # Create snapshot + elif not snapshot: + changed |= create_snapshot(params) + + # Snapshot exists and we're not creating a copy - modify exising snapshot + else: + changed |= modify_snapshot() + + snapshot = get_snapshot(snapshot_name) + module.exit_json(changed=changed, **camel_dict_to_snake_dict(snapshot, ignore_list=['Tags'])) + + +def create_snapshot(params): + method_params = get_parameters(params, 'create_db_snapshot') + if method_params.get('Tags'): + method_params['Tags'] = ansible_dict_to_boto3_tag_list(method_params['Tags']) + snapshot, changed = call_method(client, module, 'create_db_snapshot', method_params) + + return changed + + +def copy_snapshot(params): + changed = False + snapshot_id = module.params.get('db_snapshot_identifier') + snapshot = get_snapshot(snapshot_id) + if not snapshot: - params = { - "DBSnapshotIdentifier": snapshot_name, - "DBInstanceIdentifier": db_instance_identifier - } - if module.params.get("tags"): - params['Tags'] = ansible_dict_to_boto3_tag_list(module.params.get("tags")) - _result, changed = call_method(client, module, "create_db_snapshot", params) + method_params = get_parameters(params, 'copy_db_snapshot') + if method_params.get('Tags'): + method_params['Tags'] = ansible_dict_to_boto3_tag_list(method_params['Tags']) + result, changed = call_method(client, module, 'copy_db_snapshot', method_params) - if module.check_mode: - return dict(changed=changed) + return changed - return dict(changed=changed, **fetch_tags(get_snapshot(snapshot_name))) - existing_tags = get_tags(client, module, snapshot["DBSnapshotArn"]) - changed |= ensure_tags(client, module, snapshot["DBSnapshotArn"], existing_tags, - module.params["tags"], module.params["purge_tags"]) +def modify_snapshot(): + # TODO - add other modifications aside from purely tags + changed = False + snapshot_id = module.params.get('db_snapshot_identifier') + snapshot = get_snapshot(snapshot_id) - if module.check_mode: - return dict(changed=changed) + if module.params.get('tags'): + changed |= ensure_tags(client, module, snapshot['DBSnapshotArn'], snapshot['Tags'], module.params['tags'], module.params['purge_tags']) - return dict(changed=changed, **fetch_tags(get_snapshot(snapshot_name))) + return changed def main(): @@ -280,16 +356,18 @@ def main(): state=dict(choices=['present', 'absent'], default='present'), db_snapshot_identifier=dict(aliases=['id', 'snapshot_id'], required=True), db_instance_identifier=dict(aliases=['instance_id']), + source_db_snapshot_identifier=dict(aliases=['source_id', 'source_snapshot_id']), wait=dict(type='bool', default=False), wait_timeout=dict(type='int', default=300), tags=dict(type='dict'), purge_tags=dict(type='bool', default=True), + copy_tags=dict(type='bool', default=False), + source_region=dict(type='str'), ) module = AnsibleAWSModule( argument_spec=argument_spec, - required_if=[['state', 'present', ['db_instance_identifier']]], - supports_check_mode=True, + supports_check_mode=True ) retry_decorator = AWSRetry.jittered_backoff(retries=10) @@ -298,12 +376,13 @@ def main(): except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: module.fail_json_aws(e, msg="Failed to connect to AWS.") - if module.params['state'] == 'absent': - ret_dict = ensure_snapshot_absent() - else: - ret_dict = ensure_snapshot_present() + state = module.params.get("state") + if state == 'absent': + ensure_snapshot_absent() - module.exit_json(**ret_dict) + elif state == 'present': + params = arg_spec_to_rds_params(dict((k, module.params[k]) for k in module.params if k in argument_spec)) + ensure_snapshot_present(params) if __name__ == '__main__':
diff --git a/tests/integration/targets/rds_instance_snapshot/defaults/main.yml b/tests/integration/targets/rds_instance_snapshot/defaults/main.yml --- a/tests/integration/targets/rds_instance_snapshot/defaults/main.yml +++ b/tests/integration/targets/rds_instance_snapshot/defaults/main.yml @@ -2,13 +2,13 @@ # defaults file for rds_instance_snapshot # Create RDS instance -instance_id: 'ansible-test-instance-{{ resource_prefix }}' +instance_id: '{{ resource_prefix }}-instance' username: 'testrdsusername' -password: 'test-rds_password' +password: "{{ lookup('password', '/dev/null') }}" db_instance_class: db.t3.micro allocated_storage: 10 engine: 'mariadb' mariadb_engine_version: 10.3.31 # Create snapshot -snapshot_id: 'ansible-test-instance-snapshot-{{ resource_prefix }}' +snapshot_id: '{{ instance_id }}-snapshot' diff --git a/tests/integration/targets/rds_instance_snapshot/tasks/main.yml b/tests/integration/targets/rds_instance_snapshot/tasks/main.yml --- a/tests/integration/targets/rds_instance_snapshot/tasks/main.yml +++ b/tests/integration/targets/rds_instance_snapshot/tasks/main.yml @@ -27,12 +27,12 @@ that: - _result_create_instance.changed - _result_create_instance.db_instance_identifier == "{{ instance_id }}" - + - name: Get all RDS snapshots for the existing instance rds_snapshot_info: db_instance_identifier: "{{ instance_id }}" register: _result_instance_snapshot_info - + - assert: that: - _result_instance_snapshot_info is successful @@ -49,7 +49,7 @@ - assert: that: - _result_instance_snapshot.changed - + - name: Take a snapshot of the existing RDS instance rds_instance_snapshot: state: present @@ -89,18 +89,70 @@ - _result_instance_snapshot.storage_type == "gp2" - "'tags' in _result_instance_snapshot" - "'vpc_id' in _result_instance_snapshot" - + + - name: Take a snapshot of the existing RDS instance (CHECK_MODE - IDEMPOTENCE) + rds_instance_snapshot: + state: present + db_instance_identifier: "{{ instance_id }}" + db_snapshot_identifier: "{{ snapshot_id }}" + check_mode: yes + register: _result_instance_snapshot + + - assert: + that: + - not _result_instance_snapshot.changed + + - name: Take a snapshot of the existing RDS instance (IDEMPOTENCE) + rds_instance_snapshot: + state: present + db_instance_identifier: "{{ instance_id }}" + db_snapshot_identifier: "{{ snapshot_id }}" + wait: true + register: _result_instance_snapshot + + - assert: + that: + - not _result_instance_snapshot.changed + - "'availability_zone' in _result_instance_snapshot" + - "'instance_create_time' in _result_instance_snapshot" + - "'db_instance_identifier' in _result_instance_snapshot" + - _result_instance_snapshot.db_instance_identifier == "{{ instance_id }}" + - "'db_snapshot_identifier' in _result_instance_snapshot" + - _result_instance_snapshot.db_snapshot_identifier == "{{ snapshot_id }}" + - "'db_snapshot_arn' in _result_instance_snapshot" + - "'dbi_resource_id' in _result_instance_snapshot" + - "'encrypted' in _result_instance_snapshot" + - "'engine' in _result_instance_snapshot" + - _result_instance_snapshot.engine == "{{ engine }}" + - "'engine_version' in _result_instance_snapshot" + - _result_instance_snapshot.engine_version == "{{ mariadb_engine_version }}" + - "'iam_database_authentication_enabled' in _result_instance_snapshot" + - "'license_model' in _result_instance_snapshot" + - "'master_username' in _result_instance_snapshot" + - _result_instance_snapshot.master_username == "{{ username }}" + - "'snapshot_create_time' in _result_instance_snapshot" + - "'snapshot_type' in _result_instance_snapshot" + - "'status' in _result_instance_snapshot" + - _result_instance_snapshot.status == "available" + - "'snapshot_type' in _result_instance_snapshot" + - _result_instance_snapshot.snapshot_type == "manual" + - "'status' in _result_instance_snapshot" + - "'storage_type' in _result_instance_snapshot" + - _result_instance_snapshot.storage_type == "gp2" + - "'tags' in _result_instance_snapshot" + - "'vpc_id' in _result_instance_snapshot" + - name: Get information about the existing DB snapshot rds_snapshot_info: db_snapshot_identifier: "{{ snapshot_id }}" register: _result_instance_snapshot_info - + - assert: that: - _result_instance_snapshot_info is successful - _result_instance_snapshot_info.snapshots[0].db_instance_identifier == "{{ instance_id }}" - _result_instance_snapshot_info.snapshots[0].db_snapshot_identifier == "{{ snapshot_id }}" - + - name: Take another snapshot of the existing RDS instance rds_instance_snapshot: state: present @@ -140,38 +192,59 @@ - _result_instance_snapshot.storage_type == "gp2" - "'tags' in _result_instance_snapshot" - "'vpc_id' in _result_instance_snapshot" - + - name: Get all snapshots for the existing RDS instance rds_snapshot_info: db_instance_identifier: "{{ instance_id }}" register: _result_instance_snapshot_info - + - assert: that: - _result_instance_snapshot_info is successful #- _result_instance_snapshot_info.cluster_snapshots | length == 3 - + - name: Delete existing DB instance snapshot (CHECK_MODE) rds_instance_snapshot: state: absent db_snapshot_identifier: "{{ snapshot_id }}-b" register: _result_delete_snapshot check_mode: yes - + - assert: that: - _result_delete_snapshot.changed - + - name: Delete the existing DB instance snapshot rds_instance_snapshot: state: absent db_snapshot_identifier: "{{ snapshot_id }}-b" register: _result_delete_snapshot - + - assert: that: - _result_delete_snapshot.changed - + + - name: Delete existing DB instance snapshot (CHECK_MODE - IDEMPOTENCE) + rds_instance_snapshot: + state: absent + db_snapshot_identifier: "{{ snapshot_id }}-b" + register: _result_delete_snapshot + check_mode: yes + + - assert: + that: + - not _result_delete_snapshot.changed + + - name: Delete the existing DB instance snapshot (IDEMPOTENCE) + rds_instance_snapshot: + state: absent + db_snapshot_identifier: "{{ snapshot_id }}-b" + register: _result_delete_snapshot + + - assert: + that: + - not _result_delete_snapshot.changed + - name: Take another snapshot of the existing RDS instance and assign tags rds_instance_snapshot: state: present @@ -217,7 +290,7 @@ - _result_instance_snapshot.tags["tag_one"] == "{{ snapshot_id }}-b One" - _result_instance_snapshot.tags["Tag Two"] == "two {{ snapshot_id }}-b" - "'vpc_id' in _result_instance_snapshot" - + - name: Attempt to take another snapshot of the existing RDS instance and assign tags (idempotence) rds_instance_snapshot: state: present @@ -232,7 +305,7 @@ - assert: that: - not _result_instance_snapshot.changed - + - name: Take another snapshot of the existing RDS instance and update tags rds_instance_snapshot: state: present @@ -277,7 +350,7 @@ - _result_instance_snapshot.tags["tag_three"] == "{{ snapshot_id }}-b Three" - _result_instance_snapshot.tags["Tag Two"] == "two {{ snapshot_id }}-b" - "'vpc_id' in _result_instance_snapshot" - + - name: Take another snapshot of the existing RDS instance and update tags without purge rds_instance_snapshot: state: present @@ -323,7 +396,7 @@ - _result_instance_snapshot.tags["Tag Two"] == "two {{ snapshot_id }}-b" - _result_instance_snapshot.tags["tag_three"] == "{{ snapshot_id }}-b Three" - "'vpc_id' in _result_instance_snapshot" - + - name: Take another snapshot of the existing RDS instance and do not specify any tag to ensure previous tags are not removed rds_instance_snapshot: state: present @@ -334,25 +407,99 @@ - assert: that: - not _result_instance_snapshot.changed - - always: + + # ------------------------------------------------------------------------------------------ + # Test copying a snapshot + ### Note - copying a snapshot from a different region is supported, but not in CI runs, + ### because the aws-terminator only terminates resources in one region. + + - set_fact: + _snapshot_arn: "{{ _result_instance_snapshot.db_snapshot_arn }}" + + - name: Copy a snapshot (check mode) + rds_instance_snapshot: + id: "{{ snapshot_id }}-copy" + source_id: "{{ snapshot_id }}-b" + copy_tags: yes + wait: true + register: _result_instance_snapshot + check_mode: yes + + - assert: + that: + - _result_instance_snapshot.changed + + - name: Copy a snapshot + rds_instance_snapshot: + id: "{{ snapshot_id }}-copy" + source_id: "{{ snapshot_id }}-b" + copy_tags: yes + wait: true + register: _result_instance_snapshot + + - assert: + that: + - _result_instance_snapshot.changed + - _result_instance_snapshot.db_instance_identifier == "{{ instance_id }}" + - _result_instance_snapshot.source_db_snapshot_identifier == "{{ _snapshot_arn }}" + - _result_instance_snapshot.db_snapshot_identifier == "{{ snapshot_id }}-copy" + - "'tags' in _result_instance_snapshot" + - _result_instance_snapshot.tags | length == 3 + - _result_instance_snapshot.tags["tag_one"] == "{{ snapshot_id }}-b One" + - _result_instance_snapshot.tags["Tag Two"] == "two {{ snapshot_id }}-b" + - _result_instance_snapshot.tags["tag_three"] == "{{ snapshot_id }}-b Three" + + - name: Copy a snapshot (idempotence - check mode) + rds_instance_snapshot: + id: "{{ snapshot_id }}-copy" + source_id: "{{ snapshot_id }}-b" + copy_tags: yes + wait: true + register: _result_instance_snapshot + check_mode: yes + + - assert: + that: + - not _result_instance_snapshot.changed + + - name: Copy a snapshot (idempotence) + rds_instance_snapshot: + id: "{{ snapshot_id }}-copy" + source_id: "{{ snapshot_id }}-b" + copy_tags: yes + wait: true + register: _result_instance_snapshot + + - assert: + that: + - not _result_instance_snapshot.changed + - _result_instance_snapshot.db_instance_identifier == "{{ instance_id }}" + - _result_instance_snapshot.source_db_snapshot_identifier == "{{ _snapshot_arn }}" + - _result_instance_snapshot.db_snapshot_identifier == "{{ snapshot_id }}-copy" + - "'tags' in _result_instance_snapshot" + - _result_instance_snapshot.tags | length == 3 + - _result_instance_snapshot.tags["tag_one"] == "{{ snapshot_id }}-b One" + - _result_instance_snapshot.tags["Tag Two"] == "two {{ snapshot_id }}-b" + - _result_instance_snapshot.tags["tag_three"] == "{{ snapshot_id }}-b Three" + + always: - name: Delete the existing DB instance snapshots rds_instance_snapshot: state: absent db_snapshot_identifier: "{{ item }}" + wait: false register: _result_delete_snapshot ignore_errors: true loop: - "{{ snapshot_id }}" - "{{ snapshot_id }}-b" + - "{{ snapshot_id }}-copy" - name: Delete the existing RDS instance without creating a final snapshot rds_instance: state: absent - instance_id: "{{ item }}" + instance_id: "{{ instance_id }}" skip_final_snapshot: True + wait: false register: _result_delete_instance ignore_errors: true - loop: - - "{{ instance_id }}" - - "{{ instance_id }}-b"
Extend rds module to allow copying of rds snaphots cross region <!--- Verify first that your feature was not already discussed on GitHub --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Describe the new feature/improvement briefly below --> Extend to allow module to copy an rds snapshot to another region. ##### ISSUE TYPE - Feature Idea ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> rds_instance rds ##### ADDITIONAL INFORMATION <!--- Describe how the feature would be used, why it is needed and what it would solve --> During automated backups of databases, copy rds snapshot to different region for backup redundancy and ensure availability of rds instance. <!--- Paste example playbooks or commands between quotes below --> ```yaml ``` <!--- HINT: You can also paste gist.github.com links for larger files -->
Files identified in the description: * [`plugins/modules/rds.py`](https://github.com/ansible-collections/community.aws/blob/main/plugins/modules/rds.py) * [`plugins/modules/rds_instance.py`](https://github.com/ansible-collections/community.aws/blob/main/plugins/modules/rds_instance.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @jillr @s-hertel @tremble @willthames @wimnat [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> Files identified in the description: * [`plugins/modules/rds_instance.py`](https://github.com/['ansible-collections/amazon.aws', 'ansible-collections/community.aws', 'ansible-collections/community.vmware']/blob/main/plugins/modules/rds_instance.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @markuman [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> @markuman @alinabuzachis I would assume this functionality should be added to `rds_instance_snapshot` ? > @markuman @alinabuzachis I would assume this functionality should be added to `rds_instance_snapshot` ? Sounds good to me. Added PR for this!
2022-05-25T04:41:39
ansible-collections/community.aws
1,177
ansible-collections__community.aws-1177
[ "1058" ]
c36f8db82ca9086f0e2f82067185c5e4b018ed5d
diff --git a/plugins/modules/ecs_service.py b/plugins/modules/ecs_service.py --- a/plugins/modules/ecs_service.py +++ b/plugins/modules/ecs_service.py @@ -113,6 +113,7 @@ type: str expression: description: A cluster query language expression to apply to the constraint. + required: false type: str placement_strategy: description: @@ -584,7 +585,6 @@ def create_service(self, service_name, cluster_name, task_definition, load_balan clientToken=client_token, role=role, deploymentConfiguration=deployment_configuration, - placementConstraints=placement_constraints, placementStrategy=placement_strategy ) if network_configuration: @@ -597,6 +597,13 @@ def create_service(self, service_name, cluster_name, task_definition, load_balan params['healthCheckGracePeriodSeconds'] = health_check_grace_period_seconds if service_registries: params['serviceRegistries'] = service_registries + + # filter placement_constraint and left only those where value is not None + # use-case: `distinctInstance` type should never contain `expression`, but None will fail `str` type validation + if placement_constraints: + params['placementConstraints'] = [{key: value for key, value in constraint.items() if value is not None} + for constraint in placement_constraints] + # desired count is not required if scheduling strategy is daemon if desired_count is not None: params['desiredCount'] = desired_count @@ -674,7 +681,7 @@ def main(): elements='dict', options=dict( type=dict(type='str'), - expression=dict(type='str') + expression=dict(required=False, type='str') ) ), placement_strategy=dict(
diff --git a/tests/integration/targets/ecs_cluster/tasks/main.yml b/tests/integration/targets/ecs_cluster/tasks/main.yml --- a/tests/integration/targets/ecs_cluster/tasks/main.yml +++ b/tests/integration/targets/ecs_cluster/tasks/main.yml @@ -215,6 +215,8 @@ desired_count: 1 deployment_configuration: "{{ ecs_service_deployment_configuration }}" placement_strategy: "{{ ecs_service_placement_strategy }}" + placement_constraints: + - type: distinctInstance health_check_grace_period_seconds: "{{ ecs_service_health_check_grace_period }}" load_balancers: - targetGroupArn: "{{ elb_target_group_instance.target_group_arn }}" @@ -223,6 +225,12 @@ role: "ecsServiceRole" register: ecs_service + - name: check that placement constraint has been applied + assert: + that: + - ecs_service.changed + - "ecs_service.service.placementConstraints[0].type == 'distinctInstance'" + - name: check that ECS service creation changed assert: that: @@ -237,6 +245,8 @@ desired_count: 1 deployment_configuration: "{{ ecs_service_deployment_configuration }}" placement_strategy: "{{ ecs_service_placement_strategy }}" + placement_constraints: + - type: distinctInstance health_check_grace_period_seconds: "{{ ecs_service_health_check_grace_period }}" load_balancers: - targetGroupArn: "{{ elb_target_group_instance.target_group_arn }}" @@ -260,6 +270,8 @@ desired_count: 1 deployment_configuration: "{{ ecs_service_deployment_configuration }}" placement_strategy: "{{ ecs_service_placement_strategy }}" + placement_constraints: + - type: distinctInstance health_check_grace_period_seconds: "{{ ecs_service_health_check_grace_period }}" load_balancers: - targetGroupArn: "{{ elb_target_group_instance.target_group_arn }}"
ecs_service cannot handle distinctInstance Placement Constraint ### Summary Most Placement Constraint options have both a `type` and an `expression`. You can see this is `ecs_service.py` `main()` ... ``` placement_constraints=dict( required=False, default=[], type='list', elements='dict', options=dict( type=dict(type='str'), expression=dict(type='str') ) ), ``` However, the `distinctInstance` Placement Constraint does not require an `expression.` The bug here is that the above code effectively mandates that `expression` is required. If it is omitted from the playbook, we end up with the value being `None` which I was able to capture by modifying the code .... ``` [{'type': 'distinctInstance', 'expression': None}] ``` The presence of `expression` here, even with the value of `None`, yields the following error: ``` botocore.exceptions.ParamValidationError: Parameter validation failed:\nInvalid type for parameter placementConstraints[0].expression, value: None, ``` I've confirmed that `boto` supports this just fine ... ``` params = dict( cluster="default", serviceName="some-service-name", taskDefinition="some-task-definition, desiredCount=0, placementConstraints=[dict(type="distinctInstance")] ) print("params:" + str(params)) ecs.create_service(**params) ``` The bug appears to be in `ecs_service.py` during the **create service** path of execution. ### Issue Type Bug Report ### Component Name ecs_service ### Ansible Version ```console (paste below) $ ansible --version ansible [core 2.12.4] config file = None configured module search path = ['/Users/wetorres/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /Users/wetorres/Library/Python/3.8/lib/python/site-packages/ansible ansible collection location = /Users/wetorres/.ansible/collections:/usr/share/ansible/collections executable location = /Users/wetorres/Library/Python/3.8/bin/ansible python version = 3.8.9 (default, Feb 18 2022, 07:45:34) [Clang 13.1.6 (clang-1316.0.21.2)] jinja version = 3.1.1 libyaml = True ``` ### Collection Versions ```console (paste below) $ ansible-galaxy collection list # /Users/wetorres/Library/Python/3.8/lib/python/site-packages/ansible_collections Collection Version ----------------------------- ------- amazon.aws 2.1.0 ansible.netcommon 2.5.1 ansible.posix 1.3.0 ansible.utils 2.5.2 ansible.windows 1.9.0 arista.eos 3.1.0 awx.awx 19.4.0 azure.azcollection 1.11.0 check_point.mgmt 2.3.0 chocolatey.chocolatey 1.2.0 cisco.aci 2.1.0 cisco.asa 2.1.0 cisco.intersight 1.0.18 cisco.ios 2.8.0 cisco.iosxr 2.8.1 cisco.ise 1.2.1 cisco.meraki 2.6.0 cisco.mso 1.3.0 cisco.nso 1.0.3 cisco.nxos 2.9.0 cisco.ucs 1.7.0 cloud.common 2.1.0 cloudscale_ch.cloud 2.2.0 community.aws 2.3.0 community.azure 1.1.0 community.ciscosmb 1.0.4 community.crypto 2.2.3 community.digitalocean 1.15.1 community.dns 2.0.8 community.docker 2.2.1 community.fortios 1.0.0 community.general 4.6.0 community.google 1.0.0 community.grafana 1.3.3 community.hashi_vault 2.3.0 community.hrobot 1.2.2 community.kubernetes 2.0.1 community.kubevirt 1.0.0 community.libvirt 1.0.2 community.mongodb 1.3.2 community.mysql 2.3.5 community.network 3.1.0 community.okd 2.1.0 community.postgresql 1.7.1 community.proxysql 1.3.1 community.rabbitmq 1.1.0 community.routeros 2.0.0 community.skydive 1.0.0 community.sops 1.2.0 community.vmware 1.17.1 community.windows 1.9.0 community.zabbix 1.5.1 containers.podman 1.9.1 cyberark.conjur 1.1.0 cyberark.pas 1.0.13 dellemc.enterprise_sonic 1.1.0 dellemc.openmanage 4.4.0 dellemc.os10 1.1.1 dellemc.os6 1.0.7 dellemc.os9 1.0.4 f5networks.f5_modules 1.15.0 fortinet.fortimanager 2.1.4 fortinet.fortios 2.1.4 frr.frr 1.0.3 gluster.gluster 1.0.2 google.cloud 1.0.2 hetzner.hcloud 1.6.0 hpe.nimble 1.1.4 ibm.qradar 1.0.3 infinidat.infinibox 1.3.3 infoblox.nios_modules 1.2.1 inspur.sm 1.3.0 junipernetworks.junos 2.9.0 kubernetes.core 2.2.3 mellanox.onyx 1.0.0 netapp.aws 21.7.0 netapp.azure 21.10.0 netapp.cloudmanager 21.15.0 netapp.elementsw 21.7.0 netapp.ontap 21.17.3 netapp.storagegrid 21.9.0 netapp.um_info 21.8.0 netapp_eseries.santricity 1.2.13 netbox.netbox 3.6.0 ngine_io.cloudstack 2.2.3 ngine_io.exoscale 1.0.0 ngine_io.vultr 1.1.0 openstack.cloud 1.7.2 openvswitch.openvswitch 2.1.0 ovirt.ovirt 1.6.6 purestorage.flasharray 1.12.1 purestorage.flashblade 1.9.0 sensu.sensu_go 1.13.0 servicenow.servicenow 1.0.6 splunk.es 1.0.2 t_systems_mms.icinga_director 1.27.1 theforeman.foreman 2.2.0 vyos.vyos 2.8.0 wti.remote 1.0.3 # /Users/wetorres/.ansible/collections/ansible_collections Collection Version ---------- ------- amazon.aws 3.1.1 ``` ### AWS SDK versions ```console (paste below) $ pip show boto boto3 botocore WARNING: Package(s) not found: boto Name: boto3 Version: 1.21.29 Summary: The AWS SDK for Python Home-page: https://github.com/boto/boto3 Author: Amazon Web Services Author-email: License: Apache License 2.0 Location: /Users/wetorres/Library/Python/3.8/lib/python/site-packages Requires: botocore, jmespath, s3transfer Required-by: --- Name: botocore Version: 1.24.29 Summary: Low-level, data-driven core of boto 3. Home-page: https://github.com/boto/botocore Author: Amazon Web Services Author-email: License: Apache License 2.0 Location: /Users/wetorres/Library/Python/3.8/lib/python/site-packages Requires: jmespath, python-dateutil, urllib3 Required-by: boto3, s3transfer ``` We do a lot of our ansible stuff from with virtual envs and docker containers. I don't happen to have `boto` installed, but don't let that be a distraction. The bug here is in `ecs_service.py`. ### Configuration ```console (paste below) $ ansible-config dump --only-changed ``` I ran this and it produced no output ### OS / Environment ``` uname -a Darwin REDACTED 21.4.0 Darwin Kernel Version 21.4.0: Fri Mar 18 00:45:05 PDT 2022; root:xnu-8020.101.4~15/RELEASE_X86_64 x86_64 ``` ### Steps to Reproduce <!--- Paste example playbooks or commands between quotes below --> ```yaml (paste below) --- - name: "ecs_service_bug" hosts: localhost tasks: - name: "ecs_service_bug" ecs_service: state: present name: "ecs_service_bug" cluster: "default" desired_count: 0 region: "us-east-1" task_definition: "any-valid-task-definition" force_new_deployment: "yes" placement_constraints: - type: distinctInstance ``` Run `ansible-playbook ./this.yml` to reproduce the error. Notes: - **If the ECS Service does not exist**, running this playbook will generate the error above. - **If the ECS Service already exists**, no error will be produced - **If the existing ECS Service** has the `distinctInstance` Placement Constraint, it will be retained. - **If the existing ECS Service** does not have the `distinctInstance` Placement Constraint, it will not be added. ### Expected Results - I expect to be able to define `distinctInstance` Placement Strategy in my Ansible playbook, regardless of the state of the ECS Service. - I expect the `distinctInstance` Placement Strategy defined in the playbok should be applied to the ECS Service in question. ### Actual Results 1. If the ECS Service doesn't exist yet, `ansible-playbook` generates an error and fails. No ECS Service is created. 2. If the ECS Service exists _with_ `distinctInstance` Placement Strategy, this Placement Strategy is retained. 3. If the ECS Service exists _without_ `distinctInstance` Placement Strategy, this Placement Strategy (which is supplied in the playbook) is _not_ applied to the ECS Service. ### Code of Conduct - [X] I agree to follow the Ansible Code of Conduct
Files identified in the description: * [`plugins/modules/ecs_service.py`](https://github.com/['ansible-collections/amazon.aws', 'ansible-collections/community.aws', 'ansible-collections/community.vmware']/blob/main/plugins/modules/ecs_service.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @Java1Guy @jillr @kaczynskid @markuman @s-hertel @tremble @zacblazic [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> @superwesman Thx for the detail reporting. I can confirm the bug. > The bug here is that the above code effectively mandates that `expression` is required. But that's not valid. The parameter is set to `required=False,`. The parameter `placement_constraints` is just path through, from [789](https://github.com/ansible-collections/community.aws/blob/c403552f8d8d2da6be0a1797d6ac85ab1cd7b22c/plugins/modules/ecs_service.py#L789) to [Line 599](https://github.com/ansible-collections/community.aws/blob/c403552f8d8d2da6be0a1797d6ac85ab1cd7b22c/plugins/modules/ecs_service.py#L599). A possible fix might be easy. All what's to do is to pop `None` values from `params['placement_constraints']` somewhere [here](https://github.com/ansible-collections/community.aws/blob/c403552f8d8d2da6be0a1797d6ac85ab1cd7b22c/plugins/modules/ecs_service.py#L583-L598) ... * plus some integration test to cover that case * plus a changelog fragment @superwesman are you willing to provide a PR to fix this issue? hello @markuman - Unfortunately, I don't think I'm in a position to provide a PR. I've discovered this bug at work and the exact corporate policies related to open source development are many, and not clear to me. I hope that my input is at least helpful for anyone who does have capacity to implement. I'm sorry I can't do more at the moment. @markuman I think I can provide a PR. I have been investigating issues with our automation and ended up having a [solution](https://github.com/ansible-collections/community.aws/compare/main...novak-as:main) which looks pretty similar to your proposal. I can confirm that this worked for me, so it looks like not much work is left > @markuman I think I can provide a PR. I have been investigating issues with our automation and ended up having a [solution](https://github.com/ansible-collections/community.aws/compare/main...novak-as:main) which looks pretty similar to your proposal. I can confirm that this worked for me, so it looks like not much work is left That would be awesome @novak-as I've test your branch and the current integration test passes. From my perspective, there are 3 steps left. 1. [rebase your branch with upstream main branch](https://docs.ansible.com/ansible/latest/dev_guide/developing_rebasing.html) 2. open PR and add a bugfixes changelog fragment 3. expand the integration test that covers the case just a few days left until we're going to release 3.3.0. But I think we can made it.
2022-05-30T09:51:44
ansible-collections/community.aws
1,178
ansible-collections__community.aws-1178
[ "1058" ]
152e34ba2b96ad069bffc23502b58c8e6b254dec
diff --git a/plugins/modules/ecs_service.py b/plugins/modules/ecs_service.py --- a/plugins/modules/ecs_service.py +++ b/plugins/modules/ecs_service.py @@ -113,6 +113,7 @@ type: str expression: description: A cluster query language expression to apply to the constraint. + required: false type: str placement_strategy: description: @@ -584,7 +585,6 @@ def create_service(self, service_name, cluster_name, task_definition, load_balan clientToken=client_token, role=role, deploymentConfiguration=deployment_configuration, - placementConstraints=placement_constraints, placementStrategy=placement_strategy ) if network_configuration: @@ -597,6 +597,13 @@ def create_service(self, service_name, cluster_name, task_definition, load_balan params['healthCheckGracePeriodSeconds'] = health_check_grace_period_seconds if service_registries: params['serviceRegistries'] = service_registries + + # filter placement_constraint and left only those where value is not None + # use-case: `distinctInstance` type should never contain `expression`, but None will fail `str` type validation + if placement_constraints: + params['placementConstraints'] = [{key: value for key, value in constraint.items() if value is not None} + for constraint in placement_constraints] + # desired count is not required if scheduling strategy is daemon if desired_count is not None: params['desiredCount'] = desired_count @@ -674,7 +681,7 @@ def main(): elements='dict', options=dict( type=dict(type='str'), - expression=dict(type='str') + expression=dict(required=False, type='str') ) ), placement_strategy=dict(
diff --git a/tests/integration/targets/ecs_cluster/tasks/main.yml b/tests/integration/targets/ecs_cluster/tasks/main.yml --- a/tests/integration/targets/ecs_cluster/tasks/main.yml +++ b/tests/integration/targets/ecs_cluster/tasks/main.yml @@ -215,6 +215,8 @@ desired_count: 1 deployment_configuration: "{{ ecs_service_deployment_configuration }}" placement_strategy: "{{ ecs_service_placement_strategy }}" + placement_constraints: + - type: distinctInstance health_check_grace_period_seconds: "{{ ecs_service_health_check_grace_period }}" load_balancers: - targetGroupArn: "{{ elb_target_group_instance.target_group_arn }}" @@ -223,6 +225,12 @@ role: "ecsServiceRole" register: ecs_service + - name: check that placement constraint has been applied + assert: + that: + - ecs_service.changed + - "ecs_service.service.placementConstraints[0].type == 'distinctInstance'" + - name: check that ECS service creation changed assert: that: @@ -237,6 +245,8 @@ desired_count: 1 deployment_configuration: "{{ ecs_service_deployment_configuration }}" placement_strategy: "{{ ecs_service_placement_strategy }}" + placement_constraints: + - type: distinctInstance health_check_grace_period_seconds: "{{ ecs_service_health_check_grace_period }}" load_balancers: - targetGroupArn: "{{ elb_target_group_instance.target_group_arn }}" @@ -260,6 +270,8 @@ desired_count: 1 deployment_configuration: "{{ ecs_service_deployment_configuration }}" placement_strategy: "{{ ecs_service_placement_strategy }}" + placement_constraints: + - type: distinctInstance health_check_grace_period_seconds: "{{ ecs_service_health_check_grace_period }}" load_balancers: - targetGroupArn: "{{ elb_target_group_instance.target_group_arn }}"
ecs_service cannot handle distinctInstance Placement Constraint ### Summary Most Placement Constraint options have both a `type` and an `expression`. You can see this is `ecs_service.py` `main()` ... ``` placement_constraints=dict( required=False, default=[], type='list', elements='dict', options=dict( type=dict(type='str'), expression=dict(type='str') ) ), ``` However, the `distinctInstance` Placement Constraint does not require an `expression.` The bug here is that the above code effectively mandates that `expression` is required. If it is omitted from the playbook, we end up with the value being `None` which I was able to capture by modifying the code .... ``` [{'type': 'distinctInstance', 'expression': None}] ``` The presence of `expression` here, even with the value of `None`, yields the following error: ``` botocore.exceptions.ParamValidationError: Parameter validation failed:\nInvalid type for parameter placementConstraints[0].expression, value: None, ``` I've confirmed that `boto` supports this just fine ... ``` params = dict( cluster="default", serviceName="some-service-name", taskDefinition="some-task-definition, desiredCount=0, placementConstraints=[dict(type="distinctInstance")] ) print("params:" + str(params)) ecs.create_service(**params) ``` The bug appears to be in `ecs_service.py` during the **create service** path of execution. ### Issue Type Bug Report ### Component Name ecs_service ### Ansible Version ```console (paste below) $ ansible --version ansible [core 2.12.4] config file = None configured module search path = ['/Users/wetorres/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /Users/wetorres/Library/Python/3.8/lib/python/site-packages/ansible ansible collection location = /Users/wetorres/.ansible/collections:/usr/share/ansible/collections executable location = /Users/wetorres/Library/Python/3.8/bin/ansible python version = 3.8.9 (default, Feb 18 2022, 07:45:34) [Clang 13.1.6 (clang-1316.0.21.2)] jinja version = 3.1.1 libyaml = True ``` ### Collection Versions ```console (paste below) $ ansible-galaxy collection list # /Users/wetorres/Library/Python/3.8/lib/python/site-packages/ansible_collections Collection Version ----------------------------- ------- amazon.aws 2.1.0 ansible.netcommon 2.5.1 ansible.posix 1.3.0 ansible.utils 2.5.2 ansible.windows 1.9.0 arista.eos 3.1.0 awx.awx 19.4.0 azure.azcollection 1.11.0 check_point.mgmt 2.3.0 chocolatey.chocolatey 1.2.0 cisco.aci 2.1.0 cisco.asa 2.1.0 cisco.intersight 1.0.18 cisco.ios 2.8.0 cisco.iosxr 2.8.1 cisco.ise 1.2.1 cisco.meraki 2.6.0 cisco.mso 1.3.0 cisco.nso 1.0.3 cisco.nxos 2.9.0 cisco.ucs 1.7.0 cloud.common 2.1.0 cloudscale_ch.cloud 2.2.0 community.aws 2.3.0 community.azure 1.1.0 community.ciscosmb 1.0.4 community.crypto 2.2.3 community.digitalocean 1.15.1 community.dns 2.0.8 community.docker 2.2.1 community.fortios 1.0.0 community.general 4.6.0 community.google 1.0.0 community.grafana 1.3.3 community.hashi_vault 2.3.0 community.hrobot 1.2.2 community.kubernetes 2.0.1 community.kubevirt 1.0.0 community.libvirt 1.0.2 community.mongodb 1.3.2 community.mysql 2.3.5 community.network 3.1.0 community.okd 2.1.0 community.postgresql 1.7.1 community.proxysql 1.3.1 community.rabbitmq 1.1.0 community.routeros 2.0.0 community.skydive 1.0.0 community.sops 1.2.0 community.vmware 1.17.1 community.windows 1.9.0 community.zabbix 1.5.1 containers.podman 1.9.1 cyberark.conjur 1.1.0 cyberark.pas 1.0.13 dellemc.enterprise_sonic 1.1.0 dellemc.openmanage 4.4.0 dellemc.os10 1.1.1 dellemc.os6 1.0.7 dellemc.os9 1.0.4 f5networks.f5_modules 1.15.0 fortinet.fortimanager 2.1.4 fortinet.fortios 2.1.4 frr.frr 1.0.3 gluster.gluster 1.0.2 google.cloud 1.0.2 hetzner.hcloud 1.6.0 hpe.nimble 1.1.4 ibm.qradar 1.0.3 infinidat.infinibox 1.3.3 infoblox.nios_modules 1.2.1 inspur.sm 1.3.0 junipernetworks.junos 2.9.0 kubernetes.core 2.2.3 mellanox.onyx 1.0.0 netapp.aws 21.7.0 netapp.azure 21.10.0 netapp.cloudmanager 21.15.0 netapp.elementsw 21.7.0 netapp.ontap 21.17.3 netapp.storagegrid 21.9.0 netapp.um_info 21.8.0 netapp_eseries.santricity 1.2.13 netbox.netbox 3.6.0 ngine_io.cloudstack 2.2.3 ngine_io.exoscale 1.0.0 ngine_io.vultr 1.1.0 openstack.cloud 1.7.2 openvswitch.openvswitch 2.1.0 ovirt.ovirt 1.6.6 purestorage.flasharray 1.12.1 purestorage.flashblade 1.9.0 sensu.sensu_go 1.13.0 servicenow.servicenow 1.0.6 splunk.es 1.0.2 t_systems_mms.icinga_director 1.27.1 theforeman.foreman 2.2.0 vyos.vyos 2.8.0 wti.remote 1.0.3 # /Users/wetorres/.ansible/collections/ansible_collections Collection Version ---------- ------- amazon.aws 3.1.1 ``` ### AWS SDK versions ```console (paste below) $ pip show boto boto3 botocore WARNING: Package(s) not found: boto Name: boto3 Version: 1.21.29 Summary: The AWS SDK for Python Home-page: https://github.com/boto/boto3 Author: Amazon Web Services Author-email: License: Apache License 2.0 Location: /Users/wetorres/Library/Python/3.8/lib/python/site-packages Requires: botocore, jmespath, s3transfer Required-by: --- Name: botocore Version: 1.24.29 Summary: Low-level, data-driven core of boto 3. Home-page: https://github.com/boto/botocore Author: Amazon Web Services Author-email: License: Apache License 2.0 Location: /Users/wetorres/Library/Python/3.8/lib/python/site-packages Requires: jmespath, python-dateutil, urllib3 Required-by: boto3, s3transfer ``` We do a lot of our ansible stuff from with virtual envs and docker containers. I don't happen to have `boto` installed, but don't let that be a distraction. The bug here is in `ecs_service.py`. ### Configuration ```console (paste below) $ ansible-config dump --only-changed ``` I ran this and it produced no output ### OS / Environment ``` uname -a Darwin REDACTED 21.4.0 Darwin Kernel Version 21.4.0: Fri Mar 18 00:45:05 PDT 2022; root:xnu-8020.101.4~15/RELEASE_X86_64 x86_64 ``` ### Steps to Reproduce <!--- Paste example playbooks or commands between quotes below --> ```yaml (paste below) --- - name: "ecs_service_bug" hosts: localhost tasks: - name: "ecs_service_bug" ecs_service: state: present name: "ecs_service_bug" cluster: "default" desired_count: 0 region: "us-east-1" task_definition: "any-valid-task-definition" force_new_deployment: "yes" placement_constraints: - type: distinctInstance ``` Run `ansible-playbook ./this.yml` to reproduce the error. Notes: - **If the ECS Service does not exist**, running this playbook will generate the error above. - **If the ECS Service already exists**, no error will be produced - **If the existing ECS Service** has the `distinctInstance` Placement Constraint, it will be retained. - **If the existing ECS Service** does not have the `distinctInstance` Placement Constraint, it will not be added. ### Expected Results - I expect to be able to define `distinctInstance` Placement Strategy in my Ansible playbook, regardless of the state of the ECS Service. - I expect the `distinctInstance` Placement Strategy defined in the playbok should be applied to the ECS Service in question. ### Actual Results 1. If the ECS Service doesn't exist yet, `ansible-playbook` generates an error and fails. No ECS Service is created. 2. If the ECS Service exists _with_ `distinctInstance` Placement Strategy, this Placement Strategy is retained. 3. If the ECS Service exists _without_ `distinctInstance` Placement Strategy, this Placement Strategy (which is supplied in the playbook) is _not_ applied to the ECS Service. ### Code of Conduct - [X] I agree to follow the Ansible Code of Conduct
Files identified in the description: * [`plugins/modules/ecs_service.py`](https://github.com/['ansible-collections/amazon.aws', 'ansible-collections/community.aws', 'ansible-collections/community.vmware']/blob/main/plugins/modules/ecs_service.py) If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command. [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: components_banner ---> cc @Java1Guy @jillr @kaczynskid @markuman @s-hertel @tremble @zacblazic [click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md) <!--- boilerplate: notify ---> @superwesman Thx for the detail reporting. I can confirm the bug. > The bug here is that the above code effectively mandates that `expression` is required. But that's not valid. The parameter is set to `required=False,`. The parameter `placement_constraints` is just path through, from [789](https://github.com/ansible-collections/community.aws/blob/c403552f8d8d2da6be0a1797d6ac85ab1cd7b22c/plugins/modules/ecs_service.py#L789) to [Line 599](https://github.com/ansible-collections/community.aws/blob/c403552f8d8d2da6be0a1797d6ac85ab1cd7b22c/plugins/modules/ecs_service.py#L599). A possible fix might be easy. All what's to do is to pop `None` values from `params['placement_constraints']` somewhere [here](https://github.com/ansible-collections/community.aws/blob/c403552f8d8d2da6be0a1797d6ac85ab1cd7b22c/plugins/modules/ecs_service.py#L583-L598) ... * plus some integration test to cover that case * plus a changelog fragment @superwesman are you willing to provide a PR to fix this issue? hello @markuman - Unfortunately, I don't think I'm in a position to provide a PR. I've discovered this bug at work and the exact corporate policies related to open source development are many, and not clear to me. I hope that my input is at least helpful for anyone who does have capacity to implement. I'm sorry I can't do more at the moment. @markuman I think I can provide a PR. I have been investigating issues with our automation and ended up having a [solution](https://github.com/ansible-collections/community.aws/compare/main...novak-as:main) which looks pretty similar to your proposal. I can confirm that this worked for me, so it looks like not much work is left > @markuman I think I can provide a PR. I have been investigating issues with our automation and ended up having a [solution](https://github.com/ansible-collections/community.aws/compare/main...novak-as:main) which looks pretty similar to your proposal. I can confirm that this worked for me, so it looks like not much work is left That would be awesome @novak-as I've test your branch and the current integration test passes. From my perspective, there are 3 steps left. 1. [rebase your branch with upstream main branch](https://docs.ansible.com/ansible/latest/dev_guide/developing_rebasing.html) 2. open PR and add a bugfixes changelog fragment 3. expand the integration test that covers the case just a few days left until we're going to release 3.3.0. But I think we can made it.
2022-05-30T09:51:54