summaryrefslogtreecommitdiffstats
path: root/bin/rolesyncer.py
blob: 4761e42abd61e86c99ea21acabf444367dd39cc0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/usr/bin/python3

import os
import pynetbox
import roles

if not 'NB_HOST' in os.environ or not 'NB_TOKEN' in os.environ:
    print('Pass NB_HOST and NB_TOKEN as environment variables.')
    import sys
    sys.exit(1)

host = os.environ['NB_HOST']
token = os.environ['NB_TOKEN']

# unlikely to ever change, hence hardcoding the field_id. otherwise we could filter custom_fields for the name 'salt_roles'.
field_id = 1

def connect(host, token):
    netbox = pynetbox.api(host, token)
    return(netbox)

def query_nb(netbox, pk):
    try:
        field = netbox.extras.custom_fields.get(pk)
    except pynetbox.RequestError as myerr:
        if myerr.req_status_code == 404:
            print('Custom field not found')
        raise
    return(field)

def get_nb(field):
    choices = field.choices
    if not choices:
        return(None)
    if len(choices) > 0:
        return(choices)

def get_local():
    return(roles.get())

def compare(a, b):
    a.sort()
    b.sort()
    if a == b:
        return(True)
    if a != b:
        return(False)

def write_nb(field, roles):
    field.choices = roles
    try:
        if field.save():
            print('Update complete')
        else:
            print('Nothing to update')
    except:
        raise

def sync(netbox):
    field = query_nb(netbox, field_id)
    roles_local = get_local()
    roles_nb = get_nb(field)

    if roles_nb is None:
        print('Roles in NetBox are currently empty')

    is_synced = compare(roles_local, roles_nb)

    if is_synced:
        print('Roles already in sync')
    if not is_synced:
        print('Writing local roles to NetBox ...')
        write_nb(field, roles_local)

if __name__ == '__main__':
    netbox = connect(host, token)
    sync(netbox)