public async Task RunActivity(
            [ActivityTrigger] AzureResourceGroup azureResourceGroup,
            ILogger log)
        {
            if (azureResourceGroup == null)
            {
                throw new ArgumentNullException(nameof(azureResourceGroup));
            }

            try
            {
                await CleanupResourceGroupAsync(azureResourceGroup)
                .ConfigureAwait(false);

                await DeleteResourceGroupAsync(azureResourceGroup)
                .ConfigureAwait(false);
            }
            catch (CloudException ex) when(ex.Body.Code.Equals("ResourceGroupNotFound", StringComparison.InvariantCultureIgnoreCase))
            {
                log.LogInformation($"Resource group '{azureResourceGroup.ResourceGroupName}' was not found in Azure, so nothing to delete.");
            }
            catch (Exception ex)
            {
                log.LogError(ex, $"Failed to delete resource group '{azureResourceGroup.ResourceGroupName}' in Azure.");
                throw;
            }
        }
Example #2
0
        private static void CleanUp()
        {
            Console.WriteLine($"--------Deleting {rgName}--------");
            AzureResourceGroup rg = AzureClient.GetResourceGroup(subscriptionId, rgName);

            rg.Delete();
        }
Example #3
0
        public static List <AzureResourceGroup> GetResourceGroups(SubscriptionCloudCredentials credentials)
        {
            var result = new List <AzureResourceGroup>();

            ResourceManagementClient client = new ResourceManagementClient(credentials);

            var resourceGroupParams = new ResourceGroupListParameters();

            var groupResult = client.ResourceGroups.List(resourceGroupParams);

            foreach (var resourceGroup in groupResult.ResourceGroups)
            {
                var azureResourceGroup = new AzureResourceGroup(resourceGroup);

                var resourceParams = new ResourceListParameters();
                resourceParams.ResourceGroupName = resourceGroup.Name;

                var resourceResult = client.Resources.List(resourceParams);

                foreach (var resource in resourceResult.Resources)
                {
                    azureResourceGroup.Resources.Add(new Models.AzureResource(resource, credentials.SubscriptionId, resourceGroup.Name));
                }

                result.Add(azureResourceGroup);
            }

            return(result);
        }
Example #4
0
        private static void SetupVmHost(out AzureResourceGroup resourceGroup, out AzureAvailabilitySet aset, out AzureSubnet subnet)
        {
            AzureClient client       = new AzureClient();
            var         subscription = client.Subscriptions[subscriptionId];

            // Create Resource Group
            Console.WriteLine("--------Start create group--------");
            resourceGroup = subscription.ResourceGroups.CreateOrUpdate(rgName, loc);

            // Create AvailabilitySet
            Console.WriteLine("--------Start create AvailabilitySet--------");
            aset = resourceGroup.ConstructAvailabilitySet("Aligned");
            aset = resourceGroup.AvailabilitySets().CreateOrUpdateAvailabilityset(vmName + "_aSet", aset);

            // Create VNet
            Console.WriteLine("--------Start create VNet--------");
            string    vnetName = vmName + "_vnet";
            AzureVnet vnet;

            if (!resourceGroup.VNets().TryGetValue(vnetName, out vnet))
            {
                vnet = resourceGroup.ConstructVnet("10.0.0.0/16");
                vnet = resourceGroup.VNets().CreateOrUpdateVNet(vnetName, vnet);
            }

            //create subnet
            Console.WriteLine("--------Start create Subnet--------");
            if (!vnet.Subnets.TryGetValue(subnetName, out subnet))
            {
                var nsg = resourceGroup.ConstructNsg(nsgName, 80);
                nsg    = resourceGroup.Nsgs().CreateOrUpdateNsgs(nsg);
                subnet = vnet.ConstructSubnet(subnetName, "10.0.0.0/24");
                subnet = vnet.Subnets.CreateOrUpdateSubnets(subnet);
            }
        }
Example #5
0
        private static void SetTagsOnVm()
        {
            //make sure vm exists
            CreateSingleVmExample();

            AzureResourceGroup rg = AzureClient.GetResourceGroup(subscriptionId, rgName);
            AzureVm            vm = rg.Vms()[vmName];

            vm.AddTag("tagkey", "tagvalue");
        }
        private async Task CleanupResourceGroupAsync(AzureResourceGroup azureResourceGroup)
        {
            var template = new CleanupProjectTemplate();

            var deployment = await azureDeploymentService
                             .DeployResourceGroupTemplateAsync(template, azureResourceGroup.SubscriptionId, azureResourceGroup.ResourceGroupName, completeMode : true)
                             .ConfigureAwait(false);

            _ = await deployment
                .WaitAsync(throwOnError : true)
                .ConfigureAwait(false);
        }
        public async Task CreateResourceGroupIfNotExistsAsync(AzureResourceGroup resourceGroup)
        {
            log.LogInformation("Starting creation of resource group of {0}", resourceGroup.Name);

            var azure = GetAzureClient();
            var resourceGroupExists = await azure.ResourceGroups.ContainAsync(resourceGroup.Name);

            if (!resourceGroupExists)
            {
                await azure.ResourceGroups.Define(resourceGroup.Name).WithRegion(resourceGroup.Region).CreateAsync();
            }
        }
Example #8
0
        private static AzureNic CreateNic(AzureResourceGroup resourceGroup, AzureSubnet subnet, int i)
        {
            // Create IP Address
            Console.WriteLine("--------Start create IP Address--------");
            var ipAddress = resourceGroup.ConstructIPAddress();

            ipAddress = resourceGroup.IpAddresses().CreateOrUpdatePublicIpAddress(String.Format("{0}_{1}_ip", vmName, i), ipAddress);

            // Create Network Interface
            Console.WriteLine("--------Start create Network Interface--------");
            var nic = resourceGroup.ConstructNic(ipAddress, subnet.Id);

            nic = resourceGroup.Nics().CreateOrUpdateNic(String.Format("{0}_{1}_nic", vmName, i), nic);
            return(nic);
        }
Example #9
0
        private static void StartFromVm()
        {
            // TODO: Look at VM nic/nsg operations on VM
            //make sure vm exists
            CreateSingleVmExample();

            //retrieve from lowest level, doesn't give ability to walk up and down the container structure
            AzureVm vm = VmCollection.GetVm(subscriptionId, rgName, vmName);

            Console.WriteLine("Found VM {0}", vm.Id);


            //retrieve from lowest level inside management package gives ability to walk up and down
            AzureResourceGroup rg  = AzureClient.GetResourceGroup(subscriptionId, rgName);
            AzureVm            vm2 = rg.Vms()[vmName];

            Console.WriteLine("Found VM {0}", vm2.Id);
        }
        private static IList <AzureSubScription> GetSubScriptionsWithResouceGroup(AzureCredentials creds)
        {
            IList <AzureSubScription> azureSubScriptions = new List <AzureSubScription>();

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

            var subscriptions = azure.Subscriptions.List();

            foreach (var subscription in subscriptions)
            {
                AzureSubScription azureSubScription = new AzureSubScription
                {
                    SubScriptionID   = subscription.SubscriptionId,
                    SubScriptionName = subscription.DisplayName
                };
                var azureWithSubscription = azure.WithSubscription(azureSubScription.SubScriptionID);

                IList <AzureResourceGroup> azureResourceGroups = new List <AzureResourceGroup>();
                var resourceGroups = azureWithSubscription.ResourceGroups.List();
                foreach (var group in resourceGroups)
                {
                    var tags        = group.Tags;
                    var projectName = azureSubScription.SubScriptionName;
                    if (tags != null && tags.ContainsKey("ProjectName"))
                    {
                        tags.TryGetValue("ProjectName", out projectName);
                    }
                    AzureResourceGroup azureResourceGroup = new AzureResourceGroup
                    {
                        Name        = group.Name,
                        ProjectName = projectName
                    };
                    azureResourceGroups.Add(azureResourceGroup);
                }
                azureSubScription.ResourceGroups = azureResourceGroups;
                azureSubScriptions.Add(azureSubScription);
            }

            return(azureSubScriptions);
        }
Example #11
0
        private static void CreateMultipleVmShutdownSome()
        {
            AzureResourceGroup resourceGroup = CreateMultipleVms();

            resourceGroup.Vms().Select(vm =>
            {
                var parts = vm.Name.Split('-');
                var n     = Convert.ToInt32(parts[parts.Length - 2]);
                return(vm, n);
            })
            .Where(tuple => tuple.n % 2 == 0)
            .ToList()
            .ForEach(tuple =>
            {
                Console.WriteLine("Stopping {0}", tuple.vm.Name);
                tuple.vm.Stop();
                Console.WriteLine("Starting {0}", tuple.vm.Name);
                tuple.vm.Start();
            });
        }
        private async Task DeleteResourceGroupAsync(AzureResourceGroup azureResourceGroup)
        {
            var session = azureSessionService.CreateSession(azureResourceGroup.SubscriptionId);

            var mgmtLocks = await GetManagementLocksAsync()
                            .ConfigureAwait(false);

            if (mgmtLocks.Any())
            {
                await session.ManagementLocks
                .DeleteByIdsAsync(mgmtLocks.ToArray())
                .ConfigureAwait(false);

                var timeoutDuration = TimeSpan.FromMinutes(5);
                var timeout         = DateTime.UtcNow.Add(timeoutDuration);

                while (DateTime.UtcNow < timeout && mgmtLocks.Any())
                {
                    await Task.Delay(5000).ConfigureAwait(false);

                    mgmtLocks = await GetManagementLocksAsync()
                                .ConfigureAwait(false);
                }
            }

            await session.ResourceGroups
            .DeleteByNameAsync(azureResourceGroup.ResourceGroupName)
            .ConfigureAwait(false);

            async Task <IEnumerable <string> > GetManagementLocksAsync()
            {
                var locks = await session.ManagementLocks
                            .ListByResourceGroupAsync(azureResourceGroup.ResourceGroupName, loadAllPages : true)
                            .ConfigureAwait(false);

                return(locks.Select(lck => lck.Id));
            }
        }
Example #13
0
        public async Task <string> RunActivity(
            [ActivityTrigger] AzureResourceGroup azureResourceGroup)
        {
            if (azureResourceGroup == null)
            {
                throw new ArgumentNullException(nameof(azureResourceGroup));
            }
            if (string.IsNullOrWhiteSpace(azureResourceGroup.ResourceGroupName))
            {
                throw new ArgumentNullException(nameof(azureResourceGroup.ResourceGroupName));
            }
            if (azureResourceGroup.Region == null)
            {
                throw new ArgumentNullException(nameof(azureResourceGroup.Region));
            }

            var azureSession = azureSessionFactory.CreateSession(Guid.Parse(azureResourceGroup.SubscriptionId));

            if (await azureSession.ResourceGroups.ContainAsync(azureResourceGroup.ResourceGroupName).ConfigureAwait(false) == false)
            {
                var newGroup = await azureSession.ResourceGroups
                               .Define(azureResourceGroup.ResourceGroupName)
                               .WithRegion(azureResourceGroup.Region)
                               .CreateAsync()
                               .ConfigureAwait(false);

                return(newGroup.Id);
            }
            else
            {
                var existingGroup = await azureSession.ResourceGroups
                                    .GetByNameAsync(azureResourceGroup.ResourceGroupName)
                                    .ConfigureAwait(false);

                return(existingGroup.Id);
            }
        }
Example #14
0
        //*********************************************************************
        ///
        ///  <summary>
        ///
        ///  </summary>
        ///  <param name="arg"></param>
        ///  <param name="spa"></param>
        ///  <param name="aRGs"></param>
        /// <param name="hso"></param>
        ///
        //*********************************************************************
        private void ProcessFoundRg(AzureResourceGroup arg, Models.ServiceProviderAccount spa,
                                    IEnumerable <AzureResourceGroup> aRGs, HostedServiceOps hso)
        {
            //*** Look for RG in list of aRGs, leave if found
            if (aRGs.Any(vdr => vdr.Name.Equals(arg.Name,
                                                StringComparison.InvariantCultureIgnoreCase)))
            {
                return;
            }

            //var rg = hso.GetResourceGroup(arg.Name);

            //*** RG not found, so add to RG DB table
            var utcNow = DateTime.UtcNow;

            var vdb = new Models.Container()
            {
                //ID = 0,
                Name           = arg.Name,
                Region         = arg.Location,
                SubscriptionId = spa.AccountID,
                CIOwner        = "",
                Code           = "",
                Config         = "",
                CreatedBy      = "",
                CreatedOn      = utcNow,
                HasService     = false,
                IsActive       = true,
                LastUpdatedBy  = "",
                LastUpdatedOn  =
                    utcNow,
                Path = arg.Id,
                Type = CmpInterfaceModel.Constants.ContainerTypeEnum.ResourceGroup.ToString()
            };

            _cdb.InsertAzureContainer(vdb);
        }
Example #15
0
        public static async Task RunOrchestration(
            [OrchestrationTrigger] IDurableOrchestrationContext functionContext,
            ILogger log)
        {
            (OrchestratorContext orchestratorContext, ProjectCreateCommand command) = functionContext.GetInput <(OrchestratorContext, ProjectCreateCommand)>();

            var user      = command.User;
            var project   = command.Payload;
            var teamCloud = orchestratorContext.TeamCloud;

            functionContext.SetCustomStatus("Creating Project...");

            project.TeamCloudId = teamCloud.Id;
            project.TeamCloudApplicationInsightsKey = teamCloud.ApplicationInsightsKey;
            project.ProviderVariables = teamCloud.Configuration.Providers.Select(p => (p.Id, p.Variables)).ToDictionary(t => t.Id, t => t.Variables);

            // Add project to db and add new project to teamcloud in db
            project = await functionContext.CallActivityAsync <Project>(nameof(ProjectCreateActivity), project);

            // TODO: Create identity (service principal) for Project

            var projectIdentity = new AzureIdentity
            {
                Id     = Guid.NewGuid(),
                AppId  = "",
                Secret = ""
            };

            project = await functionContext.CallActivityAsync <Project>(nameof(ProjectUpdateActivity), project);

            var resourceGroup = new AzureResourceGroup
            {
                SubscriptionId    = teamCloud.Configuration.Azure.SubscriptionId,
                ResourceGroupName = $"{teamCloud.Configuration.Azure.ResourceGroupNamePrefix}{project.Name}", // TODO validate/clean
                Region            = teamCloud.Configuration.Azure.Region
            };

            // Create new resource group for project
            resourceGroup.Id = await functionContext.CallActivityAsync <Guid>(nameof(AzureResourceGroupCreateActivity), project);

            // Assign resource group to project
            project.ResourceGroup = resourceGroup;

            project = await functionContext.CallActivityAsync <Project>(nameof(ProjectUpdateActivity), project);

            var projectContext = new ProjectContext(teamCloud, project, command.User);

            functionContext.SetCustomStatus("Creating Project Resources...");

            // TODO: call create on all providers (handeling dependencies)
            // var tasks = teamCloud.Configuration.Providers.Select(p =>
            //                 functionContext.CallHttpAsync(HttpMethod.Post, p.Location, JsonConvert.SerializeObject(projectContext)));

            // await Task.WhenAll(tasks);

            functionContext.SetCustomStatus("Initializing Project Resources...");

            // TODO: call init on all providers (handeling dependencies)
            // var tasks = teamCloud.Configuration.Providers.Select(p =>
            //                 functionContext.CallHttpAsync(HttpMethod.Post, p.Location, JsonConvert.SerializeObject(projectContext)));

            // await Task.WhenAll(tasks);

            functionContext.SetOutput(project);

            //return true;
        }