public static void Main(string[] args)
        {
            ComputeService computeService = new ComputeService(new BaseClientService.Initializer
            {
                HttpClientInitializer = GetCredential(),
                ApplicationName       = "Google-ComputeSample/0.1",
            });

            // Project ID for this request.
            string project = "my-project";      // TODO: Update placeholder value.

            // The name of the zone for this request.
            string zone = "my-zone";      // TODO: Update placeholder value.

            // TODO: Assign values to desired properties of `requestBody`:
            Data.Instance requestBody = new Data.Instance();

            InstancesResource.InsertRequest request = computeService.Instances.Insert(requestBody, project, zone);

            // To execute asynchronously in an async method, replace `request.Execute()` as shown:
            Data.Operation response = request.Execute();
            // Data.Operation response = await request.ExecuteAsync();

            // TODO: Change code below to process the `response` object:
            Console.WriteLine(JsonConvert.SerializeObject(response));
        }
        private async Task <string> GetInstance()
        {
            try
            {
                ServiceAccountCredential credential = new ServiceAccountCredential(
                    new ServiceAccountCredential.Initializer(ServiceAccountEmail)
                {
                    Scopes = new[] { ComputeService.Scope.Compute, ComputeService.Scope.CloudPlatform }
                }.FromPrivateKey(PrivateKey));

                var cs = new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName       = "GCloud Get Instance"
                };

                var t = new ComputeService(cs);

                var zoneRegion = Region + "-" + Zone;

                InstancesResource.GetRequest request = t.Instances.Get(Project, zoneRegion, InstanceName);

                Google.Apis.Compute.v1.Data.Instance response = await request.ExecuteAsync();

                return(JsonConvert.SerializeObject(response));
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Пример #3
0
        public async Task CreateInstanceAsync()
        {
            var computeService = new ComputeService(new BaseClientService.Initializer
            {
                HttpClientInitializer = await GetCredentialAsync(),
                ApplicationName       = _configuration["vm_conf:computeservice_name"],
            });

            var project = Environment.GetEnvironmentVariable("GOOGLE_PROJECT");

            var zone = Environment.GetEnvironmentVariable("GOOGLE_PROJECT_ZONE");

            var requestBody = new DataCloud.Instance
            {
                Name              = _configuration["vm_conf:instance_name"],
                MachineType       = string.Format(_configuration["vm_conf:machine_type"], project, zone),
                NetworkInterfaces = new List <DataCloud.NetworkInterface>
                {
                    new DataCloud.NetworkInterface
                    {
                        Network       = string.Format(_configuration["vm_conf:network"], project),
                        AccessConfigs = new List <DataCloud.AccessConfig>
                        {
                            new DataCloud.AccessConfig
                            {
                                Name = _configuration["vm_conf:access_name"],
                                Type = _configuration["vm_conf:access_type"]
                            }
                        }
                    }
                },
                Disks = new List <DataCloud.AttachedDisk>
                {
                    new DataCloud.AttachedDisk
                    {
                        DeviceName       = _configuration["vm_conf:disk_name"],
                        Type             = _configuration["vm_conf:disk_type"],
                        Boot             = true,
                        AutoDelete       = true,
                        InitializeParams = new DataCloud.AttachedDiskInitializeParams
                        {
                            SourceImage = _configuration["vm_conf:disk_image"]
                        }
                    }
                }
            };

            var request = computeService.Instances.Insert(requestBody, project, zone);

            var response = await request.ExecuteAsync();

            Console.WriteLine(JsonConvert.SerializeObject(response));
        }
Пример #4
0
        /// <summary>
        /// 내부 테스트용 함수, 제일 간단한 옵션으로 인스턴스 하나 생성함.
        /// </summary>
        /// <param name="InstanceName">생성할 인스턴스 이름</param>
        /// <param name="zone">region string</param>
        /// <param name="MachineType">Machine Type string</param>
        /// <param name="Image">Client OS</param>
        /// <param name="ImageProject"></param>
        /// <param name="SizeGb">Size of Disk</param>
        /// <returns>Cient Operation ID</returns>
        /// MachineType의 n1-standard-N 의 N이 cpu 갯수
        internal string TestCreateInstance(string InstanceName = "kimjjang-31", string zone = "asia-east1-a", string MachineType = "zones/asia-east1-a/machineTypes/n1-standard-1", string Image = "debian-9", string ImageProject = "debian-cloud", long?SizeGb = 10)
        {
            Data.Instance BodyContent         = new Data.Instance();
            var           networkaccessconfig = new Data.AccessConfig();//외부주소/NAT설정

            networkaccessconfig.Name = "Default Network Setting";
            networkaccessconfig.Type = "ONE_TO_ONE_NAT";
            var networkconfiglist = new List <Data.AccessConfig>();

            networkconfiglist.Add(networkaccessconfig);
            var networkinterface = new Data.NetworkInterface();//내부 주소 설정

            networkinterface.AccessConfigs = networkconfiglist;
            var networkinterfacelist = new List <Data.NetworkInterface>();

            networkinterfacelist.Add(networkinterface);

            var disk = new Data.AttachedDisk();
            //disk.Source = new Data.AttachedDiskInitializeParams().SourceImage = $"https://www.googleapis.com/compute/v1/projects/{ProjectID}/zones/{zone}/disks/{InstanceName}";
            var diskinit = new Data.AttachedDiskInitializeParams();

            var Tags     = new Data.Tags();
            var settings = new List <string>();//생성시에 사용되는 옵션들은 대부분 태그에서 생성 / 조절

            settings.Add("http-server");
            settings.Add("https-server");
            Tags.Items = settings;

            diskinit.DiskName     = "imsi";
            diskinit.DiskSizeGb   = SizeGb;
            diskinit.DiskType     = $"https://www.googleapis.com/compute/v1/projects/{ProjectID}/zones/{zone}/diskTypes/pd-standard";
            diskinit.SourceImage  = "projects/debian-cloud/global/images/family/debian-9";
            disk.InitializeParams = diskinit;
            disk.Boot             = true;
            disk.AutoDelete       = true;//인스턴스 삭제할 때 디스크도 같이 삭제
            var disklist = new List <Data.AttachedDisk>();

            disklist.Add(disk);
            BodyContent.Name = InstanceName;
            BodyContent.NetworkInterfaces = networkinterfacelist; //1대1 NAT -> 내/외부 설정은 AccessConfig에서 따로 설정
            BodyContent.MachineType       = MachineType;          //"zones/asia-east1-a/machineTypes/n1-standard-1"
            BodyContent.MinCpuPlatform    = "Intel Ivy Bridge";
            BodyContent.Disks             = disklist;
            BodyContent.Tags = Tags;

            var req = MonoComputeServicenInstance.Instances.Insert(BodyContent, this.ProjectID, zone);

            try
            {
                var ret = req.Execute();
                if (ret.Error != null)
                {
                    MessageBox.Show("Error : " + ret.Error.ToString());
                }
                if (ret.Warnings != null)
                {
                    MessageBox.Show("Warning : " + ret.Warnings.ToString());
                }
                return(ret.ClientOperationId);
            }
            catch (Exception e)
            {
                if (e.ToString().Contains("403"))
                {
                    MessageBox.Show("구글 컴퓨트에 접근할 권한이 있는지 확인하십시오. 결제 방법이나 약관에 동의했는지 확인해주십시오");
                }
                else
                {
                    MessageBox.Show("알 수 없는 에러가 발생했습니다.");
                    MessageBox.Show(e.ToString());
                }
                return(null);
            }
            //디스크를 생성하면 디스크 인스턴스는 따로 만들어지고 따로 삭제 안해주면 중복된 이름 예외 발생함.
            //string url = $"https://www.googleapis.com/compute/v1/projects/[PROJECT_ID]/zones/[ZONE]/instances";
            //string body = "{\"name\":\"[INSTANCE_NAME]\",\"machineType\":\"machineTypes/[MACHINE_TYPE]\",\"networkInterfaces\":[{\"accessConfigs\":[{\"type\":\"ONE_TO_ONE_NAT\",\"name\":\"ExternalNAT\"}],\"network\":\"global/networks/default\"}],\"disks\":[{\"autoDelete\":\"true\",\"boot\":\"true\",\"type\":\"PERSISTENT\",\"initializeParams\":{\"sourceImage\":\"projects/[IMAGE_PROJECT]/global/images/family/[IMAGE]\"}},{\"initializeParams\":{\"diskSizeGb\":\"[SIZE_GB]\",\"sourceImage\":\"[IMAGE]\"},{\"initializeParams\":{\"diskSizeGb\":\"[SIZE_GB]\"}}]";
        }