Skip to content

Commit 3d98921

Browse files
Updated README (#44)
1 parent 6fcf178 commit 3d98921

File tree

2 files changed

+351
-267
lines changed

2 files changed

+351
-267
lines changed

CONTRIBUTING.md

Lines changed: 274 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,274 @@
1+
# Contributing
2+
3+
The structure of the Netbox modules attempts to follow the layout of the Netbox API by having a module_util for each application (`dcim, ipam, tenancy, etc`) that inherits from a base module (`NetboxModule - netbox_utils.py`) and then implements the specific endpoints within the correct application module.
4+
5+
e.g. Add logic for adding devices under netbox_dcim.py or ip addresses under netbox_ipam.py
6+
7+
In turn when creating the actual modules, we're just calling a single function and passing in the Ansible Module and the endpoint. This means all the logic is within the specific application's module_util module and a lot of the logic should be the same for most endpoints since it is a basic operation of using the desired state of the endpoint and then either making sure it exists, updating it if it does exist, or removing it. There may be some special logic for other endpoints, but it should be minimal.
8+
9+
(Ansible Module) netbox_{{ endpoint }} -> (Module Util) netbox_{{ application }} -> (Module Util) netbox_utils
10+
11+
These modules are built using the pynetbox Python library which allows you to interact with Netbox using objects. Most of this is abstracted away when creating more modules, but something to be aware of. The reasoning for using underscores within the endpoint names is so the endpoints work with pynetbox.
12+
13+
An example of connecting to a Netbox instance and then choosing the application, endpoint, and operation:
14+
15+
```python
16+
import pynetbox
17+
18+
nb = pynetbox.api("http://localhost:32768", "0123456789abcdef0123456789abcdef01234567")
19+
20+
# applications
21+
nb.circuits
22+
nb.dcim
23+
nb.extras
24+
nb.ipam
25+
nb.secrets
26+
nb.tenancy
27+
nb.virtualization
28+
29+
# endpoints (small sample)
30+
nb.circuits.providers
31+
nb.dcim.devices
32+
nb.dcim.device_types
33+
nb.ipam.vrfs
34+
nb.ipam.ip_addresses
35+
nb.tenancy.tenant_groups
36+
37+
# operations
38+
## Grabs a list of all endpoints
39+
nb.dcim.devices.**all**
40+
## Can pass a list of dicts to create multiple of the endpoints or just a dict to create a single endpoint
41+
nb.dcim.devices.**create**
42+
## Can filter to grab a name of the endpoint being filtered, not an object (Uses the same search criteria as the API)
43+
nb.dcim.devices.**filter**
44+
e.g. nb.dcim.devices.filter(name="test")
45+
## Will retrieve the actual object that can be manipulated (updated, etc.) (Uses the same search criteria as the API)
46+
nb.dcim.devices.**get**
47+
e.g. nb.dcim.devices.get(name="test")
48+
49+
# Manipulate object after using .get
50+
## Now you can manipulate the object the same as a Python object
51+
device = nb.dcim.devices.get(name="test")
52+
device.description = "Test Description"
53+
## Patch operation (patches the data to the API)
54+
device.save()
55+
56+
## If you were to just update the data in a fell swoop
57+
serial = {"serial": "FXS10001", "description": "Test Description"}
58+
## this operation will update the device and use the .save() method behind the scenes
59+
device.update(serial)
60+
```
61+
62+
## Adding an Endpoint
63+
64+
### Updating Variables within Module Utils
65+
66+
First thing is to setup several variables within **netbox_utils** and **netbox_application** module utils:
67+
68+
Check the following variable to make sure the endpoint is within the correct application within **netbox_utils**:
69+
70+
```python
71+
API_APPS_ENDPOINTS = dict(
72+
circuits=[],
73+
dcim=[
74+
"devices",
75+
"device_roles",
76+
"device_types",
77+
"interfaces",
78+
"manufacturers",
79+
"platforms",
80+
"racks",
81+
"rack_groups",
82+
"rack_roles",
83+
"regions",
84+
"sites",
85+
],
86+
extras=[],
87+
ipam=["ip_addresses", "prefixes", "roles", "vlans", "vlan_groups", "vrfs"],
88+
secrets=[],
89+
tenancy=["tenants", "tenant_groups"],
90+
virtualization=["clusters"],
91+
)
92+
```
93+
94+
Create a new variable in the **netbox_application** module until that matches the endpoint with any spaces being converted to underscores and all lowercase:
95+
96+
```python
97+
NB_DEVICE_TYPES = "device_types"
98+
```
99+
100+
Add the endpoint to the **run** method of supported endpoints:
101+
102+
```python
103+
class NetboxDcimModule(NetboxModule):
104+
def __init__(self, module, endpoint):
105+
super().__init__(module, endpoint)
106+
107+
def run(self):
108+
"""
109+
This function should have all necessary code for endpoints within the application
110+
to create/update/delete the endpoint objects
111+
Supported endpoints:
112+
- device_types
113+
```
114+
115+
Add the endpoint to the **ENDPOINT_NAME_MAPPING** variable within the **netbox_utils** module util.
116+
117+
```python
118+
ENDPOINT_NAME_MAPPING = {
119+
"device_types": "device_type",
120+
}
121+
```
122+
123+
Log into your Netbox instance and navigate to `/api/docs` and searching for the **POST** documents for the given endpoint you're looking to create.
124+
![POST Results](docs/media/postresults.PNG)
125+
The module should implement all available fields that are not the **id** or **readOnly** such as the **created, last_updated, device_count** in the example above.
126+
127+
Add the endpoint to the **ALLOWED_QUERY_PARAMS** variable within the **netbox_utils** module util. This should be something unique for the endpoint and will be used within the **_build_query_params** method to dynamically build query params.
128+
129+
```python
130+
ALLOWED_QUERY_PARAMS = {
131+
"device_type": set(["slug"]),
132+
}
133+
```
134+
135+
If the endpoint has a key that uses an **Array**, you will need to check the **_choices** of the application the endpoint is in and build those into **netbox_utils** module util.
136+
137+
```python
138+
SUBDEVICE_ROLES = dict(parent=True, child=False)
139+
140+
REQUIRED_ID_FIND = {
141+
"device_types": [{"subdevice_role": SUBDEVICE_ROLES}],
142+
}
143+
# This is the method that uses the REQUIRED_ID_FIND variable (no change should be required within the method)
144+
def _change_choices_id(self, endpoint, data):
145+
"""Used to change data that is static and under _choices for the application.
146+
e.g. DEVICE_STATUS
147+
:returns data (dict): Returns the user defined data back with updated fields for _choices
148+
:params endpoint (str): The endpoint that will be used for mapping to required _choices
149+
:params data (dict): User defined data passed into the module
150+
"""
151+
if REQUIRED_ID_FIND.get(endpoint):
152+
required_choices = REQUIRED_ID_FIND[endpoint]
153+
for choice in required_choices:
154+
for key, value in choice.items():
155+
if data.get(key):
156+
try:
157+
data[key] = value[data[key].lower()]
158+
except KeyError:
159+
self._handle_errors(
160+
msg="%s may not be a valid choice. If it is valid, please submit bug report."
161+
% (key)
162+
)
163+
164+
return data
165+
```
166+
167+
If the key is something that pertains to a different endpoint such as **manufacturer** it will need to be added to a few variables within **netbox_utils**.
168+
169+
```python
170+
CONVERT_TO_ID = dict(
171+
manufacturer="manufacturers",
172+
)
173+
QUERY_TYPES = dict(
174+
manufacturer="slug",
175+
)
176+
```
177+
178+
If **slug** and **name** is required, we should leave **slug** out as an option within the module docs and generate it dynamically. Add the endpoint to **SLUG_REQUIRED** within **netbox_utils** module util.
179+
180+
```python
181+
SLUG_REQUIRED = {
182+
"device_roles",
183+
"ipam_roles",
184+
"rack_groups",
185+
"rack_roles",
186+
"roles",
187+
"manufacturers",
188+
"platforms",
189+
"vlan_groups",
190+
}
191+
```
192+
193+
Add code to the **netbox_application** module util to convert name to **slug**"
194+
195+
```python
196+
if self.endpoint in SLUG_REQUIRED:
197+
if not data.get("slug"):
198+
data["slug"] = self._to_slug(name)
199+
```
200+
201+
If either **role** or **group** are within the acceptable keys to POST to the endpoint, we should prefix it with the endpoint name. This is to prevent the code from trying to fetch an ID from the wrong endpoint.
202+
Add the new key to **CONVERT_KEYS** within **netbox_utils** module util.
203+
204+
```python
205+
CONVERT_KEYS = {
206+
"prefix_role": "role",
207+
"rack_group": "group",
208+
"rack_role": "role",
209+
"tenant_group": "group",
210+
"vlan_role": "role",
211+
"vlan_group": "group",
212+
}
213+
214+
# Adding the method that uses this code (no change should be required within the method)
215+
def _convert_identical_keys(self, data):
216+
"""
217+
Used to change non-clashing keys for each module into identical keys that are required
218+
to be passed to pynetbox
219+
ex. rack_role back into role to pass to Netbox
220+
Returns data
221+
:params data (dict): Data dictionary after _find_ids method ran
222+
"""
223+
for key in data:
224+
if key in CONVERT_KEYS:
225+
new_key = CONVERT_KEYS[key]
226+
value = data.pop(key)
227+
data[new_key] = value
228+
229+
return data
230+
```
231+
232+
#### Creating **netbox_endpoint** Module
233+
234+
Copying an existing module that has close to the same options is typically the path to least resistence and then updating portions of it to fit the new module.
235+
236+
- Change the author: `Copyright: (c) 2018, Mikhail Yohman (@FragmentedPacket) <mikhail.yohman@gmail.com>`
237+
- Update the **DOCUMENTATION**/**EXAMPLES**/**RETURN** string with the necessary information
238+
- Main things are module, descriptions, author, version and the sub options under data
239+
- The **RETURN** should return the singluar of the endpoint name (done dynamically, but needs to be documented correctly)
240+
- Update the module_util, module, and endpoint variable for the endpoint
241+
242+
```python
243+
from ansible_collections.fragmentedpacket.netbox_modules.plugins.module_utils.netbox_dcim import (
244+
NetboxDcimModule,
245+
NB_DEVICE_ROLES,
246+
)
247+
```
248+
249+
- Update the **main()** as necessary:
250+
251+
```python
252+
# Add if name is required or change to match required fields
253+
if not module.params["data"].get("name"):
254+
module.fail_json(msg="missing name")
255+
# Make sure the objects are endpoint name and the correct class and variable are being called for the endpoint
256+
netbox_device_role = NetboxDcimModule(module, NB_DEVICE_ROLES)
257+
netbox_device_role.run()
258+
```
259+
260+
#### Testing
261+
262+
- Please update `tests/unit/module_utils/test_netbox_base_class.py` if editing anything within the base class that needs to be tested. This will most likely be needed as there are a few unit tests that test the data of **ALLOWED_QUERY_PARAMS**, etc.
263+
264+
```python
265+
def test_normalize_data_returns_correct_data()
266+
def test_find_app_returns_valid_app()
267+
def test_change_choices_id()
268+
def test_build_query_params_no_child()
269+
def test_build_query_params_child()
270+
```
271+
272+
- Please add or update an existing play to test the new Netbox module for integration testing within `tests/integration/integration-tests.yml`. Make sure to test creation, duplicate, update (if possible), and deletion along with any other conditions that may want to be tested.
273+
- Run `black .` within the base directory for black formatting as it's required for tests to pass
274+
- Check necessary dependencies defined within `.travis.yml` for now if you're wanting to test locally

0 commit comments

Comments
 (0)