public static async Task Run([TimerTrigger("0 0 9 * * *")] TimerInfo myTimer, ILogger log)
        {
            log.LogInformation("Running Resource Tagger...");
            string ownerTagName = Environment.GetEnvironmentVariable("OwnerTag");

            if (String.IsNullOrEmpty(ownerTagName))
            {
                log.LogCritical("Please set the OwnerTag environment variables");
                return;
            }
            string subscriptionIds = Environment.GetEnvironmentVariable("SubscriptionIds");

            if (String.IsNullOrEmpty(subscriptionIds))
            {
                log.LogCritical("Please set the SubscriptionIds environment variables");
                return;
            }

            Azure.IAuthenticated azure;
            AzureCredentials     azureCreds;

            if (Environment.GetEnvironmentVariable("UseManagedIdendity") == "true")
            {
                log.LogInformation("Using Managed Identity");
                AzureCredentialsFactory factory = new AzureCredentialsFactory();
                MSILoginInformation     msi     = new MSILoginInformation(MSIResourceType.AppService);
                azureCreds = factory.FromMSI(msi, AzureEnvironment.AzureGlobalCloud);
            }
            else
            {
                log.LogInformation("Using Service Principal");
                string clientId     = Environment.GetEnvironmentVariable("ClientId");
                string clientSecret = Environment.GetEnvironmentVariable("ClientSecret");
                string tenantId     = Environment.GetEnvironmentVariable("TenantId");

                AzureCredentialsFactory factory = new AzureCredentialsFactory();
                azureCreds = factory.FromServicePrincipal(clientId, clientSecret, tenantId,
                                                          AzureEnvironment.AzureGlobalCloud);
            }
            azure = Azure.Configure().Authenticate(azureCreds);

            foreach (var subscriptionId in subscriptionIds.Split(",", StringSplitOptions.RemoveEmptyEntries))
            {
                log.LogInformation($"Looking for new resources without an owner tag in subscription {subscriptionId}");

                var azureSub       = azure.WithSubscription(subscriptionId);
                var insightsClient = new Microsoft.Azure.Insights.InsightsClient(azureCreds);
                insightsClient.SubscriptionId = subscriptionId;

                var resourceGroups = azureSub.ResourceGroups.List();
                foreach (var group in resourceGroups)
                {
                    log.LogTrace($"Looking at resource group {group.Name}");
                    try
                    {
                        var defaultKeyValuePair = default(KeyValuePair <String, String>);
                        var ownerTag            = defaultKeyValuePair;
                        if (group.Tags != null)
                        {
                            ownerTag = group.Tags.Where(tag => tag.Key.Equals(ownerTagName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
                        }

                        if (ownerTag.Equals(defaultKeyValuePair))
                        {
                            String startTime  = DateTime.Now.ToUniversalTime().AddHours(-25).ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
                            String endTime    = DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
                            String resourceId = group.Id;

                            string unknownOwner            = "unknown";
                            string newOwner                = unknownOwner;
                            var    resourceGroupCreateLogs = await GetCreationLogs(startTime, endTime, resourceId, OPERATION_RESOURCEGROUP_WRITE, insightsClient);

                            if (resourceGroupCreateLogs.Length == 0)
                            {
                                log.LogInformation($"Resource group {group.Name}: did not find create operation - trying again");
                                startTime = DateTime.Now.ToUniversalTime().AddDays(-90).ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
                                resourceGroupCreateLogs = await GetCreationLogs(startTime, endTime, resourceId, OPERATION_RESOURCEGROUP_WRITE, insightsClient);
                            }
                            if (resourceGroupCreateLogs.Length != 0)
                            {
                                newOwner = resourceGroupCreateLogs[0].Caller;
                            }

                            if (!unknownOwner.Equals(newOwner))
                            {
                                await group.Update().WithTag(ownerTagName, newOwner).ApplyAsync();

                                log.LogInformation($"Resource group {group.Name} tagged with owner {newOwner}");
                            }
                            else
                            {
                                log.LogInformation($"Resource group {group.Name}: did not find create operation, please tag manually");
                            }
                        }
                        else
                        {
                            log.LogTrace($"Resource group {group.Name} is already owned by {ownerTag.Value}");
                        }
                    }
                    catch (Exception ex)
                    {
                        log.LogError("Exception: " + ex);
                    }
                }
            }
        }
Example #2
0
        public Singleton()
        {
            var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal("clientId", "clientsecret", "tenantId", AzureEnvironment.AzureGlobalCloud);

            azure = Azure.Configure().Authenticate(credentials).WithDefaultSubscription();
        }
Example #3
0
        static async Task AsyncMain(string[] args)
        {
            var credentials = SdkContext.AzureCredentialsFactory.FromFile("../../Credentials/authfile.json");
            var azure       = Azure
                              .Configure()
                              .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                              .Authenticate(credentials)
                              .WithDefaultSubscription();

            Console.WriteLine("Your subscription ID: \r\n" + azure.SubscriptionId);
            Console.WriteLine("Creating an AKS Cluster!");

            String rootUser     = azureConfig.GetValue("RootUser").ToString();
            String rgName       = azureConfig.GetValue("ResourceGroup").ToString();
            String aksName      = azureConfig.GetValue("ClusterName").ToString();
            String location     = azureConfig.GetValue("Location").ToString();
            String sshPublicKey = azureConfig.GetValue("SshPublicKey").ToString();
            String clientSecret = JObject.Parse(File.ReadAllText("../../Credentials/authfile.json")).GetValue("clientSecret").ToString();

            try {
                Console.WriteLine("Trying to create the cluster...");
                IKubernetesCluster cluster = await azure.KubernetesClusters.Define(aksName)
                                             .WithRegion(location)
                                             .WithNewResourceGroup(rgName)
                                             .WithLatestVersion()
                                             .WithRootUsername(rootUser)
                                             .WithSshKey(sshPublicKey)
                                             .WithServicePrincipalClientId(credentials.ClientId)
                                             .WithServicePrincipalSecret(clientSecret)
                                             .DefineAgentPool("agentpool")
                                             .WithVirtualMachineSize(ContainerServiceVMSizeTypes.StandardA2)
                                             .WithAgentPoolVirtualMachineCount(2)
                                             .Attach()
                                             .WithDnsPrefix("dns-" + aksName)
                                             .CreateAsync();

                Console.WriteLine("Created Kubernetes Cluster: " + cluster.Id);
                Console.WriteLine(cluster);

                Console.WriteLine("Updating Kubernetes Cluster. More VMs!!: " + cluster.Id);
                await cluster.Update()
                .WithAgentPoolVirtualMachineCount(4)
                .ApplyAsync();

                Console.WriteLine("Updated Kubernetes Cluster: " + cluster.Id);
                Console.WriteLine(cluster);
            }  catch (Exception g)
            {
                Console.WriteLine(g);
            }
            finally {
                try
                {
                    Console.WriteLine("Deleting Resource Group: " + rgName);
                    await azure.ResourceGroups.BeginDeleteByNameAsync(rgName);

                    Console.WriteLine("Deleted Resource Group: " + rgName);
                }
                catch (NullReferenceException)
                {
                    Console.WriteLine("Did not create any resources in Azure. No clean up is necessary");
                }
                catch (Exception g)
                {
                    Console.WriteLine(g);
                }
            }
        }
        public static void Main(string[] args)
        {
            try
            {
                //=============================================================
                // Authenticate
                AzureCredentials credentials = AzureCredentials.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

                var azure = Azure
                            .Configure()
                            .WithLogLevel(HttpLoggingDelegatingHandler.Level.BASIC)
                            .Authenticate(credentials)
                            .WithDefaultSubscription();

                // Print selected subscription
                Console.WriteLine("Selected subscription: " + azure.SubscriptionId);

                try
                {
                    //=============================================================
                    // Create an availability set

                    Console.WriteLine("Creating an availability set");

                    var availSet1 = azure.AvailabilitySets.Define(availSetName1)
                                    .WithRegion(Region.US_EAST)
                                    .WithNewResourceGroup(rgName)
                                    .WithFaultDomainCount(2)
                                    .WithUpdateDomainCount(4)
                                    .WithTag("cluster", "Windowslinux")
                                    .WithTag("tag1", "tag1val")
                                    .Create();

                    Console.WriteLine("Created first availability set: " + availSet1.Id);
                    Utilities.PrintAvailabilitySet(availSet1);

                    //=============================================================
                    // Define a virtual network for the VMs in this availability set
                    var network = azure.Networks
                                  .Define(vnetName)
                                  .WithRegion(Region.US_EAST)
                                  .WithExistingResourceGroup(rgName)
                                  .WithAddressSpace("10.0.0.0/28");

                    //=============================================================
                    // Create a Windows VM in the new availability set

                    Console.WriteLine("Creating a Windows VM in the availability set");

                    var vm1 = azure.VirtualMachines.Define(vm1Name)
                              .WithRegion(Region.US_EAST)
                              .WithExistingResourceGroup(rgName)
                              .WithNewPrimaryNetwork(network)
                              .WithPrimaryPrivateIpAddressDynamic()
                              .WithoutPrimaryPublicIpAddress()
                              .WithPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER)
                              .WithAdminUserName(userName)
                              .WithPassword(password)
                              .WithSize(VirtualMachineSizeTypes.StandardD3V2)
                              .WithExistingAvailabilitySet(availSet1)
                              .Create();

                    Console.WriteLine("Created first VM:" + vm1.Id);
                    Utilities.PrintVirtualMachine(vm1);

                    //=============================================================
                    // Create a Linux VM in the same availability set

                    Console.WriteLine("Creating a Linux VM in the availability set");

                    var vm2 = azure.VirtualMachines.Define(vm2Name)
                              .WithRegion(Region.US_EAST)
                              .WithExistingResourceGroup(rgName)
                              .WithNewPrimaryNetwork(network)
                              .WithPrimaryPrivateIpAddressDynamic()
                              .WithoutPrimaryPublicIpAddress()
                              .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
                              .WithRootUserName(userName)
                              .WithPassword(password)
                              .WithSize(VirtualMachineSizeTypes.StandardD3V2)
                              .WithExistingAvailabilitySet(availSet1)
                              .Create();

                    Console.WriteLine("Created second VM: " + vm2.Id);
                    Utilities.PrintVirtualMachine(vm2);

                    //=============================================================
                    // Update - Tag the availability set

                    availSet1 = availSet1.Update()
                                .WithTag("server1", "nginx")
                                .WithTag("server2", "iis")
                                .WithoutTag("tag1")
                                .Apply();

                    Console.WriteLine("Tagged availability set: " + availSet1.Id);

                    //=============================================================
                    // Create another availability set

                    Console.WriteLine("Creating an availability set");

                    var availSet2 = azure.AvailabilitySets.Define(availSetName2)
                                    .WithRegion(Region.US_EAST)
                                    .WithExistingResourceGroup(rgName)
                                    .Create();

                    Console.WriteLine("Created second availability set: " + availSet2.Id);
                    Utilities.PrintAvailabilitySet(availSet2);

                    //=============================================================
                    // List availability sets

                    var resourceGroupName = availSet1.ResourceGroupName;

                    Console.WriteLine("Printing list of availability sets  =======");

                    foreach (var availabilitySet in azure.AvailabilitySets.ListByGroup(resourceGroupName))
                    {
                        Utilities.PrintAvailabilitySet(availabilitySet);
                    }

                    //=============================================================
                    // Delete an availability set

                    Console.WriteLine("Deleting an availability set: " + availSet2.Id);

                    azure.AvailabilitySets.Delete(availSet2.Id);

                    Console.WriteLine("Deleted availability set: " + availSet2.Id);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                finally
                {
                    try
                    {
                        Console.WriteLine("Deleting Resource Group: " + rgName);
                        azure.ResourceGroups.Delete(rgName);
                        Console.WriteLine("Deleted Resource Group: " + rgName);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Example #5
0
        static void Main(string[] args)
        {
            // Create the management client

            var credentials = SdkContext.AzureCredentialsFactory
                              .FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

            var azure = Azure
                        .Configure()
                        .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                        .Authenticate(credentials)
                        .WithDefaultSubscription();

            // Create a resource group

            var groupName = "myResourceGroup";
            var location  = Region.USCentral;

            var resourceGroup = azure.ResourceGroups.Define(groupName)
                                .WithRegion(location)
                                .Create();

            // Create a storage account

            string storageAccountName = SdkContext.RandomResourceName("st", 10);

            Console.WriteLine("Creating storage account...");
            var storage = azure.StorageAccounts.Define(storageAccountName)
                          .WithRegion(location)
                          .WithExistingResourceGroup(resourceGroup)
                          .Create();

            var    storageKeys             = storage.GetKeys();
            string storageConnectionString = "DefaultEndpointsProtocol=https;"
                                             + "AccountName=" + storage.Name
                                             + ";AccountKey=" + storageKeys[0].Value
                                             + ";EndpointSuffix=core.windows.net";

            var account       = CloudStorageAccount.Parse(storageConnectionString);
            var serviceClient = account.CreateCloudBlobClient();

            Console.WriteLine("Creating container...");
            var container = serviceClient.GetContainerReference("templates");

            container.CreateIfNotExistsAsync().Wait();
            var containerPermissions = new BlobContainerPermissions()
            {
                PublicAccess = BlobContainerPublicAccessType.Container
            };

            container.SetPermissionsAsync(containerPermissions).Wait();

            Console.WriteLine("Uploading template file...");
            var templateblob = container.GetBlockBlobReference("CreateVMTemplate.json");

            templateblob.UploadFromFileAsync("..\\..\\CreateVMTemplate.json");

            Console.WriteLine("Uploading parameters file...");
            var paramblob = container.GetBlockBlobReference("Parameters.json");

            paramblob.UploadFromFileAsync("..\\..\\Parameters.json");

            // Deploy a template

            Console.WriteLine("Deploying the uploaded VM template...");
            var templatePath = "https://" + storageAccountName + ".blob.core.windows.net/templates/CreateVMTemplate.json";
            var paramPath    = "https://" + storageAccountName + ".blob.core.windows.net/templates/Parameters.json";
            var deployment   = azure.Deployments.Define("myDeployment")
                               .WithExistingResourceGroup(groupName)
                               .WithTemplateLink(templatePath, "1.0.0.0")
                               .WithParametersLink(paramPath, "1.0.0.0")
                               .WithMode(Microsoft.Azure.Management.ResourceManager.Fluent.Models.DeploymentMode.Incremental)
                               .Create();

            Console.WriteLine("Deployed!");
            Console.WriteLine("Press enter to delete the resource group...");
            Console.ReadLine();

            // Delete the resources

            azure.ResourceGroups.DeleteByName(groupName);
        }
        public static void Main(string[] args)
        {
            try
            {
                //=================================================================
                // Authenticate
                var credentials = AzureCredentials.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

                var azure = Azure
                            .Configure()
                            .WithLogLevel(HttpLoggingDelegatingHandler.Level.BASIC)
                            .Authenticate(credentials)
                            .WithDefaultSubscription();

                // Print selected subscription
                Console.WriteLine("Selected subscription: " + azure.SubscriptionId);
                try
                {
                    //============================================================
                    // Assign a public IP address for a VM during its creation

                    // Define a public IP address to be used during VM creation time

                    Console.WriteLine("Creating a public IP address...");

                    var publicIpAddress = azure.PublicIpAddresses
                                          .Define(publicIpAddressName1)
                                          .WithRegion(Region.US_EAST)
                                          .WithNewResourceGroup(rgName)
                                          .WithLeafDomainLabel(publicIpAddressLeafDNS1)
                                          .Create();

                    Console.WriteLine("Created a public IP address");
                    // Print public IP address details
                    Utilities.PrintIpAddress(publicIpAddress);

                    // Use the pre-created public IP for the new VM

                    Console.WriteLine("Creating a Windows VM");

                    var t1 = DateTime.UtcNow;

                    var vm = azure.VirtualMachines.Define(vmName)
                             .WithRegion(Region.US_EAST)
                             .WithExistingResourceGroup(rgName)
                             .WithNewPrimaryNetwork("10.0.0.0/28")
                             .WithPrimaryPrivateIpAddressDynamic()
                             .WithExistingPrimaryPublicIpAddress(publicIpAddress)
                             .WithPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER)
                             .WithAdminUserName(userName)
                             .WithPassword(password)
                             .WithSize(VirtualMachineSizeTypes.StandardD3V2)
                             .Create();

                    var t2 = DateTime.UtcNow;
                    Console.WriteLine("Created VM: (took "
                                      + (t2 - t1).TotalSeconds + " seconds) " + vm.Id);
                    // Print virtual machine details
                    Utilities.PrintVirtualMachine(vm);

                    //============================================================
                    // Gets the public IP address associated with the VM's primary NIC

                    Console.WriteLine("Public IP address associated with the VM's primary NIC [After create]");
                    // Print the public IP address details
                    Utilities.PrintIpAddress(vm.GetPrimaryPublicIpAddress());

                    //============================================================
                    // Assign a new public IP address for the VM

                    // Define a new public IP address

                    var publicIpAddress2 = azure.PublicIpAddresses
                                           .Define(publicIpAddressName2)
                                           .WithRegion(Region.US_EAST)
                                           .WithNewResourceGroup(rgName)
                                           .WithLeafDomainLabel(publicIpAddressLeafDNS2)
                                           .Create();

                    // Update VM's primary NIC to use the new public IP address

                    Console.WriteLine("Updating the VM's primary NIC with new public IP address");

                    var primaryNetworkInterface = vm.GetPrimaryNetworkInterface();
                    primaryNetworkInterface
                    .Update()
                    .WithExistingPrimaryPublicIpAddress(publicIpAddress2)
                    .Apply();

                    //============================================================
                    // Gets the updated public IP address associated with the VM

                    // Get the associated public IP address for a virtual machine
                    Console.WriteLine("Public IP address associated with the VM's primary NIC [After Update]");
                    vm.Refresh();
                    Utilities.PrintIpAddress(vm.GetPrimaryPublicIpAddress());

                    //============================================================
                    // Remove public IP associated with the VM

                    Console.WriteLine("Removing public IP address associated with the VM");
                    vm.Refresh();
                    primaryNetworkInterface = vm.GetPrimaryNetworkInterface();
                    publicIpAddress         = primaryNetworkInterface.PrimaryIpConfiguration.GetPublicIpAddress();
                    primaryNetworkInterface.Update()
                    .WithoutPrimaryPublicIpAddress()
                    .Apply();

                    Console.WriteLine("Removed public IP address associated with the VM");

                    //============================================================
                    // Delete the public ip
                    Console.WriteLine("Deleting the public IP address");
                    azure.PublicIpAddresses.Delete(publicIpAddress.Id);
                    Console.WriteLine("Deleted the public IP address");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                finally
                {
                    try
                    {
                        Console.WriteLine("Deleting Resource Group: " + rgName);
                        azure.ResourceGroups.Delete(rgName);
                        Console.WriteLine("Deleted Resource Group: " + rgName);
                    }
                    catch (NullReferenceException)
                    {
                        Console.WriteLine("Did not create any resources in Azure. No clean up is necessary");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Example #7
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            //Create the management client. This will be used for all the operations
            //that we will perform in Azure.
            var credentials = SdkContext
                              .AzureCredentialsFactory
                              .FromFile("./azureauth.properties");

            var azure = Azure.Configure()
                        .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                        .Authenticate(credentials)
                        .WithDefaultSubscription();

            //First of all, we need to create a resource group where we will add all
            //the resources
            // needed for the virtual machine
            var groupName     = "mcaz204-ResourceGroup";
            var vmName        = "mcaz204VMTesting";
            var location      = Region.CanadaCentral;
            var vNetName      = "mcaz204VNET";
            var vNetAddress   = "172.16.0.0/16";
            var subnetName    = "mcaz204Subnet";
            var subnetAddress = "172.16.0.0/24";
            var nicName       = "mcaz204NIC";
            var adminUser     = "******";
            var adminPassword = "******";
            var publicIPName  = "mcaz204publicIP";
            var nsgName       = "mcaz204VNET-NSG";

            Console.WriteLine($"Creating resource group {groupName} ...");
            var resourceGroup = azure.ResourceGroups.Define(groupName)
                                .WithRegion(location)
                                .Create();

            //Every virtual machine needs to be connected to a virtual network.
            Console.WriteLine($"Creating virtual network {vNetName} ...");
            var network = azure.Networks.Define(vNetName)
                          .WithRegion(location)
                          .WithExistingResourceGroup(groupName)
                          .WithAddressSpace(vNetAddress)
                          .WithSubnet(subnetName, subnetAddress)
                          .Create();

            //You need a public IP to be able to connect to the VM from the Internet
            Console.WriteLine($"Creating public IP {publicIPName} ...");
            var publicIP = azure.PublicIPAddresses.Define(publicIPName)
                           .WithRegion(location)
                           .WithExistingResourceGroup(groupName)
                           .Create();

            //You need a network security group for controlling the access to the VM
            Console.WriteLine($"Creating Network Security Group {nsgName} ...");
            var nsg = azure.NetworkSecurityGroups.Define(nsgName)
                      .WithRegion(location)
                      .WithExistingResourceGroup(groupName)
                      .Create();

            //You need a security rule for allowing the access to the VM from the
            //Internet
            Console.WriteLine($"Creating a Security Rule for allowing the remote access");
            nsg.Update().DefineRule("Allow-RDP")
            .AllowInbound()
            .FromAnyAddress()
            .FromAnyPort()
            .ToAnyAddress()
            .ToPort(3389)
            .WithProtocol(SecurityRuleProtocol.Tcp)
            .WithPriority(100)
            .WithDescription("Allow-RDP")
            .Attach()
            .Apply();

            //Any virtual machine need a network interface for connecting to the
            //virtual network
            Console.WriteLine($"Creating network interface {nicName} ...");
            var nic = azure.NetworkInterfaces.Define(nicName)
                      .WithRegion(location)
                      .WithExistingResourceGroup(groupName)
                      .WithExistingPrimaryNetwork(network)
                      .WithSubnet(subnetName)
                      .WithPrimaryPrivateIPAddressDynamic()
                      .WithExistingPrimaryPublicIPAddress(publicIP)
                      .WithExistingNetworkSecurityGroup(nsg)
                      .Create();

            //Create the virtual machine
            Console.WriteLine($"Creating virtual machine {vmName} ...");
            azure.VirtualMachines.Define(vmName)
            .WithRegion(location)
            .WithExistingResourceGroup(groupName)
            .WithExistingPrimaryNetworkInterface(nic)
            .WithLatestWindowsImage("MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter")
            .WithAdminUsername(adminUser)
            .WithAdminPassword(adminPassword)
            .WithComputerName(vmName)
            .WithSize(VirtualMachineSizeTypes.StandardDS2V2)
            .Create();
        }
Example #8
0
        public static async Task CreateContainer(TaskLogger taskLogger, MyAppParameters myAppParameters)
        {
            // Get credentials
            var credentials = SdkContext.AzureCredentialsFactory
                              .FromServicePrincipal(myAppParameters.AzureSubscriptionClientId,
                                                    myAppParameters.AzureSubscriptionClientSecret,
                                                    myAppParameters.TenantId,
                                                    AzureEnvironment.AzureGlobalCloud);

            // Authenticate with Azure
            var azure = Azure.Configure()
                        .Authenticate(credentials)
                        .WithDefaultSubscription();

            var message = $"Authenticated with azure";
            await taskLogger.Log(message).ConfigureAwait(false);

            message = $"Getting resource group '{myAppParameters.ResourceGroupName}' details.";
            await taskLogger.Log(message).ConfigureAwait(false);

            // Check resource group exist or not.
            IResourceGroup resourceGroup = azure.ResourceGroups.GetByName(myAppParameters.ResourceGroupName);

            if (resourceGroup == null)
            {
                message = $"Resource group '{myAppParameters.ResourceGroupName}' not found.";
                throw new Exception(message);
            }

            // Check container group exist or not.
            IContainerGroup containerGroup = azure.ContainerGroups.GetByResourceGroup(myAppParameters.ResourceGroupName, myAppParameters.AgentName);

            if (containerGroup != null)
            {
                message = $"Already container group with name '{myAppParameters.AgentName}' exist in resource group '{myAppParameters.ResourceGroupName}'.";
                throw new Exception(message);
            }

            message = $"Creating container group '{myAppParameters.AgentName}' in resource group '{myAppParameters.ResourceGroupName}' with container image 'microsoft/vsts-agent:latest' ...";
            await taskLogger.Log(message).ConfigureAwait(false);

            message = $"This will take more than 15 mins... You can check container creating logs in Azure portal.";
            await taskLogger.Log(message).ConfigureAwait(false);

            var azureRegion = resourceGroup.Region;
            var env         = new Dictionary <string, string>
            {
                { "VSTS_ACCOUNT", myAppParameters.PipelineAccountName },
                { "VSTS_TOKEN", myAppParameters.PATToken },       // This PAT token used to configure the agent. This PAT token should have permission to configure the agent else container moves to running state without configuring the agent
                { "VSTS_AGENT", myAppParameters.AgentName },
                { "VSTS_POOL", myAppParameters.AgentPoolName }
            };

            // Create container group with image.
            await CreateContainerWithAsync(taskLogger, azure, resourceGroup.RegionName, myAppParameters, env);

            // You can use below function to CreateContainerGroup With Polling
            // await CreateContainerGroupWithPolling(taskLogger, azure, resourceGroup.RegionName, myAppParameters, env);

            message = $"Azure pipeline agent container running..";
            await taskLogger.Log(message).ConfigureAwait(false);
        }
Example #9
0
        static void Main(string[] args)
        {
            var credentials = SdkContext.AzureCredentialsFactory
                              .FromServicePrincipal("clientId", "clientSecret", "tenantId", AzureEnvironment.AzureGlobalCloud);


            var azure = Azure
                        .Configure()
                        .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                        .Authenticate(credentials)
                        .WithDefaultSubscription();


            var groupName = "sampleResourceGroup";
            var vmName    = "VMWithCSharp";
            var location  = Region.EuropeWest;


            var resourceGroup = azure.ResourceGroups.Define(groupName)
                                .WithRegion(location)
                                .Create();

            var network = azure.Networks.Define("sampleVirtualNetwork")
                          .WithRegion(location)
                          .WithExistingResourceGroup(groupName)
                          .WithAddressSpace("10.0.0.0/16")
                          .WithSubnet("sampleSubNet", "10.0.0.0/24")
                          .Create();

            var publicIPAddress = azure.PublicIPAddresses.Define("samplePublicIP")
                                  .WithRegion(location)
                                  .WithExistingResourceGroup(groupName)
                                  .WithDynamicIP()
                                  .Create();

            var networkInterface = azure.NetworkInterfaces.Define("sampleNetWorkInterface")
                                   .WithRegion(location)
                                   .WithExistingResourceGroup(groupName)
                                   .WithExistingPrimaryNetwork(network)
                                   .WithSubnet("sampleSubNet")
                                   .WithPrimaryPrivateIPAddressDynamic()
                                   .WithExistingPrimaryPublicIPAddress(publicIPAddress)
                                   .Create();

            var availabilitySet = azure.AvailabilitySets.Define("sampleAvailabilitySet")
                                  .WithRegion(location)
                                  .WithExistingResourceGroup(groupName)
                                  .WithSku(AvailabilitySetSkuTypes.Aligned)
                                  .Create();

            azure.VirtualMachines.Define(vmName)
            .WithRegion(location)
            .WithExistingResourceGroup(groupName)
            .WithExistingPrimaryNetworkInterface(networkInterface)
            .WithLatestWindowsImage("MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter")
            .WithAdminUsername("sampleUser")
            .WithAdminPassword("Sample123467")
            .WithComputerName(vmName)
            .WithExistingAvailabilitySet(availabilitySet)
            .WithSize(VirtualMachineSizeTypes.StandardB1s)
            .Create();
        }
        public static async Task Run(
            [TimerTrigger("0 0 0 * * *")] TimerInfo myTimer,
            TraceWriter log)
        {
            var tenantId       = Config.TenantId;
            var subscriptionId = Config.SubscriptionId;
            var clientId       = Config.ClientId;
            var clientSecret   = Config.ClientSecret;

            var credentials =
                SdkContext.AzureCredentialsFactory
                .FromServicePrincipal(
                    clientId,
                    clientSecret,
                    tenantId,
                    AzureEnvironment.AzureGlobalCloud);

            var logLevel = HttpLoggingDelegatingHandler.Level.Basic;
            var azure    = Azure.Configure()
                           .WithLogLevel(logLevel)
                           .Authenticate(credentials)
                           .WithSubscription(subscriptionId);

            var resourceGroupName = Config.ResourceGroupName;

            log.Info($"Firewall rules on database servers in {resourceGroupName} are updating...");

            var res = await azure.WebApps
                      .Inner
                      .ListByResourceGroupWithHttpMessagesAsync(resourceGroupName)
                      .ConfigureAwait(false);

            var webapps     = res.Body.ToList();
            var outboundIps = webapps.SelectMany(p => p.OutboundIpAddresses.Split(','))
                              .Distinct()
                              .ToList();

            var tasks = new List <Task>();

            var servers = await azure.SqlServers
                          .ListByResourceGroupAsync(resourceGroupName)
                          .ConfigureAwait(false);

            foreach (var server in servers)
            {
                var registeredIps = server.FirewallRules
                                    .List()
                                    .ToDictionary(p => p.Name, p => p.StartIPAddress);
                var ipsToExclude = registeredIps.Where(p => !outboundIps.Contains(p.Value))
                                   .Select(p => p.Key)
                                   .ToList();
                var IpsToInclude = outboundIps.Where(p => !registeredIps.ContainsValue(p))
                                   .ToList();

                var tasksToExclude = ipsToExclude.Select(ip => server.FirewallRules
                                                         .DeleteAsync(ip));
                var tasksToInclude = IpsToInclude.Select(ip => server.FirewallRules
                                                         .Define($"webapp-{ip.Replace(".", "-")}")
                                                         .WithIPAddressRange(ip, ip)
                                                         .CreateAsync());
                tasks.AddRange(tasksToExclude);
                tasks.AddRange(tasksToInclude);
            }

            await Task.WhenAll(tasks).ConfigureAwait(false);

            log.Info($"Firewall rules on database servers in {resourceGroupName} have been updated.");
        }
        public static async Task Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");

            //Parse alert request
            string  requestBody = new StreamReader(req.Body).ReadToEnd();
            Webhook data        = new Webhook();

            data = JsonConvert.DeserializeObject <Webhook>(requestBody);
            Context alertResource = data.RequestBody.context;

            IConfigurationRoot config = new ConfigurationBuilder()
                                        .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                                        .AddEnvironmentVariables()
                                        .Build();

            string tenantId  = config.GetConnectionString("TenantId");
            string clientId  = config.GetConnectionString("clientId");
            string clientKey = config.GetConnectionString("ClientKey");

            if (string.IsNullOrEmpty(tenantId) || string.IsNullOrEmpty(clientId) || string.IsNullOrEmpty(clientKey))
            {
                log.Error("Serivice credentials are null. Check connection string settings");
                return;
            }

            AzureCredentials credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId, clientKey, tenantId, AzureEnvironment.AzureGlobalCloud);
            IAzure           azure       = Azure.Configure().Authenticate(credentials).WithSubscription(alertResource.subscriptionId);

            if (azure == null)
            {
                log.Error("Error: Issues logging into Azure subscription: " + alertResource.subscriptionId + ". Exiting.");
                return;
            }

            IVirtualMachine VM = await azure.VirtualMachines.GetByIdAsync(alertResource.resourceId);

            if (VM == null)
            {
                log.Error("Error: VM: " + alertResource.resourceId + "was not found. Exiting.");
                return;
            }

            INetworkWatcher networkWatcher = await EnsureNetworkWatcherExists(azure, VM.Region, log);

            InstallNetworkWatcherExtension(VM, log);

            string storageAccountId = Environment.GetEnvironmentVariable("PacketCaptureStorageAccount");
            var    storageAccount   = await azure.StorageAccounts.GetByIdAsync(storageAccountId);

            if (storageAccount == null)
            {
                log.Error("Storage Account: " + storageAccountId + " not found. Exiting.");
                return;
            }

            string packetCaptureName = VM.Name.Substring(0, System.Math.Min(63, VM.Name.Length)) + System.DateTime.Now.ToString("s").Replace(":", "");

            IPacketCaptures packetCapturesObj = networkWatcher.PacketCaptures;
            var             packetCaptures    = packetCapturesObj.List().ToList();

            if (packetCaptures.Count >= 10)
            {
                log.Info("More than 10 Captures, finding oldest.");
                var packetCaptureTasks = new List <Task <IPacketCaptureStatus> >();
                foreach (IPacketCapture pcap in packetCaptures)
                {
                    packetCaptureTasks.Add(pcap.GetStatusAsync());
                }

                var packetCaptureStatuses = new List <Tuple <IPacketCapture, IPacketCaptureStatus> >();
                for (int i = 0; i < packetCaptureTasks.Count; ++i)
                {
                    packetCaptureStatuses.Add(new Tuple <IPacketCapture, IPacketCaptureStatus>(packetCaptures[i], await packetCaptureTasks[i]));
                }

                packetCaptureStatuses.Sort((Tuple <IPacketCapture, IPacketCaptureStatus> first, Tuple <IPacketCapture, IPacketCaptureStatus> second) =>
                {
                    return(first.Item2.CaptureStartTime.CompareTo(second.Item2.CaptureStartTime));
                });
                log.Info("Removing: " + packetCaptureStatuses.First().Item1.Name);
                await networkWatcher.PacketCaptures.DeleteByNameAsync(packetCaptureStatuses.First().Item1.Name);
            }

            log.Info("Creating Packet Capture");
            await networkWatcher.PacketCaptures
            .Define(packetCaptureName)
            .WithTarget(VM.Id)
            .WithStorageAccountId(storageAccount.Id)
            .WithTimeLimitInSeconds(15)
            .CreateAsync();

            log.Info("Packet Capture created successfully");
        }
Example #12
0
        static void Main(string[] args)
        {
            var settingsFile = "C:\\Users\\Beheerder\\source\\repos\\az203\\provision.vm\\azureauth.properties";

            WriteLine($"Creating Credentials from {settingsFile}...");
            var credentials =
                SdkContext.AzureCredentialsFactory.FromFile(settingsFile);

            WriteLine(credentials.ToString());
            var azure = Azure.Configure().WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                        .Authenticate(credentials)
                        .WithDefaultSubscription();

            var groupName = "az203.iaas.code";
            var vmName    = "az203ws12r2code";
            var location  = Region.EuropeWest;

            WriteLine("Creating Resource Group..");
            var resourceGroup = azure.ResourceGroups
                                .Define(groupName)
                                .WithRegion(location)
                                .Create();

            WriteLine("Creating Availablity Set..");
            var availabilitySet = azure.AvailabilitySets
                                  .Define("az203.as")
                                  .WithRegion(location)
                                  .WithExistingResourceGroup(resourceGroup)
                                  .WithSku(AvailabilitySetSkuTypes.Aligned).Create();

            WriteLine("Creating Public IP..");
            var publicIpAddress = azure.PublicIPAddresses
                                  .Define($"{vmName}.pip.1")
                                  .WithRegion(location)
                                  .WithExistingResourceGroup(groupName)
                                  .WithDynamicIP().Create();

            WriteLine("Creating VNet..");
            var vnet = azure.Networks.Define("az203.vnet")
                       .WithRegion(location)
                       .WithExistingResourceGroup(groupName)
                       .WithAddressSpace("10.0.0.0/16")
                       .WithSubnet("az203.sn.1", "10.0.0.0/24")
                       .Create();

            WriteLine("Creating NIC..");
            var nic = azure.NetworkInterfaces.Define($"{vmName}.nic.1")
                      .WithRegion(location)
                      .WithExistingResourceGroup(groupName)
                      .WithExistingPrimaryNetwork(vnet)
                      .WithSubnet("az203.sn.1")
                      .WithPrimaryPrivateIPAddressDynamic()
                      .WithExistingPrimaryPublicIPAddress(publicIpAddress)
                      .Create();

            WriteLine("Creating Virtual Machine..");
            azure.VirtualMachines.Define(vmName)
            .WithRegion(location)
            .WithExistingResourceGroup(groupName)
            .WithExistingPrimaryNetworkInterface(nic)
            .WithLatestWindowsImage("MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter")
            .WithAdminUsername("demoadmin")
            .WithAdminPassword("Azure12345678!@#")
            .WithComputerName(vmName)
            .WithExistingAvailabilitySet(availabilitySet)
            .WithSize(VirtualMachineSizeTypes.StandardB1s)
            .Create();

            // if you want a managed disk..

            //            var managedDisk = azure.Disks.Define("myosdisk")
            //                .WithRegion(location)
            //                .WithExistingResourceGroup(groupName)
            //                .WithWindowsFromVhd("https://mystorage.blob.core.windows.net/vhds/myosdisk.vhd")
            //                .WithSizeInGB(128)
            //                .WithSku(DiskSkuTypes.PremiumLRS)
            //                .Create();
            //
            //            azure.VirtualMachines.Define(vmName)
            //                .WithRegion(location)
            //                .WithExistingResourceGroup(groupName)
            //                .WithExistingPrimaryNetworkInterface(nic)
            //                .WithSpecializedOSDisk(managedDisk, OperatingSystemTypes.Windows)
            //                .WithExistingAvailabilitySet(availabilitySet)
            //                .WithSize(VirtualMachineSizeTypes.StandardDS1)
            //                .Create();


            var vm = azure.VirtualMachines.GetByResourceGroup(groupName, vmName);

            WriteLine("Getting information about the virtual machine...");
            WriteLine("hardwareProfile");
            WriteLine("   vmSize: " + vm.Size);
            WriteLine("storageProfile");
            WriteLine("  imageReference");
            WriteLine("    publisher: " + vm.StorageProfile.ImageReference.Publisher);
            WriteLine("    offer: " + vm.StorageProfile.ImageReference.Offer);
            WriteLine("    sku: " + vm.StorageProfile.ImageReference.Sku);
            WriteLine("    version: " + vm.StorageProfile.ImageReference.Version);
            WriteLine("  osDisk");
            WriteLine("    osType: " + vm.StorageProfile.OsDisk.OsType);
            WriteLine("    name: " + vm.StorageProfile.OsDisk.Name);
            WriteLine("    createOption: " + vm.StorageProfile.OsDisk.CreateOption);
            WriteLine("    caching: " + vm.StorageProfile.OsDisk.Caching);
            WriteLine("osProfile");
            WriteLine("  computerName: " + vm.OSProfile.ComputerName);
            WriteLine("  adminUsername: "******"  provisionVMAgent: " + vm.OSProfile.WindowsConfiguration.ProvisionVMAgent.Value);
            WriteLine("  enableAutomaticUpdates: " + vm.OSProfile.WindowsConfiguration.EnableAutomaticUpdates.Value);
            WriteLine("networkProfile");
            foreach (string nicId in vm.NetworkInterfaceIds)
            {
                WriteLine("  networkInterface id: " + nicId);
            }
            WriteLine("vmAgent");
            WriteLine("  vmAgentVersion" + vm.InstanceView.VmAgent.VmAgentVersion);
            WriteLine("    statuses");
            foreach (InstanceViewStatus stat in vm.InstanceView.VmAgent.Statuses)
            {
                WriteLine("    code: " + stat.Code);
                WriteLine("    level: " + stat.Level);
                WriteLine("    displayStatus: " + stat.DisplayStatus);
                WriteLine("    message: " + stat.Message);
                WriteLine("    time: " + stat.Time);
            }
            WriteLine("disks");
            foreach (DiskInstanceView disk in vm.InstanceView.Disks)
            {
                WriteLine("  name: " + disk.Name);
                WriteLine("  statuses");
                foreach (InstanceViewStatus stat in disk.Statuses)
                {
                    WriteLine("    code: " + stat.Code);
                    WriteLine("    level: " + stat.Level);
                    WriteLine("    displayStatus: " + stat.DisplayStatus);
                    WriteLine("    time: " + stat.Time);
                }
            }
            WriteLine("VM general status");
            WriteLine("  provisioningStatus: " + vm.ProvisioningState);
            WriteLine("  id: " + vm.Id);
            WriteLine("  name: " + vm.Name);
            WriteLine("  type: " + vm.Type);
            WriteLine("  location: " + vm.Region);
            WriteLine("VM instance status");
            foreach (InstanceViewStatus stat in vm.InstanceView.Statuses)
            {
                WriteLine("  code: " + stat.Code);
                WriteLine("  level: " + stat.Level);
                WriteLine("  displayStatus: " + stat.DisplayStatus);
            }
            WriteLine("Press enter to continue...");
            ReadLine();
        }
Example #13
0
        private static void ConfigureResources(string projectName, List <string> testAgents)
        {
            Configurations configurations = GetProjectConfigurations(projectName);

            try
            {
                AzureCredentials credentials = SdkContext.AzureCredentialsFactory
                                               .FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

                IAzure azure = Azure
                               .Configure()
                               .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                               .Authenticate(credentials)
                               .WithDefaultSubscription();


                foreach (var testAgent in testAgents)
                {
                    Console.WriteLine("Creating Disks for VM: " + testAgent);

                    var osDiskName = testAgent + "_OSDisk";
                    var osDisk     = azure.Disks.Define(osDiskName)
                                     .WithRegion(region)
                                     .WithExistingResourceGroup(configurations.ResourceGroup)
                                     .WithWindowsFromSnapshot(configurations.OSDisksnapshot)
                                     .WithSizeInGB(127)
                                     .WithSku(DiskSkuTypes.PremiumLRS)
                                     .Create();
                    Console.WriteLine("OS Disk created for VM: " + testAgent);

                    var dataDisk1Name = testAgent + "_DataDisk1";
                    var dataDisk1     = azure.Disks.Define(dataDisk1Name)
                                        .WithRegion(region)
                                        .WithExistingResourceGroup(configurations.ResourceGroup)
                                        .WithData()
                                        .FromSnapshot(configurations.DataDisk1Snapshot)
                                        .WithSku(DiskSkuTypes.PremiumLRS)
                                        .Create();


                    var dataDisk2Name = testAgent + "_DataDisk2";
                    var dataDisk2     = azure.Disks.Define(dataDisk2Name)
                                        .WithRegion(region)
                                        .WithExistingResourceGroup(configurations.ResourceGroup)
                                        .WithData()
                                        .FromSnapshot(configurations.DataDisk2Snapshot)
                                        .WithSku(DiskSkuTypes.PremiumLRS)
                                        .Create();
                    Console.WriteLine("Data disks created for VM: " + testAgent);

                    var networkInterface = CreateNic(azure, testAgent, configurations);

                    var virtualMachine = azure.VirtualMachines.Define(testAgent)
                                         .WithRegion(region)
                                         .WithExistingResourceGroup(configurations.ResourceGroup)
                                         .WithExistingPrimaryNetworkInterface(networkInterface)
                                         .WithSpecializedOSDisk(osDisk, OperatingSystemTypes.Windows)
                                         .WithExistingDataDisk(dataDisk1, 0, CachingTypes.ReadWrite)
                                         .WithExistingDataDisk(dataDisk2, 1, CachingTypes.ReadWrite)
                                         .WithSize(VirtualMachineSizeTypes.StandardD8sV3)
                                         .Create();
                    Console.WriteLine("Created VM: " + testAgent);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw;
            }
        }
Example #14
0
        public static void Main(string[] args)
        {
            try
            {
                //=============================================================
                // Authenticate
                AzureCredentials credentials = AzureCredentials.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

                var azure = Azure
                            .Configure()
                            .WithLogLevel(HttpLoggingDelegatingHandler.Level.BASIC)
                            .Authenticate(credentials)
                            .WithDefaultSubscription();

                // Print selected subscription
                Console.WriteLine("Selected subscription: " + azure.SubscriptionId);

                try
                {
                    // Create a resource group [Where all resources gets created]
                    IResourceGroup resourceGroup = azure.ResourceGroups
                                                   .Define(rgName)
                                                   .WithRegion(Region.US_EAST)
                                                   .Create();

                    //============================================================
                    // Define a network security group for the front end of a subnet
                    // front end subnet contains two rules
                    // - ALLOW-SSH - allows SSH traffic into the front end subnet
                    // - ALLOW-WEB- allows HTTP traffic into the front end subnet

                    var frontEndNSGCreatable = azure.NetworkSecurityGroups
                                               .Define(frontEndNSGName)
                                               .WithRegion(Region.US_EAST)
                                               .WithExistingResourceGroup(resourceGroup)
                                               .DefineRule("ALLOW-SSH")
                                               .AllowInbound()
                                               .FromAnyAddress()
                                               .FromAnyPort()
                                               .ToAnyAddress()
                                               .ToPort(22)
                                               .WithProtocol(SecurityRuleProtocol.Tcp)
                                               .WithPriority(100)
                                               .WithDescription("Allow SSH")
                                               .Attach()
                                               .DefineRule("ALLOW-HTTP")
                                               .AllowInbound()
                                               .FromAnyAddress()
                                               .FromAnyPort()
                                               .ToAnyAddress()
                                               .ToPort(80)
                                               .WithProtocol(SecurityRuleProtocol.Tcp)
                                               .WithPriority(101)
                                               .WithDescription("Allow HTTP")
                                               .Attach();

                    //============================================================
                    // Define a network security group for the back end of a subnet
                    // back end subnet contains two rules
                    // - ALLOW-SQL - allows SQL traffic only from the front end subnet
                    // - DENY-WEB - denies all outbound internet traffic from the back end subnet

                    var backEndNSGCreatable = azure.NetworkSecurityGroups
                                              .Define(backEndNSGName)
                                              .WithRegion(Region.US_EAST)
                                              .WithExistingResourceGroup(resourceGroup)
                                              .DefineRule("ALLOW-SQL")
                                              .AllowInbound()
                                              .FromAddress("172.16.1.0/24")
                                              .FromAnyPort()
                                              .ToAnyAddress()
                                              .ToPort(1433)
                                              .WithProtocol(SecurityRuleProtocol.Tcp)
                                              .WithPriority(100)
                                              .WithDescription("Allow SQL")
                                              .Attach()
                                              .DefineRule("DENY-WEB")
                                              .DenyOutbound()
                                              .FromAnyAddress()
                                              .FromAnyPort()
                                              .ToAnyAddress()
                                              .ToAnyPort()
                                              .WithAnyProtocol()
                                              .WithDescription("Deny Web")
                                              .WithPriority(200)
                                              .Attach();

                    Console.WriteLine("Creating a security group for the front ends - allows SSH and HTTP");
                    Console.WriteLine("Creating a security group for the back ends - allows SSH and denies all outbound internet traffic");

                    var networkSecurityGroups = azure.NetworkSecurityGroups
                                                .Create(frontEndNSGCreatable, backEndNSGCreatable);

                    INetworkSecurityGroup frontendNSG = networkSecurityGroups.First(n => n.Name.Equals(frontEndNSGName, StringComparison.OrdinalIgnoreCase));
                    INetworkSecurityGroup backendNSG  = networkSecurityGroups.First(n => n.Name.Equals(backEndNSGName, StringComparison.OrdinalIgnoreCase));

                    Console.WriteLine("Created a security group for the front end: " + frontendNSG.Id);
                    Utilities.PrintNetworkSecurityGroup(frontendNSG);

                    Console.WriteLine("Created a security group for the back end: " + backendNSG.Id);
                    Utilities.PrintNetworkSecurityGroup(backendNSG);

                    // Create Network [Where all the virtual machines get added to]
                    var network = azure.Networks
                                  .Define(networkName)
                                  .WithRegion(Region.US_EAST)
                                  .WithExistingResourceGroup(resourceGroup)
                                  .WithAddressSpace("172.16.0.0/16")
                                  .DefineSubnet("Front-end")
                                  .WithAddressPrefix("172.16.1.0/24")
                                  .WithExistingNetworkSecurityGroup(frontendNSG)
                                  .Attach()
                                  .DefineSubnet("Back-end")
                                  .WithAddressPrefix("172.16.2.0/24")
                                  .WithExistingNetworkSecurityGroup(backendNSG)
                                  .Attach()
                                  .Create();

                    // Prepare Creatable Storage account definition [For storing VMs disk]
                    var creatableStorageAccount = azure.StorageAccounts
                                                  .Define(storageAccountName)
                                                  .WithRegion(Region.US_EAST)
                                                  .WithExistingResourceGroup(resourceGroup);

                    // Prepare a batch of Creatable Virtual Machines definitions
                    List <ICreatable <IVirtualMachine> > frontendCreatableVirtualMachines = new List <ICreatable <IVirtualMachine> >();

                    for (int i = 0; i < frontendVmCount; i++)
                    {
                        var creatableVirtualMachine = azure.VirtualMachines
                                                      .Define("VM-FE-" + i)
                                                      .WithRegion(Region.US_EAST)
                                                      .WithExistingResourceGroup(resourceGroup)
                                                      .WithExistingPrimaryNetwork(network)
                                                      .WithSubnet("Front-end")
                                                      .WithPrimaryPrivateIpAddressDynamic()
                                                      .WithoutPrimaryPublicIpAddress()
                                                      .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
                                                      .WithRootUserName(userName)
                                                      .WithPassword(password)
                                                      .WithSize(VirtualMachineSizeTypes.StandardD3V2)
                                                      .WithNewStorageAccount(creatableStorageAccount);
                        frontendCreatableVirtualMachines.Add(creatableVirtualMachine);
                    }

                    List <ICreatable <IVirtualMachine> > backendCreatableVirtualMachines = new List <ICreatable <IVirtualMachine> >();

                    for (int i = 0; i < backendVmCount; i++)
                    {
                        var creatableVirtualMachine = azure.VirtualMachines
                                                      .Define("VM-BE-" + i)
                                                      .WithRegion(Region.US_EAST)
                                                      .WithExistingResourceGroup(resourceGroup)
                                                      .WithExistingPrimaryNetwork(network)
                                                      .WithSubnet("Back-end")
                                                      .WithPrimaryPrivateIpAddressDynamic()
                                                      .WithoutPrimaryPublicIpAddress()
                                                      .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
                                                      .WithRootUserName(userName)
                                                      .WithPassword(password)
                                                      .WithSize(VirtualMachineSizeTypes.StandardD3V2)
                                                      .WithNewStorageAccount(creatableStorageAccount);
                        backendCreatableVirtualMachines.Add(creatableVirtualMachine);
                    }

                    var startTime = DateTimeOffset.Now.UtcDateTime;
                    Console.WriteLine("Creating the virtual machines");

                    List <ICreatable <IVirtualMachine> > allCreatableVirtualMachines = new List <ICreatable <IVirtualMachine> >();
                    allCreatableVirtualMachines.AddRange(frontendCreatableVirtualMachines);
                    allCreatableVirtualMachines.AddRange(backendCreatableVirtualMachines);

                    var virtualMachines = azure.VirtualMachines.Create(allCreatableVirtualMachines.ToArray());

                    var endTime = DateTimeOffset.Now.UtcDateTime;
                    Console.WriteLine("Created virtual machines");

                    foreach (var virtualMachine in virtualMachines)
                    {
                        Console.WriteLine(virtualMachine.Id);
                    }

                    Console.WriteLine($"Virtual machines create: took {(endTime - startTime).TotalSeconds } seconds");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                finally
                {
                    Console.WriteLine($"Deleting resource group : {rgName}");
                    azure.ResourceGroups.Delete(rgName);
                    Console.WriteLine($"Deleted resource group : {rgName}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Example #15
0
        static void Main(string[] args)
        {
            var credentials = SdkContext.AzureCredentialsFactory.FromFile("../../Credentials/authfile.json");

            var azure = Azure
                        .Configure()
                        .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                        .Authenticate(credentials)
                        .WithSubscription(credentials.DefaultSubscriptionId);



            var groupName = "az204_" + rng;
            var vmName    = "az204" + rng;
            var location  = "northeurope";

            Console.WriteLine("Creating Resource Group...");
            var resourceGroup = azure.ResourceGroups.Define(groupName)
                                .WithRegion(location)
                                .Create();

            // Optionally create availability set for HA scenarios

            /*
             * IAvailabilitySet availabilitySet;
             * Console.WriteLine("Creating availability set...");
             * try
             * {
             *  availabilitySet = azure.AvailabilitySets.Define("myAVSet")
             *      .WithRegion(location)
             *      .WithExistingResourceGroup(groupName)
             *      .WithSku(AvailabilitySetSkuTypes.Aligned)
             *      .Create();
             * }
             * catch (System.Threading.Tasks.TaskCanceledException e)
             * {
             *  Console.WriteLine(e.Message);
             *  throw;
             * }
             */
            Console.WriteLine("Creating public IP address...");
            var publicIPAddress = azure.PublicIPAddresses.Define("myPublicIP")
                                  .WithRegion(location)
                                  .WithExistingResourceGroup(groupName)
                                  .WithDynamicIP()
                                  .Create();

            Console.WriteLine("Creating virtual network...");
            var network = azure.Networks.Define("myVnet")
                          .WithRegion(location)
                          .WithExistingResourceGroup(groupName)
                          .WithAddressSpace("10.0.0.0/16")
                          .WithSubnet("mySubnet", "10.0.0.0/24")
                          .Create();

            Console.WriteLine("Creating network interface...");
            var networkInterface = azure.NetworkInterfaces.Define("myNIC")
                                   .WithRegion(location)
                                   .WithExistingResourceGroup(groupName)
                                   .WithExistingPrimaryNetwork(network)
                                   .WithSubnet("mySubnet")
                                   .WithPrimaryPrivateIPAddressDynamic()
                                   .WithExistingPrimaryPublicIPAddress(publicIPAddress)
                                   .Create();

            Console.WriteLine("Creating virtual machine...");
            azure.VirtualMachines.Define(vmName)
            .WithRegion(location)
            .WithExistingResourceGroup(groupName)
            .WithExistingPrimaryNetworkInterface(networkInterface)
            .WithLatestWindowsImage("MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter")
            .WithAdminUsername("azureuser")
            .WithAdminPassword("Pa$$word123!")
            //.WithExistingAvailabilitySet(availabilitySet)
            .WithSize(VirtualMachineSizeTypes.StandardDS1V2)
            .Create();
        }
Example #16
0
        static void Main(string[] args)
        {
            //Resource details
            var groupName     = "rg-vm-test-westeu-1";
            var vmName        = "vmconsole1";
            var location      = Region.EuropeWest;
            var vNetName      = "vnet-vm-test-westeu-1";
            var vNetAddress   = "172.16.0.0/16";
            var subnetName    = "snet-vm-test-westeu-1";
            var subnetAddress = "172.16.0.0/24";
            var nicName       = "nic-vm-westeu-1";
            var adminUser     = "******";
            var adminPassword = "******";
            var publicIPName  = "pip-vm-test-westeu-1";
            var nsgName       = "nsg-vm-test-westeu-1";


            //Creates management client
            var credentials = SdkContext.AzureCredentialsFactory.FromFile("./azureAuth.properties");
            var azure       = Azure.Configure().WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic).Authenticate(credentials).WithDefaultSubscription();

            Console.WriteLine($"Creating RG: {groupName}");
            var resourceGroup = azure.ResourceGroups.Define(groupName)
                                .WithRegion(location)
                                .Create();

            Console.WriteLine($"Creating VNET: {vNetName}");
            var vnet = azure.Networks.Define(vNetName)
                       .WithRegion(location)
                       .WithExistingResourceGroup(groupName)
                       .WithAddressSpace(vNetAddress)
                       .WithSubnet(subnetName, subnetAddress)
                       .Create();

            // Optional
            Console.WriteLine($"Creating PIP: {publicIPName}");
            var pip = azure.PublicIPAddresses.Define(publicIPName)
                      .WithRegion(location)
                      .WithExistingResourceGroup(groupName)
                      .Create();

            // Optional
            Console.WriteLine($"Creating NSG: {nsgName}");
            var nsg = azure.NetworkSecurityGroups.Define(nsgName)
                      .WithRegion(location)
                      .WithExistingResourceGroup(groupName)
                      .Create();

            // Optional
            Console.WriteLine($"Creating sec rule: Allow RDP");
            nsg.Update()
            .DefineRule("Allow-RDP")
            .AllowInbound()
            .FromAnyAddress()
            .FromAnyPort()
            .ToAnyAddress()
            .ToPort(3389)
            .WithProtocol(SecurityRuleProtocol.Tcp)
            .WithPriority(100)
            .WithDescription("Allow-RDP")
            .Attach()
            .Apply();
            Console.WriteLine($"Creating NIC: {nicName}");
            var nic = azure.NetworkInterfaces.Define(nicName)
                      .WithRegion(location)
                      .WithExistingResourceGroup(groupName)
                      .WithExistingPrimaryNetwork(vnet)
                      .WithSubnet(subnetName)
                      .WithPrimaryPrivateIPAddressDynamic()
                      // Optional
                      .WithExistingPrimaryPublicIPAddress(pip)
                      .WithExistingNetworkSecurityGroup(nsg)
                      //
                      .Create();

            Console.WriteLine($"Creating VM: {vmName}");
            var vm = azure.VirtualMachines.Define(vmName)
                     .WithRegion(location)
                     .WithExistingResourceGroup(groupName)
                     .WithExistingPrimaryNetworkInterface(nic)
                     .WithLatestWindowsImage("MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter")
                     .WithAdminUsername(adminUser)
                     .WithAdminPassword(adminPassword)
                     .WithComputerName(vmName)
                     .WithSize(VirtualMachineSizeTypes.StandardDS2V2)
                     .Create();
        }
Example #17
0
        static void Main(string[] args)
        {
            // The file with the Azure Service Principal Credentials.
            var authFile = "my.azureauth";

            // Parse the credentials from the file.
            var credentials = SdkContext.AzureCredentialsFactory.FromFile(authFile);

            // Authenticate with Azure
            var azure = Azure
                        .Configure()
                        .Authenticate(credentials)
                        .WithDefaultSubscription();

            // Create an InsightsClient instance.
            var client = new InsightsClient(credentials);

            // If we subscription is not set the API call will fail.
            client.SubscriptionId = credentials.DefaultSubscriptionId;

            // Create the OData filter for a time interval and the Azure.Health Provider.
            // Search back one day.
            var    days          = -1;
            var    endDateTime   = DateTime.Now;
            var    startDateTime = endDateTime.AddDays(days);
            string filterString  = FilterString.Generate <EventDataForFilter>(eventData =>
                                                                              (eventData.EventTimestamp >= startDateTime) &&
                                                                              (eventData.EventTimestamp <= endDateTime) &&
                                                                              (eventData.ResourceProvider == "Azure.Health"));

            // Get the Events from Azure.
            var response = client.Events.List(filterString);

            while (response != null && response.Any())
            {
                foreach (var eventData in response)
                {
                    // Set the Console Color according to the Event Status.
                    if (eventData.Status.Value != "Resolved" &&
                        eventData.Level <= EventLevel.Warning)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                    }
                    else if (eventData.Status.Value == "Resolved")
                    {
                        Console.ForegroundColor = ConsoleColor.Green;
                    }
                    else
                    {
                        Console.ForegroundColor = ConsoleColor.White;
                    }

                    // Write event data to the console
                    Console.WriteLine($"{eventData.EventTimestamp.ToLocalTime()} - {eventData.ResourceProviderName.Value} - {eventData.OperationName.Value}");
                    Console.WriteLine($"Status:\t {eventData.Status.Value}");
                    Console.WriteLine($"Level:\t {eventData.Level.ToString()}");
                    Console.WriteLine($"CorrelationId:\t {eventData.CorrelationId}");
                    Console.WriteLine($"Resource Type:\t {eventData.ResourceType.Value}");
                    Console.WriteLine($"Description:\t {eventData.Description}");
                }

                // Get more events if available.
                if (!string.IsNullOrEmpty(response.NextPageLink))
                {
                    response = client.Events.ListNext(response.NextPageLink);
                }
                else
                {
                    response = null;
                }
            }

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("No more events...");
            Console.ForegroundColor = ConsoleColor.White;
        }
Example #18
0
        public static void Run([TimerTrigger("0 0 */6 * * *", RunOnStartup = true)] TimerInfo myTimer, ILogger logger, ExecutionContext context)
        {
            logger.LogInformation($"C# Timer trigger function starting at: {DateTime.UtcNow}");

            IConfigurationRoot config = new ConfigurationBuilder()
                                        .SetBasePath(context.FunctionAppDirectory)
                                        .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                                        .AddEnvironmentVariables()
                                        .Build();

            var isEnabled = config["IsEnabled"];

            if (isEnabled != null && isEnabled.Equals(Boolean.FalseString))
            {
                logger.LogInformation("Function not enabled");
                return;
            }

            var tenantId         = config["TenantId"];
            var exceptedRGsRegex = config["Exceptions"];
            var environment      = AzureEnvironment.AzureGlobalCloud;
            AzureCredentials credentials;
            var isRunningLocally = config["IsRunningLocally"];

            if (isRunningLocally != null && isRunningLocally.Equals(Boolean.TrueString))
            {
                var clientId     = config["ClientId"];
                var clientSecret = config["ClientSecret"];
                credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId, clientSecret, tenantId, environment);
            }
            else
            {
                credentials = SdkContext.AzureCredentialsFactory.FromMSI(new MSILoginInformation(MSIResourceType.AppService), AzureEnvironment.AzureGlobalCloud);
            }

            var authenticated = Azure
                                .Configure()
                                .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                                .Authenticate(credentials);

            foreach (var subscriptionId in config["Subscriptions"].Split(',', StringSplitOptions.RemoveEmptyEntries))
            {
                try
                {
                    var subCleaner = new AzureSubscriptionCleaner(authenticated, subscriptionId, exceptedRGsRegex, logger, config);
                    using (logger.BeginScope(
                               new Dictionary <string, object>
                    {
                        [nameof(subscriptionId)] = subscriptionId
                    })
                           )
                    {
                        subCleaner.ProcessSubscription();
                    }
                }
                catch (Exception ex)
                {
                    logger.LogError(
                        $"Exception occured while processing the subscription: {Environment.NewLine} {ex}");
                }
            }

            logger.LogInformation($"C# Timer trigger function finishing at: {DateTime.Now}");
        }
Example #19
0
 public IAzure GetClient() => Azure.Configure()
 .WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders)
 .Authenticate(_credentials).WithDefaultSubscription();
        public async Task Create()
        {
            try
            {
                var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId, clientSecret, tenantId, AzureEnvironment.AzureGlobalCloud);

                var azure = Azure
                            .Configure()
                            .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                            .Authenticate(credentials)
                            .WithSubscription(subscriptionId);

                //var groupName = ResourceGroup;
                var location = this.Region;

                var resourceGroup = azure.ResourceGroups.Define(ResourceGroup) //groupname
                                    .WithRegion(location)
                                    .Create();

                //Storage
                string storageAccountName = SdkContext.RandomResourceName("st", 10);

                //Console.WriteLine("Creating storage account...");
                var storage = azure.StorageAccounts.Define(storageAccountName)
                              .WithRegion(this.Region)
                              .WithExistingResourceGroup(resourceGroup)
                              .Create();

                var    storageKeys             = storage.GetKeys();
                string storageConnectionString = "DefaultEndpointsProtocol=https;"
                                                 + "AccountName=" + storage.Name
                                                 + ";AccountKey=" + storageKeys[0].Value
                                                 + ";EndpointSuffix=core.windows.net";

                var account       = CloudStorageAccount.Parse(storageConnectionString);
                var serviceClient = account.CreateCloudBlobClient();

                //Console.WriteLine("Creating container...");
                var container = serviceClient.GetContainerReference("templates");
                container.CreateIfNotExistsAsync().Wait();

                var containerPermissions = new BlobContainerPermissions()
                {
                    PublicAccess = BlobContainerPublicAccessType.Container
                };

                container.SetPermissionsAsync(containerPermissions).Wait();

                //Console.WriteLine("Uploading template file...");
                CloudBlockBlob templateblob = container.GetBlockBlobReference(templateJSON);
                await templateblob.UploadFromFileAsync(templateJSON);

                //Console.WriteLine("Uploading parameters file...");
                CloudBlockBlob paramblob = container.GetBlockBlobReference(paramsJSON);
                await paramblob.UploadFromFileAsync(paramsJSON);

                //Deploy
                var templatePath = String.Format("https://{0}.blob.core.windows.net/templates/{1}", storageAccountName, templateJSON);
                var paramPath    = String.Format("https://{0}.blob.core.windows.net/templates/{1}", storageAccountName, paramsJSON);

                var deployment = azure.Deployments.Define("myDeployment")
                                 .WithExistingResourceGroup(ResourceGroup)
                                 .WithTemplateLink(templatePath, "1.0.0.0")
                                 .WithParametersLink(paramPath, "1.0.0.0")
                                 .WithMode(Microsoft.Azure.Management.ResourceManager.Fluent.Models.DeploymentMode.Incremental)
                                 .Create();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        public async Task <Azure.IAuthenticated> GetAzureConnection()
        {
            if (_azure != null)
            {
                return(_azure);
            }

            AzureCredentials credentials;
            string           localDevelopment = Environment.GetEnvironmentVariable("LocalDevelopment", EnvironmentVariableTarget.Process);

            if (!string.IsNullOrEmpty(localDevelopment) &&
                string.Equals(localDevelopment, "true", StringComparison.InvariantCultureIgnoreCase))
            {
                Log.LogDebug($"Get the local service principal for local login");
                var localDevSp = new Principal
                {
                    UserPrincipalName = "LocalLogin",
                    AppId             = Environment.GetEnvironmentVariable("ClientId", EnvironmentVariableTarget.Process),
                    TenantId          = Environment.GetEnvironmentVariable("TenantId", EnvironmentVariableTarget.Process)
                };
                string clientSecret = Environment.GetEnvironmentVariable("ClientSecret", EnvironmentVariableTarget.Process);
                Log.LogDebug($"AppId: {localDevSp.AppId}, TenantId: {localDevSp.TenantId}");

                credentials = SdkContext
                              .AzureCredentialsFactory
                              .FromServicePrincipal(localDevSp.AppId, clientSecret, localDevSp.TenantId, AzureEnvironment.AzureGlobalCloud);
            }
            else
            {
                Log.LogDebug($"Get the MSI credentials");

                // Because MSI isn't really nicely supported in this nuget package disable it for now and user workaround
                ////credentials = SdkContext
                ////     .AzureCredentialsFactory
                ////     .FromMSI(new MSILoginInformation(MSIResourceType.AppService), AzureEnvironment.AzureGlobalCloud);

                try
                {
                    // START workaround until MSI in this package is really supported
                    string tenantId = Environment.GetEnvironmentVariable("TenantId", EnvironmentVariableTarget.Process);
                    Log.LogDebug($"TenantId: {tenantId}");

                    AzureServiceTokenProvider astp = new AzureServiceTokenProvider();
                    string graphToken = await astp.GetAccessTokenAsync("https://graph.windows.net/", tenantId);

                    AzureServiceTokenProvider astp2 = new AzureServiceTokenProvider();
                    string rmToken = await astp2.GetAccessTokenAsync("https://management.azure.com/", tenantId);

                    Log.LogDebug("Logging with tokens from Token Provider");

                    AzureCredentials customTokenProvider = new AzureCredentials(
                        new TokenCredentials(rmToken),
                        new TokenCredentials(graphToken),
                        tenantId,
                        AzureEnvironment.AzureGlobalCloud);

                    RestClient client = RestClient
                                        .Configure()
                                        .WithEnvironment(AzureEnvironment.AzureGlobalCloud)
                                        .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                                        //.WithRetryPolicy(new RetryPolicy(new HttpStatusCodeErrorDetectionStrategy(), new IncrementalRetryStrategy(2, TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(1))))
                                        .WithCredentials(customTokenProvider)
                                        .Build();

                    return(Azure.Authenticate(client, tenantId));
                    // END workaround until MSI in this package is really supported
                }
                catch (Exception ex)
                {
                    Log.LogError(ex, ex.Message);
                    if (ex.InnerException != null)
                    {
                        Log.LogError(ex.InnerException, ex.InnerException.Message);
                    }
                    throw;
                }
            }

            ServiceClientTracing.AddTracingInterceptor(new MicrosoftExtensionsLoggingTracer(Log));
            ServiceClientTracing.IsEnabled = true;

            _azure = Azure
                     .Configure()
                     .WithDelegatingHandler(new HttpLoggingDelegatingHandler())
                     .WithLogLevel(HttpLoggingDelegatingHandler.Level.None)
                     .Authenticate(credentials);

            return(_azure);
        }
Example #22
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            var     subscriptionId = System.Environment.GetEnvironmentVariable("SUBSCRIPTION_ID", EnvironmentVariableTarget.Process);
            string  COUNT          = req.Query["COUNT"];
            string  requestBody    = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data           = JsonConvert.DeserializeObject(requestBody);

            COUNT = COUNT ?? data?.COUNT;

            string  TYPE         = req.Query["TYPE"];
            string  requestBody1 = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data1        = JsonConvert.DeserializeObject(requestBody);

            TYPE = TYPE ?? data?.TYPE;

            int ftdCountInt = Convert.ToInt32(COUNT);
            int index       = 1;

            if ("REGULAR" == TYPE)
            {
                log.LogWarning("GetFtdPublicIp:::: This is regular scale-out ");
            }
            else if ("INIT" == TYPE)
            {
                log.LogWarning("GetFtdPublicIp:::: This is initial deployment");
            }
            else
            {
                return((ActionResult) new BadRequestObjectResult("ERROR: Invalid request TYPE"));
            }
            var resoureGroupName     = System.Environment.GetEnvironmentVariable("RESOURCE_GROUP_NAME", EnvironmentVariableTarget.Process);
            var vmScalesetName       = System.Environment.GetEnvironmentVariable("VMSS_NAME", EnvironmentVariableTarget.Process);
            var networkInterfaceName = System.Environment.GetEnvironmentVariable("MNGT_NET_INTERFACE_NAME", EnvironmentVariableTarget.Process);
            var ipConfigurationName  = System.Environment.GetEnvironmentVariable("MNGT_IP_CONFIG_NAME", EnvironmentVariableTarget.Process);
            var publicIpAddressName  = System.Environment.GetEnvironmentVariable("MNGT_PUBLIC_IP_NAME", EnvironmentVariableTarget.Process);

            log.LogWarning("GetFtdPublicIp:::: Getting Public IP of new FTD (RG : {0}, VMSS: {1} )", resoureGroupName.ToString(), vmScalesetName.ToString());
            log.LogInformation("GetFtdPublicIp:::: Network Interface name : {0}, IP Configuration Name : {1}, Public IP Address Name : {2}", networkInterfaceName, ipConfigurationName, publicIpAddressName);

            var factory = new AzureCredentialsFactory();
            var msiCred = factory.FromMSI(new MSILoginInformation(MSIResourceType.AppService), AzureEnvironment.AzureGlobalCloud);
            var azure   = Azure.Configure().WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic).Authenticate(msiCred).WithSubscription(subscriptionId);

            var NmClient = new NetworkManagementClient(msiCred)
            {
                SubscriptionId = azure.SubscriptionId
            };
            var    interfaceList = NmClient.NetworkInterfaces.ListVirtualMachineScaleSetNetworkInterfaces(resoureGroupName, vmScalesetName);
            string vmindex       = "";
            string tmpVmindex    = "";
            int    intVmindex    = 0;
            var    vmlist        = azure.VirtualMachineScaleSets.GetByResourceGroup(resoureGroupName, vmScalesetName);
            var    vmStatus      = "";
            var    tmpVmName     = "ERROR";

            //ToDo: This logic should be simplified by only using VMSS list, netInterface is not needed
            foreach (var netInterface in interfaceList)
            {
                if (netInterface.IpConfigurations[0].PublicIPAddress != null)
                {
                    var tmpIntfName   = netInterface.IpConfigurations[0].PublicIPAddress.Id.Split('/').GetValue(12);
                    var tmpConfigName = netInterface.IpConfigurations[0].PublicIPAddress.Id.Split('/').GetValue(14);
                    var tmpPubIpName  = netInterface.IpConfigurations[0].PublicIPAddress.Id.Split('/').GetValue(16);

                    if ((tmpIntfName.ToString() == networkInterfaceName) && (tmpConfigName.ToString() == ipConfigurationName) && (tmpPubIpName.ToString() == publicIpAddressName))
                    {
                        vmindex = netInterface.IpConfigurations[0].PublicIPAddress.Id.Split('/').GetValue(10).ToString();
                        //Azure bug: Azure sometimes retains old deleted VMs in its list for very long time, need to avoid those instances
                        vmStatus = "ON";
                        foreach (var vm in vmlist.VirtualMachines.List())
                        {
                            if (vm.InstanceId == vmindex)
                            {
                                if (null == vm.PowerState)
                                {
                                    vmStatus = "OFF";
                                }
                                if (null != vm.Name)
                                {
                                    tmpVmName = vm.Name;
                                }
                                break;
                            }
                        }
                        if ("OFF" == vmStatus)
                        {
                            log.LogError("GetFtdPublicIp:::: VM index :{0} is in unknown state..skip", vmindex);
                            continue;
                        }
                        //Azure bug: some times even deleted VMs are still attahed to network interfaces for very long time
                        if ("ERROR" == tmpVmName)
                        {
                            log.LogError("GetFtdPublicIp:::: VM index :{0} VM name not found...skip", vmindex);
                            continue;
                        }

                        if ("INIT" == TYPE)
                        {
                            if (index == ftdCountInt)
                            {
                                //index >100 is just to safegaurd this loop..its has no other logic
                                break;
                            }
                            index++;
                        }
                        else
                        {
                            //Azure bug: Some time it will mix indexes and does not preserve sequence
                            if (Convert.ToInt32(vmindex) < intVmindex)
                            {
                                log.LogWarning("GetFtdPublicIp:::: Azure index jumbling detected");
                                vmindex = intVmindex.ToString();
                            }
                            else
                            {
                                intVmindex = Convert.ToInt32(vmindex);
                                log.LogInformation("GetFtdPublicIp:::: Assigning vmindex = {0}", vmindex);
                            }
                        }
                    }
                }
            }

            var publicIp = NmClient.PublicIPAddresses.GetVirtualMachineScaleSetPublicIPAddress(resoureGroupName, vmScalesetName, vmindex, networkInterfaceName, ipConfigurationName, publicIpAddressName).IpAddress;

            if (null == publicIp)
            {
                log.LogError("GetFtdPublicIp:::: Unable to get Public IP of new FTD (index {0}", vmindex);
                return((ActionResult) new BadRequestObjectResult("ERROR: Unable to get Public IP of new FTD"));
            }
            log.LogInformation("GetFtdPublicIp:::: Public IP of New FTD (VM index {0}) = {1}", vmindex, publicIp);

            //find VM name from index
            string vmname    = "";
            string privateIp = "";
            var    vmss      = azure.VirtualMachineScaleSets.GetByResourceGroup(resoureGroupName, vmScalesetName);

            foreach (var vm in vmss.VirtualMachines.List())
            {
                if (vm.InstanceId == vmindex)
                {
                    vmname = vm.Name;
                    foreach (var netintf in vm.ListNetworkInterfaces())
                    {
                        privateIp = netintf.PrimaryPrivateIP;
                        break;
                    }
                    break;
                }
            }

            var commandStr = "{ \"ftdDevName\": \"" + vmname + "\", \"ftdPublicIp\": \"" + publicIp + "\", \"ftdPrivateIp\" : \"" + privateIp + "\"  }";

            return((ActionResult) new OkObjectResult(commandStr));
        }
Example #23
0
        public static void Main(string[] args)
        {
            try
            {
                //=================================================================
                // Authenticate
                AzureCredentials credentials = AzureCredentials.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

                var azure = Azure
                            .Configure()
                            .WithLogLevel(HttpLoggingDelegatingHandler.Level.BASIC)
                            .Authenticate(credentials)
                            .WithDefaultSubscription();

                // Print selected subscription
                Console.WriteLine("Selected subscription: " + azure.SubscriptionId);

                try
                {
                    // ===========================================================
                    // Get how many batch accounts can be created in specified region.

                    int allowedNumberOfBatchAccounts = azure.BatchAccounts.GetBatchAccountQuotaByLocation(region);

                    // ===========================================================
                    // List all the batch accounts in subscription.

                    var batchAccounts = azure.BatchAccounts.List();
                    int batchAccountsAtSpecificRegion = batchAccounts.Count(x => x.Region == region);

                    if (batchAccountsAtSpecificRegion >= allowedNumberOfBatchAccounts)
                    {
                        Console.WriteLine("No more batch accounts can be created at "
                                          + region + " region, this region already have "
                                          + batchAccountsAtSpecificRegion
                                          + " batch accounts, current quota to create batch account in "
                                          + region + " region is " + allowedNumberOfBatchAccounts + ".");
                        return;
                    }

                    // ============================================================
                    // Create a batch account

                    Console.WriteLine("Creating a batch Account");

                    var batchAccount = azure.BatchAccounts.Define(batchAccountName)
                                       .WithRegion(region)
                                       .WithNewResourceGroup(rgName)
                                       .DefineNewApplication(applicationName)
                                       .DefineNewApplicationPackage(applicationPackageName)
                                       .WithAllowUpdates(true)
                                       .WithDisplayName(applicationDisplayName)
                                       .Attach()
                                       .WithNewStorageAccount(storageAccountName)
                                       .Create();

                    Console.WriteLine("Created a batch Account:");
                    Utilities.PrintBatchAccount(batchAccount);

                    // ============================================================
                    // Get | regenerate batch account access keys

                    Console.WriteLine("Getting batch account access keys");

                    var batchAccountKeys = batchAccount.GetKeys();

                    Utilities.PrintBatchAccountKey(batchAccountKeys);

                    Console.WriteLine("Regenerating primary batch account primary access key");

                    batchAccountKeys = batchAccount.RegenerateKeys(AccountKeyType.Primary);

                    Utilities.PrintBatchAccountKey(batchAccountKeys);

                    // ============================================================
                    // Regenerate the keys for storage account
                    var storageAccount     = azure.StorageAccounts.GetByGroup(rgName, storageAccountName);
                    var storageAccountKeys = storageAccount.GetKeys();

                    Utilities.PrintStorageAccountKeys(storageAccountKeys);

                    Console.WriteLine("Regenerating first storage account access key");

                    storageAccountKeys = storageAccount.RegenerateKey(storageAccountKeys[0].KeyName);

                    Utilities.PrintStorageAccountKeys(storageAccountKeys);

                    // ============================================================
                    // Synchronize storage account keys with batch account

                    batchAccount.SynchronizeAutoStorageKeys();

                    // ============================================================
                    // Update name of application.
                    batchAccount
                    .Update()
                    .UpdateApplication(applicationName)
                    .WithDisplayName("New application display name")
                    .Parent()
                    .Apply();

                    batchAccount.Refresh();
                    Utilities.PrintBatchAccount(batchAccount);

                    // ============================================================
                    // Create another batch account

                    Console.WriteLine("Creating another Batch Account");

                    allowedNumberOfBatchAccounts = azure.BatchAccounts.GetBatchAccountQuotaByLocation(region2);

                    // ===========================================================
                    // List all the batch accounts in subscription.

                    batchAccounts = azure.BatchAccounts.List();
                    batchAccountsAtSpecificRegion = batchAccounts.Count(x => x.Region == region2);

                    IBatchAccount batchAccount2 = null;
                    if (batchAccountsAtSpecificRegion < allowedNumberOfBatchAccounts)
                    {
                        batchAccount2 = azure.BatchAccounts.Define(batchAccountName2)
                                        .WithRegion(region2)
                                        .WithExistingResourceGroup(rgName)
                                        .WithExistingStorageAccount(storageAccount)
                                        .Create();

                        Console.WriteLine("Created second Batch Account:");
                        Utilities.PrintBatchAccount(batchAccount2);
                    }

                    // ============================================================
                    // List batch accounts

                    Console.WriteLine("Listing Batch accounts");

                    var           accounts = azure.BatchAccounts.ListByGroup(rgName);
                    IBatchAccount ba;
                    foreach (var account in accounts)
                    {
                        Console.WriteLine("Batch Account - " + account.Name);
                    }

                    // ============================================================
                    // Refresh a batch account.
                    batchAccount.Refresh();
                    Utilities.PrintBatchAccount(batchAccount);

                    // ============================================================
                    // Delete a batch account

                    Console.WriteLine("Deleting a batch account - " + batchAccount.Name);

                    foreach (var applicationEntry in batchAccount.Applications)
                    {
                        foreach (var applicationPackageEntry in applicationEntry.Value.ApplicationPackages)
                        {
                            Console.WriteLine("Deleting a application package - " + applicationPackageEntry.Key);
                            applicationPackageEntry.Value.Delete();
                        }
                        Console.WriteLine("Deleting a application - " + applicationEntry.Key);
                        batchAccount.Update().WithoutApplication(applicationEntry.Key).Apply();
                    }

                    try
                    {
                        azure.BatchAccounts.Delete(batchAccount.Id);
                    }
                    catch
                    {
                    }

                    Console.WriteLine("Deleted batch account");

                    if (batchAccount2 != null)
                    {
                        Console.WriteLine("Deleting second batch account - " + batchAccount2.Name);
                        try
                        {
                            azure.BatchAccounts.Delete(batchAccount2.Id);
                        }
                        catch
                        {
                        }

                        Console.WriteLine("Deleted second batch account");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                finally
                {
                    try
                    {
                        Console.WriteLine("Deleting Resource Group: " + rgName);
                        azure.ResourceGroups.Delete(rgName);
                        Console.WriteLine("Deleted Resource Group: " + rgName);
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("Did not create any resources in Azure. No clean up is necessary");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Example #24
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            try
            {
                log.LogInformation("Getting request body params");
                string  requestBody       = await new StreamReader(req.Body).ReadToEndAsync();
                dynamic data              = JsonConvert.DeserializeObject(requestBody);
                string  subscriptionId    = data?.subscriptionId;
                string  resourceGroupName = data?.resourceGroupName;
                bool?   useVmStartAwait   = data?.wait;
                string  vmName            = data?.vmName;

                if (subscriptionId == null || resourceGroupName == null || vmName == null)
                {
                    return(new BadRequestObjectResult("Please pass all 3 required parameters in the request body"));
                }

                if (useVmStartAwait == null)
                {
                    useVmStartAwait = false;
                }

                log.LogInformation("Setting authentication to use MSI");
                AzureCredentialsFactory f = new AzureCredentialsFactory();
                var msi = new MSILoginInformation(MSIResourceType.AppService);

                var msiCred = f.FromMSI(msi, AzureEnvironment.AzureGlobalCloud);

                var azureAuth = Azure.Configure()
                                .WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders)
                                .Authenticate(msiCred);

                log.LogInformation("Authenticating with Azure using MSI");
                var azure = azureAuth.WithSubscription(subscriptionId);

                log.LogInformation("Acquiring VM from Azure");
                var vm = azure.VirtualMachines.GetByResourceGroup(resourceGroupName, vmName);

                log.LogInformation("Checking VM Id");
                log.LogInformation(vm.Id.ToString());

                log.LogInformation("Checking VM Powerstate");
                log.LogInformation("VM Powerstate : " + vm.PowerState.ToString());

                bool vmStarting = false;
                if (vm.PowerState.ToString() == "PowerState/running")
                {
                    log.LogInformation("VM is already running");
                }
                else
                {
                    if (useVmStartAwait.Value)
                    {
                        log.LogInformation("Async Starting vm " + vmName);
                        await vm.StartAsync();
                    }
                    else
                    {
                        log.LogInformation("Sync Starting vm " + vmName);
                        vm.Start();
                    }

                    vmStarting = true;
                }

                return(vmStarting == false
                ? (ActionResult) new OkObjectResult("VM was already started")
                : (ActionResult) new OkObjectResult("VM started"));
            }
            catch (System.Exception ex)
            {
                log.LogError(ex.Message);
                throw;
            }
        }
Example #25
0
        public UserContext(Principal principal)
        {
            this.Principal = principal;

            var loginSettings = new ActiveDirectoryServiceSettings
            {
                AuthenticationEndpoint = Configuration.AuthorizationEndpoint,
                TokenAudience          = new Uri("https://management.core.windows.net/")
            };

            this.ClientCredentials = ApplicationTokenProvider.LoginSilentAsync(
                this.Principal.TenantId,
                new ClientCredential(this.Principal.ClientId, this.Principal.Secret),
                loginSettings).Result;

            this.AzureCredentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(
                this.Principal.ClientId,
                this.Principal.Secret,
                this.Principal.TenantId,
                AzureEnvironment.AzureGlobalCloud);

            this.AzureClient = Azure.Configure().Authenticate(this.AzureCredentials)
                               .WithSubscription(principal.SubscriptionId);
            this.DataShareClient =
                new DataShareManagementClient(Configuration.ArmEndpoint, this.ClientCredentials)
            {
                SubscriptionId = principal.SubscriptionId
            };

            if (string.IsNullOrWhiteSpace(this.Principal.DataShareResourceGroup))
            {
                this.Principal.DataShareResourceGroup = UserContext.GenerateName();
            }

            if (string.IsNullOrWhiteSpace(this.Principal.DataShareAccountName))
            {
                this.Principal.DataShareAccountName = UserContext.GenerateName();
            }

            if (string.IsNullOrWhiteSpace(this.Principal.DataShareShareName))
            {
                this.Principal.DataShareShareName = UserContext.GenerateName();
            }

            if (string.IsNullOrWhiteSpace(this.Principal.DataShareInvitation))
            {
                this.Principal.DataShareInvitation = UserContext.GenerateName();
            }

            if (string.IsNullOrWhiteSpace(this.Principal.DataShareShareSubscriptionName))
            {
                this.Principal.DataShareShareSubscriptionName = UserContext.GenerateName();
            }

            if (string.IsNullOrWhiteSpace(this.Principal.DataShareDataSetName))
            {
                this.Principal.DataShareDataSetName = UserContext.GenerateName();
            }

            if (string.IsNullOrWhiteSpace(this.Principal.DataShareDataSetMappingName))
            {
                this.Principal.DataShareDataSetMappingName = UserContext.GenerateName();
            }
        }
        public static async void Run([TimerTrigger("0 */5 * * * *")] TimerInfo myTimer, ILogger log)
        {
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");

            HttpClient client = new HttpClient();

            /*
             * The Documentation for the Office APIs specifies that each request requires an ID which is just a generated GUID.
             * https://docs.microsoft.com/en-us/Office365/Enterprise/office-365-ip-web-service#common-parameters
             */
            Guid requestId = Guid.NewGuid();

            // Building the URL
            var url = @"https://endpoints.office.com/endpoints/worldwide?clientrequestid=" + requestId;

            // Requesting the API
            var response = await client.GetAsync(url);

            var officeAPIsAsJson = await response.Content.ReadAsStringAsync();

            // Lazy People don't like Objects...
            dynamic officeEndpoints = JsonConvert.DeserializeObject(officeAPIsAsJson);

            #region PreppingStructure
            /// Everything in here is just to create a List of Objects that contain everything we need to make a rule. (IPs, Name, tcp or udp, required)
            var rules = new List <RuleSet>();

            foreach (dynamic endpoint in officeEndpoints)
            {
                string ports = "";
                bool   tcp   = true;
                if (endpoint.tcpPorts != null)
                {
                    ports = endpoint.tcpPorts;
                }
                else
                {
                    ports = endpoint.udpPorts;
                    tcp   = false;
                }


                if (endpoint.ips != null)
                {
                    foreach (string ip in endpoint.ips)
                    {
                        RuleSet rs = new RuleSet
                        {
                            Name      = endpoint.serviceAreaDisplayName,
                            IpRange   = ip,
                            PortRange = ports,
                            IsTCP     = tcp,
                            Required  = endpoint.required
                        };

                        rules.Add(rs);
                        log.LogInformation($"Adding RuleSet for IP Range: {rs.IpRange} - {rs.Name}");
                    }
                }
            }
            #endregion

            //Now Azure
            //The Function need to have a system assigned managed identity.
            //Follow the first step here to create one: https://www.azurecorner.com/using-managed-service-identity-in-azure-functions-to-access-azure-sql-database/
            //Next you need to give a Role Assignment on the target Resources/Resourcegroup to the Function App (I chose "Creator", but other more specialized role might fit better)

            //Getting the credentials for the Managed Service Identity
            var creds = SdkContext.AzureCredentialsFactory.FromSystemAssignedManagedServiceIdentity(Microsoft.Azure.Management.ResourceManager.Fluent.Authentication.MSIResourceType.AppService, AzureEnvironment.AzureGlobalCloud);

            //"Connecting" to Azure.
            var azure = Azure
                        .Configure()
                        .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                        .Authenticate(creds)
                        .WithDefaultSubscription();

            //Getting the existing NSG. If there is only one NSG per Resource Group you could probably also use GetBy..Group..
            var nsg = await azure.NetworkSecurityGroups.GetByIdAsync("/subscriptions/5becef9c-f620-40ef-9b8b-bff338e19893/resourceGroups/berndfunction/providers/Microsoft.Network/networkSecurityGroups/myNSG");

            var    update = nsg.Update();
            int    prio   = 200;
            Random r      = new Random();
            foreach (var rule in rules)
            {
                try
                {
                    var ruleName = rule.Name;
                    ruleName += r.Next();

                    update.DefineRule(ruleName)
                    .AllowInbound()
                    .FromAddress(rule.IpRange)
                    .FromAnyPort()
                    .ToAnyAddress()
                    .ToAnyPort()
                    .WithProtocol(rule.IsTCP ? SecurityRuleProtocol.Tcp : SecurityRuleProtocol.Udp)
                    .WithPriority(prio)
                    .WithDescription($"{rule.Name} is Required: {rule.Required}")
                    .Attach()
                    .DefineRule(ruleName)
                    .AllowOutbound()
                    .FromAnyAddress()
                    .FromAnyPort()
                    .ToAddress(rule.IpRange)
                    .ToAnyPort()
                    .WithProtocol(rule.IsTCP ? SecurityRuleProtocol.Tcp : SecurityRuleProtocol.Udp)
                    .WithPriority(prio)
                    .WithDescription($"{rule.Name} is Required: {rule.Required}")
                    .Attach();

                    log.LogInformation($"NSG Rule defined for: {rule.Name}");
                    prio += 5;
                }
                catch (Exception ex)
                {
                    log.LogInformation($"Exception for: {ex.Message}");
                    throw;
                }
            }

            log.LogInformation($"Applying NSG Rules");
            try
            {
                var result = await update.ApplyAsync();
            }
            catch (Exception ex)
            {
                log.LogInformation($"Exception for: {ex.Message}");
                throw;
            }


            Console.WriteLine("Hello World!");
        }
Example #27
0
        public static void Main(string[] args)
        {
            try
            {
                //=============================================================
                // Authenticate
                AzureCredentials credentials = AzureCredentials.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

                var azure = Azure
                            .Configure()
                            .WithLogLevel(HttpLoggingDelegatingHandler.Level.BASIC)
                            .Authenticate(credentials)
                            .WithDefaultSubscription();

                // Print selected subscription
                Console.WriteLine("Selected subscription: " + azure.SubscriptionId);

                try
                {
                    // Create a resource group [Where all resources gets created]
                    IResourceGroup resourceGroup = azure.ResourceGroups
                                                   .Define(rgName)
                                                   .WithRegion(Region.US_EAST)
                                                   .Create();

                    // Prepare Creatable Network definition [Where all the virtual machines get added to]
                    var creatableNetwork = azure.Networks
                                           .Define(networkName)
                                           .WithRegion(Region.US_EAST)
                                           .WithExistingResourceGroup(resourceGroup)
                                           .WithAddressSpace("172.16.0.0/16");

                    // Prepare Creatable Storage account definition [For storing VMs disk]
                    var creatableStorageAccount = azure.StorageAccounts
                                                  .Define(storageAccountName)
                                                  .WithRegion(Region.US_EAST)
                                                  .WithExistingResourceGroup(resourceGroup);

                    // Prepare a batch of Creatable Virtual Machines definitions
                    List <ICreatable <IVirtualMachine> > creatableVirtualMachines = new List <ICreatable <IVirtualMachine> >();

                    for (int i = 0; i < vmCount; i++)
                    {
                        var creatableVirtualMachine = azure.VirtualMachines
                                                      .Define("VM-" + i)
                                                      .WithRegion(Region.US_EAST)
                                                      .WithExistingResourceGroup(resourceGroup)
                                                      .WithNewPrimaryNetwork(creatableNetwork)
                                                      .WithPrimaryPrivateIpAddressDynamic()
                                                      .WithoutPrimaryPublicIpAddress()
                                                      .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
                                                      .WithRootUserName("tirekicker")
                                                      .WithPassword("12NewPA$$w0rd!")
                                                      .WithSize(VirtualMachineSizeTypes.StandardD3V2)
                                                      .WithNewStorageAccount(creatableStorageAccount);
                        creatableVirtualMachines.Add(creatableVirtualMachine);
                    }

                    var startTime = DateTimeOffset.Now.UtcDateTime;
                    Console.WriteLine("Creating the virtual machines");

                    Console.WriteLine("Created virtual machines");

                    var virtualMachines = azure.VirtualMachines.Create(creatableVirtualMachines.ToArray());

                    foreach (var virtualMachine in virtualMachines)
                    {
                        Console.WriteLine(virtualMachine.Id);
                    }

                    var endTime = DateTimeOffset.Now.UtcDateTime;

                    Console.WriteLine($"Created VM: took {(endTime - startTime).TotalSeconds} seconds");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                finally
                {
                    Console.WriteLine($"Deleting resource group : {rgName}");
                    azure.ResourceGroups.Delete(rgName);
                    Console.WriteLine($"Deleted resource group : {rgName}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Example #28
0
  { static void Main(string[] args)
    {
        Console.WriteLine("Starting Deployment");
        // Get Azure credentials
        var credentials = SdkContext.AzureCredentialsFactory
                          .FromFile("./azureauth.properties");

        // Authenticate to Azure
        var azure = Azure
                    .Configure()
                    .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                    .Authenticate(credentials)
                    .WithDefaultSubscription();


        //create required variables
        var groupName     = "az204-ResourceGroup2";
        var vmName        = "WinVM";
        var location      = Region.USEast;
        var vNetName      = "az204VNET";
        var vNetAddress   = "10.10.0.0/16";
        var subnetName    = "az204Subnet";
        var subnetAddress = "10.10.0.0/24";
        var nicName       = "az204NIC";
        var adminUser     = "******";
        var adminPassword = "******";

        Console.WriteLine($"It is time to create the resource group {groupName} ...");
        var resourceGroup = azure.ResourceGroups.Define(groupName)
                            .WithRegion(location)
                            .Create();

        Console.WriteLine($"It is time to create the virtual network {vNetName} ...");
        var network = azure.Networks.Define(vNetName)
                      .WithRegion(location)
                      .WithExistingResourceGroup(groupName)
                      .WithAddressSpace(vNetAddress)
                      .WithSubnet(subnetName, subnetAddress)
                      .Create();


        Console.WriteLine($"It is time to creating network interface {nicName} ...");
        var nic = azure.NetworkInterfaces.Define(nicName)
                  .WithRegion(location)
                  .WithExistingResourceGroup(groupName)
                  .WithExistingPrimaryNetwork(network)
                  .WithSubnet(subnetName)
                  .WithPrimaryPrivateIPAddressDynamic()
                  .Create();

        Console.WriteLine($"Creating virtual machine {vmName} ...");
        azure.VirtualMachines.Define(vmName)
        .WithRegion(location)
        .WithExistingResourceGroup(groupName)
        .WithExistingPrimaryNetworkInterface(nic)
        .WithLatestWindowsImage("MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter")
        .WithAdminUsername(adminUser)
        .WithAdminPassword(adminPassword)
        .WithComputerName(vmName)
        .WithSize(VirtualMachineSizeTypes.StandardDS2V2)
        .Create();
    }
        public static async Task Main(string[] args)
        {
            IConfigurationBuilder builder       = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddUserSecrets <ManagementExample>();
            IConfigurationRoot    configuration = builder.Build();
            IConfigurationSection c             = configuration.GetSection("ManagementExample");
            IConfigurationSection clientId      = c.GetSection("ClientId");
            IConfigurationSection clientSecret  = c.GetSection("ClientSecret");
            IConfigurationSection tenantId      = c.GetSection("TenantId");

            AzureCredentials credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId.Value, clientSecret.Value, tenantId.Value, AzureEnvironment.AzureGlobalCloud);
            IAzure           azure       = Azure
                                           .Configure()
                                           .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                                           .Authenticate(credentials)
                                           .WithDefaultSubscription();

            string rgName = SdkContext.RandomResourceName("test_", 4);

            try
            {
                // List resource groups
                Console.WriteLine("Resource Groups:");
                IPagedCollection <IResourceGroup> rgs = await azure.ResourceGroups.ListAsync();

                if (rgs.Any())
                {
                    foreach (IResourceGroup l in rgs)
                    {
                        Console.WriteLine($"-- {l.Name}");
                    }
                }
                else
                {
                    Console.WriteLine("-- No Resource Groups");
                }


                // Create resource group
                await azure.ResourceGroups
                .Define(rgName)
                .WithRegion(Region.USWest)
                .CreateAsync();

                Console.WriteLine($"Created Resource Group: {rgName}");


                // Create storage account.
                string saName = SdkContext.RandomResourceName("test", 4);
                await azure.StorageAccounts
                .Define(saName)
                .WithRegion(Region.USWest)
                .WithExistingResourceGroup(rgName)
                .CreateAsync();

                Console.WriteLine($"Created Storage Account: {saName}");

                Console.WriteLine();
                Console.WriteLine("Press any key to delete all resource groups...");
                Console.ReadLine();
            }
            catch (Exception exception)
            {
                Console.WriteLine($"Exception: {exception.Message}");
            }
            finally
            {
                try
                {
                    // Delete all resource groups
                    Console.WriteLine($"Deleting Resource Groups:");
                    foreach (IResourceGroup l in await azure.ResourceGroups.ListAsync())
                    {
                        await azure.ResourceGroups.DeleteByNameAsync(l.Name);

                        Console.WriteLine($"-- {rgName} DELETED");
                    }
                }
                catch (Exception exception)
                {
                    Console.WriteLine($"Exception: {exception.Message}");
                }
            }

            Console.ReadLine();
        }
Example #30
0
        public static void Main(string[] args)
        {
            try
            {
                //=================================================================
                // Authenticate
                AzureCredentials credentials = AzureCredentials.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

                var azure = Azure
                            .Configure()
                            .WithLogLevel(HttpLoggingDelegatingHandler.Level.BASIC)
                            .Authenticate(credentials)
                            .WithDefaultSubscription();

                //=================================================================
                // List all virtual machine image publishers and
                // list all virtual machine images
                // published by Canonical, Red Hat and SUSE
                // by browsing through locations, publishers, offers, SKUs and images

                var publishers = azure
                                 .VirtualMachineImages
                                 .Publishers
                                 .ListByRegion(Region.US_EAST);

                Console.WriteLine("US East data center: printing list of \n"
                                  + "a) Publishers and\n"
                                  + "b) Images published by Canonical, Red Hat and Suse");
                Console.WriteLine("=======================================================");
                Console.WriteLine("\n");

                foreach (var publisher in publishers)
                {
                    Console.WriteLine("Publisher - " + publisher.Name);

                    if (StringComparer.OrdinalIgnoreCase.Equals(publisher.Name, "Canonical") ||
                        StringComparer.OrdinalIgnoreCase.Equals(publisher.Name, "Suse") ||
                        StringComparer.OrdinalIgnoreCase.Equals(publisher.Name, "RedHat"))
                    {
                        Console.WriteLine("\n\n");
                        Console.WriteLine("=======================================================");
                        Console.WriteLine("Located " + publisher.Name);
                        Console.WriteLine("=======================================================");
                        Console.WriteLine("Printing entries as publisher/offer/sku/image/version");

                        foreach (var offer in publisher.Offers.List())
                        {
                            foreach (var sku in offer.Skus.List())
                            {
                                foreach (var image in sku.Images.List())
                                {
                                    Console.WriteLine($"Image - {publisher.Name}/{offer.Name}/{sku.Name}/{image.Version}");
                                }
                            }
                        }

                        Console.WriteLine("\n\n");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }