Beispiel #1
0
        public async Task <IEnumerable <AzureResource> > GetResourcesAsync(string subscriptionId)
        {
            var az = Initialize(subscriptionId);

            var arm = az.WebApps.Manager.ResourceManager.GenericResources;

            var res = await arm.ListAsync();

            var result = new List <AzureResource>();

            foreach (var r in res)
            {
                var newResource = new AzureResource {
                    ResourceType = r.ResourceType, ResourceUri = r.Id, Tags = SerializeTags(r.Tags)
                };
                if (r.ResourceProviderNamespace == "Microsoft.Web" && r.ResourceType == "sites")
                {
                    var fullResource = arm.Get(r.ResourceGroupName, r.ResourceProviderNamespace, r.ParentResourceId, r.ResourceType, r.Name, "2016-03-01");
                    var serverFarmId = (string)(fullResource.Properties as JObject)["serverFarmId"];
                    newResource.ServerFarmId = serverFarmId;
                }


                result.Add(newResource);
            }

            return(result);
        }
Beispiel #2
0
    public Task <TAzureResource> GetResourceAsync <TAzureResource>(string resourceId, bool throwIfNotExists = false)
        where TAzureResource : AzureResource
    {
        var bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
        var resource     = Activator.CreateInstance(typeof(TAzureResource), bindingFlags, null, new object[] { resourceId }, CultureInfo.InvariantCulture) as TAzureResource;

        return(AzureResource.InitializeAsync(resource, this, throwIfNotExists));
    }
 public CheckForParentResourceEvent(AzureResource parentResourceType, AzureResource resourceType, string resourceName)
     : base(
           BuildEventType.Information,
           BuildEventImportance.Low,
           $"Checking if a suitable {parentResourceType.GetEnumDescription()} that we can use exists in the subscription for the {resourceType.GetEnumDescription()} {resourceName}.")
 {
     ResourceType = resourceType;
     ResourceName = resourceName;
 }
Beispiel #4
0
 public CheckForParentResourceEvent(AzureResource parentResourceType, AzureResource resourceType, string resourceName)
     : base(
         BuildEventType.Information,
         BuildEventImportance.Low,
         $"Checking if a suitable {parentResourceType.GetEnumDescription()} that we can use exists in the subscription for the {resourceType.GetEnumDescription()} {resourceName}.")
 {
     ResourceType = resourceType;
     ResourceName = resourceName;
 }
Beispiel #5
0
        private static void RunCommand(AzureResource resource)
        {
            var args = new List <string>
            {
                "--name",
                resource.Name
            };

            resource.Args = resource.Args.Concat(args);
            Azure.Command(resource.Args.ToArray()).ForwardStdOut().ForwardStdErr().Execute();
        }
Beispiel #6
0
        public IList <AzureUtilizationRecord> MapUtilizationToCustomClass(List <CustomObject> listFromSDK)
        {
            IList <AzureUtilizationRecord> customList = new List <AzureUtilizationRecord>();

            foreach (var objFromSDK in listFromSDK)
            {
                foreach (var record in objFromSDK.ResourceUtilizationList)
                {
                    AzureUtilizationRecord objCustom = new AzureUtilizationRecord();
                    objCustom.CustomerCompanyName = objFromSDK.CustomerCompanyName;
                    objCustom.UsageStartTime      = record.UsageStartTime.LocalDateTime;
                    objCustom.UsageEndTime        = record.UsageEndTime.LocalDateTime;
                    objCustom.Unit       = record.Unit;
                    objCustom.Quantity   = (double)record.Quantity;
                    objCustom.InfoFields = record.InfoFields;

                    AzureInstanceData         objCustomInstanceData      = new AzureInstanceData();
                    AzureResource             objCustomResouceData       = new AzureResource();
                    Models.ResourceAttributes objCustomResouceAttributes = new Models.ResourceAttributes();

                    try
                    {
                        objCustomInstanceData.Location    = record.InstanceData.Location;
                        objCustomInstanceData.OrderNumber = record.InstanceData.OrderNumber;
                        objCustomInstanceData.PartNumber  = record.InstanceData.PartNumber;
                        objCustomInstanceData.ResourceUri = record.InstanceData.ResourceUri.OriginalString;
                        objCustomInstanceData.Tags        = record.InstanceData.Tags;
                    }
                    catch { }

                    objCustom.InstanceData = objCustomInstanceData;

                    objCustomResouceData.Category    = record.Resource.Category;
                    objCustomResouceData.Id          = record.Resource.Id;
                    objCustomResouceData.Name        = record.Resource.Name;
                    objCustomResouceData.Subcategory = record.Resource.Subcategory;

                    objCustom.Resource = objCustomResouceData;

                    objCustomResouceAttributes.Etag = record.Attributes.Etag;

                    objCustom.Attributes = objCustomResouceAttributes;

                    customList.Add(objCustom);
                }
            }
            return(customList);
        }
Beispiel #7
0
        public static async Task ShouldHaveRoleAssignmentAsync(this AzureResource azureResource, User user, Guid roleDefinition)
        {
            if (azureResource is null)
            {
                throw new ArgumentNullException(nameof(azureResource));
            }

            if (user is null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            var roleAssignments = await azureResource.GetRoleAssignmentsAsync(user.Id).ConfigureAwait(false);

            Assert.Contains(roleAssignments, roleAssignment => roleAssignment == roleDefinition);
        }
Beispiel #8
0
        public static async Task ShouldHaveNoRoleAssignmentAsync(this AzureResource azureResource, User user)
        {
            if (azureResource is null)
            {
                throw new ArgumentNullException(nameof(azureResource));
            }

            if (user is null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            var roleAssignments = await azureResource.GetRoleAssignmentsAsync(user.Id).ConfigureAwait(false);

            Assert.Empty(roleAssignments);
        }
        public IList <AzureUtilizationRecord> MapUtilizationToCustomClass(List <Microsoft.Store.PartnerCenter.Models.Utilizations.AzureUtilizationRecord> listFromSDK)
        {
            IList <AzureUtilizationRecord> customList = new List <AzureUtilizationRecord>();

            foreach (var objFromSDK in listFromSDK)
            {
                AzureUtilizationRecord objCustom = new AzureUtilizationRecord();
                objCustom.UsageStartTime = objFromSDK.UsageStartTime.LocalDateTime;
                objCustom.UsageEndTime   = objFromSDK.UsageEndTime.LocalDateTime;
                objCustom.Unit           = objFromSDK.Unit;
                objCustom.Quantity       = (double)objFromSDK.Quantity;
                objCustom.InfoFields     = objFromSDK.InfoFields;

                AzureInstanceData         objCustomInstanceData      = new AzureInstanceData();
                AzureResource             objCustomResouceData       = new AzureResource();
                Models.ResourceAttributes objCustomResouceAttributes = new Models.ResourceAttributes();

                objCustomInstanceData.Location    = objFromSDK.InstanceData.Location;
                objCustomInstanceData.OrderNumber = objFromSDK.InstanceData.OrderNumber;
                objCustomInstanceData.PartNumber  = objFromSDK.InstanceData.PartNumber;
                objCustomInstanceData.ResourceUri = objFromSDK.InstanceData.ResourceUri.OriginalString;
                objCustomInstanceData.Tags        = objFromSDK.InstanceData.Tags;

                objCustom.InstanceData = objCustomInstanceData;

                objCustomResouceData.Category    = objFromSDK.Resource.Category;
                objCustomResouceData.Id          = objFromSDK.Resource.Id;
                objCustomResouceData.Name        = objFromSDK.Resource.Name;
                objCustomResouceData.Subcategory = objFromSDK.Resource.Subcategory;

                objCustom.Resource = objCustomResouceData;

                objCustomResouceAttributes.Etag = objFromSDK.Attributes.Etag;

                objCustom.Attributes = objCustomResouceAttributes;

                customList.Add(objCustom);
            }
            return(customList);
        }
Beispiel #10
0
        public async Task <List <AzureResource> > GetResources(ResourceGroup resourceGroup)
        {
            try
            {
                List <AzureResource> resources = new List <AzureResource>();

                JsonDocument result = await CallARM($"https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup.Name}/resources?api-version=2020-06-01");

                var e = result.RootElement.GetProperty("value").EnumerateArray();
                while (e.MoveNext())
                {
                    AzureResource stub = AzureResource.FromJsonElement(e.Current);
                    stub.ResourceGroupName = resourceGroup.Name;
                    resources.Add(stub);
                }

                return(resources);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return(null);
            }
        }
Beispiel #11
0
 public DeploymentEventArgs(AzureResource resource)
 {
     Resource = resource;
 }
 public FoundExistingEvent(AzureResource resourceType, string resourceName)
     : base(BuildEventType.Information, BuildEventImportance.Low, $"Found an existing suitable {resourceType.GetEnumDescription()}: {resourceName}.")
 {
     ResourceType = resourceType;
     ResourceName = resourceName;
 }
Beispiel #13
0
        public async Task <List <AzureResource> > LoadResource(AzureResource stub)
        {
            // using a list because in special cases we might load subresources too
            List <AzureResource> resources = new List <AzureResource>();
            AzureResource        resource  = null;

            try
            {
                Assembly    a     = Assembly.GetExecutingAssembly();
                List <Type> types = a.GetTypes().Where(t => t.IsClass && t.BaseType == typeof(AzureResource)).ToList();

                foreach (Type t in types)
                {
                    FieldInfo fi = t.GetField("AzureType");
                    if (fi != null && fi.GetValue(null).ToString() == stub.Type)
                    {
                        // generic method of loading a single resource
                        string       apiVersion = t.GetField("ApiVersion").GetValue(null).ToString();
                        JsonDocument result     = await CallARM($"https://management.azure.com{stub.ID}?api-version={apiVersion}");

                        MethodInfo method = t.GetMethod("FromJsonElement");
                        if (method != null)
                        {
                            resource = (AzureResource)method.Invoke(null, new object[] { result.RootElement });
                            resource.ResourceGroupName = stub.ResourceGroupName;
                            resources.Add(resource);
                        }

                        // in special cases we want to load subresources, such as subnets in a virtual network that we want to create as separate objects
                        if (stub.Type == VirtualNetwork.AzureType)
                        {
                            ArrayEnumerator subnetEnum = result.RootElement.GetProperty("properties").GetProperty("subnets").EnumerateArray();
                            while (subnetEnum.MoveNext())
                            {
                                Subnet subnet = Subnet.FromJsonElement(subnetEnum.Current) as Subnet;
                                subnet.VirtualNetworkName = stub.Name;
                                resources.Add(subnet);
                            }
                        }
                        if (stub.Type == NetworkSecurityGroup.AzureType)
                        {
                            // if subnet is defined we need to add an association because inline subnet blocks don't support delegation or service endpoints
                            NetworkSecurityGroup nsg = resource as NetworkSecurityGroup;
                            foreach (string subnet in nsg.Subnets)
                            {
                                SubnetNetworkSecurityGroupAssociation assoc = new SubnetNetworkSecurityGroupAssociation();
                                assoc.SubnetName = subnet;
                                assoc.NetworkSecurityGroupName = nsg.Name;
                                resources.Add(assoc);
                            }
                        }
                        if (stub.Type == DnsZone.AzureType)
                        {
                            // DNS zones don't contain records so we need to add each one as a separate resource
                            JsonDocument records = await CallARM($"https://management.azure.com{stub.ID}/all?api-version={apiVersion}");

                            ArrayEnumerator recordEnum = records.RootElement.GetProperty("value").EnumerateArray();
                            while (recordEnum.MoveNext())
                            {
                                // this could be a recursive call, is it better to load the object twice or to duplicate this code? :S
                                string type = recordEnum.Current.GetProperty("type").GetString();

                                if (type == "Microsoft.Network/dnszones/CNAME")
                                {
                                    var record = DnsZoneCNAME.FromJsonElement(recordEnum.Current) as DnsZoneCNAME;
                                    record.Location = stub.Location;
                                    record.ZoneName = stub.Name;
                                    resources.Add(record);
                                }
                                if (type == "Microsoft.Network/dnszones/TXT")
                                {
                                    var record = DnsZoneTXT.FromJsonElement(recordEnum.Current) as DnsZoneTXT;
                                    record.Location = stub.Location;
                                    record.ZoneName = stub.Name;
                                    resources.Add(record);
                                }
                                if (type == "Microsoft.Network/dnszones/A")
                                {
                                    var record = DnsZoneA.FromJsonElement(recordEnum.Current) as DnsZoneA;
                                    record.Location = stub.Location;
                                    record.ZoneName = stub.Name;
                                    resources.Add(record);
                                }
                            }
                        }
                        if (stub.Type == KeyVault.AzureType)
                        {
                            // enumerate the access policies and create separately - inline blocks only support 16 access policies
                            ArrayEnumerator policyEnum = result.RootElement.GetProperty("properties").GetProperty("accessPolicies").EnumerateArray();
                            while (policyEnum.MoveNext())
                            {
                                var policy = KeyVaultAccessPolicy.FromJsonElement(policyEnum.Current) as KeyVaultAccessPolicy;
                                policy.KeyVaultName = stub.Name;
                                resources.Add(policy);
                            }
                        }

                        string filename = $"../{stub.Type.Replace('/', '_')}_{stub.Name}.json";
                        if (File.Exists(filename) == false)
                        {
                            string s = result.RootElement.ToString();
                            File.WriteAllText(filename, s);
                        }
                    }
                }

                if (resource == null)
                {
                    resources.Add(stub);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            return(resources);
        }
Beispiel #14
0
 public ProvisionEvent(AzureResource resourceType, string resourceName)
     : base(BuildEventType.Information, BuildEventImportance.High, $"Provisioned the {resourceType.GetEnumDescription()} {resourceName}.")
 {
     ResourceType = resourceType;
     ResourceName = resourceName;
 }
 public CheckIfExistsEvent(AzureResource resourceType, string resourceName)
     : base(BuildEventType.Information, BuildEventImportance.Low, $"Checking if the {resourceType.GetEnumDescription()} {resourceName} exists in the subscription.")
 {
     ResourceType = resourceType;
     ResourceName = resourceName;
 }
Beispiel #16
0
 public CheckIfExistsEvent(AzureResource resourceType, string resourceName)
     : base(BuildEventType.Information, BuildEventImportance.Low, $"Checking if the {resourceType.GetEnumDescription()} {resourceName} exists in the subscription.")
 {
     ResourceType = resourceType;
     ResourceName = resourceName;
 }
Beispiel #17
0
 public FoundExistingEvent(AzureResource resourceType, string resourceName)
     : base(BuildEventType.Information, BuildEventImportance.Low, $"Found an existing suitable {resourceType.GetEnumDescription()}: {resourceName}.")
 {
     ResourceType = resourceType;
     ResourceName = resourceName;
 }
Beispiel #18
0
 public ProvisionEvent(AzureResource resourceType, string resourceName)
     : base(BuildEventType.Information, BuildEventImportance.High, $"Provisioned the {resourceType.GetEnumDescription()} {resourceName}.")
 {
     ResourceType = resourceType;
     ResourceName = resourceName;
 }
Beispiel #19
0
 public Task <AzureSubscription> GetSubscriptionAsync(Guid subscriptionId, bool throwIfNotExists = false)
 => AzureResource.InitializeAsync(new AzureSubscription(subscriptionId), this, throwIfNotExists);
Beispiel #20
0
 public async Task <Result> Deploy(IAuthenticated azure, DeploymentOptions options, AzureResource resource) =>
 await CreateResourceAsync(azure, options, resource.Name, resource.Type);
Beispiel #21
0
 public Task <AzureResourceGroup> GetResourceGroupAsync(Guid subscriptionId, string resourceGroupName, bool throwIfNotExists = false)
 => AzureResource.InitializeAsync(new AzureResourceGroup(subscriptionId, resourceGroupName), this, throwIfNotExists);
 public DeploymentErrorEventArgs(AzureResource resource, Exception exception)
     : base(resource)
 {
     Exception = exception;
 }
Beispiel #23
0
 public Task <AzureResource> GetResourceAsync(string resourceId, bool throwIfNotExists = false)
 => AzureResource.InitializeAsync(new AzureResource(resourceId), this, throwIfNotExists);