예제 #1
0
        public async Task <NetworkInterfaceInner> CreateNetworkInterfaceAsync(
            IResourceGroup resourceGroup,
            NetworkSecurityGroupInner networkSecurityGroup,
            SubnetInner aksSubnet,
            string networkInterfaceName,
            string networkInterfacePrivateIPAddress,
            IDictionary <string, string> tags   = null,
            CancellationToken cancellationToken = default
            )
        {
            tags = tags ?? new Dictionary <string, string>();

            // Define Network Interface
            var networkInterfaceDefinition = new NetworkInterfaceInner {
                Location = resourceGroup.RegionName,
                Tags     = tags,

                IpConfigurations = new List <NetworkInterfaceIPConfigurationInner> {
                    new NetworkInterfaceIPConfigurationInner {
                        Name                      = "ipconfig1",
                        PrivateIPAddress          = networkInterfacePrivateIPAddress,
                        PrivateIPAllocationMethod = IPAllocationMethod.Dynamic,
                        //PublicIPAddress = new SubResource {
                        //    Id = publicIPAddress.Id
                        //},
                        Subnet = new SubResource {
                            Id = aksSubnet.Id
                        }
                    }
                },
                NetworkSecurityGroup = new SubResource {
                    Id = networkSecurityGroup.Id
                },
                EnableAcceleratedNetworking = true,
                EnableIPForwarding          = true
            };

            networkInterfaceDefinition.Validate();

            var networkInterface = await _networkManagementClient
                                   .NetworkInterfaces
                                   .CreateOrUpdateAsync(
                resourceGroup.Name,
                networkInterfaceName,
                networkInterfaceDefinition,
                cancellationToken
                );

            return(networkInterface);
        }
예제 #2
0
        /// <summary>
        /// Gets the subnet to associate with the IP configuration.
        /// <p>
        /// This method will never return null as subnet is required for a IP configuration, in case of
        /// update mode if user didn't choose to change the subnet then existing subnet will be returned.
        /// Updating the nic subnet has a restriction, the new subnet must reside in the same virtual network
        /// as the current one.
        /// </summary>
        /// <returns>the subnet resource</returns>

        ///GENMHASH:D14BFB60D59198612CF4649F7C5412EA:BCFDC718771D33AF794CADC76C0CCD5F
        private SubnetInner SubnetToAssociate()
        {
            SubnetInner subnetInner = new SubnetInner();

            if (isInCreateMode)
            {
                if (creatableVirtualNetworkKey != null)
                {
                    INetwork network = (INetwork)Parent.CreatedDependencyResource(creatableVirtualNetworkKey);
                    subnetInner.Id = network.Inner.Subnets[0].Id;
                    return(subnetInner);
                }

                foreach (var subnet in existingVirtualNetworkToAssociate.Inner.Subnets)
                {
                    if (subnet.Name.Equals(subnetToAssociate, StringComparison.OrdinalIgnoreCase))
                    {
                        subnetInner.Id = subnet.Id;
                        return(subnetInner);
                    }
                }

                throw new Exception("A subnet with name '" + subnetToAssociate + "' not found under the network '" + this.existingVirtualNetworkToAssociate.Name + "'");
            }
            else
            {
                if (subnetToAssociate != null)
                {
                    int idx = Inner.Subnet.Id.LastIndexOf('/');
                    subnetInner.Id = Inner.Subnet.Id.Substring(0, idx + 1) + subnetToAssociate;
                }
                else
                {
                    subnetInner.Id = Inner.Subnet.Id;
                }
                return(subnetInner);
            }
        }
예제 #3
0
        ///GENMHASH:0A2FDD020AE5A41E49EC1B3AEB02B394:3B60772E45391CEB653A6108BC6868A5
        internal SubnetImpl DefineSubnet(string name)
        {
            SubnetInner inner = new SubnetInner(name: name);

            return(new SubnetImpl(inner, this));
        }
예제 #4
0
        protected async Task <VirtualNetworkInner> CreateOrRetrieveNetworkAsync(string resourceGroupName, string vnetName, string subnetName)
        {
            VirtualNetworkInner vnet = null;

            // attempt to retrieve an existing vnet
            try
            {
                Console.Write("Checking the existence of vnet '{0}' in resource group '{1}'...", vnetName, resourceGroupName);
                var vNetResponse = await NetworkManagementClient.VirtualNetworks.GetWithHttpMessagesAsync(resourceGroupName, vnetName).ConfigureAwait(false);

                Console.WriteLine("done");

                vnet = vNetResponse.Body;
            }
            catch (Exception e)
            {
                VerifyExpectedException <CloudException>(e, HttpStatusCode.NotFound, (ex) => { return(ex.Response.StatusCode); });
            }

            // create one if we must
            if (vnet == null)
            {
                try
                {
                    Console.Write("Creating vnet '{0}' in resource group '{1}'...", vnetName, resourceGroupName);
                    var vNetResponse = await NetworkManagementClient.VirtualNetworks.CreateOrUpdateWithHttpMessagesAsync(
                        resourceGroupName,
                        vnetName,
                        CreateVNetParameters(vnetName, SampleConstants.VNetAddressSpace, subnetName, SampleConstants.VNetSubnetAddressSpace))
                                       .ConfigureAwait(false);

                    Console.WriteLine("done.");

                    vnet = vNetResponse.Body;
                }
                catch (Exception e)
                {
                    Console.WriteLine("Unexpected exception encountered creating the virtual network: {0}", e.Message);
                    throw;
                }
            }

            // attempt to retrieve the specified subnet; create if not existing
            var subnetEntry = new SubnetInner()
            {
                Name             = subnetName,
                ServiceEndpoints = new List <ServiceEndpointPropertiesFormat> {
                    new ServiceEndpointPropertiesFormat("Microsoft.KeyVault")
                },
                AddressPrefix = SampleConstants.VNetSubnetAddressSpace
            };

            bool hasMatchingSubnet = false;

            if (vnet.Subnets.Count > 0)
            {
                // enumerate existing subnets and look for a match.
                // Invoking vnet.Subnets.Contains() will only return true
                // for a complete match of all the properties of the subnet,
                // some of which we can't know beforehand.
                for (var subnetIt = vnet.Subnets.GetEnumerator();
                     subnetIt.MoveNext();
                     )
                {
                    hasMatchingSubnet |= subnetIt.Current.Name.Equals(subnetEntry.Name, StringComparison.InvariantCultureIgnoreCase);
                    if (hasMatchingSubnet)
                    {
                        break;
                    }
                }
            }

            if (!hasMatchingSubnet)
            {
                try
                {
                    Console.Write("Creating subnet '{0}' in resource group '{1}'...", subnetEntry.Name, resourceGroupName);
                    var subnetResponse = await NetworkManagementClient.Subnets.CreateOrUpdateWithHttpMessagesAsync(
                        resourceGroupName,
                        vnet.Name,
                        subnetEntry.Name,
                        subnetEntry)
                                         .ConfigureAwait(false);

                    Console.WriteLine("done.");

                    // retrieve the updated vnet
                    Console.Write("Retrieving the updated vnet '{0}' in resource group '{1}'...", vnetName, resourceGroupName);
                    var vNetResponse = await NetworkManagementClient.VirtualNetworks.GetWithHttpMessagesAsync(resourceGroupName, vnetName).ConfigureAwait(false);

                    Console.WriteLine("done");

                    vnet = vNetResponse.Body;
                }
                catch (Exception e)
                {
                    Console.WriteLine("Unexpected exception encountered updating the virtual network: {0}", e.Message);
                    throw;
                }
            }

            return(vnet);
        }
 /// <summary>
 /// Creates or updates a subnet in the specified virtual network.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group.
 /// </param>
 /// <param name='virtualNetworkName'>
 /// The name of the virtual network.
 /// </param>
 /// <param name='subnetName'>
 /// The name of the subnet.
 /// </param>
 /// <param name='subnetParameters'>
 /// Parameters supplied to the create or update subnet operation.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <SubnetInner> CreateOrUpdateAsync(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, SubnetInner subnetParameters, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, subnetParameters, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
예제 #6
0
        //public async Task<bool> CheckNameAvailabilityAsync(
        //    string aksClusterName,
        //    CancellationToken cancellationToken = default
        //) {
        //    throw new NotImplementedException();
        //}

        public ManagedClusterInner GetClusterDefinition(
            IResourceGroup resourceGroup,
            Application aksApplication,
            string aksApplicationRbacSecret,
            string aksClusterName,
            X509Certificate2 sshCertificate,
            SubnetInner virtualNetworkSubnet,
            Workspace operationalInsightsWorkspace,
            IDictionary <string, string> tags = null
            )
        {
            tags ??= new Dictionary <string, string>();

            var aksDnsPrefix = aksClusterName + "-dns";
            var aksClusterX509CertificateOpenSshPublicKey = X509CertificateHelper.GetOpenSSHPublicKey(sshCertificate);

            var managedClusterDefinition = new ManagedClusterInner(
                //nodeResourceGroup: aksResourceGroupName // This is not propagated yet.
                )
            {
                Location = resourceGroup.RegionName,
                Tags     = tags,

                //ProvisioningState = null,
                KubernetesVersion = KUBERNETES_VERSION,
                DnsPrefix         = aksDnsPrefix,
                //Fqdn = null,
                AgentPoolProfiles = new List <ManagedClusterAgentPoolProfile> {
                    new ManagedClusterAgentPoolProfile {
                        Name         = "agentpool",
                        Count        = 2,
                        VmSize       = ContainerServiceVMSizeTypes.StandardDS2V2,
                        OsDiskSizeGB = 100,
                        OsType       = OSType.Linux,
                        VnetSubnetID = virtualNetworkSubnet.Id
                    }
                },
                LinuxProfile = new ContainerServiceLinuxProfile {
                    AdminUsername = "******",
                    Ssh           = new ContainerServiceSshConfiguration {
                        PublicKeys = new List <ContainerServiceSshPublicKey> {
                            new ContainerServiceSshPublicKey {
                                KeyData = aksClusterX509CertificateOpenSshPublicKey
                            }
                        }
                    }
                },
                ServicePrincipalProfile = new ManagedClusterServicePrincipalProfile {
                    ClientId = aksApplication.AppId,
                    Secret   = aksApplicationRbacSecret
                },
                AddonProfiles = new Dictionary <string, ManagedClusterAddonProfile> {
                    { "omsagent", new ManagedClusterAddonProfile {
                          Enabled = true,
                          Config  = new Dictionary <string, string> {
                              { "logAnalyticsWorkspaceResourceID", operationalInsightsWorkspace.Id }
                          }
                      } },
                    { "httpApplicationRouting", new ManagedClusterAddonProfile {
                          Enabled = false
                      } }
                },
                //NodeResourceGroup = aksResourceGroupName, // This is not propagated yet.
                EnableRBAC     = true,
                NetworkProfile = new ContainerServiceNetworkProfile {
                    NetworkPlugin = NetworkPlugin.Azure,
                    //PodCidr = "10.244.0.0/16",
                    ServiceCidr      = NETWORK_PROFILE_SERVICE_CIDR,
                    DnsServiceIP     = NETWORK_PROFILE_DNS_SERVICE_IP,
                    DockerBridgeCidr = NETWORK_PROFILE_DOCKER_BRIDGE_CIDR
                }
            };

            managedClusterDefinition.Validate();

            return(managedClusterDefinition);
        }