| 1 |
# Developing Cisco ACI modules |
| 2 |
|
| 3 |
This guide is intended for developers who want to contribute code, bug fixes, or new modules to the Cisco ACI-Ansible collection. It provides step-by-step instructions and outlines the standards and conventions to follow when making contributions. |
| 4 |
|
| 5 |
For additional details about Cisco ACI, please refer to the [Cisco ACI user guide](https://www.cisco.com/c/en/us/solutions/collateral/data-center-virtualization/application-centric-infrastructure/solution-overview-c22-741487.html). |
| 6 |
|
| 7 |
What is covered in this section: |
| 8 |
|
| 9 |
Here's the Table of Contents for the Markdown content: |
| 10 |
|
| 11 |
**Table of Contents** |
| 12 |
|
| 13 |
* [Developing Cisco ACI modules](#developing-cisco-aci-modules) |
| 14 |
* [Introduction](#introduction) |
| 15 |
* [Development Environment](#development-environment) |
| 16 |
* [Git contribution workflow for ACI collection](#git-contribution-workflow-for-aci-collection) |
| 17 |
* [Tools required for installation and build](#tools-required-for-installation-and-build) |
| 18 |
* [ACI Collection structure](#aci-collection-structure) |
| 19 |
* [Building a new module](#building-a-new-module) |
| 20 |
* [Copyright Section](#copyright-section) |
| 21 |
* [Documentation Section](#documentation-section) |
| 22 |
* [Notes and Additional Sections](#notes-and-additional-sections) |
| 23 |
* [Examples Section](#examples-section) |
| 24 |
* [Return Section](#return-section) |
| 25 |
* [Importing objects from Python libraries](#importing-objects-from-python-libraries) |
| 26 |
* [Defining the argument_spec variable](#defining-the-argument_spec-variable) |
| 27 |
* [Using the AnsibleModule object](#using-the-ansiblemodule-object) |
| 28 |
* [Mapping variable definition](#mapping-variable-definition) |
| 29 |
* [Using the ACIModule object](#using-the-acimodule-object) |
| 30 |
* [Constructing URLs](#constructing-urls) |
| 31 |
* [Getting the existing configuration](#getting-the-existing-configuration) |
| 32 |
* [When state is present](#when-state-is-present) |
| 33 |
* [Building the ACI payload](#building-the-aci-payload) |
| 34 |
* [Performing the request](#performing-the-request) |
| 35 |
* [When state is absent](#when-state-is-absent) |
| 36 |
* [Exiting the module](#exiting-the-module) |
| 37 |
* [Testing the Module](#testing-the-module) |
| 38 |
* [Additional checks before making a Pull Request](#additional-checks-before-making-a-pull-request) |
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
## Introduction |
| 43 |
The [cisco.aci collection](https://galaxy.ansible.com/cisco/aci) already includes a large number of Cisco ACI modules; however, the ACI object model is extensive, and covering all possible functionality would easily require more than 1,500 individual modules. Therefore, Cisco develops modules requested on a just-in-time basis. |
| 44 |
|
| 45 |
If a specific functionality is required, there are three options: |
| 46 |
|
| 47 |
- Open an issue using https://github.com/CiscoDevNet/ansible-aci/issues/new/choose so that Cisco developers can build, enhance, or fix the modules. If you have a Cisco support contract, contact Cisco TAC to open an issue for you. |
| 48 |
- Learn the ACI object model and utilize the low-level APIC REST API using the [aci_rest](https://docs.ansible.com/ansible/latest/collections/cisco/aci/aci_rest_module.html) module. |
| 49 |
- Contribute to Cisco's ansible-aci project by writing dedicated modules, proposing a fix or an enhancement, and becoming part of the Cisco ansible-aci community. |
| 50 |
|
| 51 |
This guide will concentrate on the third option to demonstrate how to build a module, fix an issue, or improve an existing module and contribute it back to the ansible-aci project. The initial step in this process is to retrieve the latest version of the ansible-aci collection code. By retrieving the latest version, one will be able to modify existing code. |
| 52 |
|
| 53 |
## Development Environment |
| 54 |
|
| 55 |
### Git contribution workflow for ACI collection |
| 56 |
To contribute effectively, first fork the [ACI repository](https://github.com/CiscoDevNet/ansible-aci) to your GitHub account, then clone your fork locally, and finally create a feature branch named after the specific change (e.g., new_l3out_static_routes_docs). |
| 57 |
|
| 58 |
> Branching isolates development for bug fixes and new features. Always create a dedicated branch from `master` for modifications. This maintains a clean local `master` synchronized with the upstream, simplifying future updates and preventing complex merge/rebase operations. |
| 59 |
|
| 60 |
> To understand more about the Git contribution workflow, refer to the [Git contribution workflow for ACI collection](aci_collection_git_contribution_workflow.md) |
| 61 |
|
| 62 |
|
| 63 |
### Tools required for installation and build |
| 64 |
|
| 65 |
Before building or testing the modules, ensure all required tools are installed. The full list of dependencies and setup instructions are documented in the collection's [README.md](https://github.com/CiscoDevNet/ansible-aci?tab=readme-ov-file#ansible-aci) file. This includes guidance on installing Python packages, Ansible collections, linters, and other development tools needed for module creation and testing. |
| 66 |
|
| 67 |
### ACI Collection structure |
| 68 |
|
| 69 |
The structure of the cisco.aci collection which consists of directories and files that are in ansible-aci repository. To further explore the cisco.aci collection structure in detail, refer [ACI collection structure](aci_collection_structure.md). |
| 70 |
|
| 71 |
## Building a new module |
| 72 |
There are two recommended approaches for creating a new Ansible module in the Cisco ACI collection: |
| 73 |
1. Use the template module provided in [docs/sample_module/aci_module_template.md](sample_module/aci_module_template.md) |
| 74 |
2. Repurpose an existing module from the collection that is functionally or hierarchically similar |
| 75 |
|
| 76 |
Both methods ensure consistency with the existing module structure, coding conventions, and integration practices within the collection. |
| 77 |
|
| 78 |
To create a new module from scratch, this document follows the first approach: |
| 79 |
> * copy the python code from the template module provided in [docs/sample_module/aci_module_template.md](sample_module/aci_module_template.md) |
| 80 |
> * Create a new python file in the plugins/modules directory of the collection named aci_<name_of_module>.py, where <name_of_module> is the name of the module being created. |
| 81 |
> * Paste the copied contents of the template module into the newly created python file. |
| 82 |
|
| 83 |
This approach simplifies the creation of a new module without requiring everything to be written from scratch. |
| 84 |
|
| 85 |
### Copyright Section |
| 86 |
|
| 87 |
Change the copyright section by replacing <year> by current year, <name> by author's name and <author_github_handle> by author's github handle: |
| 88 |
|
| 89 |
```python |
| 90 |
#!/usr/bin/python |
| 91 |
# -*- coding: utf-8 -*- |
| 92 |
|
| 93 |
# Copyright: (c) <year>, <Name> (<author_github_handle>) |
| 94 |
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 95 |
|
| 96 |
from __future__ import absolute_import, division, print_function |
| 97 |
__metaclass__ = type |
| 98 |
|
| 99 |
ANSIBLE_METADATA = { |
| 100 |
'metadata_version': '1.1', |
| 101 |
'status': ['preview'], |
| 102 |
'supported_by': 'community' |
| 103 |
} |
| 104 |
``` |
| 105 |
|
| 106 |
> [!NOTE] |
| 107 |
> The above code block remains unchanged, except for the copyright section, which must be updated. |
| 108 |
|
| 109 |
### Documentation Section |
| 110 |
|
| 111 |
Each Ansible module must include a properly structured DOCUMENTATION section that clearly explains the module's purpose, usage, and parameters and follow the Ansible documentation guidelines. |
| 112 |
|
| 113 |
Start by updating the following: |
| 114 |
* Module name: the name of the module should be aci_<name_of_module>, where <name_of_module> is the name of the module being created. It should be same as the file name the module is being created in. |
| 115 |
* Short description of what the module does |
| 116 |
* Detailed description explaining the operations performed on the object |
| 117 |
|
| 118 |
This must be followed by the options section, which defines all the input parameters the module accepts. |
| 119 |
|
| 120 |
**Options Section** |
| 121 |
|
| 122 |
The options section lists all parameters that will be defined in the module's argument_spec. This includes: |
| 123 |
* object_id |
| 124 |
* Configurable properties of the object |
| 125 |
* Parent object reference |
| 126 |
* Any additional required parameters |
| 127 |
* state |
| 128 |
|
| 129 |
Each parameter should define: |
| 130 |
* description: Clear and concise explanation of the parameter's purpose |
| 131 |
* type: Data type (e.g., str, int, bool) |
| 132 |
* aliases: (if applicable) |
| 133 |
* choices: (if applicable) |
| 134 |
* default: (if applicable) |
| 135 |
|
| 136 |
- Description must be clear and concise, providing enough detail for users to understand the purpose and usage of the object. |
| 137 |
- Description must include specific details about the object, such as its purpose, how it is used, and any important considerations. |
| 138 |
* For example, |
| 139 |
+ The APIC defaults to `default_value` when unset during creation. Explains that when an object value is not explicitly provided in a task, the APIC automatically assigns a default value to that object. |
| 140 |
+ The object_prop1 must be in the range 1 to 100. The default value is 50. |
| 141 |
+ The object_prop3 is only applicable when using 'object_prop2' is set to <specific_value>. |
| 142 |
+ default: <xyz> , the default values should not be provided for configuration arguments, unless API adds a default_value to the payload when creating the object. Default values could cause unintended changes to the object. |
| 143 |
+ required: true; should be used only for parameters that are mandatory in all the states (present,query,absent) of the module. This ensures that users must provide a value for these parameters when using the module. |
| 144 |
|
| 145 |
> [!NOTE] |
| 146 |
> If a parameter is required in some states but not in others, then it should **NOT** be marked as required: true. Instead, it should be added in the argument_spec with the appropriate required_if conditions. |
| 147 |
|
| 148 |
### extends_documentation_fragment section |
| 149 |
|
| 150 |
The options section must be followed by the extends_documentation_fragment section, which allows modules to reuse standard documentation elements shared across the ACI collection. |
| 151 |
|
| 152 |
Common documentation fragments are located in the plugins/doc_fragments/ directory of the collection and typically include: |
| 153 |
* `cisco.aci.aci`: **Always included**; defines common ACI parameters such as host, username, password, etc. |
| 154 |
* `cisco.aci.annotation`: Include if the module supports the *annotation* parameter. |
| 155 |
* `cisco.aci.owner`: Include if the module supports the *owner* parameter. |
| 156 |
|
| 157 |
The format of `DOCUMENTATION` section is as follows: |
| 158 |
|
| 159 |
```yaml |
| 160 |
DOCUMENTATION = r""" |
| 161 |
--- |
| 162 |
module: aci_<name_of_module> |
| 163 |
short_description: Short description of the module being created (config:<name_of_class>). |
| 164 |
description: |
| 165 |
- Functionality one. |
| 166 |
- Functionality two. |
| 167 |
options: |
| 168 |
object_id: |
| 169 |
description: |
| 170 |
- Description of the object. |
| 171 |
type: Data type of object eg. 'str' |
| 172 |
aliases: [ Alternate name of the object ] |
| 173 |
object_prop1: |
| 174 |
description: |
| 175 |
- Description of property one. |
| 176 |
type: Property's data type eg. 'int' |
| 177 |
choices: [ choice one, choice two ] |
| 178 |
object_prop2: |
| 179 |
description: |
| 180 |
- Description of property two. |
| 181 |
- This attribute is only configurable in ACI versions 6.0(2h) and above. |
| 182 |
type: Property's data type eg. 'bool' |
| 183 |
object_prop3: |
| 184 |
description: |
| 185 |
- Description of property three. |
| 186 |
- The APIC defaults to C(default_value) when unset during creation. |
| 187 |
- The object_prop3 is only applicable when using 'object_prop2' is set to <specific_value>. |
| 188 |
- The object_prop3 must be in the range 1 to 100. The default value is 50. |
| 189 |
type: Property's data type eg. 'str' |
| 190 |
required: true |
| 191 |
child_object_prop: |
| 192 |
description: |
| 193 |
- Description of the child class object property |
| 194 |
- This is required for child class object B(config:<name_of_child_class>) |
| 195 |
state: |
| 196 |
description: |
| 197 |
- Use C(present) or C(absent) for adding or removing. |
| 198 |
- Use C(query) for listing an object or multiple objects. |
| 199 |
type: str |
| 200 |
choices: [ absent, present, query ] |
| 201 |
default: present |
| 202 |
extends_documentation_fragment: |
| 203 |
- cisco.aci.aci |
| 204 |
``` |
| 205 |
|
| 206 |
### Notes and Additional Sections |
| 207 |
|
| 208 |
Following the options and extends_documentation_fragment sections, include the following elements in the DOCUMENTATION block: |
| 209 |
* **notes**: Use this section to document any important dependencies or relationships with other modules in the collection. This is especially useful when the module relies on a parent object or must be used in conjunction with another module. |
| 210 |
* **see_also**: Provide references to related modules or the underlying ACI class (e.g., the REST API class or managed object) that the module interfaces with. This helps users understand the source and behavior of the module. |
| 211 |
* **author**: At the end of the documentation block, include the contributor's name and GitHub handle. |
| 212 |
|
| 213 |
The format of the notes and see_also sections is as follows: |
| 214 |
|
| 215 |
```yaml |
| 216 |
notes: |
| 217 |
- The C(root_object), C(parent_object), C(object_prop), used must exist before using this module in your playbook. |
| 218 |
The M(cisco.aci.aci_root_object_module) and M(cisco.aci.parent_object_module) modules can be used for this. |
| 219 |
seealso: |
| 220 |
- module: cisco.aci.aci_root_object_module |
| 221 |
- module: cisco.aci.aci_parent_object_module |
| 222 |
- name: APIC Management Information Model reference |
| 223 |
description: More information about the internal APIC class B(config:<name_of_class>). |
| 224 |
link: https://developer.cisco.com/docs/apic-mim-ref/ |
| 225 |
author: |
| 226 |
- <author's name> (<author's github id>) |
| 227 |
""" |
| 228 |
``` |
| 229 |
|
| 230 |
### Examples Section |
| 231 |
|
| 232 |
The EXAMPLES section provides practical usage patterns for the module and must include complete Ansible tasks that serve as references for users building playbooks. |
| 233 |
|
| 234 |
* Please note that 'remove an object' and 'query an object' will only contain the object name and no object parameters. "Query All" will not have any parameters other than the one that are set to required to construct the dn, ensuring that all the objects of the class being worked upon are returned. |
| 235 |
* The example section must include Add, Query a single object, Query all objects, and Remove operations that can be performed using the module. |
| 236 |
* Each example should include the required parameters and the expected state of the object. |
| 237 |
|
| 238 |
> Ensure the examples demonstrate realistic use cases, include proper indentation, and adhere to the module's expected argument structure, as these examples are often used directly in playbooks. |
| 239 |
|
| 240 |
The format of this section is shown below: |
| 241 |
|
| 242 |
```yaml |
| 243 |
EXAMPLES = r""" |
| 244 |
- name: Add a new object |
| 245 |
cisco.aci.aci_<name_of_module>: |
| 246 |
host: apic |
| 247 |
username: admin |
| 248 |
password: SomeSecretePassword |
| 249 |
object_id: id |
| 250 |
object_prop1: prop1 |
| 251 |
object_prop2: prop2 |
| 252 |
state: present |
| 253 |
delegate_to: localhost |
| 254 |
|
| 255 |
- name: Query an object |
| 256 |
cisco.aci.aci_<name_of_module>: |
| 257 |
host: apic |
| 258 |
username: admin |
| 259 |
password: SomeSecretePassword |
| 260 |
object_id: id |
| 261 |
state: query |
| 262 |
delegate_to: localhost |
| 263 |
|
| 264 |
- name: Query all objects |
| 265 |
cisco.aci.aci_<name_of_module>: |
| 266 |
host: apic |
| 267 |
username: admin |
| 268 |
password: SomeSecretePassword |
| 269 |
state: query |
| 270 |
delegate_to: localhost |
| 271 |
|
| 272 |
- name: Remove an object |
| 273 |
cisco.aci.aci_<name_of_module>: |
| 274 |
host: apic |
| 275 |
username: admin |
| 276 |
password: SomeSecretePassword |
| 277 |
object_id: id |
| 278 |
state: absent |
| 279 |
delegate_to: localhost |
| 280 |
""" |
| 281 |
``` |
| 282 |
|
| 283 |
### Return Section |
| 284 |
|
| 285 |
The RETURN section defines the structure and content of the output returned after execution. |
| 286 |
It is used in every module and has the same content, so copy and paste it from any module and do not modify it. |
| 287 |
|
| 288 |
Refer to the `RETURN` section in any existing module in the collection or the aci_module_template.md file in [docs/sample_module/aci_module_template.md](sample_module/aci_module_template.md) for complete content. |
| 289 |
|
| 290 |
```python |
| 291 |
RETURN = r""" |
| 292 |
current: |
| 293 |
... |
| 294 |
""" |
| 295 |
``` |
| 296 |
|
| 297 |
### Importing objects from Python libraries |
| 298 |
|
| 299 |
The import section is generally consistent across ACI modules and usually does not require changes. However, if a new shared method or utility is added to the library, it may need to be imported explicitly. |
| 300 |
|
| 301 |
The following imports are standard across ACI modules: |
| 302 |
|
| 303 |
```python |
| 304 |
from ansible.module_utils.basic import AnsibleModule |
| 305 |
from ansible.module_utils.aci.plugins.module_utils.aci import ACIModule, aci_argument_spec |
| 306 |
``` |
| 307 |
|
| 308 |
* `ansible.module_utils.aci` import the superclass `ACIModule` and the `aci_argument_spec` definition from the library in plugins/module_utils/aci.py file. |
| 309 |
* `ACIModule` is imported because it has basic functions to make API requests and other capabilities that allow modules to manipulate objects. |
| 310 |
* **aci_argument_spec** is used by all the modules as it allows them to accept shared parameters such as username and password. |
| 311 |
* If the module supports the annotation or owner parameters, also import **aci_annotation_spec** and **aci_owner_spec** respectively (as needed). |
| 312 |
|
| 313 |
Similarly, the AnsibleModule is imported to leverage the common structure for building Ansible modules in Python. |
| 314 |
|
| 315 |
> [!TIP] |
| 316 |
> To understand more about the AnsibleModule, refer to the [Ansible documentation](https://docs.ansible.com/ansible/latest/dev_guide/developing_program_flow_modules.html#ansiblemodule). |
| 317 |
|
| 318 |
* **Importing ACI Constants**: These constants, defined in plugins/module_utils/constants.py, provide standardized values and mapping dictionaries that help normalize ACI-specific parameters across modules. |
| 319 |
|
| 320 |
```python |
| 321 |
# Importing constants for ACI modules when needed. |
| 322 |
# This import is used to access predefined constants and mappings for ACI objects. |
| 323 |
from ansible_collections.cisco.aci.plugins.module_utils.constants import * |
| 324 |
``` |
| 325 |
|
| 326 |
> [!TIP] |
| 327 |
> * The '*' <ins>should</ins> be replaced with the specific constants needed, such as: |
| 328 |
`from ansible_collections.cisco.aci.plugins.module_utils.constants import FILTER_PORT_MAPPING, IPV4_REGEX` |
| 329 |
|
| 330 |
|
| 331 |
|
| 332 |
### Defining the argument_spec variable |
| 333 |
|
| 334 |
In the `main()` function, the argument_spec variable defines all arguments required by the module and is based on the shared aci_argument_spec. All parameters previously defined in the DOCUMENTATION section should be added here. |
| 335 |
|
| 336 |
The **argument_spec** provides a base set of common arguments (such as APIC credentials and connection details), and **argument_spec.update()** is used to define additional parameters specific to the module being developed. |
| 337 |
|
| 338 |
> [!TIP] |
| 339 |
> For more information on how argument_spec works, refer to the [Ansible Argument Spec](https://docs.ansible.com/ansible/latest/dev_guide/developing_program_flow_modules.html#argument-spec). |
| 340 |
|
| 341 |
Common parameters to include: |
| 342 |
* The **object_id** (usually the name). |
| 343 |
* All **configurable properties** of the object. |
| 344 |
* **Parent object IDs** (typically names) all the way up to the root object. |
| 345 |
* The **child classes** with a 1-to-1 relationship to the main object may be implemented within the same module. |
| 346 |
If the relationship is 1-to-many or many-to-many, the child object should generally have its own dedicated module. Some edge cases may deviate from this pattern. |
| 347 |
* The state parameter: |
| 348 |
* `state: absent` to ensure the object does not exist |
| 349 |
* `state: present` to ensure the object and configurations exist; this is also the default |
| 350 |
* `state: query` to retrieve information about a specific object or all objects of the class |
| 351 |
|
| 352 |
```python |
| 353 |
def main(): |
| 354 |
argument_spec = aci_argument_spec() |
| 355 |
argument_spec.update( |
| 356 |
object_id=dict(type='str', aliases=['name']), |
| 357 |
object_prop1=dict(type='str'), |
| 358 |
object_prop2=dict(type='str', choices=['choice1', 'choice2', 'choice3']), |
| 359 |
object_prop3=dict(type='int'), |
| 360 |
parent_id=dict(type='str'), |
| 361 |
child_object_id=dict(type='str'), |
| 362 |
child_object_prop=dict(type='str'), |
| 363 |
state=dict(type='str', default='present', choices=['absent', 'present', 'query']), |
| 364 |
) |
| 365 |
``` |
| 366 |
|
| 367 |
> [!NOTE] |
| 368 |
> Avoid setting default values for configuration arguments unless the APIC explicitly applies them. Providing defaults may unintentionally modify the object during execution. |
| 369 |
|
| 370 |
### Using the AnsibleModule object |
| 371 |
|
| 372 |
This section creates an instance of AnsibleModule, passing in key attributes such as argument_spec, supports_check_mode, required_if, etc. |
| 373 |
|
| 374 |
All ACI modules should support check mode, which allows Ansible to simulate a task without making any changes to the APIC. This helps users validate their playbooks safely. |
| 375 |
|
| 376 |
The constructor takes the following arguments: |
| 377 |
* `argument_spec`: The full set of module arguments, including shared and module-specific parameters. |
| 378 |
* `supports_check_mode=True`: Enables check mode support (required in almost all modules in the ACI collection). |
| 379 |
* `required_if`: Defines conditionally required arguments—i.e., arguments that are only mandatory under certain states such as present or absent. |
| 380 |
* other parameters such as `required_one_of`, `required_together`, etc., can also be used to define complex dependencies between parameters, based on the module's requirements. |
| 381 |
|
| 382 |
> [!TIP] |
| 383 |
> For more information on the AnsibleModule, refer to the [AnsibleModule documentation](https://docs.ansible.com/ansible/latest/dev_guide/developing_program_flow_modules.html#ansiblemodule). |
| 384 |
|
| 385 |
```python |
| 386 |
module = AnsibleModule( |
| 387 |
argument_spec=argument_spec, |
| 388 |
supports_check_mode=True, |
| 389 |
required_if=[ |
| 390 |
['state', 'absent', ['object_id', 'parent_id']], |
| 391 |
['state', 'present', ['object_id', 'parent_id']], |
| 392 |
], |
| 393 |
) |
| 394 |
``` |
| 395 |
|
| 396 |
Understanding required_if: |
| 397 |
* The required_if parameter ensures that specific attributes (e.g., object_id, parent_id) are provided only when the module is creating (state: present) or deleting (state: absent) an object. |
| 398 |
* These parameters are not required when the state is query, especially when performing a "query all" operation. |
| 399 |
* If any of the required parameters are missing during present or absent states, Ansible will raise an error at runtime, prompting the user to supply the missing attributes. |
| 400 |
|
| 401 |
This conditional requirement helps maintain flexibility while ensuring proper validation during object creation or removal. |
| 402 |
|
| 403 |
### Mapping variable definition |
| 404 |
|
| 405 |
After instantiating the AnsibleModule object (which is required for all modules), the next step is to extract parameter values from the playbook that correspond to the object's properties defined in the main() function. This is also the appropriate place to perform basic validations and string formatting or concatenation, as needed. |
| 406 |
|
| 407 |
Once the AnsibleModule object is initialized as module, retrieve values from the module.params dictionary. Typically, only parameters related to the ACI object and its child configuration need to be extracted. Any necessary type checks or validations (e.g., capitalize the input or add special characters) should also be performed here. |
| 408 |
|
| 409 |
```python |
| 410 |
object_id = module.params.get('object_id') |
| 411 |
object_prop1 = module.params.get('object_prop1') |
| 412 |
object_prop2 = module.params.get('object_prop2') |
| 413 |
object_prop3 = module.params.get('object_prop3') |
| 414 |
if object_prop3 is not None and object_prop3 not in range(x, y): |
| 415 |
module.fail_json(msg='Valid object_prop3 values are between x and (y-1)') |
| 416 |
child_object_id = module.params.get('child_object_id') |
| 417 |
child_object_prop = module.params.get('child_object_prop') |
| 418 |
state = module.params.get("state") |
| 419 |
``` |
| 420 |
|
| 421 |
> [!NOTE] |
| 422 |
> * In some cases, the APIC requires special characters (e.g., [, ], or -) in names, or uses internal metadata (e.g., "port_binding" attribute in aci_epg_to_domain module). Modules should handle formatting or concatenation of parameters internally to keep user input simple and intuitive. |
| 423 |
> * Most type conversions and validations at this stage are minimal and are intended to ensure that properly formatted data is passed into subsequent API calls or logic. |
| 424 |
> * Certain additional validations are only added when API response for these checks are not as expected. |
| 425 |
|
| 426 |
### Using the ACIModule object |
| 427 |
|
| 428 |
The ACIModule class manages most of the logic used by ACI modules. It extends the functionality of the AnsibleModule object, so the module instance must be passed during instantiation: |
| 429 |
|
| 430 |
```python |
| 431 |
aci = ACIModule(module) |
| 432 |
``` |
| 433 |
|
| 434 |
The ACIModule includes 7 main methods commonly used across modules: |
| 435 |
|
| 436 |
* construct_url |
| 437 |
* get_existing |
| 438 |
* payload |
| 439 |
* get_diff |
| 440 |
* post_config |
| 441 |
* delete_config |
| 442 |
* exit_json |
| 443 |
|
| 444 |
The first 2 methods are used regardless of what value is passed to the `state` parameter. |
| 445 |
|
| 446 |
#### Constructing URLs |
| 447 |
|
| 448 |
The `construct_url()` method dynamically builds the REST API URL and query parameters for retrieving or configuring ACI objects. It supports multiple levels of the object hierarchy by accepting up to six optional subclass dictionaries and one list of child classes. |
| 449 |
|
| 450 |
This method uses the root class (e.g., fvTenant) and optional subclass dictionaries to construct the full distinguished name (DN) of the object. It also applies filters and response modifiers. |
| 451 |
|
| 452 |
* When the `state` is not `query`:The URL includes the full DN (base URL (to access the APIC) with the distinguished name of the object (to access the object)) of the object, and the response is typically limited to configuration data (config-only). |
| 453 |
* When `state` is `query`, the URL and filter string used depend on which parameters are passed to the object. This method handles the complexity so that it is easier to add new modules and ensures that all modules are consistent in the type of data returned. |
| 454 |
|
| 455 |
* **Query specific object**: the URL is constructed to target a specific object within the module's class using its distinguished name. The filter string is typically not applied, allowing retrieval of the full object data. This approach simplifies module development by handling the URL construction dynamically and ensures consistent data retrieval for individual objects. |
| 456 |
|
| 457 |
* **Query all objects**: the URL is built to query all objects of the specified class. If a target filter is provided, it is applied as a query parameter to restrict the returned data to matching objects. This method manages the complexity of querying collections, making it easier to add new modules and maintain uniformity in the data returned across modules. |
| 458 |
|
| 459 |
> [!IMPORTANT] |
| 460 |
> The design goal for querying the objects, is to use the provided ID parameters to return the most specific data possible: |
| 461 |
> * If no ID parameters are given, return all objects of the class. |
| 462 |
> * If only some ID parameters are provided, return all objects that match those IDs. |
| 463 |
|
| 464 |
> [!TIP] |
| 465 |
> For more information on the ACI REST APIs and how to construct URLs [ACI REST API Guide](https://www.cisco.com/c/en/us/td/docs/dcn/aci/apic/all/apic-rest-api-configuration-guide/cisco-apic-rest-api-configuration-guide-42x-and-later/m_using_the_rest_api.html). |
| 466 |
|
| 467 |
The `construct_url()` method takes: |
| 468 |
1. **2 required arguments**: |
| 469 |
* **self** - passed automatically with the class instance |
| 470 |
* **root_class** - A dictionary consisting of `aci_class`, `aci_rn`, `target_filter`, and `module_object` keys |
| 471 |
+ **aci_class**: The name of the class used by the APIC. |
| 472 |
+ **aci_rn**: The relative name of the object. |
| 473 |
+ **target_filter**: A dictionary with key-value pairs that make up the query string for selecting a subset of entries. |
| 474 |
+ **module_object**: The particular object for this class. |
| 475 |
|
| 476 |
Some modules, like `aci_tenant`, are the root class and so would not need to pass any additional arguments to the method. |
| 477 |
|
| 478 |
2. **7 optional arguments**: |
| 479 |
1. subclass_1 to subclass_6: Dictionaries similar to root_class |
| 480 |
* subclass_1 - A dictionary consisting of `aci_class`, `aci_rn`, `target_filter`, and `module_object` keys |
| 481 |
* subclass_2 - A dictionary consisting of `aci_class`, `aci_rn`, `target_filter`, and `module_object` keys |
| 482 |
* subclass_3 - A dictionary consisting of `aci_class`, `aci_rn`, `target_filter`, and `module_object` keys |
| 483 |
* subclass_4 - A dictionary consisting of `aci_class`, `aci_rn`, `target_filter`, and `module_object` keys |
| 484 |
* subclass_5 - A dictionary consisting of `aci_class`, `aci_rn`, `target_filter`, and `module_object` keys |
| 485 |
* subclass_6 - A dictionary consisting of `aci_class`, `aci_rn`, `target_filter`, and `module_object` keys |
| 486 |
2. child_classes: A list of supported child APIC class names (even if it is just one child class object) |
| 487 |
|
| 488 |
> [!NOTE] |
| 489 |
> * `aci_rn`: the relative name of the object, which is one section of the distinguished name (DN) with the ID of the specific argument. It should not contain the entire DN, as the method will automatically construct the full DN using the provided RNs of all arguments. |
| 490 |
> * Refer to the modules aci_l3out_static_routes_nexthop for creation of object (ip:NexthopP) and aci_l3out_hsrp_secondary_vip for creation of object (hsrp:SecVip) for insights on how to use the `construct_url()` method. |
| 491 |
|
| 492 |
Example: |
| 493 |
|
| 494 |
```python |
| 495 |
# If "dn" = "uni/tn-ansible_tenant/out-ansible_l3out/lnodep-ansible_node_profile/", then the construct_url() will be constructed as follows: |
| 496 |
|
| 497 |
aci.construct_url( |
| 498 |
root_class=dict( |
| 499 |
aci_class='fvTenant', |
| 500 |
aci_rn='tn-{0}'.format(tenant), |
| 501 |
module_object=tenant, |
| 502 |
target_filter={'name': tenant} |
| 503 |
), |
| 504 |
subclass_1=dict( |
| 505 |
aci_class='l3extOut', |
| 506 |
aci_rn='out-{0}'.format(l3out), |
| 507 |
module_object=l3out, |
| 508 |
target_filter={'name': l3out} |
| 509 |
), |
| 510 |
subclass_2=dict( |
| 511 |
aci_class='l3extLNodeP', |
| 512 |
aci_rn='lnodep-{0}'.format(node_profile), |
| 513 |
module_object=node_profile, |
| 514 |
target_filter={'name': node_profile} |
| 515 |
)target_filter={'name': nexthop} |
| 516 |
) |
| 517 |
) |
| 518 |
``` |
| 519 |
|
| 520 |
> [!NOTE] |
| 521 |
> Any requirements/changes for values of arguments (object,object_prop1, etc.) such as conversion to boolean, letter case, or formatting/validating the inputs must be done before the `construct_url()` method is called. This is because the method will use the values as they are passed in the task, and it will not perform any additional validation or conversion. |
| 522 |
|
| 523 |
#### Getting the existing configuration |
| 524 |
|
| 525 |
`aci.get_existing()` This retrieves the current APIC configuration based on the URL built in `construct_url()`. |
| 526 |
|
| 527 |
* `state: present`: retrieves the configuration to use as a comparison against what was entered in the task. All values that are different from the existing values will be updated. |
| 528 |
* `state: absent`: checks existing configuration, if the object exists before deletion. |
| 529 |
* `state: query`: performs the query for the task and report back the existing data. |
| 530 |
|
| 531 |
```python |
| 532 |
aci.get_existing() |
| 533 |
``` |
| 534 |
|
| 535 |
#### When state is present |
| 536 |
|
| 537 |
When `state: present` a diff is performed between the task inputs and the existing configuration. If differences are found, the module sends a POST request to apply changes only the items that need to be updated. This ensures that only the necessary changes are made to the APIC configuration, minimizing disruption and maintaining consistency. |
| 538 |
|
| 539 |
When state is present (executed when Adding an object and Updating an object), the module will: |
| 540 |
1. Build the ACI payload using the `aci.payload()` method. |
| 541 |
2. Perform a diff between the existing configuration and the proposed configuration using the `get_diff()` method. |
| 542 |
3. Send the configuration changes to the APIC using the `post_config()` method. |
| 543 |
|
| 544 |
##### Building the ACI payload |
| 545 |
|
| 546 |
The `aci.payload()` method constructs a dictionary representing the proposed configuration for the ACI object. All parameter that is not provided a value in the task will be removed from the final dictionary — both for the main object and any child objects. Any parameters that do have values will be converted to strings and included in the resulting dictionary used for diff comparison. |
| 547 |
|
| 548 |
* Parameters explicitly set to emptiness such as "" [] or {} based on the attribute type are excluded. |
| 549 |
* If a non-default value already exists in the configuration and is not specified in the task, it will be preserved. For example, if a description is already set and the task omits it, the value will remain unchanged. |
| 550 |
|
| 551 |
If a parameter was introduced in a newer version of the APIC, it should only be added to the payload when it has been assigned a value—this preserves backward compatibility. |
| 552 |
|
| 553 |
**Parameters for `aci.payload()`** |
| 554 |
|
| 555 |
This method accepts two required arguments and one optional argument (if the module handles child objects): |
| 556 |
|
| 557 |
* `aci_class` is the Managed Object (MO) name for the object's class. |
| 558 |
* `class_config` is the set of attributes of the aci class objects to be used as the payload for the POST request |
| 559 |
+ The keys should match the names used by the APIC's MO. |
| 560 |
+ The formatted values should be the values retrieved from `module.params` and modified if necessary to comply with the object model. |
| 561 |
* `child_configs` is optional and is a list of child config dictionaries. |
| 562 |
+ The child configs include the full child object dictionary, not just the attributes configuration portion. |
| 563 |
+ The configuration portion is built the same way as the parent object. |
| 564 |
* `annotation` is an optional string that can be used to add additional information to the object. |
| 565 |
+ If annotation is a supported attribute for a module it will be populated in the payload of that respective module. |
| 566 |
+ By default the value for annotation is set to `orchestrator:ansible` when not set by the users. |
| 567 |
|
| 568 |
|
| 569 |
> [!NOTE] |
| 570 |
> If any part of the class or child configuration depends on other parameter values, it is best to build these configurations ahead of time and then pass them to the aci.payload() function. This ensures the payload passed to aci.payload() is accurate and complete. |
| 571 |
|
| 572 |
##### Performing the request |
| 573 |
|
| 574 |
When state is present, a payload needs to be constructed which will be posted to APIC. Payload takes class_config and child_config. The class_config has the main attributes. If new attributes are added in new versions of APIC, that attribute will be added to class_config only if it is assigned a value. |
| 575 |
|
| 576 |
> [!NOTE] |
| 577 |
> `aci_rn` must **not** contain the DN of the individual class. It is `construct_url()`'s task to build the entire DN leading to the target object using the series of RNs in the root class and the subsequent subclasses. |
| 578 |
|
| 579 |
##### Running the Diff |
| 580 |
|
| 581 |
The `get_diff()` method compares the existing configuration with the new payload and returns a dictionary containing only the attributes that differ. It takes one required argument: |
| 582 |
|
| 583 |
* `aci_class`: The MO name of the object being configured. |
| 584 |
|
| 585 |
Replace `<managed object class>` with the appropriate MO class name for the object being configured. |
| 586 |
|
| 587 |
You may also optionally pass: |
| 588 |
|
| 589 |
* `required_properties` (optional): A dictionary of key-value pairs that should always be included in the resulting configuration, even if they are not part of the detected differences. This ensures critical properties are not inadvertently left out of updates and helps maintain consistent configurations. |
| 590 |
|
| 591 |
This guarantees that key configuration elements are preserved in updates, even when no differences are detected in those fields. |
| 592 |
|
| 593 |
##### Sending the Configuration |
| 594 |
|
| 595 |
* `post_config()` method is used to make the POST request to the APIC by taking the result from `get_diff()`. This method: |
| 596 |
1. Requires no arguments. |
| 597 |
2. Handles check_mode internally. |
| 598 |
|
| 599 |
Example code: |
| 600 |
|
| 601 |
```python |
| 602 |
if state == 'present': |
| 603 |
aci.payload( |
| 604 |
aci_class='<managed object class>', |
| 605 |
class_config=dict( |
| 606 |
name=object_id, |
| 607 |
prop1=object_prop1, |
| 608 |
prop2=object_prop2, |
| 609 |
prop3=object_prop3, |
| 610 |
), |
| 611 |
child_configs=[ |
| 612 |
dict( |
| 613 |
'<child managed object class>'=dict( |
| 614 |
attributes=dict( |
| 615 |
child_key=child_object_id, |
| 616 |
child_prop=child_object_prop |
| 617 |
), |
| 618 |
), |
| 619 |
), |
| 620 |
], |
| 621 |
) |
| 622 |
|
| 623 |
aci.get_diff(aci_class='<managed object class>') |
| 624 |
|
| 625 |
aci.post_config() |
| 626 |
``` |
| 627 |
|
| 628 |
The end of the module does not change and generally remains as is. Therefore, the next sections until the end of the module can be used as it is. |
| 629 |
|
| 630 |
#### When state is absent |
| 631 |
If the task sets the state to absent, then the `delete_config()` method is all that is needed. This method does not take any arguments and handles check mode. |
| 632 |
|
| 633 |
```python |
| 634 |
elif state == 'absent': |
| 635 |
aci.delete_config() |
| 636 |
``` |
| 637 |
|
| 638 |
#### Exiting the module |
| 639 |
To have the module exit, call the ACIModule method `exit_json()`. This method automatically takes care of returning the common return values. |
| 640 |
|
| 641 |
```python |
| 642 |
aci.exit_json() |
| 643 |
|
| 644 |
|
| 645 |
if __name__ == "__main__": |
| 646 |
main() |
| 647 |
``` |
| 648 |
|
| 649 |
**Addition checks to perform after the module is created**: |
| 650 |
* A newline should exist at the end of the file to ensure that the file ends with a newline character, which is a good practice and avoids sanity or black issues. |
| 651 |
* Avoid using whitespaces or tabs at the end of lines, as this can lead to syntax errors or unexpected behavior. |
| 652 |
* If the template from [docs/sample_module/aci_module_template.md](sample_module/aci_module_template.md) was used to create the new module, then remove all the comments in the file, except the copyright section at the top of the file. The comments in the template are only for reference and should not be included in the Pull Request for the new module. |
| 653 |
|
| 654 |
## Testing the Module |
| 655 |
|
| 656 |
Testing a module is crucial to ensure its reliability, correctness, and stability. It verifies that the module functions as intended across various scenarios, prevents regressions from new changes, and helps maintain a high-quality codebase. |
| 657 |
|
| 658 |
Once the module is created, it should be tested using an Ansible playbook. This playbook (main.yml) is added under the collection directory at: |
| 659 |
tests/integration/targets/<aci_module_name>/tasks/. |
| 660 |
The playbook verifies the functionality of the module and ensures it behaves as expected. |
| 661 |
|
| 662 |
The following tets are the performed on the module: |
| 663 |
|
| 664 |
* **Integration Test**: These tests validate the end-to-end functionality of the module within its intended environment, ensuring it interacts correctly with external systems like the APIC. They confirm that the module's code paths work as expected in a real-world scenario. |
| 665 |
* **Sanity Test**: Sanity tests check if the module adheres to coding standards and basic functionality across different Python and Ansible versions. They act as a quick health check to ensure fundamental aspects like documentation support and syntax are correct. |
| 666 |
* **Coverage Report**: This report identifies which parts of the module's code are executed by tests and which are not. It helps developers pinpoint untested areas, guiding them to write more comprehensive tests to improve code quality and reduce potential bugs. |
| 667 |
|
| 668 |
> For complete guidelines on how to write the playbook to test the module, refer to [Testing the modules documentation](testing_aci_modules.md). |
| 669 |
|
| 670 |
### Additional checks before making a Pull Request |
| 671 |
|
| 672 |
Before making a pull request, ensure that the following checks are performed: |
| 673 |
1. The module is tested (Integration test, Sanity test, Black formatting). |
| 674 |
2. The module has the necessary code coverage. |
| 675 |
3. The commit message is **clear and concise**, following the [Ansible commit message guidelines](https://docs.ansible.com/ansible/latest/dev_guide/developing_modules_general.html#commit-message-guidelines). |
| 676 |
* The commit message should always begin with `<commit_type>`, this helps in categorizing the changes made in the module. |
| 677 |
* The commit message must always end with the name of the module or playbook or docs that the changes are related to. |
| 678 |
* Example: "`[<commit_type>]` Short description of the changes for the `aci_<ACI module name>` module." |
| 679 |
|
| 680 |
|
| 681 |
> The `<commit_type>` can be one of the following: |
| 682 |
> * `[minor_change]`: For adding small features or capabilities (e.g., adding a new module or attributes to an existing module) |
| 683 |
> * `[major_change]`: For changes made in the module which affects the existing behavior(breaking changes). (e.g., changes requiring testing the playbook or module updates) |
| 684 |
> * `[bugfix]`: For fixing bugs in the module (typically very small changes that don't add new functionality) |
| 685 |
> * `[ignore]`: For commits after the that do not affect the current test cases such as, code style changes, whitespace, typos, or documentation. |
| 686 |
|
| 687 |
> [!IMPORTANT] |
| 688 |
> It is recommended to make small PRs to ensure easier review and integration. |
| 689 |
|
| 690 |
|
| 691 |
**Note**: |
| 692 |
|
| 693 |
* [ACI Fundamentals: ACI Policy Model](https://www.cisco.com/c/en/us/td/docs/switches/datacenter/aci/apic/sw/1-x/aci-fundamentals/b_ACI-Fundamentals/b_ACI-Fundamentals_chapter_010001.html) |
| 694 |
A good introduction to the ACI object model. |
| 695 |
* [APIC Management Information Model reference](https://developer.cisco.com/docs/apic-mim-ref/) |
| 696 |
Complete reference of the APIC object model. |
| 697 |
* [APIC REST API Configuration Guide](https://www.cisco.com/c/en/us/td/docs/switches/datacenter/aci/apic/sw/2-x/rest_cfg/2_1_x/b_Cisco_APIC_REST_API_Configuration_Guide.html) |
| 698 |
Detailed guide on how the APIC REST API is designed and used, including many examples. |
| 699 |
|