Get config context for device

811 views
Skip to first unread message

Christian Strauf

unread,
Feb 16, 2021, 10:26:04 AM2/16/21
to NetBox
Hi all!

I've started programming a custom script today. I love it so far, I already scripted adding switch devices etc. However, I'm struggling with getting the config context for a device in a custom script. We store certain information for Ansible in config contexts and I need one piece of information in the config context to modify an interface on a switch. Via API it's quite easy because the config contexts can be access easily but I don't seem to find how to get it within the custom script. I've written an example script to illustrate what I want to do:

--------8<--------8<--------8<--------8<--------
[... left out the imports ...]

class GetConfigContext(Script):

class Meta:
name = "Get switch config context"
description = "Get the config context of a switch in NetBox"

switch = ObjectVar(
model=Device,
required=True,
query_params={
'role': 'switch'
}
)

def run(self, data, commit):
# Basically at this point I have a switch object as "data['switch'] and I'd like to simply print its config context in JSON format.
return data['switch']# this is where I have no clue. :)
--------8<--------8<--------8<--------8<--------

Could you give me some advice how to access the JSON config context? I've been looking through NetBox's model definitions in the source code but I wasn't able to find a solution. Thanks!

Christian

Brian Candler

unread,
Feb 16, 2021, 10:52:22 AM2/16/21
to NetBox
Device inherits from ConfigContextModel:

class Device(ChangeLoggedModel, ConfigContextModel, CustomFieldModel):

and you can see what that means here:

Hence:
- local_context_data is the database attribute containing config context data set directly on the device itself
- get_config_context() calculates the overall config context data for this device, including values inherited from regions, sites, roles etc.

Christian Strauf

unread,
Feb 17, 2021, 1:57:24 AM2/17/21
to Brian Candler, NetBox
Hi Brian!

> Hence:
> - local_context_data is the database attribute containing config context data set directly on the device itself
> - get_config_context() calculates the overall config context data for this device, including values inherited from regions, sites, roles etc.
Thank you very much for your help, that was exactly what I was looking for. :)

Christian

Reply all
Reply to author
Forward
0 new messages