/**
         * Creates subnets in a VCN and waits for the subnets to become available to use.
         *
         * @param vcnClient the service client to use to create the subnet
         * @param compartmentId the OCID of the compartment which owns the VCN
         * @param availabilityDomain the availability domain where the subnet will be created
         * @param cidrBlock the cidr block used to create subnet
         * @param vcnId the ID of the VCN which will own the subnet
         * @param subnetName the subnet that will be created
         *
         * @return the created subnets
         *
         */
        private static async Task <List <Subnet> > CreateSubnet(VirtualNetworkClient virtualNetworkClient, string compartmentId, IdentityModels.AvailabilityDomain availabilityDomain, string vcnId)
        {
            List <Subnet> subnets = new List <Subnet>();

            for (int i = 0; i < 2; i++)
            {
                CreateSubnetDetails createSubnetDetails = new CreateSubnetDetails
                {
                    AvailabilityDomain = availabilityDomain.Name,
                    CompartmentId      = compartmentId,
                    DisplayName        = SubnetDisplayNames[i],
                    CidrBlock          = SubnetCidrBlocks[i],
                    VcnId = vcnId
                };
                CreateSubnetRequest createSubnetRequest = new CreateSubnetRequest {
                    CreateSubnetDetails = createSubnetDetails
                };
                CreateSubnetResponse createSubnetResponse = await virtualNetworkClient.CreateSubnet(createSubnetRequest);

                GetSubnetRequest getSubnetRequest = new GetSubnetRequest {
                    SubnetId = createSubnetResponse.Subnet.Id
                };
                GetSubnetResponse getSubnetResponse = virtualNetworkClient.Waiters.ForSubnet(getSubnetRequest, Subnet.LifecycleStateEnum.Available).Execute();
                Subnet            subnet            = getSubnetResponse.Subnet;

                logger.Info($"Created Subnet: {subnet.Id}");
                subnets.Add(getSubnetResponse.Subnet);
            }
            return(subnets);
        }
Beispiel #2
0
        /**
         * Creates a subnet in a VCN and waits for the subnet to become available to use.
         *
         * @param vcnClient the service client to use to create the subnet.
         * @param compartmentId the OCID of the compartment which owns the VCN.
         * @param vcnId the ID of the VCN which will own the subnet.
         * @param availabilityDomain the availability domain where the subnet will be created.
         * @return the created subnet.
         */
        private static async Task <Subnet> CreateSubnet(VirtualNetworkClient vcnClient, string compartmentId, string availabilityDomain, string vcnId)
        {
            logger.Info("Creating subnet");

            CreateSubnetDetails createSubnetDetails = new CreateSubnetDetails
            {
                AvailabilityDomain = availabilityDomain,
                CompartmentId      = compartmentId,
                DisplayName        = SubnetName,
                CidrBlock          = SubnetCidrBlock,
                VcnId = vcnId
            };
            CreateSubnetRequest createSubnetRequest = new CreateSubnetRequest {
                CreateSubnetDetails = createSubnetDetails
            };
            CreateSubnetResponse createSubnetResponse = await vcnClient.CreateSubnet(createSubnetRequest);

            GetSubnetRequest getSubnetRequest = new GetSubnetRequest {
                SubnetId = createSubnetResponse.Subnet.Id
            };
            GetSubnetResponse getSubnetResponse = vcnClient.Waiters.ForSubnet(getSubnetRequest, Subnet.LifecycleStateEnum.Available).Execute();
            Subnet            subnet            = getSubnetResponse.Subnet;

            logger.Info($"Created Subnet: {subnet.Id}");
            return(subnet);
        }
        private static async Task clearRouteRulesFromDefaultRouteTable(VirtualNetworkClient virtualNetworkClient, Vcn vcn)
        {
            List <RouteRule>        routeRules = new List <RouteRule>();
            UpdateRouteTableDetails updateRouteTableDetails = new UpdateRouteTableDetails {
                RouteRules = routeRules
            };
            UpdateRouteTableRequest updateRouteTableRequest = new UpdateRouteTableRequest
            {
                UpdateRouteTableDetails = updateRouteTableDetails,
                RtId = vcn.DefaultRouteTableId
            };
            await virtualNetworkClient.UpdateRouteTable(updateRouteTableRequest);

            WaiterConfiguration waiterConfiguration = new WaiterConfiguration
            {
                MaxAttempts           = 20,
                GetNextDelayInSeconds = DelayStrategy.GetExponentialDelayInSeconds
            };

            GetRouteTableRequest getRouteTableRequest = new GetRouteTableRequest
            {
                RtId = vcn.DefaultRouteTableId
            };

            virtualNetworkClient.Waiters.ForRouteTable(getRouteTableRequest, waiterConfiguration, RouteTable.LifecycleStateEnum.Available).Execute();

            logger.Info($"Cleared route rules from route table: {vcn.DefaultRouteTableId}");
        }
        private static async Task <Subnet> createSubnet(VirtualNetworkClient virtualNetworkClient, string compartmentId, AvailabilityDomain availabilityDomain, string networkCidrBlock, Vcn vcn)
        {
            string subnetName = "oci-dotnet-sdk-example-subnet";

            // In order to launch instances in a regional subnet, build this CreateSubnetDetails with
            // the field availablityDomain set to null.
            CreateSubnetDetails createSubnetDetails = new CreateSubnetDetails
            {
                AvailabilityDomain = availabilityDomain.Name,
                CompartmentId      = compartmentId,
                DisplayName        = subnetName,
                CidrBlock          = networkCidrBlock,
                VcnId        = vcn.Id,
                RouteTableId = vcn.DefaultRouteTableId
            };
            CreateSubnetRequest createSubnetRequest = new CreateSubnetRequest {
                CreateSubnetDetails = createSubnetDetails
            };
            CreateSubnetResponse createSubnetResponse = await virtualNetworkClient.CreateSubnet(createSubnetRequest);

            GetSubnetRequest getSubnetRequest = new GetSubnetRequest {
                SubnetId = createSubnetResponse.Subnet.Id
            };
            GetSubnetResponse getSubnetResponse = virtualNetworkClient.Waiters.ForSubnet(getSubnetRequest, Subnet.LifecycleStateEnum.Available).Execute();
            Subnet            subnet            = getSubnetResponse.Subnet;

            logger.Info($"Created Subnet: {subnet.Id}");
            return(subnet);
        }
        /**
         * Creates a VCN and waits for it to become available to use.
         *
         * @param vcnClient the service client to use to create the VCN
         * @param compartmentId the OCID of the compartment where the VCN will be created
         *
         * @return the created VCN
         */
        private static async Task <Vcn> CreateVcn(VirtualNetworkClient virtualNetworkClient, string compartmentId)
        {
            logger.Info("creating vcn");

            CreateVcnDetails createVcnDetails = new CreateVcnDetails
            {
                CidrBlock     = CidrBlock,
                CompartmentId = compartmentId,
                DisplayName   = VcnDisplayName
            };
            CreateVcnRequest createVcnRequest = new CreateVcnRequest
            {
                CreateVcnDetails = createVcnDetails
            };
            CreateVcnResponse createVcnResponse = await virtualNetworkClient.CreateVcn(createVcnRequest);

            GetVcnRequest getVcnRequest = new GetVcnRequest
            {
                VcnId = createVcnResponse.Vcn.Id
            };
            GetVcnResponse getVcnResponse = virtualNetworkClient.Waiters.ForVcn(getVcnRequest, Vcn.LifecycleStateEnum.Available).Execute();
            Vcn            vcn            = getVcnResponse.Vcn;

            logger.Info($"Created vcn: {vcn.Id} and state is {vcn.LifecycleState}");
            return(vcn);
        }
        private static async Task printInstance(ComputeClient computeClient, VirtualNetworkClient virtualNetworkClient, Instance instance)
        {
            ListVnicAttachmentsRequest listVnicAttachmentsRequest = new ListVnicAttachmentsRequest
            {
                CompartmentId = instance.CompartmentId,
                InstanceId    = instance.Id
            };
            ListVnicAttachmentsResponse listVnicAttachmentsResponse = await computeClient.ListVnicAttachments(listVnicAttachmentsRequest);

            List <VnicAttachment> vnicAttachments = listVnicAttachmentsResponse.Items;
            VnicAttachment        vnicAttachment  = vnicAttachments[0];

            GetVnicRequest getVnicRequest = new GetVnicRequest
            {
                VnicId = vnicAttachment.VnicId
            };
            GetVnicResponse getVnicResponse = await virtualNetworkClient.GetVnic(getVnicRequest);

            Vnic vnic = getVnicResponse.Vnic;

            logger.Info($"Virtual Network Interface Card: {vnic.Id}");

            InstanceAgentConfig instanceAgentConfig = instance.AgentConfig;
            bool   monitoringEnabled = instanceAgentConfig.IsMonitoringDisabled.HasValue ? instanceAgentConfig.IsMonitoringDisabled.Value : false;
            string monitoringStatus  = (monitoringEnabled ? "Enabled" : "Disabled");

            logger.Info($"Instance ID: {instance.Id} has monitoring {monitoringStatus}");
        }
Beispiel #7
0
 protected override void ProcessRecord()
 {
     base.ProcessRecord();
     try
     {
         client?.Dispose();
         int timeout = GetPreferredTimeout();
         WriteDebug($"Cmdlet Timeout : {timeout} milliseconds.");
         client = new VirtualNetworkClient(AuthProvider, new Oci.Common.ClientConfiguration
         {
             RetryConfiguration = retryConfig,
             TimeoutMillis      = timeout,
             ClientUserAgent    = PSUserAgent
         });
         string region = GetPreferredRegion();
         if (region != null)
         {
             WriteDebug("Choosing Region:" + region);
             client.SetRegion(region);
         }
         if (Endpoint != null)
         {
             WriteDebug("Choosing Endpoint:" + Endpoint);
             client.SetEndpoint(Endpoint);
         }
     }
     catch (Exception ex)
     {
         TerminatingErrorDuringExecution(ex);
     }
 }
Beispiel #8
0
        /**
         * Remove all resources created by the 'setup' operation.
         *
         * NB: Resources can only be removed 30 minutes after the last Function
         * invocation.
         *
         * @param provider      the OCI credentials provider.
         * @param region        the OCI region in which to create the required
         *                      resources.
         * @param compartmentId the compartment in which to created the required
         *                      resources.
         * @param name          a name prefix to easily identify the resources.
         */
        private static async Task TearDownResources(IBasicAuthenticationDetailsProvider provider, string compartmentId)
        {
            var identityClient     = new IdentityClient(provider);
            var vcnClient          = new VirtualNetworkClient(provider);
            var fnManagementClient = new FunctionsManagementClient(provider);

            try
            {
                logger.Info("Cleaning up....");

                var vcn = await GetUniqueVcnByName(vcnClient, compartmentId);

                var ig = await GetUniqueInternetGatewayByName(vcnClient, compartmentId, vcn.Id);

                var rt = await GetUniqueRouteTableByName(vcnClient, compartmentId, vcn.Id);

                var subnet = await GetUniqueSubnetByName(vcnClient, compartmentId, vcn.Id);

                var application = await GetUniqueApplicationByName(fnManagementClient, compartmentId);

                var fn = await GetUniqueFunctionByName(fnManagementClient, application.Id, FunctionName);

                if (fn != null)
                {
                    await DeleteFunction(fnManagementClient, fn.Id);
                }

                if (application != null)
                {
                    await DeleteApplication(fnManagementClient, application.Id);
                }

                if (ig != null)
                {
                    await ClearRouteRulesFromDefaultRouteTable(vcnClient, vcn.DefaultRouteTableId);
                    await DeleteInternetGateway(vcnClient, ig.Id);
                }

                if (subnet != null)
                {
                    await DeleteSubnet(vcnClient, subnet);
                }

                if (vcn != null)
                {
                    await DeleteVcn(vcnClient, vcn);
                }
            }
            catch (Exception e)
            {
                logger.Error($"Failed to clean the resources: {e}");
            }
            finally
            {
                fnManagementClient.Dispose();
                vcnClient.Dispose();
                identityClient.Dispose();
            }
        }
Beispiel #9
0
        private PSVirtualNetwork CreateVirtualNetwork()
        {
            var vnet = new PSVirtualNetwork
            {
                Name = Name,
                ResourceGroupName = ResourceGroupName,
                Location          = Location,
                AddressSpace      = new PSAddressSpace {
                    AddressPrefixes = AddressPrefix?.ToList()
                }
            };

            if (DnsServer != null)
            {
                vnet.DhcpOptions = new PSDhcpOptions {
                    DnsServers = DnsServer?.ToList()
                };
            }

            vnet.Subnets = this.Subnet?.ToList();
            vnet.EnableDdosProtection = EnableDdosProtection;

            if (!string.IsNullOrEmpty(DdosProtectionPlanId))
            {
                vnet.DdosProtectionPlan = new PSResourceId {
                    Id = DdosProtectionPlanId
                };
            }

            if (!string.IsNullOrWhiteSpace(BgpCommunity))
            {
                vnet.BgpCommunities = new PSVirtualNetworkBgpCommunities {
                    VirtualNetworkCommunity = this.BgpCommunity
                };
            }

            // Map to the sdk object
            var vnetModel = NetworkResourceManagerProfile.Mapper.Map <MNM.VirtualNetwork>(vnet);

            vnetModel.Tags = TagsConversionHelper.CreateTagDictionary(Tag, validate: true);

            if (this.IpAllocation != null)
            {
                foreach (var ipAllocation in this.IpAllocation)
                {
                    var ipAllocationReference = new MNM.SubResource(ipAllocation.Id);
                    vnetModel.IpAllocations.Add(ipAllocationReference);
                }
            }

            // Execute the Create VirtualNetwork call
            VirtualNetworkClient.CreateOrUpdate(ResourceGroupName, Name, vnetModel);

            var getVirtualNetwork = GetVirtualNetwork(ResourceGroupName, Name);

            return(getVirtualNetwork);
        }
        /**
         * Deletes a VCN and waits for it to be deleted.
         *
         * @param vcnClient the service client to use to delete the VCN
         * @param vcn the VCN to delete
         *
         * @throws Exception if there is an error waiting on the VCN to be deleted
         */
        private static async Task DeleteVcn(VirtualNetworkClient virtualNetworkClient, Vcn vcn)
        {
            DeleteVcnRequest deleteVcnRequest = new DeleteVcnRequest {
                VcnId = vcn.Id
            };
            await virtualNetworkClient.DeleteVcn(deleteVcnRequest);

            logger.Info($"Deleted Vcn: {vcn.Id}");
        }
        /**
         * Deletes a subnet and waits for it to be deleted.
         *
         * @param vcnClient the service client to use to delete the subnet
         * @param subnet the subnet to delete
         *
         * @throws Exception if there is an error waiting on the subnet to be deleted
         */
        private static async Task DeleteSubnet(VirtualNetworkClient virtualNetworkClient, Subnet subnet)
        {
            DeleteSubnetRequest deleteSubnetRequest = new DeleteSubnetRequest
            {
                SubnetId = subnet.Id
            };
            await virtualNetworkClient.DeleteSubnet(deleteSubnetRequest);

            logger.Info($"Deleted Subnet: {subnet.Id}");
        }
        private static async Task deleteInternetGateway(VirtualNetworkClient virtualNetworkClient, InternetGateway internetGateway)
        {
            DeleteInternetGatewayRequest deleteInternetGatewayRequest = new DeleteInternetGatewayRequest
            {
                IgId = internetGateway.Id
            };
            await virtualNetworkClient.DeleteInternetGateway(deleteInternetGatewayRequest);

            logger.Info($"Deleted Internet Gateway: {internetGateway.Id}");
        }
Beispiel #13
0
        /**
         * Deletes a InternetGateway and waits for it to be deleted.
         *
         * @param vcnClient the service client to use to delete the InternetGateway.
         * @param igId      the InternetGateway to delete.
         */
        private static async Task DeleteInternetGateway(VirtualNetworkClient vcnClient, string igId)
        {
            DeleteInternetGatewayRequest deleteInternetGatewayRequest = new DeleteInternetGatewayRequest
            {
                IgId = igId
            };
            await vcnClient.DeleteInternetGateway(deleteInternetGatewayRequest);

            logger.Info($"Deleted Internet Gateway: {igId}");
        }
        /**
         * Deletes a subnet and waits for it to be deleted.
         *
         * @param virtualNetworkClient the service client to use to delete the subnet
         * @param subnet the subnet to delete
         */
        private static async Task DeleteSubnet(VirtualNetworkClient virtualNetworkClient, Subnet subnet)
        {
            DeleteSubnetRequest deleteSubnetRequest = new DeleteSubnetRequest
            {
                SubnetId = subnet.Id
            };
            RetryConfiguration retryConfiguration = new RetryConfiguration
            {
                MaxAttempts = 5
            };
            await virtualNetworkClient.DeleteSubnet(deleteSubnetRequest, retryConfiguration);

            logger.Info($"Deleted Subnet: {subnet.Id}");
        }
Beispiel #15
0
        /**
         * Configure the default RouteTable of the specified InternetGateway to ensure it
         * contains a single outbound route for all traffic.
         *
         * NB: You should restrict these routes further if you keep this piece of
         *     OCI infrastructure.
         *
         * @param vcnClient      the service client to use to query a RouteTable.
         * @param routeTableId   of the default route table associated with the VCN.
         * @param igId           of the RouteTable's associated InternetGateway.
         */
        private static async Task AddInternetGatewayToDefaultRouteTable(VirtualNetworkClient vcnClient, string routeTableId, string igId)
        {
            GetRouteTableRequest getRouteTableRequest = new GetRouteTableRequest
            {
                RtId = routeTableId
            };
            GetRouteTableResponse getRouteTableResponse = await vcnClient.GetRouteTable(getRouteTableRequest);

            var routeRules = getRouteTableResponse.RouteTable.RouteRules;

            logger.Info("Current Route Rules in Default Route Table");
            logger.Info("==========================================");
            routeRules.ForEach(delegate(RouteRule rule)
            {
                logger.Info($"rule: {rule.NetworkEntityId}");
            });

            RouteRule internetAccessRoute = new RouteRule
            {
                Destination     = "0.0.0.0/0",
                DestinationType = RouteRule.DestinationTypeEnum.CidrBlock,
                NetworkEntityId = igId
            };

            routeRules.Add(internetAccessRoute);
            UpdateRouteTableDetails updateRouteTableDetails = new UpdateRouteTableDetails
            {
                RouteRules  = routeRules,
                DisplayName = RouteTableName
            };
            UpdateRouteTableRequest updateRouteTableRequest = new UpdateRouteTableRequest
            {
                UpdateRouteTableDetails = updateRouteTableDetails,
                RtId = routeTableId
            };
            UpdateRouteTableResponse updateRouteTableResponse = await vcnClient.UpdateRouteTable(updateRouteTableRequest);

            getRouteTableResponse = vcnClient.Waiters.ForRouteTable(getRouteTableRequest, RouteTable.LifecycleStateEnum.Available).Execute();
            routeRules            = getRouteTableResponse.RouteTable.RouteRules;

            logger.Info("Updated Route Rules in Default Route Table");
            logger.Info("==========================================");
            routeRules.ForEach(delegate(RouteRule rule)
            {
                logger.Info($"rule: {rule.NetworkEntityId}\n");
            });
        }
Beispiel #16
0
        /**
         * Create all the OCI and Fn resources required to invoke a function.
         *
         * @param provider      the OCI credentials provider.
         * @param compartmentId the compartment in which to create the required
         *                      resources.
         * @param image         a valid OCI Registry image for the function.
         */
        private static async Task SetUpResources(IBasicAuthenticationDetailsProvider provider, string compartmentId, string image)
        {
            logger.Info("Setting up resources");

            var identityClient     = new IdentityClient(provider);
            var vcnClient          = new VirtualNetworkClient(provider);
            var fnManagementClient = new FunctionsManagementClient(provider);

            Vcn             vcn             = null;
            Subnet          subnet          = null;
            InternetGateway internetGateway = null;

            try
            {
                AvailabilityDomain availablityDomain = await GetAvailabilityDomain(identityClient, compartmentId);

                logger.Info($"availability domain is {availablityDomain.Name}");

                vcn = await CreateVcn(vcnClient, compartmentId);

                internetGateway = await CreateInternalGateway(vcnClient, compartmentId, vcn);
                await AddInternetGatewayToDefaultRouteTable(vcnClient, vcn.DefaultRouteTableId, internetGateway.Id);

                subnet = await CreateSubnet(vcnClient, compartmentId, availablityDomain.Name, vcn.Id);

                var subnetIds = new List <string>()
                {
                    subnet.Id
                };
                Application app = await CreateApplication(fnManagementClient, compartmentId, subnetIds);

                long     memoryInMBs      = 128L;
                int      timeoutInSeconds = 30;
                Function fn = await CreateFunction(fnManagementClient, app.Id, image, memoryInMBs, timeoutInSeconds);
            }
            catch (Exception e)
            {
                logger.Error($"failed to setup resources: {e}");
            }
            finally
            {
                fnManagementClient.Dispose();
                vcnClient.Dispose();
                identityClient.Dispose();
            }
        }
Beispiel #17
0
        /**
         * Gets VCN info of a single uniquely named VCN in the specified compartment.
         *
         * @param vcnClient      the service client to use to query the VCN.
         * @param compartmentId  of the VCN.
         * @param vcnDisplayName of the VCN.
         * @return               the VCN.
         */
        private static async Task <Vcn> GetUniqueVcnByName(VirtualNetworkClient vcnClient, string compartmentId)
        {
            // Find the Vcn in a specific compartment
            var listVcnsRequest = new ListVcnsRequest
            {
                CompartmentId = compartmentId,
                DisplayName   = VcnName
            };
            var listVcnsResponse = await vcnClient.ListVcns(listVcnsRequest);

            if (listVcnsResponse.Items.Count != 1)
            {
                logger.Error($"Could not find unique VCN with name: {VcnName} in compartment: {compartmentId}");
                return(null);
            }

            return(listVcnsResponse.Items[0]);
        }
Beispiel #18
0
        /**
         * Gets InternetGateway info of a single uniquely named InternetGateway in the
         * specified compartment.
         *
         * @param vcnClient     the service client to use to query the InternetGateway.
         * @param compartmentId of the InternetGateway.
         * @param vcnId         of the InternetGateway's associated VCN.
         * @return the InternetGateway.
         */
        private static async Task <InternetGateway> GetUniqueInternetGatewayByName(VirtualNetworkClient vcnClient, string compartmentId, string vcnId)
        {
            // Find the Internet gateway in a specific compartment
            var listInternetGatewaysRequest = new ListInternetGatewaysRequest
            {
                CompartmentId = compartmentId,
                VcnId         = vcnId,
                DisplayName   = IgName
            };
            var listInternetGatewaysResponse = await vcnClient.ListInternetGateways(listInternetGatewaysRequest);

            if (listInternetGatewaysResponse.Items.Count != 1)
            {
                logger.Error($"Could not find unique InternetGateway with name: {IgName} in compartment: {compartmentId}");
                return(null);
            }

            return(listInternetGatewaysResponse.Items[0]);
        }
Beispiel #19
0
        /**
         * Gets RouteTable info of a single uniquely named RouteTable in the
         * specified compartment.
         *
         * @param vcnClient     the service client to use to query a RouteTable.
         * @param compartmentId of the RouteTable.
         * @param vcnId         of the RouteTable's associated VCN.
         * @return the InternetGateway.
         */
        private static async Task <RouteTable> GetUniqueRouteTableByName(VirtualNetworkClient vcnClient, string compartmentId, string vcnId)
        {
            // Find the route table in a specific compartment
            var listRouteTablesRequest = new ListRouteTablesRequest
            {
                CompartmentId = compartmentId,
                VcnId         = vcnId,
                DisplayName   = RouteTableName
            };
            var listRouteTablesResponse = await vcnClient.ListRouteTables(listRouteTablesRequest);

            if (listRouteTablesResponse.Items.Count != 1)
            {
                logger.Error($"Could not find unique RouteTable with name: {RouteTableName} in compartment: {compartmentId}");
                return(null);
            }

            return(listRouteTablesResponse.Items[0]);
        }
Beispiel #20
0
        /**
         * Gets Subnet info of a single uniquely named Subnet in the specified compartment.
         *
         * @param vcnClient the service client to use to query the Subnet.
         * @param compartmentId of the Subnet.
         * @param vcnId of the Subnet.
         * @return the Subnet.
         */
        private static async Task <Subnet> GetUniqueSubnetByName(VirtualNetworkClient vcnClient, string compartmentId, string vcnId)
        {
            // Find the Subnet in a specific comparment
            var listSubnetsRequest = new ListSubnetsRequest
            {
                CompartmentId = compartmentId,
                VcnId         = vcnId,
                DisplayName   = SubnetName
            };
            var listSubnetsResponse = await vcnClient.ListSubnets(listSubnetsRequest);

            if (listSubnetsResponse.Items.Count != 1)
            {
                logger.Error($"Could not find unique subnet with name: {SubnetName} in compartment: {compartmentId}");
                return(null);
            }

            return(listSubnetsResponse.Items[0]);
        }
        private PSVirtualNetwork CreateVirtualNetwork()
        {
            var vnet = new PSVirtualNetwork
            {
                Name = Name,
                ResourceGroupName = ResourceGroupName,
                Location          = Location,
                AddressSpace      = new PSAddressSpace {
                    AddressPrefixes = AddressPrefix
                }
            };

            if (DnsServer != null)
            {
                vnet.DhcpOptions = new PSDhcpOptions {
                    DnsServers = DnsServer
                };
            }

            vnet.Subnets = Subnet;
            vnet.EnableDdosProtection = EnableDdosProtection;

            if (!string.IsNullOrEmpty(DdosProtectionPlanId))
            {
                vnet.DdosProtectionPlan = new PSResourceId {
                    Id = DdosProtectionPlanId
                };
            }

            // Map to the sdk object
            var vnetModel = NetworkResourceManagerProfile.Mapper.Map <MNM.VirtualNetwork>(vnet);

            vnetModel.Tags = TagsConversionHelper.CreateTagDictionary(Tag, validate: true);

            // Execute the Create VirtualNetwork call
            VirtualNetworkClient.CreateOrUpdate(ResourceGroupName, Name, vnetModel);

            var getVirtualNetwork = GetVirtualNetwork(ResourceGroupName, Name);

            return(getVirtualNetwork);
        }
Beispiel #22
0
        private static async Task <InternetGateway> CreateInternalGateway(VirtualNetworkClient vcnClient, string compartmentId, Vcn vcn)
        {
            CreateInternetGatewayDetails createInternetGatewayDetails = new CreateInternetGatewayDetails
            {
                CompartmentId = compartmentId,
                DisplayName   = IgName,
                IsEnabled     = true,
                VcnId         = vcn.Id
            };
            CreateInternetGatewayRequest createInternetGatewayRequest = new CreateInternetGatewayRequest {
                CreateInternetGatewayDetails = createInternetGatewayDetails
            };
            CreateInternetGatewayResponse createInternetGatewayResponse = await vcnClient.CreateInternetGateway(createInternetGatewayRequest);

            GetInternetGatewayRequest getInternetGatewayRequest = new GetInternetGatewayRequest {
                IgId = createInternetGatewayResponse.InternetGateway.Id
            };
            GetInternetGatewayResponse getInternetGatewayResponse = vcnClient.Waiters.ForInternetGateway(getInternetGatewayRequest, InternetGateway.LifecycleStateEnum.Available).Execute();
            InternetGateway            internetGateway            = getInternetGatewayResponse.InternetGateway;

            logger.Info($"Created internet gateway: {internetGateway.Id} and state is {internetGateway.LifecycleState}");
            return(internetGateway);
        }
        public static async Task MainContainerEngine(string[] args)
        {
            logger.Info("Starting example");

            string compartmentId = Environment.GetEnvironmentVariable("OCI_COMPARTMENT_ID");
            var    provider      = new ConfigFileAuthenticationDetailsProvider(OciConfigProfileName);

            var containerEngineClient = new ContainerEngineClient(provider);
            var vcnClient             = new VirtualNetworkClient(provider);
            var identityClient        = new IdentityClient(provider);

            Vcn           vcn     = null;
            List <Subnet> subnets = null;

            Cluster cluster = null;

            try
            {
                IdentityModels.AvailabilityDomain availablityDomain = await GetAvailabilityDomain(identityClient, compartmentId);

                logger.Info($"availability domain is {availablityDomain.Name}");

                vcn = await CreateVcn(vcnClient, compartmentId);

                subnets = await CreateSubnet(vcnClient, compartmentId, availablityDomain, vcn.Id);

                //Create a Container Engine Cluster
                List <string> subnetIds = new List <string>();
                foreach (Subnet subnet in subnets)
                {
                    subnetIds.Add(subnet.Id);
                }

                var kubernetesVersion = await GetKubernetesVersion(containerEngineClient);

                cluster = await CreateCluster(containerEngineClient, vcn.Id, subnetIds, kubernetesVersion, compartmentId);

                // Update the container engine cluster
                await UpdateCluster(containerEngineClient, cluster.Id, ClusterNewDisplayName);
            }
            catch (Exception e)
            {
                logger.Error($"Failed to create container engine cluster: {e}");
            }
            finally
            {
                logger.Info("Cleaning up...");

                if (cluster != null)
                {
                    await DeleteCluster(containerEngineClient, cluster.Id);
                }

                for (int i = 0; i < 2; i++)
                {
                    if (subnets[i] != null)
                    {
                        await DeleteSubnet(vcnClient, subnets[i]);
                    }
                }

                if (vcn != null)
                {
                    await DeleteVcn(vcnClient, vcn);
                }

                containerEngineClient.Dispose();
                vcnClient.Dispose();
                identityClient.Dispose();
            }
            logger.Info("End example");
        }
        public static async Task MainFileStorage()
        {
            logger.Info("Starting example");

            var provider              = new ConfigFileAuthenticationDetailsProvider("DEFAULT");
            var compartmentId         = Environment.GetEnvironmentVariable("OCI_COMPARTMENT_ID");
            var fileSystemDisplayName = Environment.GetEnvironmentVariable("FILE_SYSTEM_DISPLAY_NAME");

            var identityClient    = new IdentityClient(provider);
            var fileStorageClient = new FileStorageClient(provider);
            var vcnClient         = new VirtualNetworkClient(provider);

            Vcn         vcn         = null;
            Subnet      subnet      = null;
            FileSystem  fileSystem  = null;
            MountTarget mountTarget = null;
            Export      export      = null;
            Snapshot    snapshot    = null;

            try
            {
                var availablityDomain = await GetAvailabilityDomain(identityClient, compartmentId);

                logger.Info($"availability domain is {availablityDomain.Name}");

                // A VCN and subnet is required to create a mount target
                vcn = await CreateVcn(vcnClient, compartmentId);

                subnet = await CreateSubnet(vcnClient, compartmentId, availablityDomain, vcn);

                fileSystem = await CreateFileSystem(fileStorageClient, compartmentId,
                                                    fileSystemDisplayName, availablityDomain);

                mountTarget = await CreateMountTarget(fileStorageClient, vcnClient,
                                                      compartmentId, fileSystemDisplayName + "-mnt", availablityDomain, subnet);
                await GetExportSet(fileStorageClient, mountTarget.ExportSetId);

                export = await CreateExport(fileStorageClient, fileSystem.Id, mountTarget.ExportSetId);

                ListExports(fileStorageClient, compartmentId, fileSystem, mountTarget);

                snapshot = await CreateSnapshot(fileStorageClient, fileSystem);
            }
            catch (Exception e)
            {
                logger.Error($"Failed to mount file system: {e}");
            }
            finally
            {
                logger.Info("cleaning resources....");

                if (snapshot != null)
                {
                    await DeleteSnapshot(fileStorageClient, snapshot);
                }

                if (export != null)
                {
                    await DeleteExport(fileStorageClient, export);
                }

                if (mountTarget != null)
                {
                    await DeleteMountTarget(fileStorageClient, mountTarget);
                }

                if (fileSystem != null)
                {
                    await DeleteFileSystem(fileStorageClient, fileSystem);
                }

                if (subnet != null)
                {
                    await DeleteSubnet(vcnClient, subnet);
                }

                if (vcn != null)
                {
                    await DeleteVcn(vcnClient, vcn);
                }

                identityClient.Dispose();
                fileStorageClient.Dispose();
                vcnClient.Dispose();

                logger.Info("End example");
            }
        }
        /**
         * Creates a mount target and waits for it to become available. We recommend to retry these requests
         * so that if you receive a timeout or server error and you won't run into the risk of creating multiple resources.
         *
         * This creates a mount target WITHOUT specifying a hostname. This means that the mount target will only be accessible
         * via its private IP address.
         *
         * @param fsClient the service client to use to create the mount target
         * @param vcnClient a client used to communiate with the Virtual Networking service
         * @param compartmentId the OCID of the compartment where the file system will be created
         * @param displayName the display name of the mount target
         * @param availabilityDomain the availability domain where the file system will be created
         * @param subnet the subnet where the mount target will reside. If no private IP address is explicitly specified at
         * creation time then the mount target will be assigned a free private IP address from the subnet
         *
         * @return the created mount target
         */
        private static async Task <MountTarget> CreateMountTarget(FileStorageClient fsClient, VirtualNetworkClient vcnClient,
                                                                  string compartmentId, string displayName, AvailabilityDomain availabilityDomain, Subnet subnet)
        {
            logger.Info("Creating mount target......");

            CreateMountTargetDetails createDetails = new CreateMountTargetDetails
            {
                AvailabilityDomain = availabilityDomain.Name,
                SubnetId           = subnet.Id,
                CompartmentId      = compartmentId,
                DisplayName        = displayName
            };
            CreateMountTargetRequest createRequest = new CreateMountTargetRequest
            {
                CreateMountTargetDetails = createDetails
            };
            var retryConfiguration = new RetryConfiguration
            {
                MaxAttempts = 5
            };
            CreateMountTargetResponse createResponse = await fsClient.CreateMountTarget(createRequest, retryConfiguration);

            logger.Info($"Created Mount target: {createResponse.MountTarget.DisplayName}");

            logger.Info("Waiting for mount target to become available");
            GetMountTargetRequest getRequest = new GetMountTargetRequest
            {
                MountTargetId = createResponse.MountTarget.Id
            };
            GetMountTargetResponse getResponse = fsClient.Waiters.ForMountTarget(getRequest, MountTarget.LifecycleStateEnum.Active).Execute();

            logger.Info($"Mount target state: {getResponse.MountTarget.LifecycleState}");

            string mountTargetPrivateIpId           = getResponse.MountTarget.PrivateIpIds[0];
            GetPrivateIpRequest getPrivateIpRequest = new GetPrivateIpRequest
            {
                PrivateIpId = mountTargetPrivateIpId
            };
            GetPrivateIpResponse getPrivateIpResponse = await vcnClient.GetPrivateIp(getPrivateIpRequest);

            logger.Info($"Mount target private IP: {getPrivateIpResponse.PrivateIp.IpAddress}");

            return(getResponse.MountTarget);
        }
        static async Task MainDatabase(string[] args)
        {
            string compartmentId = Environment.GetEnvironmentVariable("OCI_COMPARTMENT_ID");
            string adminPassword = Environment.GetEnvironmentVariable("PASSWORD");

            logger.Info("Starting example");
            // Accepts profile name and creates a auth provider based on config file
            var provider = new ConfigFileAuthenticationDetailsProvider(OciConfigProfileName);

            var identityClient       = new IdentityClient(provider);
            var virtualNetworkClient = new VirtualNetworkClient(provider);
            var databaseClient       = new DatabaseClient(provider);
            var networkCidrBlock     = "10.0.1.0/24";

            Vcn    vcn        = null;
            Subnet subnet     = null;
            string dbSystemId = null;

            AvailabilityDomain availablityDomain = await getAvailabilityDomains(identityClient, compartmentId);

            logger.Info($"availability domain is {availablityDomain.Name}");

            try
            {
                vcn = await createVcn(virtualNetworkClient, compartmentId, networkCidrBlock);

                subnet = await createSubnet(virtualNetworkClient, compartmentId, availablityDomain, networkCidrBlock, vcn);

                logger.Info("Launching Database....");

                LaunchDbSystemDetails launchDbSystemDetails = new LaunchDbSystemDetails
                {
                    AvailabilityDomain = availablityDomain.Name,
                    CompartmentId      = compartmentId,
                    CpuCoreCount       = 4,
                    Shape         = "BM.DenseIO2.52",
                    SshPublicKeys = new List <string> {
                        "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAyyA8wePstPC69PeuHFtOwyTecByonsHFAjHbVnZ+h0dpomvLZxUtbknNj3+c7MPYKqKBOx9gUKV/diR/mIDqsb405MlrI1kmNR9zbFGYAAwIH/Gxt0Lv5ffwaqsz7cECHBbMojQGEz3IH3twEvDfF6cu5p00QfP0MSmEi/eB+W+h30NGdqLJCziLDlp409jAfXbQm/4Yx7apLvEmkaYSrb5f/pfvYv1FEV1tS8/J7DgdHUAWo6gyGUUSZJgsyHcuJT7v9Tf0xwiFWOWL9WsWXa9fCKqTeYnYJhHlqfinZRnT/+jkz0OZ7YmXo6j4Hyms3RCOqenIX1W6gnIn+eQIkw== This is the key's comment"
                    },
                    SubnetId        = subnet.Id,
                    DatabaseEdition = LaunchDbSystemDetails.DatabaseEditionEnum.EnterpriseEdition,
                    DisplayName     = "OCI DotNet SDK database",
                    Hostname        = "oci-dotnetsdk-host",
                    Domain          = "testdomain",
                    DbHome          = new CreateDbHomeDetails
                    {
                        DbVersion   = "12.1.0.2",
                        DisplayName = "Example DB Home",
                        Database    = new CreateDatabaseDetails
                        {
                            DbName        = "dotnetdb",
                            AdminPassword = adminPassword
                        }
                    }
                };

                LaunchDbSystemRequest launchDbSystemRequest = new LaunchDbSystemRequest
                {
                    LaunchDbSystemDetails = launchDbSystemDetails
                };
                LaunchDbSystemResponse launchDbSystemResponse = await databaseClient.LaunchDbSystem(launchDbSystemRequest);

                logger.Info($"Database ID: {launchDbSystemResponse.DbSystem.Id} and Database display name: {launchDbSystemResponse.DbSystem.DisplayName}");
                logger.Info("Waiting for Database to come to available state....");

                GetDbSystemRequest getDbSystemRequest = new GetDbSystemRequest
                {
                    DbSystemId = launchDbSystemResponse.DbSystem.Id
                };
                WaiterConfiguration waiterConfiguration = new WaiterConfiguration
                {
                    MaxAttempts           = 20,
                    GetNextDelayInSeconds = DelayStrategy.GetExponentialDelayInSeconds
                };
                GetDbSystemResponse getDbSystemResponse = databaseClient.Waiters.ForDbSystem(
                    getDbSystemRequest, waiterConfiguration, DbSystem.LifecycleStateEnum.Available).Execute();

                logger.Info("Database is available");
                logger.Info($"Database ID: {getDbSystemResponse.DbSystem.Id} and Database display name: {getDbSystemResponse.DbSystem.DisplayName}");
                dbSystemId = getDbSystemResponse.DbSystem.Id;
            }
            catch (Exception e)
            {
                logger.Error($"failed to launch DbSystem: {e}");
            }
            finally
            {
                if (dbSystemId != null)
                {
                    await terminateDbSystem(databaseClient, dbSystemId);
                }

                if (subnet != null)
                {
                    await deleteSubnet(virtualNetworkClient, subnet);
                }

                if (vcn != null)
                {
                    await deleteVcn(virtualNetworkClient, vcn);
                }

                identityClient.Dispose();
                virtualNetworkClient.Dispose();
                databaseClient.Dispose();

                logger.Info("End example");
            }
        }
        public static async Task MainContainerEngineNodePool()
        {
            logger.Info("Starting example");

            string compartmentId = Environment.GetEnvironmentVariable("OCI_COMPARTMENT_ID");
            var    provider      = new ConfigFileAuthenticationDetailsProvider(OciConfigProfileName);

            var containerEngineClient = new ContainerEngineClient(provider);
            var vcnClient             = new VirtualNetworkClient(provider);
            var identityClient        = new IdentityClient(provider);

            Vcn           vcn           = null;
            List <Subnet> subnets       = null;
            List <string> lbSubnetIds   = new List <string>();
            List <string> poolSubnetIds = new List <string>();
            Cluster       cluster       = null;
            NodePool      nodePool      = null;

            try
            {
                List <IdentityModels.AvailabilityDomain> availablityDomains = await GetAvailabilityDomains(identityClient, compartmentId);

                vcn = await CreateVcn(vcnClient, compartmentId);

                subnets = await CreateSubnets(vcnClient, compartmentId, vcn);

                lbSubnetIds.Add(subnets[0].Id);
                poolSubnetIds.Add(subnets[1].Id);

                var kubernetesVersion = await GetKubernetesVersion(containerEngineClient);

                cluster = await CreateCluster(containerEngineClient, vcn.Id, lbSubnetIds, kubernetesVersion, compartmentId);

                // Add node pool in the cluster
                KeyValue keyValue = new KeyValue
                {
                    Key   = "key1",
                    Value = "value1"
                };
                List <KeyValue> initialNodeLabels = new List <KeyValue> {
                    keyValue
                };

                List <NodePoolPlacementConfigDetails> nodePoolPlacementConfigDetails = new List <NodePoolPlacementConfigDetails>();
                foreach (var availabilityDomain in availablityDomains)
                {
                    nodePoolPlacementConfigDetails.Add(new NodePoolPlacementConfigDetails
                    {
                        AvailabilityDomain = availabilityDomain.Name,
                        SubnetId           = poolSubnetIds[0]
                    });
                }
                ;

                var createNodePoolNodeConfigDetails = new CreateNodePoolNodeConfigDetails
                {
                    Size             = availablityDomains.Count,
                    PlacementConfigs = nodePoolPlacementConfigDetails
                };
                nodePool = await CreateNodePool(containerEngineClient, compartmentId, cluster.Id, NodePoolDisplayName,
                                                kubernetesVersion, NodeImageName, NodeShape, initialNodeLabels, createNodePoolNodeConfigDetails);

                logger.Info("Created node pool");

                // Update the node pool
                await UpdateNodePool(containerEngineClient, nodePool.Id, NewNodePoolDisplayName);
            }
            catch (Exception e)
            {
                logger.Error($"Failed to create container engine cluster: {e}");
            }
            finally
            {
                logger.Info("Cleaning up...");

                if (nodePool != null)
                {
                    await DeleteNodePool(containerEngineClient, nodePool.Id);
                }
                if (cluster != null)
                {
                    await DeleteCluster(containerEngineClient, cluster.Id);
                }
                for (int i = 0; i < 2; i++)
                {
                    if (subnets[i] != null)
                    {
                        await DeleteSubnet(vcnClient, subnets[i]);
                    }
                }
                if (vcn != null)
                {
                    await DeleteVcn(vcnClient, vcn);
                }

                containerEngineClient.Dispose();
                vcnClient.Dispose();
                identityClient.Dispose();
            }
            logger.Info("End example");
        }
        public static async Task MainInstance()
        {
            logger.Info("Starting example");

            var provider      = new ConfigFileAuthenticationDetailsProvider("DEFAULT");
            var compartmentId = Environment.GetEnvironmentVariable("OCI_COMPARTMENT_ID");

            var identityClient       = new IdentityClient(provider);
            var computeClient        = new ComputeClient(provider, new ClientConfiguration());
            var virtualNetworkClient = new VirtualNetworkClient(provider);
            var blockStorageClient   = new BlockstorageClient(provider);
            var networkCidrBlock     = "10.0.1.0/24";

            LaunchInstanceDetails launchInstanceDetails = null;
            Instance          instance               = null;
            BootVolume        bootVolume             = null;
            Instance          instanceFromBootVolume = null;
            Vcn               vcn               = null;
            Subnet            subnet            = null;
            CreateVnicDetails createVnicDetails = null;
            InternetGateway   internetGateway   = null;

            AvailabilityDomain availablityDomain = await getAvailabilityDomains(identityClient, compartmentId);

            logger.Info($"availability domain is {availablityDomain.Name}");

            Shape shape = await getShape(computeClient, compartmentId, availablityDomain);

            if (shape == null)
            {
                logger.Error($"No Shapes available in the availability domain: {availablityDomain.Name}");
                return;
            }
            logger.Info($"shape is {shape.ShapeProp}");
            Image image = await getImage(computeClient, compartmentId, shape);

            try
            {
                vcn = await createVcn(virtualNetworkClient, compartmentId, networkCidrBlock);

                // The Internet Gateway with updated Route Rules will enable the instance to connect to the public
                // internet. If it is not desired, remove the following two lines below that create an internet
                // gateway and add that internet gateway to the VCN route table.
                internetGateway = await createInternalGateway(virtualNetworkClient, compartmentId, vcn);
                await addInternetGatewayToDefaultRouteTable(virtualNetworkClient, vcn, internetGateway);

                subnet = await createSubnet(virtualNetworkClient, compartmentId, availablityDomain, networkCidrBlock, vcn);

                createVnicDetails = new CreateVnicDetails {
                    SubnetId = subnet.Id
                };

                launchInstanceDetails = new LaunchInstanceDetails
                {
                    AvailabilityDomain = availablityDomain.Name,
                    CompartmentId      = compartmentId,
                    Shape             = shape.ShapeProp,
                    CreateVnicDetails = createVnicDetails,
                    ImageId           = image.Id
                };

                instance = await createInstance(computeClient, launchInstanceDetails);
                await printInstance(computeClient, virtualNetworkClient, instance);

                logger.Info("Instance is being created via boot volume ...");
                // This boot volume is created based on the boot volume of previous instance which needs to be running
                bootVolume = await createBootVolume(blockStorageClient, compartmentId, availablityDomain, image);

                launchInstanceDetails  = createLaunchInstanceDetailsFromBootVolume(launchInstanceDetails, bootVolume);
                instanceFromBootVolume = await createInstance(computeClient, launchInstanceDetails);
                await printInstance(computeClient, virtualNetworkClient, instanceFromBootVolume);
            }
            catch (Exception e)
            {
                logger.Error($"Failed to call LaunchInstance API: {e.Message}");
            }
            finally
            {
                logger.Info("cleaning up resources");
                if (instanceFromBootVolume != null)
                {
                    await terminateInstance(computeClient, instanceFromBootVolume);
                }

                if (instance != null)
                {
                    await terminateInstance(computeClient, instance);
                }

                if (internetGateway != null)
                {
                    await clearRouteRulesFromDefaultRouteTable(virtualNetworkClient, vcn);
                    await deleteInternetGateway(virtualNetworkClient, internetGateway);
                }

                if (subnet != null)
                {
                    await deleteSubnet(virtualNetworkClient, subnet);
                }

                if (vcn != null)
                {
                    await deleteVcn(virtualNetworkClient, vcn);
                }

                identityClient.Dispose();
                computeClient.Dispose();
                virtualNetworkClient.Dispose();
                blockStorageClient.Dispose();

                logger.Info("End example");
            }
        }
        public static void InstanceConsoleDisplay(ClientConfig config)
        {
            // create client
            ComputeClient computeClient = new ComputeClient(config)
            {
                Region = Regions.US_ASHBURN_1
            };

            BlockstorageClient blockstorageClient = new BlockstorageClient(config)
            {
                Region = Regions.US_ASHBURN_1
            };

            VirtualNetworkClient networkingClient = new VirtualNetworkClient(config)
            {
                Region = Regions.US_ASHBURN_1
            };

            // get instanse list(RUNNING only)
            Console.WriteLine("* List Instance------------------------");
            var listInstanceRequest = new ListInstancesRequest()
            {
                // target compartment is root compartment(tenancy)
                CompartmentId  = computeClient.Config.TenancyId,
                Limit          = 50,
                LifecycleState = ListInstancesRequest.LifecycleStates.RUNNING,
                SortOrder      = SortOrder.ASC,
                SortBy         = ListInstancesRequest.SortByParam.TIMECREATED
            };
            // get instance
            var listInstance = computeClient.ListInstances(listInstanceRequest);

            listInstance.Items.ForEach(instance => {
                GetInstanceRequest getInstanceRequest = new GetInstanceRequest()
                {
                    InstanceId = instance.Id
                };
                var insDetail = computeClient.GetInstance(getInstanceRequest).Instance;
                Console.WriteLine(" |-" + insDetail.DisplayName);
                Console.WriteLine(" | id: " + insDetail.Id);
                Console.WriteLine(" | AD: " + insDetail.AvailabilityDomain);
                Console.WriteLine(" | shape: " + insDetail.Shape);
                Console.WriteLine(" | state: " + insDetail.LifecycleState);
                Console.WriteLine(" |\t|- * SourceDetails");
                Console.WriteLine(" |\t|\t type: " + insDetail.SourceDetails.SourceType);
                if ("image".Equals(insDetail.SourceDetails.SourceType))
                {
                    Console.WriteLine(" |\t|\t id: " + insDetail.SourceDetails.ImageId);

                    // get sourceDetail machine image
                    GetImageRequest getImageRequest = new GetImageRequest()
                    {
                        ImageId = insDetail.SourceDetails.ImageId
                    };
                    var machineimage = computeClient.GetImage(getImageRequest);
                    Console.WriteLine(" |\t|\t name: " + machineimage.Image.DisplayName);
                    Console.WriteLine(" |\t|\t sizeInMBs: " + machineimage.Image.SizeInMBs);
                }
                else
                {
                    Console.WriteLine(" |\t|\t id: " + insDetail.SourceDetails.BootVolumeId);

                    // get sourceDetail bootVolume
                    GetBootVolumeRequest getBootVolumeRequest = new GetBootVolumeRequest()
                    {
                        BootVolumeId = insDetail.SourceDetails.BootVolumeId
                    };
                    var bootvol = blockstorageClient.GetBootVolume(getBootVolumeRequest);
                    Console.WriteLine(" |\t|\t name: " + bootvol.BootVolume.DisplayName);
                    Console.WriteLine(" |\t|\t sizeInGBs: " + bootvol.BootVolume.SizeInGBs.Value);
                }

                // get instance atattch bootvolumes
                var bootvolumeAtattch = new ListBootVolumeAttachmentsRequest()
                {
                    InstanceId         = instance.Id,
                    CompartmentId      = instance.CompartmentId,
                    AvailabilityDomain = instance.AvailabilityDomain,
                    Limit = 50
                };
                var listBvAtattch = computeClient.ListBootVolumeAttachments(bootvolumeAtattch);
                listBvAtattch.Items.ForEach(bootVolAtt => {
                    Console.WriteLine(" |\t|- * BootVolume");

                    // get bootvolume
                    var getBootVolumeRequest = new GetBootVolumeRequest()
                    {
                        BootVolumeId = bootVolAtt.BootVolumeId
                    };
                    var bv = blockstorageClient.GetBootVolume(getBootVolumeRequest);
                    Console.WriteLine(" |\t|\t name:" + bv.BootVolume.DisplayName);
                    Console.WriteLine(" |\t|\t id:" + bv.BootVolume.Id);
                    Console.WriteLine(" |\t|\t state:" + bv.BootVolume.LifecycleState);
                    Console.WriteLine(" |\t|\t sizeInGBs:" + bv.BootVolume.SizeInGBs.Value);
                });

                // get instance atattch vnics
                var vnicAtattch = new ListVnicAttachmentsRequest()
                {
                    InstanceId         = instance.Id,
                    CompartmentId      = instance.CompartmentId,
                    AvailabilityDomain = instance.AvailabilityDomain,
                    Limit = 50
                };
                var listVnicAtattch = computeClient.ListVnicAttachments(vnicAtattch);
                listVnicAtattch.Items.ForEach(vnicA => {
                    Console.WriteLine(" |\t|- * Vnic");
                    GetVnicRequest getVnicRequest = new GetVnicRequest()
                    {
                        VnicId = vnicA.VnicId
                    };
                    var vnic = networkingClient.GetVnic(getVnicRequest);
                    Console.WriteLine(" |\t|\t name:" + vnic.Vnic.DisplayName);
                    Console.WriteLine(" |\t|\t id:" + vnic.Vnic.Id);
                    Console.WriteLine(" |\t|\t state:" + vnic.Vnic.LifecycleState);
                    Console.WriteLine(" |\t|\t privateIp:" + vnic.Vnic.PrivateIp);
                    Console.WriteLine(" |\t|\t publicIp:" + vnic.Vnic.PublicIp);
                });

                // get instance atattch volumes
                var volumeAtattch = new ListVolumeAttachmentsRequest()
                {
                    InstanceId         = instance.Id,
                    CompartmentId      = instance.CompartmentId,
                    AvailabilityDomain = instance.AvailabilityDomain,
                    Limit = 50
                };
                var listVolAtattch = computeClient.ListVolumeAttachments(volumeAtattch);
                listVolAtattch.Items.ForEach(volAtt => {
                    Console.WriteLine(" |\t|- * Volume");

                    // get bootvolume
                    var getVolumeRequest = new GetVolumeRequest()
                    {
                        VolumeId = volAtt.VolumeId
                    };
                    var vol = blockstorageClient.GetVolume(getVolumeRequest);
                    Console.WriteLine(" |\t|\t name:" + vol.Volume.DisplayName);
                    Console.WriteLine(" |\t|\t id:" + vol.Volume.Id);
                    Console.WriteLine(" |\t|\t state:" + vol.Volume.LifecycleState);
                    Console.WriteLine(" |\t|\t sizeInGBs:" + vol.Volume.SizeInGBs.Value);
                });
            });

            // get list Machine Images
            Console.WriteLine();
            Console.WriteLine("* List Image------------------------ max 10");
            var listImagesRequest = new ListImagesRequest()
            {
                // target compartment is root compartment(tenancy)
                CompartmentId  = config.TenancyId,
                Limit          = 10,
                LifecycleState = ListImagesRequest.LifecycleStates.AVAILABLE,
                SortOrder      = SortOrder.ASC,
                SortBy         = ListImagesRequest.SortByParam.TIMECREATED
            };
            // get instance
            var listImage = computeClient.ListImages(listImagesRequest);

            listImage.Items.ForEach(image =>
            {
                Console.WriteLine(" |-" + image.DisplayName);
                Console.WriteLine(" | id: " + image.Id);
                Console.WriteLine(" | os: " + image.OperatingSystem);
                Console.WriteLine(" | os ver: " + image.OperatingSystemVersion);
                Console.WriteLine(" | lifecycle: " + image.LifecycleState);
                Console.WriteLine(" | sizeInMBs: " + image.SizeInMBs);
                Console.WriteLine(" | BaseMachineId: " + image.BaseImageId);
            });
        }
Beispiel #30
0
        private static void VirtualNetworkConsoleDisplay(ClientConfig config)
        {
            // create client
            VirtualNetworkClient client = new VirtualNetworkClient(config)
            {
                Region = Regions.US_ASHBURN_1
            };

            Console.WriteLine("* List VCN------------------------");
            var listVcnRequest = new ListVcnRequest()
            {
                // target compartment is root compartment(tenancy)
                CompartmentId = config.TenancyId,
                Limit         = 50,
                SortOrder     = SortOrder.ASC
            };
            // get vcns
            var listVcn = client.ListVcn(listVcnRequest);

            listVcn.Items.ForEach(vcn =>
            {
                Console.WriteLine(" |-" + vcn.DisplayName);
                Console.WriteLine(" | " + vcn.Id);

                // get dhcps in vcn
                var listDhcpRequest = new ListDhcpOptionsRequest()
                {
                    // target is same compartment and VCN
                    CompartmentId = vcn.CompartmentId,
                    VcnId         = vcn.Id,
                    Limit         = 50,
                    SortOrder     = SortOrder.ASC
                };
                var listDhcp = client.ListDhcpOptions(listDhcpRequest);
                listDhcp.Items.ForEach(dhcp =>
                {
                    Console.WriteLine(" |\t|- * DHCP");
                    Console.WriteLine(" |\t|\t" + dhcp.DisplayName);
                    Console.WriteLine(" |\t|\t" + dhcp.Id);
                });

                // get RouteTable in vcn
                var listRouteTableRequest = new ListRouteTableRequest()
                {
                    // target is same compartment and VCN
                    CompartmentId = vcn.CompartmentId,
                    VcnId         = vcn.Id,
                    Limit         = 50,
                    SortOrder     = SortOrder.ASC
                };
                var listRouteTable = client.ListRouteTableOptions(listRouteTableRequest);
                listRouteTable.Items.ForEach(rt =>
                {
                    Console.WriteLine(" |\t|- * RouteTable");
                    Console.WriteLine(" |\t|\t" + rt.DisplayName);
                    Console.WriteLine(" |\t|\t" + rt.Id);

                    // RouteRules
                    rt.RouteRules.ForEach(rr =>
                    {
                        if (!string.IsNullOrEmpty(rr.DestinationType))
                        {
                            Console.WriteLine(" |\t|\t|- DestinationType:" + rr.DestinationType);
                        }
                        if (!string.IsNullOrEmpty(rr.CidrBlock))
                        {
                            Console.WriteLine(" |\t|\t|\tCidrBlock:" + rr.CidrBlock);
                        }
                        if (!string.IsNullOrEmpty(rr.Destination))
                        {
                            Console.WriteLine(" |\t|\t|\tDestination:" + rr.Destination);
                        }
                        if (!string.IsNullOrEmpty(rr.NetworkEntityId))
                        {
                            Console.WriteLine(" |\t|\t|\tNetworkEntityId:" + rr.NetworkEntityId);
                        }
                    });
                });

                // get RouteTable in vcn
                var listSecurityListRequest = new ListSecurityListsRequest()
                {
                    // target is same compartment and VCN
                    CompartmentId = vcn.CompartmentId,
                    VcnId         = vcn.Id,
                    Limit         = 50,
                    SortOrder     = SortOrder.ASC
                };
                var listSecurityList = client.ListSecurityLists(listSecurityListRequest);
                listSecurityList.Items.ForEach(sl =>
                {
                    Console.WriteLine(" |\t|- * SecurityList");
                    Console.WriteLine(" |\t|\t" + sl.DisplayName);
                    Console.WriteLine(" |\t|\t" + sl.Id);
                    Console.WriteLine(" |\t|\t" + sl.LifecycleState);
                });

                // get Subnet in vcn
                var listSubnetRequest = new ListSubnetsRequest()
                {
                    // target is same compartment and VCN
                    CompartmentId = vcn.CompartmentId,
                    VcnId         = vcn.Id,
                    Limit         = 50,
                    SortOrder     = SortOrder.ASC
                };
                var listSubnet = client.ListSubnets(listSubnetRequest);
                listSubnet.Items.ForEach(sl =>
                {
                    Console.WriteLine(" |\t|- * Subnet");
                    Console.WriteLine(" |\t|\t" + sl.DisplayName);
                    Console.WriteLine(" |\t|\t" + sl.Id);
                    Console.WriteLine(" |\t|\t" + sl.LifecycleState);
                });

                // get InternetGateway in vcn
                var listIGRequest = new ListInternetGatewaysRequest()
                {
                    // target is same compartment and VCN
                    CompartmentId = vcn.CompartmentId,
                    VcnId         = vcn.Id,
                    Limit         = 50,
                    SortOrder     = SortOrder.ASC
                };
                var listIG = client.ListInternetGateways(listIGRequest);
                listDhcp.Items.ForEach(ig =>
                {
                    Console.WriteLine(" |\t|- * InternetGateway");
                    Console.WriteLine(" |\t|\t" + ig.DisplayName);
                    Console.WriteLine(" |\t|\t" + ig.Id);
                });
            });

            Console.WriteLine("* List DRG------------------------");

            var identityClient = new IdentityClient(config)
            {
                Region = Regions.US_ASHBURN_1
            };

            var listCompartmentRequest = new ListCompartmentRequest()
            {
                CompartmentId          = config.TenancyId,
                CompartmentIdInSubtree = true,
                AccessLevel            = ListCompartmentRequest.AccessLevels.ACCESSIBLE
            };
            var compartments = identityClient.ListCompartment(listCompartmentRequest).Items;

            foreach (var com in compartments)
            {
                var listDrgsRequest = new ListDrgsRequest()
                {
                    CompartmentId = com.Id
                };
                var drgs = client.ListDrgs(listDrgsRequest).Items;
                foreach (var drg in drgs)
                {
                    Console.WriteLine($" |-name: {drg.DisplayName}");
                    Console.WriteLine($" | state: {drg.LifecycleState}");
                    Console.WriteLine($" | timeCreate: {drg.TimeCreated}");
                    Console.WriteLine($" | compartment: {com.Name}");
                }
            }
        }