-
Notifications
You must be signed in to change notification settings - Fork 887
/
clusterrole.go
78 lines (66 loc) · 2.56 KB
/
clusterrole.go
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
package util
import (
"fmt"
rbacv1 "k8s.io/api/rbac/v1"
kubeclient "k8s.io/client-go/kubernetes"
"k8s.io/klog/v2"
)
// EnsureClusterRoleExist makes sure that the specific cluster role exist in cluster.
// If cluster role not exit, just create it.
func EnsureClusterRoleExist(client kubeclient.Interface, clusterRole *rbacv1.ClusterRole, dryRun bool) (*rbacv1.ClusterRole, error) {
if dryRun {
return clusterRole, nil
}
exist, err := IsClusterRoleExist(client, clusterRole.Name)
if err != nil {
return nil, fmt.Errorf("failed to check if ClusterRole exist. ClusterRole: %s, error: %v", clusterRole.Name, err)
}
if exist {
klog.V(1).Infof("Ensure ClusterRole succeed as already exist. ClusterRole: %s", clusterRole.Name)
return clusterRole, nil
}
createdObj, err := CreateClusterRole(client, clusterRole)
if err != nil {
return nil, fmt.Errorf("ensure ClusterRole failed due to create failed. ClusterRole: %s, error: %v", clusterRole.Name, err)
}
return createdObj, nil
}
// EnsureClusterRoleBindingExist makes sure that the specific ClusterRoleBinding exist in cluster.
// If ClusterRoleBinding not exit, just create it.
func EnsureClusterRoleBindingExist(client kubeclient.Interface, clusterRoleBinding *rbacv1.ClusterRoleBinding, dryRun bool) (*rbacv1.ClusterRoleBinding, error) {
if dryRun {
return clusterRoleBinding, nil
}
exist, err := IsClusterRoleBindingExist(client, clusterRoleBinding.Name)
if err != nil {
return nil, fmt.Errorf("failed to check if ClusterRole exist. ClusterRole: %s, error: %v", clusterRoleBinding.Name, err)
}
if exist {
klog.V(1).Infof("Ensure ClusterRole succeed as already exist. ClusterRole: %s", clusterRoleBinding.Name)
return clusterRoleBinding, nil
}
createdObj, err := CreateClusterRoleBinding(client, clusterRoleBinding)
if err != nil {
return nil, fmt.Errorf("ensure ClusterRole failed due to create failed. ClusterRole: %s, error: %v", clusterRoleBinding.Name, err)
}
return createdObj, nil
}
// BuildRoleBindingSubjects will generate a subject as per service account.
// The subject used by RoleBinding or ClusterRoleBinding.
func BuildRoleBindingSubjects(serviceAccountName, serviceAccountNamespace string) []rbacv1.Subject {
return []rbacv1.Subject{
{
Kind: rbacv1.ServiceAccountKind,
Name: serviceAccountName,
Namespace: serviceAccountNamespace,
},
}
}
// BuildClusterRoleReference will generate a ClusterRole reference.
func BuildClusterRoleReference(roleName string) rbacv1.RoleRef {
return rbacv1.RoleRef{
APIGroup: rbacv1.GroupName,
Kind: "ClusterRole",
Name: roleName,
}
}