Debian Codegraph @

ansible_collections/amazon/aws/docs/docsite/rst/dev_guidelines.rst

raw
1 .. _ansible_collections.amazon.aws.docsite.dev_guide_intro:
2
3 ****************************************************
4 Guidelines for Ansible Amazon AWS module development
5 ****************************************************
6
7 The Ansible AWS collection (on `Galaxy <https://galaxy.ansible.com/community/aws>`_, source code `repository <https://github.com/ansible-collections/community.aws>`_) is maintained by the Ansible AWS Working Group. For further information see the `AWS working group community page <https://github.com/ansible/community/wiki/aws>`_. If you are planning to contribute AWS modules to Ansible then getting in touch with the working group is a good way to start, especially because a similar module may already be under development.
8
9 .. contents::
10 :local:
11
12 .. _ansible_collections.amazon.aws.docsite.dev_python:
13
14 Requirements
15 ============
16
17 Python Compatibility
18 --------------------
19
20 AWS content in Ansible 2.9 and 1.x collection releases supported Python 2.7 and newer.
21
22 Starting with the 2.0 releases of both collections, Python 2.7 support will be ended in accordance with AWS' `end of Python 2.7 support <https://aws.amazon.com/blogs/developer/announcing-end-of-support-for-python-2-7-in-aws-sdk-for-python-and-aws-cli-v1/>`_. Contributions to both collections that target the 2.0 or later collection releases can be written to support Python 3.6+ syntax.
23
24 SDK Version Support
25 -------------------
26
27 Starting with the 2.0 releases of both collections, it is generally the policy to support the versions of botocore and boto3 that were released 12 months prior to the most recent major collection release, following semantic versioning (for example, 2.0.0, 3.0.0).
28
29 Features and functionality that require newer versions of the SDK can be contributed provided they are noted in the module documentation:
30
31 .. code-block:: yaml
32
33 DOCUMENTATION = '''
34 ---
35 module: ec2_vol
36 options:
37 throughput:
38 description:
39 - Volume throughput in MB/s.
40 - This parameter is only valid for gp3 volumes.
41 - Valid range is from 125 to 2000.
42 - Requires at least botocore version 1.19.27.
43 type: int
44 version_added: 1.4.0
45
46 And handled using the ``botocore_at_least`` helper method:
47
48 .. code-block:: python
49
50 if module.params.get('throughput'):
51 if not module.botocore_at_least("1.19.27"):
52 module.fail_json(msg="botocore >= 1.19.27 is required to set the throughput for a volume")
53
54 Starting with the 4.0 releases of both collections, all support for the original boto SDK has been dropped. AWS Modules must be written using the botocore and boto3 SDKs.
55
56 .. _ansible_collections.amazon.aws.docsite.dev_module_maint:
57
58 Maintaining existing modules
59 ============================
60
61 Changelogs
62 ----------
63
64 A changelog fragment must be added to any PR that changes functionality or fixes
65 a bug. More information about changelog fragments can be found in the
66 `Making your PR merge-worthy section of the Ansible Development Cycle documentation<community_changelogs>`
67
68 Breaking Changes
69 ----------------
70
71 Changes that are likely to break existing playbooks using the AWS collections should be
72 avoided, should only be made in a major release, and where practical should be
73 preceeded by a deprecation cycle of at least 1 full major release. Deprecations
74 may be backported to the stable branches.
75
76 For example:
77 - A deprecation added in release 3.0.0 may be removed in release 4.0.0.
78 - A deprecation added in release 1.2.0 may be removed in release 3.0.0.
79
80 Breaking changes include:
81 - Removing a parameter.
82 - Making a parameter ``required``.
83 - Updating the default value of a parameter.
84 - Changing or removing an existing return value.
85
86 Adding new features
87 -------------------
88
89 Try to keep backward compatibility with versions of boto3/botocore that are at least a year old.
90 This means that if you want to implement functionality that uses a new feature of boto3/botocore,
91 it should only fail if that feature is explicitly used, with a message stating the missing feature
92 and minimum required version of botocore. (Feature support is usually defined in botocore and then
93 used by boto3)
94
95 .. code-block:: python
96
97 module = AnsibleAWSModule(
98 argument_spec=argument_spec,
99 ...
100 )
101
102 if module.params.get('scope') == 'managed':
103 module.require_botocore_at_least('1.23.23', reason='to list managed rules')
104
105 .. _ansible_collections.amazon.aws.docsite.dev_backports:
106
107 Release policy and backporting merged PRs
108 -----------------------------------------
109
110 All amazon.aws and community.aws PRs must be merged to the ``main`` branch first. After a PR has
111 been accepted and merged to the ``main`` branch they can be backported to the stable branches.
112
113 The ``main`` branch is a staging location for the next major version (X+1) of the collections and
114 may include breaking changes.
115
116 General backport policy:
117
118 - New features, deprecations and minor changes can be backported to the latest stable release.
119 - Bugfixes can be backported to the 2 latest stable releases.
120 - Security fixes should be backported to at least the 2 latest stable releases.
121
122 Where necessary, additional CI related changes may be introduced to older stable branches to
123 ensure CI continues to function.
124
125 The simplest mechanism for backporting PRs is by adding the ``backport-Y`` label to a PR. Once the
126 PR has been merged the patchback bot will attempt to automatically create a backport PR.
127
128 .. _ansible_collections.amazon.aws.docsite.dev_module_create:
129
130 Creating new AWS modules
131 ========================
132
133 When writing a new module it is important to think about the scope of the module. In general, try
134 to do one thing and do it well.
135
136 Where the Amazon APIs provide a distinction between dependent resources, such as S3 buckets and S3
137 objects, this is often a good divider between modules. Additionally, resources which have a
138 many-to-many relationship with another resource, such as IAM managed policies and IAM roles, are
139 often best managed by two separate modules.
140
141 While it's possible to write an ``s3`` module which manages all things related to S3, thoroughly
142 testing and maintaining such a module is difficult. Similarly, while it would be possible to
143 write a module that manages the base EC2 security group resource, and a second module to manage the
144 rules on the security group, this would be contrary to what users of the module might anticipate.
145
146 There is no hard and fast right answer, but it's important to think about it, and Amazon have often
147 done this work for you when designing their APIs.
148
149 Naming your module
150 ------------------
151
152 Module names should include the name of the resource being managed and be prefixed with the AWS API
153 that the module is based on. Where examples of a prefix don't already exist a good rule of thumb is
154 to use whatever client name you use with boto3 as a starting point.
155
156 Unless something is a well known abbreviation of a major component of AWS (for example, VPC or ELB)
157 avoid further abbreviating names and don't create new abbreviations independently.
158
159 Where an AWS API primarily manages a single resource, the module managing this resource can be
160 named as just the name of the API. However, consider using ``instance`` or ``cluster`` for clarity
161 if Amazon refers to them using these names.
162
163 Examples:
164
165 - ``ec2_instance``
166 - ``s3_object`` (previously named ``aws_s3``, but is primarily for manipulating S3 objects)
167 - ``elb_classic_lb`` (previously ``ec2_elb_lb``, but is part of the ELB API, not EC2)
168 - ``networkfirewall_rule_group``
169 - ``networkfirewall`` (while this could be called ``networkfirewall_firewall`` the second firewall is redundant and the API is focused around creating these firewall resources)
170
171 Note: Prior to the collections being split from Ansible Core, it was common to use ``aws_`` as a
172 prefix to disambiguate services with a generic name, such as ``aws_secret``. This is no longer
173 necessary, and the ``aws_`` prefix is reserved for services with a very broad effect where
174 referencing the AWS API might cause confusion. For example, ``aws_region_info``, which
175 connects to EC2 but provides global information about the regions enabled in an account for all
176 services.
177
178 Use boto3 and AnsibleAWSModule
179 -------------------------------
180
181 All new AWS modules must use boto3/botocore and ``AnsibleAWSModule``.
182
183 ``AnsibleAWSModule`` greatly simplifies exception handling and library
184 management, reducing the amount of boilerplate code. If you cannot
185 use ``AnsibleAWSModule`` as a base, you must document the reason and request an exception to this rule.
186
187 Importing botocore and boto3
188 ----------------------------
189
190 The ``ansible_collections.amazon.aws.plugins.module_utils.botocore`` module
191 automatically imports boto3 and botocore. If boto3 is missing from the system then the variable
192 ``HAS_BOTO3`` will be set to ``False``. Normally, this means that modules don't need to import
193 boto3 directly. There is no need to check ``HAS_BOTO3`` when using AnsibleAWSModule
194 as the module does that check:
195
196 .. code-block:: python
197
198 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
199 try:
200 import botocore
201 except ImportError:
202 pass # handled by AnsibleAWSModule
203
204 or:
205
206 .. code-block:: python
207
208 from ansible.module_utils.basic import AnsibleModule
209 from ansible.module_utils.basic import missing_required_lib
210 from ansible_collections.amazon.aws.plugins.module_utils.botocore import HAS_BOTO3
211 try:
212 import botocore
213 except ImportError:
214 pass # handled by imported HAS_BOTO3
215
216 def main():
217 if not HAS_BOTO3:
218 module.fail_json(missing_required_lib('botocore and boto3'))
219
220 Supporting Module Defaults
221 --------------------------
222
223 The existing AWS modules support using :ref:`module_defaults <module_defaults>` for common
224 authentication parameters. To do the same for your new module, add an entry for it in
225 ``meta/runtime.yml``. These entries take the form of:
226
227 .. code-block:: yaml
228
229 action_groups:
230 aws:
231 ...
232 example_module
233
234 Module behavior
235 ---------------
236
237 To reduce the chance of breaking changes occurring when new features are added,
238 the module should avoid modifying the resource attribute when a parameter is
239 not explicitly set in a task.
240
241 By convention, when a parameter is explicitly set in a task, the module should
242 set the resource attribute to match what was set in the task. In some cases,
243 such as tags or associations, it can be helpful to add an additional parameter
244 which can be set to change the behavior from replacive to additive. However, the
245 default behavior should still be replacive rather than additive.
246
247 See the `Dealing with tags<ansible_collections.amazon.aws.docsite.dev_tags>`
248 section for an example with ``tags`` and ``purge_tags``.
249
250 .. _ansible_collections.amazon.aws.docsite.dev_module_connection:
251
252 Connecting to AWS
253 =================
254
255 AnsibleAWSModule provides the ``resource`` and ``client`` helper methods for obtaining boto3 connections.
256 These handle some of the more esoteric connection options, such as security tokens and boto profiles.
257
258 If using the basic AnsibleModule then you should use ``get_aws_connection_info`` and then ``boto3_conn``
259 to connect to AWS as these handle the same range of connection options.
260
261 These helpers also check for missing profiles or a region not set when it needs to be, so you don't have to.
262
263 An example of connecting to EC2 is shown below. Note that unlike boto there is no ``NoAuthHandlerFound``
264 exception handling like in boto. Instead, an ``AuthFailure`` exception will be thrown when you use the
265 connection. To ensure that authorization, parameter validation and permissions errors are all caught,
266 you should catch ``ClientError`` and ``BotoCoreError`` exceptions with every boto3 connection call.
267 See exception handling:
268
269 .. code-block:: python
270
271 module.client('ec2')
272
273 or for the higher level EC2 resource:
274
275 .. code-block:: python
276
277 module.resource('ec2')
278
279
280 An example of the older style connection used for modules based on AnsibleModule rather than AnsibleAWSModule:
281
282 .. code-block:: python
283
284 region, ec2_url, aws_connect_params = get_aws_connection_info(module, boto3=True)
285 connection = boto3_conn(module, conn_type='client', resource='ec2', region=region, endpoint=ec2_url, **aws_connect_params)
286
287 .. code-block:: python
288
289 region, ec2_url, aws_connect_params = get_aws_connection_info(module, boto3=True)
290 connection = boto3_conn(module, conn_type='client', resource='ec2', region=region, endpoint=ec2_url, **aws_connect_params)
291
292
293 Common Documentation Fragments for Connection Parameters
294 --------------------------------------------------------
295
296 There are four :ref:`common documentation fragments <module_docs_fragments>`
297 that should be included into almost all AWS modules:
298
299 * ``boto3`` - contains the minimum requirements for the collection
300 * ``common.modules`` - contains the common boto3 connection parameters
301 * ``region.modules`` - contains the common region parameter required for many AWS APIs
302 * ``tags`` - contains the common tagging parameters
303
304 These fragments should be used rather than re-documenting these properties to ensure consistency
305 and that the more esoteric connection options are documented. For example:
306
307 .. code-block:: python
308
309 DOCUMENTATION = '''
310 module: my_module
311 # some lines omitted here
312 extends_documentation_fragment:
313 - amazon.aws.boto3
314 - amazon.aws.common.modules
315 - amazon.aws.region.modules
316 '''
317
318 Other plugin types have a slightly different document fragment format, and should use
319 the following fragments:
320
321 * ``boto3`` - contains the minimum requirements for the collection
322 * ``common.plugins`` - contains the common boto3 connection parameters
323 * ``region.plugins`` - contains the common region parameter required for many AWS APIs
324 * ``tags`` - contains the common tagging parameters
325
326 These fragments should be used rather than re-documenting these properties to ensure consistency
327 and that the more esoteric connection options are documented. For example:
328
329 .. code-block:: python
330
331 DOCUMENTATION = '''
332 module: my_plugin
333 # some lines omitted here
334 extends_documentation_fragment:
335 - amazon.aws.boto3
336 - amazon.aws.common.plugins
337 - amazon.aws.region.plugins
338 '''
339
340 .. _ansible_collections.amazon.aws.docsite.dev_exceptions:
341
342 Handling exceptions
343 ===================
344
345 You should wrap any boto3 or botocore call in a try block. If an exception is thrown, then there
346 are a number of possibilities for handling it.
347
348 * Catch the general ``ClientError`` or look for a specific error code with
349 ``is_boto3_error_code``.
350 * Use ``aws_module.fail_json_aws()`` to report the module failure in a standard way.
351 * Retry using AWSRetry.
352 * Use ``fail_json()`` to report the failure without using ``AnsibleAWSModule``.
353 * Do something custom in the case where you know how to handle the exception.
354
355 For more information on botocore exception handling see the `botocore error documentation <https://botocore.readthedocs.io/en/latest/client_upgrades.html#error-handling>`_.
356
357 Using is_boto3_error_code
358 -------------------------
359
360 To use ``ansible_collections.amazon.aws.plugins.module_utils.botocore.is_boto3_error_code`` to catch a single
361 AWS error code, call it in place of ``ClientError`` in your except clauses. In
362 this example, *only* the ``InvalidGroup.NotFound`` error code will be caught here,
363 and any other error will be raised for handling elsewhere in the program.
364
365 .. code-block:: python
366
367 try:
368 info = connection.describe_security_groups(**kwargs)
369 except is_boto3_error_code('InvalidGroup.NotFound'):
370 pass
371 do_something(info) # do something with the info that was successfully returned
372
373 Using fail_json_aws()
374 ---------------------
375
376 In the AnsibleAWSModule there is a special method, ``module.fail_json_aws()`` for nice reporting of
377 exceptions. Call this on your exception and it will report the error together with a traceback for
378 use in Ansible verbose mode.
379
380 You should use the AnsibleAWSModule for all new modules, unless not possible.
381
382 .. code-block:: python
383
384 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
385
386 # Set up module parameters
387 # module params code here
388
389 # Connect to AWS
390 # connection code here
391
392 # Make a call to AWS
393 name = module.params.get('name')
394 try:
395 result = connection.describe_frooble(FroobleName=name)
396 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
397 module.fail_json_aws(e, msg="Couldn't obtain frooble %s" % name)
398
399 Note that it should normally be acceptable to catch all normal exceptions here, however if you
400 expect anything other than botocore exceptions you should test everything works as expected.
401
402 If you need to perform an action based on the error boto3 returned, use the error code and the
403 ``is_boto3_error_code()`` helper.
404
405 .. code-block:: python
406
407 # Make a call to AWS
408 name = module.params.get('name')
409 try:
410 result = connection.describe_frooble(FroobleName=name)
411 except is_boto3_error_code('FroobleNotFound'):
412 workaround_failure() # This is an error that we can work around
413 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: # pylint: disable=duplicate-except
414 module.fail_json_aws(e, msg="Couldn't obtain frooble %s" % name)
415
416 using fail_json() and avoiding AnsibleAWSModule
417 ---------------------------------------------------------------------------------------
418
419 Boto3 provides lots of useful information when an exception is thrown so pass this to the user
420 along with the message.
421
422 .. code-block:: python
423
424 from ansible_collections.amazon.aws.plugins.module_utils.botocore import HAS_BOTO3
425 try:
426 import botocore
427 except ImportError:
428 pass # caught by imported HAS_BOTO3
429
430 # Connect to AWS
431 # connection code here
432
433 # Make a call to AWS
434 name = module.params.get('name')
435 try:
436 result = connection.describe_frooble(FroobleName=name)
437 except botocore.exceptions.ClientError as e:
438 module.fail_json(msg="Couldn't obtain frooble %s: %s" % (name, str(e)),
439 exception=traceback.format_exc(),
440 **camel_dict_to_snake_dict(e.response))
441
442 Note: we use ``str(e)`` rather than ``e.message`` as the latter doesn't
443 work with python3
444
445 If you need to perform an action based on the error boto3 returned, use the error code.
446
447 .. code-block:: python
448
449 # Make a call to AWS
450 name = module.params.get('name')
451 try:
452 result = connection.describe_frooble(FroobleName=name)
453 except botocore.exceptions.ClientError as e:
454 if e.response['Error']['Code'] == 'FroobleNotFound':
455 workaround_failure() # This is an error that we can work around
456 else:
457 module.fail_json(msg="Couldn't obtain frooble %s: %s" % (name, str(e)),
458 exception=traceback.format_exc(),
459 **camel_dict_to_snake_dict(e.response))
460 except botocore.exceptions.BotoCoreError as e:
461 module.fail_json_aws(e, msg="Couldn't obtain frooble %s" % name)
462
463 .. _ansible_collections.amazon.aws.docsite.dev_ratelimits:
464
465 API throttling (rate limiting) and pagination
466 =============================================
467
468 For methods that return a lot of results, boto3 often provides
469 `paginators <https://boto3.readthedocs.io/en/latest/guide/paginators.html>`_. If the method
470 you're calling has ``NextToken`` or ``Marker`` parameters, you should probably
471 check whether a paginator exists (the top of each boto3 service reference page has a link
472 to Paginators, if the service has any). To use paginators, obtain a paginator object,
473 call ``paginator.paginate`` with the appropriate arguments and then call ``build_full_result``.
474
475 Any time that you are calling the AWS API a lot, you may experience API throttling,
476 and there is an ``AWSRetry`` decorator that can be used to ensure backoff. Because
477 exception handling could interfere with the retry working properly (as AWSRetry needs to
478 catch throttling exceptions to work correctly), you'd need to provide a backoff function
479 and then put exception handling around the backoff function.
480
481 You can use ``exponential_backoff`` or ``jittered_backoff`` strategies - see
482 the cloud ``module_utils`` ()/lib/ansible/module_utils/cloud.py)
483 and `AWS Architecture blog <https://www.awsarchitectureblog.com/2015/03/backoff.html>`_ for more details.
484
485 The combination of these two approaches is then:
486
487 .. code-block:: python
488
489 @AWSRetry.jittered_backoff(retries=5, delay=5)
490 def describe_some_resource_with_backoff(client, **kwargs):
491 paginator = client.get_paginator('describe_some_resource')
492 return paginator.paginate(**kwargs).build_full_result()['SomeResource']
493
494 def describe_some_resource(client, module):
495 filters = ansible_dict_to_boto3_filter_list(module.params['filters'])
496 try:
497 return describe_some_resource_with_backoff(client, Filters=filters)
498 except botocore.exceptions.ClientError as e:
499 module.fail_json_aws(e, msg="Could not describe some resource")
500
501
502 Prior to Ansible 2.10 if the underlying ``describe_some_resources`` API call threw
503 a ``ResourceNotFound`` exception, ``AWSRetry`` would take this as a cue to retry until
504 it is not thrown (this is so that when creating a resource, we can just retry until it
505 exists). This default was changed and it is now necessary to explicitly request
506 this behaviour. This can be done by using the ``catch_extra_error_codes``
507 argument on the decorator.
508
509 .. code-block:: python
510
511 @AWSRetry.jittered_backoff(retries=5, delay=5, catch_extra_error_codes=['ResourceNotFound'])
512 def describe_some_resource_retry_missing(client, **kwargs):
513 return client.describe_some_resource(ResourceName=kwargs['name'])['Resources']
514
515 def describe_some_resource(client, module):
516 name = module.params.get['name']
517 try:
518 return describe_some_resource_with_backoff(client, name=name)
519 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
520 module.fail_json_aws(e, msg="Could not describe resource %s" % name)
521
522
523 To make use of AWSRetry easier, it can now be wrapped around a client returned
524 by ``AnsibleAWSModule``. any call from a client. To add retries to a client,
525 create a client:
526
527 .. code-block:: python
528
529 module.client('ec2', retry_decorator=AWSRetry.jittered_backoff(retries=10))
530
531 Any calls from that client can be made to use the decorator passed at call-time
532 using the ``aws_retry`` argument. By default, no retries are used.
533
534 .. code-block:: python
535
536 ec2 = module.client('ec2', retry_decorator=AWSRetry.jittered_backoff(retries=10))
537 ec2.describe_instances(InstanceIds=['i-123456789'], aws_retry=True)
538
539 # equivalent with normal AWSRetry
540 @AWSRetry.jittered_backoff(retries=10)
541 def describe_instances(client, **kwargs):
542 return ec2.describe_instances(**kwargs)
543
544 describe_instances(module.client('ec2'), InstanceIds=['i-123456789'])
545
546 The call will be retried the specified number of times, so the calling functions
547 don't need to be wrapped in the backoff decorator.
548
549 You can also use customization for ``retries``, ``delay`` and ``max_delay`` parameters used by
550 ``AWSRetry.jittered_backoff`` API using module params. You can take a look at
551 the ``cloudformation <cloudformation_module>`` module for example.
552
553 To make all Amazon modules uniform, prefix the module param with ``backoff_``, so ``retries`` becomes ``backoff_retries``
554 and likewise with ``backoff_delay`` and ``backoff_max_delay``.
555
556 .. _ansible_collections.amazon.aws.docsite.dev_return:
557
558 Returning Values
559 ================
560
561 When you make a call using boto3, you will probably get back some useful information that you
562 should return in the module. As well as information related to the call itself, you will also have
563 some response metadata. It is OK to return this to the user as well as they may find it useful.
564
565 Boto3 returns most keys in CamelCase. Ansible adopts python standards for naming variables and usage.
566 There is a useful helper function called ``camel_dict_to_snake_dict`` that allows for an easy conversion
567 of the boto3 response to snake_case. It resides in ``module_utils/common/dict_transformations``.
568
569 You should use this helper function and avoid changing the names of values returned by Boto3.
570 E.g. if boto3 returns a value called 'SecretAccessKey' do not change it to 'AccessKey'.
571
572 There is an optional parameter, ``ignore_list``, which is used to avoid converting a sub-tree
573 of a dict. This is particularly useful for tags, where keys are case-sensitive.
574
575 .. code-block:: python
576
577 # Make a call to AWS
578 resource = connection.aws_call()
579
580 # Convert resource response to snake_case
581 snaked_resource = camel_dict_to_snake_dict(resource, ignore_list=['Tags'])
582
583 # Return the resource details to the user without modifying tags
584 module.exit_json(changed=True, some_resource=snaked_resource)
585
586 Note: The returned key representing the details of the specific resource (``some_resource`` above)
587 should be a sensible approximation of the resource name. For example, ``volume`` for ``ec2_vol``,
588 ``volumes`` for ``ec2_vol_info``.
589
590 Tags
591 ----
592
593 Tags should be returned as a dictionary of key: value pairs, with each key being the tag's
594 key and value being the tag's value. It should be noted, however, that boto3 often returns tags
595 as a list of dictionaries.
596
597 There is a helper function in module_utils/ec2.py called ``boto3_tag_list_to_ansible_dict``
598 (discussed in detail below in the "Helper Functions" section) that allows for an easy conversion
599 from boto3's returned tag list to the desired dictionary of tags to be returned by the module.
600
601 Below is a full example of getting the result of an AWS call and returning the expected values:
602
603 .. code-block:: python
604
605 # Make a call to AWS
606 result = connection.aws_call()
607
608 # Make result snake_case without modifying tags
609 snaked_result = camel_dict_to_snake_dict(result, ignore_list=['Tags'])
610
611 # Convert boto3 list of dict tags to just a dict of tags
612 snaked_result['tags'] = boto3_tag_list_to_ansible_dict(result.get('tags', []))
613
614 # Return the result to the user
615 module.exit_json(changed=True, **snaked_result)
616
617 Info modules
618 ------------
619
620 Info modules that can return information on multiple resources should return a list of
621 dictionaries, with each dictionary containing information about that particular resource
622 (i.e. ``security_groups`` in ``ec2_group_info``).
623
624 In cases where the _info module only returns information on a singular resource
625 (i.e. ``ec2_tag_info``), a singular dictionary should be returned as opposed to a list
626 of dictionaries.
627
628 In cases where the _info module returns no instances, an empty list '[]' should be returned.
629
630 Keys in the returned dictionaries should follow the guidelines above and use snake_case.
631 If a return value can be used as a parameter for its corresponding main module, the key should
632 match either the parameter name itself, or an alias of that parameter.
633
634 The following is an example of improper usage of a sample info module with its respective main module:
635
636 .. code-block:: yaml
637
638 "security_groups": {
639 {
640 "description": "Created by ansible integration tests",
641 "group_id": "sg-050dba5c3520cba71",
642 "group_name": "ansible-test-87988625-unknown5c5f67f3ad09-icmp-1",
643 "ip_permissions": [],
644 "ip_permissions_egress": [],
645 "owner_id": "721066863947",
646 "tags": [
647 {
648 "Key": "Tag_One"
649 "Value": "Tag_One_Value"
650 },
651 ],
652 "vpc_id": "vpc-0cbc2380a326b8a0d"
653 }
654 }
655
656 The sample output above shows a few mistakes in the sample security group info module:
657 * ``security_groups`` is a dict of dict, not a list of dicts.
658 * ``tags`` appears to be directly returned from boto3, since they're a list of dicts.
659
660 The following is what the sample output would look like, with the mistakes corrected.
661
662 .. code-block:: yaml
663
664 "security_groups": [
665 {
666 "description": "Created by ansible integration tests",
667 "group_id": "sg-050dba5c3520cba71",
668 "group_name": "ansible-test-87988625-unknown5c5f67f3ad09-icmp-1",
669 "ip_permissions": [],
670 "ip_permissions_egress": [],
671 "owner_id": "721066863947",
672 "tags": {
673 "Tag_One": "Tag_One_Value",
674 },
675 "vpc_id": "vpc-0cbc2380a326b8a0d"
676 }
677 ]
678
679 Deprecating return values
680 -------------------------
681
682 If changes need to be made to current return values, the new/"correct" keys should be
683 returned **in addition to** the existing keys to preserve compability with existing
684 playbooks. A deprecation should be added to the return values being replaced, initially
685 placed at least 2 years out, on the 1st of a month.
686
687 For example:
688
689 .. code-block:: python
690
691 # Deprecate old `iam_user` return key to be replaced by `user` introduced on 2022-04-10
692 module.deprecate("The 'iam_user' return key is deprecated and will be replaced by 'user'. Both values are returned for now.",
693 date='2024-05-01', collection_name='community.aws')
694
695 .. _ansible_collections.amazon.aws.docsite.dev_policies:
696
697 Dealing with IAM JSON policy
698 ============================
699
700 If your module accepts IAM JSON policies then set the type to 'json' in the module spec. For
701 example:
702
703 .. code-block:: python
704
705 argument_spec.update(
706 dict(
707 policy=dict(required=False, default=None, type='json'),
708 )
709 )
710
711 Note that AWS is unlikely to return the policy in the same order that is was submitted. Therefore,
712 use the ``compare_policies`` helper function which handles this variance.
713
714 ``compare_policies`` takes two dictionaries, recursively sorts and makes them hashable for comparison
715 and returns True if they are different.
716
717 .. code-block:: python
718
719 from ansible_collections.amazon.aws.plugins.module_utils.iam import compare_policies
720
721 import json
722
723 # some lines skipped here
724
725 # Get the policy from AWS
726 current_policy = json.loads(aws_object.get_policy())
727 user_policy = json.loads(module.params.get('policy'))
728
729 # Compare the user submitted policy to the current policy ignoring order
730 if compare_policies(user_policy, current_policy):
731 # Update the policy
732 aws_object.set_policy(user_policy)
733 else:
734 # Nothing to do
735 pass
736
737 .. _ansible_collections.amazon.aws.docsite.dev_tags:
738
739 Dealing with tags
740 =================
741
742 AWS has a concept of resource tags. Usually the boto3 API has separate calls
743 for tagging and untagging a resource. For example, the EC2 API has
744 ``create_tags`` and ``delete_tags`` calls.
745
746 When adding tagging support, Ansible AWS modules should add a ``tags`` parameter
747 that defaults to ``None`` and a ``purge_tags`` parameter that defaults to
748 ``True``.
749
750
751 .. code-block:: python
752
753 argument_spec.update(
754 dict(
755 tags=dict(type='dict', required=False, default=None),
756 purge_tags=dict(type='bool', required=False, default=True),
757 )
758 )
759
760 When the ``purge_tags`` parameter is set to ``True`` **and** the ``tags``
761 parameter is explicitly set in the task, then any tags not explicitly set in
762 ``tags`` should be removed.
763
764 If the ``tags`` parameter is not set then tags should not be modified, even if
765 ``purge_tags`` is set to ``True``. This means that removing all tags requires
766 ``tags`` be explicitly set to an empty dictionary ``{}`` in the Ansible task.
767
768
769 There is a helper function ``compare_aws_tags`` to ease dealing with tags. It
770 compares two dictionaries, the current tags and the desired tags, and returns
771 the tags to set and the tags to delete. See the Helper function section below
772 for more detail.
773
774 There is also a documentation fragment ``amazon.aws.tags`` which should be
775 included when adding tagging support.
776
777 .. _ansible_collections.amazon.aws.docsite.dev_helpers:
778
779 Helper functions
780 ================
781
782 Along with the connection functions in Ansible ec2.py module_utils, there are some other useful
783 functions detailed below.
784
785 camel_dict_to_snake_dict
786 ------------------------
787
788 boto3 returns results in a dict. The keys of the dict are in CamelCase format. In keeping with
789 Ansible format, this function will convert the keys to snake_case.
790
791 ``camel_dict_to_snake_dict`` takes an optional parameter called ``ignore_list`` which is a list of
792 keys not to convert (this is usually useful for the ``tags`` dict, whose child keys should remain with
793 case preserved)
794
795 Another optional parameter is ``reversible``. By default, ``HTTPEndpoint`` is converted to ``http_endpoint``,
796 which would then be converted by ``snake_dict_to_camel_dict`` to ``HttpEndpoint``.
797 Passing ``reversible=True`` converts HTTPEndpoint to ``h_t_t_p_endpoint`` which converts back to ``HTTPEndpoint``.
798
799 snake_dict_to_camel_dict
800 ------------------------
801
802 ``snake_dict_to_camel_dict`` converts snake cased keys to camel case. By default, because it was
803 first introduced for ECS purposes, this converts to dromedaryCase. An optional
804 parameter called ``capitalize_first``, which defaults to ``False``, can be used to convert to CamelCase.
805
806 ansible_dict_to_boto3_filter_list
807 ---------------------------------
808
809 Converts a an Ansible list of filters to a boto3 friendly list of dicts. This is useful for any
810 boto3 ``_facts`` modules.
811
812 boto_exception
813 --------------
814
815 Pass an exception returned from boto or boto3, and this function will consistently get the message from the exception.
816
817 Deprecated: use ``AnsibleAWSModule``'s ``fail_json_aws`` instead.
818
819
820 boto3_tag_list_to_ansible_dict
821 ------------------------------
822
823 Converts a boto3 tag list to an Ansible dict. Boto3 returns tags as a list of dicts containing keys
824 called 'Key' and 'Value' by default. This key names can be overridden when calling the function.
825 For example, if you have already camel_cased your list of tags you may want to pass lowercase key
826 names instead, in other words, 'key' and 'value'.
827
828 This function converts the list in to a single dict where the dict key is the tag key and the dict
829 value is the tag value.
830
831 ansible_dict_to_boto3_tag_list
832 ------------------------------
833
834 Opposite of above. Converts an Ansible dict to a boto3 tag list of dicts. You can again override
835 the key names used if 'Key' and 'Value' is not suitable.
836
837 get_ec2_security_group_ids_from_names
838 -------------------------------------
839
840 Pass this function a list of security group names or combination of security group names and IDs
841 and this function will return a list of IDs. You should also pass the VPC ID if known because
842 security group names are not necessarily unique across VPCs.
843
844 compare_policies
845 ----------------
846
847 Pass two dicts of policies to check if there are any meaningful differences and returns true
848 if there are. This recursively sorts the dicts and makes them hashable before comparison.
849
850 This method should be used any time policies are being compared so that a change in order
851 doesn't result in unnecessary changes.
852
853 compare_aws_tags
854 ----------------
855
856 Pass two dicts of tags and an optional purge parameter and this function will return a dict
857 containing key pairs you need to modify and a list of tag key names that you need to remove. Purge
858 is True by default. If purge is False then any existing tags will not be modified.
859
860 This function is useful when using boto3 ``add_tags`` and ``remove_tags`` functions. Be sure to use the
861 other helper function ``boto3_tag_list_to_ansible_dict`` to get an appropriate tag dict before
862 calling this function. Since the AWS APIs are not uniform (for example, EC2 is different from Lambda) this will work
863 without modification for some (Lambda) and others may need modification before using these values
864 (such as EC2, with requires the tags to unset to be in the form ``[{'Key': key1}, {'Key': key2}]``).
865
866 .. _ansible_collections.amazon.aws.docsite.dev_tests:
867
868 Integration Tests for AWS Modules
869 =================================
870
871 All new AWS modules should include integration tests to ensure that any changes in AWS APIs that
872 affect the module are detected. At a minimum this should cover the key API calls and check the
873 documented return values are present in the module result.
874
875 For general information on running the integration tests see the :ref:`Integration Tests page of the
876 Module Development Guide <testing_integration>`, especially the section on configuration for cloud tests.
877
878 The integration tests for your module should be added in ``test/integration/targets/MODULE_NAME``.
879
880 You must also have a aliases file in ``test/integration/targets/MODULE_NAME/aliases``. This file serves
881 two purposes. First indicates it's in an AWS test causing the test framework to make AWS credentials
882 available during the test run. Second putting the test in a test group causing it to be run in the
883 continuous integration build.
884
885 Tests for new modules should be added to the ``cloud/aws`` group. In general just copy
886 an existing aliases file such as the `aws_s3 tests aliases file <https://github.com/ansible-collections/amazon.aws/blob/master/tests/integration/targets/aws_s3/aliases>`_.
887
888
889 Custom SDK versions for Integration Tests
890 -----------------------------------------
891
892 By default integration tests will run against the earliest supported version of
893 the AWS SDK. The current supported versions can be found in
894 ``tests/integration/constraints.txt`` and should not be updated. Where a module
895 needs access to a later version of the SDK this can be installed by depending on
896 the ``setup_botocore_pip`` role and setting the ``botocore_version`` variable in
897 the ``meta/main.yml`` file for your tests.
898
899 .. code-block:: yaml
900
901 dependencies:
902 - role: setup_botocore_pip
903 vars:
904 botocore_version: "1.20.24"
905
906
907 Creating EC2 instances in Integration Tests
908 -------------------------------------------
909
910 When started, the integration tests will be passed ``aws_region`` as an extra var.
911 Any resources created should be created in in this region, this includes EC2
912 instances. Since AMIs are region specific there is a role which can be
913 included which will query the APIs for an AMI to use and set the ``ec2_ami_id``
914 fact. This role can be included by adding the ``setup_ec2_facts`` role as a
915 dependency in the ``meta/main.yml`` file for your tests.
916
917
918 .. code-block:: yaml
919
920 dependencies:
921 - role: setup_ec2_facts
922
923 The ``ec2_ami_id`` fact can then be used in the tests.
924
925 .. code-block:: yaml
926
927 - name: Create launch configuration 1
928 community.aws.ec2_lc:
929 name: '{{ resource_prefix }}-lc1'
930 image_id: '{{ ec2_ami_id }}'
931 assign_public_ip: yes
932 instance_type: '{{ ec2_instance_type }}'
933 security_groups: '{{ sg.group_id }}'
934 volumes:
935 - device_name: /dev/xvda
936 volume_size: 10
937 volume_type: gp2
938 delete_on_termination: true
939
940 To improve test result reproducability across regions, tests should use this
941 role and the fact it provides to chose an AMI to use.
942
943
944 Resource naming in Integration Tests
945 ------------------------------------
946
947 AWS has a range of limitations for the name of resources. Where possible,
948 resource names should include a string which makes the resource names unique
949 to the test.
950
951 The ``ansible-test`` tool used for running the integration tests provides two
952 helpful extra vars: ``resource_prefix`` and ``tiny_prefix`` which are unique to the
953 test set, and should generally used as part of the name. ``resource_prefix`` will generate a prefix based on the host the test is being run on. Sometimes this may result in a resource name that exceeds the character limit allowed by AWS. In these cases, ``tiny_prefix`` will provide a 12-character randomly generated prefix.
954
955 AWS Credentials for Integration Tests
956 -------------------------------------
957
958 The testing framework handles running the test with appropriate AWS credentials, these are made available
959 to your test in the following variables:
960
961 * ``aws_region``
962 * ``aws_access_key``
963 * ``aws_secret_key``
964 * ``security_token``
965
966 So all invocations of AWS modules in the test should set these parameters. To avoid duplicating these
967 for every call, it's preferable to use :ref:`module_defaults <module_defaults>`. For example:
968
969 .. code-block:: yaml
970
971 - name: set connection information for aws modules and run tasks
972 module_defaults:
973 group/aws:
974 aws_access_key: "{{ aws_access_key }}"
975 aws_secret_key: "{{ aws_secret_key }}"
976 security_token: "{{ security_token | default(omit) }}"
977 region: "{{ aws_region }}"
978
979 block:
980
981 - name: Do Something
982 ec2_instance:
983 ... params ...
984
985 - name: Do Something Else
986 ec2_instance:
987 ... params ...
988
989 AWS Permissions for Integration Tests
990 -------------------------------------
991
992 As explained in the :ref:`Integration Test guide <testing_integration>`
993 there are defined IAM policies in `mattclay/aws-terminator <https://github.com/mattclay/aws-terminator>`_ that contain the necessary permissions
994 to run the AWS integration test.
995
996 If your module interacts with a new service or otherwise requires new permissions, tests will fail when you submit a pull request and the
997 `Ansibullbot <https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md>`_ will tag your PR as needing revision.
998 We do not automatically grant additional permissions to the roles used by the continuous integration builds.
999 You will need to raise a Pull Request against `mattclay/aws-terminator <https://github.com/mattclay/aws-terminator>`_ to add them.
1000
1001 If your PR has test failures, check carefully to be certain the failure is only due to the missing permissions. If you've ruled out other sources of failure, add a comment with the ``ready_for_review``
1002 tag and explain that it's due to missing permissions.
1003
1004 Your pull request cannot be merged until the tests are passing. If your pull request is failing due to missing permissions,
1005 you must collect the minimum IAM permissions required to
1006 run the tests.
1007
1008 There are two ways to figure out which IAM permissions you need for your PR to pass:
1009
1010 * Start with the most permissive IAM policy, run the tests to collect information about which resources your tests actually use, then construct a policy based on that output. This approach only works on modules that use ``AnsibleAWSModule``.
1011 * Start with the least permissive IAM policy, run the tests to discover a failure, add permissions for the resource that addresses that failure, then repeat. If your module uses ``AnsibleModule`` instead of ``AnsibleAWSModule``, you must use this approach.
1012
1013 To start with the most permissive IAM policy:
1014
1015 1) `Create an IAM policy <https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create.html#access_policies_create-start>`_ that allows all actions (set ``Action`` and ``Resource`` to ``*``).
1016 2) Run your tests locally with this policy. On AnsibleAWSModule-based modules, the ``debug_botocore_endpoint_logs`` option is automatically set to ``yes``, so you should see a list of AWS ACTIONS after the PLAY RECAP showing all the permissions used. If your tests use a boto/AnsibleModule module, you must start with the least permissive policy (see below).
1017 3) Modify your policy to allow only the actions your tests use. Restrict account, region, and prefix where possible. Wait a few minutes for your policy to update.
1018 4) Run the tests again with a user or role that allows only the new policy.
1019 5) If the tests fail, troubleshoot (see tips below), modify the policy, run the tests again, and repeat the process until the tests pass with a restrictive policy.
1020 6) Open a pull request proposing the minimum required policy to the `CI policies <https://github.com/mattclay/aws-terminator/tree/master/aws/policy>`_.
1021
1022 To start from the least permissive IAM policy:
1023
1024 1) Run the integration tests locally with no IAM permissions.
1025 2) Examine the error when the tests reach a failure.
1026 a) If the error message indicates the action used in the request, add the action to your policy.
1027 b) If the error message does not indicate the action used in the request:
1028 - Usually the action is a CamelCase version of the method name - for example, for an ec2 client the method ``describe_security_groups`` correlates to the action ``ec2:DescribeSecurityGroups``.
1029 - Refer to the documentation to identify the action.
1030 c) If the error message indicates the resource ARN used in the request, limit the action to that resource.
1031 d) If the error message does not indicate the resource ARN used:
1032 - Determine if the action can be restricted to a resource by examining the documentation.
1033 - If the action can be restricted, use the documentation to construct the ARN and add it to the policy.
1034 3) Add the action or resource that caused the failure to `an IAM policy <https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create.html#access_policies_create-start>`_. Wait a few minutes for your policy to update.
1035 4) Run the tests again with this policy attached to your user or role.
1036 5) If the tests still fail at the same place with the same error you will need to troubleshoot (see tips below). If the first test passes, repeat steps 2 and 3 for the next error. Repeat the process until the tests pass with a restrictive policy.
1037 6) Open a pull request proposing the minimum required policy to the `CI policies <https://github.com/mattclay/aws-terminator/tree/master/aws/policy>`_.
1038
1039 Troubleshooting IAM policies
1040 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1041
1042 - When you make changes to a policy, wait a few minutes for the policy to update before re-running the tests.
1043 - Use the `policy simulator <https://policysim.aws.amazon.com/>`_ to verify that each action (limited by resource when applicable) in your policy is allowed.
1044 - If you're restricting actions to certain resources, replace resources temporarily with ``*``. If the tests pass with wildcard resources, there is a problem with the resource definition in your policy.
1045 - If the initial troubleshooting above doesn't provide any more insight, AWS may be using additional undisclosed resources and actions.
1046 - Examine the AWS FullAccess policy for the service for clues.
1047 - Re-read the AWS documentation, especially the list of `Actions, Resources and Condition Keys <https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_actions-resources-contextkeys.html>`_ for the various AWS services.
1048 - Look at the `cloudonaut <https://iam.cloudonaut.io>`_ documentation as a troubleshooting cross-reference.
1049 - Use a search engine.
1050 - Ask in the #ansible-aws chat channel (using Matrix at ansible.im or using IRC at `irc.libera.chat <https://libera.chat/>`_).
1051
1052 Unsupported Integration tests
1053 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1054
1055 There are a limited number of reasons why it may not be practical to run integration
1056 tests for a module within CI. Where these apply you should add the keyword
1057 ``unsupported`` to the aliases file in ``test/integration/targets/MODULE_NAME/aliases``.
1058
1059 Some cases where tests should be marked as unsupported:
1060 1) The tests take longer than 10 or 15 minutes to complete
1061 2) The tests create expensive resources
1062 3) The tests create inline policies
1063 4) The tests require the existence of external resources
1064 5) The tests manage Account level security policies such as the password policy or AWS Organizations.
1065
1066 Where one of these reasons apply you should open a pull request proposing the minimum required policy to the
1067 `unsupported test policies <https://github.com/mattclay/aws-terminator/tree/master/hacking/aws_config/test_policies>`_.
1068
1069 Unsupported integration tests will not be automatically run by CI. However, the
1070 necessary policies should be available so that the tests can be manually run by
1071 someone performing a PR review or writing a patch.
1072
1073 Unit-tests for AWS plugins
1074 ==========================
1075
1076 Why do we need unit-tests when we've got functional tests
1077 ---------------------------------------------------------
1078
1079 Unit-tests are much faster and more suitable to test corner cases. They also don't depend on a third party service
1080 and thus, a failure is less likely to be a false positive.
1081
1082
1083 How to keep my code simple?
1084 ---------------------------
1085
1086 Ideally, you should break up your code in tiny functions. Each function should have a limited number of parameters
1087 and a low amount of cross dependencies with the rest of the code (low coupling):
1088
1089 - Don't pass a large data structure to a function if it only uses one field. This clarifies the inputs of your
1090 function (the contract) and also reduces the risk of an unexpected transformation of the data structure
1091 from within the function.
1092 - The boto client object is complex and can be source of unwanted side-effect. It's better to isolate the calls
1093 in dedicated functions. These functions will have their own unit-tests.
1094 - Don't pass the ``module`` object when you only need the read a couple of parameters from ``module.params``.
1095 Pass the parameter directly to your function. By doing so, you're explicit about the function's inputs
1096 (the contract) and you reduce potential side-effect.
1097
1098 Unit-tests guidelines
1099 ---------------------
1100
1101 Ideally, all the ``module_utils`` should be covered by unit-tests. However we acknowledge that writing unit-tests may
1102 be challenging and we also accept contribution with no unit-test. Generally speaking, unit-tests are recommended and likely to speed up the PR reviews.
1103
1104 - Our tests are run with ``pytest`` and we use the features it provides such as Fixtures, Parametrization.
1105 - The use of ``unittest.TestCase`` is discouraged for the sake of consistency and simplicity.
1106 - Unit-tests should run fine without any network connection.
1107 - It's not necessary to mock all the boto3/botocore calls (``get_paginator()``, ``paginate()``, etc). It's often better to just set-up a function that wraps these calls and mock the result.
1108 - Simplicity prevails. Tests should be short and cover a limited set of features.
1109
1110 Pytest is well documented and you will find some example in its `how-to guides <https://docs.pytest.org/en/latest/how-to/index.html>`_
1111
1112 How to run my unit-tests
1113 ------------------------
1114
1115 In our CI, the testing is done by ``ansible-test``. You can run the tests locally with the following command:
1116
1117 .. code-block:: shell
1118
1119 $ ansible-test units --docker
1120
1121 We also provide a ``tox`` configuration which allow you to run one specific test faster. In this example, we focus on the tests for the ``s3_object`` module:
1122
1123 .. code-block:: shell
1124
1125 $ tox -e py3 -- tests/unit/plugins/modules/test_s3_object.py
1126
1127
1128 Code formatting
1129 ===============
1130
1131 To improve the consistency of our code we use a number of formatters and linters. These tools can
1132 be run locally by using tox:
1133
1134 .. code-block:: shell
1135
1136 $ tox -m format
1137
1138 .. code-block:: shell
1139
1140 $ tox -m lint
1141
1142 More information about each of the tools we use can be found on their websites:
1143
1144 - `black <https://black.readthedocs.io/en/stable/>`_ - opinionated code formatter.
1145 - `isort <https://pycqa.github.io/isort/>`_ - groups and sorts imports.
1146 - `flynt <https://github.com/ikamensh/flynt>`_ - encourages the use of f-strings over alternatives such as concatination, ``%``, ``str.format()``, and ``string.Template``.
1147 - `flake8 <https://flake8.pycqa.org/en/latest/>`_ - encourages following the PEP8 recommendations.
1148 - `pylint <https://pylint.readthedocs.io/en/latest/>`_ - a static code anaylsys tool.