/// <summary>
 /// Get the current storage account for the given subscription
 /// </summary>
 /// <param name="subscription">The subscription to check</param>
 /// <returns>The current storage accoutn in the subscription, or null if no current storage account is set</returns>
 public static string GetStorageAccount(this IAzureSubscription subscription)
 {
     return(subscription.GetProperty(AzureSubscription.Property.StorageAccount));
 }
 /// <summary>
 /// Creation and initialization of the ModelAdapter object
 /// </summary>
 /// <param name="subscription">The AzureSubscription in which the current execution is performed</param>
 /// <returns>An initialized and ready to use ModelAdapter object</returns>
 protected override SqlAuditAdapter InitModelAdapter(IAzureSubscription subscription)
 {
     return(new SqlAuditAdapter(DefaultProfile.DefaultContext));
 }
Пример #3
0
 /// <summary>
 /// Initializes the model adapter
 /// </summary>
 /// <param name="subscription">The subscription the cmdlets are operation under</param>
 /// <returns>The recommended index adapter</returns>
 protected override AzureSqlDatabaseIndexRecommendationAdapter InitModelAdapter(IAzureSubscription subscription)
 {
     return(new AzureSqlDatabaseIndexRecommendationAdapter(DefaultProfile.DefaultContext));
 }
Пример #4
0
 /// <summary>
 /// Initializes the adapter
 /// </summary>
 /// <param name="subscription">The subscription ID to operate on</param>
 /// <returns></returns>
 protected override AzureSqlDatabaseBackupAdapter InitModelAdapter(IAzureSubscription subscription)
 {
     return(new AzureSqlDatabaseBackupAdapter(DefaultProfile.DefaultContext));
 }
Пример #5
0
 /// <summary>
 /// Creation and initialization of the ModelAdapter object
 /// </summary>
 /// <param name="subscription">The AzureSubscription in which the current execution is performed</param>
 /// <returns>An initialized and ready to use ModelAdapter object</returns>
 protected override SqlVulnerabilityAssessmentAdapter InitModelAdapter(IAzureSubscription subscription)
 {
     return(new SqlVulnerabilityAssessmentAdapter(DefaultProfile.DefaultContext));
 }
 /// <summary>
 /// Init model adapter
 /// </summary>
 protected override AzureSqlServerDnsAliasAdapter InitModelAdapter(IAzureSubscription subscription)
 {
     return(new AzureSqlServerDnsAliasAdapter(DefaultProfile.DefaultContext));
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="PSRecoveryServicesClient" /> class with
 /// required current subscription.
 /// </summary>
 /// <param name="azureSubscription">Azure Subscription</param>
 public PSRecoveryServicesClient(AzureSMProfile AzureSMProfile, IAzureSubscription azureSubscription)
 {
     this.Profile = AzureSMProfile;
     this.recoveryServicesClient =
         AzureSession.Instance.ClientFactory.CreateClient <RecoveryServicesManagementClient>(AzureSMProfile, azureSubscription, AzureEnvironment.Endpoint.ServiceManagement);
 }
Пример #8
0
        private bool TryGetTenantSubscription(IAccessToken accessToken,
                                              IAzureAccount account,
                                              IAzureEnvironment environment,
                                              string tenantId,
                                              string subscriptionId,
                                              string subscriptionName,
                                              out IAzureSubscription subscription,
                                              out IAzureTenant tenant)
        {
            using (var subscriptionClient = AzureSession.Instance.ClientFactory.CreateCustomArmClient <SubscriptionClient>(
                       environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager),
                       new TokenCredentials(accessToken.AccessToken) as ServiceClientCredentials,
                       AzureSession.Instance.ClientFactory.GetCustomHandlers()))
            {
                Subscription subscriptionFromServer = null;

                try
                {
                    if (subscriptionId != null)
                    {
                        subscriptionFromServer = subscriptionClient.Subscriptions.Get(subscriptionId);
                    }
                    else
                    {
                        var subscriptions = (subscriptionClient.ListAllSubscriptions().ToList() ??
                                             new List <Subscription>())
                                            .Where(s => "enabled".Equals(s.State.ToString(), StringComparison.OrdinalIgnoreCase) ||
                                                   "warned".Equals(s.State.ToString(), StringComparison.OrdinalIgnoreCase));

                        account.SetProperty(AzureAccount.Property.Subscriptions, subscriptions.Select(i => i.SubscriptionId).ToArray());

                        if (subscriptions.Any())
                        {
                            if (subscriptionName != null)
                            {
                                subscriptionFromServer = subscriptions.FirstOrDefault(
                                    s => s.DisplayName.Equals(subscriptionName, StringComparison.OrdinalIgnoreCase));
                            }
                            else
                            {
                                if (subscriptions.Count() > 1)
                                {
                                    WriteWarningMessage(string.Format(
                                                            "TenantId '{0}' contains more than one active subscription. First one will be selected for further use. " +
                                                            "To select another subscription, use Set-AzContext.",
                                                            tenantId));
                                }
                                subscriptionFromServer = subscriptions.First();
                            }
                        }
                    }
                }
                catch (CloudException ex)
                {
                    WriteWarningMessage(ex.Message);
                }

                if (subscriptionFromServer != null)
                {
                    subscription = new AzureSubscription
                    {
                        Id    = subscriptionFromServer.SubscriptionId,
                        Name  = subscriptionFromServer.DisplayName,
                        State = subscriptionFromServer.State.ToString()
                    };

                    subscription.SetAccount(accessToken.UserId);
                    subscription.SetEnvironment(environment.Name);
                    subscription.SetTenant(accessToken.TenantId);

                    tenant    = new AzureTenant();
                    tenant.Id = accessToken.TenantId;
                    return(true);
                }

                subscription = null;

                if (accessToken != null && accessToken.TenantId != null)
                {
                    tenant    = new AzureTenant();
                    tenant.Id = accessToken.TenantId;
                    return(true);
                }

                tenant = null;
                return(false);
            }
        }
Пример #9
0
 /// <summary>
 /// Constructs a data sync adapter
 /// </summary>
 /// <param name="context">The current azure profile</param>
 public AzureSqlDataSyncAdapter(IAzureContext context)
 {
     Context       = context;
     _subscription = context.Subscription;
     Communicator  = new AzureSqlDataSyncCommunicator(Context);
 }
Пример #10
0
        public AzureRmProfile Login(
            IAzureAccount account,
            IAzureEnvironment environment,
            string tenantId,
            string subscriptionId,
            string subscriptionName,
            SecureString password,
            bool skipValidation,
            Action <string> promptAction,
            string name = null,
            bool shouldPopulateContextList = true)
        {
            IAzureSubscription newSubscription = null;
            IAzureTenant       newTenant       = null;
            string             promptBehavior  =
                (password == null &&
                 account.Type != AzureAccount.AccountType.AccessToken &&
                 account.Type != AzureAccount.AccountType.ManagedService &&
                 !account.IsPropertySet(AzureAccount.Property.CertificateThumbprint))
                ? ShowDialog.Always : ShowDialog.Never;

            if (skipValidation)
            {
                if (string.IsNullOrEmpty(subscriptionId) || string.IsNullOrEmpty(tenantId))
                {
                    throw new PSInvalidOperationException(Resources.SubscriptionOrTenantMissing);
                }

                newSubscription = new AzureSubscription
                {
                    Id = subscriptionId
                };

                newSubscription.SetOrAppendProperty(AzureSubscription.Property.Tenants, tenantId);
                newSubscription.SetOrAppendProperty(AzureSubscription.Property.Account, account.Id);

                newTenant = new AzureTenant
                {
                    Id = tenantId
                };
            }
            else
            {
                // (tenant and subscription are present) OR
                // (tenant is present and subscription is not provided)
                if (!string.IsNullOrEmpty(tenantId))
                {
                    Guid tempGuid = Guid.Empty;
                    if (!Guid.TryParse(tenantId, out tempGuid))
                    {
                        var tenant = ListAccountTenants(
                            account,
                            environment,
                            password,
                            promptBehavior,
                            promptAction)?.FirstOrDefault();
                        if (tenant == null || tenant.Id == null)
                        {
                            string baseMessage    = string.Format(ProfileMessages.TenantDomainNotFound, tenantId);
                            var    typeMessageMap = new Dictionary <string, string>
                            {
                                { AzureAccount.AccountType.ServicePrincipal, string.Format(ProfileMessages.ServicePrincipalTenantDomainNotFound, account.Id) },
                                { AzureAccount.AccountType.User, ProfileMessages.UserTenantDomainNotFound },
                                { AzureAccount.AccountType.ManagedService, ProfileMessages.MSITenantDomainNotFound }
                            };
                            string typeMessage = typeMessageMap.ContainsKey(account.Type) ? typeMessageMap[account.Type] : string.Empty;
                            throw new ArgumentNullException(string.Format("{0} {1}", baseMessage, typeMessage));
                        }

                        tenantId = tenant.Id;
                    }

                    var token = AcquireAccessToken(
                        account,
                        environment,
                        tenantId,
                        password,
                        promptBehavior,
                        promptAction);
                    if (TryGetTenantSubscription(
                            token,
                            account,
                            environment,
                            tenantId,
                            subscriptionId,
                            subscriptionName,
                            out newSubscription,
                            out newTenant))
                    {
                        account.SetOrAppendProperty(AzureAccount.Property.Tenants, new[] { newTenant.Id.ToString() });
                    }
                }
                // (tenant is not provided and subscription is present) OR
                // (tenant is not provided and subscription is not provided)
                else
                {
                    var tenants = ListAccountTenants(account, environment, password, promptBehavior, promptAction)
                                  .Select(s => s.Id.ToString()).ToList();
                    account.SetProperty(AzureAccount.Property.Tenants, null);
                    string accountId = null;

                    foreach (var tenant in tenants)
                    {
                        IAzureTenant       tempTenant;
                        IAzureSubscription tempSubscription;

                        IAccessToken token = null;

                        try
                        {
                            token = AcquireAccessToken(account, environment, tenant, password, ShowDialog.Auto, null);
                            if (accountId == null)
                            {
                                accountId = account.Id;
                                account.SetOrAppendProperty(AzureAccount.Property.Tenants, tenant);
                            }
                            else if (accountId.Equals(account.Id, StringComparison.OrdinalIgnoreCase))
                            {
                                account.SetOrAppendProperty(AzureAccount.Property.Tenants, tenant);
                            }
                            else
                            {   // if account ID is different from the first tenant account id we need to ignore current tenant
                                WriteWarningMessage(string.Format(
                                                        ProfileMessages.AccountIdMismatch,
                                                        account.Id,
                                                        tenant,
                                                        accountId));
                                account.Id = accountId;
                                token      = null;
                            }
                        }
                        catch
                        {
                            WriteWarningMessage(string.Format(ProfileMessages.UnableToAqcuireToken, tenant));
                        }

                        if (token != null &&
                            newTenant == null &&
                            TryGetTenantSubscription(token, account, environment, tenant, subscriptionId, subscriptionName, out tempSubscription, out tempTenant))
                        {
                            // If no subscription found for the given token/tenant
                            // discard tempTenant value unless current token/tenant is the last one.
                            if (tempSubscription != null || tenant.Equals(tenants[tenants.Count - 1]))
                            {
                                newTenant       = tempTenant;
                                newSubscription = tempSubscription;
                            }
                        }
                    }
                }
            }

            shouldPopulateContextList &= _profile.DefaultContext?.Account == null;
            if (newSubscription == null)
            {
                if (subscriptionId != null)
                {
                    throw new PSInvalidOperationException(String.Format(ResourceMessages.SubscriptionIdNotFound, account.Id, subscriptionId));
                }
                else if (subscriptionName != null)
                {
                    throw new PSInvalidOperationException(String.Format(ResourceMessages.SubscriptionNameNotFound, account.Id, subscriptionName));
                }

                var newContext = new AzureContext(account, environment, newTenant);
                if (!_profile.TrySetDefaultContext(name, newContext))
                {
                    WriteWarningMessage(string.Format(ProfileMessages.CannotSetDefaultContext, newContext.ToString()));
                }
            }
            else
            {
                var newContext = new AzureContext(newSubscription, account, environment, newTenant);
                if (!_profile.TrySetDefaultContext(name, newContext))
                {
                    WriteWarningMessage(string.Format(ProfileMessages.CannotSetDefaultContext, newContext.ToString()));
                }

                if (!skipValidation && !newSubscription.State.Equals("Enabled", StringComparison.OrdinalIgnoreCase))
                {
                    WriteWarningMessage(string.Format(
                                            ProfileMessages.SelectedSubscriptionNotActive,
                                            newSubscription.State));
                }
            }

            _profile.DefaultContext.TokenCache = _cache;
            if (shouldPopulateContextList)
            {
                var defaultContext = _profile.DefaultContext;
                var subscriptions  = ListSubscriptions(tenantId).Take(25);
                foreach (var subscription in subscriptions)
                {
                    IAzureTenant tempTenant = new AzureTenant()
                    {
                        Id = subscription.GetProperty(AzureSubscription.Property.Tenants)
                    };

                    var tempContext = new AzureContext(subscription, account, environment, tempTenant);
                    tempContext.TokenCache = _cache;
                    string tempName = null;
                    if (!_profile.TryGetContextName(tempContext, out tempName))
                    {
                        WriteWarningMessage(string.Format(Resources.CannotGetContextName, subscription.Id));
                        continue;
                    }

                    if (!_profile.TrySetContext(tempName, tempContext))
                    {
                        WriteWarningMessage(string.Format(Resources.CannotCreateContext, subscription.Id));
                    }
                }

                _profile.TrySetDefaultContext(defaultContext);
                _profile.TryRemoveContext("Default");
            }

            return(_profile.ToProfile());
        }
Пример #11
0
        public bool TryGetSubscriptionByName(string tenantId, string subscriptionName, out IAzureSubscription subscription)
        {
            IEnumerable <IAzureSubscription> subscriptionList = ListSubscriptions(tenantId);

            subscription = subscriptionList.FirstOrDefault(s => s.Name.Equals(subscriptionName, StringComparison.OrdinalIgnoreCase));

            return(subscription != null);
        }
 /// <summary>
 /// Constructs a database adapter
 /// </summary>
 /// <param name="profile">The current azure profile</param>
 /// <param name="subscription">The current azure subscription</param>
 public AzureSqlElasticPoolAdapter(IAzureContext context)
 {
     _subscription = context.Subscription;
     Context       = context;
     Communicator  = new AzureSqlElasticPoolCommunicator(Context);
 }
 /// <summary>
 /// Initializes the model adapter
 /// </summary>
 /// <param name="subscription">The subscription the cmdlets are operation under</param>
 /// <returns>The advisor adapter</returns>
 protected override AzureSqlServerRecommendedActionAdapter InitModelAdapter(IAzureSubscription subscription)
 {
     return(new AzureSqlServerRecommendedActionAdapter(DefaultProfile.DefaultContext));
 }
 /// <summary>
 /// Set the current storage account for the subscription
 /// </summary>
 /// <param name="subscription">The subscription to change</param>
 /// <param name="account">The connection string for the target storage account</param>
 public static void SetStorageAccount(this IAzureSubscription subscription, string account)
 {
     subscription.SetProperty(AzureSubscription.Property.StorageAccount, account);
 }
Пример #15
0
        public void NewAzureVMProcess()
        {
            IAzureSubscription  currentSubscription = Profile.Context.Subscription;
            CloudStorageAccount currentStorage      = null;

            try
            {
                currentStorage = Profile.Context.GetCurrentStorageAccount(
                    new RDFEStorageProvider(AzureSession.Instance.ClientFactory.CreateClient <StorageManagementClient>(
                                                Profile.Context, AzureEnvironment.Endpoint.ServiceManagement), Profile.Context.Environment));
            }
            catch (Exception ex) // couldn't access
            {
                throw new ArgumentException(Resources.CurrentStorageAccountIsNotAccessible, ex);
            }

            if (currentStorage == null) // not set
            {
                throw new ArgumentException(Resources.CurrentStorageAccountIsNotSet);
            }

            if (this.ParameterSetName.Equals("CreateService", StringComparison.OrdinalIgnoreCase))
            {
                var parameter = new HostedServiceCreateParameters
                {
                    AffinityGroup = this.AffinityGroup,
                    Location      = this.Location,
                    ServiceName   = this.ServiceName,
                    Description   = this.ServiceDescription ?? String.Format(
                        "Implicitly created hosted service{0}",
                        DateTime.Now.ToUniversalTime().ToString("yyyy-MM-dd HH:mm")),
                    Label          = this.ServiceLabel ?? this.ServiceName,
                    ReverseDnsFqdn = this.ReverseDnsFqdn
                };

                try
                {
                    this.ComputeClient.HostedServices.Create(parameter);
                }
                catch (CloudException ex)
                {
                    if (string.Equals(ex.Error.Code, "ConflictError"))
                    {
                        HostedServiceGetResponse existingService = this.ComputeClient.HostedServices.Get(this.ServiceName);

                        if (existingService == null || existingService.Properties == null)
                        {
                            // The same service name is already used by another subscription.
                            WriteExceptionError(ex);
                            return;
                        }
                        else if ((string.IsNullOrEmpty(existingService.Properties.Location) &&
                                  string.Compare(existingService.Properties.AffinityGroup, this.AffinityGroup, StringComparison.InvariantCultureIgnoreCase) == 0) ||
                                 (string.IsNullOrEmpty(existingService.Properties.AffinityGroup) &&
                                  string.Compare(existingService.Properties.Location, this.Location, StringComparison.InvariantCultureIgnoreCase) == 0))
                        {
                            // The same service name is already created under the same subscription,
                            // and its affinity group or location is matched with the given parameter.
                            this.WriteWarning(ex.Error.Message);
                        }
                        else
                        {
                            // The same service name is already created under the same subscription,
                            // but its affinity group or location is not matched with the given parameter.
                            this.WriteWarning("Location or AffinityGroup name is not matched with the existing service");
                            WriteExceptionError(ex);
                            return;
                        }
                    }
                    else
                    {
                        WriteExceptionError(ex);
                        return;
                    }
                }
            }

            foreach (var vm in from v in VMs let configuration = v.ConfigurationSets.OfType <Model.WindowsProvisioningConfigurationSet>().FirstOrDefault() where configuration != null select v)
            {
                if (vm.WinRMCertificate != null)
                {
                    if (!CertUtilsNewSM.HasExportablePrivateKey(vm.WinRMCertificate))
                    {
                        throw new ArgumentException(Resources.WinRMCertificateDoesNotHaveExportablePrivateKey);
                    }

                    var operationDescription = string.Format(Resources.AzureVMUploadingWinRMCertificate, CommandRuntime, vm.WinRMCertificate.Thumbprint);
                    var parameters           = CertUtilsNewSM.Create(vm.WinRMCertificate);

                    ExecuteClientActionNewSM(
                        null,
                        operationDescription,
                        () => this.ComputeClient.ServiceCertificates.Create(this.ServiceName, parameters),
                        (s, r) => ContextFactory <OperationStatusResponse, ManagementOperationContext>(r, s));
                }

                var certificateFilesWithThumbprint = from c in vm.X509Certificates
                                                     select new
                {
                    c.Thumbprint,
                    CertificateFile = CertUtilsNewSM.Create(c, vm.NoExportPrivateKey)
                };

                foreach (var current in certificateFilesWithThumbprint.ToList())
                {
                    var operationDescription = string.Format(Resources.AzureVMCommandUploadingCertificate, CommandRuntime, current.Thumbprint);
                    ExecuteClientActionNewSM(
                        null,
                        operationDescription,
                        () => this.ComputeClient.ServiceCertificates.Create(this.ServiceName, current.CertificateFile),
                        (s, r) => ContextFactory <OperationStatusResponse, ManagementOperationContext>(r, s));
                }
            }

            var persistentVMs = this.VMs.Select((vm, index) => CreatePersistentVMRole(VMTuples[index], currentStorage)).ToList();

            // If the current deployment doesn't exist set it create it
            if (CurrentDeploymentNewSM == null)
            {
                try
                {
                    var parameters = new VirtualMachineCreateDeploymentParameters
                    {
                        DeploymentSlot     = DeploymentSlot.Production,
                        Name               = this.DeploymentName ?? this.ServiceName,
                        Label              = this.DeploymentLabel ?? this.ServiceName,
                        VirtualNetworkName = this.VNetName,
                        Roles              = { persistentVMs[0] },
                        ReservedIPName     = ReservedIPName
                    };

                    if (this.DnsSettings != null)
                    {
                        parameters.DnsSettings = new Management.Compute.Models.DnsSettings();

                        foreach (var dns in this.DnsSettings)
                        {
                            parameters.DnsSettings.DnsServers.Add(
                                new Microsoft.WindowsAzure.Management.Compute.Models.DnsServer
                            {
                                Name    = dns.Name,
                                Address = dns.Address
                            });
                        }
                    }

                    if (this.InternalLoadBalancerConfig != null)
                    {
                        parameters.LoadBalancers = new LoadBalancer[1]
                        {
                            new LoadBalancer
                            {
                                Name = this.InternalLoadBalancerConfig.InternalLoadBalancerName,
                                FrontendIPConfiguration = new FrontendIPConfiguration
                                {
                                    Type       = FrontendIPConfigurationType.Private,
                                    SubnetName = this.InternalLoadBalancerConfig.SubnetName,
                                    StaticVirtualNetworkIPAddress = this.InternalLoadBalancerConfig.IPAddress
                                }
                            }
                        };
                    }

                    var operationDescription = string.Format(Resources.AzureVMCommandCreateDeploymentWithVM, CommandRuntime, persistentVMs[0].RoleName);
                    ExecuteClientActionNewSM(
                        parameters,
                        operationDescription,
                        () => this.ComputeClient.VirtualMachines.CreateDeployment(this.ServiceName, parameters));

                    if (this.WaitForBoot.IsPresent)
                    {
                        WaitForRoleToBoot(persistentVMs[0].RoleName);
                    }
                }
                catch (CloudException ex)
                {
                    if (ex.Response.StatusCode == HttpStatusCode.NotFound)
                    {
                        throw new Exception(Resources.ServiceDoesNotExistSpecifyLocationOrAffinityGroup);
                    }
                    else
                    {
                        WriteExceptionError(ex);
                    }

                    return;
                }

                this.createdDeployment = true;
            }
            else
            {
                if (this.VNetName != null || this.DnsSettings != null || !string.IsNullOrEmpty(this.DeploymentLabel) || !string.IsNullOrEmpty(this.DeploymentName))
                {
                    WriteWarning(Resources.VNetNameDnsSettingsDeploymentLabelDeploymentNameCanBeSpecifiedOnNewDeployments);
                }
            }

            if (this.createdDeployment == false && CurrentDeploymentNewSM != null)
            {
                this.DeploymentName = CurrentDeploymentNewSM.Name;
            }

            int startingVM = this.createdDeployment ? 1 : 0;

            for (int i = startingVM; i < persistentVMs.Count; i++)
            {
                var operationDescription = string.Format(Resources.AzureVMCommandCreateVM, CommandRuntime, persistentVMs[i].RoleName);

                var parameter = new VirtualMachineCreateParameters
                {
                    AvailabilitySetName         = persistentVMs[i].AvailabilitySetName,
                    OSVirtualHardDisk           = VMTuples[i].Item3 ? null : persistentVMs[i].OSVirtualHardDisk,
                    RoleName                    = persistentVMs[i].RoleName,
                    RoleSize                    = persistentVMs[i].RoleSize,
                    ProvisionGuestAgent         = persistentVMs[i].ProvisionGuestAgent,
                    ResourceExtensionReferences = persistentVMs[i].ProvisionGuestAgent != null && persistentVMs[i].ProvisionGuestAgent.Value ? persistentVMs[i].ResourceExtensionReferences : null,
                    VMImageName                 = VMTuples[i].Item3 ? persistentVMs[i].VMImageName : null,
                    MediaLocation               = VMTuples[i].Item3 ? persistentVMs[i].MediaLocation : null,
                    LicenseType                 = persistentVMs[i].LicenseType
                };

                if (parameter.OSVirtualHardDisk != null)
                {
                    parameter.OSVirtualHardDisk.IOType = null;
                }

                if (persistentVMs[i].DataVirtualHardDisks != null && persistentVMs[i].DataVirtualHardDisks.Any())
                {
                    persistentVMs[i].DataVirtualHardDisks.ForEach(c => parameter.DataVirtualHardDisks.Add(c));
                    parameter.DataVirtualHardDisks.ForEach(d => d.IOType = null);
                }

                persistentVMs[i].ConfigurationSets.ForEach(c => parameter.ConfigurationSets.Add(c));

                ExecuteClientActionNewSM(
                    persistentVMs[i],
                    operationDescription,
                    () => this.ComputeClient.VirtualMachines.Create(this.ServiceName, this.DeploymentName ?? this.ServiceName, parameter));
            }

            if (this.WaitForBoot.IsPresent)
            {
                for (int i = startingVM; i < persistentVMs.Count; i++)
                {
                    WaitForRoleToBoot(persistentVMs[i].RoleName);
                }
            }
        }
 /// <summary>
 /// Constructs a database adapter
 /// </summary>
 /// <param name="profile">The current azure profile</param>
 /// <param name="subscription">The current azure subscription</param>
 public AzureSqlFailoverGroupAdapter(IAzureContext context)
 {
     _subscription = context?.Subscription;
     Context       = context;
     Communicator  = new AzureSqlFailoverGroupCommunicator(Context);
 }
Пример #17
0
        /// <summary>
        /// Method to execute the command
        /// </summary>
        private void GetSiteRecoveryCredentials()
        {
            IAzureSubscription subscription = DefaultProfile.DefaultContext.Subscription;

            // Generate certificate
            X509Certificate2 cert = CertUtils.CreateSelfSignedCertificate(
                VaultCertificateExpiryInHoursForHRM,
                subscription.Id.ToString(),
                this.Vault.Name);

            ASRSite site = new ASRSite();

            if (!string.IsNullOrEmpty(this.SiteIdentifier) &&
                !string.IsNullOrEmpty(this.SiteFriendlyName))
            {
                site.ID   = this.SiteIdentifier;
                site.Name = this.SiteFriendlyName;
            }

            string fileName = this.GenerateFileName();

            string filePath = string.IsNullOrEmpty(this.Path) ? Utilities.GetDefaultPath() : this.Path;

            // Generate file.
            if (RecoveryServicesClient.getVaultAuthType(this.Vault.ResourceGroupName, this.Vault.Name) == 0)
            {
                ASRVaultCreds vaultCreds = RecoveryServicesClient.GenerateVaultCredential(
                    cert,
                    this.Vault,
                    site,
                    AuthType.ACS);

                // write the content to a file.
                VaultSettingsFilePath output = new VaultSettingsFilePath()
                {
                    FilePath = Utilities.WriteToFile <ASRVaultCreds>(vaultCreds, filePath, fileName)
                };

                // print the path to the user.
                this.WriteObject(output, true);
            }
            else
            {
                string fullFilePath = System.IO.Path.Combine(filePath, fileName);
                WriteDebug(
                    string.Format(
                        CultureInfo.InvariantCulture,
                        Resources.ExecutingGetVaultCredCmdlet,
                        subscription.Id,
                        this.Vault.ResourceGroupName,
                        this.Vault.Name,
                        fullFilePath));

                VaultCertificateResponse vaultCertificateResponse = null;
                try
                {
                    // Upload cert into ID Mgmt
                    WriteDebug(string.Format(CultureInfo.InvariantCulture, Resources.UploadingCertToIdmgmt));
                    vaultCertificateResponse = UploadCert(cert);
                    WriteDebug(string.Format(CultureInfo.InvariantCulture, Resources.UploadedCertToIdmgmt));

                    // generate vault credentials
                    string vaultCredsFileContent = GenerateVaultCredsForSiteRecovery(
                        cert,
                        subscription.Id,
                        vaultCertificateResponse,
                        site);

                    WriteDebug(string.Format(Resources.SavingVaultCred, fullFilePath));

                    AzureSession.Instance.DataStore.WriteFile(fullFilePath, Encoding.UTF8.GetBytes(vaultCredsFileContent));

                    VaultSettingsFilePath output = new VaultSettingsFilePath()
                    {
                        FilePath = fullFilePath,
                    };

                    // Output filename back to user
                    WriteObject(output, true);
                }
                catch (Exception exception)
                {
                    throw exception;
                }
            }
        }
Пример #18
0
 /// <summary>
 /// Copy constructor
 /// </summary>
 /// <param name="other">Environment to copy from</param>
 public PSAzureSubscription(IAzureSubscription other)
 {
     this.CopyFrom(other);
 }
Пример #19
0
 public AEMHelper(Action <ErrorRecord> errorAction, Action <string> verboseAction, Action <string> warningAction,
                  PSHostUserInterface ui, StorageManagementClient storageClient, IAzureSubscription subscription, String storageEndpoint)
 {
     this._ErrorAction     = errorAction;
     this._VerboseAction   = verboseAction;
     this._WarningAction   = warningAction;
     this._UI              = ui;
     this._StorageClient   = storageClient;
     this._Subscription    = subscription;
     this._StorageEndpoint = storageEndpoint;
 }
Пример #20
0
        /// <summary>
        /// Creates the client.
        /// </summary>
        /// <typeparam name="TClient">The type of the client.</typeparam>
        /// <param name="profile">The profile.</param>
        /// <param name="subscription">The subscription.</param>
        /// <param name="endpoint">The endpoint.</param>
        /// <returns></returns>
        /// <exception cref="System.ApplicationException"></exception>
        /// <exception cref="System.ArgumentException">
        /// accountName
        /// or
        /// environment
        /// </exception>
        public virtual TClient CreateClient <TClient>(IAzureContextContainer profile, IAzureSubscription subscription, string endpoint) where TClient : ServiceClient <TClient>
        {
            if (subscription == null)
            {
                throw new AzPSApplicationException(Resources.InvalidDefaultSubscription, ErrorKind.UserError);
            }

            var account = profile.Accounts.FirstOrDefault((a) => string.Equals(a.Id, (subscription.GetAccount()), StringComparison.OrdinalIgnoreCase));

            if (null == account)
            {
                throw new AzPSArgumentException(string.Format("Account with name '{0}' does not exist.", subscription.GetAccount()), "accountName", ErrorKind.UserError);
            }

            var environment = profile.Environments.FirstOrDefault((e) => string.Equals(e.Name, subscription.GetEnvironment(), StringComparison.OrdinalIgnoreCase));

            if (null == environment)
            {
                throw new AzPSArgumentException(string.Format(Resources.EnvironmentNotFound, subscription.GetEnvironment()), "environment", ErrorKind.UserError);
            }

            AzureContext context = new AzureContext(subscription, account, environment);

            var client = CreateClient <TClient>(context, endpoint);

            foreach (IClientAction action in GetActions())
            {
                action.Apply <TClient>(client, profile, endpoint);
            }

            return(client);
        }
 /// <summary>
 /// Creation and initialization of the ModelAdapter object
 /// </summary>
 /// <param name="subscription">The AzureSubscription in which the current execution is performed</param>
 /// <returns>An initialized and ready to use ModelAdapter object</returns>
 protected abstract A InitModelAdapter(IAzureSubscription subscription);
Пример #22
0
 /// <summary>
 /// Constructs a database backup adapter
 /// </summary>
 /// <param name="profile">The current azure profile</param>
 /// <param name="subscription">The current azure subscription</param>
 public AzureSqlDatabaseBackupAdapter(IAzureContext context)
 {
     Context       = context;
     _subscription = context?.Subscription;
     Communicator  = new AzureSqlDatabaseBackupCommunicator(Context);
 }
Пример #23
0
 /// <summary>
 /// Intializes the model adapter
 /// </summary>
 /// <param name="subscription">The subscription the cmdlets are operation under</param>
 /// <returns>The server adapter</returns>
 protected override AzureSqlDatabaseTransparentDataEncryptionAdapter InitModelAdapter(IAzureSubscription subscription)
 {
     return(new AzureSqlDatabaseTransparentDataEncryptionAdapter(DefaultProfile.DefaultContext));
 }
Пример #24
0
 /// <summary>
 /// Initializes the adapter
 /// </summary>
 /// <param name="subscription"></param>
 /// <returns></returns>
 protected override AzureSqlServerDisasterRecoveryConfigurationAdapter InitModelAdapter(IAzureSubscription subscription)
 {
     return(new AzureSqlServerDisasterRecoveryConfigurationAdapter(DefaultProfile.DefaultContext));
 }
Пример #25
0
 public static IHDInsightSubscriptionCredentials GetSubscriptionCertificateCredentials(this IAzureHDInsightCommonCommandBase command,
                                                                                       IAzureSubscription currentSubscription, IAzureAccount azureAccount, IAzureEnvironment environment)
 {
     return(new HDInsightCertificateCredential
     {
         SubscriptionId = currentSubscription.GetId(),
         Certificate = AzureSession.Instance.DataStore.GetCertificate(currentSubscription.GetAccount()),
         Endpoint = environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ServiceManagement),
     });
 }
 /// <summary>
 /// Constructs a managed database adapter
 /// </summary>
 /// <param name="profile">The current azure profile</param>
 /// <param name="subscription">The current azure subscription</param>
 public AzureSqlManagedDatabaseAdapter(IAzureContext context)
 {
     Context       = context;
     _subscription = context.Subscription;
     Communicator  = new AzureSqlManagedDatabaseCommunicator(Context);
 }
 /// <summary>
 /// Intializes the model adapter
 /// </summary>
 /// <param name="subscription">The subscription the cmdlets are operation under</param>
 /// <returns>The server adapter</returns>
 protected ImportExportDatabaseAdapter InitModelAdapter(IAzureSubscription subscription)
 {
     return(new ImportExportDatabaseAdapter(DefaultProfile.DefaultContext));
 }
Пример #28
0
 public StorageCredentialsFactory(string resourceGroupName, StorageManagementClient client, IAzureSubscription currentSubscription)
 {
     this.resourceGroupName   = resourceGroupName;
     this.client              = client;
     this.currentSubscription = currentSubscription;
 }
 /// <summary>
 /// Initializes the adapter
 /// </summary>
 /// <param name="subscription"></param>
 /// <returns></returns>
 protected override AzureSqlElasticPoolRecommendationAdapter InitModelAdapter(IAzureSubscription subscription)
 {
     return(new AzureSqlElasticPoolRecommendationAdapter(DefaultProfile.DefaultContext));
 }
 /// <summary>
 /// Set the environment for the subscription
 /// </summary>
 /// <param name="subscription">The subscription to change</param>
 /// <param name="environment">The environment containing the subscription</param>
 public static void SetEnvironment(this IAzureSubscription subscription, string environment)
 {
     subscription.SetProperty(AzureSubscription.Property.Environment, environment);
 }