-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget_contacts_openshift.py
More file actions
104 lines (99 loc) · 5.17 KB
/
get_contacts_openshift.py
File metadata and controls
104 lines (99 loc) · 5.17 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
########################
### Import libraries ###
########################
from kubernetes import client, config, dynamic
from openshift.dynamic import DynamicClient
from openshift.helper.userpassauth import OCPLoginConfiguration
import urllib3
urllib3.disable_warnings()
from ldap3 import Server, Connection, SAFE_SYNC
import yaml
########################################
### Authenticate against OCP Cluster ###
########################################
with open('/var/run/secrets/kubernetes.io/serviceaccount/token', 'r') as f:
token = f.readline().strip()
token_auth = dict(
api_key={'authorization': 'Bearer {}'.format(token)},
host='https://<>:443', # <--- Set OCP host here
verify_ssl=False
)
configuration = client.Configuration()
for k, v in token_auth.items():
setattr(configuration, k, v)
k8s_client = client.ApiClient(configuration)
dyn_client = DynamicClient(k8s_client)
###################################################################
########################## Begin Code #############################
###################################################################
####################
### Get Projects ###
####################
v1_projects = dyn_client.resources.get(api_version='project.openshift.io/v1', kind='Project')
project_list = v1_projects.get()
########################################################################################
### Loop through Projects to get Owner, Requester or User from the Admin RoleBinding ###
########################################################################################
for project in project_list.items:
project_name = project.metadata.name
owner = project.metadata.annotations.owner
contact = owner
##############################
### Define namespace patch ###
##############################
#################################################
### If there's no Owner, search for Requester ###
#################################################
if owner == None:
try:
requester = project.metadata.annotations["openshift.io/requester"]
contact = requester
######################################################################################
### If there's no Owner or Requester, search for a User from the Admin RoleBinding ###
######################################################################################
if requester == None:
admin = dyn_client.resources.get(api_version='rbac.authorization.k8s.io/v1', kind='RoleBinding')
admin_admin = admin.get(name='admin', namespace=project_name)
admin_name = admin_admin.subjects[0].name
contact = admin_name
#########################################################################
### If there's no Owner, Requester or Admin, assigh "None" to Contact ###
#########################################################################
### If no info is found, assign None ###
except:
contact = None
#####################################################
### If a user is found, query LDAP for the e-mail ###
#####################################################
if contact != None:
server=Server('<>') # <--- Insert LDAP server here
conn=Connection(server, '<user>', '<password>', client_strategy=SAFE_SYNC, auto_bind=True) # <--- Insert LDAP user/password here
status, result, response, _ = conn.search('OU=<>,DC=<>,DC=<>', f'(sAMAccountName={contact})', attributes='mail') # <--- Set OU, DC
#res = response_str[0]["attributes"]["mail"]
if len(response) > 0:
### print(response[0]["attributes"]["mail"]) to get only the e-mail ###
response_cast = response[0]["attributes"]["mail"].replace("@","__at__").replace(";","-") # <--- Switch @ for __at__ as special chars are not allowed!
print(f"Project Name: {project_name} Owner Name: {contact} Contact Email: {response_cast}")
### Update the Namespace Label
v1_namespace = dyn_client.resources.get(api_version='v1', kind='Namespace')
project_update = f"""
kind: Namespace
apiVersion: v1
metadata:
labels:
contact: {response_cast}
"""
config = yaml.safe_load(project_update)
print(f"E-mail found, cheking if namespace {project_name} has contact information")
existing_contact = project.metadata.labels["contact"]
while not existing_contact:
print(f"No contact information found, assigning {response_cast}")
v1_namespace.patch(body=config, name=project_name)
break
else:
print(f"Contact information found, skipping...")
else:
print(f"Project Name: {project_name} Owner Name: {contact} Contact Email: None")
####################################################################
############################ End Code ##############################
####################################################################