diff --git a/modules/certmanager/certificate.go b/modules/certmanager/certificate.go index 9c589e7c..4beaf1b8 100644 --- a/modules/certmanager/certificate.go +++ b/modules/certmanager/certificate.go @@ -25,6 +25,7 @@ import ( certmgrmetav1 "github.com/cert-manager/cert-manager/pkg/apis/meta/v1" "github.com/openstack-k8s-operators/lib-common/modules/common/helper" "github.com/openstack-k8s-operators/lib-common/modules/common/secret" + "github.com/openstack-k8s-operators/lib-common/modules/common/service" "github.com/openstack-k8s-operators/lib-common/modules/common/util" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" @@ -231,3 +232,49 @@ func EnsureCert( return certSecret, ctrl.Result{}, nil } + +// EnsureCertForServiceWithSelector - creates certificate for k8s service identified +// by a label selector +// Note: the expectation is that the selector receives a single k8s service object. +func EnsureCertForServiceWithSelector( + ctx context.Context, + helper *helper.Helper, + namespace string, + selector map[string]string, + issuer string, +) (string, ctrl.Result, error) { + secretName := "" + svcs, err := service.GetServicesListWithLabel( + ctx, + helper, + namespace, + selector, + ) + if err != nil { + return secretName, ctrl.Result{}, err + } + + for _, svc := range svcs.Items { + // create cert for the service + certRequest := CertificateRequest{ + IssuerName: issuer, + CertName: fmt.Sprintf("%s-svc", svc.Name), + Hostnames: []string{fmt.Sprintf("%s.%s.svc", svc.Name, namespace)}, + Labels: svc.Labels, + } + certSecret, ctrlResult, err := EnsureCert( + ctx, + helper, + certRequest) + if err != nil { + return secretName, ctrlResult, err + } else if (ctrlResult != ctrl.Result{}) { + return secretName, ctrlResult, nil + } + + secretName = certSecret.Name + break + } + + return secretName, ctrl.Result{}, nil +}