diff --git a/modules/certmanager/certificate.go b/modules/certmanager/certificate.go index 9c589e7c..110e6532 100644 --- a/modules/certmanager/certificate.go +++ b/modules/certmanager/certificate.go @@ -25,6 +25,8 @@ 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/tls" "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 +233,53 @@ func EnsureCert( return certSecret, ctrl.Result{}, nil } + +// EnsureCertForServiceWithSelector - creates certificate for k8s service identified +// by a label selector +func EnsureCertForServiceWithSelector( + ctx context.Context, + helper *helper.Helper, + namespace string, + selector map[string]string, + issuer string, +) (tls.SimpleService, ctrl.Result, error) { + t := tls.SimpleService{ + Ca: tls.Ca{ + CaBundleSecretName: tls.CABundleSecret, + }, + } + + svcs, err := service.GetServicesListWithLabel( + ctx, + helper, + namespace, + selector, + ) + if err != nil { + return t, 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 t, ctrlResult, err + } else if (ctrlResult != ctrl.Result{}) { + return t, ctrlResult, nil + } + + t.SecretName = &certSecret.Name + break + } + + return t, ctrl.Result{}, nil +}