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
|
"""
Database model for application
"""
from flask_sqlalchemy import SQLAlchemy
import requests
import yaml
db = SQLAlchemy()
host_classes = db.Table('host_classes',
db.Column('host_id', db.ForeignKey('host.id')),
db.Column('class_id', db.ForeignKey('puppet_class.id')))
# class HostClasses(db.Model):
# __tablename__ = 'host_classes'
# id = db.Column(db.Integer, primary_key=True)
# host_id = db.Column(db.Integer, db.ForeignKey('host.id'), nullable=False)
# class_id = db.Column(db.Integer, db.ForeignKey('puppet_class.id'), nullable=False)
class Host(db.Model):
__tablename__ = 'host'
id = db.Column(db.Integer, primary_key=True)
fqdn = db.Column(db.Text, nullable=False)
environment = db.Column(db.Text)
# classes = db.relationship('HostClasses', backref='host', lazy='dynamic')
classes = db.relationship('PuppetClass',
back_populates='hosts',
secondary=host_classes)
def serialize(self):
return { column.name: self.__getattribute__(column.name)
for column in self.__table__.columns }
class PuppetClass(db.Model):
__tablename__ = 'puppet_class'
id = db.Column(db.Integer, primary_key=True)
class_name = db.Column(db.Text, nullable=False)
source_file = db.Column(db.Text)
hosts = db.relationship('Host',
back_populates='classes',
secondary=host_classes)
##################################################
# Everything below should be removed
def import_from_puppetdb():
payload = {'query': 'nodes {}'}
r = requests.post('http://busting.adrift.space:8080/pdb/query/v4',
data=json.dumps(payload))
for item in r.json():
db.session.add(
Host(fqdn=item['certname'],
environment=item['catalog_environment']))
db.session.commit()
def import_more():
with open('/usr/local/puppet/nodes.yaml') as f:
data = yaml.full_load(f)
for fqdn, val in data.items():
h = Host.query.where(Host.fqdn==fqdn).first()
print(h)
if not h: continue
# print(h)
classes = data[h.fqdn]['classes']
if type(classes) == dict:
classes = classes.keys()
cls = PuppetClass.query.where(PuppetClass.class_name.in_(classes)).all()
print(cls)
for c in cls:
h.classes.append(c)
db.session.commit()
|