diff --git a/controllers/async_controller.go b/controllers/async_controller.go index 87900cbb369..ea0f2d7256d 100644 --- a/controllers/async_controller.go +++ b/controllers/async_controller.go @@ -10,6 +10,7 @@ import ( "time" "github.com/Azure/azure-service-operator/pkg/resourcemanager" + "github.com/Azure/azure-service-operator/pkg/resourcemanager/config" "github.com/Azure/azure-service-operator/pkg/secrets" keyvaultsecretlib "github.com/Azure/azure-service-operator/pkg/secrets/keyvault" telemetry "github.com/Azure/azure-service-operator/pkg/telemetry" @@ -75,7 +76,7 @@ func (r *AsyncReconciler) Reconcile(req ctrl.Request, obj runtime.Object) (resul if len(KeyVaultName) != 0 { // Instantiate the KeyVault Secret Client - keyvaultSecretClient = keyvaultsecretlib.New(KeyVaultName) + keyvaultSecretClient = keyvaultsecretlib.New(KeyVaultName, config.GlobalCredentials()) r.Telemetry.LogInfoByInstance("status", "ensuring vault", req.String()) diff --git a/controllers/azuresql_combined_test.go b/controllers/azuresql_combined_test.go index 76fcbecb000..e3a9380620b 100644 --- a/controllers/azuresql_combined_test.go +++ b/controllers/azuresql_combined_test.go @@ -16,6 +16,7 @@ import ( "github.com/stretchr/testify/assert" helpers "github.com/Azure/azure-service-operator/pkg/helpers" + "github.com/Azure/azure-service-operator/pkg/resourcemanager/config" kvsecrets "github.com/Azure/azure-service-operator/pkg/secrets/keyvault" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" @@ -300,7 +301,7 @@ func TestAzureSqlServerCombinedHappyPath(t *testing.T) { EnsureInstance(ctx, t, tc, kvSqlUser1) // Check that the user's secret is in the keyvault - keyVaultSecretClient := kvsecrets.New(keyVaultName) + keyVaultSecretClient := kvsecrets.New(keyVaultName, config.GlobalCredentials()) assert.Eventually(func() bool { keyNamespace := "azuresqluser-" + sqlServerName + "-" + sqlDatabaseName1 @@ -342,7 +343,7 @@ func TestAzureSqlServerCombinedHappyPath(t *testing.T) { EnsureInstance(ctx, t, tc, kvSqlUser2) // Check that the user's secret is in the keyvault - keyVaultSecretClient := kvsecrets.New(keyVaultName) + keyVaultSecretClient := kvsecrets.New(keyVaultName, config.GlobalCredentials()) assert.Eventually(func() bool { keyNamespace := "azuresqluser-" + sqlServerName + "-" + sqlDatabaseName1 @@ -362,7 +363,7 @@ func TestAzureSqlServerCombinedHappyPath(t *testing.T) { key := types.NamespacedName{Name: kvSqlUser1.ObjectMeta.Name, Namespace: keyNamespace} keyVaultName := tc.keyvaultName - keyVaultSecretClient := kvsecrets.New(keyVaultName) + keyVaultSecretClient := kvsecrets.New(keyVaultName, config.GlobalCredentials()) var oldSecret, _ = keyVaultSecretClient.Get(ctx, key) sqlActionName := GenerateTestResourceNameWithRandom("azuresqlaction-dev", 10) @@ -409,7 +410,7 @@ func TestAzureSqlServerCombinedHappyPath(t *testing.T) { EnsureDelete(ctx, t, tc, kvSqlUser2) // Check that the user's secret is in the keyvault - keyVaultSecretClient := kvsecrets.New(tc.keyvaultName) + keyVaultSecretClient := kvsecrets.New(tc.keyvaultName, config.GlobalCredentials()) assert.Eventually(func() bool { key := types.NamespacedName{Name: sqlUser.ObjectMeta.Name, Namespace: sqlUser.ObjectMeta.Namespace} diff --git a/controllers/eventhub_storageaccount_controller_test.go b/controllers/eventhub_storageaccount_controller_test.go index 4ddc63929bf..21757a4da96 100644 --- a/controllers/eventhub_storageaccount_controller_test.go +++ b/controllers/eventhub_storageaccount_controller_test.go @@ -15,6 +15,7 @@ import ( "github.com/Azure/azure-service-operator/pkg/errhelp" + "github.com/Azure/azure-service-operator/pkg/resourcemanager/config" kvhelper "github.com/Azure/azure-service-operator/pkg/resourcemanager/keyvaults" kvsecrets "github.com/Azure/azure-service-operator/pkg/secrets/keyvault" @@ -127,7 +128,8 @@ func TestEventHubControllerCreateAndDeleteCustomKeyVault(t *testing.T) { keyVaultNameForSecrets := tc.keyvaultName // Instantiate a KV client for the Keyvault that was created during test suite setup - _, err := kvhelper.AzureKeyVaultManager.GetVault(ctx, rgName, keyVaultNameForSecrets) + kvManager := kvhelper.NewAzureKeyVaultManager(config.GlobalCredentials(), nil) + _, err := kvManager.GetVault(ctx, rgName, keyVaultNameForSecrets) assert.Equal(nil, err, "wait for keyvault to be available") // Create EventhubNamespace instance as prereq @@ -170,7 +172,7 @@ func TestEventHubControllerCreateAndDeleteCustomKeyVault(t *testing.T) { EnsureInstance(ctx, t, tc, eventhubInstance) // Check that the secret is added to KeyVault - keyvaultSecretClient := kvsecrets.New(keyVaultNameForSecrets) + keyvaultSecretClient := kvsecrets.New(keyVaultNameForSecrets, config.GlobalCredentials()) EnsureSecrets(ctx, t, tc, eventhubInstance, keyvaultSecretClient, eventhubName, eventhubInstance.Namespace) diff --git a/controllers/eventhubnamespace_controller_test.go b/controllers/eventhubnamespace_controller_test.go index 5326a5ed4a0..d0dae13cb18 100644 --- a/controllers/eventhubnamespace_controller_test.go +++ b/controllers/eventhubnamespace_controller_test.go @@ -76,7 +76,7 @@ func TestEventHubNamespaceControllerNetworkRules(t *testing.T) { EnsureInstance(ctx, t, tc, VNetInstance) // Create EventhubNamespace network rule using the above VNET - subnetID := "/subscriptions/" + config.SubscriptionID() + "/resourceGroups/" + rgName + "/providers/Microsoft.Network/virtualNetworks/" + VNetName + "/subnets/" + subnetName + subnetID := "/subscriptions/" + config.GlobalCredentials().SubscriptionID() + "/resourceGroups/" + rgName + "/providers/Microsoft.Network/virtualNetworks/" + VNetName + "/subnets/" + subnetName vnetRules := []azurev1alpha1.VirtualNetworkRules{ { SubnetID: subnetID, diff --git a/controllers/keyvault_controller_test.go b/controllers/keyvault_controller_test.go index 01cb7520ebd..a6d1ab5277e 100644 --- a/controllers/keyvault_controller_test.go +++ b/controllers/keyvault_controller_test.go @@ -75,8 +75,8 @@ func TestKeyvaultControllerWithAccessPolicies(t *testing.T) { keyVaultLocation := tc.resourceGroupLocation accessPolicies := []azurev1alpha1.AccessPolicyEntry{ { - TenantID: config.TenantID(), - ClientID: config.ClientID(), + TenantID: config.GlobalCredentials().TenantID(), + ClientID: config.GlobalCredentials().ClientID(), Permissions: &azurev1alpha1.Permissions{ Keys: &[]string{ @@ -122,7 +122,7 @@ func TestKeyvaultControllerWithAccessPolicies(t *testing.T) { //Add code to set secret and get secret from this keyvault using secretclient - keyvaultSecretClient := kvsecrets.New(keyVaultName) + keyvaultSecretClient := kvsecrets.New(keyVaultName, config.GlobalCredentials()) secretName := "test-key" key := types.NamespacedName{Name: secretName, Namespace: "default"} datanew := map[string][]byte{ @@ -163,8 +163,8 @@ func TestKeyvaultControllerWithLimitedAccessPoliciesAndUpdate(t *testing.T) { ResourceGroup: tc.resourceGroupName, AccessPolicies: &[]azurev1alpha1.AccessPolicyEntry{ { - TenantID: config.TenantID(), - ClientID: config.ClientID(), + TenantID: config.GlobalCredentials().TenantID(), + ClientID: config.GlobalCredentials().ClientID(), Permissions: &azurev1alpha1.Permissions{ Secrets: &[]string{"backup"}, }, @@ -182,7 +182,7 @@ func TestKeyvaultControllerWithLimitedAccessPoliciesAndUpdate(t *testing.T) { }, tc.timeout, tc.retry, "wait for keyVaultInstance to be ready in azure") //Add code to set secret and get secret from this keyvault using secretclient - keyvaultSecretClient := kvsecrets.New(keyVaultName) + keyvaultSecretClient := kvsecrets.New(keyVaultName, config.GlobalCredentials()) key := types.NamespacedName{Name: "test-key", Namespace: "default"} datanew := map[string][]byte{ "test1": []byte("test2"), @@ -296,8 +296,8 @@ func TestKeyvaultControllerWithVirtualNetworkRulesAndUpdate(t *testing.T) { keyVaultLocation := tc.resourceGroupLocation accessPolicies := []azurev1alpha1.AccessPolicyEntry{ { - TenantID: config.TenantID(), - ClientID: config.ClientID(), + TenantID: config.GlobalCredentials().TenantID(), + ClientID: config.GlobalCredentials().ClientID(), Permissions: &azurev1alpha1.Permissions{ Secrets: &[]string{ @@ -329,7 +329,7 @@ func TestKeyvaultControllerWithVirtualNetworkRulesAndUpdate(t *testing.T) { return result.Response.StatusCode == http.StatusOK }, tc.timeout, tc.retry, "wait for keyVaultInstance to be ready in azure") - keyvaultSecretClient := kvsecrets.New(keyVaultName) + keyvaultSecretClient := kvsecrets.New(keyVaultName, config.GlobalCredentials()) secretName := "test-key" key := types.NamespacedName{Name: secretName, Namespace: "default"} datanew := map[string][]byte{ diff --git a/controllers/keyvaultkey_controller_test.go b/controllers/keyvaultkey_controller_test.go index ce59656226d..7bdde993c32 100644 --- a/controllers/keyvaultkey_controller_test.go +++ b/controllers/keyvaultkey_controller_test.go @@ -36,8 +36,8 @@ func TestKeyvaultKeyControllerHappyPath(t *testing.T) { keyPermissions := []string{"get", "list", "update", "delete", "recover", "backup", "restore", "create", "import"} accessPolicies := []azurev1alpha1.AccessPolicyEntry{ { - TenantID: config.TenantID(), - ClientID: config.ClientID(), + TenantID: config.GlobalCredentials().TenantID(), + ClientID: config.GlobalCredentials().ClientID(), Permissions: &azurev1alpha1.Permissions{ Keys: &keyPermissions, }, @@ -86,7 +86,7 @@ func TestKeyvaultKeyControllerHappyPath(t *testing.T) { // create key EnsureInstance(ctx, t, tc, keyVaultKey) - kvopsclient := resourcemanagerkeyvaults.NewOpsClient(keyVaultName) + kvopsclient := resourcemanagerkeyvaults.NewOpsClient(config.GlobalCredentials(), keyVaultName) assert.Eventually(func() bool { kvault, err := tc.keyVaultManager.GetVault(ctx, tc.resourceGroupName, keyVaultInstance.Name) diff --git a/controllers/suite_test.go b/controllers/suite_test.go index 6191c07087e..a60f10bcc2a 100644 --- a/controllers/suite_test.go +++ b/controllers/suite_test.go @@ -6,7 +6,6 @@ package controllers import ( "context" "fmt" - resourcemanagersqldb "github.com/Azure/azure-service-operator/pkg/resourcemanager/azuresql/azuresqldb" "log" "net/http" "os" @@ -16,6 +15,9 @@ import ( "testing" "time" + resourcemanagersqldb "github.com/Azure/azure-service-operator/pkg/resourcemanager/azuresql/azuresqldb" + "github.com/Azure/azure-service-operator/pkg/resourcemanager/config" + kscheme "k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/rest" @@ -147,11 +149,11 @@ func setup() error { } secretClient := k8sSecrets.New(k8sManager.GetClient()) - resourceGroupManager := resourcegroupsresourcemanager.NewAzureResourceGroupManager() - keyVaultManager := resourcemanagerkeyvaults.NewAzureKeyVaultManager(k8sManager.GetScheme()) - eventhubClient := resourcemanagereventhub.NewEventhubClient(secretClient, scheme.Scheme) - consumerGroupClient := resourcemanagereventhub.NewConsumerGroupClient() - azureSqlDatabaseManager := resourcemanagersqldb.NewAzureSqlDbManager() + resourceGroupManager := resourcegroupsresourcemanager.NewAzureResourceGroupManager(config.GlobalCredentials()) + keyVaultManager := resourcemanagerkeyvaults.NewAzureKeyVaultManager(config.GlobalCredentials(), k8sManager.GetScheme()) + eventhubClient := resourcemanagereventhub.NewEventhubClient(config.GlobalCredentials(), secretClient, scheme.Scheme) + consumerGroupClient := resourcemanagereventhub.NewConsumerGroupClient(config.GlobalCredentials()) + azureSqlDatabaseManager := resourcemanagersqldb.NewAzureSqlDbManager(config.GlobalCredentials()) timeout = time.Second * 780 @@ -174,9 +176,10 @@ func setup() error { err = (&KeyVaultKeyReconciler{ Reconciler: &AsyncReconciler{ Client: k8sManager.GetClient(), - AzureClient: &resourcemanagerkeyvaults.KeyvaultKeyClient{ - KeyvaultClient: keyVaultManager, - }, + AzureClient: resourcemanagerkeyvaults.NewKeyvaultKeyClient( + config.GlobalCredentials(), + keyVaultManager, + ), Telemetry: telemetry.InitializeTelemetryDefault( "KeyVaultKey", ctrl.Log.WithName("controllers").WithName("KeyVaultKey"), @@ -193,6 +196,7 @@ func setup() error { Reconciler: &AsyncReconciler{ Client: k8sManager.GetClient(), AzureClient: resourcemanagerappinsights.NewManager( + config.GlobalCredentials(), secretClient, scheme.Scheme, ), @@ -212,6 +216,7 @@ func setup() error { Reconciler: &AsyncReconciler{ Client: k8sManager.GetClient(), AzureClient: resourcemanagerappinsights.NewAPIKeyClient( + config.GlobalCredentials(), secretClient, scheme.Scheme, ), @@ -230,7 +235,7 @@ func setup() error { err = (&APIMAPIReconciler{ Reconciler: &AsyncReconciler{ Client: k8sManager.GetClient(), - AzureClient: resourcemanagerapimgmt.NewManager(), + AzureClient: resourcemanagerapimgmt.NewManager(config.GlobalCredentials()), Telemetry: telemetry.InitializeTelemetryDefault( "ApiMgmt", ctrl.Log.WithName("controllers").WithName("ApiMgmt"), @@ -246,7 +251,7 @@ func setup() error { err = (&CosmosDBReconciler{ Reconciler: &AsyncReconciler{ Client: k8sManager.GetClient(), - AzureClient: resourcemanagercosmosdb.NewAzureCosmosDBManager(secretClient), + AzureClient: resourcemanagercosmosdb.NewAzureCosmosDBManager(config.GlobalCredentials(), secretClient), Telemetry: telemetry.InitializeTelemetryDefault( "CosmosDB", ctrl.Log.WithName("controllers").WithName("CosmosDB"), @@ -295,6 +300,7 @@ func setup() error { Reconciler: &AsyncReconciler{ Client: k8sManager.GetClient(), AzureClient: rediscaches.NewAzureRedisCacheManager( + config.GlobalCredentials(), secretClient, scheme.Scheme, ), @@ -314,6 +320,7 @@ func setup() error { Reconciler: &AsyncReconciler{ Client: k8sManager.GetClient(), AzureClient: rediscacheactions.NewAzureRedisCacheActionManager( + config.GlobalCredentials(), secretClient, scheme.Scheme, ), @@ -332,7 +339,7 @@ func setup() error { err = (&RedisCacheFirewallRuleReconciler{ Reconciler: &AsyncReconciler{ Client: k8sManager.GetClient(), - AzureClient: rcfwr.NewAzureRedisCacheFirewallRuleManager(), + AzureClient: rcfwr.NewAzureRedisCacheFirewallRuleManager(config.GlobalCredentials()), Telemetry: telemetry.InitializeTelemetryDefault( "RedisCacheFirewallRule", ctrl.Log.WithName("controllers").WithName("RedisCacheFirewallRule"), @@ -348,7 +355,7 @@ func setup() error { err = (&EventhubNamespaceReconciler{ Reconciler: &AsyncReconciler{ Client: k8sManager.GetClient(), - AzureClient: resourcemanagereventhub.NewEventHubNamespaceClient(), + AzureClient: resourcemanagereventhub.NewEventHubNamespaceClient(config.GlobalCredentials()), Telemetry: telemetry.InitializeTelemetryDefault( "EventhubNamespace", ctrl.Log.WithName("controllers").WithName("EventhubNamespace"), @@ -381,6 +388,7 @@ func setup() error { Reconciler: &AsyncReconciler{ Client: k8sManager.GetClient(), AzureClient: resourcemanagersqlserver.NewAzureSqlServerManager( + config.GlobalCredentials(), secretClient, scheme.Scheme, ), @@ -415,7 +423,7 @@ func setup() error { err = (&AzureSqlFirewallRuleReconciler{ Reconciler: &AsyncReconciler{ Client: k8sManager.GetClient(), - AzureClient: resourcemanagersqlfirewallrule.NewAzureSqlFirewallRuleManager(), + AzureClient: resourcemanagersqlfirewallrule.NewAzureSqlFirewallRuleManager(config.GlobalCredentials()), Telemetry: telemetry.InitializeTelemetryDefault( "AzureSQLFirewallRuleOperator", ctrl.Log.WithName("controllers").WithName("AzureSQLFirewallRuleOperator"), @@ -431,7 +439,7 @@ func setup() error { err = (&AzureSQLVNetRuleReconciler{ Reconciler: &AsyncReconciler{ Client: k8sManager.GetClient(), - AzureClient: resourcemanagersqlvnetrule.NewAzureSqlVNetRuleManager(), + AzureClient: resourcemanagersqlvnetrule.NewAzureSqlVNetRuleManager(config.GlobalCredentials()), Telemetry: telemetry.InitializeTelemetryDefault( "AzureSQLVNetRuleOperator", ctrl.Log.WithName("controllers").WithName("AzureSQLVNetRuleOperator"), @@ -448,6 +456,7 @@ func setup() error { Reconciler: &AsyncReconciler{ Client: k8sManager.GetClient(), AzureClient: resourcemanagersqlfailovergroup.NewAzureSqlFailoverGroupManager( + config.GlobalCredentials(), secretClient, scheme.Scheme, ), @@ -467,6 +476,7 @@ func setup() error { Reconciler: &AsyncReconciler{ Client: k8sManager.GetClient(), AzureClient: resourcemanagersqluser.NewAzureSqlUserManager( + config.GlobalCredentials(), secretClient, scheme.Scheme, ), @@ -486,6 +496,7 @@ func setup() error { Reconciler: &AsyncReconciler{ Client: k8sManager.GetClient(), AzureClient: resourcemanagersqlmanageduser.NewAzureSqlManagedUserManager( + config.GlobalCredentials(), secretClient, scheme.Scheme, ), @@ -504,7 +515,7 @@ func setup() error { err = (&VirtualNetworkReconciler{ Reconciler: &AsyncReconciler{ Client: k8sManager.GetClient(), - AzureClient: resourcemanagervnet.NewAzureVNetManager(), + AzureClient: resourcemanagervnet.NewAzureVNetManager(config.GlobalCredentials()), Telemetry: telemetry.InitializeTelemetryDefault( "VirtualNetwork", ctrl.Log.WithName("controllers").WithName("VirtualNetwork"), @@ -521,6 +532,7 @@ func setup() error { Reconciler: &AsyncReconciler{ Client: k8sManager.GetClient(), AzureClient: resourcemanagerpip.NewAzurePublicIPAddressClient( + config.GlobalCredentials(), secretClient, k8sManager.GetScheme(), ), @@ -540,6 +552,7 @@ func setup() error { Reconciler: &AsyncReconciler{ Client: k8sManager.GetClient(), AzureClient: resourcemanagernic.NewAzureNetworkInterfaceClient( + config.GlobalCredentials(), secretClient, k8sManager.GetScheme(), ), @@ -559,6 +572,7 @@ func setup() error { Reconciler: &AsyncReconciler{ Client: k8sManager.GetClient(), AzureClient: vm.NewAzureVirtualMachineClient( + config.GlobalCredentials(), secretClient, k8sManager.GetScheme(), ), @@ -578,6 +592,7 @@ func setup() error { Reconciler: &AsyncReconciler{ Client: k8sManager.GetClient(), AzureClient: vmext.NewAzureVirtualMachineExtensionClient( + config.GlobalCredentials(), secretClient, k8sManager.GetScheme(), ), @@ -597,6 +612,7 @@ func setup() error { Reconciler: &AsyncReconciler{ Client: k8sManager.GetClient(), AzureClient: loadbalancer.NewAzureLoadBalancerClient( + config.GlobalCredentials(), secretClient, k8sManager.GetScheme(), ), @@ -616,6 +632,7 @@ func setup() error { Reconciler: &AsyncReconciler{ Client: k8sManager.GetClient(), AzureClient: vmss.NewAzureVMScaleSetClient( + config.GlobalCredentials(), secretClient, k8sManager.GetScheme(), ), @@ -634,7 +651,7 @@ func setup() error { err = (&AzureSqlActionReconciler{ Reconciler: &AsyncReconciler{ Client: k8sManager.GetClient(), - AzureClient: resourcemanagersqlaction.NewAzureSqlActionManager(secretClient, scheme.Scheme), + AzureClient: resourcemanagersqlaction.NewAzureSqlActionManager(config.GlobalCredentials(), secretClient, scheme.Scheme), Telemetry: telemetry.InitializeTelemetryDefault( "AzureSqlAction", ctrl.Log.WithName("controllers").WithName("AzureSqlAction"), @@ -650,7 +667,7 @@ func setup() error { err = (&BlobContainerReconciler{ Reconciler: &AsyncReconciler{ Client: k8sManager.GetClient(), - AzureClient: resourcemanagerblobcontainer.New(), + AzureClient: resourcemanagerblobcontainer.New(config.GlobalCredentials()), Telemetry: telemetry.InitializeTelemetryDefault( "BlobContainer", ctrl.Log.WithName("controllers").WithName("BlobContainer"), @@ -667,6 +684,7 @@ func setup() error { Reconciler: &AsyncReconciler{ Client: k8sManager.GetClient(), AzureClient: mysqlServerManager.NewMySQLServerClient( + config.GlobalCredentials(), secretClient, k8sManager.GetScheme(), ), @@ -685,7 +703,7 @@ func setup() error { err = (&MySQLDatabaseReconciler{ Reconciler: &AsyncReconciler{ Client: k8sManager.GetClient(), - AzureClient: mysqlDatabaseManager.NewMySQLDatabaseClient(), + AzureClient: mysqlDatabaseManager.NewMySQLDatabaseClient(config.GlobalCredentials()), Telemetry: telemetry.InitializeTelemetryDefault( "MySQLDatabase", ctrl.Log.WithName("controllers").WithName("MySQLDatabase"), @@ -701,7 +719,7 @@ func setup() error { err = (&MySQLFirewallRuleReconciler{ Reconciler: &AsyncReconciler{ Client: k8sManager.GetClient(), - AzureClient: mysqlFirewallManager.NewMySQLFirewallRuleClient(), + AzureClient: mysqlFirewallManager.NewMySQLFirewallRuleClient(config.GlobalCredentials()), Telemetry: telemetry.InitializeTelemetryDefault( "MySQLFirewallRule", ctrl.Log.WithName("controllers").WithName("MySQLFirewallRule"), @@ -717,7 +735,7 @@ func setup() error { err = (&MySQLVNetRuleReconciler{ Reconciler: &AsyncReconciler{ Client: k8sManager.GetClient(), - AzureClient: mysqlvnetrule.NewMySQLVNetRuleClient(), + AzureClient: mysqlvnetrule.NewMySQLVNetRuleClient(config.GlobalCredentials()), Telemetry: telemetry.InitializeTelemetryDefault( "MySQLVNetRule", ctrl.Log.WithName("controllers").WithName("MySQLVNetRule"), @@ -733,7 +751,7 @@ func setup() error { err = (&MySQLUserReconciler{ Reconciler: &AsyncReconciler{ Client: k8sManager.GetClient(), - AzureClient: mysqluser.NewMySqlUserManager(secretClient, scheme.Scheme), + AzureClient: mysqluser.NewMySqlUserManager(config.GlobalCredentials(), secretClient, scheme.Scheme), Telemetry: telemetry.InitializeTelemetryDefault( "MySQLUser", ctrl.Log.WithName("controllers").WithName("MySQLUser"), @@ -749,7 +767,7 @@ func setup() error { err = (&PostgreSQLServerReconciler{ Reconciler: &AsyncReconciler{ Client: k8sManager.GetClient(), - AzureClient: resourcemanagerpsqlserver.NewPSQLServerClient(secretClient, k8sManager.GetScheme()), + AzureClient: resourcemanagerpsqlserver.NewPSQLServerClient(config.GlobalCredentials(), secretClient, k8sManager.GetScheme()), Telemetry: telemetry.InitializeTelemetryDefault( "PostgreSQLServer", ctrl.Log.WithName("controllers").WithName("PostgreSQLServer"), @@ -765,7 +783,7 @@ func setup() error { err = (&PostgreSQLDatabaseReconciler{ Reconciler: &AsyncReconciler{ Client: k8sManager.GetClient(), - AzureClient: resourcemanagerpsqldatabase.NewPSQLDatabaseClient(), + AzureClient: resourcemanagerpsqldatabase.NewPSQLDatabaseClient(config.GlobalCredentials()), Telemetry: telemetry.InitializeTelemetryDefault( "PostgreSQLDatabase", ctrl.Log.WithName("controllers").WithName("PostgreSQLDatabase"), @@ -781,7 +799,7 @@ func setup() error { err = (&PostgreSQLFirewallRuleReconciler{ Reconciler: &AsyncReconciler{ Client: k8sManager.GetClient(), - AzureClient: resourcemanagerpsqlfirewallrule.NewPSQLFirewallRuleClient(), + AzureClient: resourcemanagerpsqlfirewallrule.NewPSQLFirewallRuleClient(config.GlobalCredentials()), Telemetry: telemetry.InitializeTelemetryDefault( "PostgreSQLFirewallRule", ctrl.Log.WithName("controllers").WithName("PostgreSQLFirewallRule"), @@ -797,7 +815,7 @@ func setup() error { err = (&PostgreSQLUserReconciler{ Reconciler: &AsyncReconciler{ Client: k8sManager.GetClient(), - AzureClient: resourcemanagerpsqluser.NewPostgreSqlUserManager(secretClient, k8sManager.GetScheme()), + AzureClient: resourcemanagerpsqluser.NewPostgreSqlUserManager(config.GlobalCredentials(), secretClient, k8sManager.GetScheme()), Telemetry: telemetry.InitializeTelemetryDefault( "PostgreSQLUser", ctrl.Log.WithName("controllers").WithName("PostgreSQLUser"), @@ -813,7 +831,7 @@ func setup() error { err = (&StorageAccountReconciler{ Reconciler: &AsyncReconciler{ Client: k8sManager.GetClient(), - AzureClient: resourcemanagerstorageaccount.New(secretClient, k8sManager.GetScheme()), + AzureClient: resourcemanagerstorageaccount.New(config.GlobalCredentials(), secretClient, k8sManager.GetScheme()), Telemetry: telemetry.InitializeTelemetryDefault( "StorageAccount", ctrl.Log.WithName("controllers").WithName("StorageAccount"), @@ -865,7 +883,14 @@ func setup() error { } log.Println("Creating KV:", keyvaultName) - _, err = resourcemanagerkeyvaults.AzureKeyVaultManager.CreateVaultWithAccessPolicies(context.Background(), resourceGroupName, keyvaultName, resourcegroupLocation, resourcemanagerconfig.ClientID()) + kvManager := resourcemanagerkeyvaults.NewAzureKeyVaultManager(config.GlobalCredentials(), nil) + _, err = kvManager.CreateVaultWithAccessPolicies( + context.Background(), + resourceGroupName, + keyvaultName, + resourcegroupLocation, + resourcemanagerconfig.GlobalCredentials().ClientID(), + ) // Key Vault needs to be in "Suceeded" state finish := time.Now().Add(tc.timeout) for { diff --git a/go.sum b/go.sum index 549dda280e4..85be53a0b55 100644 --- a/go.sum +++ b/go.sum @@ -28,6 +28,7 @@ github.com/Azure/go-autorest/autorest/date v0.3.0 h1:7gUk1U5M/CQbp9WoqinNzJar+8K github.com/Azure/go-autorest/autorest/date v0.3.0/go.mod h1:BI0uouVdmngYNUzGWeSYnokU+TrmwEsOqdt8Y6sso74= github.com/Azure/go-autorest/autorest/mocks v0.1.0/go.mod h1:OTyCOPRA2IgIlWxVYxBee2F5Gr4kF2zd2J5cFRaIDN0= github.com/Azure/go-autorest/autorest/mocks v0.2.0/go.mod h1:OTyCOPRA2IgIlWxVYxBee2F5Gr4kF2zd2J5cFRaIDN0= +github.com/Azure/go-autorest/autorest/mocks v0.4.0 h1:z20OWOSG5aCye0HEkDp6TPmP17ZcfeMxPi6HnSALa8c= github.com/Azure/go-autorest/autorest/mocks v0.4.0/go.mod h1:LTp+uSrOhSkaKrUy935gNZuuIPPVsHlr9DSOxSayd+k= github.com/Azure/go-autorest/autorest/to v0.2.0/go.mod h1:GunWKJp1AEqgMaGLV+iocmRAJWqST1wQYhyyjXJ3SJc= github.com/Azure/go-autorest/autorest/to v0.4.0 h1:oXVqrxakqqV1UZdSazDOPOLvOIz+XA683u8EctwboHk= @@ -277,9 +278,11 @@ github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQL github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= +github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/pty v1.1.5/go.mod h1:9r2w37qlBe7rQ6e1fg1S/9xpWHSnaqNdHD3WcMdbPDA= +github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/lib/pq v1.6.0 h1:I5DPxhYJChW9KYc66se+oKFFQX6VuQrKiprsX6ivRZc= github.com/lib/pq v1.6.0/go.mod h1:4vXEAYvW1fRQ2/FhZ78H73A60MHw1geSm145z2mdY1g= @@ -566,6 +569,7 @@ google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ij google.golang.org/grpc v1.23.1/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/cheggaaa/pb.v1 v1.0.25/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= diff --git a/main.go b/main.go index fbfb754e67d..b7bc3a6c1a5 100644 --- a/main.go +++ b/main.go @@ -31,6 +31,7 @@ import ( resourcemanagersqlserver "github.com/Azure/azure-service-operator/pkg/resourcemanager/azuresql/azuresqlserver" resourcemanagersqluser "github.com/Azure/azure-service-operator/pkg/resourcemanager/azuresql/azuresqluser" resourcemanagersqlvnetrule "github.com/Azure/azure-service-operator/pkg/resourcemanager/azuresql/azuresqlvnetrule" + "github.com/Azure/azure-service-operator/pkg/resourcemanager/config" resourcemanagerconfig "github.com/Azure/azure-service-operator/pkg/resourcemanager/config" resourcemanagercosmosdb "github.com/Azure/azure-service-operator/pkg/resourcemanager/cosmosdbs" resourcemanagereventhub "github.com/Azure/azure-service-operator/pkg/resourcemanager/eventhubs" @@ -128,77 +129,87 @@ func main() { setupLog.V(0).Info("Configuration details", "Configuration", resourcemanagerconfig.ConfigString()) - keyvaultName := resourcemanagerconfig.OperatorKeyvault() + keyvaultName := resourcemanagerconfig.GlobalCredentials().OperatorKeyvault() if keyvaultName == "" { setupLog.Info("Keyvault name is empty") secretClient = k8sSecrets.New(mgr.GetClient()) } else { setupLog.Info("Instantiating secrets client for keyvault " + keyvaultName) - secretClient = keyvaultSecrets.New(keyvaultName) + secretClient = keyvaultSecrets.New(keyvaultName, config.GlobalCredentials()) } - apimManager := resourceapimanagement.NewManager() - apimServiceManager := apimservice.NewAzureAPIMgmtServiceManager() - vnetManager := vnet.NewAzureVNetManager() - resourceGroupManager := resourcemanagerresourcegroup.NewAzureResourceGroupManager() + // TODO(creds-refactor): construction of these managers will need + // to move into the AsyncReconciler.Reconcile so that it can use the correct + // creds based on the namespace of the specific resource being reconciled. + apimManager := resourceapimanagement.NewManager(config.GlobalCredentials()) + apimServiceManager := apimservice.NewAzureAPIMgmtServiceManager(config.GlobalCredentials()) + vnetManager := vnet.NewAzureVNetManager(config.GlobalCredentials()) + resourceGroupManager := resourcemanagerresourcegroup.NewAzureResourceGroupManager(config.GlobalCredentials()) redisCacheManager := rediscache.NewAzureRedisCacheManager( + config.GlobalCredentials(), secretClient, scheme, ) redisCacheActionManager := rediscacheactions.NewAzureRedisCacheActionManager( + config.GlobalCredentials(), secretClient, scheme, ) - redisCacheFirewallRuleManager := rcfwr.NewAzureRedisCacheFirewallRuleManager() + redisCacheFirewallRuleManager := rcfwr.NewAzureRedisCacheFirewallRuleManager(config.GlobalCredentials()) appInsightsManager := resourcemanagerappinsights.NewManager( + config.GlobalCredentials(), secretClient, scheme, ) - eventhubNamespaceClient := resourcemanagereventhub.NewEventHubNamespaceClient() - consumerGroupClient := resourcemanagereventhub.NewConsumerGroupClient() + eventhubNamespaceClient := resourcemanagereventhub.NewEventHubNamespaceClient(config.GlobalCredentials()) + consumerGroupClient := resourcemanagereventhub.NewConsumerGroupClient(config.GlobalCredentials()) cosmosDBClient := resourcemanagercosmosdb.NewAzureCosmosDBManager( + config.GlobalCredentials(), secretClient, ) - keyVaultManager := resourcemanagerkeyvault.NewAzureKeyVaultManager(mgr.GetScheme()) - keyVaultKeyManager := &resourcemanagerkeyvault.KeyvaultKeyClient{ - KeyvaultClient: keyVaultManager, - } - eventhubClient := resourcemanagereventhub.NewEventhubClient(secretClient, scheme) + keyVaultManager := resourcemanagerkeyvault.NewAzureKeyVaultManager(config.GlobalCredentials(), mgr.GetScheme()) + keyVaultKeyManager := resourcemanagerkeyvault.NewKeyvaultKeyClient(config.GlobalCredentials(), keyVaultManager) + eventhubClient := resourcemanagereventhub.NewEventhubClient(config.GlobalCredentials(), secretClient, scheme) sqlServerManager := resourcemanagersqlserver.NewAzureSqlServerManager( + config.GlobalCredentials(), secretClient, scheme, ) - sqlDBManager := resourcemanagersqldb.NewAzureSqlDbManager() - sqlFirewallRuleManager := resourcemanagersqlfirewallrule.NewAzureSqlFirewallRuleManager() - sqlVNetRuleManager := resourcemanagersqlvnetrule.NewAzureSqlVNetRuleManager() + sqlDBManager := resourcemanagersqldb.NewAzureSqlDbManager(config.GlobalCredentials()) + sqlFirewallRuleManager := resourcemanagersqlfirewallrule.NewAzureSqlFirewallRuleManager(config.GlobalCredentials()) + sqlVNetRuleManager := resourcemanagersqlvnetrule.NewAzureSqlVNetRuleManager(config.GlobalCredentials()) sqlFailoverGroupManager := resourcemanagersqlfailovergroup.NewAzureSqlFailoverGroupManager( + config.GlobalCredentials(), secretClient, scheme, ) - psqlserverclient := psqlserver.NewPSQLServerClient(secretClient, mgr.GetScheme()) - psqldatabaseclient := psqldatabase.NewPSQLDatabaseClient() - psqlfirewallruleclient := psqlfirewallrule.NewPSQLFirewallRuleClient() + psqlserverclient := psqlserver.NewPSQLServerClient(config.GlobalCredentials(), secretClient, mgr.GetScheme()) + psqldatabaseclient := psqldatabase.NewPSQLDatabaseClient(config.GlobalCredentials()) + psqlfirewallruleclient := psqlfirewallrule.NewPSQLFirewallRuleClient(config.GlobalCredentials()) psqlusermanager := psqluser.NewPostgreSqlUserManager( + config.GlobalCredentials(), secretClient, scheme, ) sqlUserManager := resourcemanagersqluser.NewAzureSqlUserManager( + config.GlobalCredentials(), secretClient, scheme, ) sqlManagedUserManager := resourcemanagersqlmanageduser.NewAzureSqlManagedUserManager( + config.GlobalCredentials(), secretClient, scheme, ) - sqlActionManager := resourcemanagersqlaction.NewAzureSqlActionManager(secretClient, scheme) + sqlActionManager := resourcemanagersqlaction.NewAzureSqlActionManager(config.GlobalCredentials(), secretClient, scheme) err = (&controllers.StorageAccountReconciler{ Reconciler: &controllers.AsyncReconciler{ Client: mgr.GetClient(), - AzureClient: storageaccountManager.New(secretClient, scheme), + AzureClient: storageaccountManager.New(config.GlobalCredentials(), secretClient, scheme), Telemetry: telemetry.InitializeTelemetryDefault( "StorageAccount", ctrl.Log.WithName("controllers").WithName("StorageAccount"), @@ -495,7 +506,7 @@ func main() { if err = (&controllers.BlobContainerReconciler{ Reconciler: &controllers.AsyncReconciler{ Client: mgr.GetClient(), - AzureClient: blobContainerManager.New(), + AzureClient: blobContainerManager.New(config.GlobalCredentials()), Telemetry: telemetry.InitializeTelemetryDefault( "BlobContainer", ctrl.Log.WithName("controllers").WithName("BlobContainer"), @@ -656,6 +667,7 @@ func main() { Reconciler: &controllers.AsyncReconciler{ Client: mgr.GetClient(), AzureClient: mysqlserver.NewMySQLServerClient( + config.GlobalCredentials(), secretClient, mgr.GetScheme(), ), @@ -673,7 +685,7 @@ func main() { if err = (&controllers.MySQLDatabaseReconciler{ Reconciler: &controllers.AsyncReconciler{ Client: mgr.GetClient(), - AzureClient: mysqldatabase.NewMySQLDatabaseClient(), + AzureClient: mysqldatabase.NewMySQLDatabaseClient(config.GlobalCredentials()), Telemetry: telemetry.InitializeTelemetryDefault( "MySQLDatabase", ctrl.Log.WithName("controllers").WithName("MySQLDatabase"), @@ -688,7 +700,7 @@ func main() { if err = (&controllers.MySQLFirewallRuleReconciler{ Reconciler: &controllers.AsyncReconciler{ Client: mgr.GetClient(), - AzureClient: mysqlfirewall.NewMySQLFirewallRuleClient(), + AzureClient: mysqlfirewall.NewMySQLFirewallRuleClient(config.GlobalCredentials()), Telemetry: telemetry.InitializeTelemetryDefault( "MySQLFirewallRule", ctrl.Log.WithName("controllers").WithName("MySQLFirewallRule"), @@ -704,7 +716,7 @@ func main() { if err = (&controllers.MySQLUserReconciler{ Reconciler: &controllers.AsyncReconciler{ Client: mgr.GetClient(), - AzureClient: mysqluser.NewMySqlUserManager(secretClient, scheme), + AzureClient: mysqluser.NewMySqlUserManager(config.GlobalCredentials(), secretClient, scheme), Telemetry: telemetry.InitializeTelemetryDefault( "MySQLUser", ctrl.Log.WithName("controllers").WithName("MySQLUser"), @@ -721,6 +733,7 @@ func main() { Reconciler: &controllers.AsyncReconciler{ Client: mgr.GetClient(), AzureClient: pip.NewAzurePublicIPAddressClient( + config.GlobalCredentials(), secretClient, mgr.GetScheme(), ), @@ -740,6 +753,7 @@ func main() { Reconciler: &controllers.AsyncReconciler{ Client: mgr.GetClient(), AzureClient: nic.NewAzureNetworkInterfaceClient( + config.GlobalCredentials(), secretClient, mgr.GetScheme(), ), @@ -758,7 +772,7 @@ func main() { if err = (&controllers.MySQLVNetRuleReconciler{ Reconciler: &controllers.AsyncReconciler{ Client: mgr.GetClient(), - AzureClient: mysqlvnetrule.NewMySQLVNetRuleClient(), + AzureClient: mysqlvnetrule.NewMySQLVNetRuleClient(config.GlobalCredentials()), Telemetry: telemetry.InitializeTelemetryDefault( "MySQLVNetRule", ctrl.Log.WithName("controllers").WithName("MySQLVNetRule"), @@ -775,6 +789,7 @@ func main() { Reconciler: &controllers.AsyncReconciler{ Client: mgr.GetClient(), AzureClient: vm.NewAzureVirtualMachineClient( + config.GlobalCredentials(), secretClient, mgr.GetScheme(), ), @@ -794,6 +809,7 @@ func main() { Reconciler: &controllers.AsyncReconciler{ Client: mgr.GetClient(), AzureClient: vmext.NewAzureVirtualMachineExtensionClient( + config.GlobalCredentials(), secretClient, mgr.GetScheme(), ), @@ -812,7 +828,7 @@ func main() { if err = (&controllers.PostgreSQLVNetRuleReconciler{ Reconciler: &controllers.AsyncReconciler{ Client: mgr.GetClient(), - AzureClient: psqlvnetrule.NewPostgreSQLVNetRuleClient(), + AzureClient: psqlvnetrule.NewPostgreSQLVNetRuleClient(config.GlobalCredentials()), Telemetry: telemetry.InitializeTelemetryDefault( "PostgreSQLVNetRule", ctrl.Log.WithName("controllers").WithName("PostgreSQLVNetRule"), @@ -829,6 +845,7 @@ func main() { Reconciler: &controllers.AsyncReconciler{ Client: mgr.GetClient(), AzureClient: loadbalancer.NewAzureLoadBalancerClient( + config.GlobalCredentials(), secretClient, mgr.GetScheme(), ), @@ -848,6 +865,7 @@ func main() { Reconciler: &controllers.AsyncReconciler{ Client: mgr.GetClient(), AzureClient: vmss.NewAzureVMScaleSetClient( + config.GlobalCredentials(), secretClient, mgr.GetScheme(), ), @@ -866,7 +884,7 @@ func main() { if err = (&controllers.AppInsightsApiKeyReconciler{ Reconciler: &controllers.AsyncReconciler{ Client: mgr.GetClient(), - AzureClient: resourcemanagerappinsights.NewAPIKeyClient(secretClient, scheme), + AzureClient: resourcemanagerappinsights.NewAPIKeyClient(config.GlobalCredentials(), secretClient, scheme), Telemetry: telemetry.InitializeTelemetryDefault( "AppInsightsApiKey", ctrl.Log.WithName("controllers").WithName("AppInsightsApiKey"), diff --git a/pkg/resourcemanager/apim/apimgmt/apimgmt.go b/pkg/resourcemanager/apim/apimgmt/apimgmt.go index 0e167d0b100..29f84899e95 100644 --- a/pkg/resourcemanager/apim/apimgmt/apimgmt.go +++ b/pkg/resourcemanager/apim/apimgmt/apimgmt.go @@ -19,16 +19,19 @@ import ( "github.com/Azure/azure-service-operator/pkg/helpers" "github.com/Azure/azure-service-operator/pkg/resourcemanager" "github.com/Azure/azure-service-operator/pkg/resourcemanager/apim/apimshared" + "github.com/Azure/azure-service-operator/pkg/resourcemanager/config" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/to" ) // Manager represents an API Management type -type Manager struct{} +type Manager struct { + creds config.Credentials +} // NewManager returns an API Manager type -func NewManager() *Manager { - return &Manager{} +func NewManager(creds config.Credentials) *Manager { + return &Manager{creds: creds} } // CreateAPI creates an API within an API management service @@ -60,13 +63,13 @@ func (m *Manager) CreateAPI( } // Fetch the parent API Management service the API will reside under - svc, err := apimshared.GetAPIMgmtSvc(ctx, resourceGroupName, apiServiceName) + svc, err := apimshared.GetAPIMgmtSvc(ctx, m.creds, resourceGroupName, apiServiceName) if err != nil { // If there is no parent APIM service, we cannot proceed return apimanagement.APIContract{}, err } - apiClient, err := apimshared.GetAPIMClient() + apiClient, err := apimshared.GetAPIMClient(m.creds) if err != nil { return apimanagement.APIContract{}, err } @@ -83,7 +86,7 @@ func (m *Manager) CreateAPI( // DeleteAPI deletes an API within an API management service func (m *Manager) DeleteAPI(ctx context.Context, resourceGroupName string, apiServiceName string, apiID string, eTag string, deleteRevisions bool) (autorest.Response, error) { - apiClient, err := apimshared.GetAPIMClient() + apiClient, err := apimshared.GetAPIMClient(m.creds) if err != nil { return autorest.Response{ Response: &http.Response{ @@ -100,7 +103,7 @@ func (m *Manager) DeleteAPI(ctx context.Context, resourceGroupName string, apiSe // GetAPI fetches an API within an API management service func (m *Manager) GetAPI(ctx context.Context, resourceGroupName string, apiServiceName string, apiID string) (apimanagement.APIContract, error) { - apiClient, err := apimshared.GetAPIMClient() + apiClient, err := apimshared.GetAPIMClient(m.creds) if err != nil { return apimanagement.APIContract{}, err } @@ -116,7 +119,7 @@ func (m *Manager) Ensure(ctx context.Context, obj runtime.Object, opts ...resour } // Attempt to fetch the parent API Management service the API will or does reside within - svc, err := apimshared.GetAPIMgmtSvc(ctx, instance.Spec.ResourceGroup, instance.Spec.APIService) + svc, err := apimshared.GetAPIMgmtSvc(ctx, m.creds, instance.Spec.ResourceGroup, instance.Spec.APIService) if err != nil { instance.Status.Message = err.Error() // If there is no parent APIM service, we cannot proceed diff --git a/pkg/resourcemanager/apim/apimgmt/suite_test.go b/pkg/resourcemanager/apim/apimgmt/suite_test.go index b23524267a1..fa1c5493b1d 100644 --- a/pkg/resourcemanager/apim/apimgmt/suite_test.go +++ b/pkg/resourcemanager/apim/apimgmt/suite_test.go @@ -9,6 +9,7 @@ import ( "context" + "github.com/Azure/azure-service-operator/pkg/resourcemanager/config" resourcemanagerconfig "github.com/Azure/azure-service-operator/pkg/resourcemanager/config" resourcegroupsresourcemanager "github.com/Azure/azure-service-operator/pkg/resourcemanager/resourcegroups" . "github.com/onsi/ginkgo" @@ -52,7 +53,7 @@ var _ = BeforeSuite(func() { resourceGroupName := "AzureOperatorsTest" resourceGroupLocation := resourcemanagerconfig.DefaultLocation() - resourceGroupManager := resourcegroupsresourcemanager.NewAzureResourceGroupManager() + resourceGroupManager := resourcegroupsresourcemanager.NewAzureResourceGroupManager(config.GlobalCredentials()) //create resourcegroup for this suite _, err = resourceGroupManager.CreateGroup(ctx, resourceGroupName, resourceGroupLocation) @@ -61,7 +62,7 @@ var _ = BeforeSuite(func() { tc = TestContext{ ResourceGroupName: resourceGroupName, ResourceGroupLocation: resourceGroupLocation, - APIManager: NewManager(), + APIManager: NewManager(config.GlobalCredentials()), ResourceGroupManager: resourceGroupManager, timeout: 20 * time.Minute, retryInterval: 3 * time.Second, diff --git a/pkg/resourcemanager/apim/apimservice/apimservice.go b/pkg/resourcemanager/apim/apimservice/apimservice.go index ee88f9ce99f..5c47c032f6b 100644 --- a/pkg/resourcemanager/apim/apimservice/apimservice.go +++ b/pkg/resourcemanager/apim/apimservice/apimservice.go @@ -10,17 +10,19 @@ import ( apim "github.com/Azure/azure-sdk-for-go/services/apimanagement/mgmt/2019-01-01/apimanagement" apimshared "github.com/Azure/azure-service-operator/pkg/resourcemanager/apim/apimshared" + "github.com/Azure/azure-service-operator/pkg/resourcemanager/config" telemetry "github.com/Azure/azure-service-operator/pkg/telemetry" "github.com/Azure/go-autorest/autorest/to" ) type AzureAPIMgmtServiceManager struct { + Creds config.Credentials Telemetry telemetry.Telemetry } // CreateAPIMgmtSvc creates a new API Mgmt Svc -func (_ *AzureAPIMgmtServiceManager) CreateAPIMgmtSvc(ctx context.Context, tier string, location string, resourceGroupName string, resourceName string, publisherName string, publisherEmail string) (*apim.ServiceResource, error) { - client, err := apimshared.GetAPIMgmtSvcClient() +func (m *AzureAPIMgmtServiceManager) CreateAPIMgmtSvc(ctx context.Context, tier string, location string, resourceGroupName string, resourceName string, publisherName string, publisherEmail string) (*apim.ServiceResource, error) { + client, err := apimshared.GetAPIMgmtSvcClient(m.Creds) if err != nil { return nil, err } @@ -60,8 +62,8 @@ func (_ *AzureAPIMgmtServiceManager) CreateAPIMgmtSvc(ctx context.Context, tier } // DeleteAPIMgmtSvc deletes an instance of an API Mgmt Svc -func (_ *AzureAPIMgmtServiceManager) DeleteAPIMgmtSvc(ctx context.Context, resourceGroupName string, resourceName string) (*apim.ServiceResource, error) { - client, err := apimshared.GetAPIMgmtSvcClient() +func (m *AzureAPIMgmtServiceManager) DeleteAPIMgmtSvc(ctx context.Context, resourceGroupName string, resourceName string) (*apim.ServiceResource, error) { + client, err := apimshared.GetAPIMgmtSvcClient(m.Creds) if err != nil { return nil, err } @@ -76,15 +78,15 @@ func (_ *AzureAPIMgmtServiceManager) DeleteAPIMgmtSvc(ctx context.Context, resou } // APIMgmtSvcStatus checks to see if the API Mgmt Svc has been activated -func (_ *AzureAPIMgmtServiceManager) APIMgmtSvcStatus(ctx context.Context, resourceGroupName string, resourceName string) (exists bool, result bool, resourceID *string, err error) { - return apimshared.APIMgmtSvcStatus(ctx, resourceGroupName, resourceName) +func (m *AzureAPIMgmtServiceManager) APIMgmtSvcStatus(ctx context.Context, resourceGroupName string, resourceName string) (exists bool, result bool, resourceID *string, err error) { + return apimshared.APIMgmtSvcStatus(ctx, m.Creds, resourceGroupName, resourceName) } // SetVNetForAPIMgmtSvc sets the VNet for an API Mgmt Svc by name (only if it hasn't been previously set) -func (g *AzureAPIMgmtServiceManager) SetVNetForAPIMgmtSvc(ctx context.Context, resourceGroupName string, resourceName string, vnetType string, vnetResourceGroupName string, vnetResourceName string, subnetName string) (err error, updated bool) { +func (m *AzureAPIMgmtServiceManager) SetVNetForAPIMgmtSvc(ctx context.Context, resourceGroupName string, resourceName string, vnetType string, vnetResourceGroupName string, vnetResourceName string, subnetName string) (err error, updated bool) { // check to make sure that the API Mgmt Svc has been activated - exists, activated, _, err := g.APIMgmtSvcStatus(ctx, resourceGroupName, resourceName) + exists, activated, _, err := m.APIMgmtSvcStatus(ctx, resourceGroupName, resourceName) if !exists || !activated || err != nil { return fmt.Errorf("API Mgmt Service hasn't been created or activated yet: %s, %s", resourceGroupName, resourceName), false } @@ -100,18 +102,18 @@ func (g *AzureAPIMgmtServiceManager) SetVNetForAPIMgmtSvc(ctx context.Context, r } // get the subnet configuration - subnetConfig, err := apimshared.GetSubnetConfigurationByName(ctx, vnetResourceGroupName, vnetResourceName, subnetName) + subnetConfig, err := apimshared.GetSubnetConfigurationByName(ctx, m.Creds, vnetResourceGroupName, vnetResourceName, subnetName) if err != nil { return err, false } - client, err := apimshared.GetAPIMgmtSvcClient() + client, err := apimshared.GetAPIMgmtSvcClient(m.Creds) if err != nil { return err, false } // check to make sure that the VPN hasn't already been added to the APIM svc - apimsvc, err := apimshared.GetAPIMgmtSvc(ctx, resourceGroupName, resourceName) + apimsvc, err := apimshared.GetAPIMgmtSvc(ctx, m.Creds, resourceGroupName, resourceName) if err != nil { return err, false } @@ -146,10 +148,10 @@ func (g *AzureAPIMgmtServiceManager) SetVNetForAPIMgmtSvc(ctx context.Context, r } // SetAppInsightsForAPIMgmtSvc sets the app insight instance to use with the service -func (g *AzureAPIMgmtServiceManager) SetAppInsightsForAPIMgmtSvc(ctx context.Context, resourceGroupName string, resourceName string, appInsightsResourceGroup string, appInsightsName string) error { +func (m *AzureAPIMgmtServiceManager) SetAppInsightsForAPIMgmtSvc(ctx context.Context, resourceGroupName string, resourceName string, appInsightsResourceGroup string, appInsightsName string) error { // check to make sure app insight exists - insight, err := apimshared.GetAppInstanceIDByName(ctx, appInsightsResourceGroup, appInsightsName) + insight, err := apimshared.GetAppInstanceIDByName(ctx, m.Creds, appInsightsResourceGroup, appInsightsName) if err != nil { return err } else if insight.ID == nil || insight.InstrumentationKey == nil { @@ -157,7 +159,7 @@ func (g *AzureAPIMgmtServiceManager) SetAppInsightsForAPIMgmtSvc(ctx context.Con } // check to make sure that the API Mgmt Svc has been activated - exists, activated, _, err := g.APIMgmtSvcStatus(ctx, resourceGroupName, resourceName) + exists, activated, _, err := m.APIMgmtSvcStatus(ctx, resourceGroupName, resourceName) if !exists || !activated || err != nil { return fmt.Errorf("API Mgmt Service hasn't been created or activated yet: %s, %s", resourceGroupName, resourceName) } @@ -165,6 +167,7 @@ func (g *AzureAPIMgmtServiceManager) SetAppInsightsForAPIMgmtSvc(ctx context.Con // get the etag for apim service apimsvc, err := apimshared.GetAPIMgmtSvc( ctx, + m.Creds, resourceGroupName, resourceName, ) @@ -174,7 +177,7 @@ func (g *AzureAPIMgmtServiceManager) SetAppInsightsForAPIMgmtSvc(ctx context.Con return fmt.Errorf("could not find API Mgmt Service %s, %s", resourceGroupName, resourceName) } - loggerClient, err := apimshared.GetAPIMgmtLoggerClient() + loggerClient, err := apimshared.GetAPIMgmtLoggerClient(m.Creds) if err != nil { return err } @@ -214,6 +217,6 @@ func (g *AzureAPIMgmtServiceManager) SetAppInsightsForAPIMgmtSvc(ctx context.Con } // CheckAPIMgmtSvcName checks to see if the APIM service name is available -func (g *AzureAPIMgmtServiceManager) CheckAPIMgmtSvcName(ctx context.Context, resourceName string) (available bool, err error) { - return apimshared.CheckAPIMgmtSvcName(ctx, resourceName) +func (m *AzureAPIMgmtServiceManager) CheckAPIMgmtSvcName(ctx context.Context, resourceName string) (available bool, err error) { + return apimshared.CheckAPIMgmtSvcName(ctx, m.Creds, resourceName) } diff --git a/pkg/resourcemanager/apim/apimservice/apimservice_manager.go b/pkg/resourcemanager/apim/apimservice/apimservice_manager.go index d887c9a938f..a658c2b2e94 100644 --- a/pkg/resourcemanager/apim/apimservice/apimservice_manager.go +++ b/pkg/resourcemanager/apim/apimservice/apimservice_manager.go @@ -8,13 +8,15 @@ import ( apim "github.com/Azure/azure-sdk-for-go/services/apimanagement/mgmt/2019-01-01/apimanagement" "github.com/Azure/azure-service-operator/pkg/resourcemanager" + "github.com/Azure/azure-service-operator/pkg/resourcemanager/config" telemetry "github.com/Azure/azure-service-operator/pkg/telemetry" ctrl "sigs.k8s.io/controller-runtime" ) // NewAzureAPIMgmtServiceManager creates a new instance of AzureAPIMgmtServiceManager -func NewAzureAPIMgmtServiceManager() *AzureAPIMgmtServiceManager { +func NewAzureAPIMgmtServiceManager(creds config.Credentials) *AzureAPIMgmtServiceManager { return &AzureAPIMgmtServiceManager{ + Creds: creds, Telemetry: *telemetry.InitializeTelemetryDefault( "ApimService", ctrl.Log.WithName("controllers").WithName("ApimService"), diff --git a/pkg/resourcemanager/apim/apimshared/common.go b/pkg/resourcemanager/apim/apimshared/common.go index 1e334292364..eb063b41e06 100644 --- a/pkg/resourcemanager/apim/apimshared/common.go +++ b/pkg/resourcemanager/apim/apimshared/common.go @@ -16,9 +16,9 @@ import ( ) // GetAPIMgmtSvcClient returns a new instance of an API Svc client -func GetAPIMgmtSvcClient() (apim.ServiceClient, error) { - client := apim.NewServiceClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, err := iam.GetResourceManagementAuthorizer() +func GetAPIMgmtSvcClient(creds config.Credentials) (apim.ServiceClient, error) { + client := apim.NewServiceClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, err := iam.GetResourceManagementAuthorizer(creds) if err != nil { client = apim.ServiceClient{} } else { @@ -29,9 +29,9 @@ func GetAPIMgmtSvcClient() (apim.ServiceClient, error) { } // GetVNetClient returns a new instance of an VirtualNetwork client -func GetVNetClient() (vnet.VirtualNetworksClient, error) { - client := vnet.NewVirtualNetworksClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, err := iam.GetResourceManagementAuthorizer() +func GetVNetClient(creds config.Credentials) (vnet.VirtualNetworksClient, error) { + client := vnet.NewVirtualNetworksClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, err := iam.GetResourceManagementAuthorizer(creds) if err != nil { client = vnet.VirtualNetworksClient{} } else { @@ -42,9 +42,9 @@ func GetVNetClient() (vnet.VirtualNetworksClient, error) { } // GetAPIMgmtLoggerClient returns a new instance of an VirtualNetwork client -func GetAPIMgmtLoggerClient() (apim.LoggerClient, error) { - client := apim.NewLoggerClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, err := iam.GetResourceManagementAuthorizer() +func GetAPIMgmtLoggerClient(creds config.Credentials) (apim.LoggerClient, error) { + client := apim.NewLoggerClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, err := iam.GetResourceManagementAuthorizer(creds) if err != nil { client = apim.LoggerClient{} } else { @@ -55,9 +55,9 @@ func GetAPIMgmtLoggerClient() (apim.LoggerClient, error) { } // GetInsightsClient retrieves a client -func GetInsightsClient() (insights.ComponentsClient, error) { - client := insights.NewComponentsClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, err := iam.GetResourceManagementAuthorizer() +func GetInsightsClient(creds config.Credentials) (insights.ComponentsClient, error) { + client := insights.NewComponentsClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, err := iam.GetResourceManagementAuthorizer(creds) if err != nil { client = insights.ComponentsClient{} } else { @@ -68,8 +68,8 @@ func GetInsightsClient() (insights.ComponentsClient, error) { } // GetAPIMgmtSvc returns an instance of an APIM service -func GetAPIMgmtSvc(ctx context.Context, resourceGroupName string, resourceName string) (apim.ServiceResource, error) { - client, err := GetAPIMgmtSvcClient() +func GetAPIMgmtSvc(ctx context.Context, creds config.Credentials, resourceGroupName, resourceName string) (apim.ServiceResource, error) { + client, err := GetAPIMgmtSvcClient(creds) if err != nil { return apim.ServiceResource{}, err } @@ -82,9 +82,10 @@ func GetAPIMgmtSvc(ctx context.Context, resourceGroupName string, resourceName s } // APIMgmtSvcStatus check to see if the API Mgmt Svc has been activated, returns "true" if it has been activated -func APIMgmtSvcStatus(ctx context.Context, resourceGroupName string, resourceName string) (exists bool, result bool, resourceID *string, err error) { +func APIMgmtSvcStatus(ctx context.Context, creds config.Credentials, resourceGroupName, resourceName string) (exists bool, result bool, resourceID *string, err error) { resource, err := GetAPIMgmtSvc( ctx, + creds, resourceGroupName, resourceName, ) @@ -107,8 +108,8 @@ func APIMgmtSvcStatus(ctx context.Context, resourceGroupName string, resourceNam } // GetSubnetConfigurationByName gets a VNet by name -func GetSubnetConfigurationByName(ctx context.Context, resourceGroupName string, resourceName string, subnetName string) (apim.VirtualNetworkConfiguration, error) { - client, err := GetVNetClient() +func GetSubnetConfigurationByName(ctx context.Context, creds config.Credentials, resourceGroupName, resourceName, subnetName string) (apim.VirtualNetworkConfiguration, error) { + client, err := GetVNetClient(creds) if err != nil { return apim.VirtualNetworkConfiguration{}, err } @@ -148,8 +149,8 @@ func GetSubnetConfigurationByName(ctx context.Context, resourceGroupName string, } // CheckAPIMgmtSvcName checks to see if the APIM service name is available -func CheckAPIMgmtSvcName(ctx context.Context, resourceName string) (available bool, err error) { - client, err := GetAPIMgmtSvcClient() +func CheckAPIMgmtSvcName(ctx context.Context, creds config.Credentials, resourceName string) (available bool, err error) { + client, err := GetAPIMgmtSvcClient(creds) if err != nil { return false, err } @@ -170,8 +171,8 @@ func CheckAPIMgmtSvcName(ctx context.Context, resourceName string) (available bo } // GetAppInstanceIDByName retrieves an app insight by name -func GetAppInstanceIDByName(ctx context.Context, resourceGroup string, resourceName string) (insights.ApplicationInsightsComponent, error) { - client, err := GetInsightsClient() +func GetAppInstanceIDByName(ctx context.Context, creds config.Credentials, resourceGroup, resourceName string) (insights.ApplicationInsightsComponent, error) { + client, err := GetInsightsClient(creds) if err != nil { return insights.ApplicationInsightsComponent{}, err } @@ -184,10 +185,10 @@ func GetAppInstanceIDByName(ctx context.Context, resourceGroup string, resourceN } // GetAPIMClient returns a pointer to an API Management client -func GetAPIMClient() (apim.APIClient, error) { - apimClient := apim.NewAPIClient(config.SubscriptionID()) +func GetAPIMClient(creds config.Credentials) (apim.APIClient, error) { + apimClient := apim.NewAPIClient(creds.SubscriptionID()) - a, err := iam.GetResourceManagementAuthorizer() + a, err := iam.GetResourceManagementAuthorizer(creds) if err != nil { return apim.APIClient{}, err } diff --git a/pkg/resourcemanager/appinsights/api_keys_client.go b/pkg/resourcemanager/appinsights/api_keys_client.go index 3266b79c986..e5a5e69f6fd 100644 --- a/pkg/resourcemanager/appinsights/api_keys_client.go +++ b/pkg/resourcemanager/appinsights/api_keys_client.go @@ -15,20 +15,22 @@ import ( ) type InsightsAPIKeysClient struct { + Creds config.Credentials SecretClient secrets.SecretClient Scheme *runtime.Scheme } -func NewAPIKeyClient(secretClient secrets.SecretClient, scheme *runtime.Scheme) *InsightsAPIKeysClient { +func NewAPIKeyClient(creds config.Credentials, secretClient secrets.SecretClient, scheme *runtime.Scheme) *InsightsAPIKeysClient { return &InsightsAPIKeysClient{ + Creds: creds, SecretClient: secretClient, Scheme: scheme, } } -func getApiKeysClient() (insights.APIKeysClient, error) { - insightsClient := insights.NewAPIKeysClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, err := iam.GetResourceManagementAuthorizer() +func getApiKeysClient(creds config.Credentials) (insights.APIKeysClient, error) { + insightsClient := insights.NewAPIKeysClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, err := iam.GetResourceManagementAuthorizer(creds) if err != nil { insightsClient = insights.APIKeysClient{} return insights.APIKeysClient{}, err @@ -43,24 +45,24 @@ func getApiKeysClient() (insights.APIKeysClient, error) { func (c *InsightsAPIKeysClient) CreateKey(ctx context.Context, resourceGroup, insightsaccount, name string, read, write, authSDK bool) (insights.ApplicationInsightsComponentAPIKey, error) { apiKey := insights.ApplicationInsightsComponentAPIKey{} - client, err := getApiKeysClient() + client, err := getApiKeysClient(c.Creds) if err != nil { return apiKey, err } readIds := []string{ - fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/microsoft.insights/components/%s/api", config.SubscriptionID(), resourceGroup, insightsaccount), - fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/microsoft.insights/components/%s/draft", config.SubscriptionID(), resourceGroup, insightsaccount), - fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/microsoft.insights/components/%s/extendqueries", config.SubscriptionID(), resourceGroup, insightsaccount), - fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/microsoft.insights/components/%s/search", config.SubscriptionID(), resourceGroup, insightsaccount), - fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/microsoft.insights/components/%s/aggregate", config.SubscriptionID(), resourceGroup, insightsaccount), + fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/microsoft.insights/components/%s/api", c.Creds.SubscriptionID(), resourceGroup, insightsaccount), + fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/microsoft.insights/components/%s/draft", c.Creds.SubscriptionID(), resourceGroup, insightsaccount), + fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/microsoft.insights/components/%s/extendqueries", c.Creds.SubscriptionID(), resourceGroup, insightsaccount), + fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/microsoft.insights/components/%s/search", c.Creds.SubscriptionID(), resourceGroup, insightsaccount), + fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/microsoft.insights/components/%s/aggregate", c.Creds.SubscriptionID(), resourceGroup, insightsaccount), } writeIds := []string{ - fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/microsoft.insights/components/%s/annotations", config.SubscriptionID(), resourceGroup, insightsaccount), + fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/microsoft.insights/components/%s/annotations", c.Creds.SubscriptionID(), resourceGroup, insightsaccount), } - authSDKControl := []string{fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/microsoft.insights/components/%s/agentconfig", config.SubscriptionID(), resourceGroup, insightsaccount)} + authSDKControl := []string{fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/microsoft.insights/components/%s/agentconfig", c.Creds.SubscriptionID(), resourceGroup, insightsaccount)} keyprops := insights.APIKeyRequest{ Name: &name, @@ -97,7 +99,7 @@ func (c *InsightsAPIKeysClient) CreateKey(ctx context.Context, resourceGroup, in } func (c *InsightsAPIKeysClient) DeleteKey(ctx context.Context, resourceGroup, insightsaccount, name string) error { - client, err := getApiKeysClient() + client, err := getApiKeysClient(c.Creds) if err != nil { return err } @@ -111,7 +113,7 @@ func (c *InsightsAPIKeysClient) DeleteKey(ctx context.Context, resourceGroup, in func (c *InsightsAPIKeysClient) GetKey(ctx context.Context, resourceGroup, insightsaccount, name string) (insights.ApplicationInsightsComponentAPIKey, error) { result := insights.ApplicationInsightsComponentAPIKey{} - client, err := getApiKeysClient() + client, err := getApiKeysClient(c.Creds) if err != nil { return result, err } @@ -126,7 +128,7 @@ func (c *InsightsAPIKeysClient) GetKey(ctx context.Context, resourceGroup, insig func (c *InsightsAPIKeysClient) ListKeys(ctx context.Context, resourceGroup, insightsaccount string) (insights.ApplicationInsightsComponentAPIKeyListResult, error) { result := insights.ApplicationInsightsComponentAPIKeyListResult{} - client, err := getApiKeysClient() + client, err := getApiKeysClient(c.Creds) if err != nil { return result, err } diff --git a/pkg/resourcemanager/appinsights/appinsights.go b/pkg/resourcemanager/appinsights/appinsights.go index d7642c2c1ea..90d2b7e6ce6 100644 --- a/pkg/resourcemanager/appinsights/appinsights.go +++ b/pkg/resourcemanager/appinsights/appinsights.go @@ -25,13 +25,15 @@ import ( // Manager manages Azure Application Insights services type Manager struct { + Creds config.Credentials SecretClient secrets.SecretClient Scheme *runtime.Scheme } // NewManager creates a new AppInsights Manager -func NewManager(secretClient secrets.SecretClient, scheme *runtime.Scheme) *Manager { +func NewManager(creds config.Credentials, secretClient secrets.SecretClient, scheme *runtime.Scheme) *Manager { return &Manager{ + Creds: creds, SecretClient: secretClient, Scheme: scheme, } @@ -80,7 +82,7 @@ func (m *Manager) CreateAppInsights( location string, resourceName string) (*insights.ApplicationInsightsComponent, error) { - componentsClient, err := getComponentsClient() + componentsClient, err := getComponentsClient(m.Creds) if err != nil { return nil, err } @@ -280,7 +282,7 @@ func (m *Manager) DeleteAppInsights( resourceGroupName string, resourceName string) (autorest.Response, error) { - componentsClient, err := getComponentsClient() + componentsClient, err := getComponentsClient(m.Creds) if err != nil { return autorest.Response{Response: &http.Response{StatusCode: 500}}, err } @@ -298,16 +300,16 @@ func (m *Manager) GetAppInsights( resourceGroupName string, resourceName string) (insights.ApplicationInsightsComponent, error) { - componentsClient, err := getComponentsClient() + componentsClient, err := getComponentsClient(m.Creds) if err != nil { return insights.ApplicationInsightsComponent{}, err } return componentsClient.Get(ctx, resourceGroupName, resourceName) } -func getComponentsClient() (insights.ComponentsClient, error) { - insightsClient := insights.NewComponentsClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, err := iam.GetResourceManagementAuthorizer() +func getComponentsClient(creds config.Credentials) (insights.ComponentsClient, error) { + insightsClient := insights.NewComponentsClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, err := iam.GetResourceManagementAuthorizer(creds) if err != nil { insightsClient = insights.ComponentsClient{} } else { diff --git a/pkg/resourcemanager/appinsights/suite_test.go b/pkg/resourcemanager/appinsights/suite_test.go index 852ace59df0..5501eb8d10a 100644 --- a/pkg/resourcemanager/appinsights/suite_test.go +++ b/pkg/resourcemanager/appinsights/suite_test.go @@ -13,6 +13,7 @@ import ( "context" + "github.com/Azure/azure-service-operator/pkg/resourcemanager/config" resourcemanagerconfig "github.com/Azure/azure-service-operator/pkg/resourcemanager/config" resourcegroupsresourcemanager "github.com/Azure/azure-service-operator/pkg/resourcemanager/resourcegroups" . "github.com/onsi/ginkgo" @@ -58,7 +59,7 @@ var _ = BeforeSuite(func() { resourceGroupName := "t-rg-appinsights-" + helpers.RandomString(10) resourceGroupLocation := resourcemanagerconfig.DefaultLocation() - resourceGroupManager := resourcegroupsresourcemanager.NewAzureResourceGroupManager() + resourceGroupManager := resourcegroupsresourcemanager.NewAzureResourceGroupManager(config.GlobalCredentials()) //create resourcegroup for this suite _, err = resourceGroupManager.CreateGroup(ctx, resourceGroupName, resourceGroupLocation) @@ -88,7 +89,8 @@ var _ = AfterSuite(func() { for { time.Sleep(time.Second * 10) - _, err := resourcegroupsresourcemanager.GetGroup(ctx, tc.ResourceGroupName) + rgManager := resourcegroupsresourcemanager.NewAzureResourceGroupManager(config.GlobalCredentials()) + _, err := rgManager.GetGroup(ctx, tc.ResourceGroupName) if err == nil { log.Println("waiting for resource group to be deleted") } else { diff --git a/pkg/resourcemanager/azuresql/azuresqlaction/azuresqlaction.go b/pkg/resourcemanager/azuresql/azuresqlaction/azuresqlaction.go index 26629dd5d63..05e21946a6e 100644 --- a/pkg/resourcemanager/azuresql/azuresqlaction/azuresqlaction.go +++ b/pkg/resourcemanager/azuresql/azuresqlaction/azuresqlaction.go @@ -14,6 +14,7 @@ import ( azuresqlserver "github.com/Azure/azure-service-operator/pkg/resourcemanager/azuresql/azuresqlserver" "github.com/Azure/azure-service-operator/pkg/resourcemanager/azuresql/azuresqlshared" azuresqluser "github.com/Azure/azure-service-operator/pkg/resourcemanager/azuresql/azuresqluser" + "github.com/Azure/azure-service-operator/pkg/resourcemanager/config" "github.com/Azure/azure-service-operator/pkg/secrets" "github.com/Azure/go-autorest/autorest/to" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -22,12 +23,14 @@ import ( ) type AzureSqlActionManager struct { + Creds config.Credentials SecretClient secrets.SecretClient Scheme *runtime.Scheme } -func NewAzureSqlActionManager(secretClient secrets.SecretClient, scheme *runtime.Scheme) *AzureSqlActionManager { +func NewAzureSqlActionManager(creds config.Credentials, secretClient secrets.SecretClient, scheme *runtime.Scheme) *AzureSqlActionManager { return &AzureSqlActionManager{ + Creds: creds, SecretClient: secretClient, Scheme: scheme, } @@ -40,7 +43,7 @@ func (s *AzureSqlActionManager) UpdateUserPassword(ctx context.Context, groupNam return err } - azuresqluserManager := azuresqluser.NewAzureSqlUserManager(userSecretClient, s.Scheme) + azuresqluserManager := azuresqluser.NewAzureSqlUserManager(s.Creds, userSecretClient, s.Scheme) db, err := azuresqluserManager.ConnectToSqlDb(ctx, "sqlserver", serverName, dbName, 1433, string(data["username"]), string(data["password"])) if err != nil { return err @@ -96,7 +99,7 @@ func (s *AzureSqlActionManager) UpdateUserPassword(ctx context.Context, groupNam // for the server and stores the new password in the secret func (s *AzureSqlActionManager) UpdateAdminPassword(ctx context.Context, groupName string, serverName string, secretKey types.NamespacedName, secretClient secrets.SecretClient) error { - azuresqlserverManager := azuresqlserver.NewAzureSqlServerManager(secretClient, s.Scheme) + azuresqlserverManager := azuresqlserver.NewAzureSqlServerManager(s.Creds, secretClient, s.Scheme) // Get the SQL server instance server, err := azuresqlserverManager.GetServer(ctx, groupName, serverName) if err != nil { diff --git a/pkg/resourcemanager/azuresql/azuresqlaction/azuresqlaction_reconcile.go b/pkg/resourcemanager/azuresql/azuresqlaction/azuresqlaction_reconcile.go index 8b1dd147221..2005d8adbe7 100644 --- a/pkg/resourcemanager/azuresql/azuresqlaction/azuresqlaction_reconcile.go +++ b/pkg/resourcemanager/azuresql/azuresqlaction/azuresqlaction_reconcile.go @@ -48,7 +48,7 @@ func (s *AzureSqlActionManager) Ensure(ctx context.Context, obj runtime.Object, if len(instance.Spec.ServerSecretKeyVault) == 0 { adminSecretClient = s.SecretClient } else { - adminSecretClient = keyvaultsecretlib.New(instance.Spec.ServerSecretKeyVault) + adminSecretClient = keyvaultsecretlib.New(instance.Spec.ServerSecretKeyVault, s.Creds) if !keyvaultsecretlib.IsKeyVaultAccessible(adminSecretClient) { instance.Status.Message = "InvalidKeyVaultAccess: Keyvault not accessible yet" return false, nil @@ -96,7 +96,7 @@ func (s *AzureSqlActionManager) Ensure(ctx context.Context, obj runtime.Object, if len(instance.Spec.ServerSecretKeyVault) == 0 { adminSecretClient = s.SecretClient } else { - adminSecretClient = keyvaultsecretlib.New(instance.Spec.ServerSecretKeyVault) + adminSecretClient = keyvaultsecretlib.New(instance.Spec.ServerSecretKeyVault, s.Creds) if !keyvaultsecretlib.IsKeyVaultAccessible(adminSecretClient) { instance.Status.Message = "InvalidKeyVaultAccess: Keyvault not accessible yet" return false, nil @@ -108,7 +108,7 @@ func (s *AzureSqlActionManager) Ensure(ctx context.Context, obj runtime.Object, if len(instance.Spec.UserSecretKeyVault) == 0 { userSecretClient = s.SecretClient } else { - userSecretClient = keyvaultsecretlib.New(instance.Spec.UserSecretKeyVault) + userSecretClient = keyvaultsecretlib.New(instance.Spec.UserSecretKeyVault, s.Creds) if !keyvaultsecretlib.IsKeyVaultAccessible(userSecretClient) { instance.Status.Message = "InvalidKeyVaultAccess: Keyvault not accessible yet" return false, nil diff --git a/pkg/resourcemanager/azuresql/azuresqldb/azuresqldb.go b/pkg/resourcemanager/azuresql/azuresqldb/azuresqldb.go index 39625e0dd4c..937657cd35c 100644 --- a/pkg/resourcemanager/azuresql/azuresqldb/azuresqldb.go +++ b/pkg/resourcemanager/azuresql/azuresqldb/azuresqldb.go @@ -11,23 +11,25 @@ import ( "github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/v3.0/sql" sql3 "github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/v3.0/sql" azuresqlshared "github.com/Azure/azure-service-operator/pkg/resourcemanager/azuresql/azuresqlshared" + "github.com/Azure/azure-service-operator/pkg/resourcemanager/config" "github.com/Azure/go-autorest/autorest/to" ) type AzureSqlDbManager struct { + creds config.Credentials } // Ensure we implement the interface we expect var _ SqlDbManager = &AzureSqlDbManager{} -func NewAzureSqlDbManager() *AzureSqlDbManager { - return &AzureSqlDbManager{} +func NewAzureSqlDbManager(creds config.Credentials) *AzureSqlDbManager { + return &AzureSqlDbManager{creds: creds} } // GetServer returns a SQL server -func (_ *AzureSqlDbManager) GetServer(ctx context.Context, resourceGroupName string, serverName string) (result sql.Server, err error) { - serversClient, err := azuresqlshared.GetGoServersClient() +func (m *AzureSqlDbManager) GetServer(ctx context.Context, resourceGroupName string, serverName string) (result sql.Server, err error) { + serversClient, err := azuresqlshared.GetGoServersClient(m.creds) if err != nil { return sql.Server{}, err } @@ -40,8 +42,8 @@ func (_ *AzureSqlDbManager) GetServer(ctx context.Context, resourceGroupName str } // GetDB retrieves a database -func (_ *AzureSqlDbManager) GetDB(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (sql.Database, error) { - dbClient, err := azuresqlshared.GetGoDbClient() +func (m *AzureSqlDbManager) GetDB(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (sql.Database, error) { + dbClient, err := azuresqlshared.GetGoDbClient(m.creds) if err != nil { return sql.Database{}, err } @@ -55,25 +57,25 @@ func (_ *AzureSqlDbManager) GetDB(ctx context.Context, resourceGroupName string, } // DeleteDB deletes a DB -func (sdk *AzureSqlDbManager) DeleteDB( +func (m *AzureSqlDbManager) DeleteDB( ctx context.Context, resourceGroupName string, serverName string, databaseName string) (future *sql.DatabasesDeleteFuture, err error) { // check to see if the server exists, if it doesn't then short-circuit - server, err := sdk.GetServer(ctx, resourceGroupName, serverName) + server, err := m.GetServer(ctx, resourceGroupName, serverName) if err != nil || *server.State != "Ready" { return nil, nil } // check to see if the db exists, if it doesn't then short-circuit - _, err = sdk.GetDB(ctx, resourceGroupName, serverName, databaseName) + _, err = m.GetDB(ctx, resourceGroupName, serverName, databaseName) if err != nil { return nil, nil } - dbClient, err := azuresqlshared.GetGoDbClient() + dbClient, err := azuresqlshared.GetGoDbClient(m.creds) if err != nil { return nil, err } @@ -93,7 +95,7 @@ func (sdk *AzureSqlDbManager) DeleteDB( } // CreateOrUpdateDB creates or updates a DB in Azure -func (_ *AzureSqlDbManager) CreateOrUpdateDB( +func (m *AzureSqlDbManager) CreateOrUpdateDB( ctx context.Context, resourceGroupName string, location string, @@ -101,7 +103,7 @@ func (_ *AzureSqlDbManager) CreateOrUpdateDB( tags map[string]*string, properties azuresqlshared.SQLDatabaseProperties) (string, *sql.Database, error) { - dbClient, err := azuresqlshared.GetGoDbClient() + dbClient, err := azuresqlshared.GetGoDbClient(m.creds) if err != nil { return "", nil, err } @@ -131,9 +133,9 @@ func (_ *AzureSqlDbManager) CreateOrUpdateDB( } // AddLongTermRetention enables / disables long term retention -func (_ *AzureSqlDbManager) AddLongTermRetention(ctx context.Context, resourceGroupName string, serverName string, databaseName string, weeklyRetention string, monthlyRetention string, yearlyRetention string, weekOfYear int32) (*http.Response, error) { +func (m *AzureSqlDbManager) AddLongTermRetention(ctx context.Context, resourceGroupName string, serverName string, databaseName string, weeklyRetention string, monthlyRetention string, yearlyRetention string, weekOfYear int32) (*http.Response, error) { - longTermClient, err := azuresqlshared.GetBackupLongTermRetentionPoliciesClient() + longTermClient, err := azuresqlshared.GetBackupLongTermRetentionPoliciesClient(m.creds) // TODO: Probably shouldn't return a response at all in the err case here (all through this function) if err != nil { return &http.Response{ diff --git a/pkg/resourcemanager/azuresql/azuresqldb/azuresqldb_reconcile.go b/pkg/resourcemanager/azuresql/azuresqldb/azuresqldb_reconcile.go index 3414013c4e4..6110dda2072 100644 --- a/pkg/resourcemanager/azuresql/azuresqldb/azuresqldb_reconcile.go +++ b/pkg/resourcemanager/azuresql/azuresqldb/azuresqldb_reconcile.go @@ -6,18 +6,19 @@ package azuresqldb import ( "context" "fmt" - "github.com/Azure/azure-service-operator/pkg/resourcemanager/pollclient" "net/http" "strings" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + azurev1alpha1 "github.com/Azure/azure-service-operator/api/v1alpha1" "github.com/Azure/azure-service-operator/api/v1beta1" "github.com/Azure/azure-service-operator/pkg/errhelp" "github.com/Azure/azure-service-operator/pkg/helpers" "github.com/Azure/azure-service-operator/pkg/resourcemanager" azuresqlshared "github.com/Azure/azure-service-operator/pkg/resourcemanager/azuresql/azuresqlshared" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/types" + "github.com/Azure/azure-service-operator/pkg/resourcemanager/pollclient" ) // Ensure creates an AzureSqlDb @@ -65,7 +66,7 @@ func (db *AzureSqlDbManager) Ensure(ctx context.Context, obj runtime.Object, opt // Before we attempt to issue a new update, check if there is a previously ongoing update if instance.Status.PollingURL != "" { // TODO: There are other places which use PollClient which may or may not need this treatment as well... - pClient := pollclient.NewPollClient() + pClient := pollclient.NewPollClient(db.creds) res, err := pClient.Get(ctx, instance.Status.PollingURL) pollErr := errhelp.NewAzureError(err) if pollErr != nil { diff --git a/pkg/resourcemanager/azuresql/azuresqlfailovergroup/azuresqlfailovergroup.go b/pkg/resourcemanager/azuresql/azuresqlfailovergroup/azuresqlfailovergroup.go index ca12ee5c055..fca7fe26276 100644 --- a/pkg/resourcemanager/azuresql/azuresqlfailovergroup/azuresqlfailovergroup.go +++ b/pkg/resourcemanager/azuresql/azuresqlfailovergroup/azuresqlfailovergroup.go @@ -19,20 +19,22 @@ import ( ) type AzureSqlFailoverGroupManager struct { + Creds config.Credentials SecretClient secrets.SecretClient Scheme *runtime.Scheme } -func NewAzureSqlFailoverGroupManager(secretClient secrets.SecretClient, scheme *runtime.Scheme) *AzureSqlFailoverGroupManager { +func NewAzureSqlFailoverGroupManager(creds config.Credentials, secretClient secrets.SecretClient, scheme *runtime.Scheme) *AzureSqlFailoverGroupManager { return &AzureSqlFailoverGroupManager{ + Creds: creds, SecretClient: secretClient, Scheme: scheme, } } // GetServer returns a SQL server -func (f *AzureSqlFailoverGroupManager) GetServer(ctx context.Context, resourceGroupName string, serverName string) (result sql.Server, err error) { - serversClient, err := azuresqlshared.GetGoServersClient() +func (m *AzureSqlFailoverGroupManager) GetServer(ctx context.Context, resourceGroupName string, serverName string) (result sql.Server, err error) { + serversClient, err := azuresqlshared.GetGoServersClient(m.Creds) if err != nil { return sql.Server{}, err } @@ -45,8 +47,8 @@ func (f *AzureSqlFailoverGroupManager) GetServer(ctx context.Context, resourceGr } // GetDB retrieves a database -func (f *AzureSqlFailoverGroupManager) GetDB(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (sql.Database, error) { - dbClient, err := azuresqlshared.GetGoDbClient() +func (m *AzureSqlFailoverGroupManager) GetDB(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (sql.Database, error) { + dbClient, err := azuresqlshared.GetGoDbClient(m.Creds) if err != nil { return sql.Database{}, err } @@ -60,8 +62,8 @@ func (f *AzureSqlFailoverGroupManager) GetDB(ctx context.Context, resourceGroupN } // GetFailoverGroup retrieves a failover group -func (f *AzureSqlFailoverGroupManager) GetFailoverGroup(ctx context.Context, resourceGroupName string, serverName string, failovergroupname string) (sql.FailoverGroup, error) { - failoverGroupsClient, err := azuresqlshared.GetGoFailoverGroupsClient() +func (m *AzureSqlFailoverGroupManager) GetFailoverGroup(ctx context.Context, resourceGroupName string, serverName string, failovergroupname string) (sql.FailoverGroup, error) { + failoverGroupsClient, err := azuresqlshared.GetGoFailoverGroupsClient(m.Creds) if err != nil { return sql.FailoverGroup{}, err } @@ -75,7 +77,7 @@ func (f *AzureSqlFailoverGroupManager) GetFailoverGroup(ctx context.Context, res } // DeleteFailoverGroup deletes a failover group -func (sdk *AzureSqlFailoverGroupManager) DeleteFailoverGroup(ctx context.Context, resourceGroupName string, serverName string, failoverGroupName string) (result autorest.Response, err error) { +func (m *AzureSqlFailoverGroupManager) DeleteFailoverGroup(ctx context.Context, resourceGroupName string, serverName string, failoverGroupName string) (result autorest.Response, err error) { result = autorest.Response{ Response: &http.Response{ StatusCode: 200, @@ -83,17 +85,17 @@ func (sdk *AzureSqlFailoverGroupManager) DeleteFailoverGroup(ctx context.Context } // check to see if the server exists, if it doesn't then short-circuit - _, err = sdk.GetServer(ctx, resourceGroupName, serverName) + _, err = m.GetServer(ctx, resourceGroupName, serverName) if err != nil { return result, nil } // check to see if the failover group exists, if it doesn't then short-circuit - _, err = sdk.GetFailoverGroup(ctx, resourceGroupName, serverName, failoverGroupName) + _, err = m.GetFailoverGroup(ctx, resourceGroupName, serverName, failoverGroupName) if err != nil { return result, nil } - failoverGroupsClient, err := azuresqlshared.GetGoFailoverGroupsClient() + failoverGroupsClient, err := azuresqlshared.GetGoFailoverGroupsClient(m.Creds) if err != nil { return result, err } @@ -112,8 +114,8 @@ func (sdk *AzureSqlFailoverGroupManager) DeleteFailoverGroup(ctx context.Context } // CreateOrUpdateFailoverGroup creates a failover group -func (sdk *AzureSqlFailoverGroupManager) CreateOrUpdateFailoverGroup(ctx context.Context, resourceGroupName string, serverName string, failovergroupname string, properties azuresqlshared.SQLFailoverGroupProperties) (result sql.FailoverGroupsCreateOrUpdateFuture, err error) { - failoverGroupsClient, err := azuresqlshared.GetGoFailoverGroupsClient() +func (m *AzureSqlFailoverGroupManager) CreateOrUpdateFailoverGroup(ctx context.Context, resourceGroupName string, serverName string, failovergroupname string, properties azuresqlshared.SQLFailoverGroupProperties) (result sql.FailoverGroupsCreateOrUpdateFuture, err error) { + failoverGroupsClient, err := azuresqlshared.GetGoFailoverGroupsClient(m.Creds) if err != nil { return sql.FailoverGroupsCreateOrUpdateFuture{}, err } @@ -121,7 +123,7 @@ func (sdk *AzureSqlFailoverGroupManager) CreateOrUpdateFailoverGroup(ctx context // Construct a PartnerInfo object from the server name // Get resource ID from the servername to use - server, err := sdk.GetServer(ctx, properties.SecondaryServerResourceGroup, properties.SecondaryServer) + server, err := m.GetServer(ctx, properties.SecondaryServerResourceGroup, properties.SecondaryServer) if err != nil { return result, nil } @@ -138,7 +140,7 @@ func (sdk *AzureSqlFailoverGroupManager) CreateOrUpdateFailoverGroup(ctx context // Parse the Databases in the Databaselist and form array of Resource IDs for _, each := range properties.DatabaseList { - database, err := sdk.GetDB(ctx, resourceGroupName, serverName, each) + database, err := m.GetDB(ctx, resourceGroupName, serverName, each) if err != nil { return result, err } @@ -167,7 +169,7 @@ func (sdk *AzureSqlFailoverGroupManager) CreateOrUpdateFailoverGroup(ctx context failoverGroup) } -func (f *AzureSqlFailoverGroupManager) GetOrPrepareSecret(ctx context.Context, instance *v1beta1.AzureSqlFailoverGroup) (map[string][]byte, error) { +func (m *AzureSqlFailoverGroupManager) GetOrPrepareSecret(ctx context.Context, instance *v1beta1.AzureSqlFailoverGroup) (map[string][]byte, error) { failovergroupname := instance.ObjectMeta.Name azuresqlprimaryserver := instance.Spec.Server azuresqlsecondaryserver := instance.Spec.SecondaryServer @@ -176,7 +178,7 @@ func (f *AzureSqlFailoverGroupManager) GetOrPrepareSecret(ctx context.Context, i key := types.NamespacedName{Name: failovergroupname, Namespace: instance.Namespace} - if stored, err := f.SecretClient.Get(ctx, key); err == nil { + if stored, err := m.SecretClient.Get(ctx, key); err == nil { return stored, nil } diff --git a/pkg/resourcemanager/azuresql/azuresqlfirewallrule/azuresqlfirewallrule.go b/pkg/resourcemanager/azuresql/azuresqlfirewallrule/azuresqlfirewallrule.go index ad58ed2153c..fa899130e05 100644 --- a/pkg/resourcemanager/azuresql/azuresqlfirewallrule/azuresqlfirewallrule.go +++ b/pkg/resourcemanager/azuresql/azuresqlfirewallrule/azuresqlfirewallrule.go @@ -8,20 +8,22 @@ import ( sql "github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/v3.0/sql" azuresqlshared "github.com/Azure/azure-service-operator/pkg/resourcemanager/azuresql/azuresqlshared" + "github.com/Azure/azure-service-operator/pkg/resourcemanager/config" "github.com/Azure/go-autorest/autorest/to" ) type AzureSqlFirewallRuleManager struct { + creds config.Credentials } -func NewAzureSqlFirewallRuleManager() *AzureSqlFirewallRuleManager { - return &AzureSqlFirewallRuleManager{} +func NewAzureSqlFirewallRuleManager(creds config.Credentials) *AzureSqlFirewallRuleManager { + return &AzureSqlFirewallRuleManager{creds: creds} } // GetServer returns a SQL server -func (_ *AzureSqlFirewallRuleManager) GetServer(ctx context.Context, resourceGroupName string, serverName string) (result sql.Server, err error) { - serversClient, err := azuresqlshared.GetGoServersClient() +func (m *AzureSqlFirewallRuleManager) GetServer(ctx context.Context, resourceGroupName string, serverName string) (result sql.Server, err error) { + serversClient, err := azuresqlshared.GetGoServersClient(m.creds) if err != nil { return sql.Server{}, err } @@ -34,8 +36,8 @@ func (_ *AzureSqlFirewallRuleManager) GetServer(ctx context.Context, resourceGro } // GetSQLFirewallRule returns a firewall rule -func (_ *AzureSqlFirewallRuleManager) GetSQLFirewallRule(ctx context.Context, resourceGroupName string, serverName string, ruleName string) (result sql.FirewallRule, err error) { - firewallClient, err := azuresqlshared.GetGoFirewallClient() +func (m *AzureSqlFirewallRuleManager) GetSQLFirewallRule(ctx context.Context, resourceGroupName string, serverName string, ruleName string) (result sql.FirewallRule, err error) { + firewallClient, err := azuresqlshared.GetGoFirewallClient(m.creds) if err != nil { return sql.FirewallRule{}, err } @@ -49,21 +51,21 @@ func (_ *AzureSqlFirewallRuleManager) GetSQLFirewallRule(ctx context.Context, re } // DeleteSQLFirewallRule deletes a firewall rule -func (sdk *AzureSqlFirewallRuleManager) DeleteSQLFirewallRule(ctx context.Context, resourceGroupName string, serverName string, ruleName string) (err error) { +func (m *AzureSqlFirewallRuleManager) DeleteSQLFirewallRule(ctx context.Context, resourceGroupName string, serverName string, ruleName string) (err error) { // check to see if the server exists, if it doesn't then short-circuit - server, err := sdk.GetServer(ctx, resourceGroupName, serverName) + server, err := m.GetServer(ctx, resourceGroupName, serverName) if err != nil || *server.State != "Ready" { return nil } // check to see if the rule exists, if it doesn't then short-circuit - _, err = sdk.GetSQLFirewallRule(ctx, resourceGroupName, serverName, ruleName) + _, err = m.GetSQLFirewallRule(ctx, resourceGroupName, serverName, ruleName) if err != nil { return nil } - firewallClient, err := azuresqlshared.GetGoFirewallClient() + firewallClient, err := azuresqlshared.GetGoFirewallClient(m.creds) if err != nil { return err } @@ -79,17 +81,17 @@ func (sdk *AzureSqlFirewallRuleManager) DeleteSQLFirewallRule(ctx context.Contex } // CreateOrUpdateSQLFirewallRule creates or updates a firewall rule -// based on code from: https://github.com/Azure-Samples/azure-sdk-for-go-samples/blob/master/sql/sql.go#L111 +// based on code from: https://github.com/Azure-Samples/azure-m-for-go-samples/blob/master/sql/sql.go#L111 // to allow allow Azure services to connect example: https://docs.microsoft.com/en-us/azure/sql-database/sql-database-firewall-configure#manage-firewall-rules-using-azure-cli -func (sdk *AzureSqlFirewallRuleManager) CreateOrUpdateSQLFirewallRule(ctx context.Context, resourceGroupName string, serverName string, ruleName string, startIP string, endIP string) (result bool, err error) { +func (m *AzureSqlFirewallRuleManager) CreateOrUpdateSQLFirewallRule(ctx context.Context, resourceGroupName string, serverName string, ruleName string, startIP string, endIP string) (result bool, err error) { // check to see if the server exists, if it doesn't then short-circuit - server, err := sdk.GetServer(ctx, resourceGroupName, serverName) + server, err := m.GetServer(ctx, resourceGroupName, serverName) if err != nil || *server.State != "Ready" { return false, err } - firewallClient, err := azuresqlshared.GetGoFirewallClient() + firewallClient, err := azuresqlshared.GetGoFirewallClient(m.creds) if err != nil { return false, err } diff --git a/pkg/resourcemanager/azuresql/azuresqlmanageduser/azuresqlmanageduser.go b/pkg/resourcemanager/azuresql/azuresqlmanageduser/azuresqlmanageduser.go index 8d9abaae115..4123cdbc05a 100644 --- a/pkg/resourcemanager/azuresql/azuresqlmanageduser/azuresqlmanageduser.go +++ b/pkg/resourcemanager/azuresql/azuresqlmanageduser/azuresqlmanageduser.go @@ -25,12 +25,14 @@ import ( ) type AzureSqlManagedUserManager struct { + Creds config.Credentials SecretClient secrets.SecretClient Scheme *runtime.Scheme } -func NewAzureSqlManagedUserManager(secretClient secrets.SecretClient, scheme *runtime.Scheme) *AzureSqlManagedUserManager { +func NewAzureSqlManagedUserManager(creds config.Credentials, secretClient secrets.SecretClient, scheme *runtime.Scheme) *AzureSqlManagedUserManager { return &AzureSqlManagedUserManager{ + Creds: creds, SecretClient: secretClient, Scheme: scheme, } @@ -38,7 +40,7 @@ func NewAzureSqlManagedUserManager(secretClient secrets.SecretClient, scheme *ru // GetDB retrieves a database func (s *AzureSqlManagedUserManager) GetDB(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (azuresql.Database, error) { - dbClient, err := azuresqlshared.GetGoDbClient() + dbClient, err := azuresqlshared.GetGoDbClient(s.Creds) if err != nil { return azuresql.Database{}, err } diff --git a/pkg/resourcemanager/azuresql/azuresqlserver/azuresqlserver.go b/pkg/resourcemanager/azuresql/azuresqlserver/azuresqlserver.go index b4756b565ee..8aa90dc603b 100644 --- a/pkg/resourcemanager/azuresql/azuresqlserver/azuresqlserver.go +++ b/pkg/resourcemanager/azuresql/azuresqlserver/azuresqlserver.go @@ -10,6 +10,7 @@ import ( "github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/v3.0/sql" azuresqlshared "github.com/Azure/azure-service-operator/pkg/resourcemanager/azuresql/azuresqlshared" + "github.com/Azure/azure-service-operator/pkg/resourcemanager/config" "github.com/Azure/azure-service-operator/pkg/secrets" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/to" @@ -19,19 +20,21 @@ import ( const typeOfService = "Microsoft.Sql/servers" type AzureSqlServerManager struct { + Creds config.Credentials SecretClient secrets.SecretClient Scheme *runtime.Scheme } -func NewAzureSqlServerManager(secretClient secrets.SecretClient, scheme *runtime.Scheme) *AzureSqlServerManager { +func NewAzureSqlServerManager(creds config.Credentials, secretClient secrets.SecretClient, scheme *runtime.Scheme) *AzureSqlServerManager { return &AzureSqlServerManager{ + Creds: creds, SecretClient: secretClient, Scheme: scheme, } } // DeleteSQLServer deletes a SQL server -func (sdk *AzureSqlServerManager) DeleteSQLServer(ctx context.Context, resourceGroupName string, serverName string) (result autorest.Response, err error) { +func (m *AzureSqlServerManager) DeleteSQLServer(ctx context.Context, resourceGroupName string, serverName string) (result autorest.Response, err error) { result = autorest.Response{ Response: &http.Response{ StatusCode: 200, @@ -39,12 +42,12 @@ func (sdk *AzureSqlServerManager) DeleteSQLServer(ctx context.Context, resourceG } // check to see if the server exists, if it doesn't then short-circuit - _, err = sdk.GetServer(ctx, resourceGroupName, serverName) + _, err = m.GetServer(ctx, resourceGroupName, serverName) if err != nil { return result, nil } - serversClient, err := azuresqlshared.GetGoServersClient() + serversClient, err := azuresqlshared.GetGoServersClient(m.Creds) if err != nil { return result, err } @@ -62,8 +65,8 @@ func (sdk *AzureSqlServerManager) DeleteSQLServer(ctx context.Context, resourceG } // GetServer returns a SQL server -func (_ *AzureSqlServerManager) GetServer(ctx context.Context, resourceGroupName string, serverName string) (result sql.Server, err error) { - serversClient, err := azuresqlshared.GetGoServersClient() +func (m *AzureSqlServerManager) GetServer(ctx context.Context, resourceGroupName string, serverName string) (result sql.Server, err error) { + serversClient, err := azuresqlshared.GetGoServersClient(m.Creds) if err != nil { return sql.Server{}, err } @@ -76,8 +79,8 @@ func (_ *AzureSqlServerManager) GetServer(ctx context.Context, resourceGroupName } // CreateOrUpdateSQLServer creates a SQL server in Azure -func (_ *AzureSqlServerManager) CreateOrUpdateSQLServer(ctx context.Context, resourceGroupName string, location string, serverName string, tags map[string]*string, properties azuresqlshared.SQLServerProperties, forceUpdate bool) (pollingURL string, result sql.Server, err error) { - serversClient, err := azuresqlshared.GetGoServersClient() +func (m *AzureSqlServerManager) CreateOrUpdateSQLServer(ctx context.Context, resourceGroupName string, location string, serverName string, tags map[string]*string, properties azuresqlshared.SQLServerProperties, forceUpdate bool) (pollingURL string, result sql.Server, err error) { + serversClient, err := azuresqlshared.GetGoServersClient(m.Creds) if err != nil { return "", sql.Server{}, err } @@ -85,7 +88,7 @@ func (_ *AzureSqlServerManager) CreateOrUpdateSQLServer(ctx context.Context, res serverProp := azuresqlshared.SQLServerPropertiesToServer(properties) if forceUpdate == false { - checkNameResult, _ := CheckNameAvailability(ctx, serverName) + checkNameResult, _ := CheckNameAvailability(ctx, m.Creds, serverName) if checkNameResult.Reason == sql.AlreadyExists { err = errors.New("AlreadyExists") return @@ -115,8 +118,8 @@ func (_ *AzureSqlServerManager) CreateOrUpdateSQLServer(ctx context.Context, res return future.PollingURL(), result, err } -func CheckNameAvailability(ctx context.Context, serverName string) (result sql.CheckNameAvailabilityResponse, err error) { - serversClient, err := azuresqlshared.GetGoServersClient() +func CheckNameAvailability(ctx context.Context, creds config.Credentials, serverName string) (result sql.CheckNameAvailabilityResponse, err error) { + serversClient, err := azuresqlshared.GetGoServersClient(creds) if err != nil { return sql.CheckNameAvailabilityResponse{}, err } diff --git a/pkg/resourcemanager/azuresql/azuresqlserver/azuresqlserver_reconcile.go b/pkg/resourcemanager/azuresql/azuresqlserver/azuresqlserver_reconcile.go index fdf706b4cef..2a01623e775 100644 --- a/pkg/resourcemanager/azuresql/azuresqlserver/azuresqlserver_reconcile.go +++ b/pkg/resourcemanager/azuresql/azuresqlserver/azuresqlserver_reconcile.go @@ -55,7 +55,7 @@ func (s *AzureSqlServerManager) Ensure(ctx context.Context, obj runtime.Object, } // Assure that the requested name is available and assume the secret exists - checkNameResult, err := CheckNameAvailability(ctx, instance.Name) + checkNameResult, err := CheckNameAvailability(ctx, s.Creds, instance.Name) if err != nil { instance.Status.Provisioning = false @@ -128,7 +128,7 @@ func (s *AzureSqlServerManager) Ensure(ctx context.Context, obj runtime.Object, // handle failures in the async operation if instance.Status.PollingURL != "" { - pClient := pollclient.NewPollClient() + pClient := pollclient.NewPollClient(s.Creds) res, err := pClient.Get(ctx, instance.Status.PollingURL) if err != nil { return false, err diff --git a/pkg/resourcemanager/azuresql/azuresqlshared/getgoclients.go b/pkg/resourcemanager/azuresql/azuresqlshared/getgoclients.go index e20c6826d81..a1e767d4f0f 100644 --- a/pkg/resourcemanager/azuresql/azuresqlshared/getgoclients.go +++ b/pkg/resourcemanager/azuresql/azuresqlshared/getgoclients.go @@ -12,9 +12,9 @@ import ( ) // GetGoDbClient retrieves a DatabasesClient -func GetGoDbClient() (sql.DatabasesClient, error) { - dbClient := sql.NewDatabasesClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, err := iam.GetResourceManagementAuthorizer() +func GetGoDbClient(creds config.Credentials) (sql.DatabasesClient, error) { + dbClient := sql.NewDatabasesClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, err := iam.GetResourceManagementAuthorizer(creds) if err != nil { return sql.DatabasesClient{}, err } @@ -24,9 +24,9 @@ func GetGoDbClient() (sql.DatabasesClient, error) { } // GetGoServersClient retrieves a ServersClient -func GetGoServersClient() (sql.ServersClient, error) { - serversClient := sql.NewServersClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, err := iam.GetResourceManagementAuthorizer() +func GetGoServersClient(creds config.Credentials) (sql.ServersClient, error) { + serversClient := sql.NewServersClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, err := iam.GetResourceManagementAuthorizer(creds) if err != nil { return sql.ServersClient{}, err } @@ -36,9 +36,9 @@ func GetGoServersClient() (sql.ServersClient, error) { } // GetGoFailoverGroupsClient retrieves a FailoverGroupsClient -func GetGoFailoverGroupsClient() (sql.FailoverGroupsClient, error) { - failoverGroupsClient := sql.NewFailoverGroupsClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, err := iam.GetResourceManagementAuthorizer() +func GetGoFailoverGroupsClient(creds config.Credentials) (sql.FailoverGroupsClient, error) { + failoverGroupsClient := sql.NewFailoverGroupsClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, err := iam.GetResourceManagementAuthorizer(creds) if err != nil { return sql.FailoverGroupsClient{}, err } @@ -48,9 +48,9 @@ func GetGoFailoverGroupsClient() (sql.FailoverGroupsClient, error) { } // GetGoFirewallClient retrieves a FirewallRulesClient -func GetGoFirewallClient() (sql.FirewallRulesClient, error) { - firewallClient := sql.NewFirewallRulesClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, err := iam.GetResourceManagementAuthorizer() +func GetGoFirewallClient(creds config.Credentials) (sql.FirewallRulesClient, error) { + firewallClient := sql.NewFirewallRulesClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, err := iam.GetResourceManagementAuthorizer(creds) if err != nil { return sql.FirewallRulesClient{}, err } @@ -60,9 +60,9 @@ func GetGoFirewallClient() (sql.FirewallRulesClient, error) { } // GetGoVNetRulesClient retrieves a VirtualNetworkRulesClient -func GetGoVNetRulesClient() (sql.VirtualNetworkRulesClient, error) { - VNetRulesClient := sql.NewVirtualNetworkRulesClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, err := iam.GetResourceManagementAuthorizer() +func GetGoVNetRulesClient(creds config.Credentials) (sql.VirtualNetworkRulesClient, error) { + VNetRulesClient := sql.NewVirtualNetworkRulesClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, err := iam.GetResourceManagementAuthorizer(creds) if err != nil { return sql.VirtualNetworkRulesClient{}, err } @@ -72,9 +72,9 @@ func GetGoVNetRulesClient() (sql.VirtualNetworkRulesClient, error) { } // GetNetworkSubnetClient retrieves a Subnetclient -func GetGoNetworkSubnetClient() (network.SubnetsClient, error) { - SubnetsClient := network.NewSubnetsClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, err := iam.GetResourceManagementAuthorizer() +func GetGoNetworkSubnetClient(creds config.Credentials) (network.SubnetsClient, error) { + SubnetsClient := network.NewSubnetsClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, err := iam.GetResourceManagementAuthorizer(creds) if err != nil { return network.SubnetsClient{}, err } @@ -84,9 +84,9 @@ func GetGoNetworkSubnetClient() (network.SubnetsClient, error) { } // GetBackupLongTermRetentionPoliciesClient retrieves a Subnetclient -func GetBackupLongTermRetentionPoliciesClient() (sql3.BackupLongTermRetentionPoliciesClient, error) { - BackupClient := sql3.NewBackupLongTermRetentionPoliciesClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, err := iam.GetResourceManagementAuthorizer() +func GetBackupLongTermRetentionPoliciesClient(creds config.Credentials) (sql3.BackupLongTermRetentionPoliciesClient, error) { + BackupClient := sql3.NewBackupLongTermRetentionPoliciesClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, err := iam.GetResourceManagementAuthorizer(creds) if err != nil { return sql3.BackupLongTermRetentionPoliciesClient{}, err } diff --git a/pkg/resourcemanager/azuresql/azuresqluser/azuresqluser.go b/pkg/resourcemanager/azuresql/azuresqluser/azuresqluser.go index a5a79829b39..122a135b4e7 100644 --- a/pkg/resourcemanager/azuresql/azuresqluser/azuresqluser.go +++ b/pkg/resourcemanager/azuresql/azuresqluser/azuresqluser.go @@ -36,20 +36,22 @@ const SecretUsernameKey = "username" const SecretPasswordKey = "password" type AzureSqlUserManager struct { + Creds config.Credentials SecretClient secrets.SecretClient Scheme *runtime.Scheme } -func NewAzureSqlUserManager(secretClient secrets.SecretClient, scheme *runtime.Scheme) *AzureSqlUserManager { +func NewAzureSqlUserManager(creds config.Credentials, secretClient secrets.SecretClient, scheme *runtime.Scheme) *AzureSqlUserManager { return &AzureSqlUserManager{ + Creds: creds, SecretClient: secretClient, Scheme: scheme, } } // GetDB retrieves a database -func (s *AzureSqlUserManager) GetDB(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (azuresql.Database, error) { - dbClient, err := azuresqlshared.GetGoDbClient() +func (m *AzureSqlUserManager) GetDB(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (azuresql.Database, error) { + dbClient, err := azuresqlshared.GetGoDbClient(m.Creds) if err != nil { return azuresql.Database{}, err } @@ -63,7 +65,7 @@ func (s *AzureSqlUserManager) GetDB(ctx context.Context, resourceGroupName strin } // ConnectToSqlDb connects to the SQL db using the given credentials -func (s *AzureSqlUserManager) ConnectToSqlDb(ctx context.Context, drivername string, server string, database string, port int, user string, password string) (*sql.DB, error) { +func (m *AzureSqlUserManager) ConnectToSqlDb(ctx context.Context, drivername string, server string, database string, port int, user string, password string) (*sql.DB, error) { fullServerAddress := fmt.Sprintf("%s."+config.Environment().SQLDatabaseDNSSuffix, server) connString := fmt.Sprintf("server=%s;user id=%s;password=%s;port=%d;database=%s;Persist Security Info=False;Pooling=False;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30", fullServerAddress, user, password, port, database) @@ -82,7 +84,7 @@ func (s *AzureSqlUserManager) ConnectToSqlDb(ctx context.Context, drivername str } // GrantUserRoles grants roles to a user for a given database -func (s *AzureSqlUserManager) GrantUserRoles(ctx context.Context, user string, roles []string, db *sql.DB) error { +func (m *AzureSqlUserManager) GrantUserRoles(ctx context.Context, user string, roles []string, db *sql.DB) error { var errorStrings []string for _, role := range roles { tsql := "sp_addrolemember @role, @user" @@ -104,7 +106,7 @@ func (s *AzureSqlUserManager) GrantUserRoles(ctx context.Context, user string, r } // CreateUser creates user with secret credentials -func (s *AzureSqlUserManager) CreateUser(ctx context.Context, secret map[string][]byte, db *sql.DB) (string, error) { +func (m *AzureSqlUserManager) CreateUser(ctx context.Context, secret map[string][]byte, db *sql.DB) (string, error) { newUser := string(secret[SecretUsernameKey]) newPassword := string(secret[SecretPasswordKey]) @@ -130,7 +132,7 @@ func (s *AzureSqlUserManager) CreateUser(ctx context.Context, secret map[string] } // UpdateUser - Updates user password -func (s *AzureSqlUserManager) UpdateUser(ctx context.Context, secret map[string][]byte, db *sql.DB) error { +func (m *AzureSqlUserManager) UpdateUser(ctx context.Context, secret map[string][]byte, db *sql.DB) error { user := string(secret[SecretUsernameKey]) newPassword := helpers.NewPassword() @@ -149,7 +151,7 @@ func (s *AzureSqlUserManager) UpdateUser(ctx context.Context, secret map[string] } // UserExists checks if db contains user -func (s *AzureSqlUserManager) UserExists(ctx context.Context, db *sql.DB, username string) (bool, error) { +func (m *AzureSqlUserManager) UserExists(ctx context.Context, db *sql.DB, username string) (bool, error) { res, err := db.ExecContext( ctx, "SELECT * FROM sysusers WHERE NAME=@user", @@ -163,14 +165,14 @@ func (s *AzureSqlUserManager) UserExists(ctx context.Context, db *sql.DB, userna } // DropUser drops a user from db -func (s *AzureSqlUserManager) DropUser(ctx context.Context, db *sql.DB, user string) error { +func (m *AzureSqlUserManager) DropUser(ctx context.Context, db *sql.DB, user string) error { tsql := fmt.Sprintf("DROP USER %q", user) _, err := db.ExecContext(ctx, tsql) return err } // DeleteSecrets deletes the secrets associated with a SQLUser -func (s *AzureSqlUserManager) DeleteSecrets(ctx context.Context, instance *v1alpha1.AzureSQLUser, secretClient secrets.SecretClient) (bool, error) { +func (m *AzureSqlUserManager) DeleteSecrets(ctx context.Context, instance *v1alpha1.AzureSQLUser, secretClient secrets.SecretClient) (bool, error) { // determine our key namespace - if we're persisting to kube, we should use the actual instance namespace. // In keyvault we have some creative freedom to allow more flexibility secretKey := GetNamespacedName(instance, secretClient) @@ -219,7 +221,7 @@ func (s *AzureSqlUserManager) DeleteSecrets(ctx context.Context, instance *v1alp } // GetOrPrepareSecret gets or creates a secret -func (s *AzureSqlUserManager) GetOrPrepareSecret(ctx context.Context, instance *v1alpha1.AzureSQLUser, secretClient secrets.SecretClient) map[string][]byte { +func (m *AzureSqlUserManager) GetOrPrepareSecret(ctx context.Context, instance *v1alpha1.AzureSQLUser, secretClient secrets.SecretClient) map[string][]byte { key := GetNamespacedName(instance, secretClient) secret, err := secretClient.Get(ctx, key) diff --git a/pkg/resourcemanager/azuresql/azuresqluser/azuresqluser_reconcile.go b/pkg/resourcemanager/azuresql/azuresqluser/azuresqluser_reconcile.go index 4786ad8b21b..fa43f09f8e0 100644 --- a/pkg/resourcemanager/azuresql/azuresqluser/azuresqluser_reconcile.go +++ b/pkg/resourcemanager/azuresql/azuresqluser/azuresqluser_reconcile.go @@ -59,7 +59,7 @@ func (s *AzureSqlUserManager) Ensure(ctx context.Context, obj runtime.Object, op // if the admin secret keyvault is not specified, fall back to global secretclient if len(instance.Spec.AdminSecretKeyVault) != 0 { - adminSecretClient = keyvaultSecrets.New(instance.Spec.AdminSecretKeyVault) + adminSecretClient = keyvaultSecrets.New(instance.Spec.AdminSecretKeyVault, s.Creds) if len(instance.Spec.AdminSecret) != 0 { key = types.NamespacedName{Name: instance.Spec.AdminSecret} } @@ -312,7 +312,7 @@ func (s *AzureSqlUserManager) Delete(ctx context.Context, obj runtime.Object, op // if the admin secret keyvault is not specified, fall back to global secretclient if len(instance.Spec.AdminSecretKeyVault) != 0 { - adminSecretClient = keyvaultSecrets.New(instance.Spec.AdminSecretKeyVault) + adminSecretClient = keyvaultSecrets.New(instance.Spec.AdminSecretKeyVault, s.Creds) if len(instance.Spec.AdminSecret) != 0 { key = types.NamespacedName{Name: instance.Spec.AdminSecret} } diff --git a/pkg/resourcemanager/azuresql/azuresqlvnetrule/azuresqlvnetrule.go b/pkg/resourcemanager/azuresql/azuresqlvnetrule/azuresqlvnetrule.go index 590a33b5831..182a0cfa9d6 100644 --- a/pkg/resourcemanager/azuresql/azuresqlvnetrule/azuresqlvnetrule.go +++ b/pkg/resourcemanager/azuresql/azuresqlvnetrule/azuresqlvnetrule.go @@ -8,18 +8,20 @@ import ( sql "github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/v3.0/sql" azuresqlshared "github.com/Azure/azure-service-operator/pkg/resourcemanager/azuresql/azuresqlshared" + "github.com/Azure/azure-service-operator/pkg/resourcemanager/config" ) type AzureSqlVNetRuleManager struct { + creds config.Credentials } -func NewAzureSqlVNetRuleManager() *AzureSqlVNetRuleManager { - return &AzureSqlVNetRuleManager{} +func NewAzureSqlVNetRuleManager(creds config.Credentials) *AzureSqlVNetRuleManager { + return &AzureSqlVNetRuleManager{creds: creds} } // GetSQLVNetRule returns a VNet rule -func (vr *AzureSqlVNetRuleManager) GetSQLVNetRule(ctx context.Context, resourceGroupName string, serverName string, ruleName string) (result sql.VirtualNetworkRule, err error) { - VNetRulesClient, err := azuresqlshared.GetGoVNetRulesClient() +func (m *AzureSqlVNetRuleManager) GetSQLVNetRule(ctx context.Context, resourceGroupName string, serverName string, ruleName string) (result sql.VirtualNetworkRule, err error) { + VNetRulesClient, err := azuresqlshared.GetGoVNetRulesClient(m.creds) if err != nil { return sql.VirtualNetworkRule{}, err } @@ -33,15 +35,15 @@ func (vr *AzureSqlVNetRuleManager) GetSQLVNetRule(ctx context.Context, resourceG } // DeleteSQLVNetRule deletes a VNet rule -func (vr *AzureSqlVNetRuleManager) DeleteSQLVNetRule(ctx context.Context, resourceGroupName string, serverName string, ruleName string) (err error) { +func (m *AzureSqlVNetRuleManager) DeleteSQLVNetRule(ctx context.Context, resourceGroupName string, serverName string, ruleName string) (err error) { // check to see if the rule exists, if it doesn't then short-circuit - _, err = vr.GetSQLVNetRule(ctx, resourceGroupName, serverName, ruleName) + _, err = m.GetSQLVNetRule(ctx, resourceGroupName, serverName, ruleName) if err != nil { return nil } - VNetRulesClient, err := azuresqlshared.GetGoVNetRulesClient() + VNetRulesClient, err := azuresqlshared.GetGoVNetRulesClient(m.creds) if err != nil { return err } @@ -58,14 +60,14 @@ func (vr *AzureSqlVNetRuleManager) DeleteSQLVNetRule(ctx context.Context, resour // CreateOrUpdateSQLVNetRule creates or updates a VNet rule // based on code from: https://godoc.org/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/v3.0/sql#VirtualNetworkRulesClient.CreateOrUpdate -func (vr *AzureSqlVNetRuleManager) CreateOrUpdateSQLVNetRule(ctx context.Context, resourceGroupName string, serverName string, ruleName string, VNetRG string, VNetName string, SubnetName string, IgnoreServiceEndpoint bool) (vnr sql.VirtualNetworkRule, err error) { +func (m *AzureSqlVNetRuleManager) CreateOrUpdateSQLVNetRule(ctx context.Context, resourceGroupName string, serverName string, ruleName string, VNetRG string, VNetName string, SubnetName string, IgnoreServiceEndpoint bool) (vnr sql.VirtualNetworkRule, err error) { - VNetRulesClient, err := azuresqlshared.GetGoVNetRulesClient() + VNetRulesClient, err := azuresqlshared.GetGoVNetRulesClient(m.creds) if err != nil { return sql.VirtualNetworkRule{}, err } - SubnetClient, err := azuresqlshared.GetGoNetworkSubnetClient() + SubnetClient, err := azuresqlshared.GetGoNetworkSubnetClient(m.creds) if err != nil { return sql.VirtualNetworkRule{}, err } diff --git a/pkg/resourcemanager/config/config.go b/pkg/resourcemanager/config/config.go index 95baa943d41..5d7a11e3957 100644 --- a/pkg/resourcemanager/config/config.go +++ b/pkg/resourcemanager/config/config.go @@ -16,18 +16,15 @@ var ( // each has corresponding public accessors below. // if anything requires a `Set` accessor, that indicates it perhaps // shouldn't be set here, because mutable vars shouldn't be global. - clientID string - clientSecret string - tenantID string - subscriptionID string + + // TODO: eliminate this! + creds credentials locationDefault string authorizationServerURL string cloudName string useDeviceFlow bool - useMI bool buildID string keepResources bool - operatorKeyvault string userAgent string baseURI string environment *azure.Environment @@ -35,24 +32,10 @@ var ( testResourcePrefix string // used to generate resource names in tests, should probably exist in a test only package ) -// ClientID is the OAuth client ID. -func ClientID() string { - return clientID -} - -// ClientSecret is the OAuth client secret. -func ClientSecret() string { - return clientSecret -} - -// TenantID is the AAD tenant to which this client belongs. -func TenantID() string { - return tenantID -} - -// SubscriptionID is a target subscription for Azure resources. -func SubscriptionID() string { - return subscriptionID +// GlobalCredentials returns the configured credentials. +// TODO: get rid of all uses of this. +func GlobalCredentials() Credentials { + return creds } // deprecated: use DefaultLocation() instead @@ -74,23 +57,12 @@ func AuthorizationServerURL() string { return authorizationServerURL } -// OperatorKeyvault() specifies the keyvault the operator should use to store secrets -func OperatorKeyvault() string { - return operatorKeyvault -} - // UseDeviceFlow() specifies if interactive auth should be used. Interactive // auth uses the OAuth Device Flow grant type. func UseDeviceFlow() bool { return useDeviceFlow } -// UseMI() specifies if managed service identity auth should be used. Used for -// aad-pod-identity -func UseMI() bool { - return useMI -} - // KeepResources() specifies whether to keep resources created by samples. func KeepResources() bool { return keepResources @@ -137,12 +109,13 @@ func BaseURI() string { // ConfigString returns the parts of the configuration file with are not secrets as a string for easy logging func ConfigString() string { + creds := GlobalCredentials() return fmt.Sprintf( "clientID: %q, tenantID: %q, subscriptionID: %q, cloudName: %q, useDeviceFlow: %v, useManagedIdentity: %v", - ClientID(), - TenantID(), - SubscriptionID(), + creds.ClientID(), + creds.TenantID(), + creds.SubscriptionID(), cloudName, UseDeviceFlow(), - UseMI()) + creds.UseManagedIdentity()) } diff --git a/pkg/resourcemanager/config/credentials.go b/pkg/resourcemanager/config/credentials.go new file mode 100644 index 00000000000..0342557ea89 --- /dev/null +++ b/pkg/resourcemanager/config/credentials.go @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +// Package config manages loading configuration from environment and command-line params +package config + +// Credentials is a read-only holder for information needed to +// authenticate to ARM. +type Credentials interface { + ClientID() string + ClientSecret() string + TenantID() string + SubscriptionID() string + UseManagedIdentity() bool + OperatorKeyvault() string +} + +type credentials struct { + clientID string + clientSecret string + tenantID string + subscriptionID string + useManagedIdentity bool + operatorKeyvault string +} + +var _ Credentials = credentials{} + +// ClientID is the OAuth client ID. +func (c credentials) ClientID() string { + return c.clientID +} + +// ClientSecret is the OAuth client secret. +func (c credentials) ClientSecret() string { + return c.clientSecret +} + +// TenantID is the AAD tenant to which this client belongs. +func (c credentials) TenantID() string { + return c.tenantID +} + +// SubscriptionID is a target subscription for Azure resources. +func (c credentials) SubscriptionID() string { + return c.subscriptionID +} + +// UseMI() specifies if managed service identity auth should be used. Used for +// aad-pod-identity +func (c credentials) UseManagedIdentity() bool { + return c.useManagedIdentity +} + +// OperatorKeyvault() specifies the keyvault the operator should use to store secrets +func (c credentials) OperatorKeyvault() string { + return c.operatorKeyvault +} diff --git a/pkg/resourcemanager/config/env.go b/pkg/resourcemanager/config/env.go index 553dd7393aa..01af333bf3e 100644 --- a/pkg/resourcemanager/config/env.go +++ b/pkg/resourcemanager/config/env.go @@ -52,9 +52,9 @@ func ParseEnvironment() error { locationDefault = envy.Get("AZURE_LOCATION_DEFAULT", "westus2") // DefaultLocation() useDeviceFlow = ParseBoolFromEnvironment("AZURE_USE_DEVICEFLOW") // UseDeviceFlow() - useMI = ParseBoolFromEnvironment("AZURE_USE_MI") // UseMI() + creds.useManagedIdentity = ParseBoolFromEnvironment("AZURE_USE_MI") // UseManagedIdentity() keepResources = ParseBoolFromEnvironment("AZURE_SAMPLES_KEEP_RESOURCES") // KeepResources() - operatorKeyvault = envy.Get("AZURE_OPERATOR_KEYVAULT", "") // operatorKeyvault() + creds.operatorKeyvault = envy.Get("AZURE_OPERATOR_KEYVAULT", "") // operatorKeyvault() testResourcePrefix = envy.Get("TEST_RESOURCE_PREFIX", "t-"+helpers.RandomString(6)) var err error @@ -62,22 +62,22 @@ func ParseEnvironment() error { for _, requirement := range GetRequiredConfigs() { switch requirement { case RequireClientID: - clientID, err = envy.MustGet("AZURE_CLIENT_ID") // ClientID() + creds.clientID, err = envy.MustGet("AZURE_CLIENT_ID") // ClientID() if err != nil { return fmt.Errorf("expected env vars not provided (AZURE_CLIENT_ID): %s\n", err) } case RequireClientSecret: - clientSecret, err = envy.MustGet("AZURE_CLIENT_SECRET") // ClientSecret() + creds.clientSecret, err = envy.MustGet("AZURE_CLIENT_SECRET") // ClientSecret() if err != nil { return fmt.Errorf("expected env vars not provided (AZURE_CLIENT_SECRET): %s\n", err) } case RequireTenantID: - tenantID, err = envy.MustGet("AZURE_TENANT_ID") // TenantID() + creds.tenantID, err = envy.MustGet("AZURE_TENANT_ID") // TenantID() if err != nil { return fmt.Errorf("expected env vars not provided (AZURE_TENANT_ID): %s\n", err) } case RequireSubscriptionID: - subscriptionID, err = envy.MustGet("AZURE_SUBSCRIPTION_ID") // SubscriptionID() + creds.subscriptionID, err = envy.MustGet("AZURE_SUBSCRIPTION_ID") // SubscriptionID() if err != nil { return fmt.Errorf("expected env vars not provided (AZURE_SUBSCRIPTION_ID): %s\n", err) } @@ -92,7 +92,7 @@ func GetRequiredConfigs() []ConfigRequirementType { // Device flow required Configs return []ConfigRequirementType{RequireClientID, RequireTenantID, RequireSubscriptionID} } - if useMI { + if creds.useManagedIdentity { // Managed Service Identity required Configs return []ConfigRequirementType{RequireTenantID, RequireSubscriptionID} } diff --git a/pkg/resourcemanager/config/flags.go b/pkg/resourcemanager/config/flags.go index d056c55dec1..2d5858d1cb5 100644 --- a/pkg/resourcemanager/config/flags.go +++ b/pkg/resourcemanager/config/flags.go @@ -10,12 +10,12 @@ import ( // AddFlags adds flags applicable to all services. // Remember to call `flag.Parse()` in your main or TestMain. func AddFlags() error { - flag.StringVar(&subscriptionID, "subscription", subscriptionID, "Subscription for tests.") + flag.StringVar(&creds.subscriptionID, "subscription", creds.subscriptionID, "Subscription for tests.") flag.StringVar(&locationDefault, "location", locationDefault, "Default location for tests.") flag.StringVar(&cloudName, "cloud", cloudName, "Name of Azure cloud.") - flag.StringVar(&operatorKeyvault, "operatorKeyvault", operatorKeyvault, "Keyvault operator uses to store secrets.") - flag.BoolVar(&useDeviceFlow, "useDeviceFlow", useDeviceFlow, "Use device-flow grant type rather than client credentials.") - flag.BoolVar(&useMI, "useMI", useMI, "Use MI authentication (aad-pod-identity).") + flag.StringVar(&creds.operatorKeyvault, "operatorKeyvault", creds.operatorKeyvault, "Keyvault operator uses to store secrets.") + flag.BoolVar(&useDeviceFlow, "useDeviceFlow", useDeviceFlow, "Use device-flow grant type rather than client creds.") + flag.BoolVar(&creds.useManagedIdentity, "useMI", creds.useManagedIdentity, "Use managed identity authentication (aad-pod-identity).") flag.BoolVar(&keepResources, "keepResources", keepResources, "Keep resources created by samples.") return nil diff --git a/pkg/resourcemanager/cosmosdbs/cosmosdb.go b/pkg/resourcemanager/cosmosdbs/cosmosdb.go index 7a8ffb5cace..3048c191523 100644 --- a/pkg/resourcemanager/cosmosdbs/cosmosdb.go +++ b/pkg/resourcemanager/cosmosdbs/cosmosdb.go @@ -20,13 +20,14 @@ import ( // AzureCosmosDBManager is the struct which contains helper functions for resource groups type AzureCosmosDBManager struct { + Creds config.Credentials SecretClient secrets.SecretClient } -func getCosmosDBClient() (documentdb.DatabaseAccountsClient, error) { - cosmosDBClient := documentdb.NewDatabaseAccountsClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) +func getCosmosDBClient(creds config.Credentials) (documentdb.DatabaseAccountsClient, error) { + cosmosDBClient := documentdb.NewDatabaseAccountsClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) - a, err := iam.GetResourceManagementAuthorizer() + a, err := iam.GetResourceManagementAuthorizer(creds) if err != nil { cosmosDBClient = documentdb.DatabaseAccountsClient{} } else { @@ -38,12 +39,12 @@ func getCosmosDBClient() (documentdb.DatabaseAccountsClient, error) { } // CreateOrUpdateCosmosDB creates a new CosmosDB -func (*AzureCosmosDBManager) CreateOrUpdateCosmosDB( +func (m *AzureCosmosDBManager) CreateOrUpdateCosmosDB( ctx context.Context, accountName string, spec v1alpha1.CosmosDBSpec, tags map[string]*string) (*documentdb.DatabaseAccount, string, error) { - cosmosDBClient, err := getCosmosDBClient() + cosmosDBClient, err := getCosmosDBClient(m.Creds) if err != nil { return nil, "", err } @@ -79,11 +80,11 @@ func (*AzureCosmosDBManager) CreateOrUpdateCosmosDB( } // GetCosmosDB gets the cosmos db account -func (*AzureCosmosDBManager) GetCosmosDB( +func (m *AzureCosmosDBManager) GetCosmosDB( ctx context.Context, groupName string, cosmosDBName string) (*documentdb.DatabaseAccount, error) { - cosmosDBClient, err := getCosmosDBClient() + cosmosDBClient, err := getCosmosDBClient(m.Creds) if err != nil { return nil, err } @@ -96,10 +97,10 @@ func (*AzureCosmosDBManager) GetCosmosDB( } // CheckNameExistsCosmosDB checks if the global account name already exists -func (*AzureCosmosDBManager) CheckNameExistsCosmosDB( +func (m *AzureCosmosDBManager) CheckNameExistsCosmosDB( ctx context.Context, accountName string) (bool, error) { - cosmosDBClient, err := getCosmosDBClient() + cosmosDBClient, err := getCosmosDBClient(m.Creds) if err != nil { return false, err } @@ -120,11 +121,11 @@ func (*AzureCosmosDBManager) CheckNameExistsCosmosDB( } // DeleteCosmosDB removes the resource group named by env var -func (*AzureCosmosDBManager) DeleteCosmosDB( +func (m *AzureCosmosDBManager) DeleteCosmosDB( ctx context.Context, groupName string, cosmosDBName string) (*autorest.Response, error) { - cosmosDBClient, err := getCosmosDBClient() + cosmosDBClient, err := getCosmosDBClient(m.Creds) if err != nil { return nil, err } @@ -142,11 +143,11 @@ func (*AzureCosmosDBManager) DeleteCosmosDB( } // ListKeys lists the read & write keys for a database account -func (*AzureCosmosDBManager) ListKeys( +func (m *AzureCosmosDBManager) ListKeys( ctx context.Context, groupName string, accountName string) (*documentdb.DatabaseAccountListKeysResult, error) { - client, err := getCosmosDBClient() + client, err := getCosmosDBClient(m.Creds) if err != nil { return nil, err } @@ -160,11 +161,11 @@ func (*AzureCosmosDBManager) ListKeys( } // ListConnectionStrings lists the connection strings for a database account -func (*AzureCosmosDBManager) ListConnectionStrings( +func (m *AzureCosmosDBManager) ListConnectionStrings( ctx context.Context, groupName string, accountName string) (*documentdb.DatabaseAccountListConnectionStringsResult, error) { - client, err := getCosmosDBClient() + client, err := getCosmosDBClient(m.Creds) if err != nil { return nil, err } diff --git a/pkg/resourcemanager/cosmosdbs/cosmosdb_manager.go b/pkg/resourcemanager/cosmosdbs/cosmosdb_manager.go index 82bd20163c9..ec53a6b16c4 100644 --- a/pkg/resourcemanager/cosmosdbs/cosmosdb_manager.go +++ b/pkg/resourcemanager/cosmosdbs/cosmosdb_manager.go @@ -9,13 +9,17 @@ import ( "github.com/Azure/azure-sdk-for-go/services/cosmos-db/mgmt/2015-04-08/documentdb" "github.com/Azure/azure-service-operator/api/v1alpha1" "github.com/Azure/azure-service-operator/pkg/resourcemanager" + "github.com/Azure/azure-service-operator/pkg/resourcemanager/config" "github.com/Azure/azure-service-operator/pkg/secrets" "github.com/Azure/go-autorest/autorest" ) // NewAzureCosmosDBManager creates a new cosmos db client -func NewAzureCosmosDBManager(secretClient secrets.SecretClient) *AzureCosmosDBManager { - return &AzureCosmosDBManager{secretClient} +func NewAzureCosmosDBManager(creds config.Credentials, secretClient secrets.SecretClient) *AzureCosmosDBManager { + return &AzureCosmosDBManager{ + Creds: creds, + SecretClient: secretClient, + } } // CosmosDBManager client functions diff --git a/pkg/resourcemanager/cosmosdbs/cosmosdb_reconcile.go b/pkg/resourcemanager/cosmosdbs/cosmosdb_reconcile.go index f63579181ec..5c814c51ce1 100644 --- a/pkg/resourcemanager/cosmosdbs/cosmosdb_reconcile.go +++ b/pkg/resourcemanager/cosmosdbs/cosmosdb_reconcile.go @@ -44,7 +44,7 @@ func (m *AzureCosmosDBManager) Ensure(ctx context.Context, obj runtime.Object, o instance.Status.Provisioned = false if instance.Status.PollingURL != "" { - pollClient := pollclient.NewPollClient() + pollClient := pollclient.NewPollClient(m.Creds) pollResponse, err := pollClient.Get(ctx, instance.Status.PollingURL) if err != nil { instance.Status.Provisioning = false diff --git a/pkg/resourcemanager/eventhubs/consumergroup.go b/pkg/resourcemanager/eventhubs/consumergroup.go index 57fb9bd0a01..ac2663fd401 100644 --- a/pkg/resourcemanager/eventhubs/consumergroup.go +++ b/pkg/resourcemanager/eventhubs/consumergroup.go @@ -23,15 +23,16 @@ import ( ) type azureConsumerGroupManager struct { + creds config.Credentials } -func NewConsumerGroupClient() *azureConsumerGroupManager { - return &azureConsumerGroupManager{} +func NewConsumerGroupClient(creds config.Credentials) *azureConsumerGroupManager { + return &azureConsumerGroupManager{creds: creds} } -func getConsumerGroupsClient() (eventhub.ConsumerGroupsClient, error) { - consumerGroupClient := eventhub.NewConsumerGroupsClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - auth, err := iam.GetResourceManagementAuthorizer() +func getConsumerGroupsClient(creds config.Credentials) (eventhub.ConsumerGroupsClient, error) { + consumerGroupClient := eventhub.NewConsumerGroupsClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + auth, err := iam.GetResourceManagementAuthorizer(creds) if err != nil { return eventhub.ConsumerGroupsClient{}, err } @@ -47,8 +48,8 @@ func getConsumerGroupsClient() (eventhub.ConsumerGroupsClient, error) { // eventHubName - the Event Hub name // consumerGroupName - the consumer group name // parameters - parameters supplied to create or update a consumer group resource. -func (_ *azureConsumerGroupManager) CreateConsumerGroup(ctx context.Context, resourceGroupName string, namespaceName string, eventHubName string, consumerGroupName string) (eventhub.ConsumerGroup, error) { - consumerGroupClient, err := getConsumerGroupsClient() +func (m *azureConsumerGroupManager) CreateConsumerGroup(ctx context.Context, resourceGroupName string, namespaceName string, eventHubName string, consumerGroupName string) (eventhub.ConsumerGroup, error) { + consumerGroupClient, err := getConsumerGroupsClient(m.creds) if err != nil { return eventhub.ConsumerGroup{}, err } @@ -71,8 +72,8 @@ func (_ *azureConsumerGroupManager) CreateConsumerGroup(ctx context.Context, res // namespaceName - the Namespace name // eventHubName - the Event Hub name // consumerGroupName - the consumer group name -func (_ *azureConsumerGroupManager) DeleteConsumerGroup(ctx context.Context, resourceGroupName string, namespaceName string, eventHubName string, consumerGroupName string) (result autorest.Response, err error) { - consumerGroupClient, err := getConsumerGroupsClient() +func (m *azureConsumerGroupManager) DeleteConsumerGroup(ctx context.Context, resourceGroupName string, namespaceName string, eventHubName string, consumerGroupName string) (result autorest.Response, err error) { + consumerGroupClient, err := getConsumerGroupsClient(m.creds) if err != nil { return autorest.Response{ Response: &http.Response{ @@ -91,8 +92,8 @@ func (_ *azureConsumerGroupManager) DeleteConsumerGroup(ctx context.Context, res } //GetConsumerGroup gets consumer group description for the specified Consumer Group. -func (_ *azureConsumerGroupManager) GetConsumerGroup(ctx context.Context, resourceGroupName string, namespaceName string, eventHubName string, consumerGroupName string) (eventhub.ConsumerGroup, error) { - consumerGroupClient, err := getConsumerGroupsClient() +func (m *azureConsumerGroupManager) GetConsumerGroup(ctx context.Context, resourceGroupName string, namespaceName string, eventHubName string, consumerGroupName string) (eventhub.ConsumerGroup, error) { + consumerGroupClient, err := getConsumerGroupsClient(m.creds) if err != nil { return eventhub.ConsumerGroup{}, err } diff --git a/pkg/resourcemanager/eventhubs/hub.go b/pkg/resourcemanager/eventhubs/hub.go index c5852af41af..bd2defe18d1 100644 --- a/pkg/resourcemanager/eventhubs/hub.go +++ b/pkg/resourcemanager/eventhubs/hub.go @@ -27,13 +27,14 @@ import ( ) type azureEventHubManager struct { + Creds config.Credentials SecretClient secrets.SecretClient Scheme *runtime.Scheme } -func getHubsClient() (eventhub.EventHubsClient, error) { - hubClient := eventhub.NewEventHubsClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - auth, err := iam.GetResourceManagementAuthorizer() +func getHubsClient(creds config.Credentials) (eventhub.EventHubsClient, error) { + hubClient := eventhub.NewEventHubsClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + auth, err := iam.GetResourceManagementAuthorizer(creds) if err != nil { return eventhub.EventHubsClient{}, err } @@ -42,15 +43,16 @@ func getHubsClient() (eventhub.EventHubsClient, error) { return hubClient, nil } -func NewEventhubClient(secretClient secrets.SecretClient, scheme *runtime.Scheme) *azureEventHubManager { +func NewEventhubClient(creds config.Credentials, secretClient secrets.SecretClient, scheme *runtime.Scheme) *azureEventHubManager { return &azureEventHubManager{ + Creds: creds, SecretClient: secretClient, Scheme: scheme, } } -func (_ *azureEventHubManager) DeleteHub(ctx context.Context, resourceGroupName string, namespaceName string, eventHubName string) (result autorest.Response, err error) { - hubClient, err := getHubsClient() +func (m *azureEventHubManager) DeleteHub(ctx context.Context, resourceGroupName string, namespaceName string, eventHubName string) (result autorest.Response, err error) { + hubClient, err := getHubsClient(m.Creds) if err != nil { return autorest.Response{ Response: &http.Response{ @@ -66,8 +68,8 @@ func (_ *azureEventHubManager) DeleteHub(ctx context.Context, resourceGroupName } -func (_ *azureEventHubManager) CreateHub(ctx context.Context, resourceGroupName string, namespaceName string, eventHubName string, MessageRetentionInDays int32, PartitionCount int32, captureDescription *eventhub.CaptureDescription) (eventhub.Model, error) { - hubClient, err := getHubsClient() +func (m *azureEventHubManager) CreateHub(ctx context.Context, resourceGroupName string, namespaceName string, eventHubName string, MessageRetentionInDays int32, PartitionCount int32, captureDescription *eventhub.CaptureDescription) (eventhub.Model, error) { + hubClient, err := getHubsClient(m.Creds) if err != nil { return eventhub.Model{}, err } @@ -99,8 +101,8 @@ func (_ *azureEventHubManager) CreateHub(ctx context.Context, resourceGroupName ) } -func (_ *azureEventHubManager) GetHub(ctx context.Context, resourceGroupName string, namespaceName string, eventHubName string) (eventhub.Model, error) { - hubClient, err := getHubsClient() +func (m *azureEventHubManager) GetHub(ctx context.Context, resourceGroupName string, namespaceName string, eventHubName string) (eventhub.Model, error) { + hubClient, err := getHubsClient(m.Creds) if err != nil { return eventhub.Model{}, err } @@ -108,8 +110,8 @@ func (_ *azureEventHubManager) GetHub(ctx context.Context, resourceGroupName str return hubClient.Get(ctx, resourceGroupName, namespaceName, eventHubName) } -func (_ *azureEventHubManager) CreateOrUpdateAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, eventHubName string, authorizationRuleName string, parameters eventhub.AuthorizationRule) (result eventhub.AuthorizationRule, err error) { - hubClient, err := getHubsClient() +func (m *azureEventHubManager) CreateOrUpdateAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, eventHubName string, authorizationRuleName string, parameters eventhub.AuthorizationRule) (result eventhub.AuthorizationRule, err error) { + hubClient, err := getHubsClient(m.Creds) if err != nil { return eventhub.AuthorizationRule{}, err } @@ -117,8 +119,8 @@ func (_ *azureEventHubManager) CreateOrUpdateAuthorizationRule(ctx context.Conte return hubClient.CreateOrUpdateAuthorizationRule(ctx, resourceGroupName, namespaceName, eventHubName, authorizationRuleName, parameters) } -func (_ *azureEventHubManager) ListKeys(ctx context.Context, resourceGroupName string, namespaceName string, eventHubName string, authorizationRuleName string) (result eventhub.AccessKeys, err error) { - hubClient, err := getHubsClient() +func (m *azureEventHubManager) ListKeys(ctx context.Context, resourceGroupName string, namespaceName string, eventHubName string, authorizationRuleName string) (result eventhub.AccessKeys, err error) { + hubClient, err := getHubsClient(m.Creds) if err != nil { return eventhub.AccessKeys{}, err } @@ -214,13 +216,13 @@ func (e *azureEventHubManager) listAccessKeysAndCreateSecrets(resourcegroup stri } -func (e *azureEventHubManager) Ensure(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) { +func (m *azureEventHubManager) Ensure(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) { options := &resourcemanager.Options{} for _, opt := range opts { opt(options) } - instance, err := e.convert(obj) + instance, err := m.convert(obj) if err != nil { return false, err } @@ -234,7 +236,7 @@ func (e *azureEventHubManager) Ensure(ctx context.Context, obj runtime.Object, o secretName := instance.Spec.SecretName if options.SecretClient != nil { - e.SecretClient = options.SecretClient + m.SecretClient = options.SecretClient } if len(secretName) == 0 { @@ -245,9 +247,9 @@ func (e *azureEventHubManager) Ensure(ctx context.Context, obj runtime.Object, o // write information back to instance instance.Status.Provisioning = true - capturePtr := getCaptureDescriptionPtr(captureDescription) + capturePtr := getCaptureDescriptionPtr(m.Creds, captureDescription) - hub, err := e.CreateHub(ctx, resourcegroup, eventhubNamespace, eventhubName, messageRetentionInDays, partitionCount, capturePtr) + hub, err := m.CreateHub(ctx, resourcegroup, eventhubNamespace, eventhubName, messageRetentionInDays, partitionCount, capturePtr) if err != nil { instance.Status.Message = err.Error() azerr := errhelp.NewAzureError(err) @@ -279,13 +281,13 @@ func (e *azureEventHubManager) Ensure(ctx context.Context, obj runtime.Object, o return false, err } - err = e.createOrUpdateAccessPolicyEventHub(resourcegroup, eventhubNamespace, eventhubName, instance) + err = m.createOrUpdateAccessPolicyEventHub(resourcegroup, eventhubNamespace, eventhubName, instance) if err != nil { instance.Status.Message = err.Error() return false, err } - err = e.listAccessKeysAndCreateSecrets(resourcegroup, eventhubNamespace, eventhubName, secretName, instance.Spec.AuthorizationRule.Name, instance) + err = m.listAccessKeysAndCreateSecrets(resourcegroup, eventhubNamespace, eventhubName, secretName, instance.Spec.AuthorizationRule.Name, instance) if err != nil { // catch secret existing and fail reconciliation @@ -409,12 +411,12 @@ func (e *azureEventHubManager) convert(obj runtime.Object) (*azurev1alpha1.Event const storageAccountResourceFmt = "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Storage/storageAccounts/%s" -func getCaptureDescriptionPtr(captureDescription azurev1alpha1.CaptureDescription) *model.CaptureDescription { +func getCaptureDescriptionPtr(creds config.Credentials, captureDescription azurev1alpha1.CaptureDescription) *model.CaptureDescription { // add capture details var capturePtr *model.CaptureDescription storage := captureDescription.Destination.StorageAccount - storageAccountResourceID := fmt.Sprintf(storageAccountResourceFmt, config.SubscriptionID(), storage.ResourceGroup, storage.AccountName) + storageAccountResourceID := fmt.Sprintf(storageAccountResourceFmt, creds.SubscriptionID(), storage.ResourceGroup, storage.AccountName) if captureDescription.Enabled { capturePtr = &model.CaptureDescription{ diff --git a/pkg/resourcemanager/eventhubs/namespace.go b/pkg/resourcemanager/eventhubs/namespace.go index 02a60705706..cbb3f5637ec 100644 --- a/pkg/resourcemanager/eventhubs/namespace.go +++ b/pkg/resourcemanager/eventhubs/namespace.go @@ -27,11 +27,12 @@ import ( ) type azureEventHubNamespaceManager struct { + creds config.Credentials } -func getNamespacesClient() (eventhub.NamespacesClient, error) { - nsClient := eventhub.NewNamespacesClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - auth, err := iam.GetResourceManagementAuthorizer() +func getNamespacesClient(creds config.Credentials) (eventhub.NamespacesClient, error) { + nsClient := eventhub.NewNamespacesClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + auth, err := iam.GetResourceManagementAuthorizer(creds) if err != nil { return eventhub.NamespacesClient{}, err } @@ -40,17 +41,17 @@ func getNamespacesClient() (eventhub.NamespacesClient, error) { return nsClient, nil } -func NewEventHubNamespaceClient() *azureEventHubNamespaceManager { - return &azureEventHubNamespaceManager{} +func NewEventHubNamespaceClient(creds config.Credentials) *azureEventHubNamespaceManager { + return &azureEventHubNamespaceManager{creds: creds} } // DeleteNamespace deletes an existing namespace. This operation also removes all associated resources under the namespace. // Parameters: // resourceGroupName - name of the resource group within the azure subscription. // namespaceName - the Namespace name -func (_ *azureEventHubNamespaceManager) DeleteNamespace(ctx context.Context, resourceGroupName string, namespaceName string) (autorest.Response, error) { +func (m *azureEventHubNamespaceManager) DeleteNamespace(ctx context.Context, resourceGroupName string, namespaceName string) (autorest.Response, error) { - nsClient, err := getNamespacesClient() + nsClient, err := getNamespacesClient(m.creds) if err != nil { return autorest.Response{ Response: &http.Response{ @@ -70,8 +71,8 @@ func (_ *azureEventHubNamespaceManager) DeleteNamespace(ctx context.Context, res // Parameters: // resourceGroupName - name of the resource group within the azure subscription. // namespaceName - the Namespace name -func (_ *azureEventHubNamespaceManager) GetNamespace(ctx context.Context, resourceGroupName string, namespaceName string) (*eventhub.EHNamespace, error) { - nsClient, err := getNamespacesClient() +func (m *azureEventHubNamespaceManager) GetNamespace(ctx context.Context, resourceGroupName string, namespaceName string) (*eventhub.EHNamespace, error) { + nsClient, err := getNamespacesClient(m.creds) if err != nil { return nil, err } @@ -92,8 +93,8 @@ func (_ *azureEventHubNamespaceManager) GetNamespace(ctx context.Context, resour // resourceGroupName - name of the resource group within the azure subscription. // namespaceName - the Namespace name // location - azure region -func (_ *azureEventHubNamespaceManager) CreateNamespaceAndWait(ctx context.Context, resourceGroupName string, namespaceName string, location string) (*eventhub.EHNamespace, error) { - nsClient, err := getNamespacesClient() +func (m *azureEventHubNamespaceManager) CreateNamespaceAndWait(ctx context.Context, resourceGroupName string, namespaceName string, location string) (*eventhub.EHNamespace, error) { + nsClient, err := getNamespacesClient(m.creds) if err != nil { return nil, err } @@ -119,8 +120,8 @@ func (_ *azureEventHubNamespaceManager) CreateNamespaceAndWait(ctx context.Conte return &result, err } -func (_ *azureEventHubNamespaceManager) CreateNamespace(ctx context.Context, resourceGroupName string, namespaceName string, location string, sku v1alpha1.EventhubNamespaceSku, properties v1alpha1.EventhubNamespaceProperties) (eventhub.EHNamespace, error) { - nsClient, err := getNamespacesClient() +func (m *azureEventHubNamespaceManager) CreateNamespace(ctx context.Context, resourceGroupName string, namespaceName string, location string, sku v1alpha1.EventhubNamespaceSku, properties v1alpha1.EventhubNamespaceProperties) (eventhub.EHNamespace, error) { + nsClient, err := getNamespacesClient(m.creds) if err != nil { return eventhub.EHNamespace{}, err } @@ -177,8 +178,8 @@ func (_ *azureEventHubNamespaceManager) CreateNamespace(ctx context.Context, res return future.Result(nsClient) } -func (nr *azureEventHubNamespaceManager) CreateNetworkRuleSet(ctx context.Context, groupname string, namespace string, rules eventhub.NetworkRuleSet) (result eventhub.NetworkRuleSet, err error) { - namespaceclient, err := getNamespacesClient() +func (m *azureEventHubNamespaceManager) CreateNetworkRuleSet(ctx context.Context, groupname string, namespace string, rules eventhub.NetworkRuleSet) (result eventhub.NetworkRuleSet, err error) { + namespaceclient, err := getNamespacesClient(m.creds) if err != nil { return eventhub.NetworkRuleSet{}, err } @@ -186,8 +187,8 @@ func (nr *azureEventHubNamespaceManager) CreateNetworkRuleSet(ctx context.Contex return namespaceclient.CreateOrUpdateNetworkRuleSet(ctx, groupname, namespace, rules) } -func (nr *azureEventHubNamespaceManager) GetNetworkRuleSet(ctx context.Context, groupName string, namespace string) (ruleset eventhub.NetworkRuleSet, err error) { - namespaceclient, err := getNamespacesClient() +func (m *azureEventHubNamespaceManager) GetNetworkRuleSet(ctx context.Context, groupName string, namespace string) (ruleset eventhub.NetworkRuleSet, err error) { + namespaceclient, err := getNamespacesClient(m.creds) if err != nil { return eventhub.NetworkRuleSet{}, err } @@ -195,8 +196,8 @@ func (nr *azureEventHubNamespaceManager) GetNetworkRuleSet(ctx context.Context, return namespaceclient.GetNetworkRuleSet(ctx, groupName, namespace) } -func (nr *azureEventHubNamespaceManager) DeleteNetworkRuleSet(ctx context.Context, groupName string, namespace string) (result eventhub.NetworkRuleSet, err error) { - namespaceclient, err := getNamespacesClient() +func (m *azureEventHubNamespaceManager) DeleteNetworkRuleSet(ctx context.Context, groupName string, namespace string) (result eventhub.NetworkRuleSet, err error) { + namespaceclient, err := getNamespacesClient(m.creds) if err != nil { return eventhub.NetworkRuleSet{}, err } diff --git a/pkg/resourcemanager/eventhubs/suite_test.go b/pkg/resourcemanager/eventhubs/suite_test.go index c4a7fefc7ca..dd88a8e0779 100644 --- a/pkg/resourcemanager/eventhubs/suite_test.go +++ b/pkg/resourcemanager/eventhubs/suite_test.go @@ -6,6 +6,7 @@ package eventhubs import ( "testing" + "github.com/Azure/azure-service-operator/pkg/resourcemanager/config" resourcemanagerconfig "github.com/Azure/azure-service-operator/pkg/resourcemanager/config" resourcegroupsresourcemanager "github.com/Azure/azure-service-operator/pkg/resourcemanager/resourcegroups" @@ -52,7 +53,7 @@ var _ = BeforeSuite(func() { resourceGroupName := "t-rg-dev-rm-eh-" + helpers.RandomString(10) resourceGroupLocation := resourcemanagerconfig.DefaultLocation() - resourceGroupManager := resourcegroupsresourcemanager.NewAzureResourceGroupManager() + resourceGroupManager := resourcegroupsresourcemanager.NewAzureResourceGroupManager(config.GlobalCredentials()) // resourcegroupsresourcemanager.DeleteAllGroupsWithPrefix(context.Background(), "t-rg-dev-") diff --git a/pkg/resourcemanager/iam/authorizers.go b/pkg/resourcemanager/iam/authorizers.go index bb6d8f51fdf..1caa133b98b 100644 --- a/pkg/resourcemanager/iam/authorizers.go +++ b/pkg/resourcemanager/iam/authorizers.go @@ -31,23 +31,23 @@ const ( OAuthGrantTypeServicePrincipal OAuthGrantType = iota // OAuthGrantTypeDeviceFlow for device flow OAuthGrantTypeDeviceFlow - // OAuthGrantTypeMI for aad-pod-identity - OAuthGrantTypeMI + // OAuthGrantTypeManagedIdentity for aad-pod-identity + OAuthGrantTypeManagedIdentity ) // GrantType returns what grant type has been configured. -func grantType() OAuthGrantType { +func grantType(creds config.Credentials) OAuthGrantType { if config.UseDeviceFlow() { return OAuthGrantTypeDeviceFlow } - if config.UseMI() { - return OAuthGrantTypeMI + if creds.UseManagedIdentity() { + return OAuthGrantTypeManagedIdentity } return OAuthGrantTypeServicePrincipal } // GetResourceManagementAuthorizer gets an OAuthTokenAuthorizer for Azure Resource Manager -func GetResourceManagementAuthorizer() (autorest.Authorizer, error) { +func GetResourceManagementAuthorizer(creds config.Credentials) (autorest.Authorizer, error) { if armAuthorizer != nil { return armAuthorizer, nil } @@ -55,7 +55,7 @@ func GetResourceManagementAuthorizer() (autorest.Authorizer, error) { var a autorest.Authorizer var err error - a, err = getAuthorizerForResource(config.Environment().ResourceManagerEndpoint) + a, err = getAuthorizerForResource(config.Environment().ResourceManagerEndpoint, creds) if err == nil { // cache @@ -68,7 +68,7 @@ func GetResourceManagementAuthorizer() (autorest.Authorizer, error) { } // GetBatchAuthorizer gets an OAuthTokenAuthorizer for Azure Batch. -func GetBatchAuthorizer() (autorest.Authorizer, error) { +func GetBatchAuthorizer(creds config.Credentials) (autorest.Authorizer, error) { if batchAuthorizer != nil { return batchAuthorizer, nil } @@ -76,7 +76,7 @@ func GetBatchAuthorizer() (autorest.Authorizer, error) { var a autorest.Authorizer var err error - a, err = getAuthorizerForResource(config.Environment().BatchManagementEndpoint) + a, err = getAuthorizerForResource(config.Environment().BatchManagementEndpoint, creds) if err == nil { // cache @@ -90,7 +90,7 @@ func GetBatchAuthorizer() (autorest.Authorizer, error) { } // GetGraphAuthorizer gets an OAuthTokenAuthorizer for graphrbac API. -func GetGraphAuthorizer() (autorest.Authorizer, error) { +func GetGraphAuthorizer(creds config.Credentials) (autorest.Authorizer, error) { if graphAuthorizer != nil { return graphAuthorizer, nil } @@ -98,7 +98,7 @@ func GetGraphAuthorizer() (autorest.Authorizer, error) { var a autorest.Authorizer var err error - a, err = getAuthorizerForResource(config.Environment().GraphEndpoint) + a, err = getAuthorizerForResource(config.Environment().GraphEndpoint, creds) if err == nil { // cache @@ -111,7 +111,7 @@ func GetGraphAuthorizer() (autorest.Authorizer, error) { } // GetGroupsAuthorizer gets an OAuthTokenAuthorizer for resource group API. -func GetGroupsAuthorizer() (autorest.Authorizer, error) { +func GetGroupsAuthorizer(creds config.Credentials) (autorest.Authorizer, error) { if groupsAuthorizer != nil { return groupsAuthorizer, nil } @@ -119,7 +119,7 @@ func GetGroupsAuthorizer() (autorest.Authorizer, error) { var a autorest.Authorizer var err error - a, err = getAuthorizerForResource(config.Environment().TokenAudience) + a, err = getAuthorizerForResource(config.Environment().TokenAudience, creds) if err == nil { // cache @@ -134,7 +134,7 @@ func GetGroupsAuthorizer() (autorest.Authorizer, error) { // GetKeyvaultAuthorizer gets an OAuthTokenAuthorizer for use with Key Vault // keys and secrets. Note that Key Vault *Vaults* are managed by Azure Resource // Manager. -func GetKeyvaultAuthorizer() (autorest.Authorizer, error) { +func GetKeyvaultAuthorizer(creds config.Credentials) (autorest.Authorizer, error) { if keyvaultAuthorizer != nil { return keyvaultAuthorizer, nil } @@ -143,29 +143,29 @@ func GetKeyvaultAuthorizer() (autorest.Authorizer, error) { vaultEndpoint := strings.TrimSuffix(config.Environment().KeyVaultEndpoint, "/") // BUG: alternateEndpoint replaces other endpoints in the configs below alternateEndpoint, _ := url.Parse( - "https://login.windows.net/" + config.TenantID() + "/oauth2/token") + "https://login.windows.net/" + creds.TenantID() + "/oauth2/token") var a autorest.Authorizer var err error - switch grantType() { + switch grantType(creds) { case OAuthGrantTypeServicePrincipal: oauthconfig, err := adal.NewOAuthConfig( - config.Environment().ActiveDirectoryEndpoint, config.TenantID()) + config.Environment().ActiveDirectoryEndpoint, creds.TenantID()) if err != nil { return a, err } oauthconfig.AuthorizeEndpoint = *alternateEndpoint token, err := adal.NewServicePrincipalToken( - *oauthconfig, config.ClientID(), config.ClientSecret(), vaultEndpoint) + *oauthconfig, creds.ClientID(), creds.ClientSecret(), vaultEndpoint) if err != nil { return a, err } a = autorest.NewBearerAuthorizer(token) - case OAuthGrantTypeMI: + case OAuthGrantTypeManagedIdentity: MIEndpoint, err := adal.GetMSIVMEndpoint() if err != nil { return nil, err @@ -179,7 +179,10 @@ func GetKeyvaultAuthorizer() (autorest.Authorizer, error) { a = autorest.NewBearerAuthorizer(token) case OAuthGrantTypeDeviceFlow: - deviceConfig := auth.NewDeviceFlowConfig(config.ClientID(), config.TenantID()) + // TODO: Remove this - it's an interactive authentication + // method and doesn't make sense in an operator. Maybe it was + // useful for early testing? + deviceConfig := auth.NewDeviceFlowConfig(creds.ClientID(), creds.TenantID()) deviceConfig.Resource = vaultEndpoint deviceConfig.AADEndpoint = alternateEndpoint.String() a, err = deviceConfig.Authorizer() @@ -196,27 +199,27 @@ func GetKeyvaultAuthorizer() (autorest.Authorizer, error) { return keyvaultAuthorizer, err } -func getAuthorizerForResource(resource string) (autorest.Authorizer, error) { +func getAuthorizerForResource(resource string, creds config.Credentials) (autorest.Authorizer, error) { var a autorest.Authorizer var err error - switch grantType() { + switch grantType(creds) { case OAuthGrantTypeServicePrincipal: oauthConfig, err := adal.NewOAuthConfig( - config.Environment().ActiveDirectoryEndpoint, config.TenantID()) + config.Environment().ActiveDirectoryEndpoint, creds.TenantID()) if err != nil { return nil, err } token, err := adal.NewServicePrincipalToken( - *oauthConfig, config.ClientID(), config.ClientSecret(), resource) + *oauthConfig, creds.ClientID(), creds.ClientSecret(), resource) if err != nil { return nil, err } a = autorest.NewBearerAuthorizer(token) - case OAuthGrantTypeMI: + case OAuthGrantTypeManagedIdentity: MIEndpoint, err := adal.GetMSIVMEndpoint() if err != nil { return nil, err @@ -230,7 +233,7 @@ func getAuthorizerForResource(resource string) (autorest.Authorizer, error) { a = autorest.NewBearerAuthorizer(token) case OAuthGrantTypeDeviceFlow: - deviceconfig := auth.NewDeviceFlowConfig(config.ClientID(), config.TenantID()) + deviceconfig := auth.NewDeviceFlowConfig(creds.ClientID(), creds.TenantID()) deviceconfig.Resource = resource a, err = deviceconfig.Authorizer() if err != nil { @@ -258,16 +261,3 @@ func GetMSITokenForResource(resource string) (*adal.ServicePrincipalToken, error return token, err } - -// GetResourceManagementTokenHybrid retrieves auth token for hybrid environment -func GetResourceManagementTokenHybrid(activeDirectoryEndpoint, tokenAudience string) (adal.OAuthTokenProvider, error) { - var tokenProvider adal.OAuthTokenProvider - oauthConfig, err := adal.NewOAuthConfig(activeDirectoryEndpoint, config.TenantID()) - tokenProvider, err = adal.NewServicePrincipalToken( - *oauthConfig, - config.ClientID(), - config.ClientSecret(), - tokenAudience) - - return tokenProvider, err -} diff --git a/pkg/resourcemanager/keyvaults/keyops.go b/pkg/resourcemanager/keyvaults/keyops.go index d1d96e40d8d..0fb2e582655 100644 --- a/pkg/resourcemanager/keyvaults/keyops.go +++ b/pkg/resourcemanager/keyvaults/keyops.go @@ -14,6 +14,7 @@ import ( "github.com/Azure/azure-service-operator/pkg/errhelp" "github.com/Azure/azure-service-operator/pkg/helpers" "github.com/Azure/azure-service-operator/pkg/resourcemanager" + "github.com/Azure/azure-service-operator/pkg/resourcemanager/config" "github.com/Azure/go-autorest/autorest/to" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" @@ -21,9 +22,17 @@ import ( // KeyvaultKeyClient emcompasses the methods needed for the keyops client to fulfill the ARMClient interface type KeyvaultKeyClient struct { + Creds config.Credentials KeyvaultClient *azureKeyVaultManager } +func NewKeyvaultKeyClient(creds config.Credentials, client *azureKeyVaultManager) *KeyvaultKeyClient { + return &KeyvaultKeyClient{ + Creds: creds, + KeyvaultClient: client, + } +} + // Ensure idempotently implements the user's requested state func (k *KeyvaultKeyClient) Ensure(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) { instance, err := k.convert(obj) @@ -35,7 +44,7 @@ func (k *KeyvaultKeyClient) Ensure(ctx context.Context, obj runtime.Object, opts // Check if this KeyVault already exists and its state if it does. - kvopsclient := NewOpsClient(instance.Name) + kvopsclient := NewOpsClient(k.Creds, instance.Name) keyvault, err := k.KeyvaultClient.GetVault(ctx, instance.Spec.ResourceGroup, instance.Spec.KeyVault) if err != nil { @@ -148,7 +157,7 @@ func (k *KeyvaultKeyClient) Delete(ctx context.Context, obj runtime.Object, opts } vaultBaseURL := *keyv.Properties.VaultURI - kvopsclient := NewOpsClient(instance.Spec.KeyVault) + kvopsclient := NewOpsClient(k.Creds, instance.Spec.KeyVault) req, err := kvopsclient.DeleteKey(ctx, vaultBaseURL, instance.Name) if err != nil { diff --git a/pkg/resourcemanager/keyvaults/keyvault.go b/pkg/resourcemanager/keyvaults/keyvault.go index c370b3bab02..af351ecbddf 100644 --- a/pkg/resourcemanager/keyvaults/keyvault.go +++ b/pkg/resourcemanager/keyvaults/keyvault.go @@ -29,18 +29,20 @@ import ( ) type azureKeyVaultManager struct { + Creds config.Credentials Scheme *runtime.Scheme } -func NewAzureKeyVaultManager(scheme *runtime.Scheme) *azureKeyVaultManager { +func NewAzureKeyVaultManager(creds config.Credentials, scheme *runtime.Scheme) *azureKeyVaultManager { return &azureKeyVaultManager{ + Creds: creds, Scheme: scheme, } } -func getVaultsClient() (keyvault.VaultsClient, error) { - vaultsClient := keyvault.NewVaultsClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, err := iam.GetResourceManagementAuthorizer() +func getVaultsClient(creds config.Credentials) (keyvault.VaultsClient, error) { + vaultsClient := keyvault.NewVaultsClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, err := iam.GetResourceManagementAuthorizer(creds) if err != nil { return vaultsClient, err } @@ -49,9 +51,9 @@ func getVaultsClient() (keyvault.VaultsClient, error) { return vaultsClient, nil } -func getObjectID(ctx context.Context, tenantID string, clientID string) (*string, error) { +func getObjectID(ctx context.Context, creds config.Credentials, tenantID string, clientID string) (*string, error) { appclient := auth.NewApplicationsClient(tenantID) - a, err := iam.GetGraphAuthorizer() + a, err := iam.GetGraphAuthorizer(creds) if err != nil { return nil, err } @@ -114,7 +116,7 @@ func ParseNetworkPolicy(ruleSet *v1alpha1.NetworkRuleSet) keyvault.NetworkRuleSe } // ParseAccessPolicy - helper function to parse access policies from Kubernetes spec -func ParseAccessPolicy(policy *v1alpha1.AccessPolicyEntry, ctx context.Context) (keyvault.AccessPolicyEntry, error) { +func ParseAccessPolicy(ctx context.Context, creds config.Credentials, policy *v1alpha1.AccessPolicyEntry) (keyvault.AccessPolicyEntry, error) { tenantID, err := uuid.FromString(policy.TenantID) if err != nil { return keyvault.AccessPolicyEntry{}, err @@ -211,7 +213,7 @@ func ParseAccessPolicy(policy *v1alpha1.AccessPolicyEntry, ctx context.Context) } if policy.ClientID != "" { - objID, err := getObjectID(ctx, policy.TenantID, policy.ClientID) + objID, err := getObjectID(ctx, creds, policy.TenantID, policy.ClientID) if err != nil { return keyvault.AccessPolicyEntry{}, err } @@ -225,12 +227,12 @@ func ParseAccessPolicy(policy *v1alpha1.AccessPolicyEntry, ctx context.Context) } // InstantiateVault will instantiate VaultsClient -func InstantiateVault(ctx context.Context, vaultName string, containsUpdate bool) (keyvault.VaultsClient, uuid.UUID, error) { - vaultsClient, err := getVaultsClient() +func InstantiateVault(ctx context.Context, creds config.Credentials, vaultName string, containsUpdate bool) (keyvault.VaultsClient, uuid.UUID, error) { + vaultsClient, err := getVaultsClient(creds) if err != nil { return keyvault.VaultsClient{}, uuid.UUID{}, err } - id, err := uuid.FromString(config.TenantID()) + id, err := uuid.FromString(creds.TenantID()) if err != nil { return keyvault.VaultsClient{}, uuid.UUID{}, err } @@ -256,13 +258,13 @@ func InstantiateVault(ctx context.Context, vaultName string, containsUpdate bool } // CreateVault creates a new key vault -func (k *azureKeyVaultManager) CreateVault(ctx context.Context, instance *v1alpha1.KeyVault, sku azurev1alpha1.KeyVaultSku, tags map[string]*string, vaultExists bool) (keyvault.Vault, error) { +func (m *azureKeyVaultManager) CreateVault(ctx context.Context, instance *v1alpha1.KeyVault, sku azurev1alpha1.KeyVaultSku, tags map[string]*string, vaultExists bool) (keyvault.Vault, error) { vaultName := instance.Name location := instance.Spec.Location groupName := instance.Spec.ResourceGroup enableSoftDelete := instance.Spec.EnableSoftDelete - vaultsClient, id, err := InstantiateVault(ctx, vaultName, instance.Status.ContainsUpdate) + vaultsClient, id, err := InstantiateVault(ctx, m.Creds, vaultName, instance.Status.ContainsUpdate) if err != nil { return keyvault.Vault{}, err } @@ -271,7 +273,7 @@ func (k *azureKeyVaultManager) CreateVault(ctx context.Context, instance *v1alph if instance.Spec.AccessPolicies != nil { for _, policy := range *instance.Spec.AccessPolicies { policy := policy // Make a copy of the variable and redeclare it - newEntry, err := ParseAccessPolicy(&policy, ctx) + newEntry, err := ParseAccessPolicy(ctx, m.Creds, &policy) if err != nil { return keyvault.Vault{}, err } @@ -323,8 +325,8 @@ func (k *azureKeyVaultManager) CreateVault(ctx context.Context, instance *v1alph } //CreateVaultWithAccessPolicies creates a new key vault and provides access policies to the specified user -func (k *azureKeyVaultManager) CreateVaultWithAccessPolicies(ctx context.Context, groupName string, vaultName string, location string, clientID string) (keyvault.Vault, error) { - vaultsClient, id, err := InstantiateVault(ctx, vaultName, false) +func (m *azureKeyVaultManager) CreateVaultWithAccessPolicies(ctx context.Context, groupName string, vaultName string, location string, clientID string) (keyvault.Vault, error) { + vaultsClient, id, err := InstantiateVault(ctx, m.Creds, vaultName, false) if err != nil { return keyvault.Vault{}, err } @@ -345,7 +347,7 @@ func (k *azureKeyVaultManager) CreateVaultWithAccessPolicies(ctx context.Context }, } if clientID != "" { - objID, err := getObjectID(ctx, config.TenantID(), clientID) + objID, err := getObjectID(ctx, m.Creds, m.Creds.TenantID(), clientID) if err != nil { return keyvault.Vault{}, err } @@ -377,8 +379,8 @@ func (k *azureKeyVaultManager) CreateVaultWithAccessPolicies(ctx context.Context } // DeleteVault removes the resource group named by env var -func (k *azureKeyVaultManager) DeleteVault(ctx context.Context, groupName string, vaultName string) (result autorest.Response, err error) { - vaultsClient, err := getVaultsClient() +func (m *azureKeyVaultManager) DeleteVault(ctx context.Context, groupName string, vaultName string) (result autorest.Response, err error) { + vaultsClient, err := getVaultsClient(m.Creds) if err != nil { return autorest.Response{}, err } @@ -386,8 +388,8 @@ func (k *azureKeyVaultManager) DeleteVault(ctx context.Context, groupName string } // CheckExistence checks for the presence of a keyvault instance on Azure -func (k *azureKeyVaultManager) GetVault(ctx context.Context, groupName string, vaultName string) (result keyvault.Vault, err error) { - vaultsClient, err := getVaultsClient() +func (m *azureKeyVaultManager) GetVault(ctx context.Context, groupName string, vaultName string) (result keyvault.Vault, err error) { + vaultsClient, err := getVaultsClient(m.Creds) if err != nil { return keyvault.Vault{}, err } @@ -395,8 +397,8 @@ func (k *azureKeyVaultManager) GetVault(ctx context.Context, groupName string, v } -func (k *azureKeyVaultManager) Ensure(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) { - instance, err := k.convert(obj) +func (m *azureKeyVaultManager) Ensure(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) { + instance, err := m.convert(obj) if err != nil { return true, err } @@ -411,7 +413,7 @@ func (k *azureKeyVaultManager) Ensure(ctx context.Context, obj runtime.Object, o instance.Status.FailedProvisioning = false exists := false // Check if this KeyVault already exists and its state if it does. - keyvault, err := k.GetVault(ctx, instance.Spec.ResourceGroup, instance.Name) + keyvault, err := m.GetVault(ctx, instance.Spec.ResourceGroup, instance.Name) if err == nil { exists = true if instance.Status.SpecHash == hash { @@ -427,7 +429,7 @@ func (k *azureKeyVaultManager) Ensure(ctx context.Context, obj runtime.Object, o } - keyvault, err = k.CreateVault( + keyvault, err = m.CreateVault( ctx, instance, instance.Spec.Sku, @@ -511,15 +513,15 @@ func HandleCreationError(instance *v1alpha1.KeyVault, err error) (bool, error) { return false, err } -func (k *azureKeyVaultManager) Delete(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) { - instance, err := k.convert(obj) +func (m *azureKeyVaultManager) Delete(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) { + instance, err := m.convert(obj) if err != nil { return true, err } - _, err = k.GetVault(ctx, instance.Spec.ResourceGroup, instance.Name) + _, err = m.GetVault(ctx, instance.Spec.ResourceGroup, instance.Name) if err == nil { - _, err := k.DeleteVault(ctx, instance.Spec.ResourceGroup, instance.Name) + _, err := m.DeleteVault(ctx, instance.Spec.ResourceGroup, instance.Name) if err != nil { catch := []string{ errhelp.AsyncOpIncompleteError, @@ -544,9 +546,9 @@ func (k *azureKeyVaultManager) Delete(ctx context.Context, obj runtime.Object, o return false, nil } -func (k *azureKeyVaultManager) GetParents(obj runtime.Object) ([]resourcemanager.KubeParent, error) { +func (m *azureKeyVaultManager) GetParents(obj runtime.Object) ([]resourcemanager.KubeParent, error) { - instance, err := k.convert(obj) + instance, err := m.convert(obj) if err != nil { return nil, err } @@ -570,7 +572,7 @@ func (g *azureKeyVaultManager) GetStatus(obj runtime.Object) (*v1alpha1.ASOStatu return &instance.Status, nil } -func (k *azureKeyVaultManager) convert(obj runtime.Object) (*v1alpha1.KeyVault, error) { +func (m *azureKeyVaultManager) convert(obj runtime.Object) (*v1alpha1.KeyVault, error) { local, ok := obj.(*v1alpha1.KeyVault) if !ok { return nil, fmt.Errorf("failed type assertion on kind: %s", obj.GetObjectKind().GroupVersionKind().String()) @@ -578,9 +580,9 @@ func (k *azureKeyVaultManager) convert(obj runtime.Object) (*v1alpha1.KeyVault, return local, nil } -func NewOpsClient(keyvaultName string) *kvops.BaseClient { +func NewOpsClient(creds config.Credentials, keyvaultName string) *kvops.BaseClient { keyvaultClient := kvops.New() - a, _ := iam.GetKeyvaultAuthorizer() + a, _ := iam.GetKeyvaultAuthorizer(creds) keyvaultClient.Authorizer = a keyvaultClient.AddToUserAgent(config.UserAgent()) return &keyvaultClient diff --git a/pkg/resourcemanager/keyvaults/keyvault_manager.go b/pkg/resourcemanager/keyvaults/keyvault_manager.go index 2b41acbaf2c..e58a47c794f 100644 --- a/pkg/resourcemanager/keyvaults/keyvault_manager.go +++ b/pkg/resourcemanager/keyvaults/keyvault_manager.go @@ -13,8 +13,6 @@ import ( "github.com/Azure/azure-service-operator/pkg/resourcemanager" ) -var AzureKeyVaultManager KeyVaultManager = &azureKeyVaultManager{} - type KeyVaultManager interface { CreateVault(ctx context.Context, instance *azurev1alpha1.KeyVault, sku azurev1alpha1.KeyVaultSku, tags map[string]*string, exists bool) (keyvault.Vault, error) @@ -30,3 +28,5 @@ type KeyVaultManager interface { // also embed async client methods resourcemanager.ARMClient } + +var _ KeyVaultManager = &azureKeyVaultManager{} diff --git a/pkg/resourcemanager/keyvaults/suite_test.go b/pkg/resourcemanager/keyvaults/suite_test.go index 2644c5b0d3a..11919520d03 100644 --- a/pkg/resourcemanager/keyvaults/suite_test.go +++ b/pkg/resourcemanager/keyvaults/suite_test.go @@ -10,6 +10,7 @@ import ( "time" "github.com/Azure/azure-service-operator/pkg/errhelp" + "github.com/Azure/azure-service-operator/pkg/resourcemanager/config" resourcemanagerconfig "github.com/Azure/azure-service-operator/pkg/resourcemanager/config" "k8s.io/client-go/kubernetes/scheme" @@ -59,7 +60,7 @@ var _ = BeforeSuite(func() { resourceGroupName := "t-rg-dev-kv-" + helpers.RandomString(10) resourceGroupLocation := resourcemanagerconfig.DefaultLocation() - resourceGroupManager := resourcegroupsresourcemanager.NewAzureResourceGroupManager() + resourceGroupManager := resourcegroupsresourcemanager.NewAzureResourceGroupManager(config.GlobalCredentials()) //create resourcegroup for this suite _, err = resourceGroupManager.CreateGroup(ctx, resourceGroupName, resourceGroupLocation) @@ -92,7 +93,8 @@ var _ = AfterSuite(func() { polling := time.Second * 10 Eventually(func() bool { - _, err := resourcegroupsresourcemanager.GetGroup(ctx, tc.ResourceGroupName) + rgManager := resourcegroupsresourcemanager.NewAzureResourceGroupManager(config.GlobalCredentials()) + _, err := rgManager.GetGroup(ctx, tc.ResourceGroupName) if err == nil { log.Println("waiting for resource group to be deleted") return false diff --git a/pkg/resourcemanager/keyvaults/unittest/keyvault_test.go b/pkg/resourcemanager/keyvaults/unittest/keyvault_test.go index 4125a270184..61434bd916e 100644 --- a/pkg/resourcemanager/keyvaults/unittest/keyvault_test.go +++ b/pkg/resourcemanager/keyvaults/unittest/keyvault_test.go @@ -9,6 +9,7 @@ import ( keyvault "github.com/Azure/azure-sdk-for-go/services/keyvault/mgmt/2018-02-14/keyvault" v1alpha1 "github.com/Azure/azure-service-operator/api/v1alpha1" + "github.com/Azure/azure-service-operator/pkg/resourcemanager/config" azurekeyvault "github.com/Azure/azure-service-operator/pkg/resourcemanager/keyvaults" "github.com/google/go-cmp/cmp" uuid "github.com/satori/go.uuid" @@ -31,7 +32,7 @@ func TestParseAccessPoliciesInvalid(t *testing.T) { ctx := context.Background() - resp, err := azurekeyvault.ParseAccessPolicy(&entry, ctx) + resp, err := azurekeyvault.ParseAccessPolicy(ctx, config.GlobalCredentials(), &entry) assert.True(t, err != nil) assert.True(t, cmp.Equal(resp, keyvault.AccessPolicyEntry{})) } @@ -84,7 +85,7 @@ func TestParseAccessPolicies(t *testing.T) { ctx := context.Background() - resp, err := azurekeyvault.ParseAccessPolicy(&entry, ctx) + resp, err := azurekeyvault.ParseAccessPolicy(ctx, config.GlobalCredentials(), &entry) assert.True(t, err == nil) assert.True(t, cmp.Equal(resp, out)) } diff --git a/pkg/resourcemanager/loadbalancer/client.go b/pkg/resourcemanager/loadbalancer/client.go index 6ee5dce8653..ebd37df7b10 100644 --- a/pkg/resourcemanager/loadbalancer/client.go +++ b/pkg/resourcemanager/loadbalancer/client.go @@ -16,28 +16,30 @@ import ( ) type AzureLoadBalancerClient struct { + Creds config.Credentials SecretClient secrets.SecretClient Scheme *runtime.Scheme } -func NewAzureLoadBalancerClient(secretclient secrets.SecretClient, scheme *runtime.Scheme) *AzureLoadBalancerClient { +func NewAzureLoadBalancerClient(creds config.Credentials, secretclient secrets.SecretClient, scheme *runtime.Scheme) *AzureLoadBalancerClient { return &AzureLoadBalancerClient{ + Creds: creds, SecretClient: secretclient, Scheme: scheme, } } -func getLoadBalancerClient() vnetwork.LoadBalancersClient { - lbClient := vnetwork.NewLoadBalancersClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, _ := iam.GetResourceManagementAuthorizer() +func getLoadBalancerClient(creds config.Credentials) vnetwork.LoadBalancersClient { + lbClient := vnetwork.NewLoadBalancersClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, _ := iam.GetResourceManagementAuthorizer(creds) lbClient.Authorizer = a lbClient.AddToUserAgent(config.UserAgent()) return lbClient } -func (m *AzureLoadBalancerClient) CreateLoadBalancer(ctx context.Context, location string, resourceGroupName string, resourceName string, publicIPAddressName string, backendAddressPoolName string, inboundNatPoolName string, frontendPortRangeStart int, frontendPortRangeEnd int, backendPort int) (future vnetwork.LoadBalancersCreateOrUpdateFuture, err error) { +func (c *AzureLoadBalancerClient) CreateLoadBalancer(ctx context.Context, location string, resourceGroupName string, resourceName string, publicIPAddressName string, backendAddressPoolName string, inboundNatPoolName string, frontendPortRangeStart int, frontendPortRangeEnd int, backendPort int) (future vnetwork.LoadBalancersCreateOrUpdateFuture, err error) { - client := getLoadBalancerClient() + client := getLoadBalancerClient(c.Creds) publicIPAddressIDInput := helpers.MakeResourceID( client.SubscriptionID, @@ -125,9 +127,9 @@ func (m *AzureLoadBalancerClient) CreateLoadBalancer(ctx context.Context, locati return future, err } -func (m *AzureLoadBalancerClient) DeleteLoadBalancer(ctx context.Context, loadBalancerName string, resourcegroup string) (status string, err error) { +func (c *AzureLoadBalancerClient) DeleteLoadBalancer(ctx context.Context, loadBalancerName string, resourcegroup string) (status string, err error) { - client := getLoadBalancerClient() + client := getLoadBalancerClient(c.Creds) _, err = client.Get(ctx, resourcegroup, loadBalancerName, "") if err == nil { // load balancer present, so go ahead and delete @@ -139,9 +141,9 @@ func (m *AzureLoadBalancerClient) DeleteLoadBalancer(ctx context.Context, loadBa } -func (m *AzureLoadBalancerClient) GetLoadBalancer(ctx context.Context, resourcegroup string, loadBalancerName string) (lb vnetwork.LoadBalancer, err error) { +func (c *AzureLoadBalancerClient) GetLoadBalancer(ctx context.Context, resourcegroup string, loadBalancerName string) (lb vnetwork.LoadBalancer, err error) { - client := getLoadBalancerClient() + client := getLoadBalancerClient(c.Creds) return client.Get(ctx, resourcegroup, loadBalancerName, "") } diff --git a/pkg/resourcemanager/loadbalancer/reconcile.go b/pkg/resourcemanager/loadbalancer/reconcile.go index bf61d76542f..2c81a6d04a0 100644 --- a/pkg/resourcemanager/loadbalancer/reconcile.go +++ b/pkg/resourcemanager/loadbalancer/reconcile.go @@ -15,14 +15,14 @@ import ( "k8s.io/apimachinery/pkg/types" ) -func (g *AzureLoadBalancerClient) Ensure(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) { +func (c *AzureLoadBalancerClient) Ensure(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) { - instance, err := g.convert(obj) + instance, err := c.convert(obj) if err != nil { return true, err } - client := getLoadBalancerClient() + client := getLoadBalancerClient(c.Creds) location := instance.Spec.Location resourceGroup := instance.Spec.ResourceGroup @@ -37,7 +37,7 @@ func (g *AzureLoadBalancerClient) Ensure(ctx context.Context, obj runtime.Object instance.Status.Provisioning = true // Check if this item already exists. This is required // to overcome the issue with the lack of idempotence of the Create call - item, err := g.GetLoadBalancer(ctx, resourceGroup, resourceName) + item, err := c.GetLoadBalancer(ctx, resourceGroup, resourceName) if err == nil { instance.Status.Provisioned = true instance.Status.Provisioning = false @@ -45,7 +45,7 @@ func (g *AzureLoadBalancerClient) Ensure(ctx context.Context, obj runtime.Object instance.Status.ResourceId = *item.ID return true, nil } - future, err := g.CreateLoadBalancer( + future, err := c.CreateLoadBalancer( ctx, location, resourceGroup, diff --git a/pkg/resourcemanager/mysql/database/client.go b/pkg/resourcemanager/mysql/database/client.go index 3f9c7b3e092..0fc0de39efc 100644 --- a/pkg/resourcemanager/mysql/database/client.go +++ b/pkg/resourcemanager/mysql/database/client.go @@ -13,25 +13,26 @@ import ( //MySQLDatabaseClient struct type MySQLDatabaseClient struct { + creds config.Credentials } //NewMySQLDatabaseClient create a new MySQLDatabaseClient -func NewMySQLDatabaseClient() *MySQLDatabaseClient { - return &MySQLDatabaseClient{} +func NewMySQLDatabaseClient(creds config.Credentials) *MySQLDatabaseClient { + return &MySQLDatabaseClient{creds: creds} } //GetMySQLDatabasesClient return the mysqldatabaseclient -func GetMySQLDatabasesClient() mysql.DatabasesClient { - databasesClient := mysql.NewDatabasesClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, _ := iam.GetResourceManagementAuthorizer() +func GetMySQLDatabasesClient(creds config.Credentials) mysql.DatabasesClient { + databasesClient := mysql.NewDatabasesClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, _ := iam.GetResourceManagementAuthorizer(creds) databasesClient.Authorizer = a databasesClient.AddToUserAgent(config.UserAgent()) return databasesClient } -func getMySQLCheckNameAvailabilityClient() mysql.CheckNameAvailabilityClient { - nameavailabilityClient := mysql.NewCheckNameAvailabilityClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, _ := iam.GetResourceManagementAuthorizer() +func getMySQLCheckNameAvailabilityClient(creds config.Credentials) mysql.CheckNameAvailabilityClient { + nameavailabilityClient := mysql.NewCheckNameAvailabilityClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, _ := iam.GetResourceManagementAuthorizer(creds) nameavailabilityClient.Authorizer = a nameavailabilityClient.AddToUserAgent(config.UserAgent()) return nameavailabilityClient @@ -39,7 +40,7 @@ func getMySQLCheckNameAvailabilityClient() mysql.CheckNameAvailabilityClient { func (m *MySQLDatabaseClient) CheckDatabaseNameAvailability(ctx context.Context, databasename string) (bool, error) { - client := getMySQLCheckNameAvailabilityClient() + client := getMySQLCheckNameAvailabilityClient(m.creds) resourceType := "Microsoft.DBforMySQL/servers/databases" @@ -57,7 +58,7 @@ func (m *MySQLDatabaseClient) CheckDatabaseNameAvailability(ctx context.Context, func (m *MySQLDatabaseClient) CreateDatabaseIfValid(ctx context.Context, databasename string, servername string, resourcegroup string) (future mysql.DatabasesCreateOrUpdateFuture, err error) { - client := GetMySQLDatabasesClient() + client := GetMySQLDatabasesClient(m.creds) // Check if name is valid if this is the first create call valid, err := m.CheckDatabaseNameAvailability(ctx, databasename) @@ -80,7 +81,7 @@ func (m *MySQLDatabaseClient) CreateDatabaseIfValid(ctx context.Context, databas func (m *MySQLDatabaseClient) DeleteDatabase(ctx context.Context, databasename string, servername string, resourcegroup string) (status string, err error) { - client := GetMySQLDatabasesClient() + client := GetMySQLDatabasesClient(m.creds) _, err = client.Get(ctx, resourcegroup, servername, databasename) if err == nil { // db present, so go ahead and delete @@ -94,7 +95,7 @@ func (m *MySQLDatabaseClient) DeleteDatabase(ctx context.Context, databasename s func (m *MySQLDatabaseClient) GetDatabase(ctx context.Context, resourcegroup string, servername string, databasename string) (db mysql.Database, err error) { - client := GetMySQLDatabasesClient() + client := GetMySQLDatabasesClient(m.creds) return client.Get(ctx, resourcegroup, servername, databasename) } diff --git a/pkg/resourcemanager/mysql/database/reconcile.go b/pkg/resourcemanager/mysql/database/reconcile.go index 1dcb68db974..f01f6074f78 100644 --- a/pkg/resourcemanager/mysql/database/reconcile.go +++ b/pkg/resourcemanager/mysql/database/reconcile.go @@ -23,7 +23,7 @@ func (m *MySQLDatabaseClient) Ensure(ctx context.Context, obj runtime.Object, op return true, err } - client := GetMySQLDatabasesClient() + client := GetMySQLDatabasesClient(m.creds) instance.Status.Provisioning = true // Check if this database already exists. This is required diff --git a/pkg/resourcemanager/mysql/firewallrule/client.go b/pkg/resourcemanager/mysql/firewallrule/client.go index 8ae3d42e5ec..333fd862fe7 100644 --- a/pkg/resourcemanager/mysql/firewallrule/client.go +++ b/pkg/resourcemanager/mysql/firewallrule/client.go @@ -13,15 +13,16 @@ import ( ) type MySQLFirewallRuleClient struct { + creds config.Credentials } -func NewMySQLFirewallRuleClient() *MySQLFirewallRuleClient { - return &MySQLFirewallRuleClient{} +func NewMySQLFirewallRuleClient(creds config.Credentials) *MySQLFirewallRuleClient { + return &MySQLFirewallRuleClient{creds: creds} } -func getMySQLFirewallRulesClient() mysql.FirewallRulesClient { - firewallRulesClient := mysql.NewFirewallRulesClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, _ := iam.GetResourceManagementAuthorizer() +func getMySQLFirewallRulesClient(creds config.Credentials) mysql.FirewallRulesClient { + firewallRulesClient := mysql.NewFirewallRulesClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, _ := iam.GetResourceManagementAuthorizer(creds) firewallRulesClient.Authorizer = a firewallRulesClient.AddToUserAgent(config.UserAgent()) return firewallRulesClient @@ -29,7 +30,7 @@ func getMySQLFirewallRulesClient() mysql.FirewallRulesClient { func (m *MySQLFirewallRuleClient) CreateFirewallRule(ctx context.Context, resourcegroup string, servername string, firewallrulename string, startip string, endip string) (future mysql.FirewallRulesCreateOrUpdateFuture, err error) { - client := getMySQLFirewallRulesClient() + client := getMySQLFirewallRulesClient(m.creds) firewallRuleProperties := mysql.FirewallRuleProperties{ StartIPAddress: to.StringPtr(startip), @@ -50,7 +51,7 @@ func (m *MySQLFirewallRuleClient) CreateFirewallRule(ctx context.Context, resour func (m *MySQLFirewallRuleClient) DeleteFirewallRule(ctx context.Context, resourcegroup string, servername string, firewallrulename string) (status string, err error) { - client := getMySQLFirewallRulesClient() + client := getMySQLFirewallRulesClient(m.creds) _, err = client.Get(ctx, resourcegroup, servername, firewallrulename) if err == nil { // FW rule present, so go ahead and delete @@ -64,7 +65,7 @@ func (m *MySQLFirewallRuleClient) DeleteFirewallRule(ctx context.Context, resour func (m *MySQLFirewallRuleClient) GetFirewallRule(ctx context.Context, resourcegroup string, servername string, firewallrulename string) (firewall mysql.FirewallRule, err error) { - client := getMySQLFirewallRulesClient() + client := getMySQLFirewallRulesClient(m.creds) return client.Get(ctx, resourcegroup, servername, firewallrulename) } diff --git a/pkg/resourcemanager/mysql/firewallrule/reconcile.go b/pkg/resourcemanager/mysql/firewallrule/reconcile.go index 3d7257da4f0..d9632a985d8 100644 --- a/pkg/resourcemanager/mysql/firewallrule/reconcile.go +++ b/pkg/resourcemanager/mysql/firewallrule/reconcile.go @@ -22,7 +22,7 @@ func (m *MySQLFirewallRuleClient) Ensure(ctx context.Context, obj runtime.Object return true, err } - client := getMySQLFirewallRulesClient() + client := getMySQLFirewallRulesClient(m.creds) instance.Status.Provisioning = true // Check if this server already exists and its state if it does. This is required diff --git a/pkg/resourcemanager/mysql/mysqluser/mysqluser.go b/pkg/resourcemanager/mysql/mysqluser/mysqluser.go index f80f1964847..445ab1ef0dd 100644 --- a/pkg/resourcemanager/mysql/mysqluser/mysqluser.go +++ b/pkg/resourcemanager/mysql/mysqluser/mysqluser.go @@ -34,23 +34,25 @@ const MSecretUsernameKey = "username" // MSecretPasswordKey is the password key in secret const MSecretPasswordKey = "password" -//MySqlUserManager for mysqluser manager +// MySqlUserManager for mysqluser manager type MySqlUserManager struct { + Creds config.Credentials SecretClient secrets.SecretClient Scheme *runtime.Scheme } -//NewMySqlUserManager creates a new NewMySqlUserManager -func NewMySqlUserManager(secretClient secrets.SecretClient, scheme *runtime.Scheme) *MySqlUserManager { +// NewMySqlUserManager creates a new MySqlUserManager +func NewMySqlUserManager(creds config.Credentials, secretClient secrets.SecretClient, scheme *runtime.Scheme) *MySqlUserManager { return &MySqlUserManager{ + Creds: creds, SecretClient: secretClient, Scheme: scheme, } } // GetDB retrieves a database -func (s *MySqlUserManager) GetDB(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (db mysql.Database, err error) { - dbClient := mysqldatabase.GetMySQLDatabasesClient() +func (m *MySqlUserManager) GetDB(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (db mysql.Database, err error) { + dbClient := mysqldatabase.GetMySQLDatabasesClient(m.Creds) return dbClient.Get( ctx, resourceGroupName, @@ -60,7 +62,7 @@ func (s *MySqlUserManager) GetDB(ctx context.Context, resourceGroupName string, } // ConnectToSqlDb connects to the SQL db using the given credentials -func (s *MySqlUserManager) ConnectToSqlDb(ctx context.Context, drivername string, fullserver string, database string, port int, user string, password string) (*sql.DB, error) { +func (m *MySqlUserManager) ConnectToSqlDb(ctx context.Context, drivername string, fullserver string, database string, port int, user string, password string) (*sql.DB, error) { connString := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?tls=skip-verify&interpolateParams=true", user, password, fullserver, port, database) @@ -78,7 +80,7 @@ func (s *MySqlUserManager) ConnectToSqlDb(ctx context.Context, drivername string } // GrantUserRoles grants roles to a user for a given database -func (s *MySqlUserManager) GrantUserRoles(ctx context.Context, user string, database string, roles []string, db *sql.DB) error { +func (m *MySqlUserManager) GrantUserRoles(ctx context.Context, user string, database string, roles []string, db *sql.DB) error { var errorStrings []string if err := helpers.FindBadChars(user); err != nil { return fmt.Errorf("Problem found with username: %v", err) @@ -104,7 +106,7 @@ func (s *MySqlUserManager) GrantUserRoles(ctx context.Context, user string, data } // CreateUser creates user with secret credentials -func (s *MySqlUserManager) CreateUser(ctx context.Context, secret map[string][]byte, db *sql.DB) (string, error) { +func (m *MySqlUserManager) CreateUser(ctx context.Context, secret map[string][]byte, db *sql.DB) (string, error) { newUser := string(secret[MSecretUsernameKey]) newPassword := string(secret[MSecretPasswordKey]) @@ -125,7 +127,7 @@ func (s *MySqlUserManager) CreateUser(ctx context.Context, secret map[string][]b } // UserExists checks if db contains user -func (s *MySqlUserManager) UserExists(ctx context.Context, db *sql.DB, username string) (bool, error) { +func (m *MySqlUserManager) UserExists(ctx context.Context, db *sql.DB, username string) (bool, error) { err := db.QueryRowContext(ctx, "SELECT * FROM mysql.user WHERE User = $1", username) //err := db.ExecContext(ctx, tsql) @@ -138,7 +140,7 @@ func (s *MySqlUserManager) UserExists(ctx context.Context, db *sql.DB, username } // DropUser drops a user from db -func (s *MySqlUserManager) DropUser(ctx context.Context, db *sql.DB, user string) error { +func (m *MySqlUserManager) DropUser(ctx context.Context, db *sql.DB, user string) error { if err := helpers.FindBadChars(user); err != nil { return fmt.Errorf("Problem found with username: %v", err) @@ -148,7 +150,7 @@ func (s *MySqlUserManager) DropUser(ctx context.Context, db *sql.DB, user string } // DeleteSecrets deletes the secrets associated with a SQLUser -func (s *MySqlUserManager) DeleteSecrets(ctx context.Context, instance *v1alpha1.MySQLUser, secretClient secrets.SecretClient) (bool, error) { +func (m *MySqlUserManager) DeleteSecrets(ctx context.Context, instance *v1alpha1.MySQLUser, secretClient secrets.SecretClient) (bool, error) { // determine our key namespace - if we're persisting to kube, we should use the actual instance namespace. // In keyvault we have some creative freedom to allow more flexibility secretKey := GetNamespacedName(instance, secretClient) @@ -167,7 +169,7 @@ func (s *MySqlUserManager) DeleteSecrets(ctx context.Context, instance *v1alpha1 } // GetOrPrepareSecret gets or creates a secret -func (s *MySqlUserManager) GetOrPrepareSecret(ctx context.Context, instance *v1alpha1.MySQLUser, secretClient secrets.SecretClient) map[string][]byte { +func (m *MySqlUserManager) GetOrPrepareSecret(ctx context.Context, instance *v1alpha1.MySQLUser, secretClient secrets.SecretClient) map[string][]byte { key := GetNamespacedName(instance, secretClient) mysqldbdnssuffix := "mysql.database.azure.com" diff --git a/pkg/resourcemanager/mysql/mysqluser/mysqluser_reconcile.go b/pkg/resourcemanager/mysql/mysqluser/mysqluser_reconcile.go index a08ed0ab75a..4c9146626ce 100644 --- a/pkg/resourcemanager/mysql/mysqluser/mysqluser_reconcile.go +++ b/pkg/resourcemanager/mysql/mysqluser/mysqluser_reconcile.go @@ -57,9 +57,9 @@ func (s *MySqlUserManager) Ensure(ctx context.Context, obj runtime.Object, opts mysqlUserSecretClient = s.SecretClient } - // if the admin secret keyvault is not specified, fall back to global secretclient + // if the admin secret keyvault is not specified, fall back to configured secretclient if len(instance.Spec.AdminSecretKeyVault) != 0 { - adminSecretClient = keyvaultSecrets.New(instance.Spec.AdminSecretKeyVault) + adminSecretClient = keyvaultSecrets.New(instance.Spec.AdminSecretKeyVault, s.Creds) if len(instance.Spec.AdminSecret) != 0 { key = types.NamespacedName{Name: instance.Spec.AdminSecret} } @@ -204,9 +204,9 @@ func (s *MySqlUserManager) Delete(ctx context.Context, obj runtime.Object, opts mysqlUserSecretClient = s.SecretClient } - // if the admin secret keyvault is not specified, fall back to global secretclient + // if the admin secret keyvault is not specified, fall back to configured secretclient if len(instance.Spec.AdminSecretKeyVault) != 0 { - adminSecretClient = keyvaultSecrets.New(instance.Spec.AdminSecretKeyVault) + adminSecretClient = keyvaultSecrets.New(instance.Spec.AdminSecretKeyVault, s.Creds) if len(instance.Spec.AdminSecret) != 0 { key = types.NamespacedName{Name: instance.Spec.AdminSecret} } diff --git a/pkg/resourcemanager/mysql/server/client.go b/pkg/resourcemanager/mysql/server/client.go index f32e147bc73..4ea6255c0fb 100644 --- a/pkg/resourcemanager/mysql/server/client.go +++ b/pkg/resourcemanager/mysql/server/client.go @@ -16,28 +16,30 @@ import ( ) type MySQLServerClient struct { + Creds config.Credentials SecretClient secrets.SecretClient Scheme *runtime.Scheme } -func NewMySQLServerClient(secretclient secrets.SecretClient, scheme *runtime.Scheme) *MySQLServerClient { +func NewMySQLServerClient(creds config.Credentials, secretclient secrets.SecretClient, scheme *runtime.Scheme) *MySQLServerClient { return &MySQLServerClient{ + Creds: creds, SecretClient: secretclient, Scheme: scheme, } } -func getMySQLServersClient() mysql.ServersClient { - serversClient := mysql.NewServersClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, _ := iam.GetResourceManagementAuthorizer() +func getMySQLServersClient(creds config.Credentials) mysql.ServersClient { + serversClient := mysql.NewServersClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, _ := iam.GetResourceManagementAuthorizer(creds) serversClient.Authorizer = a serversClient.AddToUserAgent(config.UserAgent()) return serversClient } -func getMySQLCheckNameAvailabilityClient() mysql.CheckNameAvailabilityClient { - nameavailabilityClient := mysql.NewCheckNameAvailabilityClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, _ := iam.GetResourceManagementAuthorizer() +func getMySQLCheckNameAvailabilityClient(creds config.Credentials) mysql.CheckNameAvailabilityClient { + nameavailabilityClient := mysql.NewCheckNameAvailabilityClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, _ := iam.GetResourceManagementAuthorizer(creds) nameavailabilityClient.Authorizer = a nameavailabilityClient.AddToUserAgent(config.UserAgent()) return nameavailabilityClient @@ -45,7 +47,7 @@ func getMySQLCheckNameAvailabilityClient() mysql.CheckNameAvailabilityClient { func (m *MySQLServerClient) CheckServerNameAvailability(ctx context.Context, servername string) (bool, error) { - client := getMySQLCheckNameAvailabilityClient() + client := getMySQLCheckNameAvailabilityClient(m.Creds) resourceType := "Microsoft.DBforMySQL/servers" @@ -63,7 +65,7 @@ func (m *MySQLServerClient) CheckServerNameAvailability(ctx context.Context, ser func (m *MySQLServerClient) CreateServerIfValid(ctx context.Context, instance v1alpha2.MySQLServer, tags map[string]*string, skuInfo mysql.Sku, adminlogin string, adminpassword string, createmode mysql.CreateMode, hash string) (pollingURL string, server mysql.Server, err error) { - client := getMySQLServersClient() + client := getMySQLServersClient(m.Creds) // Check if name is valid if this is the first create call valid, err := m.CheckServerNameAvailability(ctx, instance.Name) @@ -146,7 +148,7 @@ func (m *MySQLServerClient) CreateServerIfValid(ctx context.Context, instance v1 func (m *MySQLServerClient) DeleteServer(ctx context.Context, resourcegroup string, servername string) (status string, err error) { - client := getMySQLServersClient() + client := getMySQLServersClient(m.Creds) _, err = client.Get(ctx, resourcegroup, servername) if err == nil { // Server present, so go ahead and delete @@ -160,6 +162,6 @@ func (m *MySQLServerClient) DeleteServer(ctx context.Context, resourcegroup stri func (m *MySQLServerClient) GetServer(ctx context.Context, resourcegroup string, servername string) (server mysql.Server, err error) { - client := getMySQLServersClient() + client := getMySQLServersClient(m.Creds) return client.Get(ctx, resourcegroup, servername) } diff --git a/pkg/resourcemanager/mysql/server/reconcile.go b/pkg/resourcemanager/mysql/server/reconcile.go index 620d02c161a..73af944eb82 100644 --- a/pkg/resourcemanager/mysql/server/reconcile.go +++ b/pkg/resourcemanager/mysql/server/reconcile.go @@ -82,7 +82,7 @@ func (m *MySQLServerClient) Ensure(ctx context.Context, obj runtime.Object, opts if err != nil { // handle failures in the async operation if instance.Status.PollingURL != "" { - pClient := pollclient.NewPollClient() + pClient := pollclient.NewPollClient(m.Creds) res, err := pClient.Get(ctx, instance.Status.PollingURL) if err != nil { instance.Status.Provisioning = false diff --git a/pkg/resourcemanager/mysql/vnetrule/client.go b/pkg/resourcemanager/mysql/vnetrule/client.go index e654660c836..e5ab87f88b8 100644 --- a/pkg/resourcemanager/mysql/vnetrule/client.go +++ b/pkg/resourcemanager/mysql/vnetrule/client.go @@ -13,32 +13,33 @@ import ( ) type MySQLVNetRuleClient struct { + creds config.Credentials } -func NewMySQLVNetRuleClient() *MySQLVNetRuleClient { - return &MySQLVNetRuleClient{} +func NewMySQLVNetRuleClient(creds config.Credentials) *MySQLVNetRuleClient { + return &MySQLVNetRuleClient{creds: creds} } -func getMySQLVNetRulesClient() mysql.VirtualNetworkRulesClient { - VNetRulesClient := mysql.NewVirtualNetworkRulesClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, _ := iam.GetResourceManagementAuthorizer() +func getMySQLVNetRulesClient(creds config.Credentials) mysql.VirtualNetworkRulesClient { + VNetRulesClient := mysql.NewVirtualNetworkRulesClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, _ := iam.GetResourceManagementAuthorizer(creds) VNetRulesClient.Authorizer = a VNetRulesClient.AddToUserAgent(config.UserAgent()) return VNetRulesClient } // GetNetworkSubnetClient retrieves a Subnetclient -func GetGoNetworkSubnetClient() network.SubnetsClient { - SubnetsClient := network.NewSubnetsClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, _ := iam.GetResourceManagementAuthorizer() +func GetGoNetworkSubnetClient(creds config.Credentials) network.SubnetsClient { + SubnetsClient := network.NewSubnetsClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, _ := iam.GetResourceManagementAuthorizer(creds) SubnetsClient.Authorizer = a SubnetsClient.AddToUserAgent(config.UserAgent()) return SubnetsClient } // GetSQLVNetRule returns a VNet rule -func (vr *MySQLVNetRuleClient) GetSQLVNetRule(ctx context.Context, resourceGroupName string, serverName string, ruleName string) (result mysql.VirtualNetworkRule, err error) { - VNetRulesClient := getMySQLVNetRulesClient() +func (c *MySQLVNetRuleClient) GetSQLVNetRule(ctx context.Context, resourceGroupName string, serverName string, ruleName string) (result mysql.VirtualNetworkRule, err error) { + VNetRulesClient := getMySQLVNetRulesClient(c.creds) return VNetRulesClient.Get( ctx, @@ -49,15 +50,15 @@ func (vr *MySQLVNetRuleClient) GetSQLVNetRule(ctx context.Context, resourceGroup } // DeleteSQLVNetRule deletes a VNet rule -func (vr *MySQLVNetRuleClient) DeleteSQLVNetRule(ctx context.Context, resourceGroupName string, serverName string, ruleName string) (err error) { +func (c *MySQLVNetRuleClient) DeleteSQLVNetRule(ctx context.Context, resourceGroupName string, serverName string, ruleName string) (err error) { // check to see if the rule exists, if it doesn't then short-circuit - _, err = vr.GetSQLVNetRule(ctx, resourceGroupName, serverName, ruleName) + _, err = c.GetSQLVNetRule(ctx, resourceGroupName, serverName, ruleName) if err != nil { return nil } - VNetRulesClient := getMySQLVNetRulesClient() + VNetRulesClient := getMySQLVNetRulesClient(c.creds) _, err = VNetRulesClient.Delete( ctx, resourceGroupName, @@ -70,10 +71,10 @@ func (vr *MySQLVNetRuleClient) DeleteSQLVNetRule(ctx context.Context, resourceGr // CreateOrUpdateSQLVNetRule creates or updates a VNet rule // based on code from: https://godoc.org/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/v3.0/sql#VirtualNetworkRulesClient.CreateOrUpdate -func (vr *MySQLVNetRuleClient) CreateOrUpdateSQLVNetRule(ctx context.Context, resourceGroupName string, serverName string, ruleName string, VNetRG string, VNetName string, SubnetName string, IgnoreServiceEndpoint bool) (vnr mysql.VirtualNetworkRule, err error) { +func (c *MySQLVNetRuleClient) CreateOrUpdateSQLVNetRule(ctx context.Context, resourceGroupName string, serverName string, ruleName string, VNetRG string, VNetName string, SubnetName string, IgnoreServiceEndpoint bool) (vnr mysql.VirtualNetworkRule, err error) { - VNetRulesClient := getMySQLVNetRulesClient() - SubnetClient := GetGoNetworkSubnetClient() + VNetRulesClient := getMySQLVNetRulesClient(c.creds) + SubnetClient := GetGoNetworkSubnetClient(c.creds) // Get ARM Resource ID of Subnet based on the VNET name, Subnet name and Subnet Address Prefix subnet, err := SubnetClient.Get(ctx, VNetRG, VNetName, SubnetName, "") diff --git a/pkg/resourcemanager/nic/client.go b/pkg/resourcemanager/nic/client.go index e83bf91a63d..f9c43388214 100644 --- a/pkg/resourcemanager/nic/client.go +++ b/pkg/resourcemanager/nic/client.go @@ -15,20 +15,22 @@ import ( ) type AzureNetworkInterfaceClient struct { + Creds config.Credentials SecretClient secrets.SecretClient Scheme *runtime.Scheme } -func NewAzureNetworkInterfaceClient(secretclient secrets.SecretClient, scheme *runtime.Scheme) *AzureNetworkInterfaceClient { +func NewAzureNetworkInterfaceClient(creds config.Credentials, secretclient secrets.SecretClient, scheme *runtime.Scheme) *AzureNetworkInterfaceClient { return &AzureNetworkInterfaceClient{ + Creds: creds, SecretClient: secretclient, Scheme: scheme, } } -func getNetworkInterfaceClient() vnetwork.InterfacesClient { - nicClient := vnetwork.NewInterfacesClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, _ := iam.GetResourceManagementAuthorizer() +func getNetworkInterfaceClient(creds config.Credentials) vnetwork.InterfacesClient { + nicClient := vnetwork.NewInterfacesClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, _ := iam.GetResourceManagementAuthorizer(creds) nicClient.Authorizer = a nicClient.AddToUserAgent(config.UserAgent()) return nicClient @@ -36,7 +38,7 @@ func getNetworkInterfaceClient() vnetwork.InterfacesClient { func (m *AzureNetworkInterfaceClient) CreateNetworkInterface(ctx context.Context, location string, resourceGroupName string, resourceName string, vnetName string, subnetName string, publicIPAddressName string) (future vnetwork.InterfacesCreateOrUpdateFuture, err error) { - client := getNetworkInterfaceClient() + client := getNetworkInterfaceClient(m.Creds) subnetIDInput := helpers.MakeResourceID( client.SubscriptionID, @@ -91,7 +93,7 @@ func (m *AzureNetworkInterfaceClient) CreateNetworkInterface(ctx context.Context func (m *AzureNetworkInterfaceClient) DeleteNetworkInterface(ctx context.Context, nicName string, resourcegroup string) (status string, err error) { - client := getNetworkInterfaceClient() + client := getNetworkInterfaceClient(m.Creds) _, err = client.Get(ctx, resourcegroup, nicName, "") if err == nil { // nic present, so go ahead and delete @@ -105,7 +107,7 @@ func (m *AzureNetworkInterfaceClient) DeleteNetworkInterface(ctx context.Context func (m *AzureNetworkInterfaceClient) GetNetworkInterface(ctx context.Context, resourcegroup string, nicName string) (nic vnetwork.Interface, err error) { - client := getNetworkInterfaceClient() + client := getNetworkInterfaceClient(m.Creds) return client.Get(ctx, resourcegroup, nicName, "") } diff --git a/pkg/resourcemanager/nic/reconcile.go b/pkg/resourcemanager/nic/reconcile.go index 6389b25d2a3..773f3c743dd 100644 --- a/pkg/resourcemanager/nic/reconcile.go +++ b/pkg/resourcemanager/nic/reconcile.go @@ -15,14 +15,14 @@ import ( "k8s.io/apimachinery/pkg/types" ) -func (g *AzureNetworkInterfaceClient) Ensure(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) { +func (m *AzureNetworkInterfaceClient) Ensure(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) { - instance, err := g.convert(obj) + instance, err := m.convert(obj) if err != nil { return true, err } - client := getNetworkInterfaceClient() + client := getNetworkInterfaceClient(m.Creds) location := instance.Spec.Location resourceGroup := instance.Spec.ResourceGroup @@ -34,7 +34,7 @@ func (g *AzureNetworkInterfaceClient) Ensure(ctx context.Context, obj runtime.Ob instance.Status.Provisioning = true // Check if this item already exists. This is required // to overcome the issue with the lack of idempotence of the Create call - item, err := g.GetNetworkInterface(ctx, resourceGroup, resourceName) + item, err := m.GetNetworkInterface(ctx, resourceGroup, resourceName) if err == nil { instance.Status.Provisioned = true instance.Status.Provisioning = false @@ -42,7 +42,7 @@ func (g *AzureNetworkInterfaceClient) Ensure(ctx context.Context, obj runtime.Ob instance.Status.ResourceId = *item.ID return true, nil } - future, err := g.CreateNetworkInterface( + future, err := m.CreateNetworkInterface( ctx, location, resourceGroup, diff --git a/pkg/resourcemanager/pip/client.go b/pkg/resourcemanager/pip/client.go index 4986533bce0..207d3fc0e24 100644 --- a/pkg/resourcemanager/pip/client.go +++ b/pkg/resourcemanager/pip/client.go @@ -15,20 +15,22 @@ import ( ) type AzurePublicIPAddressClient struct { + Creds config.Credentials SecretClient secrets.SecretClient Scheme *runtime.Scheme } -func NewAzurePublicIPAddressClient(secretclient secrets.SecretClient, scheme *runtime.Scheme) *AzurePublicIPAddressClient { +func NewAzurePublicIPAddressClient(creds config.Credentials, secretclient secrets.SecretClient, scheme *runtime.Scheme) *AzurePublicIPAddressClient { return &AzurePublicIPAddressClient{ + Creds: creds, SecretClient: secretclient, Scheme: scheme, } } -func getPublicIPAddressClient() vnetwork.PublicIPAddressesClient { - pipClient := vnetwork.NewPublicIPAddressesClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, _ := iam.GetResourceManagementAuthorizer() +func getPublicIPAddressClient(creds config.Credentials) vnetwork.PublicIPAddressesClient { + pipClient := vnetwork.NewPublicIPAddressesClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, _ := iam.GetResourceManagementAuthorizer(creds) pipClient.Authorizer = a pipClient.AddToUserAgent(config.UserAgent()) return pipClient @@ -44,7 +46,7 @@ func (m *AzurePublicIPAddressClient) CreatePublicIPAddress(ctx context.Context, skuName string, ipTags map[string]string) (future vnetwork.PublicIPAddressesCreateOrUpdateFuture, err error) { - client := getPublicIPAddressClient() + client := getPublicIPAddressClient(m.Creds) publicIPAllocationMethodField := vnetwork.Static if publicIPAllocationMethod == string(vnetwork.Dynamic) { @@ -98,7 +100,7 @@ func getIPTagsForPublicIP(tags map[string]string) *[]vnetwork.IPTag { func (m *AzurePublicIPAddressClient) DeletePublicIPAddress(ctx context.Context, publicIPAddressName string, resourcegroup string) (status string, err error) { - client := getPublicIPAddressClient() + client := getPublicIPAddressClient(m.Creds) _, err = client.Get(ctx, resourcegroup, publicIPAddressName, "") if err == nil { // pip present, so go ahead and delete @@ -112,7 +114,7 @@ func (m *AzurePublicIPAddressClient) DeletePublicIPAddress(ctx context.Context, func (m *AzurePublicIPAddressClient) GetPublicIPAddress(ctx context.Context, resourcegroup string, publicIPAddressName string) (pip network.PublicIPAddress, err error) { - client := getPublicIPAddressClient() + client := getPublicIPAddressClient(m.Creds) return client.Get(ctx, resourcegroup, publicIPAddressName, "") } diff --git a/pkg/resourcemanager/pip/reconcile.go b/pkg/resourcemanager/pip/reconcile.go index 5a43cc32e5b..4d7865694ac 100644 --- a/pkg/resourcemanager/pip/reconcile.go +++ b/pkg/resourcemanager/pip/reconcile.go @@ -15,13 +15,13 @@ import ( "k8s.io/apimachinery/pkg/types" ) -func (g *AzurePublicIPAddressClient) Ensure(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) { - instance, err := g.convert(obj) +func (m *AzurePublicIPAddressClient) Ensure(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) { + instance, err := m.convert(obj) if err != nil { return true, err } - client := getPublicIPAddressClient() + client := getPublicIPAddressClient(m.Creds) location := instance.Spec.Location resourceGroup := instance.Spec.ResourceGroup @@ -35,7 +35,7 @@ func (g *AzurePublicIPAddressClient) Ensure(ctx context.Context, obj runtime.Obj instance.Status.Provisioning = true // Check if this item already exists. This is required // to overcome the issue with the lack of idempotence of the Create call - item, err := g.GetPublicIPAddress(ctx, resourceGroup, resourceName) + item, err := m.GetPublicIPAddress(ctx, resourceGroup, resourceName) if err == nil { instance.Status.Provisioned = true instance.Status.Provisioning = false @@ -43,7 +43,7 @@ func (g *AzurePublicIPAddressClient) Ensure(ctx context.Context, obj runtime.Obj instance.Status.ResourceId = *item.ID return true, nil } - future, err := g.CreatePublicIPAddress( + future, err := m.CreatePublicIPAddress( ctx, location, resourceGroup, diff --git a/pkg/resourcemanager/pollclient/pollclient.go b/pkg/resourcemanager/pollclient/pollclient.go index a4e337b1718..2555465f6ff 100644 --- a/pkg/resourcemanager/pollclient/pollclient.go +++ b/pkg/resourcemanager/pollclient/pollclient.go @@ -35,14 +35,14 @@ type PollClient struct { } // NewPollClient returns a client using hte env values from config -func NewPollClient() PollClient { - return NewPollClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) +func NewPollClient(creds config.Credentials) PollClient { + return NewPollClientWithBaseURI(config.BaseURI(), creds) } // NewPollClientWithBaseURI returns a paramterized client -func NewPollClientWithBaseURI(baseURI string, subscriptionID string) PollClient { - c := PollClient{NewWithBaseURI(baseURI, subscriptionID)} - a, _ := iam.GetResourceManagementAuthorizer() +func NewPollClientWithBaseURI(baseURI string, creds config.Credentials) PollClient { + c := PollClient{NewWithBaseURI(baseURI, creds.SubscriptionID())} + a, _ := iam.GetResourceManagementAuthorizer(creds) c.Authorizer = a c.AddToUserAgent(config.UserAgent()) return c diff --git a/pkg/resourcemanager/psql/database/database.go b/pkg/resourcemanager/psql/database/database.go index 18c686f7754..512fb5ca391 100644 --- a/pkg/resourcemanager/psql/database/database.go +++ b/pkg/resourcemanager/psql/database/database.go @@ -13,16 +13,17 @@ import ( ) type PSQLDatabaseClient struct { + creds config.Credentials } -func NewPSQLDatabaseClient() *PSQLDatabaseClient { - return &PSQLDatabaseClient{} +func NewPSQLDatabaseClient(creds config.Credentials) *PSQLDatabaseClient { + return &PSQLDatabaseClient{creds: creds} } //GetPSQLDatabasesClient retrieves the psqldabase -func GetPSQLDatabasesClient() (psql.DatabasesClient, error) { - databasesClient := psql.NewDatabasesClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, err := iam.GetResourceManagementAuthorizer() +func GetPSQLDatabasesClient(creds config.Credentials) (psql.DatabasesClient, error) { + databasesClient := psql.NewDatabasesClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, err := iam.GetResourceManagementAuthorizer(creds) if err != nil { return psql.DatabasesClient{}, err } @@ -31,9 +32,9 @@ func GetPSQLDatabasesClient() (psql.DatabasesClient, error) { return databasesClient, err } -func getPSQLCheckNameAvailabilityClient() (psql.CheckNameAvailabilityClient, error) { - nameavailabilityClient := psql.NewCheckNameAvailabilityClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, err := iam.GetResourceManagementAuthorizer() +func getPSQLCheckNameAvailabilityClient(creds config.Credentials) (psql.CheckNameAvailabilityClient, error) { + nameavailabilityClient := psql.NewCheckNameAvailabilityClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, err := iam.GetResourceManagementAuthorizer(creds) if err != nil { return psql.CheckNameAvailabilityClient{}, err } @@ -42,9 +43,9 @@ func getPSQLCheckNameAvailabilityClient() (psql.CheckNameAvailabilityClient, err return nameavailabilityClient, err } -func (p *PSQLDatabaseClient) CheckDatabaseNameAvailability(ctx context.Context, databasename string) (bool, error) { +func (c *PSQLDatabaseClient) CheckDatabaseNameAvailability(ctx context.Context, databasename string) (bool, error) { - client, err := getPSQLCheckNameAvailabilityClient() + client, err := getPSQLCheckNameAvailabilityClient(c.creds) if err != nil { return false, err } @@ -63,9 +64,9 @@ func (p *PSQLDatabaseClient) CheckDatabaseNameAvailability(ctx context.Context, } -func (p *PSQLDatabaseClient) CreateDatabaseIfValid(ctx context.Context, databasename string, servername string, resourcegroup string) (*http.Response, error) { +func (c *PSQLDatabaseClient) CreateDatabaseIfValid(ctx context.Context, databasename string, servername string, resourcegroup string) (*http.Response, error) { - client, err := GetPSQLDatabasesClient() + client, err := GetPSQLDatabasesClient(c.creds) if err != nil { return &http.Response{ StatusCode: 500, @@ -73,7 +74,7 @@ func (p *PSQLDatabaseClient) CreateDatabaseIfValid(ctx context.Context, database } // Check if name is valid if this is the first create call - valid, err := p.CheckDatabaseNameAvailability(ctx, databasename) + valid, err := c.CheckDatabaseNameAvailability(ctx, databasename) if valid == false { return &http.Response{ StatusCode: 500, @@ -98,9 +99,9 @@ func (p *PSQLDatabaseClient) CreateDatabaseIfValid(ctx context.Context, database return future.GetResult(client) } -func (p *PSQLDatabaseClient) DeleteDatabase(ctx context.Context, databasename string, servername string, resourcegroup string) (status string, err error) { +func (c *PSQLDatabaseClient) DeleteDatabase(ctx context.Context, databasename string, servername string, resourcegroup string) (status string, err error) { - client, err := GetPSQLDatabasesClient() + client, err := GetPSQLDatabasesClient(c.creds) if err != nil { return "", err } @@ -115,9 +116,9 @@ func (p *PSQLDatabaseClient) DeleteDatabase(ctx context.Context, databasename st return "db not present", nil } -func (p *PSQLDatabaseClient) GetDatabase(ctx context.Context, resourcegroup string, servername string, databasename string) (db psql.Database, err error) { +func (c *PSQLDatabaseClient) GetDatabase(ctx context.Context, resourcegroup string, servername string, databasename string) (db psql.Database, err error) { - client, err := GetPSQLDatabasesClient() + client, err := GetPSQLDatabasesClient(c.creds) if err != nil { return psql.Database{}, err } diff --git a/pkg/resourcemanager/psql/firewallrule/firewallrule.go b/pkg/resourcemanager/psql/firewallrule/firewallrule.go index bddd1e9e68f..ff08d54374b 100644 --- a/pkg/resourcemanager/psql/firewallrule/firewallrule.go +++ b/pkg/resourcemanager/psql/firewallrule/firewallrule.go @@ -14,15 +14,16 @@ import ( ) type PSQLFirewallRuleClient struct { + creds config.Credentials } -func NewPSQLFirewallRuleClient() *PSQLFirewallRuleClient { - return &PSQLFirewallRuleClient{} +func NewPSQLFirewallRuleClient(creds config.Credentials) *PSQLFirewallRuleClient { + return &PSQLFirewallRuleClient{creds: creds} } -func getPSQLFirewallRulesClient() (psql.FirewallRulesClient, error) { - firewallRulesClient := psql.NewFirewallRulesClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, err := iam.GetResourceManagementAuthorizer() +func getPSQLFirewallRulesClient(creds config.Credentials) (psql.FirewallRulesClient, error) { + firewallRulesClient := psql.NewFirewallRulesClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, err := iam.GetResourceManagementAuthorizer(creds) if err != nil { return psql.FirewallRulesClient{}, err } @@ -31,9 +32,9 @@ func getPSQLFirewallRulesClient() (psql.FirewallRulesClient, error) { return firewallRulesClient, err } -func (p *PSQLFirewallRuleClient) CreateFirewallRule(ctx context.Context, resourcegroup string, servername string, firewallrulename string, startip string, endip string) (*http.Response, error) { +func (c *PSQLFirewallRuleClient) CreateFirewallRule(ctx context.Context, resourcegroup string, servername string, firewallrulename string, startip string, endip string) (*http.Response, error) { - client, err := getPSQLFirewallRulesClient() + client, err := getPSQLFirewallRulesClient(c.creds) if err != nil { return &http.Response{ StatusCode: 500, @@ -63,9 +64,9 @@ func (p *PSQLFirewallRuleClient) CreateFirewallRule(ctx context.Context, resourc return future.GetResult(client) } -func (p *PSQLFirewallRuleClient) DeleteFirewallRule(ctx context.Context, resourcegroup string, servername string, firewallrulename string) (status string, err error) { +func (c *PSQLFirewallRuleClient) DeleteFirewallRule(ctx context.Context, resourcegroup string, servername string, firewallrulename string) (status string, err error) { - client, err := getPSQLFirewallRulesClient() + client, err := getPSQLFirewallRulesClient(c.creds) if err != nil { return "", err } @@ -80,9 +81,9 @@ func (p *PSQLFirewallRuleClient) DeleteFirewallRule(ctx context.Context, resourc return "Firewall Rule not present", nil } -func (p *PSQLFirewallRuleClient) GetFirewallRule(ctx context.Context, resourcegroup string, servername string, firewallrulename string) (firewall psql.FirewallRule, err error) { +func (c *PSQLFirewallRuleClient) GetFirewallRule(ctx context.Context, resourcegroup string, servername string, firewallrulename string) (firewall psql.FirewallRule, err error) { - client, err := getPSQLFirewallRulesClient() + client, err := getPSQLFirewallRulesClient(c.creds) if err != nil { return psql.FirewallRule{}, err } diff --git a/pkg/resourcemanager/psql/psqluser/psqluser.go b/pkg/resourcemanager/psql/psqluser/psqluser.go index 8a173f0efa7..491b2172a42 100644 --- a/pkg/resourcemanager/psql/psqluser/psqluser.go +++ b/pkg/resourcemanager/psql/psqluser/psqluser.go @@ -36,21 +36,23 @@ const PSecretPasswordKey = "password" //PostgreSqlUserManager for psqluser manager type PostgreSqlUserManager struct { + Creds config.Credentials SecretClient secrets.SecretClient Scheme *runtime.Scheme } //NewPostgreSqlUserManager creates a new PostgreSqlUserManager -func NewPostgreSqlUserManager(secretClient secrets.SecretClient, scheme *runtime.Scheme) *PostgreSqlUserManager { +func NewPostgreSqlUserManager(creds config.Credentials, secretClient secrets.SecretClient, scheme *runtime.Scheme) *PostgreSqlUserManager { return &PostgreSqlUserManager{ + Creds: creds, SecretClient: secretClient, Scheme: scheme, } } // GetDB retrieves a database -func (s *PostgreSqlUserManager) GetDB(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (db psql.Database, err error) { - dbClient, err := psdatabase.GetPSQLDatabasesClient() +func (m *PostgreSqlUserManager) GetDB(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (db psql.Database, err error) { + dbClient, err := psdatabase.GetPSQLDatabasesClient(m.Creds) if err != nil { return psql.Database{}, err } @@ -64,7 +66,7 @@ func (s *PostgreSqlUserManager) GetDB(ctx context.Context, resourceGroupName str } // ConnectToSqlDb connects to the PostgreSQL db using the given credentials -func (s *PostgreSqlUserManager) ConnectToSqlDb(ctx context.Context, drivername string, fullservername string, database string, port int, user string, password string) (*sql.DB, error) { +func (m *PostgreSqlUserManager) ConnectToSqlDb(ctx context.Context, drivername string, fullservername string, database string, port int, user string, password string) (*sql.DB, error) { connString := fmt.Sprintf("host=%s user=%s password=%s port=%d dbname=%s sslmode=require connect_timeout=30", fullservername, user, password, port, database) @@ -82,7 +84,7 @@ func (s *PostgreSqlUserManager) ConnectToSqlDb(ctx context.Context, drivername s } // GrantUserRoles grants roles to a user for a given database -func (s *PostgreSqlUserManager) GrantUserRoles(ctx context.Context, user string, roles []string, db *sql.DB) error { +func (m *PostgreSqlUserManager) GrantUserRoles(ctx context.Context, user string, roles []string, db *sql.DB) error { var errorStrings []string if err := helpers.FindBadChars(user); err != nil { @@ -109,7 +111,7 @@ func (s *PostgreSqlUserManager) GrantUserRoles(ctx context.Context, user string, } // CreateUser creates user with secret credentials -func (s *PostgreSqlUserManager) CreateUser(ctx context.Context, secret map[string][]byte, db *sql.DB) (string, error) { +func (m *PostgreSqlUserManager) CreateUser(ctx context.Context, secret map[string][]byte, db *sql.DB) (string, error) { newUser := string(secret[PSecretUsernameKey]) newPassword := string(secret[PSecretPasswordKey]) @@ -131,7 +133,7 @@ func (s *PostgreSqlUserManager) CreateUser(ctx context.Context, secret map[strin } // UpdateUser - Updates user password -func (s *PostgreSqlUserManager) UpdateUser(ctx context.Context, secret map[string][]byte, db *sql.DB) error { +func (m *PostgreSqlUserManager) UpdateUser(ctx context.Context, secret map[string][]byte, db *sql.DB) error { user := string(secret[PSecretUsernameKey]) newPassword := helpers.NewPassword() @@ -150,7 +152,7 @@ func (s *PostgreSqlUserManager) UpdateUser(ctx context.Context, secret map[strin } // UserExists checks if db contains user -func (s *PostgreSqlUserManager) UserExists(ctx context.Context, db *sql.DB, username string) (bool, error) { +func (m *PostgreSqlUserManager) UserExists(ctx context.Context, db *sql.DB, username string) (bool, error) { res, err := db.ExecContext(ctx, "SELECT * FROM pg_user WHERE usename = $1", username) if err != nil { @@ -162,7 +164,7 @@ func (s *PostgreSqlUserManager) UserExists(ctx context.Context, db *sql.DB, user } // DropUser drops a user from db -func (s *PostgreSqlUserManager) DropUser(ctx context.Context, db *sql.DB, user string) error { +func (m *PostgreSqlUserManager) DropUser(ctx context.Context, db *sql.DB, user string) error { if err := helpers.FindBadChars(user); err != nil { return fmt.Errorf("Problem found with username: %v", err) } @@ -173,7 +175,7 @@ func (s *PostgreSqlUserManager) DropUser(ctx context.Context, db *sql.DB, user s } // DeleteSecrets deletes the secrets associated with a SQLUser -func (s *PostgreSqlUserManager) DeleteSecrets(ctx context.Context, instance *v1alpha1.PostgreSQLUser, secretClient secrets.SecretClient) (bool, error) { +func (m *PostgreSqlUserManager) DeleteSecrets(ctx context.Context, instance *v1alpha1.PostgreSQLUser, secretClient secrets.SecretClient) (bool, error) { secretKey := GetNamespacedName(instance, secretClient) @@ -191,7 +193,7 @@ func (s *PostgreSqlUserManager) DeleteSecrets(ctx context.Context, instance *v1a } // GetOrPrepareSecret gets or creates a secret -func (s *PostgreSqlUserManager) GetOrPrepareSecret(ctx context.Context, instance *v1alpha1.PostgreSQLUser, secretClient secrets.SecretClient) map[string][]byte { +func (m *PostgreSqlUserManager) GetOrPrepareSecret(ctx context.Context, instance *v1alpha1.PostgreSQLUser, secretClient secrets.SecretClient) map[string][]byte { key := GetNamespacedName(instance, secretClient) secret, err := secretClient.Get(ctx, key) diff --git a/pkg/resourcemanager/psql/psqluser/psqluser_reconcile.go b/pkg/resourcemanager/psql/psqluser/psqluser_reconcile.go index 4a81b0b2e00..466c87e3cee 100644 --- a/pkg/resourcemanager/psql/psqluser/psqluser_reconcile.go +++ b/pkg/resourcemanager/psql/psqluser/psqluser_reconcile.go @@ -25,8 +25,8 @@ import ( ) // Ensure that user exists -func (s *PostgreSqlUserManager) Ensure(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) { - instance, err := s.convert(obj) +func (m *PostgreSqlUserManager) Ensure(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) { + instance, err := m.convert(obj) if err != nil { return false, err } @@ -41,7 +41,7 @@ func (s *PostgreSqlUserManager) Ensure(ctx context.Context, obj runtime.Object, opt(options) } - adminSecretClient := s.SecretClient + adminSecretClient := m.SecretClient adminsecretName := instance.Spec.AdminSecret if len(instance.Spec.AdminSecret) == 0 { @@ -54,12 +54,12 @@ func (s *PostgreSqlUserManager) Ensure(ctx context.Context, obj runtime.Object, if options.SecretClient != nil { sqlUserSecretClient = options.SecretClient } else { - sqlUserSecretClient = s.SecretClient + sqlUserSecretClient = m.SecretClient } - // if the admin secret keyvault is not specified, fall back to global secretclient + // if the admin secret keyvault is not specified, fall back to configured secretclient if len(instance.Spec.AdminSecretKeyVault) != 0 { - adminSecretClient = keyvaultSecrets.New(instance.Spec.AdminSecretKeyVault) + adminSecretClient = keyvaultSecrets.New(instance.Spec.AdminSecretKeyVault, m.Creds) if len(instance.Spec.AdminSecret) != 0 { key = types.NamespacedName{Name: instance.Spec.AdminSecret} } @@ -76,7 +76,7 @@ func (s *PostgreSqlUserManager) Ensure(ctx context.Context, obj runtime.Object, adminUser := string(adminSecret["fullyQualifiedUsername"]) adminPassword := string(adminSecret[PSecretPasswordKey]) - _, err = s.GetDB(ctx, instance.Spec.ResourceGroup, instance.Spec.Server, instance.Spec.DbName) + _, err = m.GetDB(ctx, instance.Spec.ResourceGroup, instance.Spec.Server, instance.Spec.DbName) if err != nil { instance.Status.Message = errhelp.StripErrorIDs(err) instance.Status.Provisioning = false @@ -104,7 +104,7 @@ func (s *PostgreSqlUserManager) Ensure(ctx context.Context, obj runtime.Object, } fullServerName := string(adminSecret["fullyQualifiedServerName"]) - db, err := s.ConnectToSqlDb(ctx, PDriverName, fullServerName, instance.Spec.DbName, PSqlServerPort, adminUser, adminPassword) + db, err := m.ConnectToSqlDb(ctx, PDriverName, fullServerName, instance.Spec.DbName, PSqlServerPort, adminUser, adminPassword) if err != nil { instance.Status.Message = errhelp.StripErrorIDs(err) instance.Status.Provisioning = false @@ -129,7 +129,7 @@ func (s *PostgreSqlUserManager) Ensure(ctx context.Context, obj runtime.Object, key = GetNamespacedName(instance, sqlUserSecretClient) // create or get new user secret - DBSecret := s.GetOrPrepareSecret(ctx, instance, sqlUserSecretClient) + DBSecret := m.GetOrPrepareSecret(ctx, instance, sqlUserSecretClient) // reset user from secret in case it was loaded user := string(DBSecret[PSecretUsernameKey]) if user == "" { @@ -144,21 +144,21 @@ func (s *PostgreSqlUserManager) Ensure(ctx context.Context, obj runtime.Object, key, DBSecret, secrets.WithOwner(instance), - secrets.WithScheme(s.Scheme), + secrets.WithScheme(m.Scheme), ) if err != nil { instance.Status.Message = "failed to update secret, err: " + err.Error() return false, err } - userExists, err := s.UserExists(ctx, db, string(DBSecret[PSecretUsernameKey])) + userExists, err := m.UserExists(ctx, db, string(DBSecret[PSecretUsernameKey])) if err != nil { instance.Status.Message = fmt.Sprintf("failed checking for user, err: %v", err) return false, nil } if !userExists { - user, err = s.CreateUser(ctx, DBSecret, db) + user, err = m.CreateUser(ctx, DBSecret, db) if err != nil { instance.Status.Message = "failed creating user, err: " + err.Error() return false, err @@ -171,7 +171,7 @@ func (s *PostgreSqlUserManager) Ensure(ctx context.Context, obj runtime.Object, return false, fmt.Errorf("No roles specified for database user") } - err = s.GrantUserRoles(ctx, user, instance.Spec.Roles, db) + err = m.GrantUserRoles(ctx, user, instance.Spec.Roles, db) if err != nil { instance.Status.Message = "GrantUserRoles failed" return false, fmt.Errorf("GrantUserRoles failed") @@ -185,19 +185,19 @@ func (s *PostgreSqlUserManager) Ensure(ctx context.Context, obj runtime.Object, } // Delete deletes a user -func (s *PostgreSqlUserManager) Delete(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) { +func (m *PostgreSqlUserManager) Delete(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) { options := &resourcemanager.Options{} for _, opt := range opts { opt(options) } - instance, err := s.convert(obj) + instance, err := m.convert(obj) if err != nil { return false, err } - adminSecretClient := s.SecretClient + adminSecretClient := m.SecretClient adminsecretName := instance.Spec.AdminSecret @@ -206,9 +206,9 @@ func (s *PostgreSqlUserManager) Delete(ctx context.Context, obj runtime.Object, } key := types.NamespacedName{Name: adminsecretName, Namespace: instance.Namespace} - // if the admin secret keyvault is not specified, fall back to global secretclient + // if the admin secret keyvault is not specified, fall back to configured secretclient if len(instance.Spec.AdminSecretKeyVault) != 0 { - adminSecretClient = keyvaultSecrets.New(instance.Spec.AdminSecretKeyVault) + adminSecretClient = keyvaultSecrets.New(instance.Spec.AdminSecretKeyVault, m.Creds) if len(instance.Spec.AdminSecret) != 0 { key = types.NamespacedName{Name: instance.Spec.AdminSecret} } @@ -221,7 +221,7 @@ func (s *PostgreSqlUserManager) Delete(ctx context.Context, obj runtime.Object, } // short circuit connection if database doesn't exist - _, err = s.GetDB(ctx, instance.Spec.ResourceGroup, instance.Spec.Server, instance.Spec.DbName) + _, err = m.GetDB(ctx, instance.Spec.ResourceGroup, instance.Spec.Server, instance.Spec.DbName) if err != nil { instance.Status.Message = err.Error() @@ -241,7 +241,7 @@ func (s *PostgreSqlUserManager) Delete(ctx context.Context, obj runtime.Object, adminpassword := string(adminSecret[PSecretPasswordKey]) fullservername := string(adminSecret["fullyQualifiedServerName"]) - db, err := s.ConnectToSqlDb(ctx, PDriverName, fullservername, instance.Spec.DbName, PSqlServerPort, adminuser, adminpassword) + db, err := m.ConnectToSqlDb(ctx, PDriverName, fullservername, instance.Spec.DbName, PSqlServerPort, adminuser, adminpassword) if err != nil { instance.Status.Message = errhelp.StripErrorIDs(err) if strings.Contains(err.Error(), "no pg_hba.conf entry for host") { @@ -258,7 +258,7 @@ func (s *PostgreSqlUserManager) Delete(ctx context.Context, obj runtime.Object, if options.SecretClient != nil { psqlUserSecretClient = options.SecretClient } else { - psqlUserSecretClient = s.SecretClient + psqlUserSecretClient = m.SecretClient } userkey := GetNamespacedName(instance, psqlUserSecretClient) @@ -270,20 +270,20 @@ func (s *PostgreSqlUserManager) Delete(ctx context.Context, obj runtime.Object, user := string(userSecret[PSecretUsernameKey]) - exists, err := s.UserExists(ctx, db, user) + exists, err := m.UserExists(ctx, db, user) if err != nil { instance.Status.Message = fmt.Sprintf("Delete PostgreSqlUser failed with %s", err.Error()) return true, err } if !exists { - s.DeleteSecrets(ctx, instance, psqlUserSecretClient) + m.DeleteSecrets(ctx, instance, psqlUserSecretClient) instance.Status.Message = fmt.Sprintf("The user %s doesn't exist", user) //User doesn't exist. Stop the reconcile. return false, nil } - err = s.DropUser(ctx, db, user) + err = m.DropUser(ctx, db, user) if err != nil { instance.Status.Message = fmt.Sprintf("Delete PostgreSqlUser failed with %s", err.Error()) //stop the reconcile with err @@ -291,7 +291,7 @@ func (s *PostgreSqlUserManager) Delete(ctx context.Context, obj runtime.Object, } // Once the user has been dropped, also delete their secrets. - s.DeleteSecrets(ctx, instance, psqlUserSecretClient) + m.DeleteSecrets(ctx, instance, psqlUserSecretClient) instance.Status.Message = fmt.Sprintf("Delete PostgreSqlUser succeeded") @@ -300,8 +300,8 @@ func (s *PostgreSqlUserManager) Delete(ctx context.Context, obj runtime.Object, } // GetParents gets the parents of the user -func (s *PostgreSqlUserManager) GetParents(obj runtime.Object) ([]resourcemanager.KubeParent, error) { - instance, err := s.convert(obj) +func (m *PostgreSqlUserManager) GetParents(obj runtime.Object) ([]resourcemanager.KubeParent, error) { + instance, err := m.convert(obj) if err != nil { return nil, err } @@ -332,15 +332,15 @@ func (s *PostgreSqlUserManager) GetParents(obj runtime.Object) ([]resourcemanage } // GetStatus gets the status -func (s *PostgreSqlUserManager) GetStatus(obj runtime.Object) (*v1alpha1.ASOStatus, error) { - instance, err := s.convert(obj) +func (m *PostgreSqlUserManager) GetStatus(obj runtime.Object) (*v1alpha1.ASOStatus, error) { + instance, err := m.convert(obj) if err != nil { return nil, err } return &instance.Status, nil } -func (s *PostgreSqlUserManager) convert(obj runtime.Object) (*v1alpha1.PostgreSQLUser, error) { +func (m *PostgreSqlUserManager) convert(obj runtime.Object) (*v1alpha1.PostgreSQLUser, error) { local, ok := obj.(*v1alpha1.PostgreSQLUser) if !ok { return nil, fmt.Errorf("failed type assertion on kind: %s", obj.GetObjectKind().GroupVersionKind().String()) diff --git a/pkg/resourcemanager/psql/server/server.go b/pkg/resourcemanager/psql/server/server.go index 2ca4778560c..a982ef1eec8 100644 --- a/pkg/resourcemanager/psql/server/server.go +++ b/pkg/resourcemanager/psql/server/server.go @@ -19,20 +19,22 @@ import ( ) type PSQLServerClient struct { + Creds config.Credentials SecretClient secrets.SecretClient Scheme *runtime.Scheme } -func NewPSQLServerClient(secretclient secrets.SecretClient, scheme *runtime.Scheme) *PSQLServerClient { +func NewPSQLServerClient(creds config.Credentials, secretclient secrets.SecretClient, scheme *runtime.Scheme) *PSQLServerClient { return &PSQLServerClient{ + Creds: creds, SecretClient: secretclient, Scheme: scheme, } } -func getPSQLServersClient() (psql.ServersClient, error) { - serversClient := psql.NewServersClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, err := iam.GetResourceManagementAuthorizer() +func getPSQLServersClient(creds config.Credentials) (psql.ServersClient, error) { + serversClient := psql.NewServersClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, err := iam.GetResourceManagementAuthorizer(creds) if err != nil { return psql.ServersClient{}, err } @@ -41,9 +43,9 @@ func getPSQLServersClient() (psql.ServersClient, error) { return serversClient, nil } -func getPSQLCheckNameAvailabilityClient() (psql.CheckNameAvailabilityClient, error) { - nameavailabilityClient := psql.NewCheckNameAvailabilityClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, err := iam.GetResourceManagementAuthorizer() +func getPSQLCheckNameAvailabilityClient(creds config.Credentials) (psql.CheckNameAvailabilityClient, error) { + nameavailabilityClient := psql.NewCheckNameAvailabilityClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, err := iam.GetResourceManagementAuthorizer(creds) if err != nil { return psql.CheckNameAvailabilityClient{}, err } @@ -52,9 +54,9 @@ func getPSQLCheckNameAvailabilityClient() (psql.CheckNameAvailabilityClient, err return nameavailabilityClient, nil } -func (p *PSQLServerClient) CheckServerNameAvailability(ctx context.Context, servername string) (bool, error) { +func (c *PSQLServerClient) CheckServerNameAvailability(ctx context.Context, servername string) (bool, error) { - client, err := getPSQLCheckNameAvailabilityClient() + client, err := getPSQLCheckNameAvailabilityClient(c.Creds) if err != nil { return false, err } @@ -73,7 +75,7 @@ func (p *PSQLServerClient) CheckServerNameAvailability(ctx context.Context, serv } -func (p *PSQLServerClient) CreateServerIfValid(ctx context.Context, +func (c *PSQLServerClient) CreateServerIfValid(ctx context.Context, instance v1alpha2.PostgreSQLServer, tags map[string]*string, skuInfo psql.Sku, adminlogin string, @@ -81,13 +83,13 @@ func (p *PSQLServerClient) CreateServerIfValid(ctx context.Context, createmode psql.CreateMode, hash string) (pollingURL string, server psql.Server, err error) { - client, err := getPSQLServersClient() + client, err := getPSQLServersClient(c.Creds) if err != nil { return "", psql.Server{}, err } // Check if name is valid if this is the first create call - valid, err := p.CheckServerNameAvailability(ctx, instance.Name) + valid, err := c.CheckServerNameAvailability(ctx, instance.Name) if !valid { return "", psql.Server{}, err } @@ -164,9 +166,9 @@ func (p *PSQLServerClient) CreateServerIfValid(ctx context.Context, return pollingURL, server, err } -func (p *PSQLServerClient) DeleteServer(ctx context.Context, resourcegroup string, servername string) (status string, err error) { +func (c *PSQLServerClient) DeleteServer(ctx context.Context, resourcegroup string, servername string) (status string, err error) { - client, err := getPSQLServersClient() + client, err := getPSQLServersClient(c.Creds) if err != nil { return "", err } @@ -181,9 +183,9 @@ func (p *PSQLServerClient) DeleteServer(ctx context.Context, resourcegroup strin } -func (p *PSQLServerClient) GetServer(ctx context.Context, resourcegroup string, servername string) (server psql.Server, err error) { +func (c *PSQLServerClient) GetServer(ctx context.Context, resourcegroup string, servername string) (server psql.Server, err error) { - client, err := getPSQLServersClient() + client, err := getPSQLServersClient(c.Creds) if err != nil { return psql.Server{}, err } @@ -191,17 +193,17 @@ func (p *PSQLServerClient) GetServer(ctx context.Context, resourcegroup string, return client.Get(ctx, resourcegroup, servername) } -func (p *PSQLServerClient) AddServerCredsToSecrets(ctx context.Context, secretName string, data map[string][]byte, instance *v1alpha2.PostgreSQLServer) error { +func (c *PSQLServerClient) AddServerCredsToSecrets(ctx context.Context, secretName string, data map[string][]byte, instance *v1alpha2.PostgreSQLServer) error { key := types.NamespacedName{ Name: secretName, Namespace: instance.Namespace, } - err := p.SecretClient.Upsert(ctx, + err := c.SecretClient.Upsert(ctx, key, data, secrets.WithOwner(instance), - secrets.WithScheme(p.Scheme), + secrets.WithScheme(c.Scheme), ) if err != nil { return err @@ -210,7 +212,7 @@ func (p *PSQLServerClient) AddServerCredsToSecrets(ctx context.Context, secretNa return nil } -func (p *PSQLServerClient) UpdateSecretWithFullServerName(ctx context.Context, secretName string, data map[string][]byte, instance *v1alpha2.PostgreSQLServer, fullservername string) error { +func (c *PSQLServerClient) UpdateSecretWithFullServerName(ctx context.Context, secretName string, data map[string][]byte, instance *v1alpha2.PostgreSQLServer, fullservername string) error { key := types.NamespacedName{ Name: secretName, Namespace: instance.Namespace, @@ -218,11 +220,11 @@ func (p *PSQLServerClient) UpdateSecretWithFullServerName(ctx context.Context, s data["fullyQualifiedServerName"] = []byte(fullservername) - err := p.SecretClient.Upsert(ctx, + err := c.SecretClient.Upsert(ctx, key, data, secrets.WithOwner(instance), - secrets.WithScheme(p.Scheme), + secrets.WithScheme(c.Scheme), ) if err != nil { return err @@ -231,7 +233,7 @@ func (p *PSQLServerClient) UpdateSecretWithFullServerName(ctx context.Context, s return nil } -func (p *PSQLServerClient) GetOrPrepareSecret(ctx context.Context, instance *v1alpha2.PostgreSQLServer) (map[string][]byte, error) { +func (c *PSQLServerClient) GetOrPrepareSecret(ctx context.Context, instance *v1alpha2.PostgreSQLServer) (map[string][]byte, error) { name := instance.Name usernameLength := 8 @@ -239,7 +241,7 @@ func (p *PSQLServerClient) GetOrPrepareSecret(ctx context.Context, instance *v1a secret := map[string][]byte{} key := types.NamespacedName{Name: name, Namespace: instance.Namespace} - if stored, err := p.SecretClient.Get(ctx, key); err == nil { + if stored, err := c.SecretClient.Get(ctx, key); err == nil { return stored, nil } diff --git a/pkg/resourcemanager/psql/server/server_reconcile.go b/pkg/resourcemanager/psql/server/server_reconcile.go index 0f50a315b43..1d85f31bb52 100644 --- a/pkg/resourcemanager/psql/server/server_reconcile.go +++ b/pkg/resourcemanager/psql/server/server_reconcile.go @@ -21,17 +21,17 @@ import ( ) // Ensure creates the Postgres server -func (p *PSQLServerClient) Ensure(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) { +func (c *PSQLServerClient) Ensure(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) { options := &resourcemanager.Options{} for _, opt := range opts { opt(options) } if options.SecretClient != nil { - p.SecretClient = options.SecretClient + c.SecretClient = options.SecretClient } - instance, err := p.convert(obj) + instance, err := c.convert(obj) if err != nil { return true, err } @@ -50,13 +50,13 @@ func (p *PSQLServerClient) Ensure(ctx context.Context, obj runtime.Object, opts } // Check to see if secret exists and if yes retrieve the admin login and password - secret, err := p.GetOrPrepareSecret(ctx, instance) + secret, err := c.GetOrPrepareSecret(ctx, instance) if err != nil { return false, err } // Update secret with the fully qualified server name - err = p.AddServerCredsToSecrets(ctx, instance.Name, secret, instance) + err = c.AddServerCredsToSecrets(ctx, instance.Name, secret, instance) if err != nil { return false, err } @@ -71,7 +71,7 @@ func (p *PSQLServerClient) Ensure(ctx context.Context, obj runtime.Object, opts if instance.Status.Provisioning { // if an error occurs thats ok as it means that it doesn't exist yet - getServer, err := p.GetServer(ctx, instance.Spec.ResourceGroup, instance.Name) + getServer, err := c.GetServer(ctx, instance.Spec.ResourceGroup, instance.Name) if err == nil { instance.Status.State = string(getServer.UserVisibleState) @@ -79,7 +79,7 @@ func (p *PSQLServerClient) Ensure(ctx context.Context, obj runtime.Object, opts if getServer.UserVisibleState == psql.ServerStateReady { // Update the secret with fully qualified server name. Ignore error as we have the admin creds which is critical. - p.UpdateSecretWithFullServerName(ctx, instance.Name, secret, instance, *getServer.FullyQualifiedDomainName) + c.UpdateSecretWithFullServerName(ctx, instance.Name, secret, instance, *getServer.FullyQualifiedDomainName) instance.Status.Message = resourcemanager.SuccessMsg instance.Status.ResourceId = *getServer.ID @@ -96,7 +96,7 @@ func (p *PSQLServerClient) Ensure(ctx context.Context, obj runtime.Object, opts } else { // handle failures in the async operation if instance.Status.PollingURL != "" { - pClient := pollclient.NewPollClient() + pClient := pollclient.NewPollClient(c.Creds) res, err := pClient.Get(ctx, instance.Status.PollingURL) if err != nil { instance.Status.Provisioning = false @@ -136,7 +136,7 @@ func (p *PSQLServerClient) Ensure(ctx context.Context, obj runtime.Object, opts } // create the server - pollURL, _, err := p.CreateServerIfValid( + pollURL, _, err := c.CreateServerIfValid( ctx, *instance, labels, @@ -194,7 +194,7 @@ func (p *PSQLServerClient) Ensure(ctx context.Context, obj runtime.Object, opts } // Delete deletes the Postgres server -func (p *PSQLServerClient) Delete(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) { +func (c *PSQLServerClient) Delete(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) { options := &resourcemanager.Options{} for _, opt := range opts { @@ -202,15 +202,15 @@ func (p *PSQLServerClient) Delete(ctx context.Context, obj runtime.Object, opts } if options.SecretClient != nil { - p.SecretClient = options.SecretClient + c.SecretClient = options.SecretClient } - instance, err := p.convert(obj) + instance, err := c.convert(obj) if err != nil { return true, err } - status, err := p.DeleteServer(ctx, instance.Spec.ResourceGroup, instance.Name) + status, err := c.DeleteServer(ctx, instance.Spec.ResourceGroup, instance.Name) if err != nil { catch := []string{ errhelp.AsyncOpIncompleteError, @@ -235,7 +235,7 @@ func (p *PSQLServerClient) Delete(ctx context.Context, obj runtime.Object, opts if status != "InProgress" { // Best case deletion of secrets key := types.NamespacedName{Name: instance.Name, Namespace: instance.Namespace} - p.SecretClient.Delete(ctx, key) + c.SecretClient.Delete(ctx, key) return false, nil } } @@ -244,9 +244,9 @@ func (p *PSQLServerClient) Delete(ctx context.Context, obj runtime.Object, opts } // GetParents gets the resource's parents -func (p *PSQLServerClient) GetParents(obj runtime.Object) ([]resourcemanager.KubeParent, error) { +func (c *PSQLServerClient) GetParents(obj runtime.Object) ([]resourcemanager.KubeParent, error) { - instance, err := p.convert(obj) + instance, err := c.convert(obj) if err != nil { return nil, err } @@ -263,8 +263,8 @@ func (p *PSQLServerClient) GetParents(obj runtime.Object) ([]resourcemanager.Kub } // GetStatus returns the status -func (p *PSQLServerClient) GetStatus(obj runtime.Object) (*v1alpha1.ASOStatus, error) { - instance, err := p.convert(obj) +func (c *PSQLServerClient) GetStatus(obj runtime.Object) (*v1alpha1.ASOStatus, error) { + instance, err := c.convert(obj) if err != nil { return nil, err } @@ -272,7 +272,7 @@ func (p *PSQLServerClient) GetStatus(obj runtime.Object) (*v1alpha1.ASOStatus, e return &st, nil } -func (p *PSQLServerClient) convert(obj runtime.Object) (*v1alpha2.PostgreSQLServer, error) { +func (c *PSQLServerClient) convert(obj runtime.Object) (*v1alpha2.PostgreSQLServer, error) { local, ok := obj.(*v1alpha2.PostgreSQLServer) if !ok { return nil, fmt.Errorf("failed type assertion on kind: %s", obj.GetObjectKind().GroupVersionKind().String()) diff --git a/pkg/resourcemanager/psql/vnetrule/client.go b/pkg/resourcemanager/psql/vnetrule/client.go index 466af00bcd6..3553f526ef2 100644 --- a/pkg/resourcemanager/psql/vnetrule/client.go +++ b/pkg/resourcemanager/psql/vnetrule/client.go @@ -13,37 +13,38 @@ import ( ) type PostgreSQLVNetRuleClient struct { + creds config.Credentials } -func NewPostgreSQLVNetRuleClient() *PostgreSQLVNetRuleClient { - return &PostgreSQLVNetRuleClient{} +func NewPostgreSQLVNetRuleClient(creds config.Credentials) *PostgreSQLVNetRuleClient { + return &PostgreSQLVNetRuleClient{creds: creds} } -func GetPostgreSQLVNetRulesClient() psql.VirtualNetworkRulesClient { - VNetRulesClient := psql.NewVirtualNetworkRulesClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, _ := iam.GetResourceManagementAuthorizer() +func GetPostgreSQLVNetRulesClient(creds config.Credentials) psql.VirtualNetworkRulesClient { + VNetRulesClient := psql.NewVirtualNetworkRulesClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, _ := iam.GetResourceManagementAuthorizer(creds) VNetRulesClient.Authorizer = a VNetRulesClient.AddToUserAgent(config.UserAgent()) return VNetRulesClient } // retrieves the Subnetclient -func GetGoNetworkSubnetClient() network.SubnetsClient { - SubnetsClient := network.NewSubnetsClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, _ := iam.GetResourceManagementAuthorizer() +func GetGoNetworkSubnetClient(creds config.Credentials) network.SubnetsClient { + SubnetsClient := network.NewSubnetsClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, _ := iam.GetResourceManagementAuthorizer(creds) SubnetsClient.Authorizer = a SubnetsClient.AddToUserAgent(config.UserAgent()) return SubnetsClient } // GetPostgreSQLVNetRule returns a VNet rule -func (vr *PostgreSQLVNetRuleClient) GetPostgreSQLVNetRule( +func (c *PostgreSQLVNetRuleClient) GetPostgreSQLVNetRule( ctx context.Context, resourceGroupName string, serverName string, ruleName string) (result psql.VirtualNetworkRule, err error) { - VNetRulesClient := GetPostgreSQLVNetRulesClient() + VNetRulesClient := GetPostgreSQLVNetRulesClient(c.creds) return VNetRulesClient.Get( ctx, @@ -54,15 +55,15 @@ func (vr *PostgreSQLVNetRuleClient) GetPostgreSQLVNetRule( } // deletes a VNet rule -func (vr *PostgreSQLVNetRuleClient) DeletePostgreSQLVNetRule(ctx context.Context, resourceGroupName string, serverName string, ruleName string) (err error) { +func (c *PostgreSQLVNetRuleClient) DeletePostgreSQLVNetRule(ctx context.Context, resourceGroupName string, serverName string, ruleName string) (err error) { // check to see if the rule exists, if it doesn't then short-circuit - _, err = vr.GetPostgreSQLVNetRule(ctx, resourceGroupName, serverName, ruleName) + _, err = c.GetPostgreSQLVNetRule(ctx, resourceGroupName, serverName, ruleName) if err != nil { return nil } - VNetRulesClient := GetPostgreSQLVNetRulesClient() + VNetRulesClient := GetPostgreSQLVNetRulesClient(c.creds) _, err = VNetRulesClient.Delete( ctx, resourceGroupName, @@ -74,7 +75,7 @@ func (vr *PostgreSQLVNetRuleClient) DeletePostgreSQLVNetRule(ctx context.Context } // creates or updates a VNet rule -func (vr *PostgreSQLVNetRuleClient) CreateOrUpdatePostgreSQLVNetRule( +func (c *PostgreSQLVNetRuleClient) CreateOrUpdatePostgreSQLVNetRule( ctx context.Context, resourceGroupName string, serverName string, @@ -84,8 +85,8 @@ func (vr *PostgreSQLVNetRuleClient) CreateOrUpdatePostgreSQLVNetRule( SubnetName string, IgnoreServiceEndpoint bool) (vnr psql.VirtualNetworkRule, err error) { - VNetRulesClient := GetPostgreSQLVNetRulesClient() - SubnetClient := GetGoNetworkSubnetClient() + VNetRulesClient := GetPostgreSQLVNetRulesClient(c.creds) + SubnetClient := GetGoNetworkSubnetClient(c.creds) // Get ARM Resource ID of Subnet based on the VNET name, Subnet name and Subnet Address Prefix subnet, err := SubnetClient.Get(ctx, VNetRG, VNetName, SubnetName, "") diff --git a/pkg/resourcemanager/rediscaches/actions/rediscacheactions.go b/pkg/resourcemanager/rediscaches/actions/rediscacheactions.go index 85030a769e9..f4c2e9de23b 100644 --- a/pkg/resourcemanager/rediscaches/actions/rediscacheactions.go +++ b/pkg/resourcemanager/rediscaches/actions/rediscacheactions.go @@ -8,6 +8,7 @@ import ( "fmt" "github.com/Azure/azure-service-operator/api/v1alpha1" + "github.com/Azure/azure-service-operator/pkg/resourcemanager/config" "github.com/Azure/azure-service-operator/pkg/resourcemanager/rediscaches" "github.com/Azure/azure-service-operator/pkg/secrets" @@ -22,9 +23,10 @@ type AzureRedisCacheActionManager struct { } // NewAzureRedisCacheActionManager creates a new RedisCacheManager -func NewAzureRedisCacheActionManager(secretClient secrets.SecretClient, scheme *runtime.Scheme) *AzureRedisCacheActionManager { +func NewAzureRedisCacheActionManager(creds config.Credentials, secretClient secrets.SecretClient, scheme *runtime.Scheme) *AzureRedisCacheActionManager { return &AzureRedisCacheActionManager{ rediscaches.AzureRedisManager{ + Creds: creds, SecretClient: secretClient, Scheme: scheme, }, diff --git a/pkg/resourcemanager/rediscaches/firewallrule/rediscachefirewallrule.go b/pkg/resourcemanager/rediscaches/firewallrule/rediscachefirewallrule.go index cf4f2f64697..0f99b4e09c3 100644 --- a/pkg/resourcemanager/rediscaches/firewallrule/rediscachefirewallrule.go +++ b/pkg/resourcemanager/rediscaches/firewallrule/rediscachefirewallrule.go @@ -16,17 +16,19 @@ import ( ) // AzureRedisCacheFirewallRuleManager creates a new AzureRedisCacheFirewallRuleManager -type AzureRedisCacheFirewallRuleManager struct{} +type AzureRedisCacheFirewallRuleManager struct { + creds config.Credentials +} // NewAzureRedisCacheFirewallRuleManager creates a new AzureRedisCacheFirewallRuleManager -func NewAzureRedisCacheFirewallRuleManager() *AzureRedisCacheFirewallRuleManager { - return &AzureRedisCacheFirewallRuleManager{} +func NewAzureRedisCacheFirewallRuleManager(creds config.Credentials) *AzureRedisCacheFirewallRuleManager { + return &AzureRedisCacheFirewallRuleManager{creds: creds} } // getRedisCacheFirewallRuleClient retrieves a firewallrules client -func getRedisCacheFirewallRuleClient() (redis.FirewallRulesClient, error) { - firewallRulesClient := redis.NewFirewallRulesClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, err := iam.GetResourceManagementAuthorizer() +func getRedisCacheFirewallRuleClient(creds config.Credentials) (redis.FirewallRulesClient, error) { + firewallRulesClient := redis.NewFirewallRulesClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, err := iam.GetResourceManagementAuthorizer(creds) if err != nil { return redis.FirewallRulesClient{}, err } @@ -36,9 +38,9 @@ func getRedisCacheFirewallRuleClient() (redis.FirewallRulesClient, error) { } // CreateRedisCacheFirewallRule creates a new RedisCacheFirewallRule -func (r *AzureRedisCacheFirewallRuleManager) CreateRedisCacheFirewallRule(ctx context.Context, instance azurev1alpha1.RedisCacheFirewallRule) (result redis.FirewallRule, err error) { +func (m *AzureRedisCacheFirewallRuleManager) CreateRedisCacheFirewallRule(ctx context.Context, instance azurev1alpha1.RedisCacheFirewallRule) (result redis.FirewallRule, err error) { - firewallRuleClient, err := getRedisCacheFirewallRuleClient() + firewallRuleClient, err := getRedisCacheFirewallRuleClient(m.creds) if err != nil { return redis.FirewallRule{}, err } @@ -68,9 +70,9 @@ func (r *AzureRedisCacheFirewallRuleManager) CreateRedisCacheFirewallRule(ctx co } // Get gets a single firewall rule in a specified redis cache -func (r *AzureRedisCacheFirewallRuleManager) Get(ctx context.Context, resourceGroup string, redisCacheName string, firewallRuleName string) (result redis.FirewallRule, err error) { +func (m *AzureRedisCacheFirewallRuleManager) Get(ctx context.Context, resourceGroup string, redisCacheName string, firewallRuleName string) (result redis.FirewallRule, err error) { - firewallRuleClient, err := getRedisCacheFirewallRuleClient() + firewallRuleClient, err := getRedisCacheFirewallRuleClient(m.creds) if err != nil { return redis.FirewallRule{}, err } @@ -79,13 +81,13 @@ func (r *AzureRedisCacheFirewallRuleManager) Get(ctx context.Context, resourceGr } // DeleteRedisCacheFirewallRule deletes a redis firewall rule -func (r *AzureRedisCacheFirewallRuleManager) DeleteRedisCacheFirewallRule(ctx context.Context, resourceGroup string, redisCacheName string, firewallRuleName string) (result autorest.Response, err error) { +func (m *AzureRedisCacheFirewallRuleManager) DeleteRedisCacheFirewallRule(ctx context.Context, resourceGroup string, redisCacheName string, firewallRuleName string) (result autorest.Response, err error) { result = autorest.Response{ Response: &http.Response{ StatusCode: 200, }, } - firewallRuleClient, err := getRedisCacheFirewallRuleClient() + firewallRuleClient, err := getRedisCacheFirewallRuleClient(m.creds) if err != nil { return result, err } diff --git a/pkg/resourcemanager/rediscaches/redis/rediscaches.go b/pkg/resourcemanager/rediscaches/redis/rediscaches.go index ad9dc1fd080..fc0ff564e3e 100644 --- a/pkg/resourcemanager/rediscaches/redis/rediscaches.go +++ b/pkg/resourcemanager/rediscaches/redis/rediscaches.go @@ -11,6 +11,7 @@ import ( "github.com/Azure/azure-sdk-for-go/services/redis/mgmt/2018-03-01/redis" azurev1alpha1 "github.com/Azure/azure-service-operator/api/v1alpha1" "github.com/Azure/azure-service-operator/pkg/helpers" + "github.com/Azure/azure-service-operator/pkg/resourcemanager/config" "github.com/Azure/azure-service-operator/pkg/resourcemanager/rediscaches" "github.com/Azure/azure-service-operator/pkg/resourcemanager/vnet" "github.com/Azure/azure-service-operator/pkg/secrets" @@ -25,9 +26,10 @@ type AzureRedisCacheManager struct { } // NewAzureRedisCacheManager creates a new RedisCacheManager -func NewAzureRedisCacheManager(secretClient secrets.SecretClient, scheme *runtime.Scheme) *AzureRedisCacheManager { +func NewAzureRedisCacheManager(creds config.Credentials, secretClient secrets.SecretClient, scheme *runtime.Scheme) *AzureRedisCacheManager { return &AzureRedisCacheManager{ rediscaches.AzureRedisManager{ + Creds: creds, SecretClient: secretClient, Scheme: scheme, }, @@ -84,7 +86,7 @@ func (r *AzureRedisCacheManager) CreateRedisCache( if len(props.SubnetID) > 0 { ip := props.StaticIP if len(props.StaticIP) == 0 { - vnetManager := vnet.NewAzureVNetManager() + vnetManager := vnet.NewAzureVNetManager(r.Creds) sid := vnet.ParseSubnetID(props.SubnetID) ip, err = vnetManager.GetAvailableIP(ctx, sid.ResourceGroup, sid.VNet, sid.Subnet) diff --git a/pkg/resourcemanager/rediscaches/shared.go b/pkg/resourcemanager/rediscaches/shared.go index b6c3aaa4638..10273d6d7ac 100644 --- a/pkg/resourcemanager/rediscaches/shared.go +++ b/pkg/resourcemanager/rediscaches/shared.go @@ -20,13 +20,14 @@ import ( // AzureRedisManager type AzureRedisManager struct { + Creds config.Credentials SecretClient secrets.SecretClient Scheme *runtime.Scheme } -func (r *AzureRedisManager) GetRedisCacheClient() (redis.Client, error) { - redisClient := redis.NewClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, err := iam.GetResourceManagementAuthorizer() +func (m *AzureRedisManager) GetRedisCacheClient() (redis.Client, error) { + redisClient := redis.NewClientWithBaseURI(config.BaseURI(), m.Creds.SubscriptionID()) + a, err := iam.GetResourceManagementAuthorizer(m.Creds) if err != nil { log.Println("failed to initialize authorizer: " + err.Error()) return redisClient, err @@ -37,8 +38,8 @@ func (r *AzureRedisManager) GetRedisCacheClient() (redis.Client, error) { } //ListKeys lists the keys for redis cache -func (r *AzureRedisManager) ListKeys(ctx context.Context, resourceGroupName string, redisCacheName string) (result redis.AccessKeys, err error) { - redisClient, err := r.GetRedisCacheClient() +func (m *AzureRedisManager) ListKeys(ctx context.Context, resourceGroupName string, redisCacheName string) (result redis.AccessKeys, err error) { + redisClient, err := m.GetRedisCacheClient() if err != nil { return result, err } @@ -46,7 +47,7 @@ func (r *AzureRedisManager) ListKeys(ctx context.Context, resourceGroupName stri } // CreateSecrets creates a secret for a redis cache -func (r *AzureRedisManager) CreateSecrets(ctx context.Context, instance *v1alpha1.RedisCache, data map[string][]byte) error { +func (m *AzureRedisManager) CreateSecrets(ctx context.Context, instance *v1alpha1.RedisCache, data map[string][]byte) error { secretName := instance.Spec.SecretName if secretName == "" { secretName = instance.Name @@ -54,12 +55,12 @@ func (r *AzureRedisManager) CreateSecrets(ctx context.Context, instance *v1alpha key := types.NamespacedName{Name: secretName, Namespace: instance.Namespace} - err := r.SecretClient.Upsert( + err := m.SecretClient.Upsert( ctx, key, data, secrets.WithOwner(instance), - secrets.WithScheme(r.Scheme), + secrets.WithScheme(m.Scheme), ) if err != nil { return err @@ -69,11 +70,11 @@ func (r *AzureRedisManager) CreateSecrets(ctx context.Context, instance *v1alpha } // ListKeysAndCreateSecrets lists keys and creates secrets -func (r *AzureRedisManager) ListKeysAndCreateSecrets(ctx context.Context, instance *v1alpha1.RedisCache) error { +func (m *AzureRedisManager) ListKeysAndCreateSecrets(ctx context.Context, instance *v1alpha1.RedisCache) error { var err error var result redis.AccessKeys - result, err = r.ListKeys(ctx, instance.Spec.ResourceGroupName, instance.Name) + result, err = m.ListKeys(ctx, instance.Spec.ResourceGroupName, instance.Name) if err != nil { return err } @@ -82,7 +83,7 @@ func (r *AzureRedisManager) ListKeysAndCreateSecrets(ctx context.Context, instan "secondaryKey": []byte(*result.SecondaryKey), } - err = r.CreateSecrets( + err = m.CreateSecrets( ctx, instance, data, diff --git a/pkg/resourcemanager/resourcegroups/resourcegroup.go b/pkg/resourcemanager/resourcegroups/resourcegroup.go index 20f49aa12de..9a8619c33aa 100644 --- a/pkg/resourcemanager/resourcegroups/resourcegroup.go +++ b/pkg/resourcemanager/resourcegroups/resourcegroup.go @@ -19,11 +19,13 @@ import ( ) // AzureResourceGroupManager is the struct which contains helper functions for resource groups -type AzureResourceGroupManager struct{} +type AzureResourceGroupManager struct { + creds config.Credentials +} -func getGroupsClient() (resources.GroupsClient, error) { - groupsClient := resources.NewGroupsClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, err := iam.GetResourceManagementAuthorizer() +func getGroupsClient(creds config.Credentials) (resources.GroupsClient, error) { + groupsClient := resources.NewGroupsClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, err := iam.GetResourceManagementAuthorizer(creds) if err != nil { return resources.GroupsClient{}, err } @@ -32,8 +34,8 @@ func getGroupsClient() (resources.GroupsClient, error) { return groupsClient, nil } -func getGroupsClientWithAuthFile() (resources.GroupsClient, error) { - groupsClient := resources.NewGroupsClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) +func getGroupsClientWithAuthFile(creds config.Credentials) (resources.GroupsClient, error) { + groupsClient := resources.NewGroupsClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) // requires env var AZURE_AUTH_LOCATION set to output of // `az ad sp create-for-rbac --sdk-auth` a, err := auth.NewAuthorizerFromFile(config.BaseURI()) @@ -46,8 +48,8 @@ func getGroupsClientWithAuthFile() (resources.GroupsClient, error) { } // CreateGroup creates a new resource group named by env var -func (_ *AzureResourceGroupManager) CreateGroup(ctx context.Context, groupName string, location string) (resources.Group, error) { - groupsClient, err := getGroupsClient() +func (m *AzureResourceGroupManager) CreateGroup(ctx context.Context, groupName string, location string) (resources.Group, error) { + groupsClient, err := getGroupsClient(m.creds) if err != nil { return resources.Group{}, err } @@ -62,8 +64,8 @@ func (_ *AzureResourceGroupManager) CreateGroup(ctx context.Context, groupName s // CreateGroupWithAuthFile creates a new resource group. The client authorizer // is set up based on an auth file created using the Azure CLI. -func CreateGroupWithAuthFile(ctx context.Context, groupName string, location string) (resources.Group, error) { - groupsClient, err := getGroupsClientWithAuthFile() +func (m *AzureResourceGroupManager) CreateGroupWithAuthFile(ctx context.Context, groupName, location string) (resources.Group, error) { + groupsClient, err := getGroupsClientWithAuthFile(m.creds) if err != nil { return resources.Group{}, err } @@ -77,8 +79,8 @@ func CreateGroupWithAuthFile(ctx context.Context, groupName string, location str } // DeleteGroup removes the resource group named by env var -func (_ *AzureResourceGroupManager) DeleteGroup(ctx context.Context, groupName string) (result autorest.Response, err error) { - client, err := getGroupsClient() +func (m *AzureResourceGroupManager) DeleteGroup(ctx context.Context, groupName string) (result autorest.Response, err error) { + client, err := getGroupsClient(m.creds) if err != nil { return autorest.Response{ Response: &http.Response{ @@ -95,12 +97,12 @@ func (_ *AzureResourceGroupManager) DeleteGroup(ctx context.Context, groupName s return future.Result(client) } -func (_ *AzureResourceGroupManager) DeleteGroupAsync(ctx context.Context, groupName string) (result resources.GroupsDeleteFuture, err error) { - return deleteGroupAsync(ctx, groupName) +func (m *AzureResourceGroupManager) DeleteGroupAsync(ctx context.Context, groupName string) (result resources.GroupsDeleteFuture, err error) { + return m.deleteGroupAsync(ctx, groupName) } -func deleteGroupAsync(ctx context.Context, groupName string) (result resources.GroupsDeleteFuture, err error) { - groupsClient, err := getGroupsClient() +func (m *AzureResourceGroupManager) deleteGroupAsync(ctx context.Context, groupName string) (result resources.GroupsDeleteFuture, err error) { + groupsClient, err := getGroupsClient(m.creds) if err != nil { return resources.GroupsDeleteFuture{}, err } @@ -109,8 +111,8 @@ func deleteGroupAsync(ctx context.Context, groupName string) (result resources.G } // ListGroups gets an interator that gets all resource groups in the subscription -func ListGroups(ctx context.Context) (resources.GroupListResultIterator, error) { - groupsClient, err := getGroupsClient() +func (m *AzureResourceGroupManager) ListGroups(ctx context.Context) (resources.GroupListResultIterator, error) { + groupsClient, err := getGroupsClient(m.creds) if err != nil { return resources.GroupListResultIterator{}, err } @@ -119,8 +121,8 @@ func ListGroups(ctx context.Context) (resources.GroupListResultIterator, error) } // GetGroup gets info on the resource group in use -func GetGroup(ctx context.Context, groupName string) (resources.Group, error) { - groupsClient, err := getGroupsClient() +func (m *AzureResourceGroupManager) GetGroup(ctx context.Context, groupName string) (resources.Group, error) { + groupsClient, err := getGroupsClient(m.creds) if err != nil { return resources.Group{}, err } @@ -129,15 +131,15 @@ func GetGroup(ctx context.Context, groupName string) (resources.Group, error) { } // DeleteAllGroupsWithPrefix deletes all rescource groups that start with a certain prefix -func DeleteAllGroupsWithPrefix(ctx context.Context, prefix string) (futures []resources.GroupsDeleteFuture, groups []string) { +func (m *AzureResourceGroupManager) DeleteAllGroupsWithPrefix(ctx context.Context, prefix string) (futures []resources.GroupsDeleteFuture, groups []string) { - for list, err := ListGroups(ctx); list.NotDone(); err = list.Next() { + for list, err := m.ListGroups(ctx); list.NotDone(); err = list.Next() { if err != nil { return } rgName := *list.Value().Name if strings.HasPrefix(rgName, prefix) { - future, err := deleteGroupAsync(ctx, rgName) + future, err := m.deleteGroupAsync(ctx, rgName) if err != nil { return } @@ -149,11 +151,11 @@ func DeleteAllGroupsWithPrefix(ctx context.Context, prefix string) (futures []re } // WaitForDeleteCompletion concurrently waits for delete group operations to finish -func WaitForDeleteCompletion(ctx context.Context, wg *sync.WaitGroup, futures []resources.GroupsDeleteFuture, groups []string) { +func (m *AzureResourceGroupManager) WaitForDeleteCompletion(ctx context.Context, wg *sync.WaitGroup, futures []resources.GroupsDeleteFuture, groups []string) { for i, f := range futures { wg.Add(1) go func(ctx context.Context, future resources.GroupsDeleteFuture, rg string) { - client, err := getGroupsClient() + client, err := getGroupsClient(m.creds) if err != nil { return } @@ -168,8 +170,8 @@ func WaitForDeleteCompletion(ctx context.Context, wg *sync.WaitGroup, futures [] } // CheckExistence checks whether a resource exists -func (_ *AzureResourceGroupManager) CheckExistence(ctx context.Context, resourceGroupName string) (result autorest.Response, err error) { - groupsClient, err := getGroupsClient() +func (m *AzureResourceGroupManager) CheckExistence(ctx context.Context, resourceGroupName string) (result autorest.Response, err error) { + groupsClient, err := getGroupsClient(m.creds) if err != nil { return autorest.Response{ Response: &http.Response{ diff --git a/pkg/resourcemanager/resourcegroups/resourcegroup_manager.go b/pkg/resourcemanager/resourcegroups/resourcegroup_manager.go index 6c265fb905b..1a4b3825d8e 100644 --- a/pkg/resourcemanager/resourcegroups/resourcegroup_manager.go +++ b/pkg/resourcemanager/resourcegroups/resourcegroup_manager.go @@ -8,13 +8,14 @@ import ( "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2017-05-10/resources" "github.com/Azure/azure-service-operator/pkg/resourcemanager" + "github.com/Azure/azure-service-operator/pkg/resourcemanager/config" "github.com/Azure/go-autorest/autorest" ) // var AzureResourceGroupManager ResourceGroupManager = &azureResourceGroupManager{} -func NewAzureResourceGroupManager() *AzureResourceGroupManager { - return &AzureResourceGroupManager{} +func NewAzureResourceGroupManager(creds config.Credentials) *AzureResourceGroupManager { + return &AzureResourceGroupManager{creds: creds} } type ResourceGroupManager interface { diff --git a/pkg/resourcemanager/resourcegroups/resourcegroup_test.go b/pkg/resourcemanager/resourcegroups/resourcegroup_test.go index ce31ad36d62..3b17909483c 100644 --- a/pkg/resourcemanager/resourcegroups/resourcegroup_test.go +++ b/pkg/resourcemanager/resourcegroups/resourcegroup_test.go @@ -40,7 +40,7 @@ var _ = Describe("ResourceGroups", func() { resourcegroupName := "t-rg-" + helpers.RandomString(10) resourcegroupLocation := config.DefaultLocation() - resourceGroupManager := NewAzureResourceGroupManager() + resourceGroupManager := NewAzureResourceGroupManager(config.GlobalCredentials()) var err error _, err = resourceGroupManager.CreateGroup(context.Background(), resourcegroupName, resourcegroupLocation) @@ -63,7 +63,8 @@ var _ = Describe("ResourceGroups", func() { Expect(err).NotTo(HaveOccurred()) Eventually(func() bool { - result, _ := GetGroup(context.Background(), resourcegroupName) + manager := NewAzureResourceGroupManager(config.GlobalCredentials()) + result, _ := manager.GetGroup(context.Background(), resourcegroupName) return result.Response.StatusCode == http.StatusNotFound || *result.Properties.ProvisioningState == "Deleting" }, timeout, ).Should(BeTrue()) diff --git a/pkg/resourcemanager/storages/blobcontainer/blob_container.go b/pkg/resourcemanager/storages/blobcontainer/blob_container.go index 2ce94406822..8a85cb7a454 100644 --- a/pkg/resourcemanager/storages/blobcontainer/blob_container.go +++ b/pkg/resourcemanager/storages/blobcontainer/blob_container.go @@ -13,11 +13,13 @@ import ( "github.com/Azure/go-autorest/autorest" ) -type AzureBlobContainerManager struct{} +type AzureBlobContainerManager struct { + creds config.Credentials +} -func getContainerClient() (s.BlobContainersClient, error) { - containersClient := s.NewBlobContainersClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - auth, err := iam.GetResourceManagementAuthorizer() +func getContainerClient(creds config.Credentials) (s.BlobContainersClient, error) { + containersClient := s.NewBlobContainersClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + auth, err := iam.GetResourceManagementAuthorizer(creds) if err != nil { return s.BlobContainersClient{}, err } @@ -32,8 +34,8 @@ func getContainerClient() (s.BlobContainersClient, error) { // accountName - the name of the storage account // containerName - the name of the container // accessLevel - 'PublicAccessContainer', 'PublicAccessBlob', or 'PublicAccessNone' -func (bc *AzureBlobContainerManager) CreateBlobContainer(ctx context.Context, resourceGroupName string, accountName string, containerName string, accessLevel s.PublicAccess) (*s.BlobContainer, error) { - containerClient, err := getContainerClient() +func (m *AzureBlobContainerManager) CreateBlobContainer(ctx context.Context, resourceGroupName string, accountName string, containerName string, accessLevel s.PublicAccess) (*s.BlobContainer, error) { + containerClient, err := getContainerClient(m.creds) if err != nil { return nil, err } @@ -61,8 +63,8 @@ func (bc *AzureBlobContainerManager) CreateBlobContainer(ctx context.Context, re // resourceGroupName - name of the resource group within the azure subscription. // accountName - the name of the storage account // containerName - the name of the container -func (bc *AzureBlobContainerManager) GetBlobContainer(ctx context.Context, resourceGroupName string, accountName string, containerName string) (result s.BlobContainer, err error) { - containerClient, err := getContainerClient() +func (m *AzureBlobContainerManager) GetBlobContainer(ctx context.Context, resourceGroupName string, accountName string, containerName string) (result s.BlobContainer, err error) { + containerClient, err := getContainerClient(m.creds) if err != nil { return s.BlobContainer{}, err } @@ -75,8 +77,8 @@ func (bc *AzureBlobContainerManager) GetBlobContainer(ctx context.Context, resou // resourceGroupName - name of the resource group within the azure subscription. // accountName - the name of the storage account // containerName - the name of the container -func (bc *AzureBlobContainerManager) DeleteBlobContainer(ctx context.Context, resourceGroupName string, accountName string, containerName string) (result autorest.Response, err error) { - containerClient, err := getContainerClient() +func (m *AzureBlobContainerManager) DeleteBlobContainer(ctx context.Context, resourceGroupName string, accountName string, containerName string) (result autorest.Response, err error) { + containerClient, err := getContainerClient(m.creds) if err != nil { return autorest.Response{ Response: &http.Response{ diff --git a/pkg/resourcemanager/storages/blobcontainer/blob_container_manager.go b/pkg/resourcemanager/storages/blobcontainer/blob_container_manager.go index b4628447e4d..042c30772e6 100644 --- a/pkg/resourcemanager/storages/blobcontainer/blob_container_manager.go +++ b/pkg/resourcemanager/storages/blobcontainer/blob_container_manager.go @@ -8,12 +8,13 @@ import ( "github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2019-04-01/storage" s "github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2019-04-01/storage" + "github.com/Azure/azure-service-operator/pkg/resourcemanager/config" "github.com/Azure/go-autorest/autorest" ) // New returns a pointer to a new instance of a blob container client -func New() *AzureBlobContainerManager { - return &AzureBlobContainerManager{} +func New(creds config.Credentials) *AzureBlobContainerManager { + return &AzureBlobContainerManager{creds: creds} } // BlobContainerManager exists in case we need it diff --git a/pkg/resourcemanager/storages/managers.go b/pkg/resourcemanager/storages/managers.go index e3c1bdcec17..3f6992e3298 100644 --- a/pkg/resourcemanager/storages/managers.go +++ b/pkg/resourcemanager/storages/managers.go @@ -4,6 +4,7 @@ package storages import ( + "github.com/Azure/azure-service-operator/pkg/resourcemanager/config" "github.com/Azure/azure-service-operator/pkg/resourcemanager/storages/blobcontainer" "github.com/Azure/azure-service-operator/pkg/resourcemanager/storages/storageaccount" "github.com/Azure/azure-service-operator/pkg/secrets" @@ -15,9 +16,9 @@ type StorageManagers struct { BlobContainer blobcontainer.BlobContainerManager } -func NewAzureStorageManagers(secretClient secrets.SecretClient, scheme *runtime.Scheme) StorageManagers { +func NewAzureStorageManagers(creds config.Credentials, secretClient secrets.SecretClient, scheme *runtime.Scheme) StorageManagers { return StorageManagers{ - StorageAccount: storageaccount.New(secretClient, scheme), - BlobContainer: blobcontainer.New(), + StorageAccount: storageaccount.New(creds, secretClient, scheme), + BlobContainer: blobcontainer.New(creds), } } diff --git a/pkg/resourcemanager/storages/storageaccount/storageaccount.go b/pkg/resourcemanager/storages/storageaccount/storageaccount.go index 5b6cd768cca..cd108625236 100644 --- a/pkg/resourcemanager/storages/storageaccount/storageaccount.go +++ b/pkg/resourcemanager/storages/storageaccount/storageaccount.go @@ -26,6 +26,7 @@ import ( const templateForConnectionString = "DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s;EndpointSuffix=%s" type azureStorageManager struct { + Creds config.Credentials SecretClient secrets.SecretClient Scheme *runtime.Scheme } @@ -80,19 +81,19 @@ func ParseNetworkPolicy(ruleSet *v1alpha1.StorageNetworkRuleSet) storage.Network } } -func getStoragesClient() (storage.AccountsClient, error) { - storagesClient := storage.NewAccountsClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, err := iam.GetResourceManagementAuthorizer() +func getStorageClient(creds config.Credentials) (storage.AccountsClient, error) { + storageClient := storage.NewAccountsClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, err := iam.GetResourceManagementAuthorizer(creds) if err != nil { return storage.AccountsClient{}, err } - storagesClient.Authorizer = a - storagesClient.AddToUserAgent(config.UserAgent()) - return storagesClient, nil + storageClient.Authorizer = a + storageClient.AddToUserAgent(config.UserAgent()) + return storageClient, nil } // CreateStorage creates a new storage account -func (_ *azureStorageManager) CreateStorage(ctx context.Context, +func (m *azureStorageManager) CreateStorage(ctx context.Context, groupName string, storageAccountName string, location string, @@ -102,7 +103,7 @@ func (_ *azureStorageManager) CreateStorage(ctx context.Context, accessTier azurev1alpha1.StorageAccountAccessTier, enableHTTPsTrafficOnly *bool, dataLakeEnabled *bool, networkRule *storage.NetworkRuleSet) (pollingURL string, result storage.Account, err error) { - storagesClient, err := getStoragesClient() + storageClient, err := getStorageClient(m.Creds) if err != nil { return "", storage.Account{}, err } @@ -110,7 +111,7 @@ func (_ *azureStorageManager) CreateStorage(ctx context.Context, //Check if name is available storageType := "Microsoft.Storage/storageAccounts" checkAccountParams := storage.AccountCheckNameAvailabilityParameters{Name: &storageAccountName, Type: &storageType} - checkNameResult, err := storagesClient.CheckNameAvailability(ctx, checkAccountParams) + checkNameResult, err := storageClient.CheckNameAvailability(ctx, checkAccountParams) if err != nil { return "", result, err } @@ -147,12 +148,12 @@ func (_ *azureStorageManager) CreateStorage(ctx context.Context, } //log.Println(fmt.Sprintf("creating storage '%s' in resource group '%s' and location: %v", storageAccountName, groupName, location)) - future, err := storagesClient.Create(ctx, groupName, storageAccountName, params) + future, err := storageClient.Create(ctx, groupName, storageAccountName, params) if err != nil { return "", result, err } - result, err = future.Result(storagesClient) + result, err = future.Result(storageClient) return future.PollingURL(), result, err @@ -162,18 +163,18 @@ func (_ *azureStorageManager) CreateStorage(ctx context.Context, // Parameters: // resourceGroupName - name of the resource group within the azure subscription. // storageAccountName - the name of the storage account -func (_ *azureStorageManager) GetStorage(ctx context.Context, resourceGroupName string, storageAccountName string) (result storage.Account, err error) { - storagesClient, err := getStoragesClient() +func (m *azureStorageManager) GetStorage(ctx context.Context, resourceGroupName string, storageAccountName string) (result storage.Account, err error) { + storageClient, err := getStorageClient(m.Creds) if err != nil { return storage.Account{}, err } - return storagesClient.GetProperties(ctx, resourceGroupName, storageAccountName, "") + return storageClient.GetProperties(ctx, resourceGroupName, storageAccountName, "") } // DeleteStorage removes the resource group named by env var -func (_ *azureStorageManager) DeleteStorage(ctx context.Context, groupName string, storageAccountName string) (result autorest.Response, err error) { - storagesClient, err := getStoragesClient() +func (m *azureStorageManager) DeleteStorage(ctx context.Context, groupName string, storageAccountName string) (result autorest.Response, err error) { + storageClient, err := getStorageClient(m.Creds) if err != nil { return autorest.Response{ Response: &http.Response{ @@ -182,23 +183,23 @@ func (_ *azureStorageManager) DeleteStorage(ctx context.Context, groupName strin }, err } - return storagesClient.Delete(ctx, groupName, storageAccountName) + return storageClient.Delete(ctx, groupName, storageAccountName) } -func (_ *azureStorageManager) ListKeys(ctx context.Context, resourceGroupName string, accountName string) (result storage.AccountListKeysResult, err error) { - storagesClient, err := getStoragesClient() +func (m *azureStorageManager) ListKeys(ctx context.Context, resourceGroupName string, accountName string) (result storage.AccountListKeysResult, err error) { + storageClient, err := getStorageClient(m.Creds) if err != nil { return storage.AccountListKeysResult{}, err } - return storagesClient.ListKeys(ctx, resourceGroupName, accountName, storage.Kerb) + return storageClient.ListKeys(ctx, resourceGroupName, accountName, storage.Kerb) } // StoreSecrets upserts the secret information for this storage account -func (s *azureStorageManager) StoreSecrets(ctx context.Context, resourceGroupName string, accountName string, instance *v1alpha1.StorageAccount) error { +func (m *azureStorageManager) StoreSecrets(ctx context.Context, resourceGroupName string, accountName string, instance *v1alpha1.StorageAccount) error { // get the keys - keyResult, err := s.ListKeys(ctx, resourceGroupName, accountName) + keyResult, err := m.ListKeys(ctx, resourceGroupName, accountName) if err != nil { return err } @@ -222,10 +223,10 @@ func (s *azureStorageManager) StoreSecrets(ctx context.Context, resourceGroupNam Name: fmt.Sprintf("storageaccount-%s-%s", resourceGroupName, accountName), Namespace: instance.Namespace, } - return s.SecretClient.Upsert(ctx, + return m.SecretClient.Upsert(ctx, key, data, secrets.WithOwner(instance), - secrets.WithScheme(s.Scheme), + secrets.WithScheme(m.Scheme), ) } diff --git a/pkg/resourcemanager/storages/storageaccount/storageaccount_manager.go b/pkg/resourcemanager/storages/storageaccount/storageaccount_manager.go index 375d54bbed9..e83b364b1fc 100644 --- a/pkg/resourcemanager/storages/storageaccount/storageaccount_manager.go +++ b/pkg/resourcemanager/storages/storageaccount/storageaccount_manager.go @@ -10,14 +10,16 @@ import ( "github.com/Azure/azure-service-operator/api/v1alpha1" azurev1alpha1 "github.com/Azure/azure-service-operator/api/v1alpha1" "github.com/Azure/azure-service-operator/pkg/resourcemanager" + "github.com/Azure/azure-service-operator/pkg/resourcemanager/config" "github.com/Azure/azure-service-operator/pkg/secrets" "github.com/Azure/go-autorest/autorest" "k8s.io/apimachinery/pkg/runtime" ) // New returns an instance of the Storage Account Client -func New(secretClient secrets.SecretClient, scheme *runtime.Scheme) *azureStorageManager { +func New(creds config.Credentials, secretClient secrets.SecretClient, scheme *runtime.Scheme) *azureStorageManager { return &azureStorageManager{ + Creds: creds, SecretClient: secretClient, Scheme: scheme, } diff --git a/pkg/resourcemanager/storages/storageaccount/storageaccount_reconcile.go b/pkg/resourcemanager/storages/storageaccount/storageaccount_reconcile.go index 9856d42f6c1..74ac2ba0606 100644 --- a/pkg/resourcemanager/storages/storageaccount/storageaccount_reconcile.go +++ b/pkg/resourcemanager/storages/storageaccount/storageaccount_reconcile.go @@ -19,9 +19,9 @@ import ( ) // Ensure creates a storage account -func (sa *azureStorageManager) Ensure(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) { +func (m *azureStorageManager) Ensure(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) { - instance, err := sa.convert(obj) + instance, err := m.convert(obj) if err != nil { return false, err } @@ -45,14 +45,14 @@ func (sa *azureStorageManager) Ensure(ctx context.Context, obj runtime.Object, o labels := helpers.LabelsToTags(instance.GetLabels()) hash := "" - stor, err := sa.GetStorage(ctx, groupName, name) + stor, err := m.GetStorage(ctx, groupName, name) if err != nil { instance.Status.Message = err.Error() instance.Status.State = "NotReady" // handle failures in the async operation if pollURL != "" { - pClient := pollclient.NewPollClient() + pClient := pollclient.NewPollClient(m.Creds) res, err := pClient.Get(ctx, pollURL) azerr := errhelp.NewAzureError(err) if err != nil { @@ -84,7 +84,7 @@ func (sa *azureStorageManager) Ensure(ctx context.Context, obj runtime.Object, o if instance.Status.State == "Succeeded" { // upsert - err = sa.StoreSecrets(ctx, groupName, name, instance) + err = m.StoreSecrets(ctx, groupName, name, instance) if err != nil { return false, err } @@ -102,7 +102,7 @@ func (sa *azureStorageManager) Ensure(ctx context.Context, obj runtime.Object, o instance.Status.Provisioning = true instance.Status.Provisioned = false - pollURL, _, err = sa.CreateStorage(ctx, groupName, name, location, sku, kind, labels, accessTier, enableHTTPSTrafficOnly, dataLakeEnabled, &networkAcls) + pollURL, _, err = m.CreateStorage(ctx, groupName, name, location, sku, kind, labels, accessTier, enableHTTPSTrafficOnly, dataLakeEnabled, &networkAcls) if err != nil { instance.Status.Message = err.Error() azerr := errhelp.NewAzureError(err) @@ -129,7 +129,7 @@ func (sa *azureStorageManager) Ensure(ctx context.Context, obj runtime.Object, o // call to the reconcile loop for an update of this exact resource. So // we call a Get to check if this is the current resource and if // yes, we let the call go through instead of ending the reconcile loop - _, err := sa.GetStorage(ctx, instance.Spec.ResourceGroup, instance.ObjectMeta.Name) + _, err := m.GetStorage(ctx, instance.Spec.ResourceGroup, instance.ObjectMeta.Name) if err != nil { // This means that the Server exists elsewhere and we should // terminate the reconcile loop diff --git a/pkg/resourcemanager/storages/suite_test.go b/pkg/resourcemanager/storages/suite_test.go index ca787a010c8..67745649829 100644 --- a/pkg/resourcemanager/storages/suite_test.go +++ b/pkg/resourcemanager/storages/suite_test.go @@ -10,6 +10,7 @@ import ( "github.com/Azure/azure-service-operator/pkg/helpers" + "github.com/Azure/azure-service-operator/pkg/resourcemanager/config" resourcemanagerconfig "github.com/Azure/azure-service-operator/pkg/resourcemanager/config" resourcegroupsresourcemanager "github.com/Azure/azure-service-operator/pkg/resourcemanager/resourcegroups" @@ -61,7 +62,7 @@ var _ = BeforeSuite(func() { resourceGroupName := "t-rg-dev-rm-st-" + helpers.RandomString(10) resourceGroupLocation := resourcemanagerconfig.DefaultLocation() - resourceGroupManager := resourcegroupsresourcemanager.NewAzureResourceGroupManager() + resourceGroupManager := resourcegroupsresourcemanager.NewAzureResourceGroupManager(config.GlobalCredentials()) // create resourcegroup for this suite _, err = resourceGroupManager.CreateGroup(context.Background(), resourceGroupName, resourceGroupLocation) diff --git a/pkg/resourcemanager/vm/client.go b/pkg/resourcemanager/vm/client.go index da6b737c393..c3508e979de 100644 --- a/pkg/resourcemanager/vm/client.go +++ b/pkg/resourcemanager/vm/client.go @@ -19,28 +19,30 @@ import ( ) type AzureVirtualMachineClient struct { + Creds config.Credentials SecretClient secrets.SecretClient Scheme *runtime.Scheme } -func NewAzureVirtualMachineClient(secretclient secrets.SecretClient, scheme *runtime.Scheme) *AzureVirtualMachineClient { +func NewAzureVirtualMachineClient(creds config.Credentials, secretclient secrets.SecretClient, scheme *runtime.Scheme) *AzureVirtualMachineClient { return &AzureVirtualMachineClient{ + Creds: creds, SecretClient: secretclient, Scheme: scheme, } } -func getVirtualMachineClient() compute.VirtualMachinesClient { - computeClient := compute.NewVirtualMachinesClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, _ := iam.GetResourceManagementAuthorizer() +func getVirtualMachineClient(creds config.Credentials) compute.VirtualMachinesClient { + computeClient := compute.NewVirtualMachinesClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, _ := iam.GetResourceManagementAuthorizer(creds) computeClient.Authorizer = a computeClient.AddToUserAgent(config.UserAgent()) return computeClient } -func (m *AzureVirtualMachineClient) CreateVirtualMachine(ctx context.Context, location string, resourceGroupName string, resourceName string, vmSize string, osType string, adminUserName string, adminPassword string, sshPublicKeyData string, networkInterfaceName string, platformImageURN string) (future compute.VirtualMachinesCreateOrUpdateFuture, err error) { +func (c *AzureVirtualMachineClient) CreateVirtualMachine(ctx context.Context, location string, resourceGroupName string, resourceName string, vmSize string, osType string, adminUserName string, adminPassword string, sshPublicKeyData string, networkInterfaceName string, platformImageURN string) (future compute.VirtualMachinesCreateOrUpdateFuture, err error) { - client := getVirtualMachineClient() + client := getVirtualMachineClient(c.Creds) vmSizeInput := compute.VirtualMachineSizeTypes(vmSize) provisionVMAgent := true @@ -134,9 +136,9 @@ func (m *AzureVirtualMachineClient) CreateVirtualMachine(ctx context.Context, lo return future, err } -func (m *AzureVirtualMachineClient) DeleteVirtualMachine(ctx context.Context, vmName string, resourcegroup string) (status string, err error) { +func (c *AzureVirtualMachineClient) DeleteVirtualMachine(ctx context.Context, vmName string, resourcegroup string) (status string, err error) { - client := getVirtualMachineClient() + client := getVirtualMachineClient(c.Creds) _, err = client.Get(ctx, resourcegroup, vmName, "") if err == nil { // vm present, so go ahead and delete @@ -148,24 +150,24 @@ func (m *AzureVirtualMachineClient) DeleteVirtualMachine(ctx context.Context, vm } -func (m *AzureVirtualMachineClient) GetVirtualMachine(ctx context.Context, resourcegroup string, vmName string) (vm compute.VirtualMachine, err error) { +func (c *AzureVirtualMachineClient) GetVirtualMachine(ctx context.Context, resourcegroup string, vmName string) (vm compute.VirtualMachine, err error) { - client := getVirtualMachineClient() + client := getVirtualMachineClient(c.Creds) return client.Get(ctx, resourcegroup, vmName, "") } -func (p *AzureVirtualMachineClient) AddVirtualMachineCredsToSecrets(ctx context.Context, secretName string, data map[string][]byte, instance *azurev1alpha1.AzureVirtualMachine) error { +func (c *AzureVirtualMachineClient) AddVirtualMachineCredsToSecrets(ctx context.Context, secretName string, data map[string][]byte, instance *azurev1alpha1.AzureVirtualMachine) error { key := types.NamespacedName{ Name: secretName, Namespace: instance.Namespace, } - err := p.SecretClient.Upsert(ctx, + err := c.SecretClient.Upsert(ctx, key, data, secrets.WithOwner(instance), - secrets.WithScheme(p.Scheme), + secrets.WithScheme(c.Scheme), ) if err != nil { return err @@ -174,13 +176,13 @@ func (p *AzureVirtualMachineClient) AddVirtualMachineCredsToSecrets(ctx context. return nil } -func (p *AzureVirtualMachineClient) GetOrPrepareSecret(ctx context.Context, instance *azurev1alpha1.AzureVirtualMachine) (map[string][]byte, error) { +func (c *AzureVirtualMachineClient) GetOrPrepareSecret(ctx context.Context, instance *azurev1alpha1.AzureVirtualMachine) (map[string][]byte, error) { name := instance.Name secret := map[string][]byte{} key := types.NamespacedName{Name: name, Namespace: instance.Namespace} - if stored, err := p.SecretClient.Get(ctx, key); err == nil { + if stored, err := c.SecretClient.Get(ctx, key); err == nil { return stored, nil } diff --git a/pkg/resourcemanager/vm/reconcile.go b/pkg/resourcemanager/vm/reconcile.go index e2f643309b2..ae742270742 100644 --- a/pkg/resourcemanager/vm/reconcile.go +++ b/pkg/resourcemanager/vm/reconcile.go @@ -15,14 +15,14 @@ import ( "k8s.io/apimachinery/pkg/types" ) -func (g *AzureVirtualMachineClient) Ensure(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) { +func (c *AzureVirtualMachineClient) Ensure(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) { - instance, err := g.convert(obj) + instance, err := c.convert(obj) if err != nil { return true, err } - client := getVirtualMachineClient() + client := getVirtualMachineClient(c.Creds) location := instance.Spec.Location resourceGroup := instance.Spec.ResourceGroup @@ -37,12 +37,12 @@ func (g *AzureVirtualMachineClient) Ensure(ctx context.Context, obj runtime.Obje const SucceededProvisioningState = "Succeeded" // Check to see if secret exists and if yes retrieve the admin login and password - secret, err := g.GetOrPrepareSecret(ctx, instance) + secret, err := c.GetOrPrepareSecret(ctx, instance) if err != nil { return false, err } // Update secret - err = g.AddVirtualMachineCredsToSecrets(ctx, instance.Name, secret, instance) + err = c.AddVirtualMachineCredsToSecrets(ctx, instance.Name, secret, instance) if err != nil { return false, err } @@ -52,7 +52,7 @@ func (g *AzureVirtualMachineClient) Ensure(ctx context.Context, obj runtime.Obje instance.Status.Provisioning = true // Check if this item already exists. This is required // to overcome the issue with the lack of idempotence of the Create call - item, err := g.GetVirtualMachine(ctx, resourceGroup, resourceName) + item, err := c.GetVirtualMachine(ctx, resourceGroup, resourceName) if err == nil { if *item.ProvisioningState == SucceededProvisioningState { @@ -71,7 +71,7 @@ func (g *AzureVirtualMachineClient) Ensure(ctx context.Context, obj runtime.Obje return false, nil } - future, err := g.CreateVirtualMachine( + future, err := c.CreateVirtualMachine( ctx, location, resourceGroup, @@ -150,9 +150,9 @@ func (g *AzureVirtualMachineClient) Ensure(ctx context.Context, obj runtime.Obje return false, nil } -func (g *AzureVirtualMachineClient) Delete(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) { +func (c *AzureVirtualMachineClient) Delete(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) { - instance, err := g.convert(obj) + instance, err := c.convert(obj) if err != nil { return true, err } @@ -160,7 +160,7 @@ func (g *AzureVirtualMachineClient) Delete(ctx context.Context, obj runtime.Obje resourceGroup := instance.Spec.ResourceGroup resourceName := instance.Name - status, err := g.DeleteVirtualMachine( + status, err := c.DeleteVirtualMachine( ctx, resourceName, resourceGroup, diff --git a/pkg/resourcemanager/vmext/client.go b/pkg/resourcemanager/vmext/client.go index a213c696986..f735622bce9 100644 --- a/pkg/resourcemanager/vmext/client.go +++ b/pkg/resourcemanager/vmext/client.go @@ -17,28 +17,30 @@ import ( ) type AzureVirtualMachineExtensionClient struct { + Creds config.Credentials SecretClient secrets.SecretClient Scheme *runtime.Scheme } -func NewAzureVirtualMachineExtensionClient(secretclient secrets.SecretClient, scheme *runtime.Scheme) *AzureVirtualMachineExtensionClient { +func NewAzureVirtualMachineExtensionClient(creds config.Credentials, secretclient secrets.SecretClient, scheme *runtime.Scheme) *AzureVirtualMachineExtensionClient { return &AzureVirtualMachineExtensionClient{ + Creds: creds, SecretClient: secretclient, Scheme: scheme, } } -func getVirtualMachineExtensionClient() compute.VirtualMachineExtensionsClient { - computeClient := compute.NewVirtualMachineExtensionsClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, _ := iam.GetResourceManagementAuthorizer() +func getVirtualMachineExtensionClient(creds config.Credentials) compute.VirtualMachineExtensionsClient { + computeClient := compute.NewVirtualMachineExtensionsClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, _ := iam.GetResourceManagementAuthorizer(creds) computeClient.Authorizer = a computeClient.AddToUserAgent(config.UserAgent()) return computeClient } -func (m *AzureVirtualMachineExtensionClient) CreateVirtualMachineExtension(ctx context.Context, location string, resourceGroupName string, vmName string, extName string, autoUpgradeMinorVersion bool, forceUpdateTag string, publisher string, typeName string, typeHandlerVersion string, settings string, protectedSettings string) (future compute.VirtualMachineExtensionsCreateOrUpdateFuture, err error) { +func (c *AzureVirtualMachineExtensionClient) CreateVirtualMachineExtension(ctx context.Context, location string, resourceGroupName string, vmName string, extName string, autoUpgradeMinorVersion bool, forceUpdateTag string, publisher string, typeName string, typeHandlerVersion string, settings string, protectedSettings string) (future compute.VirtualMachineExtensionsCreateOrUpdateFuture, err error) { - client := getVirtualMachineExtensionClient() + client := getVirtualMachineExtensionClient(c.Creds) var extensionSettings map[string]*string @@ -75,9 +77,9 @@ func (m *AzureVirtualMachineExtensionClient) CreateVirtualMachineExtension(ctx c return future, err } -func (m *AzureVirtualMachineExtensionClient) DeleteVirtualMachineExtension(ctx context.Context, extName string, vmName string, resourcegroup string) (status string, err error) { +func (c *AzureVirtualMachineExtensionClient) DeleteVirtualMachineExtension(ctx context.Context, extName string, vmName string, resourcegroup string) (status string, err error) { - client := getVirtualMachineExtensionClient() + client := getVirtualMachineExtensionClient(c.Creds) _, err = client.Get(ctx, resourcegroup, vmName, extName, "") if err == nil { // vm present, so go ahead and delete @@ -89,9 +91,9 @@ func (m *AzureVirtualMachineExtensionClient) DeleteVirtualMachineExtension(ctx c } -func (m *AzureVirtualMachineExtensionClient) GetVirtualMachineExtension(ctx context.Context, resourcegroup string, vmName string, extName string) (vm compute.VirtualMachineExtension, err error) { +func (c *AzureVirtualMachineExtensionClient) GetVirtualMachineExtension(ctx context.Context, resourcegroup string, vmName string, extName string) (vm compute.VirtualMachineExtension, err error) { - client := getVirtualMachineExtensionClient() + client := getVirtualMachineExtensionClient(c.Creds) return client.Get(ctx, resourcegroup, vmName, extName, "") } diff --git a/pkg/resourcemanager/vmext/reconcile.go b/pkg/resourcemanager/vmext/reconcile.go index 70bbfaead1f..df5441a6c06 100644 --- a/pkg/resourcemanager/vmext/reconcile.go +++ b/pkg/resourcemanager/vmext/reconcile.go @@ -15,14 +15,14 @@ import ( "k8s.io/apimachinery/pkg/types" ) -func (g *AzureVirtualMachineExtensionClient) Ensure(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) { +func (c *AzureVirtualMachineExtensionClient) Ensure(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) { - instance, err := g.convert(obj) + instance, err := c.convert(obj) if err != nil { return true, err } - client := getVirtualMachineExtensionClient() + client := getVirtualMachineExtensionClient(c.Creds) location := instance.Spec.Location resourceGroup := instance.Spec.ResourceGroup @@ -37,12 +37,12 @@ func (g *AzureVirtualMachineExtensionClient) Ensure(ctx context.Context, obj run protectedSettings := instance.Spec.ProtectedSettings // Check to see if secret exists and if yes retrieve the admin login and password - secret, err := g.GetOrPrepareSecret(ctx, instance) + secret, err := c.GetOrPrepareSecret(ctx, instance) if err != nil { return false, err } // Update secret - err = g.AddVirtualMachineExtensionCredsToSecrets(ctx, instance.Name, secret, instance) + err = c.AddVirtualMachineExtensionCredsToSecrets(ctx, instance.Name, secret, instance) if err != nil { return false, err } @@ -56,7 +56,7 @@ func (g *AzureVirtualMachineExtensionClient) Ensure(ctx context.Context, obj run instance.Status.Provisioning = true // Check if this item already exists. This is required // to overcome the issue with the lack of idempotence of the Create call - item, err := g.GetVirtualMachineExtension(ctx, resourceGroup, vmName, extName) + item, err := c.GetVirtualMachineExtension(ctx, resourceGroup, vmName, extName) if err == nil { instance.Status.Provisioned = true instance.Status.Provisioning = false @@ -64,7 +64,7 @@ func (g *AzureVirtualMachineExtensionClient) Ensure(ctx context.Context, obj run instance.Status.ResourceId = *item.ID return true, nil } - future, err := g.CreateVirtualMachineExtension( + future, err := c.CreateVirtualMachineExtension( ctx, location, resourceGroup, diff --git a/pkg/resourcemanager/vmss/client.go b/pkg/resourcemanager/vmss/client.go index 6976f46abca..e481b05e0a4 100644 --- a/pkg/resourcemanager/vmss/client.go +++ b/pkg/resourcemanager/vmss/client.go @@ -19,28 +19,30 @@ import ( ) type AzureVMScaleSetClient struct { + Creds config.Credentials SecretClient secrets.SecretClient Scheme *runtime.Scheme } -func NewAzureVMScaleSetClient(secretclient secrets.SecretClient, scheme *runtime.Scheme) *AzureVMScaleSetClient { +func NewAzureVMScaleSetClient(creds config.Credentials, secretclient secrets.SecretClient, scheme *runtime.Scheme) *AzureVMScaleSetClient { return &AzureVMScaleSetClient{ + Creds: creds, SecretClient: secretclient, Scheme: scheme, } } -func getVMScaleSetClient() compute.VirtualMachineScaleSetsClient { - computeClient := compute.NewVirtualMachineScaleSetsClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, _ := iam.GetResourceManagementAuthorizer() +func getVMScaleSetClient(creds config.Credentials) compute.VirtualMachineScaleSetsClient { + computeClient := compute.NewVirtualMachineScaleSetsClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, _ := iam.GetResourceManagementAuthorizer(creds) computeClient.Authorizer = a computeClient.AddToUserAgent(config.UserAgent()) return computeClient } -func (m *AzureVMScaleSetClient) CreateVMScaleSet(ctx context.Context, location string, resourceGroupName string, resourceName string, vmSize string, capacity int64, osType string, adminUserName string, adminPassword string, sshPublicKeyData string, platformImageURN string, vnetName string, subnetName string, loadBalancerName string, backendAddressPoolName string, inboundNatPoolName string) (future compute.VirtualMachineScaleSetsCreateOrUpdateFuture, err error) { +func (c *AzureVMScaleSetClient) CreateVMScaleSet(ctx context.Context, location string, resourceGroupName string, resourceName string, vmSize string, capacity int64, osType string, adminUserName string, adminPassword string, sshPublicKeyData string, platformImageURN string, vnetName string, subnetName string, loadBalancerName string, backendAddressPoolName string, inboundNatPoolName string) (future compute.VirtualMachineScaleSetsCreateOrUpdateFuture, err error) { - client := getVMScaleSetClient() + client := getVMScaleSetClient(c.Creds) // Construct OS Profile provisionVMAgent := true @@ -193,9 +195,9 @@ func (m *AzureVMScaleSetClient) CreateVMScaleSet(ctx context.Context, location s return future, err } -func (m *AzureVMScaleSetClient) DeleteVMScaleSet(ctx context.Context, vmssName string, resourcegroup string) (status string, err error) { +func (c *AzureVMScaleSetClient) DeleteVMScaleSet(ctx context.Context, vmssName string, resourcegroup string) (status string, err error) { - client := getVMScaleSetClient() + client := getVMScaleSetClient(c.Creds) _, err = client.Get(ctx, resourcegroup, vmssName) if err == nil { // vmss present, so go ahead and delete @@ -207,9 +209,9 @@ func (m *AzureVMScaleSetClient) DeleteVMScaleSet(ctx context.Context, vmssName s } -func (m *AzureVMScaleSetClient) GetVMScaleSet(ctx context.Context, resourcegroup string, vmssName string) (vmss compute.VirtualMachineScaleSet, err error) { +func (c *AzureVMScaleSetClient) GetVMScaleSet(ctx context.Context, resourcegroup string, vmssName string) (vmss compute.VirtualMachineScaleSet, err error) { - client := getVMScaleSetClient() + client := getVMScaleSetClient(c.Creds) return client.Get(ctx, resourcegroup, vmssName) } diff --git a/pkg/resourcemanager/vmss/reconcile.go b/pkg/resourcemanager/vmss/reconcile.go index b101268a892..ff5f270109d 100644 --- a/pkg/resourcemanager/vmss/reconcile.go +++ b/pkg/resourcemanager/vmss/reconcile.go @@ -15,14 +15,14 @@ import ( "k8s.io/apimachinery/pkg/types" ) -func (g *AzureVMScaleSetClient) Ensure(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) { +func (c *AzureVMScaleSetClient) Ensure(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) { - instance, err := g.convert(obj) + instance, err := c.convert(obj) if err != nil { return true, err } - client := getVMScaleSetClient() + client := getVMScaleSetClient(c.Creds) location := instance.Spec.Location resourceGroup := instance.Spec.ResourceGroup @@ -40,12 +40,12 @@ func (g *AzureVMScaleSetClient) Ensure(ctx context.Context, obj runtime.Object, natPoolName := instance.Spec.InboundNatPoolName // Check to see if secret exists and if yes retrieve the admin login and password - secret, err := g.GetOrPrepareSecret(ctx, instance) + secret, err := c.GetOrPrepareSecret(ctx, instance) if err != nil { return false, err } // Update secret - err = g.AddVMScaleSetCredsToSecrets(ctx, instance.Name, secret, instance) + err = c.AddVMScaleSetCredsToSecrets(ctx, instance.Name, secret, instance) if err != nil { return false, err } @@ -55,7 +55,7 @@ func (g *AzureVMScaleSetClient) Ensure(ctx context.Context, obj runtime.Object, instance.Status.Provisioning = true // Check if this item already exists. This is required // to overcome the issue with the lack of idempotence of the Create call - item, err := g.GetVMScaleSet(ctx, resourceGroup, resourceName) + item, err := c.GetVMScaleSet(ctx, resourceGroup, resourceName) if err == nil { instance.Status.Provisioned = true instance.Status.Provisioning = false @@ -64,7 +64,7 @@ func (g *AzureVMScaleSetClient) Ensure(ctx context.Context, obj runtime.Object, return true, nil } - future, err := g.CreateVMScaleSet( + future, err := c.CreateVMScaleSet( ctx, location, resourceGroup, @@ -149,9 +149,9 @@ func (g *AzureVMScaleSetClient) Ensure(ctx context.Context, obj runtime.Object, return true, nil } -func (g *AzureVMScaleSetClient) Delete(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) { +func (c *AzureVMScaleSetClient) Delete(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) { - instance, err := g.convert(obj) + instance, err := c.convert(obj) if err != nil { return true, err } @@ -159,7 +159,7 @@ func (g *AzureVMScaleSetClient) Delete(ctx context.Context, obj runtime.Object, resourceGroup := instance.Spec.ResourceGroup resourceName := instance.Name - status, err := g.DeleteVMScaleSet( + status, err := c.DeleteVMScaleSet( ctx, resourceName, resourceGroup, @@ -191,9 +191,9 @@ func (g *AzureVMScaleSetClient) Delete(ctx context.Context, obj runtime.Object, return true, nil } -func (g *AzureVMScaleSetClient) GetParents(obj runtime.Object) ([]resourcemanager.KubeParent, error) { +func (c *AzureVMScaleSetClient) GetParents(obj runtime.Object) ([]resourcemanager.KubeParent, error) { - instance, err := g.convert(obj) + instance, err := c.convert(obj) if err != nil { return nil, err } @@ -209,16 +209,16 @@ func (g *AzureVMScaleSetClient) GetParents(obj runtime.Object) ([]resourcemanage }, nil } -func (g *AzureVMScaleSetClient) GetStatus(obj runtime.Object) (*azurev1alpha1.ASOStatus, error) { +func (c *AzureVMScaleSetClient) GetStatus(obj runtime.Object) (*azurev1alpha1.ASOStatus, error) { - instance, err := g.convert(obj) + instance, err := c.convert(obj) if err != nil { return nil, err } return &instance.Status, nil } -func (g *AzureVMScaleSetClient) convert(obj runtime.Object) (*azurev1alpha1.AzureVMScaleSet, error) { +func (c *AzureVMScaleSetClient) convert(obj runtime.Object) (*azurev1alpha1.AzureVMScaleSet, error) { local, ok := obj.(*azurev1alpha1.AzureVMScaleSet) if !ok { return nil, fmt.Errorf("failed type assertion on kind: %s", obj.GetObjectKind().GroupVersionKind().String()) diff --git a/pkg/resourcemanager/vnet/subnet.go b/pkg/resourcemanager/vnet/subnet.go index 64a036c5d6f..59044a6e434 100644 --- a/pkg/resourcemanager/vnet/subnet.go +++ b/pkg/resourcemanager/vnet/subnet.go @@ -13,17 +13,19 @@ import ( ) // AzureSubnetManager is the struct that the manager functions hang off -type AzureSubnetManager struct{} +type AzureSubnetManager struct { + creds config.Credentials +} //NewAzureSubnetManager returns a new client for subnets -func NewAzureSubnetManager() *AzureSubnetManager { - return &AzureSubnetManager{} +func NewAzureSubnetManager(creds config.Credentials) *AzureSubnetManager { + return &AzureSubnetManager{creds: creds} } // getSubnetClient returns a new instance of an subnet client -func getSubnetClient() (vnetwork.SubnetsClient, error) { - client := vnetwork.NewSubnetsClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, err := iam.GetResourceManagementAuthorizer() +func getSubnetClient(creds config.Credentials) (vnetwork.SubnetsClient, error) { + client := vnetwork.NewSubnetsClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, err := iam.GetResourceManagementAuthorizer(creds) if err != nil { client = vnetwork.SubnetsClient{} } else { @@ -34,8 +36,8 @@ func getSubnetClient() (vnetwork.SubnetsClient, error) { } // Get gets a Subnet from Azure -func (v *AzureSubnetManager) Get(ctx context.Context, resourceGroup, vnet, subnet string) (vnetwork.Subnet, error) { - client, err := getSubnetClient() +func (m *AzureSubnetManager) Get(ctx context.Context, resourceGroup, vnet, subnet string) (vnetwork.Subnet, error) { + client, err := getSubnetClient(m.creds) if err != nil { return vnetwork.Subnet{}, err } diff --git a/pkg/resourcemanager/vnet/suite_test.go b/pkg/resourcemanager/vnet/suite_test.go index ff2939d3b7f..87e9d295be4 100644 --- a/pkg/resourcemanager/vnet/suite_test.go +++ b/pkg/resourcemanager/vnet/suite_test.go @@ -13,6 +13,7 @@ import ( "context" + "github.com/Azure/azure-service-operator/pkg/resourcemanager/config" resourcemanagerconfig "github.com/Azure/azure-service-operator/pkg/resourcemanager/config" resourcegroupsresourcemanager "github.com/Azure/azure-service-operator/pkg/resourcemanager/resourcegroups" . "github.com/onsi/ginkgo" @@ -61,7 +62,7 @@ var _ = BeforeSuite(func() { resourceGroupName := "t-rg-vnet-" + helpers.RandomString(10) resourceGroupLocation := resourcemanagerconfig.DefaultLocation() - resourceGroupManager := resourcegroupsresourcemanager.NewAzureResourceGroupManager() + resourceGroupManager := resourcegroupsresourcemanager.NewAzureResourceGroupManager(config.GlobalCredentials()) //create resourcegroup for this suite _, err = resourceGroupManager.CreateGroup(ctx, resourceGroupName, resourceGroupLocation) @@ -73,7 +74,7 @@ var _ = BeforeSuite(func() { AddressSpace: "10.0.0.0/8", SubnetName: "test-subnet-" + helpers.RandomString(5), SubnetAddressPrefix: "10.1.0.0/16", - VirtualNetworkManager: NewAzureVNetManager(), + VirtualNetworkManager: NewAzureVNetManager(config.GlobalCredentials()), ResourceGroupManager: resourceGroupManager, timeout: 20 * time.Minute, retryInterval: 3 * time.Second, @@ -94,7 +95,8 @@ var _ = AfterSuite(func() { for { time.Sleep(time.Second * 10) - _, err := resourcegroupsresourcemanager.GetGroup(ctx, tc.ResourceGroupName) + rgManager := resourcegroupsresourcemanager.NewAzureResourceGroupManager(config.GlobalCredentials()) + _, err := rgManager.GetGroup(ctx, tc.ResourceGroupName) if err == nil { log.Println("waiting for resource group to be deleted") } else { diff --git a/pkg/resourcemanager/vnet/vnet.go b/pkg/resourcemanager/vnet/vnet.go index eb5b8820988..e50b9e10980 100644 --- a/pkg/resourcemanager/vnet/vnet.go +++ b/pkg/resourcemanager/vnet/vnet.go @@ -19,13 +19,14 @@ import ( // AzureVNetManager is the struct that the manager functions hang off type AzureVNetManager struct { + Creds config.Credentials Telemetry telemetry.Telemetry } // getVNetClient returns a new instance of an VirtualNetwork client -func getVNetClient() (vnetwork.VirtualNetworksClient, error) { - client := vnetwork.NewVirtualNetworksClientWithBaseURI(config.BaseURI(), config.SubscriptionID()) - a, err := iam.GetResourceManagementAuthorizer() +func getVNetClient(creds config.Credentials) (vnetwork.VirtualNetworksClient, error) { + client := vnetwork.NewVirtualNetworksClientWithBaseURI(config.BaseURI(), creds.SubscriptionID()) + a, err := iam.GetResourceManagementAuthorizer(creds) if err != nil { client = vnetwork.VirtualNetworksClient{} } else { @@ -36,8 +37,8 @@ func getVNetClient() (vnetwork.VirtualNetworksClient, error) { } // CreateVNet creates VNets -func (*AzureVNetManager) CreateVNet(ctx context.Context, location string, resourceGroupName string, resourceName string, addressSpace string, subnets []azurev1alpha1.VNetSubnets) (vnetwork.VirtualNetwork, error) { - client, err := getVNetClient() +func (m *AzureVNetManager) CreateVNet(ctx context.Context, location string, resourceGroupName string, resourceName string, addressSpace string, subnets []azurev1alpha1.VNetSubnets) (vnetwork.VirtualNetwork, error) { + client, err := getVNetClient(m.Creds) if err != nil { return vnetwork.VirtualNetwork{}, err } @@ -86,8 +87,8 @@ func (*AzureVNetManager) CreateVNet(ctx context.Context, location string, resour } // DeleteVNet deletes a VNet -func (*AzureVNetManager) DeleteVNet(ctx context.Context, resourceGroupName string, resourceName string) (autorest.Response, error) { - client, err := getVNetClient() +func (m *AzureVNetManager) DeleteVNet(ctx context.Context, resourceGroupName string, resourceName string) (autorest.Response, error) { + client, err := getVNetClient(m.Creds) if err != nil { return autorest.Response{}, err } @@ -105,8 +106,8 @@ func (*AzureVNetManager) DeleteVNet(ctx context.Context, resourceGroupName strin } // GetVNet gets a VNet -func (v *AzureVNetManager) GetVNet(ctx context.Context, resourceGroupName string, resourceName string) (vNet vnetwork.VirtualNetwork, err error) { - client, err := getVNetClient() +func (m *AzureVNetManager) GetVNet(ctx context.Context, resourceGroupName string, resourceName string) (vNet vnetwork.VirtualNetwork, err error) { + client, err := getVNetClient(m.Creds) if err != nil { return vnetwork.VirtualNetwork{}, err } @@ -114,13 +115,13 @@ func (v *AzureVNetManager) GetVNet(ctx context.Context, resourceGroupName string return client.Get(ctx, resourceGroupName, resourceName, "") } -func (v *AzureVNetManager) GetAvailableIP(ctx context.Context, resourceGroup, vnet, subnet string) (string, error) { - client, err := getVNetClient() +func (m *AzureVNetManager) GetAvailableIP(ctx context.Context, resourceGroup, vnet, subnet string) (string, error) { + client, err := getVNetClient(m.Creds) if err != nil { return "", err } - sclient := NewAzureSubnetManager() + sclient := NewAzureSubnetManager(m.Creds) sub, err := sclient.Get(ctx, resourceGroup, vnet, subnet) if err != nil { diff --git a/pkg/resourcemanager/vnet/vnet_manager.go b/pkg/resourcemanager/vnet/vnet_manager.go index 2c850e06e75..5f38e41b149 100644 --- a/pkg/resourcemanager/vnet/vnet_manager.go +++ b/pkg/resourcemanager/vnet/vnet_manager.go @@ -9,12 +9,13 @@ import ( vnetwork "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-09-01/network" azurev1alpha1 "github.com/Azure/azure-service-operator/api/v1alpha1" "github.com/Azure/azure-service-operator/pkg/resourcemanager" + "github.com/Azure/azure-service-operator/pkg/resourcemanager/config" "github.com/Azure/go-autorest/autorest" ) // NewAzureVNetManager creates a new instance of AzureVNetManager -func NewAzureVNetManager() *AzureVNetManager { - return &AzureVNetManager{} +func NewAzureVNetManager(creds config.Credentials) *AzureVNetManager { + return &AzureVNetManager{Creds: creds} } // VNetManager manages VNet service components diff --git a/pkg/secrets/keyvault/client.go b/pkg/secrets/keyvault/client.go index cc989f41bbb..051b80183cf 100644 --- a/pkg/secrets/keyvault/client.go +++ b/pkg/secrets/keyvault/client.go @@ -25,9 +25,9 @@ import ( "k8s.io/apimachinery/pkg/types" ) -func getVaultsClient() (mgmtclient.VaultsClient, error) { - vaultsClient := mgmtclient.NewVaultsClient(config.SubscriptionID()) - a, err := iam.GetResourceManagementAuthorizer() +func getVaultsClient(creds config.Credentials) (mgmtclient.VaultsClient, error) { + vaultsClient := mgmtclient.NewVaultsClient(creds.SubscriptionID()) + a, err := iam.GetResourceManagementAuthorizer(creds) if err != nil { return vaultsClient, err } @@ -59,10 +59,14 @@ func getVaultsURL(ctx context.Context, vaultName string) string { return vaultURL } -// New instantiates a new KeyVaultSecretClient instance -func New(keyvaultName string) *KeyvaultSecretClient { +// New instantiates a new KeyVaultSecretClient instance. +// TODO(creds-refactor): The keyvaultName argument seems seems +// redundant since that's in the credentials, but it's used to +// override the one specified in credentials so it might be right to +// keep it. Confirm this. +func New(keyvaultName string, creds config.Credentials) *KeyvaultSecretClient { keyvaultClient := keyvaults.New() - a, _ := iam.GetKeyvaultAuthorizer() + a, _ := iam.GetKeyvaultAuthorizer(creds) keyvaultClient.Authorizer = a keyvaultClient.AddToUserAgent(config.UserAgent()) return &KeyvaultSecretClient{ diff --git a/pkg/secrets/keyvault/client_test.go b/pkg/secrets/keyvault/client_test.go index bb46f579df2..fc130a58e04 100644 --- a/pkg/secrets/keyvault/client_test.go +++ b/pkg/secrets/keyvault/client_test.go @@ -34,7 +34,8 @@ var _ = Describe("Keyvault Secrets Client", func() { var resourcegroupLocation string var userID string - resourceGroupManager := rghelper.NewAzureResourceGroupManager() + resourceGroupManager := rghelper.NewAzureResourceGroupManager(config.GlobalCredentials()) + kvManager := kvhelper.NewAzureKeyVaultManager(config.GlobalCredentials(), nil) BeforeEach(func() { // Add any setup steps that needs to be executed before each test @@ -49,7 +50,7 @@ var _ = Describe("Keyvault Secrets Client", func() { retry = 1 * time.Second // Initialize service principal ID to give access to the keyvault - userID = config.ClientID() + userID = config.GlobalCredentials().ClientID() // Initialize resource names keyVaultName = "t-kvtest-kv" + strconv.FormatInt(GinkgoRandomSeed(), 10) @@ -68,7 +69,7 @@ var _ = Describe("Keyvault Secrets Client", func() { ).Should(BeTrue()) // Create a keyvault - _, err = kvhelper.AzureKeyVaultManager.CreateVaultWithAccessPolicies(ctx, resourcegroupName, keyVaultName, resourcegroupLocation, userID) + _, err = kvManager.CreateVaultWithAccessPolicies(ctx, resourcegroupName, keyVaultName, resourcegroupLocation, userID) //Expect(err).NotTo(HaveOccurred()) }) @@ -76,7 +77,7 @@ var _ = Describe("Keyvault Secrets Client", func() { AfterEach(func() { // Add any teardown steps that needs to be executed after each test // Delete the keyvault - kvhelper.AzureKeyVaultManager.DeleteVault(ctx, resourcegroupName, keyVaultName) + kvManager.DeleteVault(ctx, resourcegroupName, keyVaultName) //Expect(err).NotTo(HaveOccurred()) // Delete the resource group @@ -114,7 +115,7 @@ var _ = Describe("Keyvault Secrets Client", func() { "sweet": []byte("potato"), } - client := New(keyVaultName) + client := New(keyVaultName, config.GlobalCredentials()) key := types.NamespacedName{Name: secretName, Namespace: "default"} @@ -174,7 +175,7 @@ var _ = Describe("Keyvault Secrets Client", func() { "sweet": []byte("potato"), } - client := New(keyVaultName) + client := New(keyVaultName, config.GlobalCredentials()) key := types.NamespacedName{Name: secretName, Namespace: "default"}