diff --git a/netbox/netbox.py b/netbox/netbox.py index 88394df..9e50863 100755 --- a/netbox/netbox.py +++ b/netbox/netbox.py @@ -80,6 +80,7 @@ def __init__(self, script_args, script_config_data): self.script_config = script_config_data self.api_url = self._config(["main", "api_url"]) self.group_by = self._config(["group_by"], default={}) + self.filters = self._config(["filters"], default={}) self.hosts_vars = self._config(["hosts_vars"], default={}) # Get value based on key. @@ -150,7 +151,7 @@ def _config(self, key_path, default=""): return key_value @staticmethod - def get_hosts_list(api_url, specific_host=None): + def get_hosts_list(api_url, specific_host=None, filters=None): """Retrieves hosts list from netbox API. Returns: @@ -161,9 +162,15 @@ def get_hosts_list(api_url, specific_host=None): sys.exit("Please check API URL in script configuration file.") if specific_host: - api_url_params = {"name": specific_host} + api_url_params = "name=%s&" % specific_host else: - api_url_params = {} + api_url_params = "" + + # Add filters provided into the URL + if filters: + for filter in filters: + for key,value in filter.items(): + api_url_params += "%s=%s&" % (key, value) # Get hosts list. hosts_list = requests.get(api_url, params=api_url_params) @@ -318,7 +325,7 @@ def generate_inventory(self): """ inventory_dict = dict() - netbox_hosts_list = self.get_hosts_list(self.api_url, self.host) + netbox_hosts_list = self.get_hosts_list(self.api_url, self.host, self.filters) if isinstance(netbox_hosts_list, dict) and "results" in netbox_hosts_list: netbox_hosts_list = netbox_hosts_list["results"] diff --git a/netbox/netbox.yml b/netbox/netbox.yml index ad5a7ec..ac7073c 100644 --- a/netbox/netbox.yml +++ b/netbox/netbox.yml @@ -14,6 +14,11 @@ netbox: #custom: # - env + # Add filters to limit the list of host that will be returned + # All parameters valid for the API (GET /api/dcim/devices/) are accepted + filters: + # - site: dc1 + # Use Netbox sections as host variables. hosts_vars: # Sections related to IPs e.g. "primary_ip" or "primary_ip4". diff --git a/tests/test_netbox.py b/tests/test_netbox.py index ab1ea8a..86ff0ae 100644 --- a/tests/test_netbox.py +++ b/tests/test_netbox.py @@ -47,6 +47,11 @@ #custom: # - env + # Add filters to limit the list of host that will be returned + # All parameters valid for the API (GET /api/dcim/devices/) are accepted + filters: + - site: dc1 + # Use Netbox sections as host variables. hosts_vars: # Sections related to IPs e.g. "primary_ip" or "primary_ip4".