示例#1
0
        /// <summary>
        /// Create a new vault
        /// </summary>
        /// <param name="parameters">vault creation parameters</param>
        /// <param name="adClient">the active directory client</param>
        /// <returns></returns>
        public PSKeyVault CreateNewVault(VaultCreationParameters parameters, ActiveDirectoryClient adClient = null)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            if (string.IsNullOrWhiteSpace(parameters.VaultName))
            {
                throw new ArgumentNullException("parameters.VaultName");
            }
            if (string.IsNullOrWhiteSpace(parameters.ResourceGroupName))
            {
                throw new ArgumentNullException("parameters.ResourceGroupName");
            }
            if (string.IsNullOrWhiteSpace(parameters.Location))
            {
                throw new ArgumentNullException("parameters.Location");
            }

            var properties = new VaultProperties();

            if (parameters.CreateMode != CreateMode.Recover)
            {
                if (string.IsNullOrWhiteSpace(parameters.SkuFamilyName))
                {
                    throw new ArgumentNullException("parameters.SkuFamilyName");
                }
                if (parameters.TenantId == null || parameters.TenantId == Guid.Empty)
                {
                    throw new ArgumentException("parameters.TenantId");
                }

                properties.Sku = new Sku
                {
                    Name = parameters.SkuName,
                };
                properties.EnabledForDeployment         = parameters.EnabledForDeployment;
                properties.EnabledForTemplateDeployment = parameters.EnabledForTemplateDeployment;
                properties.EnabledForDiskEncryption     = parameters.EnabledForDiskEncryption;
                properties.EnableSoftDelete             = parameters.EnableSoftDelete ? true : (bool?)null;
                properties.TenantId       = parameters.TenantId;
                properties.VaultUri       = "";
                properties.AccessPolicies = (parameters.AccessPolicy != null) ? new[] { parameters.AccessPolicy } : new AccessPolicyEntry[] { };
            }
            else
            {
                properties.CreateMode = CreateMode.Recover;
            }
            var response = this.KeyVaultManagementClient.Vaults.CreateOrUpdate(
                resourceGroupName: parameters.ResourceGroupName,
                vaultName: parameters.VaultName,

                parameters: new VaultCreateOrUpdateParameters()
            {
                Location   = parameters.Location,
                Tags       = TagsConversionHelper.CreateTagDictionary(parameters.Tags, validate: true),
                Properties = properties
            });

            return(new PSKeyVault(response, adClient));
        }
        public override void ExecuteCmdlet()
        {
            if (this.IsParameterBound(c => c.WorkspaceObject))
            {
                this.ResourceGroupName = new ResourceIdentifier(this.WorkspaceObject.Id).ResourceGroupName;
                this.WorkspaceName     = this.WorkspaceObject.Name;
            }

            if (this.IsParameterBound(c => c.InputObject))
            {
                var resourceIdentifier = new ResourceIdentifier(this.InputObject.Id);
                this.ResourceGroupName = resourceIdentifier.ResourceGroupName;
                this.WorkspaceName     = resourceIdentifier.ParentResource;
                this.WorkspaceName     = this.WorkspaceName.Substring(this.WorkspaceName.LastIndexOf('/') + 1);
                this.Name = this.InputObject.Name;
            }

            if (this.IsParameterBound(c => c.ResourceId))
            {
                var resourceIdentifier = new ResourceIdentifier(this.ResourceId);
                this.ResourceGroupName = resourceIdentifier.ResourceGroupName;
                this.WorkspaceName     = resourceIdentifier.ParentResource;
                this.WorkspaceName     = this.WorkspaceName.Substring(this.WorkspaceName.LastIndexOf('/') + 1);
                this.Name = resourceIdentifier.ResourceName;
            }

            if (string.IsNullOrEmpty(this.ResourceGroupName))
            {
                this.ResourceGroupName = this.SynapseAnalyticsClient.GetResourceGroupByWorkspaceName(this.WorkspaceName);
            }

            BigDataPoolResourceInfo existingSparkPool = null;

            try
            {
                existingSparkPool = this.SynapseAnalyticsClient.GetSparkPool(this.ResourceGroupName, this.WorkspaceName, this.Name);
            }
            catch
            {
                existingSparkPool = null;
            }

            if (existingSparkPool == null)
            {
                throw new SynapseException(string.Format(Resources.FailedToDiscoverSparkPool, this.Name, this.ResourceGroupName, this.WorkspaceName));
            }

            existingSparkPool.Tags                = this.IsParameterBound(c => c.Tag) ? TagsConversionHelper.CreateTagDictionary(this.Tag, validate: true) : existingSparkPool.Tags;
            existingSparkPool.NodeCount           = this.IsParameterBound(c => c.NodeCount) ? this.NodeCount : existingSparkPool.NodeCount;
            existingSparkPool.NodeSizeFamily      = NodeSizeFamily.MemoryOptimized;
            existingSparkPool.NodeSize            = this.IsParameterBound(c => c.NodeSize) ? this.NodeSize : existingSparkPool.NodeSize;
            existingSparkPool.LibraryRequirements = this.IsParameterBound(c => c.LibraryRequirementsFilePath) ? CreateLibraryRequirements() : existingSparkPool.LibraryRequirements;

            if (this.IsParameterBound(c => c.EnableAutoScale) ||
                this.IsParameterBound(c => c.AutoScaleMinNodeCount) ||
                this.IsParameterBound(c => c.AutoScaleMaxNodeCount))
            {
                existingSparkPool.AutoScale = new AutoScaleProperties
                {
                    Enabled      = this.EnableAutoScale != null ? this.EnableAutoScale : existingSparkPool.AutoScale?.Enabled ?? false,
                    MinNodeCount = this.IsParameterBound(c => c.AutoScaleMinNodeCount) ? AutoScaleMinNodeCount : existingSparkPool.AutoScale?.MinNodeCount ?? 0,
                    MaxNodeCount = this.IsParameterBound(c => c.AutoScaleMaxNodeCount) ? AutoScaleMaxNodeCount : existingSparkPool.AutoScale?.MaxNodeCount ?? 0
                };
            }

            if (this.IsParameterBound(c => c.EnableAutoPause) ||
                this.IsParameterBound(c => c.AutoPauseDelayInMinute))
            {
                existingSparkPool.AutoPause = new AutoPauseProperties
                {
                    Enabled        = this.EnableAutoPause != null ? this.EnableAutoPause : existingSparkPool.AutoPause?.Enabled ?? false,
                    DelayInMinutes = this.IsParameterBound(c => c.AutoPauseDelayInMinute)
                        ? this.AutoPauseDelayInMinute
                        : existingSparkPool.AutoPause?.DelayInMinutes ?? 0
                };
            }

            if (this.ShouldProcess(this.Name, string.Format(Resources.UpdatingSynapseSparkPool, this.Name, this.ResourceGroupName, this.WorkspaceName)))
            {
                var result = new PSSynapseSparkPool(this.SynapseAnalyticsClient.CreateOrUpdateSparkPool(this.ResourceGroupName, this.WorkspaceName, this.Name, existingSparkPool));
                WriteObject(result);
            }
        }
示例#3
0
        public override void Execute()
        {
            base.Execute();

            if (this.IsParameterBound(c => c.ResourceId))
            {
                var resourceIdentifier = new ResourceIdentifier(this.ResourceId);
                this.ResourceGroupName = resourceIdentifier.ResourceGroupName;
                this.Name = resourceIdentifier.ResourceName;
            }

            var present = true;

            try
            {
                if (this.InputObject == null)
                {
                    var natGateway = this.NetworkClient.NetworkManagementClient.NatGateways.Get(this.ResourceGroupName, this.Name);
                    this.InputObject = NetworkResourceManagerProfile.Mapper.Map <PSNatGateway>(natGateway);
                    this.InputObject.ResourceGroupName = this.ResourceGroupName;
                    this.InputObject.Name = this.Name;
                }
                this.NetworkClient.NetworkManagementClient.NatGateways.Get(this.InputObject.ResourceGroupName, this.InputObject.Name);
            }
            catch (Microsoft.Rest.Azure.CloudException exception)
            {
                if (exception.Response.StatusCode == HttpStatusCode.NotFound)
                {
                    // Resource is not present
                    present = false;
                }
                else
                {
                    throw;
                }
            }

            if (!present)
            {
                throw new ArgumentException(Microsoft.Azure.Commands.Network.Properties.Resources.ResourceNotFound);
            }

            // PublicIpAddresses
            List <PSResourceId> vPublicIpAddresses = null;

            // PublicIpPrefixes
            List <PSResourceId> vPublicIpPrefixes = null;

            if (this.IdleTimeoutInMinutes > 0)
            {
                this.InputObject.IdleTimeoutInMinutes = this.IdleTimeoutInMinutes;
            }

            if (this.PublicIpAddress != null)
            {
                vPublicIpAddresses = this.PublicIpAddress?.ToList();
                this.InputObject.PublicIpAddresses = vPublicIpAddresses;
            }

            if (this.PublicIpPrefix != null)
            {
                vPublicIpPrefixes = this.PublicIpPrefix?.ToList();
                this.InputObject.PublicIpPrefixes = vPublicIpPrefixes;
            }

            // Map to the sdk object
            var vNatGatewayModel = NetworkResourceManagerProfile.Mapper.Map <MNM.NatGateway>(this.InputObject);

            vNatGatewayModel.Tags = TagsConversionHelper.CreateTagDictionary(this.InputObject.Tag, validate: true);

            // Execute the PUT NatGateway call
            this.NetworkClient.NetworkManagementClient.NatGateways.CreateOrUpdate(this.InputObject.ResourceGroupName, this.InputObject.Name, vNatGatewayModel);

            var getNatGateway = this.NetworkClient.NetworkManagementClient.NatGateways.Get(this.InputObject.ResourceGroupName, this.InputObject.Name);
            var psNatGateway  = NetworkResourceManagerProfile.Mapper.Map <PSNatGateway>(getNatGateway);

            psNatGateway.ResourceGroupName = this.InputObject.ResourceGroupName;
            psNatGateway.Tag = TagsConversionHelper.CreateTagHashtable(getNatGateway.Tags);
            WriteObject(psNatGateway, true);
        }
        private PSAzureFirewallPolicy CreateAzureFirewallPolicy()
        {
            var firewallPolicy = new PSAzureFirewallPolicy()
            {
                Name = this.Name,
                ResourceGroupName    = this.ResourceGroupName,
                Location             = this.Location,
                ThreatIntelMode      = this.ThreatIntelMode ?? MNM.AzureFirewallThreatIntelMode.Alert,
                ThreatIntelWhitelist = this.ThreatIntelWhitelist,
                BasePolicy           = BasePolicy != null ? new Microsoft.Azure.Management.Network.Models.SubResource(BasePolicy) : null,
                DnsSettings          = this.DnsSetting,
                Sku = new PSAzureFirewallPolicySku {
                    Tier = this.SkuTier ?? MNM.FirewallPolicySkuTier.Standard
                },
                IntrusionDetection = this.IntrusionDetection,
                PrivateRange       = this.PrivateRange
            };

            if (this.UserAssignedIdentityId != null)
            {
                firewallPolicy.Identity = new PSManagedServiceIdentity
                {
                    Type = MNM.ResourceIdentityType.UserAssigned,
                    UserAssignedIdentities = new Dictionary <string, PSManagedServiceIdentityUserAssignedIdentitiesValue>
                    {
                        { this.UserAssignedIdentityId, new PSManagedServiceIdentityUserAssignedIdentitiesValue() }
                    }
                };
            }
            else if (this.Identity != null)
            {
                firewallPolicy.Identity = this.Identity;
            }

            if (this.TransportSecurityKeyVaultSecretId != null)
            {
                if (this.TransportSecurityName == null)
                {
                    throw new ArgumentException("TransportSecurityName must be provided with TransportSecurityKeyVaultSecretId");
                }

                if (this.Identity == null && this.UserAssignedIdentityId == null)
                {
                    throw new ArgumentException("Identity must be provided with TransportSecurityKeyVaultSecretId");
                }

                firewallPolicy.TransportSecurity = new PSAzureFirewallPolicyTransportSecurity
                {
                    CertificateAuthority = new PSAzureFirewallPolicyTransportSecurityCertificateAuthority
                    {
                        Name             = this.TransportSecurityName,
                        KeyVaultSecretId = this.TransportSecurityKeyVaultSecretId
                    }
                };
            }

            // Map to the sdk object
            var azureFirewallPolicyModel = NetworkResourceManagerProfile.Mapper.Map <MNM.FirewallPolicy>(firewallPolicy);

            azureFirewallPolicyModel.Tags = TagsConversionHelper.CreateTagDictionary(this.Tag, validate: true);

            // Execute the Create AzureFirewall call
            this.AzureFirewallPolicyClient.CreateOrUpdate(this.ResourceGroupName, this.Name, azureFirewallPolicyModel);
            return(this.GetAzureFirewallPolicy(this.ResourceGroupName, this.Name));
        }
示例#5
0
        private PSLoadBalancer CreateLoadBalancer()
        {
            var loadBalancer = new PSLoadBalancer();

            loadBalancer.Name = this.Name;
            loadBalancer.ResourceGroupName = this.ResourceGroupName;
            loadBalancer.Location          = this.Location;

            if (!string.IsNullOrEmpty(this.Sku))
            {
                loadBalancer.Sku      = new PSLoadBalancerSku();
                loadBalancer.Sku.Name = this.Sku;
            }

            if (this.FrontendIpConfiguration != null)
            {
                loadBalancer.FrontendIpConfigurations = this.FrontendIpConfiguration;
            }

            if (this.BackendAddressPool != null)
            {
                loadBalancer.BackendAddressPools = this.BackendAddressPool;
            }

            if (this.Probe != null)
            {
                loadBalancer.Probes = this.Probe;
            }

            if (this.InboundNatRule != null)
            {
                loadBalancer.InboundNatRules = this.InboundNatRule;
            }

            if (this.LoadBalancingRule != null)
            {
                loadBalancer.LoadBalancingRules = this.LoadBalancingRule;
            }

            if (this.InboundNatPool != null)
            {
                loadBalancer.InboundNatPools = this.InboundNatPool;
            }

            loadBalancer.ResourceGroupName = this.ResourceGroupName;
            loadBalancer.Name = this.Name;

            // Normalize the IDs
            ChildResourceHelper.NormalizeChildResourcesId(loadBalancer, this.NetworkClient.NetworkManagementClient.SubscriptionId);

            // Map to the sdk object
            var lbModel = NetworkResourceManagerProfile.Mapper.Map <MNM.LoadBalancer>(loadBalancer);

            lbModel.Tags = TagsConversionHelper.CreateTagDictionary(this.Tag, validate: true);

            // Execute the Create VirtualNetwork call
            this.LoadBalancerClient.CreateOrUpdate(this.ResourceGroupName, this.Name, lbModel);

            var getLoadBalancer = this.GetLoadBalancer(this.ResourceGroupName, this.Name);

            return(getLoadBalancer);
        }
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();

            CheckNameAvailabilityResult checkNameAvailabilityResult = this.StorageClient.StorageAccounts.CheckNameAvailability(this.Name);

            if (!checkNameAvailabilityResult.NameAvailable.Value)
            {
                throw new System.ArgumentException(checkNameAvailabilityResult.Message, "Name");
            }

            StorageAccountCreateParameters createParameters = new StorageAccountCreateParameters()
            {
                Location = this.Location,
                Sku      = new Sku(this.SkuName),
                Tags     = TagsConversionHelper.CreateTagDictionary(Tag, validate: true),
            };

            if (this.CustomDomainName != null)
            {
                createParameters.CustomDomain = new CustomDomain()
                {
                    Name             = CustomDomainName,
                    UseSubDomainName = UseSubDomain
                };
            }
            else if (UseSubDomain != null)
            {
                throw new System.ArgumentException(string.Format("UseSubDomain must be set together with CustomDomainName."));
            }

            if (kind != null)
            {
                createParameters.Kind = kind;
            }

            if (this.AccessTier != null)
            {
                createParameters.AccessTier = ParseAccessTier(AccessTier);
            }
            if (enableHttpsTrafficOnly != null)
            {
                createParameters.EnableHttpsTrafficOnly = enableHttpsTrafficOnly;
            }

            if (AssignIdentity.IsPresent || this.UserAssignedIdentityId != null || this.IdentityType != null)
            {
                createParameters.Identity = new Identity()
                {
                    Type = StorageModels.IdentityType.SystemAssigned
                };
                if (this.IdentityType != null)
                {
                    createParameters.Identity.Type = GetIdentityTypeString(this.IdentityType);
                }
                if (this.UserAssignedIdentityId != null)
                {
                    if (createParameters.Identity.Type != StorageModels.IdentityType.UserAssigned && createParameters.Identity.Type != StorageModels.IdentityType.SystemAssignedUserAssigned)
                    {
                        throw new ArgumentException("UserAssignIdentityId should only be specified when AssignIdentityType is UserAssigned or SystemAssignedUserAssigned.", "UserAssignIdentityId");
                    }
                    createParameters.Identity.UserAssignedIdentities = new Dictionary <string, UserAssignedIdentity>();
                    createParameters.Identity.UserAssignedIdentities.Add(this.UserAssignedIdentityId, new UserAssignedIdentity());
                }
            }
            if (NetworkRuleSet != null)
            {
                createParameters.NetworkRuleSet = PSNetworkRuleSet.ParseStorageNetworkRule(NetworkRuleSet);
            }
            if (enableHierarchicalNamespace != null)
            {
                createParameters.IsHnsEnabled = enableHierarchicalNamespace;
            }
            if (enableAzureActiveDirectoryDomainServicesForFile != null || enableActiveDirectoryDomainServicesForFile != null)
            {
                createParameters.AzureFilesIdentityBasedAuthentication = new AzureFilesIdentityBasedAuthentication();
                if (enableAzureActiveDirectoryDomainServicesForFile != null && enableAzureActiveDirectoryDomainServicesForFile.Value)
                {
                    createParameters.AzureFilesIdentityBasedAuthentication.DirectoryServiceOptions = DirectoryServiceOptions.AADDS;
                }
                else if (enableActiveDirectoryDomainServicesForFile != null && enableActiveDirectoryDomainServicesForFile.Value)
                {
                    if (string.IsNullOrEmpty(this.ActiveDirectoryDomainName) ||
                        string.IsNullOrEmpty(this.ActiveDirectoryNetBiosDomainName) ||
                        string.IsNullOrEmpty(this.ActiveDirectoryForestName) ||
                        string.IsNullOrEmpty(this.ActiveDirectoryDomainGuid) ||
                        string.IsNullOrEmpty(this.ActiveDirectoryDomainSid) ||
                        string.IsNullOrEmpty(this.ActiveDirectoryAzureStorageSid)
                        )
                    {
                        throw new System.ArgumentNullException("ActiveDirectoryDomainName, ActiveDirectoryNetBiosDomainName, ActiveDirectoryForestName, ActiveDirectoryDomainGuid, ActiveDirectoryDomainSid, ActiveDirectoryAzureStorageSid",
                                                               "To enable ActiveDirectoryDomainServicesForFile, user must specify all of: ActiveDirectoryDomainName, ActiveDirectoryNetBiosDomainName, ActiveDirectoryForestName, ActiveDirectoryDomainGuid, ActiveDirectoryDomainSid, ActiveDirectoryAzureStorageSid.");
                    }
                    createParameters.AzureFilesIdentityBasedAuthentication.DirectoryServiceOptions   = DirectoryServiceOptions.AD;
                    createParameters.AzureFilesIdentityBasedAuthentication.ActiveDirectoryProperties = new ActiveDirectoryProperties()
                    {
                        DomainName        = this.ActiveDirectoryDomainName,
                        NetBiosDomainName = this.ActiveDirectoryNetBiosDomainName,
                        ForestName        = this.ActiveDirectoryForestName,
                        DomainGuid        = this.ActiveDirectoryDomainGuid,
                        DomainSid         = this.ActiveDirectoryDomainSid,
                        AzureStorageSid   = this.ActiveDirectoryAzureStorageSid,
                        SamAccountName    = this.ActiveDirectorySamAccountName,
                        AccountType       = this.ActiveDirectoryAccountType
                    };
                }
                else
                {
                    createParameters.AzureFilesIdentityBasedAuthentication.DirectoryServiceOptions = DirectoryServiceOptions.None;
                }
            }

            if (this.DefaultSharePermission != null)
            {
                if (enableAzureActiveDirectoryDomainServicesForFile == null && enableActiveDirectoryDomainServicesForFile == null)
                {
                    throw new ArgumentException("'-DefaultSharePermission' need be specify together with '-EnableAzureActiveDirectoryDomainServicesForFile' or '-EnableActiveDirectoryDomainServicesForFile'.");
                }
                if (createParameters.AzureFilesIdentityBasedAuthentication == null)
                {
                    createParameters.AzureFilesIdentityBasedAuthentication = new AzureFilesIdentityBasedAuthentication();
                }
                createParameters.AzureFilesIdentityBasedAuthentication.DefaultSharePermission = this.DefaultSharePermission;
            }
            if (this.EnableLargeFileShare.IsPresent)
            {
                createParameters.LargeFileSharesState = LargeFileSharesState.Enabled;
            }
            if (this.EncryptionKeyTypeForQueue != null || this.EncryptionKeyTypeForTable != null || this.RequireInfrastructureEncryption.IsPresent)
            {
                createParameters.Encryption           = new Encryption();
                createParameters.Encryption.KeySource = KeySource.MicrosoftStorage;
                if (this.EncryptionKeyTypeForQueue != null || this.EncryptionKeyTypeForTable != null)
                {
                    createParameters.Encryption.Services = new EncryptionServices();
                    if (this.EncryptionKeyTypeForQueue != null)
                    {
                        createParameters.Encryption.Services.Queue = new EncryptionService(keyType: this.EncryptionKeyTypeForQueue);
                    }
                    if (this.EncryptionKeyTypeForTable != null)
                    {
                        createParameters.Encryption.Services.Table = new EncryptionService(keyType: this.EncryptionKeyTypeForTable);
                    }
                }
                if (this.RequireInfrastructureEncryption.IsPresent)
                {
                    createParameters.Encryption.RequireInfrastructureEncryption = true;
                    if (createParameters.Encryption.Services is null)
                    {
                        createParameters.Encryption.Services      = new EncryptionServices();
                        createParameters.Encryption.Services.Blob = new EncryptionService();
                    }
                }
            }
            if (this.KeyVaultUri != null || this.KeyName != null || this.KeyVersion != null || this.KeyVaultUserAssignedIdentityId != null)
            {
                if ((this.KeyVaultUri != null && this.KeyName == null) || (this.KeyVaultUri == null && this.KeyName != null))
                {
                    throw new ArgumentException("KeyVaultUri and KeyName must be specify together");
                }

                if (this.KeyVersion != null && (this.KeyVaultUri == null || this.KeyName == null))
                {
                    throw new ArgumentException("KeyVersion can only be specified when specify KeyVaultUri and KeyName together.", "KeyVersion");
                }

                if (this.KeyVaultUserAssignedIdentityId != null && (this.KeyVaultUri == null || this.KeyName == null))
                {
                    throw new ArgumentException("KeyVaultUserAssignedIdentityId can only be specified when specify KeyVaultUri and KeyName together.", "KeyVaultUserAssignedIdentityId");
                }

                if (createParameters.Encryption == null)
                {
                    createParameters.Encryption           = new Encryption();
                    createParameters.Encryption.KeySource = KeySource.MicrosoftStorage;
                }

                if (createParameters.Encryption.Services is null)
                {
                    createParameters.Encryption.Services      = new EncryptionServices();
                    createParameters.Encryption.Services.Blob = new EncryptionService();
                }

                if (this.KeyVaultUri != null || this.KeyName != null || this.KeyVersion != null)
                {
                    createParameters.Encryption.KeySource          = KeySource.MicrosoftKeyvault;
                    createParameters.Encryption.KeyVaultProperties = new KeyVaultProperties(this.KeyName, this.KeyVersion, this.KeyVaultUri);
                }

                if (this.KeyVaultUserAssignedIdentityId != null)
                {
                    createParameters.Encryption.EncryptionIdentity = new EncryptionIdentity();
                    createParameters.Encryption.EncryptionIdentity.EncryptionUserAssignedIdentity = this.KeyVaultUserAssignedIdentityId;
                }
            }
            if (this.minimumTlsVersion != null)
            {
                createParameters.MinimumTlsVersion = this.minimumTlsVersion;
            }
            if (this.allowBlobPublicAccess != null)
            {
                createParameters.AllowBlobPublicAccess = this.allowBlobPublicAccess;
            }
            if (this.RoutingChoice != null || this.publishMicrosoftEndpoint != null || this.publishInternetEndpoint != null)
            {
                createParameters.RoutingPreference = new RoutingPreference(this.RoutingChoice, this.publishMicrosoftEndpoint, this.publishInternetEndpoint);
            }
            if (allowSharedKeyAccess != null)
            {
                createParameters.AllowSharedKeyAccess = allowSharedKeyAccess;
            }
            if (enableNfsV3 != null)
            {
                createParameters.EnableNfsV3 = enableNfsV3;
            }
            if (this.EdgeZone != null)
            {
                createParameters.ExtendedLocation = new ExtendedLocation()
                {
                    Type = ExtendedLocationTypes.EdgeZone,
                    Name = this.EdgeZone
                };
            }
            if (sasExpirationPeriod != null)
            {
                createParameters.SasPolicy = new SasPolicy(sasExpirationPeriod.Value.ToString(@"d\.hh\:mm\:ss"));
            }
            if (keyExpirationPeriodInDay != null)
            {
                createParameters.KeyPolicy = new KeyPolicy(keyExpirationPeriodInDay.Value);
            }
            if (allowCrossTenantReplication != null)
            {
                createParameters.AllowCrossTenantReplication = allowCrossTenantReplication;
            }
            if (this.PublicNetworkAccess != null)
            {
                createParameters.PublicNetworkAccess = this.PublicNetworkAccess;
            }
            if (EnableAccountLevelImmutability.IsPresent || this.immutabilityPeriod != null || this.ImmutabilityPolicyState != null)
            {
                if (!EnableAccountLevelImmutability.IsPresent)
                {
                    throw new ArgumentException("ImmutabilityPeriod, ImmutabilityPolicyState and AllowProtectedAppendWrite, can only be specified with -EnableAccountLevelImmutability.");
                }
                createParameters.ImmutableStorageWithVersioning         = new ImmutableStorageAccount();
                createParameters.ImmutableStorageWithVersioning.Enabled = this.EnableAccountLevelImmutability.IsPresent;
                if (this.immutabilityPeriod != null || this.ImmutabilityPolicyState != null)
                {
                    createParameters.ImmutableStorageWithVersioning.ImmutabilityPolicy = new AccountImmutabilityPolicyProperties();
                    createParameters.ImmutableStorageWithVersioning.ImmutabilityPolicy.ImmutabilityPeriodSinceCreationInDays = this.immutabilityPeriod;
                    createParameters.ImmutableStorageWithVersioning.ImmutabilityPolicy.State = this.ImmutabilityPolicyState;
                }
            }

            var createAccountResponse = this.StorageClient.StorageAccounts.Create(
                this.ResourceGroupName,
                this.Name,
                createParameters);

            var storageAccount = this.StorageClient.StorageAccounts.GetProperties(this.ResourceGroupName, this.Name);

            this.WriteStorageAccount(storageAccount);
        }
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();

            ManagedCluster cluster = null;

            switch (ParameterSetName)
            {
            case IdParameterSet:
            {
                var resource = new ResourceIdentifier(Id);
                ResourceGroupName = resource.ResourceGroupName;
                Name = resource.ResourceName;
                break;
            }

            case InputObjectParameterSet:
            {
                WriteVerbose(Resources.UsingClusterFromPipeline);
                cluster = PSMapper.Instance.Map <ManagedCluster>(InputObject);
                var resource = new ResourceIdentifier(cluster.Id);
                ResourceGroupName = resource.ResourceGroupName;
                Name = resource.ResourceName;
                break;
            }
            }

            var msg = $"{Name} in {ResourceGroupName}";

            if (ShouldProcess(msg, Resources.UpdateOrCreateAManagedKubernetesCluster))
            {
                RunCmdLet(() =>
                {
                    AcsServicePrincipal acsServicePrincipal;
                    if (Exists())
                    {
                        if (cluster == null)
                        {
                            cluster = Client.ManagedClusters.Get(ResourceGroupName, Name);
                        }

                        if (this.IsParameterBound(c => c.Location))
                        {
                            throw new AzPSArgumentException(
                                Resources.LocationCannotBeUpdateForExistingCluster,
                                nameof(Location),
                                desensitizedMessage: Resources.LocationCannotBeUpdateForExistingCluster);
                        }

                        if (this.IsParameterBound(c => c.DnsNamePrefix))
                        {
                            WriteVerbose(Resources.UpdatingDnsNamePrefix);
                            cluster.DnsPrefix = DnsNamePrefix;
                        }

                        if (this.IsParameterBound(c => c.SshKeyValue))
                        {
                            WriteVerbose(Resources.UpdatingSshKeyValue);
                            cluster.LinuxProfile.Ssh.PublicKeys = new List <ContainerServiceSshPublicKey>
                            {
                                new ContainerServiceSshPublicKey(GetSshKey(SshKeyValue))
                            };
                        }
                        if (this.IsParameterBound(c => c.ServicePrincipalIdAndSecret))
                        {
                            WriteVerbose(Resources.UpdatingServicePrincipal);
                            acsServicePrincipal = EnsureServicePrincipal(ServicePrincipalIdAndSecret.UserName, ServicePrincipalIdAndSecret.Password?.ConvertToString());

                            var spProfile = new ManagedClusterServicePrincipalProfile(
                                acsServicePrincipal.SpId,
                                acsServicePrincipal.ClientSecret);
                            cluster.ServicePrincipalProfile = spProfile;
                        }

                        if (this.IsParameterBound(c => c.LinuxProfileAdminUserName))
                        {
                            WriteVerbose(Resources.UpdatingAdminUsername);
                            cluster.LinuxProfile.AdminUsername = LinuxProfileAdminUserName;
                        }

                        if (NeedUpdateNodeAgentPool())
                        {
                            ManagedClusterAgentPoolProfile defaultAgentPoolProfile;

                            string nodePoolName = "default";
                            if (this.IsParameterBound(c => c.NodeName))
                            {
                                nodePoolName = NodeName;
                            }

                            if (cluster.AgentPoolProfiles.Any(x => x.Name == nodePoolName))
                            {
                                defaultAgentPoolProfile = cluster.AgentPoolProfiles.First(x => x.Name == nodePoolName);
                            }
                            else
                            {
                                throw new AzPSArgumentException(
                                    Resources.SpecifiedAgentPoolDoesNotExist,
                                    nameof(Name),
                                    desensitizedMessage: Resources.SpecifiedAgentPoolDoesNotExist);
                            }

                            if (this.IsParameterBound(c => c.NodeMinCount))
                            {
                                defaultAgentPoolProfile.MinCount = NodeMinCount;
                            }
                            if (this.IsParameterBound(c => c.NodeMaxCount))
                            {
                                defaultAgentPoolProfile.MaxCount = NodeMaxCount;
                            }
                            if (this.IsParameterBound(c => c.EnableNodeAutoScaling))
                            {
                                defaultAgentPoolProfile.EnableAutoScaling = EnableNodeAutoScaling.ToBool();
                            }
                            if (this.IsParameterBound(c => c.NodeVmSize))
                            {
                                WriteVerbose(Resources.UpdatingNodeVmSize);
                                defaultAgentPoolProfile.VmSize = NodeVmSize;
                            }

                            if (this.IsParameterBound(c => c.NodeCount))
                            {
                                WriteVerbose(Resources.UpdatingNodeCount);
                                defaultAgentPoolProfile.Count = NodeCount;
                            }

                            if (this.IsParameterBound(c => c.NodeOsDiskSize))
                            {
                                WriteVerbose(Resources.UpdatingNodeOsDiskSize);
                                defaultAgentPoolProfile.OsDiskSizeGB = NodeOsDiskSize;
                            }

                            if (this.IsParameterBound(c => c.NodePoolMode))
                            {
                                WriteVerbose(Resources.UpdatingNodePoolMode);
                                defaultAgentPoolProfile.Mode = NodePoolMode;
                            }
                        }

                        if (this.IsParameterBound(c => c.KubernetesVersion) && this.IsParameterBound(c => c.NodeImageOnly))
                        {
                            throw new AzPSArgumentException(Resources.UpdateKubernetesVersionAndNodeImageOnlyConflict, "KubernetesVersion");
                        }

                        bool allAgentPoolVirtualMachineScaleSets = cluster.AgentPoolProfiles.All(c => c.Type.ToLower().Equals("virtualmachinescalesets"));
                        if (this.IsParameterBound(c => c.NodeImageOnly))
                        {
                            if (!ShouldProcess(Resources.ConfirmOnlyUpgradeNodeVersion, ""))
                            {
                                return;
                            }

                            foreach (var agentPoolProfile in cluster.AgentPoolProfiles)
                            {
                                if (!allAgentPoolVirtualMachineScaleSets)
                                {
                                    throw new AzPSApplicationException(Resources.NotUsingVirtualMachineScaleSets);
                                }
                                var agentPoolClient = Client.AgentPools.Get(ResourceGroupName, Name, agentPoolProfile.Name);
                                AgentPool parameter = new AgentPool
                                {
                                    Count               = agentPoolClient.Count,
                                    VmSize              = agentPoolClient.VmSize,
                                    OsDiskSizeGB        = agentPoolClient.OsDiskSizeGB,
                                    MaxPods             = agentPoolClient.MaxPods,
                                    Mode                = agentPoolClient.Mode,
                                    OsType              = agentPoolClient.OsType,
                                    OrchestratorVersion = cluster.KubernetesVersion,
                                };
                                Client.AgentPools.CreateOrUpdate(ResourceGroupName, Name, agentPoolProfile.Name, parameter);
                            }
                            cluster = Client.ManagedClusters.Get(ResourceGroupName, Name);
                            WriteObject(PSMapper.Instance.Map <PSKubernetesCluster>(cluster));
                            return;
                        }
                        if (this.IsParameterBound(c => c.KubernetesVersion))
                        {
                            WriteVerbose(Resources.UpdatingKubernetesVersion);
                            cluster.KubernetesVersion = KubernetesVersion;
                        }
                        bool upgradeAllNode = false;
                        if (cluster.MaxAgentPools < 8 || !allAgentPoolVirtualMachineScaleSets)
                        {
                            if (this.IsParameterBound(c => c.ControlPlaneOnly))
                            {
                                if (!ShouldProcess(string.Format(Resources.ConfirmControlPlaneOnlyInVMASCluster, KubernetesVersion), ""))
                                {
                                    return;
                                }
                            }
                            upgradeAllNode = true;
                        }
                        else
                        {
                            if (!this.IsParameterBound(c => c.ControlPlaneOnly))
                            {
                                if (!ShouldProcess(string.Format(Resources.ConfirmNotControlPlaneOnly, KubernetesVersion), ""))
                                {
                                    return;
                                }
                                upgradeAllNode = true;
                            }
                            else
                            {
                                if (!ShouldProcess(string.Format(Resources.ConfirmControlPlaneOnly, KubernetesVersion), ""))
                                {
                                    return;
                                }
                            }
                        }
                        if (upgradeAllNode)
                        {
                            cluster.AgentPoolProfiles.ForEach(c => c.OrchestratorVersion = KubernetesVersion);
                        }

                        if (this.IsParameterBound(c => c.Tag))
                        {
                            WriteVerbose(Resources.UpdatingTags);
                            cluster.Tags = TagsConversionHelper.CreateTagDictionary(Tag, true);
                        }

                        //To avoid server error: for agentPoolProfiles.availabilityZones, server will expect
                        //$null instead of empty collection, otherwise it will throw error.
                        foreach (var profile in cluster.AgentPoolProfiles)
                        {
                            if (profile.AvailabilityZones?.Count == 0)
                            {
                                profile.AvailabilityZones = null;
                            }
                        }

                        WriteVerbose(Resources.UpdatingYourManagedKubernetesCluster);
                    }
                    else
                    {
                        WriteVerbose(Resources.PreparingForDeploymentOfYourNewManagedKubernetesCluster);
                        cluster = BuildNewCluster();
                    }

                    if (this.IsParameterBound(c => c.AcrNameToAttach) ||
                        this.IsParameterBound(c => c.AcrNameToDetach))
                    {
                        acsServicePrincipal = EnsureServicePrincipal(ServicePrincipalIdAndSecret?.UserName, ServicePrincipalIdAndSecret?.Password?.ConvertToString());
                        if (this.IsParameterBound(c => c.AcrNameToAttach))
                        {
                            AddAcrRoleAssignment(AcrNameToAttach, nameof(AcrNameToAttach), acsServicePrincipal);
                        }
                        if (this.IsParameterBound(c => c.AcrNameToDetach))
                        {
                            RemoveAcrRoleAssignment(AcrNameToDetach, nameof(AcrNameToDetach), acsServicePrincipal);
                        }
                    }
                    cluster.NetworkProfile         = SetNetworkProfile(cluster.NetworkProfile);
                    cluster.ApiServerAccessProfile = CreateOrUpdateApiServerAccessProfile(cluster.ApiServerAccessProfile);
                    if (this.IsParameterBound(c => c.FqdnSubdomain))
                    {
                        cluster.FqdnSubdomain = FqdnSubdomain;
                    }

                    var kubeCluster = Client.ManagedClusters.CreateOrUpdate(ResourceGroupName, Name, cluster);

                    WriteObject(PSMapper.Instance.Map <PSKubernetesCluster>(kubeCluster));
                });
            }
        }
示例#8
0
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();

            CheckNameAvailabilityResult checkNameAvailabilityResult = this.StorageClient.StorageAccounts.CheckNameAvailability(this.Name);

            if (!checkNameAvailabilityResult.NameAvailable.Value)
            {
                throw new System.ArgumentException(checkNameAvailabilityResult.Message, "Name");
            }

            StorageAccountCreateParameters createParameters = new StorageAccountCreateParameters()
            {
                Location = this.Location,
                Sku      = new Sku(this.SkuName),
                Tags     = TagsConversionHelper.CreateTagDictionary(Tag, validate: true),
            };

            if (this.CustomDomainName != null)
            {
                createParameters.CustomDomain = new CustomDomain()
                {
                    Name             = CustomDomainName,
                    UseSubDomainName = UseSubDomain
                };
            }
            else if (UseSubDomain != null)
            {
                throw new System.ArgumentException(string.Format("UseSubDomain must be set together with CustomDomainName."));
            }

            if (kind != null)
            {
                createParameters.Kind = kind;
            }

            if (this.AccessTier != null)
            {
                createParameters.AccessTier = ParseAccessTier(AccessTier);
            }
            if (enableHttpsTrafficOnly != null)
            {
                createParameters.EnableHttpsTrafficOnly = enableHttpsTrafficOnly;
            }

            if (AssignIdentity.IsPresent)
            {
                createParameters.Identity = new Identity();
            }
            if (NetworkRuleSet != null)
            {
                createParameters.NetworkRuleSet = PSNetworkRuleSet.ParseStorageNetworkRule(NetworkRuleSet);
            }
            if (enableHierarchicalNamespace != null)
            {
                createParameters.IsHnsEnabled = enableHierarchicalNamespace;
            }
            if (enableAzureActiveDirectoryDomainServicesForFile != null || enableActiveDirectoryDomainServicesForFile != null)
            {
                createParameters.AzureFilesIdentityBasedAuthentication = new AzureFilesIdentityBasedAuthentication();
                if (enableAzureActiveDirectoryDomainServicesForFile != null && enableAzureActiveDirectoryDomainServicesForFile.Value)
                {
                    createParameters.AzureFilesIdentityBasedAuthentication.DirectoryServiceOptions = DirectoryServiceOptions.AADDS;
                }
                else if (enableActiveDirectoryDomainServicesForFile != null && enableActiveDirectoryDomainServicesForFile.Value)
                {
                    if (string.IsNullOrEmpty(this.ActiveDirectoryDomainName) ||
                        string.IsNullOrEmpty(this.ActiveDirectoryNetBiosDomainName) ||
                        string.IsNullOrEmpty(this.ActiveDirectoryForestName) ||
                        string.IsNullOrEmpty(this.ActiveDirectoryDomainGuid) ||
                        string.IsNullOrEmpty(this.ActiveDirectoryDomainSid) ||
                        string.IsNullOrEmpty(this.ActiveDirectoryAzureStorageSid)
                        )
                    {
                        throw new System.ArgumentNullException("ActiveDirectoryDomainName, ActiveDirectoryNetBiosDomainName, ActiveDirectoryForestName, ActiveDirectoryDomainGuid, ActiveDirectoryDomainSid, ActiveDirectoryAzureStorageSid",
                                                               "To enable ActiveDirectoryDomainServicesForFile, user must specify all of: ActiveDirectoryDomainName, ActiveDirectoryNetBiosDomainName, ActiveDirectoryForestName, ActiveDirectoryDomainGuid, ActiveDirectoryDomainSid, ActiveDirectoryAzureStorageSid.");
                    }
                    createParameters.AzureFilesIdentityBasedAuthentication.DirectoryServiceOptions   = DirectoryServiceOptions.AD;
                    createParameters.AzureFilesIdentityBasedAuthentication.ActiveDirectoryProperties = new ActiveDirectoryProperties()
                    {
                        DomainName        = this.ActiveDirectoryDomainName,
                        NetBiosDomainName = this.ActiveDirectoryNetBiosDomainName,
                        ForestName        = this.ActiveDirectoryForestName,
                        DomainGuid        = this.ActiveDirectoryDomainGuid,
                        DomainSid         = this.ActiveDirectoryDomainSid,
                        AzureStorageSid   = this.ActiveDirectoryAzureStorageSid
                    };
                }
                else
                {
                    createParameters.AzureFilesIdentityBasedAuthentication.DirectoryServiceOptions = DirectoryServiceOptions.None;
                }
            }
            if (this.EnableLargeFileShare.IsPresent)
            {
                createParameters.LargeFileSharesState = LargeFileSharesState.Enabled;
            }
            if (this.EncryptionKeyTypeForQueue != null || this.EncryptionKeyTypeForTable != null || this.RequireInfrastructureEncryption.IsPresent)
            {
                createParameters.Encryption           = new Encryption();
                createParameters.Encryption.KeySource = KeySource.MicrosoftStorage;
                if (this.EncryptionKeyTypeForQueue != null || this.EncryptionKeyTypeForTable != null)
                {
                    createParameters.Encryption.Services = new EncryptionServices();
                    if (this.EncryptionKeyTypeForQueue != null)
                    {
                        createParameters.Encryption.Services.Queue = new EncryptionService(keyType: this.EncryptionKeyTypeForQueue);
                    }
                    if (this.EncryptionKeyTypeForTable != null)
                    {
                        createParameters.Encryption.Services.Table = new EncryptionService(keyType: this.EncryptionKeyTypeForTable);
                    }
                }
                if (this.RequireInfrastructureEncryption.IsPresent)
                {
                    createParameters.Encryption.RequireInfrastructureEncryption = true;
                    if (createParameters.Encryption.Services is null)
                    {
                        createParameters.Encryption.Services      = new EncryptionServices();
                        createParameters.Encryption.Services.Blob = new EncryptionService();
                    }
                }
            }
            if (this.minimumTlsVersion != null)
            {
                createParameters.MinimumTlsVersion = this.minimumTlsVersion;
            }
            if (this.allowBlobPublicAccess != null)
            {
                createParameters.AllowBlobPublicAccess = this.allowBlobPublicAccess;
            }
            if (this.RoutingChoice != null || this.publishMicrosoftEndpoint != null || this.publishInternetEndpoint != null)
            {
                createParameters.RoutingPreference = new RoutingPreference(this.RoutingChoice, this.publishMicrosoftEndpoint, this.publishInternetEndpoint);
            }

            var createAccountResponse = this.StorageClient.StorageAccounts.Create(
                this.ResourceGroupName,
                this.Name,
                createParameters);

            var storageAccount = this.StorageClient.StorageAccounts.GetProperties(this.ResourceGroupName, this.Name);

            this.WriteStorageAccount(storageAccount);
        }
示例#9
0
        public override void Execute()
        {
            base.Execute();
            if (!string.IsNullOrEmpty(this.Name))
            {
                PSPublicIpAddress publicIp;
                if (ParameterSetName.Contains("ScaleSetIp"))
                {
                    var publicIpVmss = PublicIpAddressClient.GetVirtualMachineScaleSetPublicIPAddress(
                        this.ResourceGroupName, this.VirtualMachineScaleSetName, this.VirtualMachineIndex, this.NetworkInterfaceName, this.IpConfigurationName, this.Name, this.ExpandResource);
                    publicIp = ToPsPublicIpAddress(publicIpVmss);
                    publicIp.ResourceGroupName = this.ResourceGroupName;
                    publicIp.Tag = TagsConversionHelper.CreateTagHashtable(publicIpVmss.Tags);
                }
                else
                {
                    publicIp = this.GetPublicIpAddress(this.ResourceGroupName, this.Name, this.ExpandResource);
                }

                WriteObject(publicIp);
            }
            else
            {
                IPage <PublicIPAddress> publicipPage;
                if (!string.IsNullOrEmpty(this.ResourceGroupName))
                {
                    if (ParameterSetName.Contains("ScaleSetIp"))
                    {
                        if (string.IsNullOrEmpty(this.VirtualMachineIndex))
                        {
                            publicipPage =
                                this.PublicIpAddressClient.ListVirtualMachineScaleSetPublicIPAddresses(
                                    this.ResourceGroupName,
                                    this.VirtualMachineScaleSetName);
                        }
                        else
                        {
                            publicipPage =
                                this.PublicIpAddressClient.ListVirtualMachineScaleSetVMPublicIPAddresses(
                                    this.ResourceGroupName,
                                    this.VirtualMachineScaleSetName,
                                    this.VirtualMachineIndex,
                                    this.NetworkInterfaceName,
                                    this.IpConfigurationName);
                        }
                    }
                    else
                    {
                        publicipPage = this.PublicIpAddressClient.List(this.ResourceGroupName);
                    }
                }
                else
                {
                    publicipPage = this.PublicIpAddressClient.ListAll();
                }

                // Get all resources by polling on next page link
                List <PublicIPAddress> publicIPList;
                if (ParameterSetName.Contains("ScaleSetIp"))
                {
                    if (string.IsNullOrEmpty(this.VirtualMachineIndex))
                    {
                        publicIPList = ListNextLink <PublicIPAddress> .GetAllResourcesByPollingNextLink(publicipPage, this.PublicIpAddressClient.ListVirtualMachineScaleSetPublicIPAddressesNext);
                    }
                    else
                    {
                        publicIPList = ListNextLink <PublicIPAddress> .GetAllResourcesByPollingNextLink(publicipPage, this.PublicIpAddressClient.ListVirtualMachineScaleSetVMPublicIPAddressesNext);
                    }
                }
                else
                {
                    publicIPList = ListNextLink <PublicIPAddress> .GetAllResourcesByPollingNextLink(publicipPage, this.PublicIpAddressClient.ListNext);
                }

                var psPublicIps = new List <PSPublicIpAddress>();

                // populate the publicIpAddresses with the ResourceGroupName
                foreach (var publicIp in publicIPList)
                {
                    var psPublicIp = this.ToPsPublicIpAddress(publicIp);
                    psPublicIp.ResourceGroupName = NetworkBaseCmdlet.GetResourceGroup(publicIp.Id);
                    psPublicIps.Add(psPublicIp);
                }

                WriteObject(psPublicIps, true);
            }
        }
示例#10
0
        private PSVirtualNetworkGateway CreateVirtualNetworkGateway()
        {
            var vnetGateway = new PSVirtualNetworkGateway();

            vnetGateway.Name = this.Name;
            vnetGateway.ResourceGroupName = this.ResourceGroupName;
            vnetGateway.Location          = this.Location;

            if (this.IpConfigurations != null)
            {
                vnetGateway.IpConfigurations = this.IpConfigurations;
            }

            vnetGateway.GatewayType = this.GatewayType;
            vnetGateway.VpnType     = this.VpnType;
            vnetGateway.EnableBgp   = this.EnableBgp;

            if (this.GatewayDefaultSite != null)
            {
                vnetGateway.GatewayDefaultSite    = new PSResourceId();
                vnetGateway.GatewayDefaultSite.Id = this.GatewayDefaultSite.Id;
            }
            else
            {
                vnetGateway.GatewayDefaultSite = null;
            }

            if (this.GatewaySku != null)
            {
                vnetGateway.Sku      = new PSVirtualNetworkGatewaySku();
                vnetGateway.Sku.Tier = this.GatewaySku;
                vnetGateway.Sku.Name = this.GatewaySku;
            }
            else
            {
                vnetGateway.Sku = null;
            }

            if (this.VpnClientAddressPool != null || this.VpnClientRootCertificates != null || this.VpnClientRevokedCertificates != null)
            {
                vnetGateway.VpnClientConfiguration = new PSVpnClientConfiguration();

                if (this.VpnClientAddressPool != null)
                {
                    // Make sure passed Virtual Network gateway type is RouteBased if P2S VpnClientAddressPool is specified.
                    if (this.VpnType == null || !this.VpnType.Equals(MNM.VpnType.RouteBased))
                    {
                        throw new ArgumentException("Virtual Network Gateway VpnType should be :{0} when P2S VpnClientAddressPool is specified.");
                    }

                    vnetGateway.VpnClientConfiguration.VpnClientAddressPool = new PSAddressSpace();
                    vnetGateway.VpnClientConfiguration.VpnClientAddressPool.AddressPrefixes = this.VpnClientAddressPool;
                }

                if (this.VpnClientRootCertificates != null)
                {
                    vnetGateway.VpnClientConfiguration.VpnClientRootCertificates = this.VpnClientRootCertificates;
                }

                if (this.VpnClientRevokedCertificates != null)
                {
                    vnetGateway.VpnClientConfiguration.VpnClientRevokedCertificates = this.VpnClientRevokedCertificates;
                }
            }
            else
            {
                vnetGateway.VpnClientConfiguration = null;
            }

            if (this.Asn > 0 || this.PeerWeight > 0)
            {
                vnetGateway.BgpSettings = new PSBgpSettings();
                vnetGateway.BgpSettings.BgpPeeringAddress = null; // We block modifying the gateway's BgpPeeringAddress (CA)

                if (this.Asn > 0)
                {
                    vnetGateway.BgpSettings.Asn = this.Asn;
                }

                if (this.PeerWeight > 0)
                {
                    vnetGateway.BgpSettings.PeerWeight = this.PeerWeight;
                }
                else if (this.PeerWeight < 0)
                {
                    throw new ArgumentException("PeerWeight must be a positive integer");
                }
            }

            // Map to the sdk object
            var vnetGatewayModel = Mapper.Map <MNM.VirtualNetworkGateway>(vnetGateway);

            vnetGatewayModel.Tags = TagsConversionHelper.CreateTagDictionary(this.Tag, validate: true);

            // Execute the Create VirtualNetwork call
            this.VirtualNetworkGatewayClient.CreateOrUpdate(this.ResourceGroupName, this.Name, vnetGatewayModel);

            var getVirtualNetworkGateway = this.GetVirtualNetworkGateway(this.ResourceGroupName, this.Name);

            return(getVirtualNetworkGateway);
        }
示例#11
0
        /// <summary>
        /// Filters the subscription's resource groups.
        /// </summary>
        /// <param name="name">The resource group name.</param>
        /// <param name="tag">The resource group tag.</param>
        /// <param name="detailed">Whether the  return is detailed or not.</param>
        /// <param name="location">The resource group location.</param>
        /// <returns>The filtered resource groups</returns>
        public virtual List <PSResourceGroup> FilterResourceGroups(string name, Hashtable tag, bool detailed, string location = null)
        {
            List <PSResourceGroup> result = new List <PSResourceGroup>();

            if (string.IsNullOrEmpty(name))
            {
                List <ResourceGroup> resourceGroups = new List <ResourceGroup>();

                var listResult = ResourceManagementClient.ResourceGroups.List(null);
                resourceGroups.AddRange(listResult);

                while (!string.IsNullOrEmpty(listResult.NextPageLink))
                {
                    listResult = ResourceManagementClient.ResourceGroups.ListNext(listResult.NextPageLink);
                    resourceGroups.AddRange(listResult);
                }

                resourceGroups = !string.IsNullOrEmpty(location)
                    ? resourceGroups.Where(resourceGroup => resourceGroup.Location.EqualsAsLocation(location)).ToList()
                    : resourceGroups;

                // TODO: Replace with server side filtering when available
                if (tag != null && tag.Count >= 1)
                {
                    PSTagValuePair tagValuePair = TagsConversionHelper.Create(tag);
                    if (tagValuePair == null)
                    {
                        throw new ArgumentException(ProjectResources.InvalidTagFormat);
                    }
                    if (string.IsNullOrEmpty(tagValuePair.Value))
                    {
                        resourceGroups =
                            resourceGroups.Where(rg => rg.Tags != null &&
                                                 rg.Tags.Keys.Contains(tagValuePair.Name,
                                                                       StringComparer.OrdinalIgnoreCase))
                            .Select(rg => rg).ToList();
                    }
                    else
                    {
                        resourceGroups =
                            resourceGroups.Where(rg => rg.Tags != null && rg.Tags.Keys.Contains(tagValuePair.Name,
                                                                                                StringComparer.OrdinalIgnoreCase))
                            .Where(rg => rg.Tags.Values.Contains(tagValuePair.Value,
                                                                 StringComparer.OrdinalIgnoreCase))
                            .Select(rg => rg).ToList();
                    }
                }
                result.AddRange(resourceGroups.Select(rg => rg.ToPSResourceGroup()));
            }
            else
            {
                try
                {
                    result.Add(ResourceManagementClient.ResourceGroups.Get(name).ToPSResourceGroup());
                }
                catch (CloudException)
                {
                    WriteError(ProjectResources.ResourceGroupDoesntExists);
                }
            }

            return(result);
        }
示例#12
0
        public override void Execute()
        {
            if (ParameterSetName.Equals(VirtualRouterPeerParameterSetNames.ByVirtualRouterPeerInputObject, StringComparison.OrdinalIgnoreCase))
            {
                PeerName = InputObject.Name;
                PeerAsn  = InputObject.PeerAsn;
                PeerIp   = InputObject.PeerIp;
            }
            else if (ParameterSetName.Equals(VirtualRouterPeerParameterSetNames.ByVirtualRouterPeerResourceId, StringComparison.OrdinalIgnoreCase))
            {
                var parsedResourceId = new ResourceIdentifier(ResourceId);
                PeerName = parsedResourceId.ResourceName;
            }

            base.Execute();

            var present = true;
            VirtualRouterPeering existingVirtualRouterPeer = null;

            try
            {
                existingVirtualRouterPeer = this.NetworkClient.NetworkManagementClient.VirtualRouterPeerings.Get(this.ResourceGroupName, this.VirtualRouterName, this.PeerName);
            }
            catch (Microsoft.Rest.Azure.CloudException exception)
            {
                if (exception.Response.StatusCode == HttpStatusCode.NotFound)
                {
                    // Resource is not present
                    present = false;
                }
                else
                {
                    throw;
                }
            }

            if (!present)
            {
                throw new PSArgumentException(string.Format(Properties.Resources.ResourceNotFound, this.PeerName, this.ResourceGroupName, this.VirtualRouterName));
            }

            if (ParameterSetName.Equals(VirtualRouterPeerParameterSetNames.ByVirtualRouterPeerResourceId, StringComparison.OrdinalIgnoreCase))
            {
                var parsedResourceId = new ResourceIdentifier(ResourceId);
                PeerAsn = (uint)existingVirtualRouterPeer.PeerAsn;
                PeerIp  = existingVirtualRouterPeer.PeerIp;
            }

            ConfirmAction(
                Properties.Resources.SettingResourceMessage,
                PeerName,
                () =>
            {
                WriteVerbose(String.Format(Properties.Resources.UpdatingLongRunningOperationMessage, this.ResourceGroupName, this.PeerName));
                PSVirtualRouterPeer virtualRouterPeer = new PSVirtualRouterPeer
                {
                    Name    = this.PeerName,
                    PeerAsn = this.PeerAsn,
                    PeerIp  = this.PeerIp
                };

                var vVirtualRouterPeerModel = NetworkResourceManagerProfile.Mapper.Map <MNM.VirtualRouterPeering>(virtualRouterPeer);

                this.NetworkClient.NetworkManagementClient.VirtualRouterPeerings.CreateOrUpdate(this.ResourceGroupName, this.VirtualRouterName, this.PeerName, vVirtualRouterPeerModel);
                var getVirtualRouter    = this.NetworkClient.NetworkManagementClient.VirtualRouters.Get(this.ResourceGroupName, this.VirtualRouterName);
                var vVirtualRouterModel = NetworkResourceManagerProfile.Mapper.Map <CNM.PSVirtualRouter>(getVirtualRouter);
                vVirtualRouterModel.ResourceGroupName = this.ResourceGroupName;
                vVirtualRouterModel.Tag = TagsConversionHelper.CreateTagHashtable(getVirtualRouter.Tags);
                AddPeeringsToPSVirtualRouter(getVirtualRouter, vVirtualRouterModel, ResourceGroupName, this.VirtualRouterName);

                WriteObject(vVirtualRouterModel, true);
            });
        }
示例#13
0
        private PSVirtualNetwork CreateVirtualNetwork()
        {
            var vnet = new PSVirtualNetwork
            {
                Name = Name,
                ResourceGroupName = ResourceGroupName,
                Location          = Location,
                AddressSpace      = new PSAddressSpace {
                    AddressPrefixes = AddressPrefix?.ToList()
                }
            };

            if (DnsServer != null)
            {
                vnet.DhcpOptions = new PSDhcpOptions {
                    DnsServers = DnsServer?.ToList()
                };
            }

            if (this.FlowTimeout > 0)
            {
                vnet.FlowTimeoutInMinutes = this.FlowTimeout;
            }

            vnet.Subnets = this.Subnet?.ToList();
            vnet.EnableDdosProtection = EnableDdosProtection;

            if (!string.IsNullOrEmpty(DdosProtectionPlanId))
            {
                vnet.DdosProtectionPlan = new PSResourceId {
                    Id = DdosProtectionPlanId
                };
            }

            if (!string.IsNullOrWhiteSpace(BgpCommunity))
            {
                vnet.BgpCommunities = new PSVirtualNetworkBgpCommunities {
                    VirtualNetworkCommunity = this.BgpCommunity
                };
            }

            if (!string.IsNullOrEmpty(this.EdgeZone))
            {
                vnet.ExtendedLocation = new PSExtendedLocation(this.EdgeZone);
            }

            // Map to the sdk object
            var vnetModel = NetworkResourceManagerProfile.Mapper.Map <MNM.VirtualNetwork>(vnet);

            vnetModel.Tags = TagsConversionHelper.CreateTagDictionary(Tag, validate: true);

            if (this.IpAllocation != null)
            {
                foreach (var ipAllocation in this.IpAllocation)
                {
                    var ipAllocationReference = new MNM.SubResource(ipAllocation.Id);
                    vnetModel.IpAllocations.Add(ipAllocationReference);
                }
            }

            // Execute the Create VirtualNetwork call
            VirtualNetworkClient.CreateOrUpdate(ResourceGroupName, Name, vnetModel);

            var getVirtualNetwork = GetVirtualNetwork(ResourceGroupName, Name);

            return(getVirtualNetwork);
        }
        private PSNetworkInterface CreateNetworkInterface()
        {
            // Get the subnetId and publicIpAddressId from the object if specified
            if (string.Equals(ParameterSetName, Microsoft.Azure.Commands.Network.Properties.Resources.SetByResource))
            {
                this.SubnetId = this.Subnet.Id;

                if (this.PublicIpAddress != null)
                {
                    this.PublicIpAddressId = this.PublicIpAddress.Id;
                }

                if (this.NetworkSecurityGroup != null)
                {
                    this.NetworkSecurityGroupId = this.NetworkSecurityGroup.Id;
                }

                if (this.LoadBalancerBackendAddressPool != null)
                {
                    this.LoadBalancerBackendAddressPoolId = new List <string>();
                    foreach (var bepool in this.LoadBalancerBackendAddressPool)
                    {
                        this.LoadBalancerBackendAddressPoolId.Add(bepool.Id);
                    }
                }

                if (this.LoadBalancerInboundNatRule != null)
                {
                    this.LoadBalancerInboundNatRuleId = new List <string>();
                    foreach (var natRule in this.LoadBalancerInboundNatRule)
                    {
                        this.LoadBalancerInboundNatRuleId.Add(natRule.Id);
                    }
                }
            }

            var networkInterface = new PSNetworkInterface();

            networkInterface.Name               = this.Name;
            networkInterface.Location           = this.Location;
            networkInterface.EnableIPForwarding = this.EnableIPForwarding.IsPresent;
            networkInterface.IpConfigurations   = new List <PSNetworkInterfaceIPConfiguration>();

            var nicIpConfiguration = new PSNetworkInterfaceIPConfiguration();

            nicIpConfiguration.Name = string.IsNullOrEmpty(this.IpConfigurationName) ? "ipconfig1" : this.IpConfigurationName;
            nicIpConfiguration.PrivateIpAllocationMethod = MNM.IPAllocationMethod.Dynamic;

            if (!string.IsNullOrEmpty(this.PrivateIpAddress))
            {
                nicIpConfiguration.PrivateIpAddress          = this.PrivateIpAddress;
                nicIpConfiguration.PrivateIpAllocationMethod = MNM.IPAllocationMethod.Static;
            }

            nicIpConfiguration.Subnet    = new PSSubnet();
            nicIpConfiguration.Subnet.Id = this.SubnetId;

            if (!string.IsNullOrEmpty(this.PublicIpAddressId))
            {
                nicIpConfiguration.PublicIpAddress    = new PSPublicIpAddress();
                nicIpConfiguration.PublicIpAddress.Id = this.PublicIpAddressId;
            }

            if (!string.IsNullOrEmpty(this.NetworkSecurityGroupId))
            {
                networkInterface.NetworkSecurityGroup    = new PSNetworkSecurityGroup();
                networkInterface.NetworkSecurityGroup.Id = this.NetworkSecurityGroupId;
            }

            if (this.LoadBalancerBackendAddressPoolId != null)
            {
                nicIpConfiguration.LoadBalancerBackendAddressPools = new List <PSBackendAddressPool>();
                foreach (var bepoolId in this.LoadBalancerBackendAddressPoolId)
                {
                    nicIpConfiguration.LoadBalancerBackendAddressPools.Add(new PSBackendAddressPool {
                        Id = bepoolId
                    });
                }
            }

            if (this.LoadBalancerInboundNatRuleId != null)
            {
                nicIpConfiguration.LoadBalancerInboundNatRules = new List <PSInboundNatRule>();
                foreach (var natruleId in this.LoadBalancerInboundNatRuleId)
                {
                    nicIpConfiguration.LoadBalancerInboundNatRules.Add(new PSInboundNatRule {
                        Id = natruleId
                    });
                }
            }

            if (this.DnsServer != null || this.InternalDnsNameLabel != null)
            {
                networkInterface.DnsSettings = new PSNetworkInterfaceDnsSettings();
                if (this.DnsServer != null)
                {
                    networkInterface.DnsSettings.DnsServers = this.DnsServer;
                }
                if (this.InternalDnsNameLabel != null)
                {
                    networkInterface.DnsSettings.InternalDnsNameLabel = this.InternalDnsNameLabel;
                }
            }

            networkInterface.IpConfigurations.Add(nicIpConfiguration);

            var networkInterfaceModel = Mapper.Map <MNM.NetworkInterface>(networkInterface);

            networkInterfaceModel.Tags = TagsConversionHelper.CreateTagDictionary(this.Tag, validate: true);

            this.NetworkInterfaceClient.CreateOrUpdate(this.ResourceGroupName, this.Name, networkInterfaceModel);

            var getNetworkInterface = this.GetNetworkInterface(this.ResourceGroupName, this.Name);

            return(getNetworkInterface);
        }
        /// <summary>
        /// The create direct peering.
        /// </summary>
        /// <returns>
        /// The <see cref="PSPeering"/>.
        /// </returns>
        /// <exception cref="PSArgumentNullException">
        /// </exception>
        /// <exception cref="PSArgumentException">
        /// </exception>
        /// <exception cref="Exception">
        /// </exception>
        /// <exception cref="ArmErrorException">
        /// </exception>
        /// <exception cref="HttpRequestException">
        /// </exception>
        private PSPeering CreateDirectPeering()
        {
            var peeringRequest =
                new PSPeering(
                    name: this.Name,
                    location: this.GetAzureRegion(this.PeeringLocation, Constants.Direct),
                    sku: new PSPeeringSku {
                Name = this.Sku
            },
                    kind: Constants.Direct)
            {
                PeeringLocation = this.PeeringLocation,
                Direct          = new PSPeeringPropertiesDirect
                {
                    DirectPeeringType = this.ConvertToDirectPeeringType(this.MicrosoftNetwork),
                    Connections       = new List <PSDirectConnection>(),
                    PeerAsn           = new PSSubResource(this.PeerAsnResourceId),
                },
                Tags = TagsConversionHelper.CreateTagDictionary(this.Tag, true),
            };

            if (this.DirectConnection == null)
            {
                throw new PSArgumentNullException(string.Format(Resources.Create_NewConnectionObject, Constants.Direct));
            }

            foreach (var psDirectConnection in this.DirectConnection)
            {
                if (this.IsValidConnection(psDirectConnection))
                {
                    peeringRequest.Direct.Connections.Add(psDirectConnection);
                }
            }


            if (this.DirectConnection.Any((c) => c.UseForPeeringService == true))
            {
                if (this.Sku != Constants.PremiumDirectFree && this.Sku != Constants.PremiumDirectMetered && this.Sku != Constants.PremiumDirectUnlimited)
                {
                    throw new PSArgumentException(string.Format(Resources.Error_Sku, $"{Constants.PremiumDirectFree},{Constants.PremiumDirectMetered},{Constants.PremiumDirectUnlimited}"));
                }
            }

            if (this.ParameterSetName.Equals(Constants.Direct))
            {
                if (peeringRequest.Direct?.Connections.Count <= 0)
                {
                    throw new PSArgumentException(string.Format(Resources.Error_NullConnection, Constants.Direct));
                }
                if (peeringRequest.Exchange != null)
                {
                    peeringRequest.Exchange = null;
                }

                try
                {
                    return((PSPeering)this.PutNewPeering(peeringRequest));
                }
                catch (ErrorResponseException ex)
                {
                    var error = this.GetErrorCodeAndMessageFromArmOrErm(ex);
                    throw new ErrorResponseException(string.Format(Resources.Error_CloudError, error?.Code, error?.Message));
                }
            }
            else
            {
                throw new PSInvalidOperationException(string.Format(Resources.Error_GenericSyntax));
            }
        }
        public override void ExecuteCmdlet()
        {
            if (this.IsParameterBound(c => c.InputObject))
            {
                this.ResourceGroupName = new ResourceIdentifier(this.InputObject.Id).ResourceGroupName;
                this.Name = this.InputObject.Name;
            }

            if (this.IsParameterBound(c => c.ResourceId))
            {
                var resourceIdentifier = new ResourceIdentifier(this.ResourceId);
                this.ResourceGroupName = resourceIdentifier.ResourceGroupName;
                this.Name = resourceIdentifier.ResourceName;
            }

            if (string.IsNullOrEmpty(ResourceGroupName))
            {
                ResourceGroupName = SynapseAnalyticsClient.GetResourceGroupByWorkspaceName(Name);
            }

            Workspace existingWorkspace = null;

            try
            {
                existingWorkspace = SynapseAnalyticsClient.GetWorkspace(this.ResourceGroupName, this.Name);
            }
            catch
            {
                existingWorkspace = null;
            }

            if (existingWorkspace == null)
            {
                throw new AzPSInvalidOperationException(string.Format(Resources.FailedToDiscoverWorkspace, this.Name, this.ResourceGroupName));
            }

            WorkspacePatchInfo patchInfo = new WorkspacePatchInfo();

            patchInfo.Tags = this.IsParameterBound(c => c.Tag) ? TagsConversionHelper.CreateTagDictionary(this.Tag, validate: true) : TagsConversionHelper.CreateTagDictionary(this.InputObject?.Tags, validate: true);
            patchInfo.SqlAdministratorLoginPassword = this.IsParameterBound(c => c.SqlAdministratorLoginPassword) ? this.SqlAdministratorLoginPassword.ConvertToString() : null;

            if (ShouldProcess(this.Name, string.Format(Resources.UpdatingSynapseWorkspace, this.Name, this.ResourceGroupName)))
            {
                var workspace = new PSSynapseWorkspace(SynapseAnalyticsClient.UpdateWorkspace(
                                                           this.ResourceGroupName,
                                                           this.Name,
                                                           patchInfo));
                this.WriteObject(workspace);
            }
        }
        public override void Execute()
        {
            base.Execute();

            if (!this.IsVirtualNetworkGatewayPresent(this.VirtualNetworkGateway.ResourceGroupName, this.VirtualNetworkGateway.Name))
            {
                throw new ArgumentException(Microsoft.Azure.Commands.Network.Properties.Resources.ResourceNotFound);
            }

            this.VirtualNetworkGateway.ActiveActive = this.ActiveActive;

            if (this.VirtualNetworkGateway.ActiveActive)
            {
                bool activeActiveSkuCriteria = !string.IsNullOrEmpty(this.GatewaySku) ? !this.GatewaySku.Equals(MNM.VirtualNetworkGatewaySkuTier.HighPerformance) : !this.VirtualNetworkGateway.Sku.Tier.Equals(MNM.VirtualNetworkGatewaySkuTier.HighPerformance);

                if (activeActiveSkuCriteria)
                {
                    throw new ArgumentException("Virtual Network Gateway Sku should be " + MNM.VirtualNetworkGatewaySkuTier.HighPerformance + " when Active-Active feature flag is set to True.");
                }
            }

            if (!string.IsNullOrEmpty(GatewaySku))
            {
                this.VirtualNetworkGateway.Sku      = new PSVirtualNetworkGatewaySku();
                this.VirtualNetworkGateway.Sku.Tier = this.GatewaySku;
                this.VirtualNetworkGateway.Sku.Name = this.GatewaySku;
            }

            if (this.VirtualNetworkGateway.ActiveActive && !this.VirtualNetworkGateway.VpnType.Equals(MNM.VpnType.RouteBased))
            {
                throw new ArgumentException("Virtual Network Gateway VpnType should be " + MNM.VpnType.RouteBased + " when Active-Active feature flag is set to True.");
            }

            if (this.VirtualNetworkGateway.ActiveActive && this.VirtualNetworkGateway.IpConfigurations.Count != 2)
            {
                throw new ArgumentException("Virtual Network Gateway should have 2 Gateway IpConfigurations specified when Active-Active feature flag is True.");
            }

            if (!this.VirtualNetworkGateway.ActiveActive && this.VirtualNetworkGateway.IpConfigurations.Count == 2)
            {
                throw new ArgumentException("Virtual Network Gateway should have Active-Active feature flag set to True as there are 2 Gateway IpConfigurations specified. OR there should be only one Gateway IpConfiguration specified.");
            }

            if (this.GatewayDefaultSite != null)
            {
                this.VirtualNetworkGateway.GatewayDefaultSite    = new PSResourceId();
                this.VirtualNetworkGateway.GatewayDefaultSite.Id = this.GatewayDefaultSite.Id;
            }

            if ((this.VpnClientAddressPool != null || this.VpnClientRootCertificates != null || this.VpnClientRevokedCertificates != null) && this.VirtualNetworkGateway.VpnClientConfiguration == null)
            {
                this.VirtualNetworkGateway.VpnClientConfiguration = new PSVpnClientConfiguration();
            }

            if (this.VpnClientAddressPool != null)
            {
                this.VirtualNetworkGateway.VpnClientConfiguration.VpnClientAddressPool = new PSAddressSpace();
                this.VirtualNetworkGateway.VpnClientConfiguration.VpnClientAddressPool.AddressPrefixes = this.VpnClientAddressPool;
            }

            if (this.VpnClientRootCertificates != null)
            {
                this.VirtualNetworkGateway.VpnClientConfiguration.VpnClientRootCertificates = this.VpnClientRootCertificates;
            }

            if (this.VpnClientRevokedCertificates != null)
            {
                this.VirtualNetworkGateway.VpnClientConfiguration.VpnClientRevokedCertificates = this.VpnClientRevokedCertificates;
            }

            if ((this.Asn > 0 || this.PeerWeight > 0) && this.VirtualNetworkGateway.BgpSettings == null)
            {
                this.VirtualNetworkGateway.BgpSettings = new PSBgpSettings();
                this.VirtualNetworkGateway.BgpSettings.BgpPeeringAddress = null; // The gateway's BGP peering address (private IP address assigned within the vnet) can't be changed
            }

            if (this.Asn > 0)
            {
                this.VirtualNetworkGateway.BgpSettings.Asn = this.Asn;
            }

            if (this.PeerWeight > 0)
            {
                this.VirtualNetworkGateway.BgpSettings.PeerWeight = this.PeerWeight;
            }
            else if (this.PeerWeight < 0)
            {
                throw new ArgumentException("PeerWeight must be a positive integer");
            }

            // Map to the sdk object
            MNM.VirtualNetworkGateway sdkVirtualNetworkGateway = Mapper.Map <MNM.VirtualNetworkGateway>(this.VirtualNetworkGateway);
            sdkVirtualNetworkGateway.Tags = TagsConversionHelper.CreateTagDictionary(this.VirtualNetworkGateway.Tag, validate: true);

            this.VirtualNetworkGatewayClient.CreateOrUpdate(this.VirtualNetworkGateway.ResourceGroupName, this.VirtualNetworkGateway.Name, sdkVirtualNetworkGateway);

            var getVirtualNetworkGateway = this.GetVirtualNetworkGateway(this.VirtualNetworkGateway.ResourceGroupName, this.VirtualNetworkGateway.Name);

            WriteObject(getVirtualNetworkGateway);
        }
        /// <summary>
        /// Update an existing vault. Only EnabledForDeployment and AccessPolicies can be updated currently.
        /// </summary>
        /// <param name="existingVault">the existing vault</param>
        /// <param name="updatedPolicies">the update access policies</param>
        /// <param name="updatedEnabledForDeployment">enabled for deployment</param>
        /// <param name="updatedEnabledForTemplateDeployment">enabled for template deployment</param>
        /// <param name="updatedEnabledForDiskEncryption">enabled for disk encryption</param>
        /// <param name="updatedNetworkAcls">updated network rule set</param>
        /// <param name="adClient">the active directory client</param>
        /// <returns>the updated vault</returns>
        public PSKeyVault UpdateVault(
            PSKeyVault existingVault,
            PSKeyVaultAccessPolicy[] updatedPolicies,
            bool?updatedEnabledForDeployment,
            bool?updatedEnabledForTemplateDeployment,
            bool?updatedEnabledForDiskEncryption,
            bool?updatedSoftDeleteSwitch,
            bool?updatedPurgeProtectionSwitch,
            bool?updatedRbacAuthorization,
            int?softDeleteRetentionInDays,
            PSKeyVaultNetworkRuleSet updatedNetworkAcls,
            ActiveDirectoryClient adClient = null)
        {
            if (existingVault == null)
            {
                throw new ArgumentNullException("existingVault");
            }
            if (existingVault.OriginalVault == null)
            {
                throw new ArgumentNullException("existingVault.OriginalVault");
            }

            //Update the vault properties in the object received from server
            //Only access policies and EnabledForDeployment can be changed
            var properties = existingVault.OriginalVault.Properties;

            properties.EnabledForDeployment         = updatedEnabledForDeployment;
            properties.EnabledForTemplateDeployment = updatedEnabledForTemplateDeployment;
            properties.EnabledForDiskEncryption     = updatedEnabledForDiskEncryption;
            properties.SoftDeleteRetentionInDays    = softDeleteRetentionInDays;

            // soft delete flags can only be applied if they enable their respective behaviors
            // and if different from the current corresponding properties on the vault.
            if (!(properties.EnableSoftDelete.HasValue && properties.EnableSoftDelete.Value) &&
                updatedSoftDeleteSwitch.HasValue &&
                updatedSoftDeleteSwitch.Value)
            {
                properties.EnableSoftDelete = updatedSoftDeleteSwitch;
            }

            if (!(properties.EnablePurgeProtection.HasValue && properties.EnablePurgeProtection.Value) &&
                updatedPurgeProtectionSwitch.HasValue &&
                updatedPurgeProtectionSwitch.Value)
            {
                properties.EnablePurgeProtection = updatedPurgeProtectionSwitch;
            }

            // Update EnableRbacAuthorization when specified, otherwise stay current value
            properties.EnableRbacAuthorization = updatedRbacAuthorization;

            properties.AccessPolicies = (updatedPolicies == null) ?
                                        new List <AccessPolicyEntry>() :
                                        updatedPolicies.Select(a => new AccessPolicyEntry
            {
                TenantId      = a.TenantId,
                ObjectId      = a.ObjectId,
                ApplicationId = a.ApplicationId,
                Permissions   = new Permissions
                {
                    Keys         = a.PermissionsToKeys.ToArray(),
                    Secrets      = a.PermissionsToSecrets.ToArray(),
                    Certificates = a.PermissionsToCertificates.ToArray(),
                    Storage      = a.PermissionsToStorage.ToArray(),
                }
            }).ToList();

            UpdateVaultNetworkRuleSetProperties(properties, updatedNetworkAcls);

            var response = KeyVaultManagementClient.Vaults.CreateOrUpdate(
                resourceGroupName: existingVault.ResourceGroupName,
                vaultName: existingVault.VaultName,
                parameters: new VaultCreateOrUpdateParameters
            {
                Location   = existingVault.Location,
                Properties = properties,
                Tags       = TagsConversionHelper.CreateTagDictionary(existingVault.Tags, validate: true)
            }
                );

            return(new PSKeyVault(response, adClient));
        }
        public override void ExecuteCmdlet()
        {
            switch (ParameterSetName)
            {
            case CreateByNameAndEnableAutoScaleParameterSet:
            case CreateByParentObjectAndEnableAutoScaleParameterSet:
                this.enableAutoScale = true;
                break;
            }

            if (this.IsParameterBound(c => c.WorkspaceObject))
            {
                this.ResourceGroupName = new ResourceIdentifier(this.WorkspaceObject.Id).ResourceGroupName;
                this.WorkspaceName     = this.WorkspaceObject.Name;
            }

            if (string.IsNullOrEmpty(this.ResourceGroupName))
            {
                this.ResourceGroupName = this.SynapseAnalyticsClient.GetResourceGroupByWorkspaceName(this.WorkspaceName);
            }

            BigDataPoolResourceInfo existingSparkPool = null;

            try
            {
                existingSparkPool = this.SynapseAnalyticsClient.GetSparkPool(this.ResourceGroupName, this.WorkspaceName, this.Name);
            }
            catch
            {
                existingSparkPool = null;
            }

            if (existingSparkPool != null)
            {
                throw new AzPSInvalidOperationException(string.Format(Resources.SynapseSparkPoolExists, this.Name, this.ResourceGroupName, this.WorkspaceName));
            }

            Workspace existingWorkspace = null;

            try
            {
                existingWorkspace = this.SynapseAnalyticsClient.GetWorkspace(this.ResourceGroupName, this.WorkspaceName);
            }
            catch
            {
                existingWorkspace = null;
            }

            if (existingWorkspace == null)
            {
                throw new AzPSResourceNotFoundCloudException(string.Format(Resources.WorkspaceDoesNotExist, this.WorkspaceName));
            }

            SparkConfigProperties sparkConfigProperties = null;

            if (this.IsParameterBound(c => c.SparkConfigFilePath))
            {
                string path     = this.TryResolvePath(SparkConfigFilePath);
                string filename = Path.GetFileNameWithoutExtension(path);
                sparkConfigProperties = new SparkConfigProperties()
                {
                    Content  = this.ReadFileAsText(this.SparkConfigFilePath),
                    Filename = filename
                };
            }

            var createParams = new BigDataPoolResourceInfo
            {
                Location       = existingWorkspace.Location,
                Tags           = TagsConversionHelper.CreateTagDictionary(this.Tag, validate: true),
                NodeCount      = this.enableAutoScale ? (int?)null : this.NodeCount,
                NodeSizeFamily = NodeSizeFamily.MemoryOptimized,
                NodeSize       = NodeSize,
                AutoScale      = !this.enableAutoScale ? new AutoScaleProperties {
                    Enabled = false
                } : new AutoScaleProperties
                {
                    Enabled      = this.enableAutoScale,
                    MinNodeCount = AutoScaleMinNodeCount,
                    MaxNodeCount = AutoScaleMaxNodeCount
                },
                AutoPause = !EnableAutoPause ? new AutoPauseProperties {
                    Enabled = false
                } : new AutoPauseProperties
                {
                    Enabled        = EnableAutoPause.IsPresent,
                    DelayInMinutes = AutoPauseDelayInMinute
                },
                SparkVersion          = this.SparkVersion,
                SparkConfigProperties = sparkConfigProperties
            };

            if (this.ShouldProcess(this.Name, string.Format(Resources.CreatingSynapseSparkPool, this.ResourceGroupName, this.WorkspaceName, this.Name)))
            {
                var result = new PSSynapseSparkPool(this.SynapseAnalyticsClient.CreateOrUpdateSparkPool(this.ResourceGroupName, this.WorkspaceName, this.Name, createParams));
                WriteObject(result);
            }
        }
        /// <summary>
        /// Create a Managed HSM pool
        /// </summary>
        /// <param name="parameters">vault creation parameters</param>
        /// <param name="adClient">the active directory client</param>
        /// <returns></returns>
        public PSManagedHsm CreateNewManagedHsm(VaultCreationOrUpdateParameters parameters, ActiveDirectoryClient adClient = null)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            if (string.IsNullOrWhiteSpace(parameters.Name))
            {
                throw new ArgumentNullException("parameters.Name");
            }
            if (string.IsNullOrWhiteSpace(parameters.ResourceGroupName))
            {
                throw new ArgumentNullException("parameters.ResourceGroupName");
            }
            if (string.IsNullOrWhiteSpace(parameters.Location))
            {
                throw new ArgumentNullException("parameters.Location");
            }
            if (parameters.Administrator.Length == 0)
            {
                throw new ArgumentNullException("parameters.Administrator");
            }

            var properties    = new ManagedHsmProperties();
            var managedHsmSku = new ManagedHsmSku();

            if (parameters.CreateMode != CreateMode.Recover)
            {
                if (string.IsNullOrWhiteSpace(parameters.SkuFamilyName))
                {
                    throw new ArgumentNullException("parameters.SkuFamilyName");
                }
                if (parameters.TenantId == Guid.Empty)
                {
                    throw new ArgumentException("parameters.TenantId");
                }
                if (!string.IsNullOrWhiteSpace(parameters.SkuName))
                {
                    if (Enum.TryParse(parameters.SkuName, true, out ManagedHsmSkuName skuName))
                    {
                        managedHsmSku.Name = skuName;
                    }
                    else
                    {
                        throw new InvalidEnumArgumentException("parameters.SkuName");
                    }
                }
                properties.TenantId = parameters.TenantId;
                properties.InitialAdminObjectIds = parameters.Administrator;
                properties.HsmUri                    = "";
                properties.EnableSoftDelete          = parameters.EnableSoftDelete;
                properties.SoftDeleteRetentionInDays = parameters.SoftDeleteRetentionInDays;
                properties.EnablePurgeProtection     = parameters.EnablePurgeProtection;
            }
            else
            {
                properties.CreateMode = CreateMode.Recover;
            }

            var response = KeyVaultManagementClient.ManagedHsms.CreateOrUpdate(
                resourceGroupName: parameters.ResourceGroupName,
                name: parameters.Name,
                parameters: new ManagedHsm
            {
                Location   = parameters.Location,
                Sku        = managedHsmSku,
                Tags       = TagsConversionHelper.CreateTagDictionary(parameters.Tags, validate: true),
                Properties = properties
            });

            return(new PSManagedHsm(response, adClient));
        }
示例#21
0
        private PSApplicationGateway CreateApplicationGateway()
        {
            var applicationGateway = new PSApplicationGateway();

            applicationGateway.Name = this.Name;
            applicationGateway.ResourceGroupName = this.ResourceGroupName;
            applicationGateway.Location          = this.Location;
            applicationGateway.Sku = this.Sku;

            if (this.SslPolicy != null)
            {
                applicationGateway.SslPolicy = new PSApplicationGatewaySslPolicy();
                applicationGateway.SslPolicy = this.SslPolicy;
            }

            if (this.GatewayIPConfigurations != null)
            {
                applicationGateway.GatewayIPConfigurations = this.GatewayIPConfigurations;
            }

            if (this.SslCertificates != null)
            {
                applicationGateway.SslCertificates = this.SslCertificates;
            }

            if (this.AuthenticationCertificates != null)
            {
                applicationGateway.AuthenticationCertificates = this.AuthenticationCertificates;
            }

            if (this.FrontendIPConfigurations != null)
            {
                applicationGateway.FrontendIPConfigurations = this.FrontendIPConfigurations;
            }

            if (this.FrontendPorts != null)
            {
                applicationGateway.FrontendPorts = this.FrontendPorts;
            }

            if (this.Probes != null)
            {
                applicationGateway.Probes = this.Probes;
            }

            if (this.BackendAddressPools != null)
            {
                applicationGateway.BackendAddressPools = this.BackendAddressPools;
            }

            if (this.BackendHttpSettingsCollection != null)
            {
                applicationGateway.BackendHttpSettingsCollection = this.BackendHttpSettingsCollection;
            }

            if (this.HttpListeners != null)
            {
                applicationGateway.HttpListeners = this.HttpListeners;
            }

            if (this.UrlPathMaps != null)
            {
                applicationGateway.UrlPathMaps = this.UrlPathMaps;
            }

            if (this.RequestRoutingRules != null)
            {
                applicationGateway.RequestRoutingRules = this.RequestRoutingRules;
            }

            // Normalize the IDs
            ApplicationGatewayChildResourceHelper.NormalizeChildResourcesId(applicationGateway);

            // Map to the sdk object
            var appGwModel = Mapper.Map <MNM.ApplicationGateway>(applicationGateway);

            appGwModel.Tags = TagsConversionHelper.CreateTagDictionary(this.Tag, validate: true);

            // Execute the Create ApplicationGateway call
            this.ApplicationGatewayClient.CreateOrUpdate(this.ResourceGroupName, this.Name, appGwModel);

            var getApplicationGateway = this.GetApplicationGateway(this.ResourceGroupName, this.Name);

            return(getApplicationGateway);
        }
        /// <summary>
        /// Create a new vault
        /// </summary>
        /// <param name="parameters">vault creation parameters</param>
        /// <param name="adClient">the active directory client</param>
        /// <returns></returns>
        public PSKeyVault CreateNewVault(VaultCreationOrUpdateParameters parameters, ActiveDirectoryClient adClient = null, PSKeyVaultNetworkRuleSet networkRuleSet = null)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            if (string.IsNullOrWhiteSpace(parameters.Name))
            {
                throw new ArgumentNullException("parameters.Name");
            }
            if (string.IsNullOrWhiteSpace(parameters.ResourceGroupName))
            {
                throw new ArgumentNullException("parameters.ResourceGroupName");
            }
            if (string.IsNullOrWhiteSpace(parameters.Location))
            {
                throw new ArgumentNullException("parameters.Location");
            }

            var properties = new VaultProperties();

            if (parameters.CreateMode != CreateMode.Recover)
            {
                if (string.IsNullOrWhiteSpace(parameters.SkuFamilyName))
                {
                    throw new ArgumentNullException("parameters.SkuFamilyName");
                }
                if (parameters.TenantId == Guid.Empty)
                {
                    throw new ArgumentException("parameters.TenantId");
                }
                if (!string.IsNullOrWhiteSpace(parameters.SkuName))
                {
                    if (Enum.TryParse(parameters.SkuName, true, out SkuName skuName))
                    {
                        properties.Sku = new Sku(skuName);
                    }
                    else
                    {
                        throw new InvalidEnumArgumentException("parameters.SkuName");
                    }
                }
                properties.EnabledForDeployment         = parameters.EnabledForDeployment;
                properties.EnabledForTemplateDeployment = parameters.EnabledForTemplateDeployment;
                properties.EnabledForDiskEncryption     = parameters.EnabledForDiskEncryption;
                properties.EnableSoftDelete             = parameters.EnableSoftDelete;
                properties.EnablePurgeProtection        = parameters.EnablePurgeProtection;
                properties.EnableRbacAuthorization      = parameters.EnableRbacAuthorization;
                properties.SoftDeleteRetentionInDays    = parameters.SoftDeleteRetentionInDays;
                properties.TenantId       = parameters.TenantId;
                properties.VaultUri       = "";
                properties.AccessPolicies = (parameters.AccessPolicy != null) ? new[] { parameters.AccessPolicy } : new AccessPolicyEntry[] { };

                properties.NetworkAcls = parameters.NetworkAcls;
                if (networkRuleSet != null)
                {
                    UpdateVaultNetworkRuleSetProperties(properties, networkRuleSet);
                }
            }
            else
            {
                properties.CreateMode = CreateMode.Recover;
            }

            var response = KeyVaultManagementClient.Vaults.CreateOrUpdate(
                resourceGroupName: parameters.ResourceGroupName,
                vaultName: parameters.Name,
                parameters: new VaultCreateOrUpdateParameters
            {
                Location   = parameters.Location,
                Tags       = TagsConversionHelper.CreateTagDictionary(parameters.Tags, validate: true),
                Properties = properties
            });

            return(new PSKeyVault(response, adClient));
        }
示例#23
0
        private PSAzureFirewall CreateAzureFirewall()
        {
            var firewall = new PSAzureFirewall();

            if (Sku == MNM.AzureFirewallSkuName.AZFWHub)
            {
                if (VirtualHubId != null && this.Location != null)
                {
                    var resourceInfo = new ResourceIdentifier(VirtualHubId);
                    var hub          = this.VirtualHubClient.Get(resourceInfo.ResourceGroupName, resourceInfo.ResourceName);
                    if (hub.Location != this.Location)
                    {
                        throw new ArgumentException("VirtualHub and Firewall cannot be in different locations", nameof(VirtualHubId));
                    }
                }

                var sku = new PSAzureFirewallSku();
                sku.Name = MNM.AzureFirewallSkuName.AZFWHub;
                sku.Tier = MNM.AzureFirewallSkuTier.Standard;

                firewall = new PSAzureFirewall()
                {
                    Name = this.Name,
                    ResourceGroupName = this.ResourceGroupName,
                    Location          = this.Location,
                    Sku            = sku,
                    VirtualHub     = VirtualHubId != null ? new MNM.SubResource(VirtualHubId) : null,
                    FirewallPolicy = FirewallPolicyId != null ? new MNM.SubResource(FirewallPolicyId) : null
                };
            }
            else
            {
                var sku = new PSAzureFirewallSku();
                sku.Name = MNM.AzureFirewallSkuName.AZFWVNet;
                sku.Tier = MNM.AzureFirewallSkuTier.Standard;
                firewall = new PSAzureFirewall()
                {
                    Name = this.Name,
                    ResourceGroupName          = this.ResourceGroupName,
                    Location                   = this.Location,
                    FirewallPolicy             = FirewallPolicyId != null ? new MNM.SubResource(FirewallPolicyId) : null,
                    ApplicationRuleCollections = this.ApplicationRuleCollection?.ToList(),
                    NatRuleCollections         = this.NatRuleCollection?.ToList(),
                    NetworkRuleCollections     = this.NetworkRuleCollection?.ToList(),
                    ThreatIntelMode            = this.ThreatIntelMode ?? MNM.AzureFirewallThreatIntelMode.Alert,
                    ThreatIntelWhitelist       = this.ThreatIntelWhitelist,
                    PrivateRange               = this.PrivateRange,
                    Sku = sku
                };

                if (this.Zone != null)
                {
                    firewall.Zones = this.Zone?.ToList();
                }

                if (this.virtualNetwork != null)
                {
                    firewall.Allocate(this.virtualNetwork, this.publicIpAddresses, this.ManagementPublicIpAddress);
                }
            }

            // Map to the sdk object
            var azureFirewallModel = NetworkResourceManagerProfile.Mapper.Map <MNM.AzureFirewall>(firewall);

            azureFirewallModel.Tags = TagsConversionHelper.CreateTagDictionary(this.Tag, validate: true);

            // Execute the Create AzureFirewall call
            this.AzureFirewallClient.CreateOrUpdate(this.ResourceGroupName, this.Name, azureFirewallModel);
            return(this.GetAzureFirewall(this.ResourceGroupName, this.Name));
        }
示例#24
0
        public override void Execute()
        {
            base.Execute();

            ConfirmAction(
                Force.IsPresent,
                string.Format(Properties.Resources.OverwritingResource, VirtualNetworkGatewayConnection.Name),
                Properties.Resources.SettingResourceMessage,
                VirtualNetworkGatewayConnection.Name,
                () =>
            {
                if (!this.IsVirtualNetworkGatewayConnectionPresent(this.VirtualNetworkGatewayConnection.ResourceGroupName, this.VirtualNetworkGatewayConnection.Name))
                {
                    throw new ArgumentException(Properties.Resources.ResourceNotFound);
                }

                if (this.EnableBgp.HasValue)
                {
                    this.VirtualNetworkGatewayConnection.EnableBgp = this.EnableBgp.Value;
                }

                if (this.DpdTimeoutInSeconds.HasValue)
                {
                    this.VirtualNetworkGatewayConnection.DpdTimeoutSeconds = this.DpdTimeoutInSeconds.Value;
                }

                if (!String.IsNullOrEmpty(this.ConnectionMode))
                {
                    this.VirtualNetworkGatewayConnection.ConnectionMode = this.ConnectionMode;
                }

                if (this.UsePolicyBasedTrafficSelectors.HasValue)
                {
                    this.VirtualNetworkGatewayConnection.UsePolicyBasedTrafficSelectors = this.UsePolicyBasedTrafficSelectors.Value;
                }

                if (this.UseLocalAzureIpAddress.HasValue)
                {
                    this.VirtualNetworkGatewayConnection.UseLocalAzureIpAddress = this.UseLocalAzureIpAddress.Value;
                }

                if (this.IpsecPolicies != null)
                {
                    this.VirtualNetworkGatewayConnection.IpsecPolicies = this.IpsecPolicies?.ToList();
                }

                if (this.TrafficSelectorPolicy != null)
                {
                    this.VirtualNetworkGatewayConnection.TrafficSelectorPolicies = this.TrafficSelectorPolicy?.ToList();
                }

                var vnetGatewayConnectionModel = NetworkResourceManagerProfile.Mapper.Map <MNM.VirtualNetworkGatewayConnection>(this.VirtualNetworkGatewayConnection);

                vnetGatewayConnectionModel.Tags =
                    ParameterSetName.Equals(VirtualNetworkGatewayParameterSets.UpdateResourceWithTags) ?
                    TagsConversionHelper.CreateTagDictionary(this.Tag, validate: true) :
                    TagsConversionHelper.CreateTagDictionary(this.VirtualNetworkGatewayConnection.Tag, validate: true);

                this.VirtualNetworkGatewayConnectionClient.CreateOrUpdate(
                    this.VirtualNetworkGatewayConnection.ResourceGroupName,
                    this.VirtualNetworkGatewayConnection.Name, vnetGatewayConnectionModel);
                var getvnetGatewayConnection = this.GetVirtualNetworkGatewayConnection(this.VirtualNetworkGatewayConnection.ResourceGroupName, this.VirtualNetworkGatewayConnection.Name);
                WriteObject(getvnetGatewayConnection);
            });
        }
        public DataLakeStoreAccount CreateAccount(
            string resourceGroupName,
            string accountName,
            string defaultGroup,
            string location,
            Hashtable customTags        = null,
            EncryptionIdentity identity = null,
            EncryptionConfig config     = null,
            IList <TrustedIdProvider> trustedProviders = null,
            IList <FirewallRule> firewallRules         = null,
            EncryptionConfigType?encryptionType        = null,
            TierType?tier = null)
        {
            if (string.IsNullOrEmpty(resourceGroupName))
            {
                resourceGroupName = GetResourceGroupByAccount(accountName);
            }

            var tags = TagsConversionHelper.CreateTagDictionary(customTags, true);

            var parameters = new DataLakeStoreAccount
            {
                Location     = location,
                DefaultGroup = defaultGroup,
                Tags         = tags ?? new Dictionary <string, string>()
            };

            if (identity != null)
            {
                parameters.EncryptionState  = EncryptionState.Enabled;
                parameters.Identity         = identity;
                parameters.EncryptionConfig = config ?? new EncryptionConfig
                {
                    Type = EncryptionConfigType.ServiceManaged
                };
            }

            if (trustedProviders != null && trustedProviders.Count > 0)
            {
                parameters.TrustedIdProviders     = trustedProviders;
                parameters.TrustedIdProviderState = TrustedIdProviderState.Enabled;
            }

            if (firewallRules != null && firewallRules.Count > 0)
            {
                parameters.FirewallRules = firewallRules;
                parameters.FirewallState = FirewallState.Enabled;
            }

            // if there is no encryption value, then it was not set by the cmdlet which means encryption was explicitly disabled.
            if (!encryptionType.HasValue)
            {
                parameters.EncryptionState  = EncryptionState.Disabled;
                parameters.Identity         = null;
                parameters.EncryptionConfig = null;
            }

            if (tier.HasValue)
            {
                parameters.NewTier = tier;
            }

            return(_client.Account.Create(resourceGroupName, accountName, parameters));
        }
示例#26
0
        public AnalysisServicesServer CreateOrUpdateServer(
            string resourceGroupName,
            string serverName,
            string location,
            string skuName        = null,
            Hashtable customTags  = null,
            string administrators = null,
            AnalysisServicesServer existingServer = null,
            string backupBlobContainerUri         = null,
            int ReadonlyReplicaCount     = 0,
            string DefaultConnectionMode = null,
            IPv4FirewallSettings setting = null)
        {
            if (string.IsNullOrEmpty(resourceGroupName))
            {
                resourceGroupName = GetResourceGroupByServer(serverName);
            }

            var tags = (customTags != null)
                ? TagsConversionHelper.CreateTagDictionary(customTags, true)
                : null;

            var adminList = new List <string>();

            if (!string.IsNullOrEmpty(administrators))
            {
                adminList.AddRange(administrators.Split(','));
                if (adminList.Count == 0)
                {
                    adminList.Add(_currentUser);
                }
            }

            AnalysisServicesServer newOrUpdatedServer = null;

            if (existingServer != null)
            {
                var updateParameters = new AnalysisServicesServerUpdateParameters()
                {
                    Sku  = skuName == null ? existingServer.Sku : GetResourceSkuFromName(skuName),
                    Tags = tags,
                };

                if (adminList.Count > 0)
                {
                    updateParameters.AsAdministrators = new ServerAdministrators(adminList);
                }

                if (backupBlobContainerUri != null)
                {
                    updateParameters.BackupBlobContainerUri = backupBlobContainerUri;
                }

                if (ReadonlyReplicaCount != -1)
                {
                    updateParameters.Sku.Capacity = ReadonlyReplicaCount + 1;
                }

                if (DefaultConnectionMode != null)
                {
                    updateParameters.QuerypoolConnectionMode = (ConnectionMode)Enum.Parse(typeof(ConnectionMode), DefaultConnectionMode, true);
                }

                if (setting != null)
                {
                    updateParameters.IpV4FirewallSettings = setting;
                }

                newOrUpdatedServer = _client.Servers.Update(resourceGroupName, serverName, updateParameters);
            }
            else
            {
                ConnectionMode?connectionMode = null;
                if (DefaultConnectionMode != null)
                {
                    connectionMode = (ConnectionMode)Enum.Parse(typeof(ConnectionMode), DefaultConnectionMode, true);
                }

                newOrUpdatedServer = _client.Servers.Create(
                    resourceGroupName,
                    serverName,
                    new AnalysisServicesServer()
                {
                    AsAdministrators       = new ServerAdministrators(adminList),
                    BackupBlobContainerUri = backupBlobContainerUri,
                    Location = location,
                    Sku      = GetResourceSkuFromName(skuName, ReadonlyReplicaCount + 1),
                    Tags     = tags,
                    QuerypoolConnectionMode = connectionMode,
                    IpV4FirewallSettings    = setting
                });
            }

            return(newOrUpdatedServer);
        }
示例#27
0
 private AppPatch CreateApplicationPatch()
 {
     return(new AppPatch(TagsConversionHelper.CreateTagDictionary(this.Tag, true), null, this.DisplayName, this.Subdomain));
 }
        public override void ExecuteCmdlet()
        {
            if (this.IsParameterBound(c => c.WorkspaceObject))
            {
                this.ResourceGroupName = new ResourceIdentifier(this.WorkspaceObject.Id).ResourceGroupName;
                this.WorkspaceName     = this.WorkspaceObject.Name;
            }

            if (string.IsNullOrEmpty(this.ResourceGroupName))
            {
                this.ResourceGroupName = this.SynapseAnalyticsClient.GetResourceGroupByWorkspaceName(this.WorkspaceName);
            }

            BigDataPoolResourceInfo existingSparkPool = null;

            try
            {
                existingSparkPool = this.SynapseAnalyticsClient.GetSparkPool(this.ResourceGroupName, this.WorkspaceName, this.Name);
            }
            catch
            {
                existingSparkPool = null;
            }

            if (existingSparkPool != null)
            {
                throw new SynapseException(string.Format(Resources.SynapseSparkPoolExists, this.Name, this.ResourceGroupName, this.WorkspaceName));
            }

            Workspace existingWorkspace = null;

            try
            {
                existingWorkspace = this.SynapseAnalyticsClient.GetWorkspace(this.ResourceGroupName, this.WorkspaceName);
            }
            catch
            {
                existingWorkspace = null;
            }

            if (existingWorkspace == null)
            {
                throw new SynapseException(string.Format(Resources.WorkspaceDoesNotExist, this.WorkspaceName));
            }

            LibraryRequirements libraryRequirements = null;

            if (this.IsParameterBound(c => c.LibraryRequirementsFilePath))
            {
                var powerShellDestinationPath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(LibraryRequirementsFilePath);

                libraryRequirements = new LibraryRequirements
                {
                    Filename = Path.GetFileName(powerShellDestinationPath),
                    Content  = this.ReadFileAsText(powerShellDestinationPath),
                };
            }

            var createParams = new BigDataPoolResourceInfo
            {
                Location       = existingWorkspace.Location,
                Tags           = TagsConversionHelper.CreateTagDictionary(this.Tag, validate: true),
                NodeCount      = this.NodeCount,
                NodeSizeFamily = NodeSizeFamily.MemoryOptimized,
                NodeSize       = NodeSize,
                AutoScale      = !EnableAutoScale.IsPresent ? null : new AutoScaleProperties
                {
                    Enabled      = EnableAutoScale.IsPresent,
                    MinNodeCount = AutoScaleMinNodeCount,
                    MaxNodeCount = AutoScaleMaxNodeCount
                },
                AutoPause = !EnableAutoPause ? null : new AutoPauseProperties
                {
                    Enabled        = EnableAutoPause.IsPresent,
                    DelayInMinutes = AutoPauseDelayInMinute
                },
                SparkVersion        = this.SparkVersion,
                LibraryRequirements = libraryRequirements
            };

            if (this.ShouldProcess(this.Name, string.Format(Resources.CreatingSynapseSparkPool, this.ResourceGroupName, this.WorkspaceName, this.Name)))
            {
                var result = new PSSynapseSparkPool(this.SynapseAnalyticsClient.CreateOrUpdateSparkPool(this.ResourceGroupName, this.WorkspaceName, this.Name, createParams));
                WriteObject(result);
            }
        }
示例#29
0
        /// <summary>
        /// Create a new vault
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public PSVault CreateNewVault(VaultCreationParameters parameters, ActiveDirectoryClient adClient = null)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            if (string.IsNullOrWhiteSpace(parameters.VaultName))
            {
                throw new ArgumentNullException("parameters.VaultName");
            }
            if (string.IsNullOrWhiteSpace(parameters.ResourceGroupName))
            {
                throw new ArgumentNullException("parameters.ResourceGroupName");
            }
            if (string.IsNullOrWhiteSpace(parameters.Location))
            {
                throw new ArgumentNullException("parameters.Location");
            }
            if (string.IsNullOrWhiteSpace(parameters.SkuName))
            {
                throw new ArgumentNullException("parameters.SkuName");
            }
            if (string.IsNullOrWhiteSpace(parameters.SkuFamilyName))
            {
                throw new ArgumentNullException("parameters.SkuFamilyName");
            }
            if (parameters.TenantId == null || parameters.TenantId == Guid.Empty)
            {
                throw new ArgumentException("parameters.TenantId");
            }
            if (parameters.ObjectId == null || parameters.ObjectId == Guid.Empty)
            {
                throw new ArgumentException("parameters.ObjectId");
            }

            var response = this.KeyVaultManagementClient.Vaults.CreateOrUpdate(
                resourceGroupName: parameters.ResourceGroupName,
                vaultName: parameters.VaultName,

                parameters: new VaultCreateOrUpdateParameters()
            {
                Location   = parameters.Location,
                Tags       = TagsConversionHelper.CreateTagDictionary(parameters.Tags, validate: true),
                Properties = new VaultProperties()
                {
                    Sku = new Sku()
                    {
                        Family = parameters.SkuFamilyName,
                        Name   = parameters.SkuName
                    },
                    EnabledForDeployment         = parameters.EnabledForDeployment,
                    EnabledForTemplateDeployment = parameters.EnabledForTemplateDeployment,
                    EnabledForDiskEncryption     = parameters.EnabledForDiskEncryption,
                    TenantId       = parameters.TenantId,
                    VaultUri       = "",
                    AccessPolicies = new AccessPolicyEntry[]
                    {
                        new AccessPolicyEntry
                        {
                            TenantId             = parameters.TenantId,
                            ObjectId             = parameters.ObjectId,
                            PermissionsToKeys    = parameters.PermissionsToKeys,
                            PermissionsToSecrets = parameters.PermissionsToSecrets
                        }
                    }
                }
            }
                );

            return(new PSVault(response.Vault, adClient));
        }
示例#30
0
        public override void Execute()
        {
            base.Execute();

            // Sku
            PSNatGatewaySku vSku = null;

            if (this.Sku != null)
            {
                if (vSku == null)
                {
                    vSku = new PSNatGatewaySku();
                }
                vSku.Name = MNM.NatGatewaySkuName.Standard;
            }

            // PublicIpAddresses
            List <PSResourceId> vPublicIpAddresses = null;

            // PublicIpPrefixes
            List <PSResourceId> vPublicIpPrefixes = null;

            vPublicIpAddresses = this.PublicIpAddress?.ToList();
            vPublicIpPrefixes  = this.PublicIpPrefix?.ToList();

            var vNatGateway = new PSNatGateway
            {
                IdleTimeoutInMinutes = this.IdleTimeoutInMinutes,
                Location             = this.Location,
                Sku = vSku,
                PublicIpAddresses = vPublicIpAddresses,
                PublicIpPrefixes  = vPublicIpPrefixes,
            };

            vNatGateway.Zones = this.Zone?.ToList();

            var vNatGatewayModel = NetworkResourceManagerProfile.Mapper.Map <MNM.NatGateway>(vNatGateway);

            vNatGatewayModel.Tags = TagsConversionHelper.CreateTagDictionary(this.Tag, validate: true);
            var present = true;

            try
            {
                this.NetworkClient.NetworkManagementClient.NatGateways.Get(this.ResourceGroupName, this.Name);
            }
            catch (Microsoft.Rest.Azure.CloudException exception)
            {
                if (exception.Response.StatusCode == HttpStatusCode.NotFound)
                {
                    // Resource is not present
                    present = false;
                }
                else
                {
                    throw;
                }
            }

            ConfirmAction(
                Force.IsPresent,
                string.Format(Properties.Resources.OverwritingResource, Name),
                Properties.Resources.CreatingResourceMessage,
                Name,
                () =>
            {
                this.NetworkClient.NetworkManagementClient.NatGateways.CreateOrUpdate(this.ResourceGroupName, this.Name, vNatGatewayModel);
                var getNatGateway = this.NetworkClient.NetworkManagementClient.NatGateways.Get(this.ResourceGroupName, this.Name);
                var psNatGateway  = NetworkResourceManagerProfile.Mapper.Map <PSNatGateway>(getNatGateway);
                psNatGateway.ResourceGroupName = this.ResourceGroupName;
                psNatGateway.Tag = TagsConversionHelper.CreateTagHashtable(getNatGateway.Tags);
                WriteObject(psNatGateway, true);
            },
                () => present);
        }