/// <summary>
        /// Create the model from user input
        /// </summary>
        /// <param name="model">Model retrieved from service</param>
        /// <returns>The model that was passed in</returns>
        protected override IEnumerable <AzureSqlElasticPoolModel> ApplyUserInputToModel(IEnumerable <AzureSqlElasticPoolModel> model)
        {
            string location = ModelAdapter.GetServerLocation(ResourceGroupName, ServerName);
            List <AzureSqlElasticPoolModel> newEntity = new List <AzureSqlElasticPoolModel>();
            AzureSqlElasticPoolModel        newModel  = new AzureSqlElasticPoolModel()
            {
                ResourceGroupName = ResourceGroupName,
                ServerName        = ServerName,
                ElasticPoolName   = ElasticPoolName,
                Tags          = TagsConversionHelper.CreateTagDictionary(Tags, validate: true),
                Location      = location,
                ZoneRedundant = MyInvocation.BoundParameters.ContainsKey("ZoneRedundant") ? (bool?)ZoneRedundant.ToBool() : null,
                MaxSizeBytes  = MyInvocation.BoundParameters.ContainsKey("StorageMB") ? (long?)(StorageMB * Megabytes) : null
            };

            var elasticPool = ModelAdapter.GetElasticPool(ResourceGroupName, ServerName, ElasticPoolName);

            Management.Sql.Models.Sku poolCurrentSku = new Management.Sql.Models.Sku()
            {
                Name     = elasticPool.SkuName,
                Tier     = elasticPool.Edition,
                Family   = elasticPool.Family,
                Capacity = elasticPool.Capacity
            };
            Management.Sql.Models.ElasticPoolPerDatabaseSettings poolCurrentDbSetting = new Management.Sql.Models.ElasticPoolPerDatabaseSettings()
            {
                MinCapacity = elasticPool.DatabaseCapacityMin,
                MaxCapacity = elasticPool.DatabaseCapacityMax
            };

            if (ParameterSetName == DtuPoolParameterSet)
            {
                if (!string.IsNullOrWhiteSpace(Edition) || MyInvocation.BoundParameters.ContainsKey("Dtu"))
                {
                    string edition = string.IsNullOrWhiteSpace(Edition) ? poolCurrentSku.Tier : Edition;

                    newModel.SkuName  = AzureSqlElasticPoolAdapter.GetPoolSkuName(edition);
                    newModel.Edition  = edition;
                    newModel.Capacity = MyInvocation.BoundParameters.ContainsKey("Dtu") ? (int?)Dtu : null;
                }

                if (MyInvocation.BoundParameters.ContainsKey("DatabaseDtuMin") || MyInvocation.BoundParameters.ContainsKey("DatabaseDtuMax"))
                {
                    newModel.DatabaseCapacityMin = MyInvocation.BoundParameters.ContainsKey("DatabaseDtuMin") ? (double?)DatabaseDtuMin : null;
                    newModel.DatabaseCapacityMax = MyInvocation.BoundParameters.ContainsKey("DatabaseDtuMax") ? (double?)DatabaseDtuMax : null;
                }
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(Edition) || MyInvocation.BoundParameters.ContainsKey("VCore") || !string.IsNullOrWhiteSpace(ComputeGeneration))
                {
                    string skuTier = string.IsNullOrWhiteSpace(Edition) ? poolCurrentSku.Tier : Edition;

                    newModel.SkuName  = AzureSqlElasticPoolAdapter.GetPoolSkuName(skuTier);
                    newModel.Edition  = skuTier;
                    newModel.Capacity = MyInvocation.BoundParameters.ContainsKey("VCore") ? VCore : poolCurrentSku.Capacity;
                    newModel.Family   = string.IsNullOrWhiteSpace(ComputeGeneration) ? poolCurrentSku.Family : ComputeGeneration;
                }

                if (MyInvocation.BoundParameters.ContainsKey("DatabaseVCoreMin") || MyInvocation.BoundParameters.ContainsKey("DatabaseVCoreMax"))
                {
                    newModel.DatabaseCapacityMin = MyInvocation.BoundParameters.ContainsKey("DatabaseVCoreMin") ? (double?)DatabaseVCoreMin : null;
                    newModel.DatabaseCapacityMax = MyInvocation.BoundParameters.ContainsKey("DatabaseVCoreMax") ? (double?)DatabaseVCoreMax : null;
                }
            }

            newEntity.Add(newModel);
            return(newEntity);
        }
        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)
            {
                createParameters.AzureFilesIdentityBasedAuthentication = new AzureFilesIdentityBasedAuthentication();
                if (enableAzureActiveDirectoryDomainServicesForFile.Value)
                {
                    createParameters.AzureFilesIdentityBasedAuthentication.DirectoryServiceOptions = DirectoryServiceOptions.AADDS;
                }
                else
                {
                    createParameters.AzureFilesIdentityBasedAuthentication.DirectoryServiceOptions = DirectoryServiceOptions.None;
                }
            }
            if (this.EnableLargeFileShare.IsPresent)
            {
                createParameters.LargeFileSharesState = LargeFileSharesState.Enabled;
            }
            if (this.EncryptionKeyTypeForQueue != null || this.EncryptionKeyTypeForTable != null)
            {
                createParameters.Encryption           = new Encryption();
                createParameters.Encryption.KeySource = KeySource.MicrosoftStorage;
                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);
                }
            }

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

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

            this.WriteStorageAccount(storageAccount);
        }
예제 #3
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;
            }

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

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

            this.WriteStorageAccount(storageAccount);
        }
예제 #4
0
        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);
            }

            var existingWorkspace = this.SynapseAnalyticsClient.GetWorkspaceOrDefault(this.ResourceGroupName, this.WorkspaceName);

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

            if (this.Version == 3)
            {
                var existingSqlPool = this.SynapseAnalyticsClient.GetSqlPoolV3OrDefault(this.ResourceGroupName, this.WorkspaceName, this.Name);
                if (existingSqlPool != null)
                {
                    throw new AzPSInvalidOperationException(string.Format(Resources.SynapseSqlPoolExists, this.Name, this.ResourceGroupName, this.WorkspaceName));
                }

                var createParams = new SqlPoolV3
                {
                    Location = existingWorkspace.Location,
                    Tags     = TagsConversionHelper.CreateTagDictionary(this.Tag, validate: true)
                };

                switch (this.ParameterSetName)
                {
                case CreateByNameParameterSet:
                case CreateByParentObjectParameterSet:
                    createParams.Sku = new Sku
                    {
                        Name = this.PerformanceLevel
                    };
                    break;

                default: throw new AzPSInvalidOperationException(string.Format(Resources.InvalidParameterSet, this.ParameterSetName));
                }

                if (this.ShouldProcess(this.Name, string.Format(Resources.CreatingSynapseSqlPool, this.ResourceGroupName, this.WorkspaceName, this.Name)))
                {
                    var result = new PSSynapseSqlPoolV3(this.SynapseAnalyticsClient.CreateSqlPoolV3(this.ResourceGroupName, this.WorkspaceName, this.Name, createParams));
                    WriteObject(result);
                }
            }
            else
            {
                var existingSqlPool = this.SynapseAnalyticsClient.GetSqlPoolOrDefault(this.ResourceGroupName, this.WorkspaceName, this.Name);
                if (existingSqlPool != null)
                {
                    throw new AzPSInvalidOperationException(string.Format(Resources.SynapseSqlPoolExists, this.Name, this.ResourceGroupName, this.WorkspaceName));
                }

                var createParams = new SqlPool
                {
                    Location = existingWorkspace.Location,
                    Tags     = TagsConversionHelper.CreateTagDictionary(this.Tag, validate: true)
                };

                createParams.CreateMode = SynapseSqlPoolCreateMode.Default;
                createParams.Collation  = this.IsParameterBound(c => c.Collation) ? this.Collation : SynapseConstants.DefaultCollation;
                createParams.Sku        = new Sku
                {
                    Name = this.PerformanceLevel
                };

                if (this.ShouldProcess(this.Name, string.Format(Resources.CreatingSynapseSqlPool, this.ResourceGroupName, this.WorkspaceName, this.Name)))
                {
                    var result = new PSSynapseSqlPool(this.ResourceGroupName, this.WorkspaceName, this.SynapseAnalyticsClient.CreateSqlPool(this.ResourceGroupName, this.WorkspaceName, this.Name, createParams));
                    WriteObject(result);
                }
            }
        }
예제 #5
0
        private PSAzureFirewall CreateAzureFirewall()
        {
            var firewall = new PSAzureFirewall();
            var sku      = new PSAzureFirewallSku();

            sku.Name = !string.IsNullOrEmpty(this.SkuName) ? this.SkuName : MNM.AzureFirewallSkuName.AZFWVNet;
            sku.Tier = !string.IsNullOrEmpty(this.SkuTier) ? this.SkuTier : MNM.AzureFirewallSkuTier.Standard;

            if (this.SkuName == 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));
                    }
                }

                if (this.HubIPAddress != null && this.HubIPAddress.PublicIPs != null && this.HubIPAddress.PublicIPs.Addresses != null)
                {
                    throw new ArgumentException("The list of public Ip addresses cannot be provided during the firewall creation");
                }

                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,
                    HubIPAddresses = this.HubIPAddress
                };
            }
            else
            {
                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,
                    DNSEnableProxy             = (this.EnableDnsProxy.IsPresent ? "true" : null),
                    DNSServer                  = this.DnsServer,
                    AllowActiveFTP             = (this.AllowActiveFTP.IsPresent ? "true" : null),
                    Sku = sku
                };

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

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

                firewall.ValidateDNSProxyRequirements();
            }

            // 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));
        }
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();

            if (ShouldProcess(this.Name, "Set Storage Account"))
            {
                if (this.force || this.AccessTier == null || ShouldContinue("Changing the access tier may result in additional charges. See (http://go.microsoft.com/fwlink/?LinkId=786482) to learn more.", ""))
                {
                    StorageAccountUpdateParameters updateParameters = new StorageAccountUpdateParameters();
                    if (this.SkuName != null)
                    {
                        updateParameters.Sku = new Sku(ParseSkuName(this.SkuName));
                    }

                    if (this.Tag != null)
                    {
                        Dictionary <string, string> tagDictionary = TagsConversionHelper.CreateTagDictionary(Tag, validate: true);
                        updateParameters.Tags = tagDictionary ?? new Dictionary <string, string>();
                    }

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

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

                    if (AssignIdentity.IsPresent)
                    {
                        updateParameters.Identity = new Identity();
                    }

                    if (StorageEncryption || (ParameterSetName == KeyvaultEncryptionParameterSet))
                    {
                        if (ParameterSetName == KeyvaultEncryptionParameterSet)
                        {
                            keyvaultEncryption = true;
                        }
                        updateParameters.Encryption = ParseEncryption(StorageEncryption, keyvaultEncryption, KeyName, KeyVersion, KeyVaultUri);
                    }
                    if (NetworkRuleSet != null)
                    {
                        updateParameters.NetworkRuleSet = PSNetworkRuleSet.ParseStorageNetworkRule(NetworkRuleSet);
                    }

                    if (UpgradeToStorageV2.IsPresent)
                    {
                        updateParameters.Kind = Kind.StorageV2;
                    }

                    var updatedAccountResponse = this.StorageClient.StorageAccounts.Update(
                        this.ResourceGroupName,
                        this.Name,
                        updateParameters);

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

                    WriteStorageAccount(storageAccount);
                }
            }
        }
        private PSNetworkInterface CreateNetworkInterface()
        {
            var networkInterface = new PSNetworkInterface();

            networkInterface.Name = this.Name;

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

            networkInterface.EnableIPForwarding          = this.EnableIPForwarding.IsPresent;
            networkInterface.EnableAcceleratedNetworking = this.EnableAcceleratedNetworking.IsPresent;

            // Get the subnetId and publicIpAddressId from the object if specified
            if (ParameterSetName.Contains(Microsoft.Azure.Commands.Network.Properties.Resources.SetByIpConfiguration))
            {
                networkInterface.IpConfigurations = this.IpConfiguration?.ToList();

                if (string.Equals(ParameterSetName, Microsoft.Azure.Commands.Network.Properties.Resources.SetByIpConfigurationResourceId))
                {
                    if (this.NetworkSecurityGroup != null)
                    {
                        this.NetworkSecurityGroupId = this.NetworkSecurityGroup.Id;
                    }
                }
            }
            else
            {
                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)
                    {
                        var poolIds = new List <string>();
                        foreach (var bepool in this.LoadBalancerBackendAddressPool)
                        {
                            poolIds.Add(bepool.Id);
                        }
                        this.LoadBalancerBackendAddressPoolId = poolIds.ToArray();
                    }

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

                    if (this.ApplicationGatewayBackendAddressPool != null)
                    {
                        var appGwPoolIds = new List <string>();
                        foreach (var appgwBepool in this.ApplicationGatewayBackendAddressPool)
                        {
                            appGwPoolIds.Add(appgwBepool.Id);
                        }
                        ApplicationGatewayBackendAddressPoolId = appGwPoolIds.ToArray();
                    }

                    if (this.ApplicationSecurityGroup != null)
                    {
                        var groupIds = new List <string>();
                        foreach (var asg in this.ApplicationSecurityGroup)
                        {
                            groupIds.Add(asg.Id);
                        }
                        ApplicationSecurityGroupId = groupIds.ToArray();
                    }
                }

                var nicIpConfiguration = new PSNetworkInterfaceIPConfiguration();
                nicIpConfiguration.Name = string.IsNullOrEmpty(this.IpConfigurationName) ? "ipconfig1" : this.IpConfigurationName;
                nicIpConfiguration.PrivateIpAllocationMethod = MNM.IPAllocationMethod.Dynamic;
                nicIpConfiguration.Primary = true;
                // Uncomment when ipv6 is supported as standalone ipconfig in a nic
                // nicIpConfiguration.PrivateIpAddressVersion = this.PrivateIpAddressVersion;

                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 (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.ApplicationGatewayBackendAddressPoolId != null)
                {
                    nicIpConfiguration.ApplicationGatewayBackendAddressPools = new List <PSApplicationGatewayBackendAddressPool>();
                    foreach (var appgwBepoolId in this.ApplicationGatewayBackendAddressPoolId)
                    {
                        nicIpConfiguration.ApplicationGatewayBackendAddressPools.Add(new PSApplicationGatewayBackendAddressPool {
                            Id = appgwBepoolId
                        });
                    }
                }

                if (this.ApplicationSecurityGroupId != null)
                {
                    nicIpConfiguration.ApplicationSecurityGroups = new List <PSApplicationSecurityGroup>();
                    foreach (var id in this.ApplicationSecurityGroupId)
                    {
                        nicIpConfiguration.ApplicationSecurityGroups.Add(new PSApplicationSecurityGroup {
                            Id = id
                        });
                    }
                }

                networkInterface.IpConfigurations = new List <PSNetworkInterfaceIPConfiguration>();
                networkInterface.IpConfigurations.Add(nicIpConfiguration);
            }

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

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

            List <string> resourceIdsRequiringAuthToken       = new List <string>();
            Dictionary <string, List <string> > auxAuthHeader = null;

            // Get aux token for each gateway lb references
            foreach (var ipConfiguration in networkInterface.IpConfigurations)
            {
                if (ipConfiguration.GatewayLoadBalancer != null)
                {
                    //Get the aux header for the remote vnet
                    resourceIdsRequiringAuthToken.Add(ipConfiguration.GatewayLoadBalancer.Id);
                }
            }

            if (resourceIdsRequiringAuthToken.Count > 0)
            {
                var auxHeaderDictionary = GetAuxilaryAuthHeaderFromResourceIds(resourceIdsRequiringAuthToken);
                if (auxHeaderDictionary != null && auxHeaderDictionary.Count > 0)
                {
                    auxAuthHeader = new Dictionary <string, List <string> >(auxHeaderDictionary);
                }
            }

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

            this.NullifyApplicationSecurityGroupIfAbsent(networkInterfaceModel);

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

            this.NetworkInterfaceClient.CreateOrUpdateWithHttpMessagesAsync(this.ResourceGroupName, this.Name, networkInterfaceModel, auxAuthHeader).GetAwaiter().GetResult();

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

            return(getNetworkInterface);
        }
예제 #8
0
        public override void Execute()
        {
            base.Execute();

            if (ExpressRouteCrossConnection != null)
            {
                // If ExpressRouteCrossConnection object is provided
                ConfirmAction(
                    Force.IsPresent,
                    string.Format(Properties.Resources.OverwritingResource, ExpressRouteCrossConnection.Name),
                    Properties.Resources.CreatingResourceMessage,
                    ExpressRouteCrossConnection.Name,
                    () =>
                {
                    var crossConnection = GetExistingExpressRouteCrossConnection(ExpressRouteCrossConnection.ResourceGroupName, ExpressRouteCrossConnection.Name);
                    if (crossConnection == null)
                    {
                        throw new ArgumentException(Microsoft.Azure.Commands.Network.Properties.Resources.ResourceNotFound);
                    }

                    // Map to the sdk operation
                    var crossConnectionModel  = NetworkResourceManagerProfile.Mapper.Map <MNM.ExpressRouteCrossConnection>(ExpressRouteCrossConnection);
                    crossConnectionModel.Tags = TagsConversionHelper.CreateTagDictionary(ExpressRouteCrossConnection.Tag, validate: true);

                    // Execute the Update ExpressRouteCrossConnection call
                    ExpressRouteCrossConnectionClient.CreateOrUpdate(ExpressRouteCrossConnection.ResourceGroupName, ExpressRouteCrossConnection.Name, crossConnectionModel);

                    var getExpressRouteCircuit = GetExpressRouteCrossConnection(ExpressRouteCrossConnection.ResourceGroupName, ExpressRouteCrossConnection.Name);
                    WriteObject(getExpressRouteCircuit);
                });
            }
            else
            {
                // If individual parameters are provided
                ConfirmAction(
                    Force.IsPresent,
                    string.Format(Properties.Resources.OverwritingResource, Name),
                    Properties.Resources.CreatingResourceMessage,
                    Name,
                    () =>
                {
                    var crossConnection = GetExistingExpressRouteCrossConnection(ResourceGroupName, Name);
                    if (crossConnection == null)
                    {
                        throw new ArgumentException(Microsoft.Azure.Commands.Network.Properties.Resources.ResourceNotFound);
                    }

                    if (!string.IsNullOrWhiteSpace(ServiceProviderNotes))
                    {
                        crossConnection.ServiceProviderNotes = ServiceProviderNotes;
                    }

                    if (!string.IsNullOrWhiteSpace(ServiceProviderProvisioningState))
                    {
                        crossConnection.ServiceProviderProvisioningState = ServiceProviderProvisioningState;
                    }

                    if (Peerings != null && Peerings.Length > 0)
                    {
                        crossConnection.Peerings = Peerings?.ToList();
                    }

                    // Map to the sdk operation
                    var crossConnectionModel  = NetworkResourceManagerProfile.Mapper.Map <MNM.ExpressRouteCrossConnection>(crossConnection);
                    crossConnectionModel.Tags = TagsConversionHelper.CreateTagDictionary(crossConnection.Tag, validate: true);

                    // Execute the Update ExpressRouteCrossConnection call
                    ExpressRouteCrossConnectionClient.CreateOrUpdate(ResourceGroupName, Name, crossConnectionModel);

                    var getExpressRouteCrossConnection = GetExpressRouteCrossConnection(ResourceGroupName, Name);
                    WriteObject(getExpressRouteCrossConnection);
                });
            }
        }
        private ManagedCluster BuildNewCluster()
        {
            BeforeBuildNewCluster();

            var pubKey =
                new List <ContainerServiceSshPublicKey> {
                new ContainerServiceSshPublicKey(SshKeyValue)
            };

            var linuxProfile =
                new ContainerServiceLinuxProfile(LinuxProfileAdminUserName,
                                                 new ContainerServiceSshConfiguration(pubKey));

            acsServicePrincipal = EnsureServicePrincipal(ServicePrincipalIdAndSecret?.UserName, ServicePrincipalIdAndSecret?.Password?.ConvertToString());

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

            var aadProfile = GetAadProfile();

            var defaultAgentPoolProfile = GetAgentPoolProfile();

            var windowsProfile = GetWindowsProfile();

            var networkProfile = GetNetworkProfile();

            var apiServerAccessProfile = CreateOrUpdateApiServerAccessProfile(null);

            var addonProfiles = CreateAddonsProfiles();

            WriteVerbose(string.Format(Resources.DeployingYourManagedKubeCluster, AcsSpFilePath));

            var managedCluster = new ManagedCluster(
                Location,
                name: Name,
                tags: TagsConversionHelper.CreateTagDictionary(Tag, true),
                dnsPrefix: DnsNamePrefix,
                kubernetesVersion: KubernetesVersion,
                agentPoolProfiles: new List <ManagedClusterAgentPoolProfile> {
                defaultAgentPoolProfile
            },
                linuxProfile: linuxProfile,
                windowsProfile: windowsProfile,
                servicePrincipalProfile: spProfile,
                aadProfile: aadProfile,
                addonProfiles: addonProfiles,
                networkProfile: networkProfile,
                apiServerAccessProfile: apiServerAccessProfile);

            if (EnableRbac.IsPresent)
            {
                managedCluster.EnableRBAC = EnableRbac;
            }
            if (this.IsParameterBound(c => c.FqdnSubdomain))
            {
                managedCluster.FqdnSubdomain = FqdnSubdomain;
            }
            //if(EnablePodSecurityPolicy.IsPresent)
            //{
            //    managedCluster.EnablePodSecurityPolicy = EnablePodSecurityPolicy;
            //}

            return(managedCluster);
        }
예제 #10
0
        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 AzPSResourceNotFoundCloudException(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;
            existingSparkPool.SparkConfigProperties = this.IsParameterBound(c => c.SparkConfigFilePath) ? CreateSparkConfigProperties() : existingSparkPool.SparkConfigProperties;

            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 ?? int.Parse(SynapseConstants.DefaultAutoPauseDelayInMinute)
                };
            }

            if ((!this.IsParameterBound(c => c.PackageAction) && this.IsParameterBound(c => c.Package)) ||
                ((this.IsParameterBound(c => c.PackageAction) && !this.IsParameterBound(c => c.Package))))
            {
                throw new AzPSInvalidOperationException(Resources.FailedToValidatePackageParameter);
            }

            if (this.IsParameterBound(c => c.PackageAction) && this.IsParameterBound(c => c.Package))
            {
                if (this.PackageAction == SynapseConstants.PackageActionType.Add)
                {
                    if (existingSparkPool.CustomLibraries == null)
                    {
                        existingSparkPool.CustomLibraries = new List <LibraryInfo>();
                    }

                    existingSparkPool.CustomLibraries = existingSparkPool.CustomLibraries.Union(this.Package.Select(psPackage => new LibraryInfo
                    {
                        Name              = psPackage?.Name,
                        Type              = psPackage?.PackageType,
                        Path              = psPackage?.Path,
                        ContainerName     = psPackage?.ContainerName,
                        UploadedTimestamp = DateTime.Parse(psPackage?.UploadedTimestamp).ToUniversalTime()
                    }), new LibraryComparer()).ToList();
                }
                else if (this.PackageAction == SynapseConstants.PackageActionType.Remove)
                {
                    existingSparkPool.CustomLibraries = existingSparkPool.CustomLibraries.Where(lib => !this.Package.Any(p => lib.Path.Equals(p.Path, System.StringComparison.OrdinalIgnoreCase))).ToList();
                }
            }

            bool?isForceApplySetting = false;

            if (ForceApplySetting.IsPresent)
            {
                isForceApplySetting = true;
            }

            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, isForceApplySetting));
                WriteObject(result);
            }
        }
        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(ParseSkuName(this.SkuName)),
                Tags     = TagsConversionHelper.CreateTagDictionary(Tag, validate: true),
            };

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

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

            if (this.EnableEncryptionService != null)
            {
                createParameters.Encryption           = ParseEncryption(EnableEncryptionService);
                createParameters.Encryption.KeySource = "Microsoft.Storage";
            }

            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.NetworkAcls = PSNetworkRuleSet.ParseStorageNetworkRule(NetworkRuleSet);
            }

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

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

            this.WriteStorageAccount(storageAccount);
        }
예제 #12
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.GatewayIPConfigurations != null)
            {
                applicationGateway.GatewayIPConfigurations = new List <PSApplicationGatewayIPConfiguration>();
                applicationGateway.GatewayIPConfigurations = this.GatewayIPConfigurations;
            }

            if (this.SslCertificates != null)
            {
                applicationGateway.SslCertificates = new List <PSApplicationGatewaySslCertificate>();
                applicationGateway.SslCertificates = this.SslCertificates;
            }

            if (this.FrontendIPConfigurations != null)
            {
                applicationGateway.FrontendIPConfigurations = new List <PSApplicationGatewayFrontendIPConfiguration>();
                applicationGateway.FrontendIPConfigurations = this.FrontendIPConfigurations;
            }

            if (this.FrontendPorts != null)
            {
                applicationGateway.FrontendPorts = new List <PSApplicationGatewayFrontendPort>();
                applicationGateway.FrontendPorts = this.FrontendPorts;
            }

            if (this.Probes != null)
            {
                applicationGateway.Probes = new List <PSApplicationGatewayProbe>();
                applicationGateway.Probes = this.Probes;
            }

            if (this.BackendAddressPools != null)
            {
                applicationGateway.BackendAddressPools = new List <PSApplicationGatewayBackendAddressPool>();
                applicationGateway.BackendAddressPools = this.BackendAddressPools;
            }

            if (this.BackendHttpSettingsCollection != null)
            {
                applicationGateway.BackendHttpSettingsCollection = new List <PSApplicationGatewayBackendHttpSettings>();
                applicationGateway.BackendHttpSettingsCollection = this.BackendHttpSettingsCollection;
            }

            if (this.HttpListeners != null)
            {
                applicationGateway.HttpListeners = new List <PSApplicationGatewayHttpListener>();
                applicationGateway.HttpListeners = this.HttpListeners;
            }

            if (this.UrlPathMaps != null)
            {
                applicationGateway.UrlPathMaps = new List <PSApplicationGatewayUrlPathMap>();
                applicationGateway.UrlPathMaps = this.UrlPathMaps;
            }

            if (this.RequestRoutingRules != null)
            {
                applicationGateway.RequestRoutingRules = new List <PSApplicationGatewayRequestRoutingRule>();
                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);
        }
        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;
            }

            var toReturn = _client.Account.Create(resourceGroupName, accountName, parameters);

            return(toReturn);
        }
        public override void Execute()
        {
            base.Execute();

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

            var existingResourcePsModel = GetCustomIpPrefix(this.ResourceGroupName, this.Name);

            if (existingResourcePsModel == null)
            {
                throw new ArgumentException(Microsoft.Azure.Commands.Network.Properties.Resources.ResourceNotFound);
            }

            if (Commission && Decomission)
            {
                throw new ArgumentException(Microsoft.Azure.Commands.Network.Properties.Resources.CommissioningStateConflict);
            }

            PSCustomIpPrefix customIpPrefixToUpdate = this.GetCustomIpPrefix(this.ResourceGroupName, this.Name);

            if (customIpPrefixToUpdate == null)
            {
                throw new PSArgumentException(Properties.Resources.ResourceNotFound, this.Name);
            }

            if (Commission || Decomission)
            {
                customIpPrefixToUpdate.CommissionedState = Commission ? "Commissioning" : "Decomissioning";
            }

            var sdkModel = NetworkResourceManagerProfile.Mapper.Map <MNM.CustomIpPrefix>(customIpPrefixToUpdate);

            if (this.IsParameterBound(c => c.InputObject))
            {
                sdkModel.Tags = TagsConversionHelper.CreateTagDictionary(this.IsParameterBound(c => c.Tag) ? this.Tag : InputObject.Tag, validate: true);
            }
            else
            {
                sdkModel.Tags = TagsConversionHelper.CreateTagDictionary(this.Tag, validate: true);
            }

            if (this.ShouldProcess($"Name: {this.Name} ResourceGroup: {this.ResourceGroupName}", "Update existing CustomIpPrefix"))
            {
                // Execute the PUT MasterCustomIpPrefix Policy call
                this.CustomIpPrefixClient.CreateOrUpdate(this.ResourceGroupName, this.Name, sdkModel);

                var customIpPrefix = this.GetCustomIpPrefix(this.ResourceGroupName, this.Name);

                WriteObject(customIpPrefix);
            }
        }
        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(() =>
                {
                    if (Exists())
                    {
                        if (cluster == null)
                        {
                            cluster = Client.ManagedClusters.Get(ResourceGroupName, Name);
                        }

                        if (MyInvocation.BoundParameters.ContainsKey("Location"))
                        {
                            throw new CmdletInvocationException(Resources.LocationCannotBeUpdateForExistingCluster);
                        }

                        if (MyInvocation.BoundParameters.ContainsKey("DnsNamePrefix"))
                        {
                            WriteVerbose(Resources.UpdatingDnsNamePrefix);
                            cluster.DnsPrefix = DnsNamePrefix;
                        }

                        if (MyInvocation.BoundParameters.ContainsKey("SshKeyValue"))
                        {
                            WriteVerbose(Resources.UpdatingSshKeyValue);
                            cluster.LinuxProfile.Ssh.PublicKeys = new List <ContainerServiceSshPublicKey>
                            {
                                new ContainerServiceSshPublicKey(GetSshKey(SshKeyValue))
                            };
                        }

                        if (ParameterSetName == SpParamSet)
                        {
                            WriteVerbose(Resources.UpdatingServicePrincipal);
                            var acsServicePrincipal = EnsureServicePrincipal(ClientIdAndSecret.UserName, ClientIdAndSecret.Password.ToString());

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

                        if (MyInvocation.BoundParameters.ContainsKey("AdminUserName"))
                        {
                            WriteVerbose(Resources.UpdatingAdminUsername);
                            cluster.LinuxProfile.AdminUsername = AdminUserName;
                        }

                        ContainerServiceAgentPoolProfile defaultAgentPoolProfile;
                        if (cluster.AgentPoolProfiles.Any(x => x.Name == "default"))
                        {
                            defaultAgentPoolProfile = cluster.AgentPoolProfiles.First(x => x.Name == "default");
                        }
                        else
                        {
                            defaultAgentPoolProfile = new ContainerServiceAgentPoolProfile(
                                "default",
                                NodeVmSize,
                                NodeCount,
                                NodeOsDiskSize,
                                DnsNamePrefix ?? DefaultDnsPrefix());
                            cluster.AgentPoolProfiles.Add(defaultAgentPoolProfile);
                        }

                        if (MyInvocation.BoundParameters.ContainsKey("NodeVmSize"))
                        {
                            WriteVerbose(Resources.UpdatingNodeVmSize);
                            defaultAgentPoolProfile.VmSize = NodeVmSize;
                        }

                        if (MyInvocation.BoundParameters.ContainsKey("NodeCount"))
                        {
                            WriteVerbose(Resources.UpdatingNodeCount);
                            defaultAgentPoolProfile.Count = NodeCount;
                        }

                        if (MyInvocation.BoundParameters.ContainsKey("NodeOsDiskSize"))
                        {
                            WriteVerbose(Resources.UpdatingNodeOsDiskSize);
                            defaultAgentPoolProfile.OsDiskSizeGB = NodeOsDiskSize;
                        }

                        if (MyInvocation.BoundParameters.ContainsKey("KubernetesVersion"))
                        {
                            WriteVerbose(Resources.UpdatingKubernetesVersion);
                            cluster.KubernetesVersion = KubernetesVersion;
                        }

                        if (MyInvocation.BoundParameters.ContainsKey("Tag"))
                        {
                            WriteVerbose(Resources.UpdatingTags);
                            cluster.Tags = TagsConversionHelper.CreateTagDictionary(Tag, true);
                        }

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

                    var kubeCluster = Client.ManagedClusters.CreateOrUpdate(ResourceGroupName, Name, cluster);
                    WriteObject(PSMapper.Instance.Map <PSKubernetesCluster>(kubeCluster));
                });
            }
        }
        public override void ExecuteCmdlet()
        {
            if (InputObject != null)
            {
                VaultName = InputObject.VaultName;
                Name      = InputObject.Name;
            }

            if (ShouldProcess(Name, Properties.Resources.SetSecret))
            {
                var secret = DataServiceClient.SetSecret(
                    VaultName,
                    Name,
                    SecretValue,
                    new PSKeyVaultSecretAttributes(!Disable.IsPresent, Expires, NotBefore, ContentType,
                                                   TagsConversionHelper.CreateTagHashtable(TagsConversionHelper.CreateTagDictionary(this.Tag, true))));
                WriteObject(secret);
            }
        }
        public override void Execute()
        {
            base.Execute();

            // Sku
            PSLoadBalancerSku vSku = null;

            if (this.Sku != null)
            {
                if (vSku == null)
                {
                    vSku = new PSLoadBalancerSku();
                }
                vSku.Name = this.Sku;
            }

            // Tier
            if (this.Tier != null)
            {
                if (vSku == null)
                {
                    vSku = new PSLoadBalancerSku();
                }
                vSku.Tier = this.Tier;
            }

            var vLoadBalancer = new PSLoadBalancer
            {
                Location = this.Location,
                FrontendIpConfigurations = this.FrontendIpConfiguration?.ToList(),
                BackendAddressPools      = this.BackendAddressPool?.ToList(),
                LoadBalancingRules       = this.LoadBalancingRule?.ToList(),
                Probes           = this.Probe?.ToList(),
                InboundNatRules  = this.InboundNatRule?.ToList(),
                InboundNatPools  = this.InboundNatPool?.ToList(),
                OutboundRules    = this.OutboundRule?.ToList(),
                Sku              = vSku,
                ExtendedLocation = string.IsNullOrEmpty(this.EdgeZone) ? null : new PSExtendedLocation(this.EdgeZone)
            };

            NormalizeChildIds(vLoadBalancer);

            var vLoadBalancerModel = NetworkResourceManagerProfile.Mapper.Map <MNM.LoadBalancer>(vLoadBalancer);

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

            try
            {
                this.NetworkClient.NetworkManagementClient.LoadBalancers.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;
                }
            }

            List <string> resourceIdsRequiringAuthToken       = new List <string>();
            Dictionary <string, List <string> > auxAuthHeader = null;

            // Get aux token for each gateway lb references
            foreach (FrontendIPConfiguration frontend in vLoadBalancerModel.FrontendIPConfigurations)
            {
                if (frontend.GatewayLoadBalancer != null)
                {
                    //Get the aux header for the remote vnet
                    resourceIdsRequiringAuthToken.Add(frontend.GatewayLoadBalancer.Id);
                }
            }

            if (resourceIdsRequiringAuthToken.Count > 0)
            {
                var auxHeaderDictionary = GetAuxilaryAuthHeaderFromResourceIds(resourceIdsRequiringAuthToken);
                if (auxHeaderDictionary != null && auxHeaderDictionary.Count > 0)
                {
                    auxAuthHeader = new Dictionary <string, List <string> >(auxHeaderDictionary);
                }
            }


            ConfirmAction(
                Force.IsPresent,
                string.Format(Properties.Resources.OverwritingResource, Name),
                Properties.Resources.CreatingResourceMessage,
                Name,
                () =>
            {
                this.NetworkClient.NetworkManagementClient.LoadBalancers.CreateOrUpdateWithHttpMessagesAsync(this.ResourceGroupName, this.Name, vLoadBalancerModel, auxAuthHeader).GetAwaiter().GetResult();
                var getLoadBalancer = this.NetworkClient.NetworkManagementClient.LoadBalancers.Get(this.ResourceGroupName, this.Name);
                var psLoadBalancer  = NetworkResourceManagerProfile.Mapper.Map <PSLoadBalancer>(getLoadBalancer);
                psLoadBalancer.ResourceGroupName = this.ResourceGroupName;
                psLoadBalancer.Tag = TagsConversionHelper.CreateTagHashtable(getLoadBalancer.Tags);
                WriteObject(psLoadBalancer, true);
            },
                () => present);
        }