Cleaning up sqlserver_controller.go
@@ -29,8 +29,12 @@ import (
"k8s.io/client-go/tools/record"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
+ "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
azurev1 "github.com/Azure/azure-service-operator/api/v1"
+ v1 "k8s.io/api/core/v1"
+ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ "k8s.io/apimachinery/pkg/types"
)
// SqlServerReconciler reconciles a SqlServer object
@@ -136,6 +140,57 @@ func (r *SqlServerReconciler) reconcileExternal(instance *azurev1.SqlServer) err
AdministratorLoginPassword: to.StringPtr("generate_me_1234"),
}
+ // Check to see if secret already exists for admin username/password
+ var checkForSecretsErr error
+ secret := &v1.Secret{}
+
+ checkForSecretsErr = r.Get(context.Background(), types.NamespacedName{Name: name, Namespace: instance.Namespace}, secret)
+
+ // If secret doesn't exist, generate creds
+ // Note: sql server enforces password policy. Details can be found here:
+ // https://docs.microsoft.com/en-us/sql/relational-databases/security/password-policy?view=sql-server-2017
+ if checkForSecretsErr != nil {
+ r.Log.Info("secret did not exist, generating creds now")
+ sqlServerProperties.AdministratorLogin = to.StringPtr(generateRandomString(8))
+ sqlServerProperties.AdministratorLoginPassword = to.StringPtr(generateRandomString(16))
+ } else {
+ r.Log.Info("secret already exists, pulling creds now")
+ sqlServerProperties.AdministratorLogin = to.StringPtr(string(secret.Data["username"]))
+ sqlServerProperties.AdministratorLoginPassword = to.StringPtr(string(secret.Data["password"]))
+ }
+
+ csecret := &v1.Secret{
+ TypeMeta: metav1.TypeMeta{
+ Kind: "Secret",
+ APIVersion: "apps/v1beta1",
+ },
+ ObjectMeta: metav1.ObjectMeta{
+ Name: name,
+ Namespace: instance.Namespace,
+ },
+ Data: map[string][]byte{
+ "username": []byte(*sqlServerProperties.AdministratorLogin),
+ "password": []byte(*sqlServerProperties.AdministratorLoginPassword),
+ "sqlservernamespace": []byte(instance.Namespace),
+ "sqlservername": []byte(name),
+ },
+ Type: "Opaque",
+ }
+
+ _, createOrUpdateSecretErr := controllerutil.CreateOrUpdate(context.Background(), r.Client, csecret, func() error {
+ r.Log.Info("mutating secret bundle")
+ innerErr := controllerutil.SetControllerReference(instance, csecret, r.Scheme)
+ if innerErr != nil {
+ return innerErr
+ }
+ return nil
+ })
+
+ if createOrUpdateSecretErr != nil {
+ return createOrUpdateSecretErr
+ }
+
+ // create the sql server
instance.Status.Provisioning = true
_, err := sdkClient.CreateOrUpdateSQLServer(sqlServerProperties)
if err != nil {
