Ejemplo n.º 1
0
        public HttpResponseMessage Get(String hostName)
        {
            List <String> subList = new List <string>();

            Subscriptions subscriptions = ListSubscriptions.GetSubscriptions();

            foreach (var sub in subscriptions.value)
            {
                if (sub.id.Contains(SubscriptionFilter))
                {
                    subList.Add(sub.subscriptionId);
                }
            }

            String accessToken = "";

            accessToken = Adal.AccessToken();
            string authToken = "Bearer" + " " + accessToken;
            var    client    = new WebClient();

            client.Headers.Add("Authorization", authToken);
            client.Headers.Add("Content-Type", "application/json");
            ComputeVms masterComputeVmsList = new ComputeVms();

            masterComputeVmsList.value = new List <ComputeVm>();

            foreach (var subId in subList)
            {
                Uri    resourceGroupsUri = new Uri(String.Format("https://management.azure.com/subscriptions/{0}/providers/Microsoft.Compute/virtualmachines?api-version=2015-05-01-preview", subId));
                String text = "";
                text = client.DownloadString(resourceGroupsUri);
                ComputeVms computeVmsList = JsonConvert.DeserializeObject <ComputeVms>(text);
                foreach (var vm in computeVmsList.value)
                {
                    masterComputeVmsList.value.Add(vm);
                }
            }

            foreach (var vm in masterComputeVmsList.value)
            {
                ResourceGroup thisRg = ComputeResources.GetHostResourceGroup(accessToken, vm);
                if ((vm.tags != null) && (vm.tags.ContainsKey("AnsibleDomainSuffix")))
                {
                    vm.name = vm.name + "." + vm.tags["AnsibleDomainSuffix"];
                }
                else if ((thisRg.tags != null) && (thisRg.tags.ContainsKey("AnsibleDomainSuffix")))
                {
                    vm.name = vm.name + "." + thisRg.tags["AnsibleDomainSuffix"];
                }
            }

            ComputeVm thisComputeVm = masterComputeVmsList.value.Where(t => t.name.ToLower() == hostName.ToLower()).FirstOrDefault();

            if (thisComputeVm == null)
            {
                var response = this.Request.CreateResponse(HttpStatusCode.NotFound);
                return(response);
            }
            else
            {
                Dictionary <String, String> TagsDict = new Dictionary <String, String>();

                if (thisComputeVm.tags != null)
                {
                    foreach (var tag in thisComputeVm.tags.Where(t => t.Key.ToLower().StartsWith("ansible__")))
                    {
                        TagsDict.Add((tag.Key.ToLower().Replace("ansible__", "")), tag.Value);
                    }
                }


                String json     = JsonConvert.SerializeObject(TagsDict);
                var    response = this.Request.CreateResponse(HttpStatusCode.OK);
                response.Content = new StringContent(json, Encoding.UTF8, "application/json");
                return(response);
            }
        }
Ejemplo n.º 2
0
        public static Dictionary <String, Object> GetHosts(String accessToken, String subscriptionId = null)
        {
            //get the subs
            List <String> subList = new List <string>();

            if (subscriptionId != null)
            {
                subList.Add(subscriptionId);
            }
            else
            {
                Subscriptions subscriptions = ListSubscriptions.GetSubscriptions();
                foreach (var sub in subscriptions.value)
                {
                    if (sub.id.Contains(SubscriptionFilter))
                    {
                        subList.Add(sub.subscriptionId);
                    }
                }
            }

            var ansibleHostList     = new Dictionary <String, Object>();
            var ansibleHostVarsList = new Dictionary <String, Object>();


            accessToken = Adal.AccessToken();
            string authToken = "Bearer" + " " + accessToken;
            var    client    = new WebClient();

            client.Headers.Add("Authorization", authToken);
            client.Headers.Add("Content-Type", "application/json");

            foreach (var subId in subList)
            {
                Uri    resourceGroupsUri = new Uri(String.Format("https://management.azure.com/subscriptions/{0}/resourcegroups?api-version=2015-01-01", subId));
                String text = "";


                text = client.DownloadString(resourceGroupsUri);
                ResourceGroups       rgList = Newtonsoft.Json.JsonConvert.DeserializeObject <ResourceGroups>(text);
                List <ResourceGroup> filteredResourceGroups = new List <ResourceGroup>();
                foreach (var rg in rgList.value)
                {
                    if (ResourceGroupFilter == "*")
                    {
                        filteredResourceGroups.Add(rg);
                    }
                    else if (rg.name.ToLower().Contains(ResourceGroupFilter.ToLower()))
                    {
                        filteredResourceGroups.Add(rg);
                    }
                }


                foreach (ResourceGroup rg in filteredResourceGroups)
                {
                    //get each host
                    String rgId   = rg.id;
                    String rgName = rg.name;

                    //remove Prod/Test/Dev from rg name
                    if (RemoveStageFromRgName)
                    {
                        if (rgName.ToLower().StartsWith("prod."))
                        {
                            rgName = rgName.Remove(0, 5);
                        }
                        else if (rgName.ToLower().StartsWith("test."))
                        {
                            rgName = rgName.Remove(0, 5);
                        }
                        else if (rgName.ToLower().StartsWith("dev."))
                        {
                            rgName = rgName.Remove(0, 4);
                        }

                        else if (rgName.ToLower().StartsWith("uat."))
                        {
                            rgName = rgName.Remove(0, 4);
                        }
                    }


                    if (ResourceGroupCasing != "")
                    {
                        if (ResourceGroupCasing.ToLower() == "lowercase")
                        {
                            rgName = rgName.ToLower();
                        }
                    }



                    String     rgComputeUrl = String.Format("https://management.azure.com{0}/providers/Microsoft.Compute/virtualmachines?api-version=2015-05-01-preview", rgId);
                    String     rgVmsText    = client.DownloadString(rgComputeUrl);
                    ComputeVms rgCompVms    = JsonConvert.DeserializeObject <ComputeVms>(rgVmsText);
                    if (rgCompVms.value.Count != 0)
                    {
                        //resource group has vms. Fill the thing
                        List <Object> hostList = new List <Object>();
                        foreach (var vm in rgCompVms.value)
                        {
                            var  tagDict           = new Dictionary <String, Object>();
                            bool VerifyPoweredOnVM = true;
                            if (ReturnOnlyPoweredOnVms.ToLower() == "true")
                            {
                                VerifyPoweredOnVM = GetVmPowerStatus(accessToken, vm);
                            }

                            var simplifiedNic = GetNicDetails(accessToken, vm);
                            vm.simplifiedNicDetails = simplifiedNic;


                            if (HostCasingSetting == "UpperCase")
                            {
                                vm.name = vm.name.ToUpper();
                            }

                            if (HostCasingSetting == "LowerCase")
                            {
                                vm.name = vm.name.ToLower();
                            }

                            string vmname = vm.name;



                            if ((vm.tags != null) && (vm.tags.ContainsKey("AnsibleDomainSuffix")))
                            {
                                vmname = vm.name + "." + vm.tags["AnsibleDomainSuffix"];
                            }
                            else if ((rg.tags != null) && (rg.tags.ContainsKey("AnsibleDomainSuffix")))
                            {
                                vmname = vm.name + "." + rg.tags["AnsibleDomainSuffix"];
                            }
                            String ansibleReturnType = null;
                            if ((vm.tags != null) && (vm.tags.ContainsKey("AnsibleReturn")))
                            {
                                ansibleReturnType = vm.tags["AnsibleReturn"];
                            }
                            else if ((rg.tags != null) && (rg.tags.ContainsKey("AnsibleReturn")))
                            {
                                ansibleReturnType = rg.tags["AnsibleReturn"];
                            }

                            //add location thing if specified
                            if (LocationTag != "" && LocationTagName != "")
                            {
                                String Location = LocationTag.Replace("%location%", vm.location);
                                tagDict.Add(LocationTagName, Location);
                            }

                            //If ansiblereturn is set, figure out what to return
                            if (ansibleReturnType != null)
                            {
                                if ((ansibleReturnType.ToLower() == "privateipaddress") && (vm.simplifiedNicDetails.InternalIpAddress != null))
                                {
                                    vmname = vm.simplifiedNicDetails.InternalIpAddress;
                                }
                                else if ((ansibleReturnType.ToLower() == "publicipaddress") && (vm.simplifiedNicDetails.PublicIpAddress != null))
                                {
                                    vmname = vm.simplifiedNicDetails.PublicIpAddress;
                                }
                                else if ((ansibleReturnType.ToLower() == "publichostname") && (vm.simplifiedNicDetails.PublicHostName != null))
                                {
                                    vmname = vm.simplifiedNicDetails.PublicHostName;
                                }
                                else if ((ansibleReturnType.ToLower() == "privateipaddress_asansiblehost") && (vm.simplifiedNicDetails.InternalIpAddress != null))
                                {
                                    tagDict.Add("ansible_host", vm.simplifiedNicDetails.InternalIpAddress);
                                }
                                else if ((ansibleReturnType.ToLower() == "publicipaddress_asansiblehost") && (vm.simplifiedNicDetails.PublicIpAddress != null))
                                {
                                    tagDict.Add("ansible_host", vmname = vm.simplifiedNicDetails.PublicIpAddress);
                                }
                                else if ((ansibleReturnType.ToLower() == "publichostname_asansiblehost") && (vm.simplifiedNicDetails.PublicHostName != null))
                                {
                                    tagDict.Add("ansible_host", vmname = vmname = vm.simplifiedNicDetails.PublicHostName);
                                }
                            }

                            //vmname is now either computername, computername+domain, one ip address or public fqdn


                            if (VerifyPoweredOnVM == true)
                            {
                                hostList.Add(vmname);
                                //check if we have hostsvars to add to meta
                                if ((vm.tags != null) && (vm.tags.Where(t => t.Key.ToLower().StartsWith("ansible__")).Count() > 0))
                                {
                                    foreach (var tag in vm.tags.Where(t => t.Key.ToLower().StartsWith("ansible__")))
                                    {
                                        tagDict.Add(tag.Key.ToLower().Replace("ansible__", ""), tag.Value);
                                    }
                                }
                            }

                            if (tagDict.Count > 0)
                            {
                                //add tags if any
                                ansibleHostVarsList.Add(vmname, tagDict);
                            }
                        }
                        //Add the rg to the main obj
                        var rgValueList = new Dictionary <String, Object>();
                        rgValueList.Add("hosts", hostList);

                        //add vars to the main object if they exists
                        if ((rg.tags != null) && (rg.tags.Where(t => t.Key.ToLower().StartsWith("ansible__")).Count() > 0))
                        {
                            var tagDict = new Dictionary <String, Object>();
                            foreach (var tag in rg.tags.Where(t => t.Key.ToLower().StartsWith("ansible__")))
                            {
                                tagDict.Add(tag.Key.ToLower().Replace("ansible__", ""), tag.Value);
                            }
                            rgValueList.Add("vars", tagDict);
                        }


                        ansibleHostList.Add(rgName, rgValueList);
                    }
                }
            }

            //Add the _meta thing to the result output
            var metaDict = new Dictionary <String, Object>();

            metaDict.Add("hostvars", ansibleHostVarsList);
            ansibleHostList.Add("_meta", metaDict);
            return(ansibleHostList);
        }